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
19,949,923
Simpler way to check if variable is not equal to multiple string values?
<p>Current Codes:</p> <pre><code>&lt;?php // See the AND operator; How do I simplify/shorten this line? if( $some_variable !== 'uk' &amp;&amp; $some_variable !== 'in' ) { // Do something } ?&gt; </code></pre> <p>And:</p> <pre><code>&lt;?php // See the OR operator; How do I simplify/shorten this line? if( $some_variable !== 'uk' || $some_variable !== 'in' ) { // Do something else } ?&gt; </code></pre> <p>Is there a simpler (i.e. shorter) way to write the two conditions?</p> <p><strong>NOTE:</strong> Yes, they are different, and I am expecting different ways to shorten the codes.</p>
19,950,682
8
8
null
2013-11-13 09:23:10.89 UTC
13
2021-11-26 18:09:59.75 UTC
2013-11-13 09:37:08.823 UTC
null
1,071,413
null
1,071,413
null
1
60
php|if-statement|conditional-statements
135,566
<p>For your first code, you can use a short alteration of <a href="https://stackoverflow.com/a/19949968/532495">the answer given by @ShankarDamodaran</a> using <a href="http://de1.php.net/in_array" rel="noreferrer"><code>in_array()</code></a>:</p> <pre><code>if ( !in_array($some_variable, array('uk','in'), true ) ) { </code></pre> <p>or even shorter with <code>[]</code> notation available since php 5.4 as pointed out by @Forty in the comments</p> <pre><code>if ( !in_array($some_variable, ['uk','in'], true ) ) { </code></pre> <p>is the same as:</p> <pre><code>if ( $some_variable !== 'uk' &amp;&amp; $some_variable !== 'in' ) { </code></pre> <p>... but shorter. Especially if you compare more than just 'uk' and 'in'. I do not use an additional variable (<em>Shankar used $os</em>) but instead define the array in the if statement. Some might find that dirty, i find it quick and neat :D</p> <p>The problem with your second code is that it can easily be exchanged with just TRUE since:</p> <pre><code>if (true) { </code></pre> <p>equals</p> <pre><code>if ( $some_variable !== 'uk' || $some_variable !== 'in' ) { </code></pre> <p>You are asking if the value of a string is not A or Not B. If it is A, it is definitely not also B and if it is B it is definitely not A. And if it is C or literally anything else, it is also not A and not B. So that statement always (<em>not taking into account schrödingers law here</em>) returns true.</p>
3,735,900
What is the difference between escapeXml and escapeHtml?
<p>I would like to escape characters in JSP pages. Which is more suitable, <code>escapeXml</code> or <code>escapeHtml</code>?</p>
3,735,946
4
0
null
2010-09-17 13:52:40.087 UTC
3
2016-04-26 08:29:54.94 UTC
2010-09-17 14:09:09.67 UTC
null
157,882
null
273,533
null
1
18
html|xml|jsp|escaping
41,041
<p>They're designed for different purposes, HTML has lots of entities that XML doesn't. XML only has 5 escapes:</p> <pre><code>&amp;lt; represents "&lt;" &amp;gt; represents "&gt;" &amp;amp; represents "&amp;" &amp;apos; represents ' &amp;quot; represents " </code></pre> <p>While HTML has loads - think of <code>&amp;nbsp;</code> <code>&amp;copy;</code> etc. These HTML codes aren't valid in XML unless you include a definition in the header. The numeric codes (like <code>&amp;#169;</code> for the copyright symbol) are valid in both.</p>
3,798,874
Retrieving/Listing all key/value pairs in a Redis db
<p>I'm using an ORM called Ohm in Ruby that works on top of Redis and am curious to find out how the data is actually stored. I was wondering if there is way to list all the keys/values in a Redis db.</p> <p>Any lead will go a long way in helping me out (I'm basically stuck atm). Thanks in advance!</p> <p><strong>Update:</strong><br> A note for others trying this out using redis-cli, use this:</p> <pre><code>$ redis-cli keys * (press * followed by Ctrl-D) ... (prints a list of keys and exits) $ </code></pre> <p>Thanks @antirez and @hellvinz!</p>
3,798,911
4
0
null
2010-09-26 17:07:12.117 UTC
19
2021-09-21 23:08:34.003 UTC
2019-07-25 17:36:46.67 UTC
null
3,036,782
null
129,912
null
1
72
ruby|rubygems|nosql|redis|ohm
81,847
<p>You can explore the Redis dataset using the <code>redis-cli</code> tool included in the Redis distribution.</p> <p>Just start the tool without arguments, then type commands to explore the dataset.</p> <p>For instance <code>KEYS</code> will list all the keys matching a glob-style pattern, for instance with: <code>keys *</code> you'll see all the keys available.</p> <p>Then you can use the <code>TYPE</code> command to check what type is a given key, if it's a list you can retrieve the elements inside using <code>LRANGE mykey 0 -1</code>. If it is a Set you'll use instead <code>SMEMBERS mykey</code> and so forth. Check the Redis documentation for a list of all the available commands and how they work.</p>
3,401,850
After array_filter(), how can I reset the keys to go in numerical order starting at 0
<p>I just used array_filter to remove entries that had only the value '' from an array, and now I want to apply certain transformations on it depending on the placeholder starting from 0, but unfortunately it still retains the original index. I looked for a while and couldn't see anything, perhaps I just missed the obvious, but my question is...</p> <p>How can I easily reset the indexes of the array to begin at 0 and go in order in the NEW array, rather than have it retain old indexes?</p>
3,401,863
4
2
null
2010-08-04 00:56:50.76 UTC
21
2020-06-21 16:51:18.46 UTC
2017-05-03 10:33:00.45 UTC
null
2,943,403
null
410,276
null
1
144
php|arrays|filter|reindex
72,760
<p>If you call <a href="https://www.php.net/manual/en/function.array-values.php" rel="noreferrer"><code>array_values</code></a> on your array, it will be reindexed from zero.</p>
3,780,737
Add a custom button to a Django application's admin page
<p>I have an application in Django with a routine which would be available only to the admin. What I want to do is add a button to perform the routine in this application's section of the admin app.</p> <p>Am I supposed to make a template for it, and if that's the case, how do I add a html template for an app in the admin. Or maybe there's a command to simply add a button?</p>
3,788,051
5
2
null
2010-09-23 16:58:07.953 UTC
1
2018-01-31 15:31:11.177 UTC
2018-01-10 18:28:28.887 UTC
null
1,192,111
null
409,701
null
1
21
python|django|django-admin
45,717
<p>Messing with the admin forms can be complicated but i've commonly found that adding links, buttons, or extra info is easy and helpful. (Like a list of links to related objects witout making an inline, esp for things that are more viewed than edited).</p> <p>From <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-vs-replacing-an-admin-template" rel="noreferrer">Django docs</a></p> <blockquote> <p>Because of the modular design of the admin templates, it is usually neither necessary nor advisable to replace an entire template. It is almost always better to override only the section of the template which you need to change.</p> </blockquote> <p>This will add a list over the top of the form.</p> <p>Place in <code>templates/admin/[your_app]/[template_to_override]</code>:</p> <pre><code>{% extends "admin/change_form.html" %} {% block form_top %} {% for item in original.items %} {{ item }} {% endfor %} {% endblock %} </code></pre>
3,415,582
How can I use optional parameters in a T-SQL stored procedure?
<p>I am creating a stored procedure to do a search through a table. I have many different search fields, all of which are optional. Is there a way to create a stored procedure that will handle this? Let's say I have a table with four fields: ID, FirstName, LastName and Title. I could do something like this:</p> <pre><code>CREATE PROCEDURE spDoSearch @FirstName varchar(25) = null, @LastName varchar(25) = null, @Title varchar(25) = null AS BEGIN SELECT ID, FirstName, LastName, Title FROM tblUsers WHERE FirstName = ISNULL(@FirstName, FirstName) AND LastName = ISNULL(@LastName, LastName) AND Title = ISNULL(@Title, Title) END </code></pre> <p>This sort of works. However it ignores records where FirstName, LastName or Title are NULL. If Title is not specified in the search parameters I want to include records where Title is NULL - same for FirstName and LastName. I know I could probably do this with dynamic SQL but I would like to avoid that.</p>
3,415,629
6
3
null
2010-08-05 14:17:50.77 UTC
70
2022-07-22 17:37:18.84 UTC
2022-07-22 17:37:18.84 UTC
null
4,808,079
null
100,077
null
1
195
tsql|select|filter|optional-parameters
361,049
<p>Dynamically changing searches based on the given parameters is a complicated subject and doing it one way over another, even with only a very slight difference, can have massive performance implications. The key is to use an index, ignore compact code, ignore worrying about repeating code, you must make a good query execution plan (use an index).</p> <p>Read this and consider all the methods. Your best method will depend on your parameters, your data, your schema, and your actual usage:</p> <p><a href="http://www.sommarskog.se/dyn-search.html" rel="noreferrer">Dynamic Search Conditions in T-SQL by by Erland Sommarskog</a></p> <p><a href="http://www.sommarskog.se/dynamic_sql.html" rel="noreferrer">The Curse and Blessings of Dynamic SQL by Erland Sommarskog</a></p> <p>If you have the proper SQL Server 2008 version (SQL 2008 SP1 CU5 (10.0.2746) and later), you can use this little trick to actually use an index:</p> <p>Add <code>OPTION (RECOMPILE)</code> onto your query, <a href="http://www.sommarskog.se/dyn-search-2008.html#static" rel="noreferrer">see Erland's article</a>, and SQL Server will resolve the <code>OR</code> from within <code>(@LastName IS NULL OR LastName= @LastName)</code> before the query plan is created based on the runtime values of the local variables, and an index can be used.</p> <p>This will work for any SQL Server version (return proper results), but only include the OPTION(RECOMPILE) if you are on SQL 2008 SP1 CU5 (10.0.2746) and later. The OPTION(RECOMPILE) will recompile your query, only the verison listed will recompile it based on the current run time values of the local variables, which will give you the best performance. If not on that version of SQL Server 2008, just leave that line off.</p> <pre><code>CREATE PROCEDURE spDoSearch @FirstName varchar(25) = null, @LastName varchar(25) = null, @Title varchar(25) = null AS BEGIN SELECT ID, FirstName, LastName, Title FROM tblUsers WHERE (@FirstName IS NULL OR (FirstName = @FirstName)) AND (@LastName IS NULL OR (LastName = @LastName )) AND (@Title IS NULL OR (Title = @Title )) OPTION (RECOMPILE) ---&lt;&lt;&lt;&lt;use if on for SQL 2008 SP1 CU5 (10.0.2746) and later END </code></pre>
3,879,011
Entity Framework/SQL2008 - How to Automatically Update LastModified fields for Entities?
<p>If i have the following entity:</p> <pre><code>public class PocoWithDates { public string PocoName { get; set; } public DateTime CreatedOn { get; set; } public DateTime LastModified { get; set; } } </code></pre> <p>Which corresponds to a SQL Server 2008 table with the same name/attributes...</p> <p>How can i <strong>automatically</strong>:</p> <ol> <li>Set the CreatedOn/LastModified field for the record to <strong>now</strong> (when doing INSERT)</li> <li>Set the LastModified field for the record to <strong>now</strong> (when doing UPDATE)</li> </ol> <p>When i say <strong>automatically</strong>, i mean i want to be able to do this:</p> <pre><code>poco.Name = "Changing the name"; repository.Save(); </code></pre> <p>Not this:</p> <pre><code>poco.Name = "Changing the name"; poco.LastModified = DateTime.Now; repository.Save(); </code></pre> <p>Behind the scenes, "something" should automatically update the datetime fields. What is that "something"?</p> <p>I'm using Entity Framework 4.0 - is there a way that EF can do that automatically for me? (a special setting in the EDMX maybe?)</p> <p>From the SQL Server side, i can use <strong>DefaultValue</strong>, but that will only work for <strong>INSERT's</strong> (not UPDATE's).</p> <p>Similarly, i can set a default value using a constructor on the POCO's, but again this will only work when instantiating the object.</p> <p>And of course i <strong>could</strong> use Triggers, but it's not ideal.</p> <p>Because i'm using Entity Framework, i can hook into the <strong>SavingChanges</strong> event and update the date fields here, but the problem is i need to become "aware" of the POCO's (at the moment, my repository is implemented with generics). I would need to do some sort of OO trickery (like make my POCO's implement an interface, and call a method on that). I'm not adversed to that, but if i have to do that, i would rather manually set the fields.</p> <p>I'm basically looking for a SQL Server 2008 or Entity Framework 4.0 solution. (or a smart .NET way)</p> <p>Any ideas?</p> <p><strong>EDIT</strong></p> <p>Thanks to @marc_s for his answer, but i went with a solution which is better for my scenario.</p>
3,911,021
7
1
null
2010-10-07 05:44:52.163 UTC
20
2017-05-26 13:29:26.947 UTC
2010-10-12 01:04:06.127 UTC
null
321,946
null
321,946
null
1
41
c#|.net|sql-server-2008|entity-framework-4|datetime-generation
22,358
<p>As i have a service layer mediating between my controllers (im using ASP.NET MVC), and my repository, i have decided to auto-set the fields here.</p> <p>Also, my POCO's have no relationships/abstractions, they are completely independant. I would like to keep it this way, and not mark any virtual properties, or create base classes.</p> <p>So i created an interface, IAutoGenerateDateFields:</p> <pre><code>public interface IAutoGenerateDateFields { DateTime LastModified { get;set; } DateTime CreatedOn { get;set; } } </code></pre> <p>For any POCO's i wish to auto-generate these fields, i implement this inteface.</p> <p>Using the example in my question:</p> <pre><code>public class PocoWithDates : IAutoGenerateDateFields { public string PocoName { get; set; } public DateTime CreatedOn { get; set; } public DateTime LastModified { get; set; } } </code></pre> <p>In my service layer, i now check if the concrete object implements the interface:</p> <pre><code>public void Add(SomePoco poco) { var autoDateFieldsPoco = poco as IAutoGenerateDateFields; // returns null if it's not. if (autoDateFieldsPoco != null) // if it implements interface { autoDateFieldsPoco.LastModified = DateTime.Now; autoDateFieldsPoco.CreatedOn = DateTime.Now; } // ..go on about other persistence work. } </code></pre> <p>I will probably break that code in the Add out to a helper/extension method later on.</p> <p>But i think this is a decent solution for my scenario, as i dont want to use virtuals on the Save (as i'm using Unit of Work, Repository, and Pure POCO's), and don't want to use triggers.</p> <p>If you have any thoughts/suggestions, let me know.</p>
3,527,203
GetFiles with multiple extensions
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/163162/can-you-call-directory-getfiles-with-multiple-filters">Can you call Directory.GetFiles() with multiple filters?</a> </p> </blockquote> <p>How do you filter on more than one extension?</p> <p>I've tried:</p> <pre><code>FileInfo[] Files = dinfo.GetFiles("*.jpg;*.tiff;*.bmp"); FileInfo[] Files = dinfo.GetFiles("*.jpg,*.tiff,*.bmp"); </code></pre>
3,527,717
7
6
null
2010-08-19 23:55:28.833 UTC
14
2019-08-05 13:33:23.273 UTC
2017-04-04 09:58:29.63 UTC
null
1,033,581
null
314,836
null
1
100
c#|.net|fileinfo|getfiles
140,452
<p>Why not create an extension method? That's more readable.</p> <pre><code>public static IEnumerable&lt;FileInfo&gt; GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions) { if (extensions == null) throw new ArgumentNullException("extensions"); IEnumerable&lt;FileInfo&gt; files = Enumerable.Empty&lt;FileInfo&gt;(); foreach(string ext in extensions) { files = files.Concat(dir.GetFiles(ext)); } return files; } </code></pre> <p>EDIT: a more efficient version:</p> <pre><code>public static IEnumerable&lt;FileInfo&gt; GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions) { if (extensions == null) throw new ArgumentNullException("extensions"); IEnumerable&lt;FileInfo&gt; files = dir.EnumerateFiles(); return files.Where(f =&gt; extensions.Contains(f.Extension)); } </code></pre> <p>Usage:</p> <pre><code>DirectoryInfo dInfo = new DirectoryInfo(@"c:\MyDir"); dInfo.GetFilesByExtensions(".jpg",".exe",".gif"); </code></pre>
3,585,840
How to use command to shutdown grails run-app
<p>After executing <code>grails run-app</code>, except using <kbd>Ctrl</kbd> + <kbd>C</kbd>", is there a command to shutdown it?</p>
3,587,718
9
0
null
2010-08-27 15:42:48.037 UTC
10
2019-11-07 18:39:54.29 UTC
2019-11-07 18:39:54.29 UTC
null
971,141
null
378,062
null
1
17
grails|shutdown|run-app
21,195
<p>No. <code>grails run-app</code> is intended to be run for development, interactively.</p> <p>If you want to control grails as a service, you should deploy it to a web application container such as tomcat. The tomcat plugin allows you to easily deploy your app to tomcat, for example. Add lines like</p> <pre><code>tomcat.deploy.username="manager" tomcat.deploy.password="secret" tomcat.deploy.url="http://myserver.com/manager" </code></pre> <p>to Config.groovy and then you can use</p> <pre><code>grails tomcat deploy grails tomcat undeploy </code></pre> <p>to start and stop your application. Alternatively, you can use <code>grails war</code> to bundle your app into a war archive which all java app servers should be able to use.</p> <p>If you really want to stop <code>grails run-app</code> without <kbd>Ctrl+C</kbd>, write a small controller that calls <code>System.exit(0)</code>. Then browse to that URL, or write a small shell script or batch file that invokes it with e.g. <code>wget</code> or <code>curl</code>.</p>
3,400,525
Global Variable from a different file Python
<p>So I have two different files somewhat like this:</p> <p>file1.py</p> <pre class="lang-py prettyprint-override"><code>from file2 import * foo = &quot;bar&quot; test = SomeClass() </code></pre> <p>file2.py</p> <pre class="lang-py prettyprint-override"><code>class SomeClass : def __init__ (self): global foo print foo </code></pre> <p>However I cannot seem to get file2 to recognize variables from file1 even though its imported into file1 already. It would be extremely helpful if this is possible in some way.</p>
3,400,652
9
2
null
2010-08-03 20:28:55.173 UTC
17
2021-08-20 03:50:22.727 UTC
2021-08-20 03:50:22.727 UTC
null
14,141,223
null
394,155
null
1
51
python
162,485
<p>Importing <code>file2</code> in <code>file1.py</code> makes the global (i.e., module level) names bound in <code>file2</code> available to following code in <code>file1</code> -- the only such name is <code>SomeClass</code>. It does <strong>not</strong> do the reverse: names defined in <code>file1</code> are not made available to code in <code>file2</code> when <code>file1</code> imports <code>file2</code>. This would be the case even if you imported the right way (<code>import file2</code>, as @nate correctly recommends) rather than in the horrible, horrible way you're doing it (if everybody under the Sun forgot the very existence of the construct <code>from ... import *</code>, life would be <em>so</em> much better for everybody).</p> <p>Apparently you want to make global names defined in <code>file1</code> available to code in <code>file2</code> <em>and</em> vice versa. This is known as a "cyclical dependency" and is a <em>terrible</em> idea (in Python, or anywhere else for that matter).</p> <p>So, rather than showing you the incredibly fragile, often unmaintainable hacks to achieve (some semblance of) a cyclical dependency in Python, I'd much rather discuss the many excellent way in which you can <strong>avoid</strong> such terrible structure.</p> <p>For example, you could put global names that need to be available to both modules in a <em>third</em> module (e.g. <code>file3.py</code>, to continue your naming streak;-) and import that third module into each of the other two (<code>import file3</code> in both <code>file1</code> and <code>file2</code>, and then use <code>file3.foo</code> etc, that is, <em>qualified</em> names, for the purpose of accessing or setting those global names from either or both of the other modules, <strong>not</strong> barenames).</p> <p>Of course, more and more specific help could be offered if you clarified (by editing your Q) exactly <em>why</em> you think you need a cyclical dependency (just one easy prediction: no matter what makes you think you need a cyclical dependency, you're wrong;-).</p>
3,226,711
Giving up Agile, Switching to waterfall - Is this right?
<p>I am working in an Agile environment and things have gone to the state where the client feels that they would prefer Waterfall due to the failures (that's what they think) of the current Agile scenario. The reason that made them think like this would be the immense amount of design level changes that happened during the end stages of the sprints which we (developers) could not complete within the time they specified. </p> <p>As usual, we both were blaming each other. From our perspective, the changes said at the end were too many and design/code alterations were too much. Whereas from the client's perspective, they complain that we (developers) are not understanding the requirements fully and coming up with solutions that were 'not' what they intended in the requirement. (like they have asked us to draw a tiger, and we drew a cat).</p> <p>So, the client felt (not us) that Agile process is not correct and they want to switch to a Waterfall mode which IMHO would be disastrous. The simple reason being their satisfaction levels in a Agile mode itself were not enough, then how are they going to tolerate the output after spending so much time during the design phase of a Waterfall development?</p> <p>Please give your suggestions.</p>
3,226,807
16
3
null
2010-07-12 07:57:04.727 UTC
16
2016-05-31 09:52:14.547 UTC
2011-12-13 16:34:15.553 UTC
null
1,977,903
null
1,977,903
null
1
53
agile|waterfall
4,414
<p>First off - ask yourself are you <em>really</em> doing Agile? If you are then you should have already delivered a large portion of usable functionality to the client which satisfied their requirements in the earlier sprints. In theory, the "damage" should be limited to the final sprint where you discovered you needed large design changes. That being the case you should have proven your ability to deliver and now need a dialogue with the client to plan the changes now required. </p> <p>However given your description I suspect you have fallen into the trap of just developing on a two week cycle without actually delivering into production each time and have a fixed end date in mind for the first proper release. If this is the case then you're really doing iterative waterfall without the requirements analysis/design up front - a bad place to be usually.</p> <p>Full waterfall is not necessarily the answer (there's enough evidence to show what the problems are with it), but some amount of upfront planning and design is generally far preferable in practice to the "pure" Agile ethos of emergent architecture (which fits with a Lean approach actually). Big projects simply cannot hope to achieve a sensible stable architectural foundation if they just start hacking at code and hope it'll all come good some number of sprints down the line.</p> <p>In addition to the above another common problem with "pure" Agile is client expectation management. Agile is sold as this wonderful thing that means the client can defer decisions, change their mind and add new requirements as they see fit. HOWEVER that doesn't mean the end date / budget / effort required remains fixed, but people always seem to miss that part.</p>
14,684,885
How to add new observation to already created dataset in SAS?
<p>How to add new observation to already created dataset in SAS ? For example, if I have dataset 'dataX' with variable 'x' and 'y' and I want to add new observation which is multiplication by two of the of the observation number n, how can I do it ?</p> <p>dataX :<br> x y<br> 1 1<br> 1 21<br> 2 3 </p> <p>I want to create :</p> <p>dataX :<br> x y<br> 1 1<br> 1 21<br> 2 3<br> 10 210</p> <p>where observation number four is multiplication by ten of observation number two.</p>
14,688,406
4
1
null
2013-02-04 10:34:33.497 UTC
null
2014-06-05 13:24:30.62 UTC
2013-02-04 13:02:35.477 UTC
null
783,421
null
783,421
null
1
3
sas
52,425
<p>Here is one way to do this:</p> <pre><code>data dataX; input x y; datalines; 1 1 1 21 2 3 run; /* Create a new observation into temp data set */ data _addRec; set dataX(firstobs=2); /* Get observation 2 */ x = x * 10; /* Multiply each by 10 */ y = y * 10; output; /* Output new observation */ stop; run; /* Add new obs to original data set */ proc append base=dataX data=_addRec; run; /* Delete the temp data set (to be safe) */ proc delete data=_addRec; run; </code></pre>
4,315,727
How to get previous and new selected value from a option DOM element with JavaScript?
<p>How can I retrieve the new selected value and the previous selected value with JavaScript when onChange or similar event is called?</p> <pre><code>&lt;select size="1" id="x" onchange="doSomething()"&gt; &lt;option value="47"&gt;Value 47&lt;/option&gt; ... function doSomething() { var oldValue = null; // how to get the old value? var newValue = document.getElementById('x').selected.value; // ... </code></pre> <p>Thank you! :)</p>
4,315,813
4
0
null
2010-11-30 16:00:13.533 UTC
3
2021-01-18 19:05:47.253 UTC
2010-11-30 16:05:35.67 UTC
null
42,659
null
42,659
null
1
10
javascript|html|xhtml
42,880
<p>Using straight JavaScript and DOM, something like this (<a href="http://jsbin.com/asomu3" rel="nofollow">live example</a>):</p> <pre class="lang-js prettyprint-override"><code>var box, oldValue; // Get a reference to the select box's DOM element. // This can be any of several ways; below I'll look // it up by ID. box = document.getElementById('theSelect'); if (box.addEventListener) { // DOM2 standard box.addEventListener("change", changeHandler, false); } else if (box.attachEvent) { // IE fallback box.attachEvent("onchange", changeHandler); } else { // DOM0 fallback box.onchange = changeHandler; } // Our handler function changeHandler(event) { var index, newValue; // Get the current index index = this.selectedIndex; if (index &gt;= 0 &amp;&amp; this.options.length &gt; index) { // Get the new value newValue = this.options[index].value; } // **Your code here**: old value is `oldValue`, new value is `newValue` // Note that `newValue`` may well be undefined display("Old value: " + oldValue); display("New value: " + newValue); // When done processing the change, remember the old value oldValue = newValue; } </code></pre> <p>(I'm assuming all of the above is inside a function, like a page load function or similar, as in the <a href="http://jsbin.com/asomu3" rel="nofollow">live example</a>, so we're not creating unnecessary global symbols [<code>box</code>, <code>oldValue</code>, 'changeHandler`].)</p> <p>Note that the <code>change</code> event is raised by different browsers at different times. Some browsers raise the event when the selection changes, others wait until focus leaves the select box.</p> <p>But you might consider using a library like <a href="http://jquery.com" rel="nofollow">jQuery</a>, <a href="http://prototypejs.org" rel="nofollow">Prototype</a>, <a href="http://developer.yahoo.com/yui/" rel="nofollow">YUI</a>, <a href="http://code.google.com/closure/library" rel="nofollow">Closure</a>, or <a href="http://en.wikipedia.org/wiki/List_of_JavaScript_libraries" rel="nofollow">any of several others</a>, as they make a lot of this stuff a lot easier.</p>
4,706,216
java singleton instantiation
<p>I've found three ways of instantiating a Singleton, but I have doubts as to whether any of them is the best there is. I'm using them in a multi-threaded environment and prefer lazy instantiation.<br> Sample 1: </p> <pre><code>private static final ClassName INSTANCE = new ClassName(); public static ClassName getInstance() { return INSTANCE; } </code></pre> <p>Sample 2:</p> <pre><code>private static class SingletonHolder { public static final ClassName INSTANCE = new ClassName(); } public static ClassName getInstance() { return SingletonHolder.INSTANCE; } </code></pre> <p>Sample 3:</p> <pre><code>private static ClassName INSTANCE; public static synchronized ClassName getInstance() { if (INSTANCE == null) INSTANCE = new ClassName(); return INSTANCE; } </code></pre> <p>The project I'm using ATM uses Sample 2 everywhere, but I kind of like Sample 3 more. There is also the Enum version, but I just don't get it. </p> <p>The question here is - in which cases I should/shouldn't use any of these variations? I'm not looking for lengthy explanations though (there's plenty of other topics about that, but they all eventually turn into arguing IMO), I'd like it to be understandable with few words.</p>
4,706,256
4
0
null
2011-01-16 15:35:58.107 UTC
11
2014-09-21 07:10:25.98 UTC
null
null
null
null
540,394
null
1
10
java|singleton|instance
10,872
<p>The most secure and easy way to implement a singleton in java is by using enums (like you mentioned):</p> <pre><code>public enum ClassName { INSTANCE; // fields, setters and getters } </code></pre> <p>The enum semantics guarantees that there will be only one <code>INSTANCE</code></p> <p>If not using the enum approach, you must take care of quite a lot aspects, like race conditions and reflection. I've been breaking singletons of some frameworks, and abusing them, because they weren't properly written. The enum guarantees no one will break it.</p>
4,052,304
Selenium - check if an image is displayed on page
<p>I'm creating a suite of Selenium tests for an web album application. I would like to test whether an image is actually displayed (it contains valid image data). Is such thing possible?</p>
10,430,032
4
0
null
2010-10-29 13:28:49.57 UTC
16
2018-04-07 13:17:02.43 UTC
2016-07-29 07:22:29.01 UTC
null
2,306,173
null
38,256
null
1
15
image|selenium|selenium-webdriver
24,008
<p>I faced this similar situation before where the src of the image is as expected but the image is not displayed on the page.</p> <p>You can check if the image is getting displayed or not by using the JavaScriptExcecutor.</p> <p>Use the following code - Pass the WebElement (image) - </p> <pre><code> Object result = ((JavascriptExecutor) driver).executeScript( "return arguments[0].complete &amp;&amp; "+ "typeof arguments[0].naturalWidth != \"undefined\" &amp;&amp; "+ "arguments[0].naturalWidth &gt; 0", image); boolean loaded = false; if (result instanceof Boolean) { loaded = (Boolean) result; System.out.println(loaded); } </code></pre> <p>You can verify if the image has actually loaded on the webpage by doing this. </p>
4,287,503
Where in the Ruby language is %q, %w, etc., defined?
<p>So much of the Ruby language is methods rather than syntax, so I expected to find <code>%q</code>, <code>%w</code>, etc., defined as methods in the <code>Kernel</code> class. However, they're not there.</p> <p>So where are they defined? Are they language keywords?</p>
4,287,702
4
0
null
2010-11-26 17:43:54.687 UTC
14
2012-10-20 02:51:02.39 UTC
2012-09-04 01:57:10.917 UTC
null
211,563
null
501,266
null
1
30
ruby
8,461
<p>They are “hard coded” in the parser; see</p> <ul> <li><a href="http://svn.ruby-lang.org/cgi-bin/viewvc.cgi/branches/ruby_1_9_2/parse.y?view=markup" rel="noreferrer">parse.y from the tip of Ruby 1.9.2</a> or</li> <li><a href="http://svn.ruby-lang.org/cgi-bin/viewvc.cgi/branches/ruby_1_8_7/parse.y?view=markup" rel="noreferrer">parse.y from the tip of Ruby 1.8.7</a>.</li> </ul> <p>The easiest way to find the code in question is to look for the second occurrence of <code>str_sword</code> (Single-quoted WORDs). All the “delimited input” syntax is defined there: <code>%Q</code>, <code>%q</code>, <code>%W</code>, <code>%w</code>, <code>%x</code>, <code>%r</code>, and <code>%s</code> (both versions referenced above define the same set of delimited input markers).</p>
4,337,582
Do events handlers on a DOM node get deleted with the node?
<p>(Note: I'm using jQuery below, but the question is really a general JavaScript one.)</p> <p>Say I've got a <code>div#formsection</code> whose contents are repeatedly updated using AJAX, like this:</p> <pre><code>var formSection = $('div#formsection'); var newContents = $.get(/* URL for next section */); formSection.html(newContents); </code></pre> <p>Whenever I update this div, I <a href="http://fuelyourcoding.com/jquery-custom-events-they-will-rock-your-world/" rel="nofollow noreferrer">trigger a custom event</a>, which binds event handlers to some of the newly-added elements, like this:</p> <pre><code>// When the first section of the form is loaded, this runs... formSection.find('select#phonenumber').change(function(){/* stuff */}); ... // ... when the second section of the form is loaded, this runs... formSection.find('input#foo').focus(function(){/* stuff */}); </code></pre> <p>So: I'm binding event handlers to some DOM nodes, then later, deleting those DOM nodes and inserting new ones (<code>html()</code> does that) and binding event handlers to the new DOM nodes.</p> <p><strong>Are my event handlers deleted along with the DOM nodes they're bound to?</strong> In other words, as I load new sections, are lots of useless event handlers piling up in the browser memory, waiting for events on DOM nodes that no longer exist, or are they cleared out when their DOM nodes are deleted?</p> <p>Bonus question: <strong>how can test this myself?</strong></p>
4,338,065
5
9
null
2010-12-02 16:55:21.28 UTC
11
2022-07-25 10:53:59.737 UTC
2022-07-25 10:53:59.737 UTC
null
4,370,109
null
4,376
null
1
33
javascript|dom|jquery-events
12,202
<p>Event handler functions are subject to the same Garbage Collection that other variables are. That means they will be removed from memory when the interpreter determines that there is no possible means to obtain a reference to the function. Simply deleting a node however does not guarantee garbage collection. For instance, take this node and associated event handler</p> <pre><code>var node = document.getElementById('test'); node.onclick = function() { alert('hai') }; </code></pre> <p>Now lets remove the node from the DOM</p> <pre><code>node.parentNode.removeChild(node); </code></pre> <p>So <code>node</code> will no longer be visible on your website, but it clearly still exists in memory, as does the event handler</p> <pre><code>node.onclick(); //alerts hai </code></pre> <p>As long as the reference to <code>node</code> is still accessible somehow, it's associated properties (of which <code>onclick</code> is one) will remain intact.</p> <p>Now let's try it without creating a dangling variable</p> <pre><code>document.getElementById('test').onclick = function() { alert('hai'); } document.getElementById('test').parentNode.removeChild(document.getElementById('test')); </code></pre> <p>In this case, there seems to be no further way to access the DOM node #test, so when a garbage collection cycle is run, the <code>onclick</code> handler should be removed from memory.</p> <p>But this is a very simple case. Javascript's use of closures can greatly complicate the determination of garbage collectability. Lets try binding a slightly more complex event handler function to <code>onclick</code></p> <pre><code>document.getElementById('test').onclick = function() { var i = 0; setInterval(function() { console.log(i++); }, 1000); this.parentNode.removeChild(this); }; </code></pre> <p>So when you click on #test, the element will instantly be removed, however one second later, and every second afterwards, you will see an incremented number printed to your console. The node is removed, and no further reference to it is possible, yet it seems parts of it remain. In this case the event handler function itself is likely not retained in memory but the scope it created is. </p> <p>So the answer I guess is; it depends. If there are dangling, accessible references to deleted DOM nodes, their associated event handlers will still reside in memory, along with the rest of their properties. Even if this is not the case, the scope created by the event handler functions might still be in use and in memory. </p> <p>In most cases (and happily ignoring IE6) it is best to just trust the Garbage Collector to do its job, Javascript is not C after all. However, in cases like the last example, it is important to write destructor functions of some sort to implicitly shut down functionality. </p>
4,242,634
Class vs data structure
<p>In object oriented programming, a custom class (like Person class with data of Name, list of addresses, etc)holds data and can include collection objects too. A data structure is also used to hold data too. So, is a class considered advanced data structure conceptually ? And in design of efficient systems (in object oriented world and large systems), are classes considered as similar to data structures and algorithmic analysis done for efficient classes designs for greater efficiency(in companies like google, facebook) ? </p>
4,242,802
6
2
null
2010-11-22 05:46:23.873 UTC
14
2019-08-28 08:23:59.183 UTC
2010-11-22 14:43:36.647 UTC
Aryabhatta
null
null
515,661
null
1
28
oop|class|data-structures
26,945
<p>Whether a custom class is a data structure depends on whom you ask. At the very least, the yes people would acknowledge than it's a user-defined data structure which is more domain specific and less established than data structures such as arrays, linked lists or binary trees for example. For this answer, I consider them distinct.</p> <p>While it's easy to apply Big O algorithm analysis to data structures, it's a little more complex for classes since they wrap many of these structures, as well as other instances of other classes... but a lot of operations on class instances can be broken down into primitive operations on data structures and represented in terms of Big O. As a programmer, you can endeavour to make your classes more efficient by avoiding unnecessary copying of members and ensuring that method invocations don't go through too many layers. And of course, using performant algorithms in your methods goes without saying, but that's not OOP specific. However, functionality, design and clarity should not be sacrificed in favour of performance unless necessary. And premature optimisation is the devil yada yada yada.</p> <p>I'm certain that some academic, somewhere, has attempted to formulate a metric for quantifying class performance or even a calculus for classes and their operations, but I haven't come across it yet. However, there exists QA research like <a href="http://www.cs.auckland.ac.nz/~hayden/research.htm" rel="noreferrer">this</a> which measures dependencies between classes in a project... one could possibly argue that there's a correlation between the number of dependencies and the layering of method invocations (and therefore lower class performance). But if someone has researched this, I'm sure you could find a more relevant metric which doesn't require sweeping inferences.</p>
4,718,960
DateTime.TryParse issue with dates of yyyy-dd-MM format
<p>I have the following date in string format "2011-29-01 12:00 am" . Now I am trying to convert that to datetime format with the following code:</p> <pre><code>DateTime.TryParse(dateTime, out dt); </code></pre> <p>But I am alwayws getting dt as {1/1/0001 12:00:00 AM} , Can you please tell me why ? and how can I convert that string to date.</p> <p>EDIT: I just saw everybody mentioned to use format argument. I will mention now that I can't use the format parameter as I have some setting to select the custom dateformat what user wants, and based on that user is able to get the date in textbox in that format automatically via jQuery datepicker.</p>
4,719,050
7
1
null
2011-01-17 23:20:24.297 UTC
9
2021-12-27 16:43:14.523 UTC
2011-01-17 23:39:19.1 UTC
null
449,907
null
449,907
null
1
92
c#|asp.net|datetime|date|tryparse
207,181
<p>This should work based on your example "2011-29-01 12:00 am"</p> <pre><code>DateTime dt; DateTime.TryParseExact(dateTime, "yyyy-dd-MM hh:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt); </code></pre>
4,262,550
How do I get Ruby to parse time as if it were in a different time zone?
<p>I'm parsing something like this:</p> <pre><code>11/23/10 23:29:57 </code></pre> <p>which has no time zone associated with it, but I know it's in the UTC time zone (while I'm not). How can I get Ruby to parse this as if it were in the UTC timezone?</p>
4,262,615
8
0
null
2010-11-24 00:54:34.263 UTC
5
2021-10-26 00:43:34.97 UTC
2010-11-24 02:25:23.997 UTC
null
128,421
null
1,193,598
null
1
51
ruby|timezone
49,511
<p>You could just append the UTC timezone name to the string before parsing it:</p> <pre><code>require 'time' s = "11/23/10 23:29:57" Time.parse(s) # =&gt; Tue Nov 23 23:29:57 -0800 2010 s += " UTC" Time.parse(s) # =&gt; Tue Nov 23 23:29:57 UTC 2010 </code></pre>
4,551,230
Bind jQuery UI autocomplete using .live()
<p>I've searched everywhere, but I can't seem to find any help...</p> <p>I have some textboxes that are created dynamically via JS, so I need to bind all of their classes to an autocomplete. As a result, I need to use the new .live() option.</p> <p>As an example, to bind all items with a class of .foo now and future created:</p> <pre><code>$('.foo').live('click', function(){ alert('clicked'); }); </code></pre> <p>It takes (and behaves) the same as .bind(). However, I want to bind an autocomplete...</p> <p>This doesn't work:</p> <pre><code>$('.foo').live('autocomplete', function(event, ui){ source: 'url.php' // (surpressed other arguments) }); </code></pre> <p>How can I use .live() to bind autocomplete?</p> <p>UPDATE</p> <p>Figured it out with Framer:</p> <pre><code>$(function(){ $('.search').live('keyup.autocomplete', function(){ $(this).autocomplete({ source : 'url.php' }); }); }); </code></pre>
4,551,267
12
2
null
2010-12-29 03:19:25.407 UTC
14
2017-06-13 16:41:28.807 UTC
2011-06-03 16:10:01.89 UTC
null
365,738
null
365,738
null
1
65
binding|autocomplete|jquery
38,817
<p>If you are using the <code>jquery.ui.autocomplete.js</code> try this instead</p> <pre><code>.bind("keydown.autocomplete") or .live("keydown.autocomplete") </code></pre> <p>if not, use the <code>jquery.ui.autocomplete.js</code> and see if it'll work</p> <p>If that doesn't apply, I don't know how to help you bro</p>
14,422,409
Difference between tuples and frozensets in Python
<p>I'm learning Python 3 using The Quick Python Book, where the author talks about frozensets, stating that since sets are mutable and hence unhashable, thereby becoming unfit for being dictionary keys, their frozen counterparts were introduced. Other than the obvious difference that a tuple is an ordered data structure while frozenset, or more generally a set, is unordered, are there any other differences between a tuple and a frozenset?</p>
14,422,446
4
0
null
2013-01-20 07:00:17.37 UTC
7
2020-08-08 20:30:03.75 UTC
2014-02-17 11:07:32.77 UTC
null
183,120
null
183,120
null
1
61
python|data-structures|set|tuples
30,413
<p><code>tuples</code> are immutable <code>lists</code>, <code>frozensets</code> are immutable <code>sets</code>.</p> <p><code>tuples</code> are indeed an ordered collection of objects, but they can contain duplicates and unhashable objects, and have slice functionality</p> <p><code>frozensets</code> aren't indexed, but you have the functionality of <code>sets</code> - O(1) element lookups, and functionality such as unions and intersections. They also can't contain duplicates, like their mutable counterparts.</p>
14,481,592
WebAPI No action was found on the controller
<p>I got an error - No action was found on the controller 'Action' that matches the request.</p> <p>The url is <code>http://localhost:37331/api/action/FindByModule/1</code>.</p> <p>The routing I used is </p> <pre><code>config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); </code></pre> <p>Controller:</p> <pre><code>public class ActionController : ApiController { private IActionRepository repository = null; [HttpGet] [ActionName("All")] public IEnumerable&lt;JsonAction&gt; All() { return from action in this.repository.Get() select new JsonAction { ID = action.ID, Text = action.Text.Trim(), Description = action.Description.Trim(), }; } [HttpGet] [ActionName("FindByModule")] public IEnumerable&lt;JsonAction&gt; FindByModule(Int64 moduleId) { return from action in this.repository.FindByModule(moduleId) select new JsonAction { ID = action.ID, Text = action.Text.Trim(), Description = action.Description.Trim(), }; } } </code></pre>
14,482,488
2
0
null
2013-01-23 14:03:29.687 UTC
8
2022-01-24 08:22:46.877 UTC
2013-02-25 18:39:39.167 UTC
null
333,253
null
528,837
null
1
64
asp.net|asp.net-web-api
105,040
<p>This is because there is a parameter name mismatch. From your route the value <strong>1</strong> is assigned to parameter named <code>id</code> and your action is looking for parameter named <code>moduleId</code>.</p> <p>First option is to change your route like this:</p> <pre><code>config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{moduleId}", defaults: new { moduleId = RouteParameter.Optional } ); </code></pre> <p>Second is to change your URL like this:</p> <pre><code>http://localhost:37331/api/action/FindByModule?moduleId=1 </code></pre> <p>So the parameter name match.</p>
14,485,115
Synchronously waiting for an async operation, and why does Wait() freeze the program here
<p><strong>Preface</strong>: I'm looking for an explanation, not just a solution. I already know the solution.</p> <p>Despite having spent several days studying MSDN articles about the Task-based Asynchronous Pattern (TAP), async and await, I'm still a bit confused about some of the finer details.</p> <p>I'm writing a logger for Windows Store Apps, and I want to support both asynchronous and synchronous logging. The asynchronous methods follow the TAP, the synchronous ones should hide all this, and look and work like ordinary methods.</p> <p>This is the core method of asynchronous logging:</p> <pre><code>private async Task WriteToLogAsync(string text) { StorageFolder folder = ApplicationData.Current.LocalFolder; StorageFile file = await folder.CreateFileAsync("log.log", CreationCollisionOption.OpenIfExists); await FileIO.AppendTextAsync(file, text, Windows.Storage.Streams.UnicodeEncoding.Utf8); } </code></pre> <p>Now the corresponding synchronous method...</p> <p><strong>Version 1</strong>:</p> <pre><code>private void WriteToLog(string text) { Task task = WriteToLogAsync(text); task.Wait(); } </code></pre> <p>This looks correct, but it does not work. The whole program freezes forever.</p> <p><strong>Version 2</strong>:</p> <p>Hmm.. Maybe the task was not started?</p> <pre><code>private void WriteToLog(string text) { Task task = WriteToLogAsync(text); task.Start(); task.Wait(); } </code></pre> <p>This throws <code>InvalidOperationException: Start may not be called on a promise-style task.</code></p> <p><strong>Version 3:</strong></p> <p>Hmm.. <code>Task.RunSynchronously</code> sounds promising.</p> <pre><code>private void WriteToLog(string text) { Task task = WriteToLogAsync(text); task.RunSynchronously(); } </code></pre> <p>This throws <code>InvalidOperationException: RunSynchronously may not be called on a task not bound to a delegate, such as the task returned from an asynchronous method.</code></p> <p><strong>Version 4 (the solution):</strong></p> <pre><code>private void WriteToLog(string text) { var task = Task.Run(async () =&gt; { await WriteToLogAsync(text); }); task.Wait(); } </code></pre> <p>This works. So, 2 and 3 are the wrong tools. But 1? What's wrong with 1 and what's the difference to 4? What makes 1 cause a freeze? Is there some problem with the task object? Is there a non-obvious deadlock?</p>
14,485,163
5
4
null
2013-01-23 16:56:39.22 UTC
115
2021-06-18 20:27:10.013 UTC
2019-01-21 03:16:08.373 UTC
null
5,640
null
469,708
null
1
363
c#|.net|task-parallel-library|windows-store-apps|async-await
136,654
<p>The <code>await</code> inside your asynchronous method is trying to come back to the UI thread.</p> <p>Since the UI thread is busy waiting for the entire task to complete, you have a deadlock.</p> <p>Moving the async call to <code>Task.Run()</code> solves the issue.<br> Because the async call is now running on a thread pool thread, it doesn't try to come back to the UI thread, and everything therefore works.</p> <p>Alternatively, you could call <code>StartAsTask().ConfigureAwait(false)</code> before awaiting the inner operation to make it come back to the thread pool rather than the UI thread, avoiding the deadlock entirely. </p>
2,819,435
Codeigniter: Get Instance
<p>What is the purpose of "Get Instance" in Codeigniter? How would you explain this to a total beginner?</p>
2,819,775
2
0
null
2010-05-12 13:56:08.213 UTC
4
2015-07-16 08:50:47.803 UTC
null
null
null
null
103,753
null
1
24
codeigniter
46,367
<p>Ok, so everything in CodeIgniter runs through the super-magic <code>$this</code> variable. This only works for classes, as <code>$this</code> basically defines the current class.</p> <p>Your controller is a class, so $this is there, allowing you to do <code>$this-&gt;load-&gt;model('whatever');</code></p> <p>In models, you are also using a class. It is slightly different here, as <code>$this</code> only contains useful stuff as you are extending from Model. Still, <code>$this</code> is still valid.</p> <p>When you are using a helper or a library, you need to find that "instance" or <code>$this</code> equivalent.</p> <pre><code>$ci =&amp; get_instance(); </code></pre> <p>…makes <code>$ci</code> contain the exact same stuff/code/usefulness as <code>$this</code>, even though you are not in a class, or not in a class that inherits it.</p> <p>That's an explanation for total beginners after 2 pints, so it's either wrong or about right. ;-)</p>
3,107,514
HTML Agility Pack strip tags NOT IN whitelist
<p>I'm trying to create a function which removes html tags and attributes which are not in a white list. I have the following HTML: </p> <pre><code>&lt;b&gt;first text &lt;/b&gt; &lt;b&gt;second text here &lt;a&gt;some text here&lt;/a&gt; &lt;a&gt;some text here&lt;/a&gt; &lt;/b&gt; &lt;a&gt;some twxt here&lt;/a&gt; </code></pre> <p>I am using HTML agility pack and the code I have so far is:</p> <pre><code>static List&lt;string&gt; WhiteNodeList = new List&lt;string&gt; { "b" }; static List&lt;string&gt; WhiteAttrList = new List&lt;string&gt; { }; static HtmlNode htmlNode; public static void RemoveNotInWhiteList(out string _output, HtmlNode pNode, List&lt;string&gt; pWhiteList, List&lt;string&gt; attrWhiteList) { // remove all attributes not on white list foreach (var item in pNode.ChildNodes) { item.Attributes.Where(u =&gt; attrWhiteList.Contains(u.Name) == false).ToList().ForEach(u =&gt; RemoveAttribute(u)); } // remove all html and their innerText and attributes if not on whitelist. //pNode.ChildNodes.Where(u =&gt; pWhiteList.Contains(u.Name) == false).ToList().ForEach(u =&gt; u.Remove()); //pNode.ChildNodes.Where(u =&gt; pWhiteList.Contains(u.Name) == false).ToList().ForEach(u =&gt; u.ParentNode.ReplaceChild(ConvertHtmlToNode(u.InnerHtml),u)); //pNode.ChildNodes.Where(u =&gt; pWhiteList.Contains(u.Name) == false).ToList().ForEach(u =&gt; u.Remove()); for (int i = 0; i &lt; pNode.ChildNodes.Count; i++) { if (!pWhiteList.Contains(pNode.ChildNodes[i].Name)) { HtmlNode _newNode = ConvertHtmlToNode(pNode.ChildNodes[i].InnerHtml); pNode.ChildNodes[i].ParentNode.ReplaceChild(_newNode, pNode.ChildNodes[i]); if (pNode.ChildNodes[i].HasChildNodes &amp;&amp; !string.IsNullOrEmpty(pNode.ChildNodes[i].InnerText.Trim().Replace("\r\n", ""))) { HtmlNode outputNode1 = pNode.ChildNodes[i]; for (int j = 0; j &lt; pNode.ChildNodes[i].ChildNodes.Count; j++) { string _childNodeOutput; RemoveNotInWhiteList(out _childNodeOutput, pNode.ChildNodes[i], WhiteNodeList, WhiteAttrList); pNode.ChildNodes[i].ReplaceChild(ConvertHtmlToNode(_childNodeOutput), pNode.ChildNodes[i].ChildNodes[j]); i++; } } } } // Console.WriteLine(pNode.OuterHtml); _output = pNode.OuterHtml; } private static void RemoveAttribute(HtmlAttribute u) { u.Value = u.Value.ToLower().Replace("javascript", ""); u.Remove(); } public static HtmlNode ConvertHtmlToNode(string html) { HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(html); if (doc.DocumentNode.ChildNodes.Count == 1) return doc.DocumentNode.ChildNodes[0]; else return doc.DocumentNode; } </code></pre> <p>The output I am tryig to achieve is</p> <pre><code>&lt;b&gt;first text &lt;/b&gt; &lt;b&gt;second text here some text here some text here &lt;/b&gt; some twxt here </code></pre> <p>That means that I only want to keep the <code>&lt;b&gt;</code> tags.<br> The reason i'm doing this is because Some of the users do cpoy-paste from MS WORD into ny WYSYWYG html editor.</p> <p>Thanks.!</p>
3,107,567
2
0
null
2010-06-24 05:52:00.593 UTC
25
2021-11-02 09:54:44.92 UTC
2012-04-04 19:18:35.617 UTC
null
134,445
null
249,895
null
1
30
c#|tags|html-parsing|html-agility-pack|sanitize
19,213
<p>heh, apparently I ALMOST found an answer in a blog post someone made....</p> <pre><code>using System.Collections.Generic; using System.Linq; using HtmlAgilityPack; namespace Wayloop.Blog.Core.Markup { public static class HtmlSanitizer { private static readonly IDictionary&lt;string, string[]&gt; Whitelist; static HtmlSanitizer() { Whitelist = new Dictionary&lt;string, string[]&gt; { { "a", new[] { "href" } }, { "strong", null }, { "em", null }, { "blockquote", null }, }; } public static string Sanitize(string input) { var htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(input); SanitizeNode(htmlDocument.DocumentNode); return htmlDocument.DocumentNode.WriteTo().Trim(); } private static void SanitizeChildren(HtmlNode parentNode) { for (int i = parentNode.ChildNodes.Count - 1; i &gt;= 0; i--) { SanitizeNode(parentNode.ChildNodes[i]); } } private static void SanitizeNode(HtmlNode node) { if (node.NodeType == HtmlNodeType.Element) { if (!Whitelist.ContainsKey(node.Name)) { node.ParentNode.RemoveChild(node); return; } if (node.HasAttributes) { for (int i = node.Attributes.Count - 1; i &gt;= 0; i--) { HtmlAttribute currentAttribute = node.Attributes[i]; string[] allowedAttributes = Whitelist[node.Name]; if (!allowedAttributes.Contains(currentAttribute.Name)) { node.Attributes.Remove(currentAttribute); } } } } if (node.HasChildNodes) { SanitizeChildren(node); } } } } </code></pre> <p><a href="http://thomasjo.com/blog/archive/a-pessimistic-html-sanitizer/" rel="noreferrer">I got HtmlSanitizer from here</a> Apparently it does not strip th tags, but removes the element altoghether.</p> <p>OK, here is the solution for those who will need it later.</p> <pre><code>public static class HtmlSanitizer { private static readonly IDictionary&lt;string, string[]&gt; Whitelist; private static List&lt;string&gt; DeletableNodesXpath = new List&lt;string&gt;(); static HtmlSanitizer() { Whitelist = new Dictionary&lt;string, string[]&gt; { { "a", new[] { "href" } }, { "strong", null }, { "em", null }, { "blockquote", null }, { "b", null}, { "p", null}, { "ul", null}, { "ol", null}, { "li", null}, { "div", new[] { "align" } }, { "strike", null}, { "u", null}, { "sub", null}, { "sup", null}, { "table", null }, { "tr", null }, { "td", null }, { "th", null } }; } public static string Sanitize(string input) { if (input.Trim().Length &lt; 1) return string.Empty; var htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(input); SanitizeNode(htmlDocument.DocumentNode); string xPath = HtmlSanitizer.CreateXPath(); return StripHtml(htmlDocument.DocumentNode.WriteTo().Trim(), xPath); } private static void SanitizeChildren(HtmlNode parentNode) { for (int i = parentNode.ChildNodes.Count - 1; i &gt;= 0; i--) { SanitizeNode(parentNode.ChildNodes[i]); } } private static void SanitizeNode(HtmlNode node) { if (node.NodeType == HtmlNodeType.Element) { if (!Whitelist.ContainsKey(node.Name)) { if (!DeletableNodesXpath.Contains(node.Name)) { //DeletableNodesXpath.Add(node.Name.Replace("?","")); node.Name = "removeableNode"; DeletableNodesXpath.Add(node.Name); } if (node.HasChildNodes) { SanitizeChildren(node); } return; } if (node.HasAttributes) { for (int i = node.Attributes.Count - 1; i &gt;= 0; i--) { HtmlAttribute currentAttribute = node.Attributes[i]; string[] allowedAttributes = Whitelist[node.Name]; if (allowedAttributes != null) { if (!allowedAttributes.Contains(currentAttribute.Name)) { node.Attributes.Remove(currentAttribute); } } else { node.Attributes.Remove(currentAttribute); } } } } if (node.HasChildNodes) { SanitizeChildren(node); } } private static string StripHtml(string html, string xPath) { HtmlDocument htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(html); if (xPath.Length &gt; 0) { HtmlNodeCollection invalidNodes = htmlDoc.DocumentNode.SelectNodes(@xPath); foreach (HtmlNode node in invalidNodes) { node.ParentNode.RemoveChild(node, true); } } return htmlDoc.DocumentNode.WriteContentTo(); ; } private static string CreateXPath() { string _xPath = string.Empty; for (int i = 0; i &lt; DeletableNodesXpath.Count; i++) { if (i != DeletableNodesXpath.Count - 1) { _xPath += string.Format("//{0}|", DeletableNodesXpath[i].ToString()); } else _xPath += string.Format("//{0}", DeletableNodesXpath[i].ToString()); } return _xPath; } } </code></pre> <p>I renamed the node because if I had to parse an XML namespace node it would crash on the xpath parsing.</p>
3,195,668
Android programmatically include layout (i.e. without XML)
<p>So I've created an Activity subclass called CustomTitlebarActivity. Essentially, each main activity in my app will have a custom titlebar with many common features such as a Home button, a title, a search button, etc. In my current implementation, I am still explicitly using an include statement in the layout XML for each CustomTitlebarActivity:</p> <pre><code>&lt;include layout="@layout/titlebar" /&gt; </code></pre> <p>It seems natural that I should be able to do this within CustomTitlebarActivity. I have two questions: What code can replace this include tag, and where should I put the code? (My first instinct would be to put it in CustomTitlebarActivity's setContentView method.)</p> <p>On a related note, I would appreciate insight into better ways to reuse android UI code (even if, per se, the titlebars need to vary slightly between activities.)</p>
3,195,924
2
0
null
2010-07-07 14:24:06.337 UTC
14
2017-11-22 16:22:58.727 UTC
2012-03-16 07:22:33.287 UTC
null
948,041
null
127,422
null
1
41
java|android|include
65,227
<p>Personally, I'd probably write my <code>Activity</code> subclass to always <code>setContentView</code> to a layout file containing a vertical <code>fill_parent</code> <code>LinearLayout</code> containing only my title bar:-</p> <pre><code>&lt;LinearLayout android:id="@+id/custom_titlebar_container" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;!--titlebar here--&gt; &lt;/LinearLayout&gt; </code></pre> <p>Then I'd define an abstract <code>getContentAreaLayoutId()</code> method in <code>CustomTitlebarActivity</code> that returns the layout <code>ID</code> of the content below the titlebar for each subclass; the base <code>onCreate()</code> of <code>CustomTitlebarActivity</code> would then just call</p> <pre><code>setContentView(R.layout.custom_titlebar_activity_frame_from_above); View.inflate(this, getContentAreaLayoutId(), findViewById(R.id.custom_titlebar_container)); </code></pre> <p>Alternatively, you could have your abstract method for getting the content area return a <code>View</code> rather than an <code>int</code>, giving you more flexibility to construct your views dynamically (but forcing you to inflate them yourself in the simple <em>just dump this XML layout here</em> case).</p>
55,091,768
What is .phpunit.result.cache
<p>When I run tests with <strong>PhpUnit</strong> on a new package I'm creating for Laravel, it generates the file <code>.phpunit.result.cache</code>. </p> <p>What to do with that? Do I add it to my <code>.gitignore</code> file or not?</p> <p>I'm using PHPUnit 8.0.4</p>
55,091,860
3
0
null
2019-03-10 19:54:45.447 UTC
4
2022-09-20 14:17:02.977 UTC
2022-09-20 14:17:02.977 UTC
null
4,840,661
null
10,075,394
null
1
53
php|laravel|unit-testing|laravel-5|phpunit
17,719
<p>This file helps PHPUnit remember which tests previously failed, which can speed up your testing flow if you only re-run failed tests during development. This is useful for test-driven workflows in which you have configured tests to run automatically, such as on file save, and the same collection of tests is being run repeatedly.</p> <blockquote> <p>It is also a good idea to add the cache file .phpunit.result.cache to your .gitignore so that it does not end up being committed to your repository.</p> <p><a href="https://laravel-news.com/tips-to-speed-up-phpunit-tests" rel="noreferrer">https://laravel-news.com/tips-to-speed-up-phpunit-tests</a></p> </blockquote> <p>If you would prefer not to generate the file then you can run phpunit with the <code>--do-not-cache-result</code> option, as pointed out by @Slack Undertow in the comments. This might be desired when running tests as part of a build pipeline, for example. Or, as @codekandis pointed out, the same option is available as the <code>cacheResult</code> attribute in <code>phpunit.xml</code>.</p>
45,742,607
Switch to "Native Windows Secure Channel library" from "OpenSSL library" on Windows Git, without reinstalling?
<p>During the installation of Git on my Windows machine, I selected "Use the OpenSSL library" for HTTPS Transport backend.</p> <p>I would like to switch to "Native Windows Secure Channel library" for HTTPS Transport.</p> <p>Is this possible without re-installing git on Windows?</p>
47,022,235
4
0
null
2017-08-17 18:30:17.54 UTC
9
2019-06-07 15:46:31.59 UTC
2017-10-14 17:47:21.777 UTC
null
202,229
null
420,558
null
1
17
git|ssh|https|configuration|installation
24,442
<p>The issue has been resolved by the Git for Windows developer: <a href="https://github.com/git-for-windows/git/issues/1274" rel="nofollow noreferrer">https://github.com/git-for-windows/git/issues/1274</a></p>
29,542,576
How do I get the value of a radio button in PHP?
<p>I've created a basic website that requires the user to select a radio button. I want a PHP file to retrieve the value of the radio button that was chosen and respond accordingly, but the file does not currently produce any output. What is wrong with the code I am using now? Why can my PHP file not retrieve the radio button value properly?</p> <p>Index.html:</p> <pre><code>&lt;form method="POST"&gt; &lt;input type="radio" name="MyRadio" value="First" checked&gt;First&lt;br&gt; //This one is automatically checked when the user opens the page &lt;input type="radio" name="MyRadio" value="Second"&gt;Second &lt;/form&gt; &lt;form method="GET" action="Result.php"&gt; &lt;input type="submit" value="Result" name="Result"&gt; //This button opens Result.php &lt;/form&gt; </code></pre> <p>Result.php:</p> <pre><code>&lt;?php $radioVal = $_POST["MyRadio"]; if($radioVal == "First") { echo("You chose the first button. Good choice. :D"); } else if ($radioVal == "Second") { echo("Second, eh?"); } ?&gt; </code></pre>
29,542,741
5
0
null
2015-04-09 15:20:19.76 UTC
4
2017-12-24 15:23:09.097 UTC
null
null
null
user4721723
null
null
1
22
php|html
130,942
<p>Your are using two separate forms for your general input elements and one consisting of a submit button only.</p> <p>Include the submit button in the first form and it should work fine:</p> <pre><code>&lt;form method="POST" action="Result.php"&gt; &lt;input type="radio" name="MyRadio" value="First" checked&gt;First&lt;br&gt; //This one is automatically checked when the user opens the page &lt;input type="radio" name="MyRadio" value="Second"&gt;Second &lt;input type="submit" value="Result" name="Result"&gt; //This button opens Result.php &lt;/form&gt; </code></pre>
67,655,096
Bootstrap 5 form-group, form-row, form-inline not working
<p>I'm trying to update my app from Bootstrap 4 to Bootstrap 5, but all the elements that were using form classes such as <code>form-group</code>, <code>form-row</code>, <code>form-inline</code> are completely broken.</p>
67,655,097
4
0
null
2021-05-23 00:04:48.477 UTC
8
2022-06-30 20:32:47.317 UTC
2022-02-03 14:19:07.303 UTC
null
3,497,671
null
3,497,671
null
1
29
css|twitter-bootstrap|bootstrap-5
24,131
<p>The reason is <code>form-group</code>, <code>form-row</code>, and <code>form-inline</code> classes have been removed in Bootstrap 5:</p> <blockquote> <p>Breaking change: Dropped form-specific layout classes for our grid system. Use our grid and utilities instead of .form-group, .form-row, or .form-inline.</p> </blockquote> <p><a href="https://getbootstrap.com/docs/5.0/migration/#forms" rel="noreferrer">https://getbootstrap.com/docs/5.0/migration/#forms</a></p> <p>So <a href="https://getbootstrap.com/docs/5.0/layout/grid/" rel="noreferrer">Grid</a> and <a href="https://getbootstrap.com/docs/5.0/layout/utilities/" rel="noreferrer">Utilities</a> are supposed to be used instead.</p> <p>...but if you are looking for a quick solution, here's how these classes were working in Bootstrap 4:</p> <pre class="lang-css prettyprint-override"><code>.form-group { margin-bottom: 1rem; } .form-inline .form-control { display: inline-block; width: auto; vertical-align: middle; } .form-row { display: flex; flex-wrap: wrap; margin-right: -5px; margin-left: -5px; } .form-row &gt; .col { padding-left: 5px; padding-right: 5px; } label { margin-bottom: 0.5rem; } </code></pre>
28,387,142
How to configure Maven installation in Jenkins per individual Slave node?
<h3>Symptom</h3> <p>If I create a Maven job in Jenkins (<em>New Item</em> => <em>Maven project</em>, using the maven plugin) with all defaults and run it, I get this error:</p> <pre><code>Started by user anonymous Building on master in workspace /var/lib/jenkins/jobs/job_name/workspace ERROR: A Maven installation needs to be available for this project to be built.Either your server has no Maven installations defined, or the requested Maven version does not exist. Finished: FAILURE </code></pre> <p>Maven runs perfectly from command line with just <code>mvn</code>.</p> <h3>Unacceptable Workaround</h3> <p>There is a system-wide Jenkins configuration for Maven installation: <em>Manage Jenkins</em> => <em>Configure System</em> => <em>Maven</em> / <em>Maven installations</em>. And if I add Maven installation using this web UI (by providing pre-installed path in <code>MAVEN_HOME</code> as <code>/usr/share/maven</code>), the job runs SUCCESSFULLY.</p> <h3>Question: Why is it global Jenkins config and not Slave-specific one?</h3> <p>The global Jenkins config does not make sense: Maven is run per Slave, not per Jenkins.</p> <p>The zoo of Slaves where Jenkins runs jobs may contain Slaves with various platforms, OSes, environments where different versions of Maven are installed in different locations.</p> <h3>Question: How would I configure Maven installation per Slave node?</h3> <p>Setting environment variables like <a href="https://stackoverflow.com/a/19765881/441652"><code>MAVEN_HOME</code> and <code>M2_HOME</code></a> to the same path for entire system on Slave node didn't work.</p> <h3>Versions</h3> <p>Both Jenkins Master and Slave are Linux hosts. Jenkins version: <code>1.598</code></p>
35,599,130
4
0
null
2015-02-07 20:43:05.61 UTC
3
2020-06-07 12:24:33.27 UTC
2019-09-16 22:02:24.59 UTC
null
32,453
null
441,652
null
1
24
java|maven|jenkins
82,689
<p>Assuming you have Java and Maven installed on your slave:</p> <ol> <li>Go to Manage Jenkins -> Manage Nodes</li> <li>Click configure icon on the node you wish to configure</li> <li>Scroll down to 'Node Properties' and tick the 'Tool Locations' checkbox</li> <li>Fill in the options for Java and Maven.</li> </ol> <p>It should now work (even if you have configured a Maven installation on the master).</p>
56,960,561
Getting HttpRequestExceptions: The response ended prematurely
<p>For some reason, I'm getting a HttpRequestException with the message "The response ended prematurely. I'm creating about 500 tasks that use my RateLimitedHttpClient to make a request to a website so it can scrape it.</p> <p>The exception is being thrown from the line <code>return await response.Content.ReadAsStringAsync();</code>. </p> <p>Is it possible that with 500 tasks, each with ~20 pages to be downloaded and parsed (~11000 total), that I'm exceeding the capability of .Net's HttpClient?</p> <pre><code>public class SECScraper { public event EventHandler&lt;ProgressChangedEventArgs&gt; ProgressChangedEvent; public SECScraper(EPSDownloader downloader, FinanceContext financeContext) { _downloader = downloader; _financeContext = financeContext; } public void Download() { _numDownloaded = 0; var companies = _financeContext.Companies.OrderBy(c =&gt; c.Name); _interval = companies.Count() / 100; var tasks = companies.Select(c =&gt; ScrapeSEC(c.CIK) ).ToList(); Task.WhenAll(tasks); } } public class RateLimitedHttpClient : IHttpClient { public RateLimitedHttpClient(System.Net.Http.HttpClient client) { _client = client; _client.Timeout = TimeSpan.FromMinutes(30); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; } public async Task&lt;string&gt; ReadAsync(string url) { if (!_sw.IsRunning) _sw.Start(); await Delay(); using var response = await _client.GetAsync(url); return await response.Content.ReadAsStringAsync(); } private async Task Delay() { var totalElapsed = GetTimeElapsedSinceLastRequest(); while (totalElapsed &lt; MinTimeBetweenRequests) { await Task.Delay(MinTimeBetweenRequests - totalElapsed); totalElapsed = GetTimeElapsedSinceLastRequest(); }; _timeElapsedOfLastHttpRequest = (int)_sw.Elapsed.TotalMilliseconds; } private int GetTimeElapsedSinceLastRequest() { return (int)_sw.Elapsed.TotalMilliseconds - _timeElapsedOfLastHttpRequest; } private readonly System.Net.Http.HttpClient _client; private readonly Stopwatch _sw = new Stopwatch(); private int _timeElapsedOfLastHttpRequest; private const int MinTimeBetweenRequests = 100; } </code></pre> <p>It appears that I am getting a few HttpRequestExceptions here.</p> <pre><code>System.Net.Http.HttpRequestException: An error occurred while sending the request. ---&gt; System.IO.IOException: The response ended prematurely. at System.Net.Http.HttpConnection.FillAsync() at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed) at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23 at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65 at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19 at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40 System.Net.Http.HttpRequestException: An error occurred while sending the request. ---&gt; System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.. ---&gt; System.Net.Sockets.SocketException (10053): An established connection was aborted by the software in your host machine. --- End of inner exception stack trace --- at System.Net.Security.SslStream.&lt;FillBufferAsync&gt;g__InternalFillBufferAsync|215_0[TReadAdapter](TReadAdapter adap, ValueTask`1 task, Int32 min, Int32 initial) at System.Net.Security.SslStream.ReadAsyncInternal[TReadAdapter](TReadAdapter adapter, Memory`1 buffer) at System.Net.Http.HttpConnection.FillAsync() at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed) at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23 at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65 at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19 at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40 System.Net.Http.HttpRequestException: An error occurred while sending the request. ---&gt; System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.. ---&gt; System.Net.Sockets.SocketException (10053): An established connection was aborted by the software in your host machine. --- End of inner exception stack trace --- at System.Net.Security.SslStream.&lt;WriteSingleChunk&gt;g__CompleteAsync|210_1[TWriteAdapter](ValueTask writeTask, Byte[] bufferToReturn) at System.Net.Security.SslStream.WriteAsyncInternal[TWriteAdapter](TWriteAdapter writeAdapter, ReadOnlyMemory`1 buffer) at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23 at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65 at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19 at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40 System.Net.Http.HttpRequestException: An error occurred while sending the request. ---&gt; System.IO.IOException: The response ended prematurely. at System.Net.Http.HttpConnection.FillAsync() at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed) at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23 at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65 at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19 at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40 System.Net.Http.HttpRequestException: An error occurred while sending the request. ---&gt; System.IO.IOException: The response ended prematurely. &gt; at System.Net.Http.HttpConnection.FillAsync() &gt; at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed) &gt; at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) &gt; --- End of inner exception stack trace --- &gt; at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) &gt; at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) &gt; at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) &gt; at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) &gt; at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) &gt; at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23 &gt; at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65 &gt; at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19 &gt; at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40 &gt; System.Net.Http.HttpRequestException: An error occurred while sending the request. ---&gt; System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.. ---&gt; System.Net.Sockets.SocketException (10053): An established connection was aborted by the software in your host machine. &gt; --- End of inner exception stack trace --- &gt; at System.Net.Security.SslStream.&lt;FillBufferAsync&gt;g__InternalFillBufferAsync|215_0[TReadAdapter](TReadAdapter adap, ValueTask`1 task, Int32 min, Int32 initial) &gt; at System.Net.Security.SslStream.ReadAsyncInternal[TReadAdapter](TReadAdapter adapter, Memory`1 buffer) &gt; at System.Net.Http.HttpConnection.FillAsync() &gt; at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed) &gt; at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) &gt; --- End of inner exception stack trace --- &gt; at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) &gt; at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) &gt; at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) &gt; at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) &gt; at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) &gt; at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23 &gt; at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65 &gt; at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19 &gt; at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40 &gt; System.Net.Http.HttpRequestException: An error occurred while sending the request. ---&gt; System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.. ---&gt; System.Net.Sockets.SocketException (10053): An established connection was aborted by the software in your host machine. &gt; --- End of inner exception stack trace --- &gt; at System.Net.Security.SslStream.&lt;WriteSingleChunk&gt;g__CompleteAsync|210_1[TWriteAdapter](ValueTask writeTask, Byte[] bufferToReturn) &gt; at System.Net.Security.SslStream.WriteAsyncInternal[TWriteAdapter](TWriteAdapter writeAdapter, ReadOnlyMemory`1 buffer) System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---&gt; System.IO.IOException: Authentication failed because the remote party has closed the transport stream. at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.ProcessAuthentication(LazyAsyncResult lazyResult, CancellationToken cancellationToken) at System.Net.Security.SslStream.BeginAuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback asyncCallback, Object asyncState) at System.Net.Security.SslStream.&lt;&gt;c.&lt;AuthenticateAsClientAsync&gt;b__65_0(SslClientAuthenticationOptions arg1, CancellationToken arg2, AsyncCallback callback, Object state) at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl[TArg1,TArg2](Func`5 beginMethod, Func`2 endFunction, Action`1 endAction, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions) at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2](Func`5 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions) at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2](Func`5 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, Object state) at System.Net.Security.SslStream.AuthenticateAsClientAsync(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken) at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask`1.get_Result() at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask`1.get_Result() at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask`1.get_Result() at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask`1.get_Result() at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23 at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65 at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19 at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40 &gt; at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---&gt; System.IO.IOException: Authentication failed because the remote party has closed the transport stream. at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.ProcessAuthentication(LazyAsyncResult lazyResult, CancellationToken cancellationToken) at System.Net.Security.SslStream.BeginAuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback asyncCallback, Object asyncState) at System.Net.Security.SslStream.&lt;&gt;c.&lt;AuthenticateAsClientAsync&gt;b__65_0(SslClientAuthenticationOptions arg1, CancellationToken arg2, AsyncCallback callback, Object state) at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl[TArg1,TArg2](Func`5 beginMethod, Func`2 endFunction, Action`1 endAction, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions) at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2](Func`5 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions) at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2](Func`5 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, Object state) at System.Net.Security.SslStream.AuthenticateAsClientAsync(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken) at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask`1.get_Result() at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask`1.get_Result() at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask`1.get_Result() at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask`1.get_Result() at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23 at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65 at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19 at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40 &gt; --- End of inner exception stack trace --- System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---&gt; System.IO.IOException: Authentication failed because the remote party has closed the transport stream. at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.ProcessAuthentication(LazyAsyncResult lazyResult, CancellationToken cancellationToken) at System.Net.Security.SslStream.BeginAuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback asyncCallback, Object asyncState) at System.Net.Security.SslStream.&lt;&gt;c.&lt;AuthenticateAsClientAsync&gt;b__65_0(SslClientAuthenticationOptions arg1, CancellationToken arg2, AsyncCallback callback, Object state) at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl[TArg1,TArg2](Func`5 beginMethod, Func`2 endFunction, Action`1 endAction, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions) at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2](Func`5 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, Object state, TaskCreationOptions creationOptions) at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2](Func`5 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, Object state) at System.Net.Security.SslStream.AuthenticateAsClientAsync(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken) at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask`1.get_Result() at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask`1.get_Result() at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask`1.get_Result() at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask`1.get_Result() at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at POLib.Http.RateLimitedHttpClient.ReadAsync(String url) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\Http\RateLimitedHttpClient.cs:line 23 at POLib.SECScraper.EPS.EPSDownloader.GetReportLinks(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 65 at POLib.SECScraper.EPS.EPSDownloader.GetEPSData(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\EPS\EPSDownloader.cs:line 19 at POLib.SECScraper.SECScraper.ScrapeSEC(Int32 cik) in C:\Users\Joshua\source\repos\PortfolioOptimizer\POLib\SECScraper\SECScraper.cs:line 40 </code></pre>
56,962,354
4
0
null
2019-07-09 21:11:05.917 UTC
1
2022-08-18 04:52:45.567 UTC
2019-07-09 21:19:12.3 UTC
null
1,296,840
null
1,296,840
null
1
26
c#|.net-core-3.0
50,512
<p>You just need to keep digging. The exception "The response ended prematurely" isn't the root cause. Keep digging into the inner exceptions until you find the last one. You'll find this:</p> <blockquote> <p>System.IO.IOException: Authentication failed because the remote party has closed the transport stream.</p> </blockquote> <p>So it's not about your code. It seems the server you're hitting either can't handle the load, or is intentionally dropping your requests because you're hitting it too hard.</p>
46,312,206
Narrowing a return type from a generic, discriminated union in TypeScript
<p>I have a class method which accepts a single argument as a string and returns an object which has the matching <code>type</code> property. This method is used to narrow a discriminated union type down, and guarantees that the returned object will always be of the particular narrowed type which has the provided <code>type</code> discriminate value.</p> <p>I'm trying to provide a type signature for this method that will correctly narrow the type down from a generic param, but nothing I try narrows it down from the discriminated union without the user explicitly providing the type it should be narrowed down to. That works, but is annoying and feels quite redundant.</p> <p>Hopefully this minimum reproduction makes it clear:</p> <pre class="lang-ts prettyprint-override"><code>interface Action { type: string; } interface ExampleAction extends Action { type: 'Example'; example: true; } interface AnotherAction extends Action { type: 'Another'; another: true; } type MyActions = ExampleAction | AnotherAction; declare class Example&lt;T extends Action&gt; { // THIS IS THE METHOD IN QUESTION doSomething&lt;R extends T&gt;(key: R['type']): R; } const items = new Example&lt;MyActions&gt;(); // result is guaranteed to be an ExampleAction // but it is not inferred as such const result1 = items.doSomething('Example'); // ts: Property 'example' does not exist on type 'AnotherAction' console.log(result1.example); /** * If the dev provides the type more explicitly it narrows it * but I'm hoping it can be inferred instead */ // this works, but is not ideal const result2 = items.doSomething&lt;ExampleAction&gt;('Example'); // this also works, but is not ideal const result3: ExampleAction = items.doSomething('Example'); </code></pre> <p>I also tried getting clever, attempting to build up a "mapped type" dynamically--which is a fairly new feature in TS.</p> <pre class="lang-ts prettyprint-override"><code>declare class Example2&lt;T extends Action&gt; { doSomething&lt;R extends T['type'], TypeMap extends { [K in T['type']]: T }&gt;(key: R): TypeMap[R]; } </code></pre> <p>This suffers from the same outcome: it doesn't narrow the type because in the type map <code>{ [K in T['type']]: T }</code> the value for each computed property, <code>T</code>, is not <em>for each property of the <code>K in</code> iteration</em> but is instead just the same <code>MyActions</code> union. If I require the user provide a predefined mapped type I can use, that would work but this is not an option as in practice it would be a very poor developer experience. (the unions are huge)</p> <hr> <p>This use case might seem weird. I tried to distill my issue into a more consumable form, but my use case is actually regarding Observables. If you're familiar with them, I'm trying to more accurately type the <a href="https://github.com/redux-observable/redux-observable/blob/master/index.d.ts#L28" rel="noreferrer"><code>ofType</code> operator provided by redux-observable</a>. It is basically a shorthand for a <a href="https://github.com/redux-observable/redux-observable/blob/master/src/ActionsObservable.js#L26-L40" rel="noreferrer"><code>filter()</code> on the <code>type</code> property</a>.</p> <p>This is actually super similar to how <code>Observable#filter</code> and <code>Array#filter</code> also narrow the types, but TS seems to figure that out because the predicate callbacks have the <code>value is S</code> return value. It's not clear how I could adapt something similar here.</p>
50,499,316
5
0
null
2017-09-20 02:12:29.77 UTC
8
2018-05-24 00:40:08.503 UTC
2017-09-20 02:21:45.89 UTC
null
1,770,633
null
1,770,633
null
1
31
typescript|typescript-typings|discriminated-union
14,670
<p>As of TypeScript 2.8, you can accomplish this via conditional types.</p> <pre><code>// Narrows a Union type base on N // e.g. NarrowAction&lt;MyActions, 'Example'&gt; would produce ExampleAction type NarrowAction&lt;T, N&gt; = T extends { type: N } ? T : never; interface Action { type: string; } interface ExampleAction extends Action { type: 'Example'; example: true; } interface AnotherAction extends Action { type: 'Another'; another: true; } type MyActions = | ExampleAction | AnotherAction; declare class Example&lt;T extends Action&gt; { doSomething&lt;K extends T['type']&gt;(key: K): NarrowAction&lt;T, K&gt; } const items = new Example&lt;MyActions&gt;(); // Inferred ExampleAction works const result1 = items.doSomething('Example'); </code></pre> <p>NOTE: Credit to @jcalz for the idea of the NarrowAction type from this answer <a href="https://stackoverflow.com/a/50125960/20489">https://stackoverflow.com/a/50125960/20489</a></p>
6,126,061
PBEKeySpec what do the iterationCount and keyLength parameters influence?
<p>Delving into the java encryption and hashing world I see examples of the constructor for the <code>PBEKeySpec</code> class with various values for the <code>iterationCount</code> and the <code>keyLength</code> parameters. Nothing seems to explain what these parameters impact or mean.</p> <p>I am assuming that <code>keyLength</code> is how long the key is so 32 bit encryption would take a value of 32 for the key length, but that assumption feels wrong. My guess for the <code>iterationCount</code> is the number of times each char is encrypted, again not feeling the love on that assumption either.</p> <p>Links to info or an explanation are appreciated.</p>
6,138,384
1
0
null
2011-05-25 14:30:11.323 UTC
7
2019-02-22 14:48:15.443 UTC
2014-07-29 18:17:19.337 UTC
null
589,259
null
97,724
null
1
31
java|encryption|cryptography|pbkdf2|kdf
21,620
<p>The iteration count is the number of times that the password is hashed during the derivation of the symmetric key. The higher number, the more difficult it is to validate a password guess and then derive the correct key. It is used together with the salt which is used to prevent against attacks using rainbow tables. The iteration count should be as high as possible, without slowing your own system down too much. A more generic term for iteration count is <em>work factor</em>.</p> <p>The key length is the length <em>in bits</em> of the derived symmetric key. A DESede key can be either 128 or 192 bits long, including parity bits. An AES key can be 128, 192 or 256 bits long. The problem is that it is not specified by the API which key length (bits / bytes, with- or without parity) is meant; for <code>PBEKeySpec</code> the key size is bits, including the parity bits as shown in this section.</p> <p>The key derivation function normally just outputs &quot;enough&quot; random bits, so that's why you can still specify the required key size.</p> <hr /> <p>Notes:</p> <ul> <li>For more info, please have a look at <a href="https://www.rfc-editor.org/rfc/rfc2898" rel="nofollow noreferrer">the standard</a>, PKCS standards tend to be relatively easy to read.</li> <li>The salt just needs to be unique; generally this is achieved by creating a 64 to 256 bit fully random salt using a secure random number generator (which, for Java means using <code>new SecureRandom()</code> and then <code>nextBytes(int amount)</code>). The salt can be public and stored with the ciphertext or password hash.</li> <li>Specifying any value larger than the output size of the hash (by default this is SHA-1, 160 bits output size) for the key size may fail (for PBKDF1) or result in an additional slowdown (for PBKDF2). Not recommended; just use a hash function such as SHA-256, SHA-512 in the algorithm specification.</li> <li>SHA-1 (sometimes just called SHA as SHA-0 was never used) and <em>even</em> MD5 are still completely secure for this kind of function (as it doesn't rely on collision resistance) but you should still go for a more secure option such as SHA-256 or SHA-512 for new protocols.</li> </ul>
24,496,131
Where is my m2 folder on Mac OS X Mavericks
<p>I cant seem to find the local .m2 folder on Mac OS X mavericks. Ideally it should be at <code>{user.home}/.m2</code> but I cant seem to find it. </p> <p>Should I create it?</p>
33,916,805
9
0
null
2014-06-30 17:58:40.863 UTC
10
2022-04-22 03:58:42.917 UTC
null
null
null
null
919,858
null
1
62
maven-2|osx-mavericks
209,680
<p>If you have used brew to install maven, create .m2 directory and then copy settings.xml in .m2 directory.</p> <pre><code>mkdir ~/.m2 cp /usr/local/Cellar/maven32/3.2.5/libexec/conf/settings.xml ~/.m2 </code></pre> <p>You may need to change the maven version in the path, mine is 3.2.5</p>
37,873,608
How do I detect if a user is already logged in Firebase?
<p>I'm using the firebase node api in my javascript files for Google login. </p> <pre><code>firebase.initializeApp(config); let provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithPopup(provider); </code></pre> <p>This works fine and the user is able to login with his Google credentials. When the user visits the page again, the popup opens again but since he has already logged in, the popup closes without requiring any interaction from the user. Is there any way to check if there is already a logged in user before prompting the popup?</p>
37,886,999
12
0
null
2016-06-17 05:16:30.397 UTC
26
2022-08-24 14:26:15.13 UTC
2022-01-21 14:56:31.793 UTC
null
4,294,399
null
843,241
null
1
144
javascript|firebase|firebase-authentication
177,172
<p><a href="https://firebase.google.com/docs/auth/web/manage-users">https://firebase.google.com/docs/auth/web/manage-users</a></p> <p>You have to add an auth state change observer.</p> <pre><code>firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. } else { // No user is signed in. } }); </code></pre>
28,531,809
I want to select the greater of the two values from two columns in R
<p>My data looks like:</p> <pre><code>head(myframe) id fwt_r fwt_l [1,] 101 72 52 [2,] 102 61 48 [3,] 103 46 49 [4,] 104 48 41 [5,] 105 51 42 [6,] 106 49 35 </code></pre> <p>I want to select the greater of the two values among fwt_r and fwt_l. I want the output like: </p> <pre><code>72 61 49 48 51 49 </code></pre> <p>Kindly help me out. Thanks!</p>
28,531,874
1
0
null
2015-02-15 22:14:03.52 UTC
2
2020-12-27 20:13:19.52 UTC
2015-02-15 22:33:07.78 UTC
null
496,803
null
4,567,022
null
1
13
r
40,485
<p>You are looking for the 'pmax' function</p> <p>Just run this:</p> <pre><code>pmax(myframe$fwt_r, myframe$fwt_l) </code></pre> <p>pmax means 'parallel maxima' (or vectorized)</p>
28,517,979
Pygame font error
<p>So I decided to start making a game and I was testing it a bit and then I got this error: </p> <pre><code>Traceback (most recent call last): File "TheAviGame.py", line 15, in &lt;module&gt; font = pygame.font.Font(None,25) pygame.error: font not initialized </code></pre> <p>I have no idea what I have done wrong so far... Code:</p> <pre><code>#!/usr/bin/python import pygame blue = (25,25,112) black = (0,0,0) red = (255,0,0) white = (255,255,255) groundcolor = (139,69,19) gameDisplay = pygame.display.set_mode((1336,768)) pygame.display.set_caption("TheAviGame") direction = 'none' clock = pygame.time.Clock() img = pygame.image.load('player.bmp') imgx = 1000 imgy = 100 font = pygame.font.Font(None,25) def mts(text, textcolor, x, y): text = font.render(text, True, textcolor) gamedisplay.blit(text, [x,y]) def gameloop(): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.pygame == pygame.KEYDOWN: if event.key == pygame.RIGHT: imgx += 10 gameDisplay.fill(blue) pygame.display.update() clock.tick(15) gameloop() </code></pre>
28,518,075
3
0
null
2015-02-14 17:03:47.58 UTC
4
2019-05-25 04:18:22.61 UTC
2015-02-14 17:08:46.71 UTC
null
386,856
null
4,533,588
null
1
16
python|fonts|pygame
45,898
<p>You never initialized <code>pygame</code> and <code>pygame.font</code> after importing:</p> <pre><code># imports pygame.init() # now use display and fonts </code></pre>
18,307,131
How to create HTTPS tornado server
<p>Please help me to create HTTPS tornado server My current code Python3 doesn't work</p> <pre><code>import os, socket, ssl, pprint, tornado.ioloop, tornado.web, tornado.httpserver from tornado.tcpserver import TCPServer class getToken(tornado.web.RequestHandler): def get(self): self.write("hello") application = tornado.web.Application([ (r'/', getToken), ]) # implementation for SSL http_server = tornado.httpserver.HTTPServer(application) TCPServer(ssl_options={ "certfile": os.path.join("/var/pyTest/keys/", "ca.csr"), "keyfile": os.path.join("/var/pyTest/keys/", "ca.key"), }) if __name__ == '__main__': #http_server.listen(8888) http_server = TCPServer() http_server.listen(443) tornado.ioloop.IOLoop.instance().start() </code></pre> <p>HTTPS is very important for me, please help</p>
18,307,308
1
0
null
2013-08-19 05:50:52.487 UTC
13
2018-04-23 18:18:18.33 UTC
2018-04-23 18:18:18.33 UTC
null
667,301
null
2,149,406
null
1
27
python|python-3.x|ssl|https|tornado
31,233
<p>No need to use <code>TCPServer</code>.</p> <p>Try following:</p> <pre><code>import tornado.httpserver import tornado.ioloop import tornado.web class getToken(tornado.web.RequestHandler): def get(self): self.write("hello") application = tornado.web.Application([ (r'/', getToken), ]) if __name__ == '__main__': http_server = tornado.httpserver.HTTPServer(application, ssl_options={ "certfile": "/var/pyTest/keys/ca.csr", "keyfile": "/var/pyTest/keys/ca.key", }) http_server.listen(443) tornado.ioloop.IOLoop.instance().start() </code></pre>
38,786,014
How to compile executable for Windows with GCC with Linux Subsystem?
<p>Windows 10 Anniversary Update includes the Linux Subsystem for Ubuntu. I installed gcc with <code>sudo apt-get install gcc</code>.</p> <p>I wrote some simple C code for testing purposes:</p> <pre><code>#include &lt;stdio.h&gt; int main(void){ printf("Hello\n"); return 0; } </code></pre> <p>And compiled it with <code>gcc -c main.c</code> but the execute (Linux only) <code>main.o</code> is generated. If I run it <code>./main.o</code>, it displays <code>Hello</code>.</p> <p>My question is, how can I compile <code>main.c</code> so that Windows can run it? Basically, how do you generate a <code>*.exe</code> file with GCC in Linux Subsystem ?</p>
38,788,588
2
13
null
2016-08-05 09:35:25.81 UTC
46
2020-07-12 03:21:10.567 UTC
2016-08-06 02:13:54.013 UTC
null
3,980,929
null
5,526,354
null
1
74
c|bash|gcc
116,239
<p>Linux Subsystem works as a Linux-computer. You can only run Linux executables inside it and default <code>gcc</code> creates Linux executables.</p> <p>To create Windows executables, you need to install mingw cross-compiler:</p> <pre><code>sudo apt-get install mingw-w64 </code></pre> <p>Then you can create 32-bit Windows executable with:</p> <pre><code>i686-w64-mingw32-gcc -o main32.exe main.c </code></pre> <p>And 64-bit Windows executable with:</p> <pre><code>x86_64-w64-mingw32-gcc -o main64.exe main.c </code></pre> <p>Note that these Windows executables will not work inside Linux Subsystem, only outside of it.</p>
24,655,684
Spring Boot default H2 jdbc connection (and H2 console)
<p>I am simply trying to see the H2 database content for an embedded H2 database which spring-boot creates when I don't specify anything in my <code>application.properties</code> and start with mvn spring:run. I can see hibernate JPA creating the tables but if I try to access the h2 console at the URL below the database has no tables.</p> <pre class="lang-none prettyprint-override"><code>http://localhost:8080/console/ </code></pre> <p>I see suggestions like this one: <a href="https://stackoverflow.com/questions/17803718/view-content-of-embedded-h2-database-started-by-spring">View content of embedded H2 database started by Spring</a></p> <p>But I don't know where to put the suggested XML in spring-boot and even if I did, I don't want the <code>h2console</code> to be available anymore when an external database is configured so it is more likely that I need to handle this with some kind of conditional code (or maybe just allow spring to automatically handle it in the most ideal case where I only include H2 when a maven profile is activated).</p> <p>Does anyone have some sample code showing how to get the H2 console working in boot (and also the way to find out what the jdbc connection string that spring is using is)?</p>
24,727,653
14
0
null
2014-07-09 13:57:18.22 UTC
55
2020-11-02 07:18:47.587 UTC
2020-10-30 08:51:58.413 UTC
null
-1
null
1,519,434
null
1
123
java|spring|spring-boot|h2|spring-jdbc
278,984
<p>This is how I got the H2 console working in spring-boot with H2. I am not sure if this is right but since no one else has offered a solution then I am going to suggest this is the best way to do it.</p> <p>In my case, I chose a specific name for the database so that I would have something to enter when starting the H2 console (in this case, "AZ"). I think all of these are required though it seems like leaving out the spring.jpa.database-platform does not hurt anything. </p> <p>In application.properties:</p> <pre><code>spring.datasource.url=jdbc:h2:mem:AZ;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect </code></pre> <p>In Application.java (or some configuration):</p> <pre><code>@Bean public ServletRegistrationBean h2servletRegistration() { ServletRegistrationBean registration = new ServletRegistrationBean(new WebServlet()); registration.addUrlMappings("/console/*"); return registration; } </code></pre> <p>Then you can access the H2 console at {server}/console/. Enter this as the JDBC URL: jdbc:h2:mem:AZ</p>
3,114,786
Python library to extract 'epub' information
<p>I'm trying to create a epub uploader to iBook in python. I need a python lib to extract book information. Before implementing this by myself I wonder if anyone know a already made python lib that does it.</p>
3,114,929
4
3
null
2010-06-25 00:12:10.347 UTC
18
2022-07-28 08:33:26.273 UTC
2013-12-05 07:22:13.663 UTC
null
881,229
null
335,918
null
1
26
python|epub|ibooks
24,154
<p>An .epub file is a zip-encoded file containing a META-INF directory, which contains a file named container.xml, which points to another file usually named Content.opf, which indexes all the other files which make up the e-book (summary based on <a href="http://www.jedisaber.com/eBooks/tutorial.asp" rel="nofollow noreferrer">http://www.jedisaber.com/eBooks/tutorial.asp</a> ; full spec at <a href="http://www.idpf.org/2007/opf/opf2.0/download/" rel="nofollow noreferrer">http://www.idpf.org/2007/opf/opf2.0/download/</a> )</p> <p>The following Python code will extract the basic meta-information from an .epub file and return it as a dict.</p> <pre class="lang-py prettyprint-override"><code>import zipfile from lxml import etree def epub_info(fname): def xpath(element, path): return element.xpath( path, namespaces={ &quot;n&quot;: &quot;urn:oasis:names:tc:opendocument:xmlns:container&quot;, &quot;pkg&quot;: &quot;http://www.idpf.org/2007/opf&quot;, &quot;dc&quot;: &quot;http://purl.org/dc/elements/1.1/&quot;, }, )[0] # prepare to read from the .epub file zip_content = zipfile.ZipFile(fname) # find the contents metafile cfname = xpath( etree.fromstring(zip_content.read(&quot;META-INF/container.xml&quot;)), &quot;n:rootfiles/n:rootfile/@full-path&quot;, ) # grab the metadata block from the contents metafile metadata = xpath( etree.fromstring(zip_content.read(cfname)), &quot;/pkg:package/pkg:metadata&quot; ) # repackage the data return { s: xpath(metadata, f&quot;dc:{s}/text()&quot;) for s in (&quot;title&quot;, &quot;language&quot;, &quot;creator&quot;, &quot;date&quot;, &quot;identifier&quot;) } </code></pre> <p>Sample output:</p> <pre><code>{ 'date': '2009-12-26T17:03:31', 'identifier': '25f96ff0-7004-4bb0-b1f2-d511ca4b2756', 'creator': 'John Grisham', 'language': 'UND', 'title': 'Ford County' } </code></pre>
3,033,410
How to set a property of a C# 4 dynamic object when you have the name in another variable
<p>I'm looking for a way to modify properties on a <code>dynamic</code> C# 4.0 object with the name of the property known only at runtime.</p> <p>Is there a way to do something like (<code>ExpandoObject</code> is just used as an example, this could be any class that implements <code>IDynamicMetaObjectProvider</code>):</p> <pre><code>string key = "TestKey"; dynamic e = new ExpandoObject(); e[key] = "value"; </code></pre> <p>Which would be equivalent to:</p> <pre><code>dynamic e = new ExpandoObject(); e.TestKey = "value"; </code></pre> <p>Or is the only way forward reflection?</p>
3,033,430
4
3
null
2010-06-13 18:33:22.603 UTC
8
2022-02-17 19:24:38.81 UTC
null
null
null
null
5,777
null
1
50
c#|.net|reflection|dynamic
46,339
<p>Not very easily, no. Reflection doesn't work, since it assumes a regular type model, which is <em>not</em> the full range of <code>dynamic</code>. If you are actually just talking to regular objects, then just use reflection here. Otherwise, I expect you may want to reverse-engineer the code that the compiler emits for a basic assignment, and tweak it to have a flexibly member-name. I'll be honest, though: this isn't an attractive option; a simple:</p> <pre><code>dynamic foo = ... foo.Bar = "abc"; </code></pre> <p>translates to:</p> <pre><code>if (&lt;Main&gt;o__SiteContainer0.&lt;&gt;p__Site1 == null) { &lt;Main&gt;o__SiteContainer0.&lt;&gt;p__Site1 = CallSite&lt;Func&lt;CallSite, object, string, object&gt;&gt;.Create(Binder.SetMember(CSharpBinderFlags.None, "Bar", typeof(Program), new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant | CSharpArgumentInfoFlags.UseCompileTimeType, null) })); } &lt;Main&gt;o__SiteContainer0.&lt;&gt;p__Site1.Target(&lt;Main&gt;o__SiteContainer0.&lt;&gt;p__Site1, foo, "abc"); </code></pre> <hr> <p>If you want an approach that works for both dynamic and non-dynamic objects: <a href="http://marcgravell.blogspot.com/2012/01/playing-with-your-member.html" rel="noreferrer">FastMember</a> is handy for this, and works at either the type or object level:</p> <pre><code>// could be static or DLR var wrapped = ObjectAccessor.Create(obj); string propName = // something known only at runtime Console.WriteLine(wrapped[propName]); </code></pre> <p>available on Nuget, and heavily optimised for both dynamic and non-dynamic scenarios.</p>
46,580,253
collect_list by preserving order based on another variable
<p>I am trying to create a new column of lists in Pyspark using a groupby aggregation on existing set of columns. An example input data frame is provided below:</p> <pre><code>------------------------ id | date | value ------------------------ 1 |2014-01-03 | 10 1 |2014-01-04 | 5 1 |2014-01-05 | 15 1 |2014-01-06 | 20 2 |2014-02-10 | 100 2 |2014-03-11 | 500 2 |2014-04-15 | 1500 </code></pre> <p>The expected output is:</p> <pre><code>id | value_list ------------------------ 1 | [10, 5, 15, 20] 2 | [100, 500, 1500] </code></pre> <p>The values within a list are sorted by the date.</p> <p>I tried using collect_list as follows:</p> <pre><code>from pyspark.sql import functions as F ordered_df = input_df.orderBy(['id','date'],ascending = True) grouped_df = ordered_df.groupby("id").agg(F.collect_list("value")) </code></pre> <p>But collect_list doesn't guarantee order even if I sort the input data frame by date before aggregation.</p> <p>Could someone help on how to do aggregation by preserving the order based on a second (date) variable?</p>
46,584,296
10
0
null
2017-10-05 07:34:03.737 UTC
42
2022-03-14 19:39:06.95 UTC
2017-10-05 11:16:01.693 UTC
null
4,964,651
null
1,002,903
null
1
77
python|apache-spark|pyspark
65,236
<p>If you collect both dates and values as a list, you can sort the resulting column according to date using and <code>udf</code>, and then keep only the values in the result.</p> <pre><code>import operator import pyspark.sql.functions as F # create list column grouped_df = input_df.groupby("id") \ .agg(F.collect_list(F.struct("date", "value")) \ .alias("list_col")) # define udf def sorter(l): res = sorted(l, key=operator.itemgetter(0)) return [item[1] for item in res] sort_udf = F.udf(sorter) # test grouped_df.select("id", sort_udf("list_col") \ .alias("sorted_list")) \ .show(truncate = False) +---+----------------+ |id |sorted_list | +---+----------------+ |1 |[10, 5, 15, 20] | |2 |[100, 500, 1500]| +---+----------------+ </code></pre>
52,537,638
How to resolve NoClassDefFoundError: Failed resolution of: Landroid/view/View$OnUnhandledKeyEventListener;
<p>I have upgraded my Android Studio to</p> <pre><code>Android Studio 3.2 Build #AI-181.5540.7.32.5014246, built on September 17, 2018 JRE: 1.8.0_152-release-1136-b06 x86_64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o Mac OS X 10.11.6 </code></pre> <p>I create a new Project using Empty Activity template</p> <pre><code>Sync Gradle Clean Build Run </code></pre> <p>my application logcat shows this exception on startup</p> <pre><code>2018-09-27 13:51:41.116 22090-22090/? I/zygote64: Rejecting re-init on previously-failed class java.lang.Class&lt;android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper&gt;: java.lang.NoClassDefFoundError: Failed resolution of: Landroid/view/View$OnUnhandledKeyEventListener; 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void android.support.v4.view.ViewCompat.setBackground(android.view.View, android.graphics.drawable.Drawable) (ViewCompat.java:2341) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void android.support.v7.widget.ActionBarContainer.&lt;init&gt;(android.content.Context, android.util.AttributeSet) (ActionBarContainer.java:62) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at java.lang.Object java.lang.reflect.Constructor.newInstance0(java.lang.Object[]) (Constructor.java:-2) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at java.lang.Object java.lang.reflect.Constructor.newInstance(java.lang.Object[]) (Constructor.java:334) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at android.view.View android.view.LayoutInflater.createView(java.lang.String, java.lang.String, android.util.AttributeSet) (LayoutInflater.java:647) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at android.view.View android.view.LayoutInflater.createViewFromTag(android.view.View, java.lang.String, android.content.Context, android.util.AttributeSet, boolean) (LayoutInflater.java:790) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at android.view.View android.view.LayoutInflater.createViewFromTag(android.view.View, java.lang.String, android.content.Context, android.util.AttributeSet) (LayoutInflater.java:730) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void android.view.LayoutInflater.rInflate(org.xmlpull.v1.XmlPullParser, android.view.View, android.content.Context, android.util.AttributeSet, boolean) (LayoutInflater.java:863) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void android.view.LayoutInflater.rInflateChildren(org.xmlpull.v1.XmlPullParser, android.view.View, android.util.AttributeSet, boolean) (LayoutInflater.java:824) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at android.view.View android.view.LayoutInflater.inflate(org.xmlpull.v1.XmlPullParser, android.view.ViewGroup, boolean) (LayoutInflater.java:515) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at android.view.View android.view.LayoutInflater.inflate(int, android.view.ViewGroup, boolean) (LayoutInflater.java:423) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at android.view.View android.view.LayoutInflater.inflate(int, android.view.ViewGroup) (LayoutInflater.java:374) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at android.view.ViewGroup android.support.v7.app.AppCompatDelegateImpl.createSubDecor() (AppCompatDelegateImpl.java:607) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void android.support.v7.app.AppCompatDelegateImpl.ensureSubDecor() (AppCompatDelegateImpl.java:518) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void android.support.v7.app.AppCompatDelegateImpl.setContentView(int) (AppCompatDelegateImpl.java:466) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void android.support.v7.app.AppCompatActivity.setContentView(int) (AppCompatActivity.java:140) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void com.manacle.secondmanacle.MainActivity.onCreate(android.os.Bundle) (MainActivity.java:11) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void android.app.Activity.performCreate(android.os.Bundle, android.os.PersistableBundle) (Activity.java:7009) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void android.app.Activity.performCreate(android.os.Bundle) (Activity.java:7000) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void android.app.Instrumentation.callActivityOnCreate(android.app.Activity, android.os.Bundle) (Instrumentation.java:1214) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at android.app.Activity android.app.ActivityThread.performLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent) (ActivityThread.java:2731) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void android.app.ActivityThread.handleLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:2856) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void android.app.ActivityThread.-wrap11(android.app.ActivityThread, android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:-1) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1589) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:106) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void android.os.Looper.loop() (Looper.java:164) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6494) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run() (RuntimeInit.java:438) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:807) 2018-09-27 13:51:41.116 22090-22090/? I/zygote64: Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.View$OnUnhandledKeyEventListener" on path: DexPathList[[zip file "/data/app/com.manacle.secondmanacle-6Ra5peoMwc4HH30iTlEXCg==/base.apk"],nativeLibraryDirectories=[/data/app/com.manacle.secondmanacle-6Ra5peoMwc4HH30iTlEXCg==/lib/arm64, /system/lib64, /vendor/lib64]] </code></pre> <p>I have made no changes to the template app generated by Android Studio.</p> <p>Why doesnt the generate template app start cleanly?</p> <p>I tried migrating to androidX, however the issue remains exactly the same.</p> <p>Why cant Android Studio generate a "clean" template application?</p> <p>My gradle files resemble this:-</p> <pre><code>buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.2.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } </code></pre> <p>====</p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.manacle.secondmanacle" minSdkVersion 21 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.0.0' implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha2' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.1.0-alpha4' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4' } </code></pre>
52,538,255
10
0
null
2018-09-27 13:01:55.64 UTC
22
2021-06-06 12:18:28.51 UTC
null
null
null
null
423,199
null
1
115
android|android-studio
89,330
<p>Sometimes after an upgrade, you need to invalidate and clear cache. </p> <p><a href="https://i.stack.imgur.com/jF5No.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jF5No.png" alt="enter image description here"></a></p> <p>There are some known issues in 3.2 so also ensure you are not on Kotlin tools org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.70</p> <p>as that causes freeze issues as well. If that doesn't work, remove your google plugin lines and support libraries, sync and add them again and sync. Sometimes the cache directories just get out of whack.</p>
49,030,977
Angular 5, HTML, boolean on checkbox is checked
<p>Angular 5, Typescript 2.7.1</p> <p>I can't seem to get the checkbox to be checked when returning a boolean, I've tried, <code>item.check</code> returns either true or false.</p> <pre><code>&lt;tr class="even" *ngFor="let item of rows"&gt; &lt;input value="{{item.check}}" type="checkbox" checked="item.check"&gt; </code></pre> <p>The checkbox is always checked when checked is written inside input. And it does not get unchecked when <code>checked="false"</code>.</p> <p>Is there a better way to do it with Angular features instead? like ngModel or ngIf???</p> <p>Solution</p> <pre><code>&lt;input type="checkbox" [checked]="item.check == 'true'"&gt; </code></pre>
49,032,410
6
1
null
2018-02-28 13:41:23.77 UTC
16
2021-06-11 12:59:34.733 UTC
2018-12-11 18:26:56.75 UTC
null
4,719,114
null
9,410,274
null
1
100
html|angular|typescript
319,556
<p>try:</p> <pre><code>[checked]="item.checked" </code></pre> <p>check out: <a href="https://scotch.io/tutorials/how-to-deal-with-different-form-controls-in-angular-2" rel="noreferrer">How to Deal with Different Form Controls in Angular</a></p>
38,417,984
android spinner dropdown checkbox
<p>I have <code>Spinner</code> like this :</p> <pre><code>&lt;Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/spinner1" android:background="@drawable/spinner_bg" android:popupBackground="@drawable/spinner_bg"/&gt; </code></pre> <p>this is <strong>spinner_bg.xml</strong> :</p> <p></p> <pre><code>&lt;item&gt; &lt;layer-list&gt; &lt;item&gt; &lt;shape&gt; &lt;gradient android:startColor="#ffffff" android:centerColor="#111111" android:endColor="#000000" android:angle="-90" /&gt; &lt;stroke android:width="2dp" android:color="#ffffff" /&gt; &lt;corners android:radius="2dp" /&gt; &lt;padding android:left="10dp" android:right="10dp"/&gt; &lt;/shape&gt; &lt;/item&gt; &lt;item &gt; &lt;bitmap android:gravity="right" android:src="@android:drawable/arrow_down_float" /&gt; &lt;/item&gt; &lt;/layer-list&gt; &lt;/item&gt; </code></pre> <p></p> <p>this is my code to Custom spinner :</p> <pre><code>ArrayAdapter&lt;ClassId&gt; adapter = new ArrayAdapter&lt;ClassId&gt;(getActivity(), R.layout.list_id, idList); adapter.setDropDownViewResource(R.layout.list_id_select); </code></pre> <p>this is layout of <strong>list_id.xml</strong> :</p> <pre><code>&lt;TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAllCaps="true" android:singleLine="true" android:ellipsize="end" android:textColor="#ff0004" android:textSize="14sp" android:paddingTop="10dp" android:paddingBottom="10dp"/&gt; </code></pre> <p>this is layout of <strong>list_id_select.xml</strong> :</p> <pre><code>&lt;CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAllCaps="true" android:singleLine="true" android:ellipsize="end" android:textColor="#0004ff" android:textSize="14sp" android:checked="true" android:checkMark="@drawable/custom_checkbox" android:paddingTop="10dp" android:paddingBottom="10dp"/&gt; </code></pre> <p>and this is <strong>custom_checkbox.xml</strong> :</p> <pre><code>&lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:state_checked="true" android:drawable="@android:drawable/checkbox_on_background" /&gt; &lt;item android:state_pressed="true" android:drawable="@android:drawable/checkbox_on_background" /&gt; &lt;item android:drawable="@android:drawable/checkbox_off_background" /&gt; </code></pre> <p></p> <p>this is my result when dropdown of spinner show : _________________________________________________<br> __________________________checkbox_______________<br> ____text_________________________________________<br></p> <p>that mean text and checkbox not in line (checkbox higher than text).<br> how to fix it?</p>
38,418,249
2
0
null
2016-07-17 04:43:37.407 UTC
13
2018-12-12 14:06:43.747 UTC
2016-07-17 05:52:13.39 UTC
null
6,343,685
null
6,546,433
null
1
19
android|drop-down-menu|textview|android-spinner|android-checkbox
37,269
<p>For that you have to Create <code>Custom Adapter</code> and set <code>TextView</code> and <code>CheckBox</code> inside that below way.</p> <p>Define <code>Spinner</code> in xml </p> <pre><code>&lt;Spinner android:id="@+id/spinner" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="10dp" /&gt; </code></pre> <p>Create <code>spinner_item.xml</code> file in <code>layout</code> folder.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"&gt; &lt;TextView android:id="@+id/text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:text="text" android:textAlignment="gravity" /&gt; &lt;CheckBox android:id="@+id/checkbox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>Now create <code>StateVO.java</code> class that can contain the <code>TextView</code> and <code>CheckBox</code> value.</p> <pre><code>public class StateVO { private String title; private boolean selected; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } } </code></pre> <p>Now in your <code>Activity</code> inititlize the <code>Spinner</code> and set <code>CustomAdapter</code> below way.</p> <pre><code> final String[] select_qualification = { "Select Qualification", "10th / Below", "12th", "Diploma", "UG", "PG", "Phd"}; Spinner spinner = (Spinner) findViewById(R.id.spinner); ArrayList&lt;StateVO&gt; listVOs = new ArrayList&lt;&gt;(); for (int i = 0; i &lt; select_qualification.length; i++) { StateVO stateVO = new StateVO(); stateVO.setTitle(select_qualification[i]); stateVO.setSelected(false); listVOs.add(stateVO); } MyAdapter myAdapter = new MyAdapter(Main2Activity.this, 0, listVOs); spinner.setAdapter(myAdapter); </code></pre> <p>And Finally Create <code>CustomAdapter</code> class like below way.</p> <p><strong>MyAdapter.java</strong></p> <pre><code>public class MyAdapter extends ArrayAdapter&lt;StateVO&gt; { private Context mContext; private ArrayList&lt;StateVO&gt; listState; private MyAdapter myAdapter; private boolean isFromView = false; public MyAdapter(Context context, int resource, List&lt;StateVO&gt; objects) { super(context, resource, objects); this.mContext = context; this.listState = (ArrayList&lt;StateVO&gt;) objects; this.myAdapter = this; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } @Override public View getView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } public View getCustomView(final int position, View convertView, ViewGroup parent) { final ViewHolder holder; if (convertView == null) { LayoutInflater layoutInflator = LayoutInflater.from(mContext); convertView = layoutInflator.inflate(R.layout.spinner_item, null); holder = new ViewHolder(); holder.mTextView = (TextView) convertView .findViewById(R.id.text); holder.mCheckBox = (CheckBox) convertView .findViewById(R.id.checkbox); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.mTextView.setText(listState.get(position).getTitle()); // To check weather checked event fire from getview() or user input isFromView = true; holder.mCheckBox.setChecked(listState.get(position).isSelected()); isFromView = false; if ((position == 0)) { holder.mCheckBox.setVisibility(View.INVISIBLE); } else { holder.mCheckBox.setVisibility(View.VISIBLE); } holder.mCheckBox.setTag(position); holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int getPosition = (Integer) buttonView.getTag(); if (!isFromView) { listState.get(position).setSelected(isChecked); } } }); return convertView; } private class ViewHolder { private TextView mTextView; private CheckBox mCheckBox; } } </code></pre> <p><strong>Output :</strong> </p> <p><a href="https://i.stack.imgur.com/OtIHN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OtIHN.png" alt="enter image description here"></a></p>
38,273,353
How to repeat individual characters in strings in Python
<p>I know that </p> <pre><code>"123abc" * 2 </code></pre> <p>evaluates as <code>"123abc123abc"</code>, but is there an easy way to repeat individual letters N times, e.g. convert <code>"123abc"</code> to <code>"112233aabbcc"</code> or <code>"111222333aaabbbccc"</code>?</p>
38,273,369
10
1
null
2016-07-08 18:36:47.503 UTC
9
2020-11-09 05:26:54.117 UTC
2016-07-08 18:47:57.787 UTC
null
3,254,859
null
44,330
null
1
36
python|string
91,413
<p>What about:</p> <pre><code>&gt;&gt;&gt; s = '123abc' &gt;&gt;&gt; n = 3 &gt;&gt;&gt; ''.join([char*n for char in s]) '111222333aaabbbccc' &gt;&gt;&gt; </code></pre> <p>(changed to a list comp from a generator expression as using a list comp inside join is <a href="https://stackoverflow.com/a/9061024/2302482">faster</a>)</p>
1,298,122
Where are methods stored in memory?
<p>I learned that class fields are stored in the heap, but where are methods stored? In the heap or somewhere else? are they inline?</p>
1,298,133
2
0
null
2009-08-19 06:32:34.533 UTC
19
2021-12-07 02:38:28.37 UTC
2009-08-19 06:34:44.653 UTC
null
3,957
null
85,606
null
1
32
c#|.net|memory
9,925
<p>Methods are stored somewhere else in the memory. Notice that methods are per-class, not per-instance. So typically, the number of methods doesn't change over the run-time of a program (there are exceptions). In traditional models, the place where the methods live is called the "code segment". In .net, it's more difficult: the methods originally live in the assembly, and get mapped into the process memory. There, the just-in-time compiler creates a second copy of some methods in native code; this copy gets executed. The JIT code may get created and deleted several times during the runtime, so it is practical to view it also as living "in Heap".</p>
816,211
WCF: What is a ServiceHost?
<p>As I'm currently learning to use WCF Services, I am constantly encountering tutorials on the internet which mention using a <code>ServiceHost</code> when using a WCF Service. </p> <p><strong>What exactly is this <code>ServiceHost</code> ?</strong></p> <hr> <p>In my current project I am using a WCF Service and having a reference to it from my app and whenever I want to consume it from my app I just instantiate its <code>ServiceClient</code> like such:</p> <pre><code>new MusicRepo_DBAccess_ServiceClient(new InstanceContext(instanceContext), customBinding, endpointAddress); </code></pre> <p>And then access my web methods (<code>OperationContract</code>s) from that instance (obviously opening it before consuming the method and closing it afterwards with <code>Open</code> and <code>Close</code>)</p> <p>My WCF service is host in my IIS and I just access the <code>.svc</code> from my app to instantiate the <code>ServiceClient</code>.</p> <p>So why and where is <code>ServiceHost</code> used?</p>
816,250
2
0
null
2009-05-03 03:09:36.817 UTC
7
2016-09-17 11:26:51.43 UTC
null
null
null
null
44,084
null
1
39
c#|wcf|web-services|servicehost
46,484
<p>A ServiceHost basically provides you everything you need to host a WCF service in a non-IIS or WAS setting. A common place for a ServiceHost would be in a console app or Windows service. See the example code from MSDN for <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost.aspx" rel="noreferrer">how to setup a ServiceHost in a console app</a>.</p>
248,545
WPF Trigger for IsSelected in a DataTemplate for ListBox items
<p>I have a listbox, and I have the following ItemTemplate for it:</p> <pre><code>&lt;DataTemplate x:Key="ScenarioItemTemplate"&gt; &lt;Border Margin="5,0,5,0" Background="#FF3C3B3B" BorderBrush="#FF797878" BorderThickness="2" CornerRadius="5"&gt; &lt;DockPanel&gt; &lt;DockPanel DockPanel.Dock="Top" Margin="0,2,0,0"&gt; &lt;Button HorizontalAlignment="Left" DockPanel.Dock="Left" FontWeight="Heavy" Foreground="White" /&gt; &lt;Label Content="{Binding Path=Name}" DockPanel.Dock="Left" FontWeight="Heavy" Foreground="white" /&gt; &lt;Label HorizontalAlignment="Right" Background="#FF3C3B3B" Content="X" DockPanel.Dock="Left" FontWeight="Heavy" Foreground="White" /&gt; &lt;/DockPanel&gt; &lt;ContentControl Name="designerContent" Visibility="Collapsed" MinHeight="100" Margin="2,0,2,2" Content="{Binding Path=DesignerInstance}" Background="#FF999898"&gt; &lt;/ContentControl&gt; &lt;/DockPanel&gt; &lt;/Border&gt; &lt;/DataTemplate&gt; </code></pre> <p>As you can see the ContentControl has Visibility set to collapsed.</p> <p>I need to define a trigger that causes the Visibility to be set to "Visible"</p> <p>when the ListItem is selected, but I can't figure it out.</p> <p>Any ideas? </p> <p>UPDATE: Of course I could simply duplicate the DataTemplate and add triggers to the ListBox in question to use either one or the other, but I want to prevent duplicating this code.</p>
248,581
2
0
null
2008-10-29 21:44:26.51 UTC
22
2015-02-23 18:48:44.273 UTC
2015-02-23 18:48:44.273 UTC
null
64,046
TimothyP
28,149
null
1
60
wpf|triggers|listbox|itemtemplate|event-triggers
97,769
<p>You can style your ContentControl such that a trigger fires when its container (the ListBoxItem) becomes selected:</p> <pre><code>&lt;ContentControl x:Name="designerContent" MinHeight="100" Margin="2,0,2,2" Content="{Binding Path=DesignerInstance}" Background="#FF999898"&gt; &lt;ContentControl.Style&gt; &lt;Style TargetType="{x:Type ContentControl}"&gt; &lt;Setter Property="Visibility" Value="Collapsed"/&gt; &lt;Style.Triggers&gt; &lt;DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Value="True"&gt; &lt;Setter Property="Visibility" Value="Visible"/&gt; &lt;/DataTrigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/ContentControl.Style&gt; &lt;/ContentControl&gt; </code></pre> <p>Alternatively, I think you can add the trigger to the template itself and reference the control by name. I don't know this technique well enough to type it from memory and assume it'll work, but it's something like this:</p> <pre><code>&lt;DataTemplate x:Key="ScenarioItemTemplate"&gt; &lt;DataTemplate.Triggers&gt; &lt;DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Value="True"&gt; &lt;Setter TargetName="designerContent" Property="Visibility" Value="Visible"/&gt; &lt;/DataTrigger&gt; &lt;/DataTemplate.Triggers&gt; ... &lt;/DataTemplate&gt; </code></pre>
343,557
How to distinguish command-line and web-server invocation?
<p>Is there a way to distinguish if a script was invoked from the command line or by the web server? </p> <p>(<strong>See <a href="https://stackoverflow.com/questions/173851/what-is-the-canonical-way-to-determine-commandline-vs-http-execution-of-a-php-s">What is the canonical way to determine commandline vs. http execution of a PHP script?</a> for best answer</strong> and more detailed discussion - didn't find that one before posting)</p> <hr> <p>I have a (non-production) server with Apache 2.2.10 and PHP 5.2.6. On it, in a web-accessible directory is my PHP script, <code>maintenance_tasks.php</code>. I would like to invoke this script from the command line or through a HTTP request (by opening in a browser). Is there some variable that allows me to reliably determine how script is invoked?</p> <p>(I already tackled the issues of different views for each type of invocation and HTTP response timeout, just looking for a way of telling the two invocation types apart)</p> <p>I'll be trying different things and add my findings below.</p> <p><strong>Duplicate:</strong> <a href="https://stackoverflow.com/questions/173851/what-is-the-canonical-way-to-determine-commandline-vs-http-execution-of-a-php-s">What is the canonical way to determine commandline vs. http execution of a PHP script?</a></p>
343,569
2
3
null
2008-12-05 11:25:53.927 UTC
21
2013-01-07 20:11:52.507 UTC
2017-05-23 10:30:19.17 UTC
Piskvor
-1
Piskvor
19,746
null
1
60
php|command-line-interface
37,623
<p><strike>If called from command line, the server variable HTTP_USER_AGENT is not set. I use this constant to define, whether the script is called from command line or not:</p> <pre><code>define("CLI", !isset($_SERVER['HTTP_USER_AGENT'])); </code></pre> <p></strike></p> <p><strong>UPDATE:</strong> Since this answer is still marked as the 'correct' one, I'd like to revise my statement - relying on the "User-Agent" header can be problematic, since it's a user-defined value.</p> <p>Please use <code>php_sapi_name() == 'cli'</code> or <code>PHP_SAPI == 'cli'</code>, as suggested by Eugene/cam8001 in the comments.</p> <p>Thanks for pointing this out!</p>
2,551,776
Database Design Primay Key, ID vs String
<p>I am currently planning to develop a music streaming application. And i am wondering what would be better as a primary key in my tables on the server. An ID int or a Unique String.</p> <blockquote> <p>Methods 1:</p> </blockquote> <p>Songs Table: <strong>SongID</strong>(int), Title(string), *Artist**(string), Length(int), *Album**(string)</p> <p>Genre Table <strong>Genre</strong>(string), Name(string)</p> <p>SongGenre: ***SongID****(int), ***Genre****(string)</p> <blockquote> <p>Method 2</p> </blockquote> <p>Songs Table: <strong>SongID</strong>(int), Title(string), *ArtistID**(int), Length(int), *AlbumID**(int)</p> <p>Genre Table <strong>GenreID</strong>(int), Name(string)</p> <p>SongGenre: ***SongID****(int), ***GenreID****(int)</p> <p>Key: <strong>Bold</strong> = Primary Key, *Field** = Foreign Key</p> <p>I'm currently designing using method 2 as I believe it will speed up lookup performance and use less space as an int takes a lot less space then a string.</p> <p>Is there any reason this isn't a good idea? Is there anything I should be aware of?</p>
2,551,791
5
0
null
2010-03-31 09:33:03.907 UTC
13
2015-12-19 11:54:33.22 UTC
2010-04-16 18:06:59.123 UTC
null
164,901
null
271,106
null
1
40
database|database-design
44,491
<p>You are doing the right thing - identity field should be numeric and not string based, both for space saving and for performance reasons (matching keys on strings is slower than matching on integers).</p>
2,953,381
Android: Is it possible to refresh just one item in a listview?
<p>I'm wondering if it is possible to rerender just one element in a listview? I assume by calling <code>notifyDatasetChanged()</code> is gonna rerender the whole list? </p> <p>Thanks,</p>
2,953,665
6
3
null
2010-06-01 21:12:52.767 UTC
4
2014-07-23 11:05:19.097 UTC
2011-11-29 14:33:29.18 UTC
null
231,716
null
109,704
null
1
24
android|listview
42,465
<p>You can, but it's a bit convoluted. You would have to get the index of the first visible item in the list and then use that do decide how how far down in the list of visual items the item is that needs updated, then grab its view and update it there.</p> <p>It's much easier to just call <code>notifyDatasetChanged()</code>.</p>
3,178,900
How do I install the Ruby ri documentation?
<p>I've recently installed Ruby 1.9.1 on Windows 7, and apparently it doesn't come with the standard ri documentation. So when I do 'ri Array', I get:</p> <pre><code>C:\&gt;ri Array Nothing known about Array </code></pre> <p>Is there a way I can install this documentation so that the above works?</p>
3,180,173
8
0
null
2010-07-05 10:54:25.47 UTC
10
2020-07-13 16:19:39.07 UTC
2013-10-09 01:49:50.263 UTC
null
128,421
null
368,134
null
1
26
ruby
20,488
<p>Seems you have installer Ruby 1.9.1 distributed by the RubyInstaller project.</p> <p>You can use the Windows Help Files (CHM) that came with the installer instead of the ri documentation.</p> <p>The problem of the RI documentation is that some versions of RDoc have problems generating it and also generated more than 10 thousands files which slowed down the installers considerably.</p>
2,768,104
How To Create a Flexible Plug-In Architecture?
<p>A repeating theme in my development work has been the use of or creation of an in-house plug-in architecture. I've seen it approached many ways - configuration files (XML, .conf, and so on), inheritance frameworks, database information, libraries, and others. In my experience:</p> <ul> <li>A database isn't a great place to store your configuration information, especially co-mingled with data</li> <li>Attempting this with an inheritance hierarchy requires knowledge about the plug-ins to be coded in, meaning the plug-in architecture isn't all that dynamic</li> <li>Configuration files work well for providing simple information, but can't handle more complex behaviors</li> <li>Libraries seem to work well, but the one-way dependencies have to be carefully created.</li> </ul> <p>As I seek to learn from the various architectures I've worked with, I'm also looking to the community for suggestions. How have you implemented a SOLID plug-in architecture? What was your worst failure (or the worst failure you've seen)? What would you do if you were going to implement a new plug-in architecture? What SDK or open source project that you've worked with has the best example of a good architecture?</p> <p>A few examples I've been finding on my own:</p> <ul> <li>Perl's <a href="http://search.cpan.org/~simonw/Module-Pluggable-3.9/lib/Module/Pluggable.pm" rel="noreferrer">Module::Plugable</a> and <a href="http://www.drdobbs.com/web-development/184416179" rel="noreferrer">IOC</a> for dependency injection in Perl</li> <li><a href="http://www.springsource.org/" rel="noreferrer">The various Spring frameworks</a> (Java, .NET, Python) for dependency injection.</li> <li>An <a href="https://stackoverflow.com/questions/1613935/java-plugin-framework-choice">SO question</a> with a list for Java (including <a href="http://en.wikipedia.org/wiki/Service_Provider_Interface" rel="noreferrer">Service Provider Interfaces</a>)</li> <li>An <a href="https://stackoverflow.com/questions/43322/whats-safe-for-a-c-plug-in-system">SO question</a> for C++ pointing to a <a href="http://www.drdobbs.com/cpp/204202899;jsessionid=2P021EF4CUUAFQE1GHPSKH4ATMY32JVN?cid=RSSfeed%255FDDJ%255FCpp" rel="noreferrer">Dr. Dobbs article</a></li> <li>An <a href="https://stackoverflow.com/questions/340183/plug-in-architecture-for-asp-net-mvc">SO question</a> regarding a specific plugin idea for ASP.NET MVC</li> </ul> <p>These examples seem to play to various language strengths. Is a good plugin architecture necessarily tied to the language? Is it best to use tools to create a plugin architecture, or to do it on one's own following models?</p>
2,788,522
9
2
2010-05-04 18:50:51.693 UTC
2010-05-04 18:50:51.693 UTC
128
2020-03-03 16:47:46.213 UTC
2018-10-29 13:16:04.673 UTC
null
1,497,139
null
213,758
null
1
171
plugins|architecture|language-agnostic|plugin-architecture
71,697
<p>This is not an <em>answer</em> as much as a bunch of potentially useful remarks/examples. </p> <ul> <li><p>One effective way to make your application extensible is to expose its internals as a scripting language and write all the top level stuff in that language. This makes it quite modifiable and practically future proof (if your primitives are well chosen and implemented). A success story of this kind of thing is Emacs. I prefer this to the eclipse style plugin system because if I want to extend functionality, I don't have to learn the API and write/compile a separate plugin. I can write a 3 line snippet in the current buffer itself, evaluate it and use it. Very smooth learning curve and very pleasing results. </p></li> <li><p>One application which I've extended a little is <a href="http://trac.edgewall.org/wiki/TracDev/ComponentArchitecture" rel="noreferrer">Trac</a>. It has a component architecture which in this situation means that tasks are delegated to modules that advertise extension points. You can then implement other components which would fit into these points and change the flow. It's a little like Kalkie's suggestion above. </p></li> <li><p>Another one that's good is <a href="http://pytest.org/latest/index.html" rel="noreferrer">py.test</a>. It follows the "best API is no API" philosophy and relies purely on hooks being called at every level. You can override these hooks in files/functions named according to a convention and alter the behaviour. You can see the list of plugins on the site to see how quickly/easily they can be implemented. </p></li> </ul> <p>A few general points. </p> <ul> <li>Try to keep your non-extensible/non-user-modifiable core as small as possible. Delegate everything you can to a higher layer so that the extensibility increases. Less stuff to correct in the core then in case of bad choices. </li> <li>Related to the above point is that you shouldn't make too many decisions about the direction of your project at the outset. Implement the smallest needed subset and then start writing plugins. </li> <li>If you are embedding a scripting language, make sure it's a full one in which you can write general programs and not a toy language <em>just</em> for your application. </li> <li>Reduce boilerplate as much as you can. Don't bother with subclassing, complex APIs, plugin registration and stuff like that. Try to keep it simple so that it's <em>easy</em> and not just <em>possible</em> to extend. This will let your plugin API be used more and will encourage end users to write plugins. Not just plugin developers. py.test does this well. Eclipse as far as I know, <a href="http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/runtime/Plugin.html" rel="noreferrer">does not</a>. </li> </ul>
2,523,765
QString to char* conversion
<p>I was trying to convert a QString to char* type by the following methods, but they don't seem to work.</p> <pre><code>//QLineEdit *line=new QLineEdit();{just to describe what is line here} QString temp=line-&gt;text(); char *str=(char *)malloc(10); QByteArray ba=temp.toLatin1(); strcpy(str,ba.data()); </code></pre> <p>Can you elaborate the possible flaw with this method, or give an alternative method?</p>
2,523,786
10
2
null
2010-03-26 13:59:33.613 UTC
22
2022-06-21 16:08:57.513 UTC
2014-12-16 06:42:37.57 UTC
null
2,682,142
null
90,575
null
1
114
c++|qt|qstring|qtcore
235,481
<p>Well, the <a href="https://wiki.qt.io/Technical_FAQ#How_can_I_convert_a_QString_to_char.2A_and_vice_versa.3F" rel="noreferrer">Qt FAQ</a> says:</p> <pre><code>int main(int argc, char **argv) { QApplication app(argc, argv); QString str1 = "Test"; QByteArray ba = str1.toLocal8Bit(); const char *c_str2 = ba.data(); printf("str2: %s", c_str2); return app.exec(); } </code></pre> <p>So perhaps you're having other problems. How exactly doesn't this work?</p>
24,968,410
Install single package from Rawhide
<p>How can one install a single Rawhide package, without upgrading the entire operating system?</p> <p><a href="http://apps.fedoraproject.org/packages/bash">Example package</a></p>
24,968,411
2
0
null
2014-07-26 06:52:41.293 UTC
9
2022-05-20 18:50:21.253 UTC
2020-07-28 17:21:24.223 UTC
null
9,315,690
null
1,002,260
null
1
25
fedora|yum|dnf
10,152
<pre><code>yum install fedora-repos-rawhide yum install --enablerepo rawhide bash </code></pre>
33,603,027
Get Apple clang version and corresponding upstream LLVM version
<p>I want to understand which version of clang Apple installed in my macbook, to see with c++11 and/or c++14 features are available. I typed this command:</p> <pre><code>clang --version //----response Apple LLVM version 7.0.0 (clang-700.1.76) Target: x86_64-apple-darwin15.0.0 Thread model: posix </code></pre> <p>But I am not able to understand what <code>(clang-700.1.76)</code> mean. How can I convert this code to a clang version?</p> <p>This is the site where you could check c++ features available in clang version <a href="http://clang.llvm.org/cxx_status.html">http://clang.llvm.org/cxx_status.html</a></p>
33,614,612
10
2
null
2015-11-09 05:28:16.88 UTC
11
2022-01-13 23:45:26.423 UTC
2018-03-06 23:04:04.84 UTC
null
202,229
null
1,591,956
null
1
71
c++11|clang|c++14|llvm-clang|c++17
52,135
<p>The (Apple) version number of the compiler is mostly useless, since you also need to consider whether your code is compiled with <code>libstdc++</code> or with <code>libc++</code> (or any other standard library) - and which version of those.</p> <p>If you want to test for language or library features, it is better to check other defined values, e.g., <code>__cplusplus</code>, <code>__cpp_constexpr</code>, <code>__cpp_variadic_templates</code>, etc. It is not perfect, but it seems to work better (if you want portability) in my experience and the support from all major compiler is improving.</p> <p>Each C++ standard version defines a value for <code>__cplusplus</code>, some compilers use intermediate values to say "we already started on C++14, but we are not there yet". Use <code>&gt;=</code> to test when needed.</p> <p>The other feature test macros are similar, you can find the current version at <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4440.html" rel="nofollow noreferrer">N4440</a>. Not all compilers implement N4440, though.</p>
45,546,401
Wait for sequence of action with a Redux Observable
<p>I have a use case where I need to wait for a sequence of actions before I dispatch another using Redux Observables. I've seen some similar questions but I cannot fathom how I can use these approaches for my given use case.</p> <p>In essence I want to do something like so:</p> <pre><code>action$ .ofType(PAGINATION_CLICKED) // This action occurred. .ofType(FETCH_SUCCESS) // Then this action occurred after. .map(() =&gt; analyticsAction()); // Dispatch analytics. </code></pre> <p>I would also like to cancel and start that sequence over again if another action of type <code>FETCH_ERROR</code> fires for example.</p>
45,554,647
1
0
null
2017-08-07 11:59:47.053 UTC
11
2017-10-17 17:53:55.717 UTC
null
null
null
null
976,497
null
1
22
redux|redux-observable
6,558
<p>Great question. The important point is that <code>action$</code> is a hot/multicast stream of all actions as they are dispatched (it's a Subject). Since it's hot we can combine it multiple times and they'll all be listening to the same stream of actions.</p> <pre><code>// uses switchMap so if another PAGINATION_CLICKED comes in // before FETCH_SUCCESS we start over action$ .ofType(PAGINATION_CLICKED) .switchMap(() =&gt; action$.ofType(FETCH_SUCCESS) .take(1) // &lt;-------------------- very important! .map(() =&gt; analyticsAction()) .takeUntil(action$.ofType(FETCH_ERROR)) ); </code></pre> <p>So every time we receive <code>PAGINATION_CLICKED</code> we'll start listening to that inner Observable chain that listens for a single <code>FETCH_SUCCESS</code>. It's important to have that <code>.take(1)</code> because otherwise we'd continue to listen for more than one <code>FETCH_SUCCESS</code> which might cause strange bugs and even if not is just generally best practice to only take what you need.</p> <p>We use <code>takeUntil</code> to cancel waiting for <code>FETCH_SUCCESS</code> if we receive <code>FETCH_ERROR</code> first.</p> <hr> <p>As a bonus, if you decide you want also to do some analytics stuff based on the error too, not only start over, you can use <code>race</code> to indeed race between the two streams. First one to emit, wins; the other is unsubscribed.</p> <pre><code>action$ .ofType(PAGINATION_CLICKED) .switchMap(() =&gt; Observable.race( action$.ofType(FETCH_SUCCESS) .take(1) .map(() =&gt; analyticsAction()), action$.ofType(FETCH_ERROR) .take(1) .map(() =&gt; someOtherAnalyticsAction()) ) ); </code></pre> <p>Here's the same thing, but using <code>race</code> as an instance operator instead of the static one. This is a stylistic preference you can choose. They both do the same thing. Use whichever one is more clear to you.</p> <pre><code>action$ .ofType(PAGINATION_CLICKED) .switchMap(() =&gt; action$.ofType(FETCH_SUCCESS) .map(() =&gt; analyticsAction()) .race( action$.ofType(FETCH_ERROR) .map(() =&gt; someOtherAnalyticsAction()) ) .take(1) ); </code></pre>
45,505,333
Difference between hyperledger composer and hyperledger fabric?
<p>I am java developer and new to hyperledger. I am interested in learning it and need to know where to start . fabric vs composer?</p>
45,506,238
8
1
null
2017-08-04 11:10:54.927 UTC
11
2019-11-16 03:37:54.87 UTC
null
null
null
null
4,844,908
null
1
34
hyperledger|hyperledger-fabric|hyperledger-composer
16,477
<p>Hyperledger Composer simplifies application development on top of the Hyperledger Fabric blockchain infrastructure.</p> <p>If you are interested in the blockchain infrastructure, start with the Fabric <a href="https://hyperledger-fabric.readthedocs.io/en/latest/build_network.html#" rel="noreferrer">tutorials</a>.</p> <p>If you are interested in blockchain applications, start with the Composer <a href="https://hyperledger.github.io/composer/latest/tutorials/tutorials.html" rel="noreferrer">tutorials</a>.</p> <p>The Fabric tutorials also include samples of low level chaincode development (in golang). Composer is a higher level application development framework.</p> <p>I'd suggest trying both to get an overall view of the capabilities.</p> <p>As a Java developer, you will also want to check out the <a href="https://hyperledger-fabric.readthedocs.io/en/latest/fabric-sdks.html" rel="noreferrer">Fabric Java SDK</a> for building Java client applications that interact with the blockchain. Java chaincode is also available as of Fabric v1.3.</p>
40,090,111
PostCSS error: [object Object] is not a PostCSS plugin
<p>The error is coming from the <code>postcss</code> plugin, I think I may have written it incorrectly. </p> <p>I'm trying to add <code>cssnano</code> and <code>autoprefixer</code> to the <code>postcss</code> plugin.</p> <pre><code>gulp/node_modules/gulp-postcss/node_modules/postcss/lib/processor.js:143 throw new Error(i + ' is not a PostCSS plugin'); ^ Error: [object Object] is not a PostCSS plugin at Processor.normalize (/Applications/XAMPP/xamppfiles/htdocs/sites/gulp/node_modules/gulp-postcss/node_modules/postcss/lib/processor.js:143:15) at new Processor (/Applications/XAMPP/xamppfiles/htdocs/sites/gulp/node_modules/gulp-postcss/node_modules/postcss/lib/processor.js:51:25) at postcss (/Applications/XAMPP/xamppfiles/htdocs/sites/gulp/node_modules/gulp-postcss/node_modules/postcss/lib/postcss.js:73:10) at Transform.stream._transform (/Applications/XAMPP/xamppfiles/htdocs/sites/gulp/node_modules/gulp-postcss/index.js:47:5) at Transform._read (_stream_transform.js:167:10) at Transform._write (_stream_transform.js:155:12) at doWrite (_stream_writable.js:300:12) at writeOrBuffer (_stream_writable.js:286:5) at Transform.Writable.write (_stream_writable.js:214:11) at DestroyableTransform.ondata (/Applications/XAMPP/xamppfiles/htdocs/sites/gulp/node_modules/gulp-sass/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:531:20) Mac-a45e60e72dad:gulp JoeKonst$ </code></pre> <p>My code:</p> <pre><code>// Dependancies var gulp = require('gulp'), browserSync = require('browser-sync'), plumber = require('gulp-plumber'), autoprefixer = require('gulp-autoprefixer'), uglify = require('gulp-uglify'), compass = require('gulp-compass'), rename = require('gulp-rename'), nano = require('cssnano'), del = require('del'), postcss = require('gulp-postcss'), sass = require('gulp-sass'); // Styles gulp.task('styles', function(){ gulp.src('sass/main.scss') .pipe(sass()) .pipe(postcss([autoprefixer({browsers: ['last 2 versions']}), nano()])) .pipe(gulp.dest('css/')); gulp.watch('sass/**/*.scss', ['styles']); }); // Tasks gulp.task('default', ['styles']); </code></pre>
40,090,454
6
0
null
2016-10-17 15:19:26.287 UTC
9
2022-04-17 13:56:35.773 UTC
2016-10-17 15:41:40.34 UTC
null
5,892,036
null
4,580,542
null
1
31
gulp|postcss
46,807
<p>You are using the <a href="https://www.npmjs.com/package/gulp-autoprefixer" rel="noreferrer"><code>gulp-autoprefixer</code></a> package. That's simply a wrapper around the original <a href="https://www.npmjs.com/package/autoprefixer" rel="noreferrer"><code>autoprefixer</code></a> package that turns it into a gulp plugin, so you can do <code>.pipe(autoprefixer())</code>.</p> <p>However <code>postcss</code> expects the original package itself, not the gulp plugin.</p> <p>So instead of this:</p> <pre><code>autoprefixer = require('gulp-autoprefixer'), </code></pre> <p>You need to install the <code>autoprefixer</code> package and do this:</p> <pre><code>autoprefixer = require('autoprefixer'), </code></pre>
10,790,183
Setting image property of UIImageView causes major lag
<p>Let me tell you about the problem I am having and how I tried to solve it. I have a UIScrollView which loads subviews as one scrolls from left to right. Each subview has 10-20 images around 400x200 each. When I scroll from view to view, I experience quite a bit of lag.</p> <p>After investigating, I discovered that after unloading all the views and trying it again, the lag was gone. I figured that the synchronous caching of the images was the cause of the lag. So I created a subclass of UIImageView which loaded the images asynchronously. The loading code looks like the following (<code>self.dispatchQueue</code> returns a serial dispatch queue).</p> <pre><code>- (void)loadImageNamed:(NSString *)name { dispatch_async(self.dispatchQueue, ^{ UIImage *image = [UIImage imageNamed:name]; dispatch_sync(dispatch_get_main_queue(), ^{ self.image = image; }); }); } </code></pre> <p>However, after changing all of my UIImageViews to this subclass, I still experienced lag (I'm not sure if it was lessened or not). I boiled down the cause of the problem to <code>self.image = image;</code>. Why is this causing so much lag (but only on the first load)?</p> <p>Please help me. =(</p>
10,818,917
2
0
null
2012-05-28 20:37:20.017 UTC
17
2021-06-10 18:53:54.09 UTC
2012-05-28 20:45:18.407 UTC
null
815,742
null
815,742
null
1
23
performance|asynchronous|uiimageview|uiimage|core-graphics
11,468
<p>EDIT 3: iOS 15 now offers <a href="https://developer.apple.com/documentation/uikit/uiimage/3750844-preparefordisplay" rel="nofollow noreferrer"><code>UIImage.prepareForDisplay(completionHandler:)</code></a>.</p> <pre class="lang-swift prettyprint-override"><code>image.prepareForDisplay { decodedImage in imageView.image = decodedImage } </code></pre> <p>or</p> <pre class="lang-swift prettyprint-override"><code>imageView.image = await image.byPreparingForDisplay() </code></pre> <hr /> <p>EDIT 2: Here is a Swift version that contains a few improvements. (Untested.) <a href="https://gist.github.com/fumoboy007/d869e66ad0466a9c246d" rel="nofollow noreferrer">https://gist.github.com/fumoboy007/d869e66ad0466a9c246d</a></p> <hr /> <p>EDIT: Actually, I believe all that is necessary is the following. (Untested.)</p> <pre class="lang-objectivec prettyprint-override"><code>- (void)loadImageNamed:(NSString *)name { dispatch_async(self.dispatchQueue, ^{ // Determine path to image depending on scale of device's screen, // fallback to 1x if 2x is not available NSString *pathTo1xImage = [[NSBundle mainBundle] pathForResource:name ofType:@&quot;png&quot;]; NSString *pathTo2xImage = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@&quot;@2x&quot;] ofType:@&quot;png&quot;]; NSString *pathToImage = ([UIScreen mainScreen].scale == 1 || !pathTo2xImage) ? pathTo1xImage : pathTo2xImage; UIImage *image = [[UIImage alloc] initWithContentsOfFile:pathToImage]; // Decompress image if (image) { UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale); [image drawAtPoint:CGPointZero]; image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); } // Configure the UI with pre-decompressed UIImage dispatch_async(dispatch_get_main_queue(), ^{ self.image = image; }); }); } </code></pre> <hr /> <p>ORIGINAL ANSWER: It turns out that it wasn't <code>self.image = image;</code> directly. The UIImage image loading methods don't decompress and process the image data right away; they do it when the view refreshes its display. So the solution was to go a level lower to Core Graphics and decompress and process the image data myself. The new code looks like the following.</p> <pre class="lang-objectivec prettyprint-override"><code>- (void)loadImageNamed:(NSString *)name { dispatch_async(self.dispatchQueue, ^{ // Determine path to image depending on scale of device's screen, // fallback to 1x if 2x is not available NSString *pathTo1xImage = [[NSBundle mainBundle] pathForResource:name ofType:@&quot;png&quot;]; NSString *pathTo2xImage = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@&quot;@2x&quot;] ofType:@&quot;png&quot;]; NSString *pathToImage = ([UIScreen mainScreen].scale == 1 || !pathTo2xImage) ? pathTo1xImage : pathTo2xImage; UIImage *uiImage = nil; if (pathToImage) { // Load the image CGDataProviderRef imageDataProvider = CGDataProviderCreateWithFilename([pathToImage fileSystemRepresentation]); CGImageRef image = CGImageCreateWithPNGDataProvider(imageDataProvider, NULL, NO, kCGRenderingIntentDefault); // Create a bitmap context from the image's specifications // (Note: We need to specify kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little // because PNGs are optimized by Xcode this way.) CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef bitmapContext = CGBitmapContextCreate(NULL, CGImageGetWidth(image), CGImageGetHeight(image), CGImageGetBitsPerComponent(image), CGImageGetWidth(image) * 4, colorSpace, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little); // Draw the image into the bitmap context CGContextDrawImage(bitmapContext, CGRectMake(0, 0, CGImageGetWidth(image), CGImageGetHeight(image)), image); // Extract the decompressed image CGImageRef decompressedImage = CGBitmapContextCreateImage(bitmapContext); // Create a UIImage uiImage = [[UIImage alloc] initWithCGImage:decompressedImage]; // Release everything CGImageRelease(decompressedImage); CGContextRelease(bitmapContext); CGColorSpaceRelease(colorSpace); CGImageRelease(image); CGDataProviderRelease(imageDataProvider); } // Configure the UI with pre-decompressed UIImage dispatch_async(dispatch_get_main_queue(), ^{ self.image = uiImage; }); }); } </code></pre>
10,581,206
Boolean literals in PowerShell
<p>What are the Boolean literals in PowerShell?</p>
10,581,229
3
0
null
2012-05-14 10:05:33.453 UTC
9
2021-04-24 21:25:54.32 UTC
2021-03-14 22:29:13.58 UTC
null
63,550
null
284,795
null
1
191
powershell
116,260
<p><code>$true</code> and <code>$false</code>.</p> <p>Those are constants, though. There are no language-level literals for Booleans.</p> <p>Depending on where you need them, you can also use anything that <em>coerces</em> to a Boolean value, if the type has to be Boolean, e.g., in method calls that require Boolean (and have no conflicting overload), or conditional statements. Most non-null objects are true, for example. <code>null</code>, empty strings, empty arrays and the number <code>0</code> are false.</p>
6,139,508
Launching an Android Application from the Browser
<p>I have looked at several Stack Overflow questions with similar titles to mine. Each is answered, and the original author seems satisfied, but when I try to replicate their results I come up empty handed. Obviously I'm doing something horribly wrong, but I can't seem to figure it out.</p> <p>For reference, these are the questions that I've been looking at:</p> <ul> <li><a href="https://stackoverflow.com/questions/2958701/launch-custom-android-application-from-android-browser">Launch Custom Android Application From Android Browser</a></li> <li><a href="https://stackoverflow.com/questions/3469908/make-a-link-in-the-android-browser-start-up-my-app">Make a Link in the Android Browser Start Up My App</a></li> <li><a href="https://stackoverflow.com/questions/5545803/android-dev-callback-url-not-working-0-o">Android Dev Callback Url Not Working</a></li> <li><a href="https://stackoverflow.com/questions/3586627/android-intent-filters-how-do-you-use-intent-category-browsable-correctly">Android Intent Filters: How Do You Use Intent Category Browsable Correctly</a></li> </ul> <p>Ultimately, I want to use this to restart my application once the user has performed an OAuth authentication request. However, my real application is a bit too large to post here. For this question, I've put together a simple application, to show you what I've done. I have two activities. This is mostly because every example I've seen uses an activity using the VIEW action. I'd prefer to use the MAIN action, but I've used both here to show that I tried both. </p> <p>AndroidManifest.xml (Original; see edited version below)</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.example" android:versionCode="1" android:versionName="1.0-SNAPSHOT"&gt; &lt;application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true"&gt; &lt;activity android:name=".HelloAndroidActivity"&gt; &lt;intent-filter&gt; &lt;data android:scheme="ex1"/&gt; &lt;action android:name="android.intent.action.MAIN"/&gt; &lt;category android:name="android.intent.category.LAUNCHER"/&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".CallbackActivity"&gt; &lt;intent-filter&gt; &lt;data android:scheme="ex2"/&gt; &lt;action android:name="android.intent.action.VIEW"/&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; </code></pre> <p></p> <p>AndroidManifest.xml (Edited in response to comment)</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.example" android:versionCode="1" android:versionName="1.0-SNAPSHOT"&gt; &lt;application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true"&gt; &lt;activity android:name=".HelloAndroidActivity"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN"/&gt; &lt;category android:name="android.intent.category.LAUNCHER"/&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".CallbackActivity"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.VIEW"/&gt; &lt;category android:name="android.intent.category.DEFAULT"/&gt; &lt;category android:name="android.intent.category.BROWSABLE"/&gt; &lt;data android:host="www.this-so-does-not-exist.com" android:scheme="http" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; </code></pre> <p></p> <p>main.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" &gt; </code></pre> <p> </p> <p>HelloAndroidActivity.java</p> <pre><code>package org.example; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.widget.TextView; public class HelloAndroidActivity extends Activity { private TextView textView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView) findViewById(R.id.textView); } @Override public void onResume() { super.onResume(); Intent intent = getIntent(); Uri data = intent.getData(); if (data != null) { textView.setText("Hello Web!"); } } } </code></pre> <p>CallbackActivity.java</p> <pre><code>package org.example; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.widget.TextView; public class CallbackActivity extends Activity { private TextView textView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView) findViewById(R.id.textView); } @Override public void onResume() { super.onResume(); Intent intent = getIntent(); Uri data = intent.getData(); if (data != null) { textView.setText("Hello Web!"); } } } </code></pre> <p>This builds happily enough. Then, inside the browser, if I enter ex1://helloworld or ex2://helloworld I get different results depending upon how it is done. If I enter it in the url bar I get a google search for ex1://helloworld. If I do it via a redirect, I get "Web page not available". If I try to start the intent directly with something similar to:</p> <pre><code> Intent intent = new Intent(Intent.ACTION_MAIN); ComponentName componentName = new ComponentName( "org.example", "org.example.HelloAndroidActivity"); intent.setComponent(componentName); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setData(Uri.parse("ex1://helloworld")); intent.addCategory(Intent.CATEGORY_BROWSABLE); startActivity(intent); </code></pre> <p>I get the default "Hello my-example!". I'm not sure what I'm doing incorrectly. Any insights?</p>
6,139,783
2
0
null
2011-05-26 13:44:58.217 UTC
10
2013-05-16 09:12:02.31 UTC
2017-05-23 12:01:33.3 UTC
null
-1
null
771,398
null
1
8
android|android-intent
27,028
<p>You cannot use <code>MAIN</code> -- URLs in Android are only <code>VIEW</code>ed from the browser or <code>WebView</code>.</p> <p>Also, none of your <code>Intent</code> filters include the <code>BROWSABLE</code> category, so they will never work with the browser.</p> <p>It is not recommended to invent your own schemes. You can use a regular HTTP scheme, for some domain that you control. <a href="https://github.com/commonsguy/cw-advandroid/tree/master/Introspection/URLHandler">This sample project</a> demonstrates this. In particular, you can follow the pattern shown by this filter:</p> <pre><code>&lt;intent-filter&gt; &lt;action android:name="android.intent.action.VIEW" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;category android:name="android.intent.category.BROWSABLE" /&gt; &lt;data android:host="www.this-so-does-not-exist.com" android:scheme="http" /&gt; &lt;/intent-filter&gt; </code></pre> <p>replacing <code>www.this-so-does-not-exist.com</code> with something you own, and perhaps adding in a <code>path</code> to narrow the filter's scope. You can also see this technique used by the Barcode Scanner app from <a href="http://code.google.com/p/zxing/">ZXing</a>.</p>
5,726,575
Head (and shoulder) detection using OpenCV
<p>(Appology in advance if I am asking a too nwbie question. I am a beginner with OpenCV. I have done some tutorials yet I have not a good grasp of it's concepts.)</p> <p>Question: How to do head detection (not face detection) using OpenCV - For example in a photo of inside a bus or a room?</p> <p>Note: I do not want to do face detection; just head detection to figure out number of people in the photo. Unfortunately - for me - those tutorials and documents that I'v found are about face detection and not head detection.</p> <p>Thank you</p>
5,727,231
2
4
null
2011-04-20 06:54:54.42 UTC
18
2020-12-09 23:29:39.6 UTC
null
null
null
null
54,467
null
1
17
opencv
26,487
<p>Look at all the Haar boosted classifiers that are available with OpenCV and the dedicated class <a href="http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html#cascadeclassifier" rel="noreferrer"><code>CascadeClassifier</code></a> to use it. Here are a list of what the classifiers have locally:</p> <ul> <li>haarcascade_eye.xml</li> <li>haarcascade_lefteye_2splits.xml</li> <li>haarcascade_mcs_righteye.xml</li> <li>haarcascade_eye_tree_eyeglasses.xml</li> <li>haarcascade_lowerbody.xml</li> <li><strong>haarcascade_mcs_upperbody.xml</strong></li> <li>haarcascade_frontalface_alt.xml</li> <li>haarcascade_mcs_eyepair_big.xml</li> <li>haarcascade_profileface.xml</li> <li>haarcascade_frontalface_alt2.xml</li> <li>haarcascade_mcs_eyepair_small.xml</li> <li>haarcascade_righteye_2splits.xml</li> <li>haarcascade_frontalface_alt_tree.xml</li> <li>haarcascade_mcs_lefteye.xml</li> <li><strong>haarcascade_upperbody.xml</strong></li> <li>haarcascade_frontalface_default.xml</li> <li>haarcascade_mcs_mouth.xml</li> <li>haarcascade_fullbody.xml</li> <li>haarcascade_mcs_nose.xml</li> </ul> <p>The two I bolded may be of special interest to you. Try those as a start for your project. As <a href="https://stackoverflow.com/users/682376/alessandro-vermeulen">Alessandro Vermeulen</a> commented, head detection classifiers may also be interesting, as what they find is usely connected to shoulders :-)</p>
5,941,960
How to implement a listener
<p>I have a design issue. I need to implement a listener. I saw the following SO question: <a href="https://stackoverflow.com/questions/994840/how-to-create-our-own-listener-interface-in-android">How to create our own Listener interface in android?</a></p> <p>But in the link it provides in the answer, author creates a listener which just extends the system-defined listener. E.g onClick, you would do some validation &amp; then call another method called "whenValidatedListener"</p> <p>I need to define listeners which are not linked to existing event listeners. Basically there would be some processing going on in native(C/C++) code &amp; in the Android code I need a listener to respond to certain messages from it.</p> <p>I think I could do this using handlers. But AsyncTask is the recommended approach for multithreading. </p> <p>Is there a way to implement a user-defined-listener using AsyncTask? </p>
5,942,114
2
0
null
2011-05-09 20:11:22.743 UTC
18
2018-04-09 06:08:04.657 UTC
2017-05-23 12:34:11.22 UTC
null
-1
null
289,918
null
1
17
android|android-asynctask|listener
40,806
<p>AsyncTask has nothing to do with implementing a listener.</p> <p>Here's a listener:</p> <pre><code>public interface TheListener { public void somethingHappened(); } </code></pre> <p>Call it however you want. For example, here's a class doing something like View:</p> <pre><code>public class Something { private TheListener mTheListener; public void setTheListener(TheListener listen) { mTheListener = listen; } private void reportSomethingChanged() { if (mTheListener != null) { mTheListener.somethingHappened(); } } } </code></pre> <p>You can make this as complicated as you want. For example, instead of a single listener pointer you could have an ArrayList to allow multiple listeners to be registered.</p> <p>Calling this from native code also has nothing to do with implementing a listener interface. You just need to learn about JNI to learn how native code can interact with Java language code.</p>
6,195,872
Applying multiple filters at once with FFMPEG
<p>I have the need to apply fadein and overlay filters to a video. Is it possible to apply 2 filters at once?</p> <p>I got:</p> <pre><code>ffmpeg -i input.mpg -vf "movie=watermark.png [logo]; [in][logo] overlay=W-w-10:H-h-10 [out]" output.mpg </code></pre> <p>I'm trying to add <code>fade=in:0:20</code>, but if I add a new <code>-vf</code> parameter, it will overwrite the preceding one, and if I add:</p> <pre><code>-vf "fade=in:0:20; movie=......" </code></pre> <p>it won't work.</p> <p>Is this possible or do I have to run FFmpeg twice?</p>
6,206,742
2
0
null
2011-06-01 03:13:30.273 UTC
17
2017-11-15 14:46:05.043 UTC
2015-07-07 10:26:04.697 UTC
null
4,928,615
null
638,668
null
1
72
filter|ffmpeg
75,225
<p>Okay, someone helped me somewhere.</p> <p>I had to separate filters with commas:</p> <pre><code>ffmpeg -i input.mpg -vf "movie=watermark.png [logo]; [in][logo] overlay=W-w-10:H-h-10, fade=in:0:20 [out]" output.mpg </code></pre> <p>This will apply fadein to both the watermark and the video.</p>
31,046,231
What is the most pythonic way to iterate over OrderedDict
<p>I have an OrderedDict and in a loop I want to get index, key and value. It's sure can be done in multiple ways, i.e.</p> <pre><code>a = collections.OrderedDict({…}) for i,b,c in zip(range(len(a)), a.iterkeys(), a.itervalues()): … </code></pre> <p>But I would like to avoid range(len(a)) and shorten a.iterkeys(), a.itervalues() to something like a.iteritems(). With enumerate and iteritems it's possible to rephrase as</p> <pre><code>for i,d in enumerate(a.iteritems()): b,c = d </code></pre> <p>But it requires to unpack inside the loop body. Is there a way to unpack in a for statement or maybe a more elegant way to iterate?</p>
31,046,250
3
0
null
2015-06-25 09:22:45.63 UTC
5
2016-12-04 12:29:08.443 UTC
2015-06-25 09:24:45.773 UTC
null
2,225,682
null
3,219,777
null
1
33
python|python-2.7|loops|dictionary
19,892
<p>You can use tuple unpacking in <a href="https://docs.python.org/2/reference/compound_stmts.html#the-for-statement" rel="noreferrer"><code>for</code> statement</a>:</p> <pre><code>for i, (key, value) in enumerate(a.iteritems()): # Do something with i, key, value </code></pre> <hr> <pre><code>&gt;&gt;&gt; d = {'a': 'b'} &gt;&gt;&gt; for i, (key, value) in enumerate(d.iteritems()): ... print i, key, value ... 0 a b </code></pre> <p>Side Note:</p> <p>In Python 3.x, use <a href="https://docs.python.org/3/library/stdtypes.html#dict.items" rel="noreferrer"><code>dict.items()</code></a> which returns an iterable dictionary view.</p> <pre><code>&gt;&gt;&gt; for i, (key, value) in enumerate(d.items()): ... print(i, key, value) </code></pre>
31,046,203
How to add multiple "Set-Cookie" header in servlet response?
<p>As per RFC <a href="https://www.rfc-editor.org/rfc/rfc6265#page-7" rel="nofollow noreferrer">https://www.rfc-editor.org/rfc/rfc6265#page-7</a> It is allowed to have two headers with same key of &quot;Set-Cookie&quot;. The example provided in RFC is -</p> <pre><code>​​Set-Cookie: SID=31d4d96e407aad42; Path=/; Secure; HttpOnly Set-Cookie: ​​lang=en-US; Path=/; Domain=example.com </code></pre> <p>How​ do ​I achieve same with Jetty(or any other servlet container)? When I call httpServletResponse.addHeader this way-</p> <pre><code>​httpServletResponse.addHeader(&quot;Set-Cookie&quot;, &quot;SID=31d4d96e407aad42; Path=/; Secure; HttpOnly&quot;); httpServletResponse.addHeader(&quot;Set-Cookie&quot;, &quot;lang=en-US; Path=/; Domain=example.com&quot;);​ </code></pre> <p>I see that the second addHeader() doesn't add a new header. According to javadoc for this method-</p> <blockquote> <p>Adds a response header with the given name and value. This method allows response headers to have multiple values.</p> </blockquote> <p>So it seems that multiple values of allowed but I am not sure how to go about having multiple &quot;Set-Cookie&quot; in servlet response.</p>
31,055,209
2
1
null
2015-06-25 09:21:43.217 UTC
1
2015-06-25 21:20:51.877 UTC
2021-10-07 05:54:43.27 UTC
null
-1
null
375,869
null
1
5
java|tomcat|servlets|http-headers|jetty
48,920
<p>Setting Cookies directly like that is a bit awkward, considering that the Servlet API has methods specifically for working with Cookies.</p> <p>Anyway, tested on Jetty 9.3.0.v20150612 and it works as expected.</p> <p><strong>Example: SetCookieTest.java</strong></p> <pre class="lang-java prettyprint-override"><code>package jetty; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.nio.charset.StandardCharsets; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class SetCookieTest { @SuppressWarnings("serial") public static class SetCookieAddHeaderServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.addHeader("Set-Cookie","SID=31d4d96e407aad42; Path=/; Secure; HttpOnly"); resp.addHeader("Set-Cookie","lang=en-US; Path=/; Domain=example.com"); PrintWriter out = resp.getWriter(); out.println("Hello From: " + this.getClass().getName()); } } @SuppressWarnings("serial") public static class SetCookieAddCookieServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); // Set-Cookie: SID=31d4d96e407aad42; Path=/; Secure; HttpOnly Cookie sidCookie = new Cookie("SID","31d4d96e407aad42"); sidCookie.setPath("/"); sidCookie.setSecure(true); sidCookie.setHttpOnly(true); resp.addCookie(sidCookie); // Set-Cookie: lang=en-US; Path=/; Domain=example.com Cookie langCookie = new Cookie("lang","en-US"); langCookie.setPath("/"); langCookie.setDomain("example.com"); resp.addCookie(langCookie); PrintWriter out = resp.getWriter(); out.println("Hello From: " + this.getClass().getName()); } } private static Server server; @BeforeClass public static void startServer() throws Exception { server = new Server(9090); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.addServlet(SetCookieAddHeaderServlet.class,"/test-add-header"); context.addServlet(SetCookieAddCookieServlet.class,"/test-add-cookie"); server.setHandler(context); server.start(); } @AfterClass public static void stopServer() throws Exception { server.stop(); } /** * Issue simple GET request, returning entire response (including payload) * * @param uri * the URI to request * @return the response */ private String issueSimpleHttpGetRequest(String path) throws IOException { StringBuilder req = new StringBuilder(); req.append("GET ").append(path).append(" HTTP/1.1\r\n"); req.append("Host: localhost\r\n"); req.append("Connection: close\r\n"); req.append("\r\n"); // Connect try (Socket socket = new Socket("localhost",9090)) { try (OutputStream out = socket.getOutputStream()) { // Issue Request byte rawReq[] = req.toString().getBytes(StandardCharsets.UTF_8); out.write(rawReq); out.flush(); // Read Response StringBuilder resp = new StringBuilder(); try (InputStream stream = socket.getInputStream(); InputStreamReader reader = new InputStreamReader(stream); BufferedReader buf = new BufferedReader(reader)) { String line; while ((line = buf.readLine()) != null) { resp.append(line).append(System.lineSeparator()); } } // Return Response return resp.toString(); } } } @Test public void testAddHeader() throws Exception { String response = issueSimpleHttpGetRequest("/test-add-header"); System.out.println(response); assertThat("response", response, containsString("Set-Cookie: SID=31d")); assertThat("response", response, containsString("Set-Cookie: lang=en-US")); } @Test public void testAddCookie() throws Exception { String response = issueSimpleHttpGetRequest("/test-add-cookie"); System.out.println(response); assertThat("response", response, containsString("Set-Cookie: SID=31d")); assertThat("response", response, containsString("Set-Cookie: lang=en-US")); } } </code></pre> <p><strong>Console Output</strong></p> <pre class="lang-none prettyprint-override"><code>2015-06-25 14:18:19.186:INFO::main: Logging initialized @167ms 2015-06-25 14:18:19.241:INFO:oejs.Server:main: jetty-9.3.0.v20150612 2015-06-25 14:18:19.276:INFO:oejsh.ContextHandler:main: Started o.e.j.s.ServletContextHandler@56cbfb61{/,null,AVAILABLE} 2015-06-25 14:18:19.288:INFO:oejs.ServerConnector:main: Started ServerConnector@1ef05443{HTTP/1.1,[http/1.1]}{0.0.0.0:9090} 2015-06-25 14:18:19.289:INFO:oejs.Server:main: Started @270ms HTTP/1.1 200 OK Date: Thu, 25 Jun 2015 21:18:19 GMT Content-Type: text/plain;charset=iso-8859-1 Set-Cookie: SID=31d4d96e407aad42;Path=/;Secure;HttpOnly Expires: Thu, 01 Jan 1970 00:00:00 GMT Set-Cookie: lang=en-US;Path=/;Domain=example.com Connection: close Server: Jetty(9.3.0.v20150612) Hello From: jetty.SetCookieTest$SetCookieAddCookieServlet HTTP/1.1 200 OK Date: Thu, 25 Jun 2015 21:18:19 GMT Content-Type: text/plain;charset=iso-8859-1 Set-Cookie: SID=31d4d96e407aad42; Path=/; Secure; HttpOnly Set-Cookie: lang=en-US; Path=/; Domain=example.com Connection: close Server: Jetty(9.3.0.v20150612) Hello From: jetty.SetCookieTest$SetCookieAddHeaderServlet 2015-06-25 14:18:19.405:INFO:oejs.ServerConnector:main: Stopped ServerConnector@1ef05443{HTTP/1.1,[http/1.1]}{0.0.0.0:9090} 2015-06-25 14:18:19.407:INFO:oejsh.ContextHandler:main: Stopped o.e.j.s.ServletContextHandler@56cbfb61{/,null,UNAVAILABLE} </code></pre>
19,338,686
Getting max value from an arraylist of objects?
<p>Is there an easy way to get the max value from one field of an object in an arraylist of objects? For example, out of the following object, I was hoping to get the highest value for the Value field.</p> <p>Example arraylist I want to get the max value for ValuePairs.mValue from.</p> <pre><code>ArrayList&lt;ValuePairs&gt; ourValues = new ArrayList&lt;&gt;(); outValues.add(new ValuePairs(&quot;descr1&quot;, 20.00)); outValues.add(new ValuePairs(&quot;descr2&quot;, 40.00)); outValues.add(new ValuePairs(&quot;descr3&quot;, 50.00)); </code></pre> <p>Class to create objects stored in arraylist:</p> <pre><code>public class ValuePairs { public String mDescr; public double mValue; public ValuePairs(String strDescr, double dValue) { this.mDescr = strDescr; this.mValue = dValue; } } </code></pre> <p>I'm trying to get the max value for mValue by doing something like (which I know is incorrect):</p> <pre><code>double dMax = Collections.max(ourValues.dValue); </code></pre> <p>dMax should be 50.00.</p>
19,338,698
5
0
null
2013-10-12 20:07:44.97 UTC
2
2021-09-15 06:42:06.983 UTC
2021-01-03 11:38:02.927 UTC
null
466,862
null
797,963
null
1
19
java
69,774
<p>Use a <code>Comparator</code> with <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#max%28java.util.Collection,%20java.util.Comparator%29" rel="noreferrer"><code>Collections.max()</code></a> to let it know which is greater in comparison.</p> <hr> <p><strong>Also See</strong></p> <ul> <li><a href="https://stackoverflow.com/questions/5178092/sorting-a-list-of-points-with-java">How to use custom <code>Comparator</code></a></li> </ul>
19,355,024
MySQL table partition by month
<p>I have a huge table that stores many tracked events, such as a user click.</p> <p>The table is already in the 10s of millions, and it's growing larger every day. The queries are starting to get slower when I try to fetch events from a large timeframe, and after reading quite a bit on the subject I understand that partitioning the table may boost the performance.</p> <p>What I want to do is partition the table on a per month basis.</p> <p>I have only found guides that show how to partition manually each month, is there a way to just tell MySQL to partition by month and it will do that automatically?</p> <p>If not, what is the command to do it manually considering my partitioned by column is a datetime?</p>
19,355,553
4
0
null
2013-10-14 07:04:24.193 UTC
10
2022-05-13 11:23:36.43 UTC
2022-05-13 11:21:36.003 UTC
null
74,089
null
539,638
null
1
18
mysql|partition
38,801
<p>As explained by the manual: <a href="http://dev.mysql.com/doc/refman/5.6/en/partitioning-overview.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.6/en/partitioning-overview.html</a></p> <p>This is easily possible by hash partitioning of the month output.</p> <pre><code>CREATE TABLE ti (id INT, amount DECIMAL(7,2), tr_date DATE) ENGINE=INNODB PARTITION BY HASH( MONTH(tr_date) ) PARTITIONS 6; </code></pre> <p>Do note that this only partitions by month and not by year, also there are only 6 partitions (so 6 months) in this example.</p> <p>And for partitioning an existing table (manual: <a href="https://dev.mysql.com/doc/refman/5.7/en/alter-table-partition-operations.html" rel="nofollow noreferrer">https://dev.mysql.com/doc/refman/5.7/en/alter-table-partition-operations.html</a>):</p> <pre><code>ALTER TABLE ti PARTITION BY HASH( MONTH(tr_date) ) PARTITIONS 6; </code></pre> <p>Querying can be done both from the entire table:</p> <pre><code>SELECT * from ti; </code></pre> <p>Or from specific partitions:</p> <pre><code>SELECT * from ti PARTITION (HASH(MONTH(some_date))); </code></pre>
58,578,341
How to implement localization in Swift UI
<p>Can anybody help me? I can't find any description of the localization in Swift UI. Can anyone please give advice or better an example of how to localize for example <code>Text()</code>?</p>
58,578,851
7
0
null
2019-10-27 10:04:41.613 UTC
11
2022-04-19 05:20:53.643 UTC
2020-06-17 10:52:06.513 UTC
null
7,948,372
null
8,295,040
null
1
36
ios|swift|localization|swiftui|xcode11.1
20,391
<p>When you look at <a href="https://developer.apple.com/documentation/swiftui/text/init(_:tablename:bundle:comment:)" rel="noreferrer">documentation</a> for <code>Text</code> you can see that it takes <code>LocalizedStringKey</code> not a <code>String</code> into its initializer:</p> <pre class="lang-swift prettyprint-override"><code>init(_ key: LocalizedStringKey, tableName: String? = nil, bundle: Bundle? = nil, comment: StaticString? = nil) </code></pre> <p>It makes localizing very straightforward. All you have to do is:</p> <ul> <li>create a new file of type &quot;Strings File&quot;, call it <code>Localizable.strings</code></li> <li>select the new file and navigate to File Inspector in the right hand side panel and click Localize...</li> <li>go to your project file to the Localizations section and add another language to the list - Xcode will create localization files for you</li> </ul> <p>When you select you <code>Localizable.strings</code> you will see that it contains files for the original language and the language you have just added. That's where you put your translations, i.e. key - localized text pairs.</p> <p>If you have a text like this is your app:</p> <pre class="lang-swift prettyprint-override"><code>Text(&quot;Hello World!&quot;) </code></pre> <p>You have to now add to your <code>Localizable.strings</code> your translations:</p> <p>for your base language:</p> <pre class="lang-swift prettyprint-override"><code>&quot;Hello World!&quot; = &quot;Hello World!&quot;; </code></pre> <p>and for your second language (in this case German):</p> <pre class="lang-swift prettyprint-override"><code>&quot;Hello World!&quot; = &quot;Hallo Welt!&quot;; </code></pre> <p>To see your previews localised you can define them like this:</p> <pre class="lang-swift prettyprint-override"><code>struct ContentViewView_Previews: PreviewProvider { static var previews: some View { ForEach([&quot;en&quot;, &quot;de&quot;], id: \.self) { id in ContentView() .environment(\.locale, .init(identifier: id)) } } } </code></pre>
41,192,491
How can I provide a SSL certificate with create-react-app?
<p><br/> I am trying to host a react app I created and tested locally using the facebook boilerplate. <br/> The client app interacts with an API I made using node.js, and with which I had no issue setting up a secure connection (with a node.js client sending my SSL certificate, for testing). <br/> However, I am encountering difficulties when it comes to using react to send my SSL certificate instead of a self-signed one which causes me to encounter this error using chrome and trying to access to <a href="https://example.net:3000" rel="noreferrer">https://example.net:3000</a> :</p> <blockquote> <p>Your connection is not private (NET:ERR_CERT_AUTHORITY_INVALID)</p> </blockquote> <p>The documentation did not quite help me:</p> <blockquote> <p>Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. <a href="https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#using-https-in-development" rel="noreferrer">https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#using-https-in-development</a></p> </blockquote> <p>How can I use my own SSL certificate (which I already use on another app on my domain and works like a charm) instead of this self-signed one ? Did I miss something ?</p>
60,821,222
11
0
null
2016-12-16 21:13:07.933 UTC
24
2022-09-03 06:28:43.417 UTC
2017-07-13 10:05:23.337 UTC
null
5,599,091
null
5,599,091
null
1
44
node.js|facebook|reactjs|ssl|https
101,061
<p>I was able to get a local certificate working <strong>without</strong> modifying the <code>webpack-dev-server</code> files using <code>react-scripts</code> <code>3.4.1</code> (technically added in <code>3.4.0</code> but I had some—probably unrelated—issues). I added these two environment variables to my <code>.env.development</code>:</p> <pre><code>SSL_CRT_FILE=.cert/server.crt SSL_KEY_FILE=.cert/server.key </code></pre> <p>Notes:</p> <ul> <li><code>.cert</code> is a folder I created in the root of my project</li> <li><a href="https://gist.github.com/ptvandi/5a33c28d74ccc5100d7fe2bf5de96deb" rel="noreferrer">My script that generates the SSL certificate</a></li> <li><a href="https://create-react-app.dev/docs/using-https-in-development/#custom-ssl-certificate" rel="noreferrer">Official documentation on these two environment variables</a></li> </ul>
8,681,177
How to make full screen in Android 4.0
<p>Android 4.0 phones only have virtual buttons, which actually go invisible when playing youtube/video at fullscreen (the video portion takes over where the buttons are).</p> <p>I want to do this, but haven't found a way. </p> <pre><code>android:theme="@android:style/Theme.NoTitleBar.Fullscreen" </code></pre> <p>or</p> <pre><code>requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); </code></pre> <p>do not cover the virtual buttons.</p> <p>Here is an example that shows the type of full screen I'm talking about:</p> <p><a href="http://www.youtube.com/watch?v=Lw_O1JpmPns">http://www.youtube.com/watch?v=Lw_O1JpmPns</a></p>
8,686,131
4
0
null
2011-12-30 15:44:35.993 UTC
9
2014-04-03 19:48:59.177 UTC
null
null
null
null
277,140
null
1
9
android-layout|android-4.0-ice-cream-sandwich
20,403
<p>Okay, I added this <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> flag to my video activity and that hid the virtual buttons.</p> <pre><code>WebView view = new WebView(this); view.setSystemUiVisibility(WebView.SYSTEM_UI_FLAG_HIDE_NAVIGATION); </code></pre> <p>Another choice is to use the <code>SYSTEM_UI_FLAG_LOW_PROFILE</code> flag. This doesn't hide the buttons though. Instead it makes the buttons go to "Low Profile" mode (basically turns them into little dots)</p>
8,589,645
How to determine MIME type of file in android?
<p>Suppose I have a full path of file like:(/sdcard/tlogo.png). I want to know its mime type.</p> <p>I created a function for it </p> <pre><code>public static String getMimeType(File file, Context context) { Uri uri = Uri.fromFile(file); ContentResolver cR = context.getContentResolver(); MimeTypeMap mime = MimeTypeMap.getSingleton(); String type = mime.getExtensionFromMimeType(cR.getType(uri)); return type; } </code></pre> <p>but when i call it, it returns null.</p> <pre><code>File file = new File(filePath); String fileType=CommonFunctions.getMimeType(file, context); </code></pre>
8,591,230
28
0
null
2011-12-21 12:13:03.427 UTC
62
2021-10-18 05:13:30.623 UTC
2019-02-15 14:53:23.013 UTC
null
6,625,726
null
995,197
null
1
211
android|filesystems|mime-types
178,130
<p>First and foremost, you should consider calling <code>MimeTypeMap#getMimeTypeFromExtension()</code>, like this:</p> <pre><code>// url = file path or whatever suitable URL you want. public static String getMimeType(String url) { String type = null; String extension = MimeTypeMap.getFileExtensionFromUrl(url); if (extension != null) { type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } return type; } </code></pre>
26,938,210
ExecutorService vs Casual Thread Spawner
<p>I have a basic question about how <code>ExecutorService</code> works in Java.</p> <p>It is quite hard to see the difference between simply creating <code>Threads</code> to perform some tasks in parallel and assigning each tasks to the <code>ThreadPool</code>.</p> <p>The <code>ExecutorService</code> also looks very simple and efficient to use, so I was wondering why we don't use it all the time. </p> <p>Is it just a matter of one way executing its job faster than the other ?</p> <p>Here's two very simple examples to show the difference between the two ways :</p> <p><strong>Using executor service: Hello World (task)</strong> </p> <pre><code>static class HelloTask implements Runnable { String msg; public HelloTask(String msg) { this.msg = msg; } public void run() { long id = Thread.currentThread().getId(); System.out.println(msg + " from thread:" + id); } } </code></pre> <p><strong>Using executor service: Hello World (creating executor, submitting)</strong></p> <pre><code>static class HelloTask { public static void main(String[] args) { int ntasks = 1000; ExecutorService exs = Executors.newFixedThreadPool(4); for (int i=0; i&lt;ntasks; i++) { HelloTask t = new HelloTask("Hello from task " + i); exs.submit(t); } exs.shutdown(); } } </code></pre> <hr> <p>the following shows a similar example but extending the Callable interface, could you tell me the difference between the two and in which cases one should use a specific one instead of the other ?</p> <p><strong>Using executor service: Counter (task)</strong></p> <pre><code>static class HelloTaskRet implements Callable&lt;Long&gt; { String msg; public HelloTaskRet(String msg) { this.msg = msg; } public Long call() { long tid = Thread.currentThread().getId(); System.out.println(msg + " from thread:" + tid); return tid; } } </code></pre> <p><strong>Using executor service: (creating, submitting)</strong> </p> <pre><code>static class HelloTaskRet { public static void main(String[] args) { int ntasks = 1000; ExecutorService exs = Executors.newFixedThreadPool(4); Future&lt;Long&gt;[] futures = (Future&lt;Long&gt;[]) new Future[ntasks]; for (int i=0; i&lt;ntasks; i++) { HelloTaskRet t = new HelloTaskRet("Hello from task " + i); futures[i] = exs.submit(t); } exs.shutdown(); } } </code></pre>
26,938,900
2
1
null
2014-11-14 20:21:57.92 UTC
8
2018-12-17 12:08:47.363 UTC
2018-08-14 10:59:04.83 UTC
null
1,240,502
null
4,129,131
null
1
25
java|multithreading|executorservice
21,498
<p>While the question and the sample code do not correlate, I'll try clarifying both. The advantage of <code>ExecutorService</code> over haphazardly spawning threads is that it behaves predictably and avoids the overhead of thread creation, which is relatively big on the JVM (it needs to reserve memory for each thread, for example). By predictability, at least for the <code>fixedThreadPool</code>, I mean you know the maximum number of concurrent threads, and you know when and how they might get created (so your JVM won't blow up in case of sudden peaks).</p> <blockquote> <p><em>By Vince Emigh:</em> <code>ExecutorService</code> also supports <code>cachedThreadPool</code>, which doesn't have a max. The main reason people choose to use <code>ExecutorService</code> is to prevent the overhead of creating multiple threads (by using <em>worker threads</em>). It's mostly used in cases where many small tasks need to be executed on a separate thread. Also, don't forget about <code>singleThreadExecutor</code>.</p> </blockquote> <p>Now, on the topic of <code>Runnable</code> vs <code>Callable</code>, it is easy to see from your examples. <code>Callable</code>s can return a value place-holder (<code>Future</code>) that will eventually be populated by an actual value in the future. <code>Runnable</code>s can not return anything.</p> <blockquote> <p><em>By Vince Emigh:</em> <code>Runnable</code> also cannot throw exceptions, while <code>Callable</code> can.</p> </blockquote>
777,562
Moving From Eclipse to Visual Studio 2008
<p>After working in Eclipse for the past 3 years and memorizing all of the great shortcut keys and features, my new job has me moving back to Visual Studio. I've found some listings of shortcut keys on VS, but am looking for a comprehensive guide mapping Eclipse features to Visual Studio. Does anyone know of a good tutorial aimed at helping Eclipse users transition to VS? </p>
890,094
3
2
null
2009-04-22 14:43:36.863 UTC
10
2013-10-16 17:31:39.557 UTC
2013-08-20 12:47:33.633 UTC
user1228
null
null
4,513
null
1
21
eclipse|visual-studio-2008
10,946
<p>Because of the lack of information out there on this, let's start a community wiki answer. Please add additional information on migration tips to this answer. Please avoid 3rd party plug-ins such as ReSharper in the answer.</p> <h2>Shortcut Keys</h2> <pre><code>+----------------------+---------------------+---------------------+ | Command | Eclipse shortcut | VS.NET shortcut | +----------------------+---------------------+---------------------+ | Delete line | Ctrl-D | Ctrl-L | | Comment line | Ctrl-/ | Ctrl-K-C | | Uncomment line | Ctrl-/ | Ctrl-K-U | | Toggle editor tabs | Ctrl-F6 | Ctrl-F6 | | Goto Line | Ctrl-L | Ctrl-G | | Goto Definition | Ctrl-Click or F3 | F12 | | Find next | Ctrl-K | F3 | | Find previous | Ctrl-Shift-K | Shift-F3 | | Go backward | Alt-LeftArrow | Ctrl-minus | | Go forward | Alt-RightArrow | Ctrl-Shift-minus | | Find usage | Ctrl-Shift-G | Ctrl-K-R | | Rename | Alt-Shift-R | Ctrl-R-R | | Refactor | Alt-Shift-T | none | | Open Type | Ctrl-Shift-T | Ctrl-, | | Navigate To | Ctrl-Shift-R | Ctrl-, | +----------------------+---------------------+---------------------+ </code></pre>
22,242,984
Declare variable in Razor
<p>I want to add a variable outside the foreach and then use that inside the foreach loop</p> <pre><code>&lt;table class="generalTbl"&gt; &lt;tr&gt; &lt;th&gt;Date&lt;/th&gt; &lt;th&gt;Location&lt;/th&gt; &lt;/tr&gt; @int i; @foreach (var item in Model) { i=0; &lt;tr&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.DueDate) &lt;/td&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.location) &lt;/td&gt; &lt;/tr&gt; } &lt;/table&gt; </code></pre> <p>The above example I have added @int i; outside of the foreach and I tried to access it inside the foreach like i=0; But it shows "<strong>The name 'i' does not exist in the current context</strong>"</p> <p>How can I access the variable inside the loop?</p>
22,243,047
4
0
null
2014-03-07 06:19:28.873 UTC
null
2019-12-18 09:44:00.66 UTC
2019-12-18 09:44:00.66 UTC
null
4,981,637
null
2,501,044
null
1
18
c#|asp.net-mvc|razor|foreach|declaration
63,458
<pre><code>&lt;table class="generalTbl"&gt; &lt;tr&gt; &lt;th&gt;Date&lt;/th&gt; &lt;th&gt;Location&lt;/th&gt; &lt;/tr&gt; @{ int i = 0;//value you want to initialize it with foreach (var item in Model) { &lt;tr&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.DueDate) &lt;/td&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.location) &lt;/td&gt; &lt;/tr&gt; } } &lt;/table&gt; </code></pre>
6,728,356
login POST form with cURL
<p>I am trying to login to the website www.centralgreen.com.sg/login.php using cURL (first time user of cURL)</p> <p>I used the Tamper plugin for Firefox, and I have 4 POST inputs:</p> <pre><code>login=mylogin password=mypassword Button_DoLogin.x=33 Button_DoLogin.y=6 </code></pre> <p>I tried to use curl again using</p> <pre><code>curl.exe --data 'login=mylogin&amp;password=mypassword&amp;Button_DoLogin.x=33&amp;Button_DoLogin.y=6' www.centralgreen.com.sg/login.php?ccsForm=Login </code></pre> <p>But the login apparently doesn't go through (the output of this command is the same form, filled with only the password, and an error message <strong>The value in field Username is required.</strong>)</p> <p>Here is the full list of info I get from Tamper</p> <pre><code>Host centralgreen.com.sg User-Agent Mozilla/5.0 (Windows NT 5.1; rv:2.0) Gecko/20100101 Firefox/4.0 Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept Language en-us,en;q=0.5 Accept Encoding gzip, deflate Accept Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep Alive 115 Connection keep-alive Referer http://centralgreen.com.sg/login.php Cookie PHPSESSID=65fbxxxxxxx02694e3a72xxxxxxxx; Valley_ParkLogin=04E203A459FCxxxxxxxA2DCD9AAE5B9678G08C04F1952155E2482xxxxxxxxxxxxx </code></pre> <p>Is there anything I do wrong? How can I pass the login through the POST form?</p>
6,728,373
1
0
null
2011-07-18 03:22:07.93 UTC
5
2015-08-07 03:43:26.433 UTC
2015-08-07 03:43:26.433 UTC
null
2,754,166
null
482,711
null
1
10
curl|authentication
47,960
<p>Try using the <code>-F</code> option instead of <code>--data</code>. </p> <p><a href="http://curl.haxx.se/docs/manpage.html#-F" rel="noreferrer">http://curl.haxx.se/docs/manpage.html#-F</a></p> <p>Basically, this changes the content type header to:</p> <pre><code>Content-Type: multipart/form-data </code></pre> <p>This may give you a better result.</p>
6,863,147
MATLAB: how to display UTF-8-encoded text read from file?
<p>The gist of my question is this:</p> <blockquote> <p>How can I display Unicode characters in Matlab's GUI (OS X) so that they are properly rendered?</p> </blockquote> <p>Details:</p> <p>I have a table of strings stored in a file, and some of these strings contain UTF-8-encoded Unicode characters. I have tried many different ways (too many to list here) to display the contents of this file in the MATLAB GUI, without success. For example:</p> <pre><code>&gt;&gt; fid = fopen('/Users/kj/mytable.txt', 'r', 'n', 'UTF-8'); &gt;&gt; [x, x, x, enc] = fopen(fid); enc enc = UTF-8 &gt;&gt; tbl = textscan(fid, '%s', 35, 'delimiter', ','); &gt;&gt; tbl{1}{1} ans = ÎÎÎÎÎΠΣΦΩαβγδεζηθικλμνξÏÏÏÏÏÏÏÏÏÏ &gt;&gt; </code></pre> <p>As it happens, if I paste the string directly into the MATLAB GUI, the pasted string is displayed properly, which shows that the GUI is not fundamentally incapable of displaying these characters, but once MATLAB reads it in, it longer displays it correctly. For example:</p> <pre><code>&gt;&gt; pasted = 'ΓΔΘΛΞΠΣΦΩαβγδεζηθικλμνξπρςστυφχψω' pasted = &gt;&gt; </code></pre> <p>Thanks!</p>
6,872,642
1
0
null
2011-07-28 17:31:29.417 UTC
9
2011-07-29 11:50:27.727 UTC
2011-07-29 11:50:27.727 UTC
null
330,644
null
559,827
null
1
25
macos|user-interface|matlab|unicode|utf-8
21,933
<p>I present below my findings after doing some digging... Consider these test files:</p> <h3>a.txt</h3> <pre><code>ΓΔΘΛΞΠΣΦΩαβγδεζηθικλμνξπρςστυφχψω </code></pre> <h3>b.txt</h3> <pre><code>தமிழ் </code></pre> <p>First, we read files:</p> <pre><code>%# open file in binary mode, and read a list of bytes fid = fopen('a.txt', 'rb'); b = fread(fid, '*uint8')'; %'# read bytes fclose(fid); %# decode as unicode string str = native2unicode(b,'UTF-8'); </code></pre> <p>If you try to print the string, you get a bunch of nonsense:</p> <pre><code>&gt;&gt; str str = </code></pre> <p>Nonetheless, <code>str</code> does hold the correct string. We can check the Unicode code of each character, which are as you can see outside the ASCII range (last two are the non-printable CR-LF line endings):</p> <pre><code>&gt;&gt; double(str) ans = Columns 1 through 13 915 916 920 923 926 928 931 934 937 945 946 947 948 Columns 14 through 26 949 950 951 952 953 954 955 956 957 958 960 961 962 Columns 27 through 35 963 964 965 966 967 968 969 13 10 </code></pre> <p>Unfortunately, MATLAB seems unable to display this Unicode string in a GUI on its own. For example, all these fail:</p> <pre><code>figure text(0.1, 0.5, str, 'FontName','Arial Unicode MS') title(str) xlabel(str) </code></pre> <p>One trick I found is to use the embedded Java capability:</p> <pre><code>%# Java Swing label = javax.swing.JLabel(); label.setFont( java.awt.Font('Arial Unicode MS',java.awt.Font.PLAIN, 30) ); label.setText(str); f = javax.swing.JFrame('frame'); f.getContentPane().add(label); f.pack(); f.setVisible(true); </code></pre> <p><img src="https://i.stack.imgur.com/HSTDq.png" alt="enter image description here"></p> <hr> <p>As I was preparing to write the above, I found an alternative solution. We can use the <code>DefaultCharacterSet</code> undocumented feature and set the charset to <code>UTF-8</code> (on my machine, it is <code>ISO-8859-1</code> by default):</p> <pre><code>feature('DefaultCharacterSet','UTF-8'); </code></pre> <p>Now with a proper font (you can change the font used in the Command Window from <code>Preferences &gt; Font</code>), we can print the string in the prompt (note that DISP is still incapable of printing Unicode):</p> <pre><code>&gt;&gt; str str = ΓΔΘΛΞΠΣΦΩαβγδεζηθικλμνξπρςστυφχψω &gt;&gt; disp(str) ΓΔΘΛΞΠΣΦΩαβγδεζηθικλμνξπÏςστυφχψω </code></pre> <p>And to display it in a GUI, UICONTROL should work (under the hood, I think it is really a Java Swing component):</p> <pre><code>uicontrol('Style','text', 'String',str, ... 'Units','normalized', 'Position',[0 0 1 1], ... 'FontName','Arial Unicode MS', 'FontSize',30) </code></pre> <p><img src="https://i.stack.imgur.com/yvrkv.png" alt="enter image description here"></p> <p>Unfortunately, TEXT, TITLE, XLABEL, etc.. are still showing garbage:</p> <p><img src="https://i.stack.imgur.com/8uSuf.png" alt="enter image description here"></p> <hr> <p>As a side note: It is difficult to work with m-file sources containing Unicode characters in the MATLAB editor. I was using <a href="http://notepad-plus-plus.org/" rel="noreferrer">Notepad++</a>, with files encoded as <em>UTF-8 without BOM</em>.</p>
42,593,604
Using external javascript libraries in angular 2 lazy loaded module, not index.html
<p>So I want to include an external JS library, a carousel slider in the is case, to my Angular 2 app. I have seen a lot of tutorials that show how it can be added I have done that successfully, but referencing the library on index.html.</p> <p>This as you will know, will load the library every time the app is visited, regardless of whether they visit the components needing the carousel. Since it's pretty hefty, I only want to load it where it is needed, which is inside a lazy loaded module.</p> <p>I haven't tried, but I'm sure I could just chuck the script tag in the component that uses it, but this doesn't feel right to me. </p> <p>There must be a <em>right</em> way. What is it!?</p> <p>Thanks!</p>
42,593,976
2
1
null
2017-03-04 07:52:07.13 UTC
10
2017-03-13 14:26:30.847 UTC
null
null
null
null
6,192,794
null
1
20
angular|angular-cli|external-js
6,512
<p>We are doing this in one of our projects to load js libraries dynamically</p> <p><strong>ScriptStore.ts</strong> that will contain the <strong>path</strong> of the script either locally or on a remote server and a <strong>name</strong> that will be used to load the script dynamically</p> <pre><code> interface Scripts { name: string; src: string; } export const ScriptStore: Scripts[] = [ {name: 'filepicker', src: 'https://api.filestackapi.com/filestack.js'}, { name: 'rangeSlider', src: '../../../assets/js/ion.rangeSlider.min.js' } ]; </code></pre> <p><strong>script.service.ts</strong> is an injectable service that will handle the loading of script, copy <code>script.service.ts</code> as it is</p> <pre><code>import {Injectable} from "@angular/core"; import {ScriptStore} from "./script.store"; declare var document: any; @Injectable() export class Script { private scripts: any = {}; constructor() { ScriptStore.forEach((script: any) =&gt; { this.scripts[script.name] = { loaded: false, src: script.src }; }); } load(...scripts: string[]) { var promises: any[] = []; scripts.forEach((script) =&gt; promises.push(this.loadScript(script))); return Promise.all(promises); } loadScript(name: string) { return new Promise((resolve, reject) =&gt; { //resolve if already loaded if (this.scripts[name].loaded) { resolve({script: name, loaded: true, status: 'Already Loaded'}); } else { //load script let script = document.createElement('script'); script.type = 'text/javascript'; script.src = this.scripts[name].src; if (script.readyState) { //IE script.onreadystatechange = () =&gt; { if (script.readyState === "loaded" || script.readyState === "complete") { script.onreadystatechange = null; this.scripts[name].loaded = true; resolve({script: name, loaded: true, status: 'Loaded'}); } }; } else { //Others script.onload = () =&gt; { this.scripts[name].loaded = true; resolve({script: name, loaded: true, status: 'Loaded'}); }; } script.onerror = (error: any) =&gt; resolve({script: name, loaded: false, status: 'Loaded'}); document.getElementsByTagName('head')[0].appendChild(script); } }); } } </code></pre> <p>Inject this <code>ScriptService</code> wherever you need it and load js libs like this </p> <pre><code>this.script.load('filepicker', 'rangeSlider').then(data =&gt; { console.log('script loaded ', data); }).catch(error =&gt; console.log(error)); </code></pre>
42,767,733
Inserting date into PostgreSQL: Columns from and to
<p>I can't insert a <code>date</code> into a PostgreSQL 9.6 table.</p> <p>This is the INSERT Query:</p> <pre><code>INSERT INTO rates (idproperty, from, to, price) VALUES (1, '2017-03-14', '2017-04-30', 130); </code></pre> <p>And that's the result:</p> <pre><code>ERROR: syntax error at or near "from" LINE 1: INSERT INTO rates (idproperty, from, to, price) </code></pre> <p>The columns <code>from</code> and <code>to</code> are defined with the data type <code>date</code>.</p> <p>Thanks </p>
42,767,817
3
2
null
2017-03-13 15:41:33.967 UTC
2
2019-09-13 12:54:39.18 UTC
2019-09-13 12:54:39.18 UTC
null
3,402,754
null
7,064,476
null
1
10
database|postgresql
73,026
<p><code>from</code> and <code>to</code> are reserved words in PostgreSQL. You need to escape them with <code>"</code>:</p> <pre><code>-- This fails: test=# SELECT from FROM rates; ERROR: syntax error at or near "FROM" LINE 1: SELECT from FROM rates; ^ -- This works: test=# SELECT "from" FROM rates; from ------ (0 rows) </code></pre> <p>See list of reserved words: <a href="https://www.postgresql.org/docs/current/static/sql-keywords-appendix.html" rel="noreferrer">https://www.postgresql.org/docs/current/static/sql-keywords-appendix.html</a></p>
5,741,518
Reading each column from csv file
<p>I want to read each column of a csv file and do some modification before storing them into table.</p> <p>I have a csv files as :</p> <pre><code>"1";"testOne";"ValueOne" "2";"testTwo";"ValueTwo" "3";"testThree";"ValueThree" </code></pre> <p>Here I want to read the first value "1" and then store it somewhere in a varaible and do something with this value, and similary with the others. However currently I can read the whole file, but could not find the way to access individual columns in a row.</p> <p>Thank you.</p>
5,741,588
3
0
null
2011-04-21 08:30:45.803 UTC
8
2016-07-20 20:27:34.76 UTC
null
null
null
null
638,517
null
1
6
python|csv
62,668
<p>Python has a built-in <a href="http://docs.python.org/library/csv.html">csv</a> module.</p> <pre><code>import csv with open('some.csv', 'rb') as f: reader = csv.reader(f, delimiter=';') for row in reader: print row[0] </code></pre>
5,779,351
Event Sourcing Resources
<p>Looking for some suggestions for useful discussion groups, articles, success stories, reference apps, and tooling (.Net) on the subject of event sourcing.</p> <p>I am already familiar with:</p> <p>Fowler's article: <a href="http://martinfowler.com/eaaDev/EventSourcing.html" rel="nofollow noreferrer">http://martinfowler.com/eaaDev/EventSourcing.html</a></p> <p>Greg Young's Article (with downloaded docs in the comments): <a href="http://codebetter.com/gregyoung/2010/02/20/why-use-event-sourcing/" rel="nofollow noreferrer">http://codebetter.com/gregyoung/2010/02/20/why-use-event-sourcing/</a></p> <p>Greg Young's excellent (draft) article on DDDD: <a href="https://web.archive.org/web/20101025095403if_/http://abdullin.com/storage/uploads/2010/04/2010-04-16_DDDD_Drafts_by_Greg_Young.pdf" rel="nofollow noreferrer">http://abdullin.com/storage/uploads/2010/04/2010-04-16_DDDD_Drafts_by_Greg_Young.pdf</a></p> <p>Anything else I should be reading and looking at?</p>
5,780,631
3
0
null
2011-04-25 14:28:41.35 UTC
16
2018-05-27 11:25:28.643 UTC
2018-02-27 13:34:00.527 UTC
null
303,290
null
151,084
null
1
27
c#|.net|cqrs|event-sourcing
10,478
<p>You should look at <a href="https://github.com/joliver/EventStore" rel="nofollow noreferrer">this implementation of an EventStore</a> as well as <a href="https://github.com/gregoryyoung/m-r" rel="nofollow noreferrer">these</a> <a href="https://github.com/MarkNijhof/Fohjin" rel="nofollow noreferrer">two</a> implementations of mini-systems based on CQRS with event sourcing.</p> <p>EDIT (2011-05-18): <a href="https://github.com/elliotritchie/NES" rel="nofollow noreferrer">NES (.Net Event Sourcing)</a> is yet another implementation available to reference.</p> <p>It may also be worth following the <a href="http://groups.google.com/group/dddcqrs/topics" rel="nofollow noreferrer">Google</a> and <a href="http://tech.groups.yahoo.com/group/domaindrivendesign/" rel="nofollow noreferrer">Yahoo</a> groups related to CQRS &amp; Distributed DDD.</p>
32,491,360
Deserializing Json-Api with Rails Strong Parameters
<p>I am using Active Model Serializers 0.10.x with EmberCLI and Rails while trying to have the Json-Api as the Adapter. GET requests are working, but deserialization for the Active Model is not even though I tried to implement the rails strong_parameters solution described by jimbeaudoin <a href="https://github.com/rails-api/active_model_serializers/issues/1061" rel="noreferrer">here</a>.</p> <p>My latest attempt in saving a comment:</p> <p><strong>Payload:</strong></p> <pre><code>{"data":{ "attributes": {"soft_delete":false,"soft_delete_date":null,"text":"hjfgfhjghjg","hidden":false,"empathy_level":0}, "relationships":{ "user":{"data":{"type":"users","id":"1"}}, "post":{"data":{"type":"posts","id":"1"}}},"type":"comments"}} </code></pre> <p><strong>Console Output:</strong></p> <pre><code>Completed 400 Bad Request in 13ms (ActiveRecord: 8.6ms) ActionController::ParameterMissing (param is missing or the value is empty: data): </code></pre> <p><strong>Comments Controller:</strong></p> <pre><code>class Api::V1::CommentsController &lt; MasterApiController respond_to :json ... def create render json: Comment.create(comment_params) end ... def comment_params #Deserialization issues... Waiting for #950 https://github.com/rails-api/active_model_serializers/pull/950 params.require(:data).require(:attributes).permit(:text, :user_id, :post_id, :empathy_level, :soft_delete_date, :soft_delete, :hidden) end end </code></pre> <p>Noting that if I set the parameters to only <strong>params.permit(...)</strong>, the server saves it with everything null (I did not set any constraints on the comments model for now):</p> <pre><code>data: {id: "9", type: "comments",…} attributes: {soft_delete: null, soft_delete_date: null, text: null, hidden: null, empathy_level: null} id: "9" relationships: {post: {data: null}, user: {data: null}} type: "comments" </code></pre> <p>You can access the full code <a href="https://github.com/Deovandski/fakktion" rel="noreferrer">here</a>. </p>
35,541,693
4
1
null
2015-09-10 00:58:26.823 UTC
9
2017-05-30 13:33:30.103 UTC
2017-05-30 13:32:48.1 UTC
null
4,830,578
null
4,830,578
null
1
23
active-model-serializers
7,276
<h3>Update #2: For AMS &gt;= 0.10.2, please check other answers.</h3> <h3>Update #1: Answer is still valid for AMS <strong>0.10.1</strong>.</h3> <p>If you use <strong>0.10.0.rc4</strong>, you can now use the Deserialization implementation described on Active Model Serializers <a href="https://github.com/rails-api/active_model_serializers/pull/1248" rel="nofollow noreferrer">#1248</a>.</p> <pre><code>def post_params ActiveModel::Serializer::Adapter::JsonApi::Deserialization.parse(params.to_h) // or (params.to_unsafe_h) in some cases like in my example below... end </code></pre> <p><strong>Bonus:</strong> If you use Ember Data, then you can see an example implementation on my <a href="https://github.com/Deovandski/fakktion" rel="nofollow noreferrer">Fakktion Github repo</a>.</p>
6,136,200
Difference between Style and ControlTemplate
<p>Could you tell me what is the main differences between Style and ControlTemplate ? When or why to use one or the other ?</p> <p>To my eyes, they are exactly the very <strong>same</strong>. As I am beginner I think that I am wrong, thus my question.</p>
6,136,293
5
2
null
2011-05-26 09:12:50.873 UTC
33
2020-10-23 15:34:18.94 UTC
2018-02-19 20:47:29.63 UTC
null
563,088
null
356,440
null
1
72
c#|.net|wpf|xaml
36,954
<p>You can think of a Style as a convenient way to apply a set of property values to more than one element. You can change the default appearance by setting properties, such as FontSize and FontFamily, on each TextBlock element directly. However, if you want your TextBlock elements to share some properties, you can create a Style in the Resources section of your XAML file.</p> <p>On the other hand, a ControlTemplate specifies the visual structure and visual behavior of a control. You can customize the appearance of a control by giving it a new ControlTemplate. When you create a ControlTemplate, you replace the appearance of an existing control without changing its functionality. For example, you can make the buttons in your application round instead of the default square shape, but the button will still raise the Click event.</p> <p>Ref: <a href="http://msdn.microsoft.com/en-us/library/ms745683.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms745683.aspx</a></p>
5,915,325
Open Google Chrome from VBA/Excel
<p>I'm trying to open a Chrome browser from VBA. I understand Chrome does not support ActiveX settings so I'm curious if theres any work-arounds?</p> <pre><code>Dim ie As Object Set ie = CreateObject("ChromeTab.ChromeFrame") ie.Navigate "google.ca" ie.Visible = True </code></pre>
5,915,643
6
1
null
2011-05-06 18:08:36.653 UTC
12
2021-03-22 06:02:17.603 UTC
2018-07-09 19:34:03.733 UTC
user2140173
-1
null
740,363
null
1
20
vba|google-chrome|excel
249,038
<pre><code>shell("C:\Users\USERNAME\AppData\Local\Google\Chrome\Application\Chrome.exe -url http:google.ca") </code></pre>
5,698,284
In my .vimrc, how can I check for the existence of a color scheme?
<p>In a <code>.vimrc</code>, is it possible to load a color scheme only if it exists?</p>
5,703,164
6
0
null
2011-04-18 03:41:59.077 UTC
1
2019-07-10 12:24:33.487 UTC
2011-04-18 04:00:01.473 UTC
null
527,623
null
527,623
null
1
58
vim|color-scheme
13,245
<p>Using <code>:colorscheme</code> in a <em>try-catch</em> as <a href="https://stackoverflow.com/questions/5698284/in-my-vimrc-how-can-i-check-for-the-existence-of-a-color-scheme/5702498#5702498">Randy has done</a> may be enough if you just want to load it if it exists and do something else otherwise. If you are not interested in the <em>else</em> part, a simple <code>:silent! colorscheme</code> is enough.</p> <p>Otherwise, <a href="http://vimhelp.appspot.com/eval.txt.html#globpath%28%29" rel="noreferrer"><code>globpath()</code></a> is the way to go. You may, then, check each path returned with <code>filereadable()</code> if you really wish to.</p> <pre><code>" {rtp}/autoload/has.vim function! has#colorscheme(name) abort let pat = 'colors/'.a:name.'.vim' return !empty(globpath(&amp;rtp, pat)) endfunction " .vimrc if has#colorscheme('desert') ... </code></pre> <p>EDIT: <code>filereadable($HOME.'/.vim/colors/'.name.'.vim')</code> may seem simple and it's definitively attractive, but this is not enough if the colorscheme we're looking for is elsewhere. Typically if it has been installed in another directory thanks to a plugin manager. In that case the only reliable way is to check in the vim <a href="http://vimhelp.appspot.com/options.txt.html#%27runtimepath%27" rel="noreferrer"><code>'runtimepath'</code></a> (a.k.a. <code>'rtp'</code>). Hence <code>globpath()</code>. Note that <code>:colorscheme name</code> command searches in <code>{rtp}/colors/{name}.vim</code>.</p>
5,617,211
What is "git remote add ..." and "git push origin master"?
<p>Quite often, Git and <a href="https://en.wikipedia.org/wiki/Ruby_on_Rails" rel="noreferrer">Ruby on Rails</a> looks like magic... such as in the <a href="http://ruby.railstutorial.org/chapters/beginning#sec:version_control" rel="noreferrer">first chapter of Ruby on Rails 3 Tutorial book</a>, it talks about Git:</p> <pre><code>git remote add origin [email protected]:peter/first_app.git git push origin master </code></pre> <p>And it pretty much says &quot;it just works&quot; without saying too much about what they are and start talking about branching. Searching on the Internet shows that <code>git remote add</code> is to add a &quot;short name&quot;, such as <code>origin</code>, and it can be any name as well, which is like an alias to a URL.</p> <p>And <code>origin</code> is the usual path of where the remote repository points to (in <a href="http://git-scm.com/book/en/Git-Basics-Working-with-Remotes" rel="noreferrer">http://git-scm.com/book/en/Git-Basics-Working-with-Remotes</a> under &quot;Adding Remote Repositories&quot;).</p> <p>So why is the URL not <code>git://[email protected]/peter/first_app.git</code>, but in the other syntax -- what syntax is it? Why must it end with <code>.git</code>? I tried not using <code>.git</code> at the end and it works too. If not <code>.git</code>, what else can it be? The <code>git</code> in <code>[email protected]</code> seems to be a user account on the Git server?</p> <p>Also, why does it need to be so verbose to use <code>git push origin master</code>? Can't the default be origin and master? I found that the first time, the <code>origin master</code> is needed, but after a small edit and commit, then <code>git push</code> is all it needs (no need <code>origin master</code>). Can somebody who knows what is going on give some details?</p> <p>Sometimes it feels like a lot of magic without explanation... and sometimes the person using it is so confident and when asked why, can't explain it, and respond with something like &quot;that's the way it is&quot;. Sometimes very practical and pragmatic. It is not bad to be practical, but probably not practical to the point to not know what is going on.</p>
5,617,350
6
0
null
2011-04-11 05:43:44.833 UTC
139
2021-07-12 19:41:03.47 UTC
2021-06-13 16:40:18.707 UTC
null
63,550
null
325,418
null
1
317
git|github
362,464
<p>Git is like Unix. It is user-friendly, but it is picky about its friends. It's about as powerful and as user-friendly as a shell pipeline.</p> <p>That being said, once you understand its paradigms and concepts, it has the same Zenlike clarity that I've come to expect from Unix command-line tools. You should consider taking some time off to read one of the many good Git tutorials available online. The <em><a href="https://git-scm.com/book/en/v2" rel="noreferrer">Pro Git</a></em> book is a good place to start.</p> <p>To answer your first question.</p> <ol> <li><p>What is <code>git remote add ...</code>?</p> <p>As you probably know, Git is a distributed version control system. Most operations are done locally. To communicate with the outside world, Git uses what are called <em>&quot;remotes&quot;</em>. These are repositories other than the one on your local disk which you can <em>push</em> your changes into (so that other people can see them) or <em>pull</em> from (so that you can get others changes). The command <code>git remote add origin [email protected]:peter/first_app.git</code> creates a new remote called <code>origin</code> located at <code>[email protected]:peter/first_app.git</code>. Once you do this, in your push commands, you can push to <em>origin</em> instead of typing out the whole URL.</p> </li> <li><p>What is <code>git push origin master</code>?</p> <p>This is a command that says &quot;push the commits in the local branch named <em>master</em> to the remote named <em>origin</em>&quot;. Once this is executed, all the stuff that you last synchronised with <em>origin</em> will be sent to the remote repository and other people will be able to see them there.</p> </li> </ol> <p>Now about transports (i.e., what <code>git://</code>) means. Remote repository URLs can be of many types (<code>file://</code>, <code>https://</code>, etc.). Git simply relies on the authentication mechanism provided by the transport to take care of permissions and stuff. This means that for <code>file://</code> URLs, it will be Unix file permissions, etc. The <code>git://</code> scheme is asking Git to use its own internal transport protocol, which is optimised for sending Git changesets around. As for the exact URL, it's the way it is because of the way GitHub has set up its Git server.</p> <p>Now the verbosity. The command you've typed is the general one. It's possible to tell Git something like &quot;the branch called <em>master</em> over here is local mirror of the branch called <em>foo</em> on the remote called <em>bar</em>&quot;. In Git speak, this means that <em>master</em> <em><strong>tracks</strong></em> <em>bar/foo</em>. When you clone for the first time, you will get a branch called <em>master</em> and a remote called <em>origin</em> (where you cloned from) with the local master set to track the master on origin.</p> <p>Once this is set up, you can simply say <code>git push</code> and it'll do it. The longer command is available in case you need it (e.g., <code>git push</code> might push to the official public repository and <code>git push review master</code> can be used to push to a separate remote which your team uses to review code). You can set your branch to be a tracking branch using the <code>--set-upstream</code> option of the <code>git branch</code> command.</p> <p>I've felt that Git (unlike most other applications I've used) is better understood from the inside out. Once you understand how data is stored and maintained inside the repository, the commands and what they do become crystal clear. I do agree with you that there's some elitism amongst many Git users, but I also found that with Unix users once upon a time, and it was worth ploughing past them to learn the system. Good luck!</p>
14,245,507
Count number of populated cells in range
<p>How do I count the number of populated cells (with text/number or combinations of text+number)?</p> <p>I tried <code>=countif(A2:A2000,1=1)</code> (with a general criteria, e.g. 1=1 always) but shows zero (0) for a text column.</p>
14,246,051
4
2
null
2013-01-09 20:04:28.227 UTC
null
2020-03-20 04:31:40.38 UTC
2020-03-20 04:31:40.38 UTC
null
-1
null
1,464,026
null
1
2
excel|vba|excel-formula
102,266
<p>The formula is <code>=COUNTA(A2:A2000)</code> : non-blank cells are counted.</p>
24,594,507
Exporting non-S3-methods with dots in the name using roxygen2 v4
<p>Since <code>roxygen2</code> version <code>4.0.0</code>, the <code>@S3method</code> tag has been deprecated in favour of using <code>@export</code>.</p> <p>The package now tries to detect if a function is an S3 method, and automatically adds the line <code>S3method(function,class)</code> to the <code>NAMESPACE</code> file if it think it is one.</p> <p>The problem is that if a function is not an S3 method but its name contains a <code>.</code> then roxygen sometimes makes a mistake and adds the line when it shouldn't. </p> <p>Is there a way to tell roxygen that a function is not an S3 method?</p> <hr> <p>As requested, here's a reproducible example.</p> <p>I have a package that imports <code>R.oo</code>, with a function named <code>check.arg</code>.</p> <pre><code>library(roxygen2) package.skeleton("test") cat("Imports: R.oo\n", file = "test/DESCRIPTION", append = TRUE) writeLines( "#' Check an argument #' #' Checks an argument. #' @param ... Some arguments. #' @return A value. #' @export check.arg &lt;- function(...) 0", "test/R/check.arg.R" ) roxygenise("test") </code></pre> <p>Now the namespace contains the line <code>S3method(check,arg)</code>.</p> <p><code>check</code> is an S3 generic in <code>R.oo</code>, so roxygen is trying to be smart and guessing that I want <code>check.arg</code> to be an S3 method. Unfortunately, these functions are unrelated, so I don't. </p> <p>(To preempt suggestions that I just rename <code>check.arg</code>: this is legacy code written by others, and I've created a <code>checkArg</code> replacement, but I need to leave <code>check.arg</code> as a deprecated function for compatibility.)</p>
24,607,763
2
2
null
2014-07-06 09:36:04.317 UTC
8
2014-12-11 09:25:38.24 UTC
2014-07-07 09:52:07.433 UTC
null
134,830
null
134,830
null
1
22
r|roxygen2
1,580
<p>As Mr Flick commented, appending the full function name to the roxygen line works correctly. If I change the line to:</p> <pre><code>#' @export check.arg </code></pre> <p>then the <code>NAMESPACE</code> file contains:</p> <pre><code>export(check.arg) </code></pre>
9,566,633
How to use onConfigurationChanged() and newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE in android 2.3.3
<p>I am using <code>onConfigurationChanged()</code>. In that, when I am changing from LandScape to Portrait, it is calling <code>if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)</code> and shifting to Portrait from LandScape. But when I am changing from Portrait to Land-Scape, it is not changing to LandScape because it is calling <code>if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)</code> so, it is not changing from LandScape to Portrait. Please help.</p> <pre><code>public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); //int orientation = this.getResources().getConfiguration().orientation; if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { Log.d("Entered to change as Portrait ","PPPPPPPPPPPPPPPPP"); setContentView(R.layout.settings); } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.d("Entered to change as LandScape ","LLLLLLLLLLLLLLLLLLLL"); setContentView(R.layout.settings); } } </code></pre>
9,733,622
6
0
null
2012-03-05 12:27:31.083 UTC
10
2018-01-30 11:19:24.397 UTC
2012-03-06 09:22:57.957 UTC
null
1,108,213
null
1,201,479
null
1
39
android
77,794
<p>Just write the below code into <code>onConfigurationChanged</code> method and test </p> <pre><code>if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){ Log.e("On Config Change","LANDSCAPE"); }else{ Log.e("On Config Change","PORTRAIT"); } </code></pre> <p>and write the <code>android:configChanges="keyboardHidden|orientation"</code> into your manifiest file like this</p> <pre><code>&lt;activity android:name="TestActivity" android:configChanges="keyboardHidden|orientation"&gt; </code></pre> <p>it's working at my side, i hope it helps you.</p> <p>If you're on tablet also add <code>|screenSize</code> to <code>android:configChanges</code></p>
30,976,123
Multiple return statements without compiler error
<p>This was an interview question:</p> <pre><code>public class Demo { public static void main(String[] args) { System.out.println(foo()); } static String foo() { try { return "try ..."; } catch (Exception e) { return "catch ..."; } finally { return "finally ..."; //got as result } } } </code></pre> <p>My question is why there are no compile time errors. When I have the return statement in my <code>finally</code> block, it is bound to return from <code>finally</code> instead of <code>try</code> and <code>catch</code> block. I tried to compile this code with <code>-Xlint</code> option, it gives a warning as.</p> <pre><code>warning: [finally] finally clause cannot complete normally </code></pre>
30,977,317
8
1
null
2015-06-22 09:13:30.013 UTC
4
2015-08-01 08:43:46.663 UTC
2015-07-05 18:10:09.627 UTC
null
1,391,249
user2575725
null
null
1
65
java|compiler-errors|return|try-catch|try-catch-finally
4,009
<p>It does not give a compilation error because it is allowed by the Java Language Specification. However, it gives a warning message because including a <code>return</code> statement in the <code>finally</code> block is usually a bad idea.</p> <p>What happens in your example is the following. The <code>return</code> statement in the <code>try</code> block is executed. However, the <code>finally</code> block must always be executed so it is executed after the <code>catch</code> block finishes. The <code>return</code> statement occurring there overwrites the result of the previous <code>return</code> statement, and so the method returns the second result.</p> <p>Similarly a <code>finally</code> block usually should not throw an exception. That's why the warning says that the <code>finally</code> block should complete normally, that is, without <code>return</code> or throwing an exception.</p>
34,331,351
How to resize animated GIF with HTML/CSS?
<p>I am working on an exam project.</p> <p>I have only just now noticed that my animated GIF that the webpage relies heavily upon does not resize in accordance with neither container or window width. I am using Bootstrap 3 framework.</p> <p>How is it possible to resize an animated GIF with CSS/HTML? And if that's not possible, what can I use to achieve this as easily as possible?</p>
34,331,484
1
1
null
2015-12-17 09:46:58.857 UTC
1
2021-07-28 10:42:04.447 UTC
2018-04-12 23:35:07.937 UTC
null
472,495
null
2,304,993
null
1
4
html|css|twitter-bootstrap|gif
56,468
<p>You can do this:</p> <p><strong>CSS</strong></p> <pre><code>img.animated-gif{ width: 120px; height: auto; } </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;img class="animated-gif" src="https://media.giphy.com/media/Wq6DnHvHchrTG/giphy.gif"&gt; </code></pre> <p>Note: Adjust the width size as you want. Beware never resize more than the actual size, it will be pixelated.</p> <p><strong><a href="https://jsfiddle.net/luispa/kd4kjdck/95/" rel="noreferrer">DEMO HERE</a></strong></p>
22,628,981
What is the difference between destroy() and delete() methods in Laravel?
<p>I'm having a minor issue with Laravel 4. I'd like to use the <code>delete()</code> method on a record but for some reason it doesn't actually delete the record. <code>destroy()</code> does, though, so my code is good. Also, if I pass <code>Teetime::where('date', '=', $formattedDate)-&gt;count()</code> to my view I get one which is correct. What's the problem?</p> <pre><code> if($action=="delete") { $teetime = Teetime::where('date', '=', $formattedDate)-&gt;firstOrFail(); // for some reason $teetime-&gt;delete() doesn't work Teetime::destroy($teetime-&gt;id); } </code></pre>
22,629,013
2
1
null
2014-03-25 08:27:56.457 UTC
12
2021-12-17 17:23:48.207 UTC
2016-11-28 11:21:29.593 UTC
null
323,041
user347284
null
null
1
44
php|laravel|laravel-4|eloquent
70,451
<ul> <li><code>destroy</code> is correct method for removing an entity directly (via object or model).</li> </ul> <p>Example:</p> <pre><code>$teetime = Teetime::where('date', '=', $formattedDate)-&gt;firstOrFail(); $teetime-&gt;destroy(); </code></pre> <ul> <li><code>delete</code> can only be called in query builder</li> </ul> <p>Example: </p> <pre><code>$teetime = Teetime::where('date', '=', $formattedDate)-&gt;delete(); </code></pre> <p>From documentation: </p> <h1>Deleting An Existing Model By Key</h1> <pre><code>User::destroy(1); User::destroy(array(1, 2, 3)); User::destroy(1, 2, 3); </code></pre> <p>Of course, you may also run a delete query on a set of models:</p> <pre><code>$affectedRows = User::where('votes', '&gt;', 100)-&gt;delete(); </code></pre> <p>More info: <a href="http://laravel.com/docs/eloquent">http://laravel.com/docs/eloquent</a></p>
7,266,218
how to check if NSString = a specific string value?
<p>Hi I am woundering if you can check to see if a NSString equals a specific value say for instance a name of a person?</p> <p>I am thinking along the lines of</p> <pre><code>if (mystring == @"Johns"){ //do some stuff in here } </code></pre>
7,266,238
2
0
null
2011-09-01 04:46:33.59 UTC
10
2015-06-08 13:41:26.303 UTC
null
null
null
null
807,400
null
1
70
iphone|ios|nsstring
46,647
<pre><code>if ([mystring isEqualToString:@"Johns"]){ //do some stuff in here } </code></pre>
23,354,124
How can I "unpivot" specific columns from a pandas DataFrame?
<p>I have a pandas DataFrame, eg:</p> <pre><code>x = DataFrame.from_dict({'farm' : ['A','B','A','B'], 'fruit':['apple','apple','pear','pear'], '2014':[10,12,6,8], '2015':[11,13,7,9]}) </code></pre> <p>ie:</p> <pre><code> 2014 2015 farm fruit 0 10 11 A apple 1 12 13 B apple 2 6 7 A pear 3 8 9 B pear </code></pre> <p>How can I convert it to this: ?</p> <pre><code> farm fruit value year 0 A apple 10 2014 1 B apple 12 2014 2 A pear 6 2014 3 B pear 8 2014 4 A apple 11 2015 5 B apple 13 2015 6 A pear 7 2015 7 B pear 9 2015 </code></pre> <p>I have tried <code>stack</code> and <code>unstack</code> but haven't been able to make it work.</p> <p>Thanks!</p>
23,354,240
1
1
null
2014-04-29 01:48:25.833 UTC
10
2014-04-29 02:05:49.027 UTC
null
null
null
null
905,720
null
1
33
python|pandas|pivot-table
33,340
<p>This can be done with <code>pd.melt()</code>:</p> <pre><code># value_name is 'value' by default, but setting it here to make it clear pd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value') </code></pre> <p>Result:</p> <pre><code> farm fruit year value 0 A apple 2014 10 1 B apple 2014 12 2 A pear 2014 6 3 B pear 2014 8 4 A apple 2015 11 5 B apple 2015 13 6 A pear 2015 7 7 B pear 2015 9 [8 rows x 4 columns] </code></pre> <p>I'm not sure how common "melt" is as the name for this kind of operation, but that's what it's called in R's <code>reshape2</code> package, which probably inspired the name here.</p>
18,939,282
Why are some of the logical operators so slow?
<p>While trying to optimize my code, I found some <code>logical</code> operations were slower than I expected when compared to similar operations on <code>integer</code> or <code>numeric</code>.</p> <p>So I went onto rewriting basic boolean operators <code>!</code>, <code>&amp;</code>, <code>|</code>, <code>xor</code> as follows:</p> <pre><code>my.not &lt;- function(x) as.logical(1L - as.integer(x)) my.and &lt;- function(e1, e2) as.logical(as.integer(e1) * as.integer(e2)) my.or &lt;- function(e1, e2) as.logical(as.integer(e1) + as.integer(e2)) my.xor &lt;- function(e1, e2) as.logical(as.integer(e1) + as.integer(e2) == 1L) </code></pre> <p>Testing that everything works as expected:</p> <pre><code>a &lt;- sample(c(TRUE, FALSE), 1e6, TRUE) b &lt;- sample(c(TRUE, FALSE), 1e6, TRUE) identical(!a, my.not(a)) # TRUE identical(a &amp; b, my.and(a, b)) # TRUE identical(a | b, my.or(a, b)) # TRUE identical(xor(a, b), my.xor(a, b)) # TRUE </code></pre> <p>Now benchmarking:</p> <pre><code>library(microbenchmark) microbenchmark(!a, my.not(a), a &amp; b, my.and(a, b), a | b, my.or(a, b), xor(a, b), my.xor(a, b)) # Unit: milliseconds # expr min lq median uq max neval # !a 1.237437 1.459042 1.463259 1.492671 17.28209 100 # my.not(a) 6.018455 6.263176 6.414515 15.291194 70.16313 100 # a &amp; b 32.318530 32.667525 32.769014 32.973878 50.55528 100 # my.and(a, b) 8.010022 8.592776 8.750786 18.145590 78.38736 100 # a | b 32.030545 32.383769 32.506937 32.820720 102.43609 100 # my.or(a, b) 12.089538 12.434793 12.663695 22.046841 32.19095 100 # xor(a, b) 94.892791 95.480200 96.072202 106.104000 164.19937 100 # my.xor(a, b) 13.337110 13.708025 14.048350 24.485478 29.75883 100 </code></pre> <p>Looking at the results, the <code>!</code> operator is the only one that seems to do a decent job versus my own. The other three are a few times slower. A bit embarrassing for <code>Primitive</code> functions. I even expect that well implemented boolean operators should be a lot faster than operations on integers (how I implemented my own functions.)</p> <p>Question: Why? Bad implementation? Or maybe the primitive functions are doing some good things (e.g. error checking, special cases) that my functions are not?</p>
18,940,100
3
1
null
2013-09-22 00:59:33.87 UTC
12
2014-02-14 14:48:52.517 UTC
2013-09-22 01:06:38.277 UTC
null
1,201,032
null
1,201,032
null
1
27
r|boolean-logic
1,645
<p>Looking at the C implementation a little, the logical and math operations implement their loops differently. The logical operations do something like (in logic.c:327)</p> <pre><code>library(inline) or1 &lt;- cfunction(c(x="logical", y="logical"), " int nx = LENGTH(x), ny = LENGTH(y), n = nx &gt; ny ? nx : ny; SEXP ans = PROTECT(allocVector(LGLSXP, n)); int x1, y1; for (int i = 0; i &lt; n; i++) { x1 = LOGICAL(x)[i % nx]; y1 = LOGICAL(y)[i % ny]; if ((x1 != NA_LOGICAL &amp;&amp; x1) || (y1 != NA_LOGICAL &amp;&amp; y1)) LOGICAL(ans)[i] = 1; else if (x1 == 0 &amp;&amp; y1 == 0) LOGICAL(ans)[i] = 0; else LOGICAL(ans)[i] = NA_LOGICAL; } UNPROTECT(1); return ans; ") </code></pre> <p>where there are two modulo operators <code>%</code> each iteration. In contrast the arithmetic operations (in Itermacros.h:54) do something like</p> <pre><code>or2 &lt;- cfunction(c(x="logical", y="logical"), " int nx = LENGTH(x), ny = LENGTH(y), n = nx &gt; ny ? nx : ny; SEXP ans = PROTECT(allocVector(LGLSXP, n)); int x1, y1, ix=0, iy=0; for (int i = 0; i &lt; n; i++) { x1 = LOGICAL(x)[ix]; y1 = LOGICAL(x)[iy]; if (x1 == 0 || y1 == 0) LOGICAL(ans)[i] = 0; else if (x1 == NA_LOGICAL || y1 == NA_LOGICAL) LOGICAL(ans)[i] = NA_LOGICAL; else LOGICAL(ans)[i] = 1; if (++ix == nx) ix = 0; if (++iy == ny) iy = 0; } UNPROTECT(1); return ans; ") </code></pre> <p>performing two tests for identity. Here's a version that skips the test for NA</p> <pre><code>or3 &lt;- cfunction(c(x="logical", y="logical"), " int nx = LENGTH(x), ny = LENGTH(y), n = nx &gt; ny ? nx : ny; SEXP ans = PROTECT(allocVector(LGLSXP, n)); int x1, y1, ix=0, iy=0; for (int i = 0; i &lt; n; ++i) { x1 = LOGICAL(x)[ix]; y1 = LOGICAL(y)[iy]; LOGICAL(ans)[i] = (x1 || y1); if (++ix == nx) ix = 0; if (++iy == ny) iy = 0; } UNPROTECT(1); return ans; ") </code></pre> <p>and then a version that avoids the LOGICAL macro</p> <pre><code>or4 &lt;- cfunction(c(x="logical", y="logical"), " int nx = LENGTH(x), ny = LENGTH(y), n = nx &gt; ny ? nx : ny; SEXP ans = PROTECT(allocVector(LGLSXP, n)); int *xp = LOGICAL(x), *yp = LOGICAL(y), *ansp = LOGICAL(ans); for (int i = 0, ix = 0, iy = 0; i &lt; n; ++i) { *ansp++ = xp[ix] || yp[iy]; ix = (++ix == nx) ? 0 : ix; iy = (++iy == ny) ? 0 : iy; } UNPROTECT(1); return ans; ") </code></pre> <p>Here are some timings</p> <pre><code>microbenchmark(my.or(a, b), a|b, or1(a, b), or2(a, b), or3(a, b), or4(a, b)) Unit: milliseconds expr min lq median uq max neval my.or(a, b) 8.002435 8.100143 10.082254 11.56076 12.05393 100 a | b 23.194829 23.404483 23.860382 24.30020 24.96712 100 or1(a, b) 17.323696 17.659705 18.069139 18.42815 19.57483 100 or2(a, b) 13.040063 13.197042 13.692152 14.09390 14.59378 100 or3(a, b) 9.982705 10.037387 10.578464 10.96945 11.48969 100 or4(a, b) 5.544096 5.592754 6.106694 6.30091 6.94995 100 </code></pre> <p>The difference between <code>a|b</code> and <code>or1</code> reflects things not implemented here, like attributes and dimensions and special handling of objects. From <code>or1</code> to <code>or2</code> reflects the cost of different ways of recycling; I was surprised that there were differences here. From <code>or2</code> to <code>or3</code> is the cost of NA-safety. It's a little hard to know whether the additional speed-up in <code>or4</code> would be seen in a base R implementation -- in user C code <code>LOGICAL()</code> is a macro, but in base R it's an inlined function call.</p> <p>The code was compiled with <code>-O2</code> flags and</p> <pre><code>&gt; system("clang++ --version") Ubuntu clang version 3.0-6ubuntu3 (tags/RELEASE_30/final) (based on LLVM 3.0) Target: x86_64-pc-linux-gnu Thread model: posix </code></pre> <p>Times of <code>my.or</code> were not particularly consistent between independent R sessions, sometimes taking quite a bit longer; I'm not sure why. The timings above were with R version 2.15.3 Patched (2013-03-13 r62579); current R-devel seemed about 10% faster.</p>