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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
13,215,024 | Why is data getting stored with weird keys in Redis when using Jedis with Spring Data? | <p>I am using Spring Data Redis with Jedis. I am trying to store a hash with key <code>vc:${list_id}</code>. I was able to successfully insert to redis. However, when I inspect the keys using the redis-cli, I don't see the key <code>vc:501381</code>. Instead I see <code>\xac\xed\x00\x05t\x00\tvc:501381</code>. </p>
<p>Why is this happening and how do I change this? </p> | 13,216,053 | 5 | 0 | null | 2012-11-04 00:49:11.237 UTC | 26 | 2018-11-12 20:21:42.833 UTC | 2018-11-12 20:21:42.833 UTC | null | 254,477 | null | 1,333,610 | null | 1 | 60 | redis|spring-data|jedis | 49,371 | <p>Ok, googled around for a while and found help at <a href="http://java.dzone.com/articles/spring-data-redis" rel="noreferrer">http://java.dzone.com/articles/spring-data-redis</a>.</p>
<p>It happened because of Java serialization. </p>
<p>The key serializer for redisTemplate needs to be configured to <code>StringRedisSerializer</code> i.e. like this:</p>
<pre class="lang-xml prettyprint-override"><code><bean
id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.server}"
p:port="${redis.port}"
p:use-pool="true"/>
<bean
id="stringRedisSerializer"
class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
<bean
id="redisTemplate"
class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="jedisConnectionFactory"
p:keySerializer-ref="stringRedisSerializer"
p:hashKeySerializer-ref="stringRedisSerializer"
/>
</code></pre>
<p>Now the key in redis is <code>vc:501381</code>.</p>
<p>Or like @niconic says, we can also set the default serializer itself to the string serializer as follows:</p>
<pre class="lang-xml prettyprint-override"><code><bean
id="redisTemplate"
class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="jedisConnectionFactory"
p:defaultSerializer-ref="stringRedisSerializer"
/>
</code></pre>
<p>which means all our keys and values are strings. Notice however that this may not be preferable, since you may want your values to be not just strings.</p>
<p>If your value is a domain object, then you can use Jackson serializer and configure a serializer as mentioned <a href="https://stackoverflow.com/a/25324443/1333610">here</a> i.e. like this:</p>
<pre class="lang-xml prettyprint-override"><code><bean id="userJsonRedisSerializer" class="org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer">
<constructor-arg type="java.lang.Class" value="com.mycompany.redis.domain.User"/>
</bean>
</code></pre>
<p>and configure your template as:</p>
<pre class="lang-xml prettyprint-override"><code><bean
id="redisTemplate"
class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="jedisConnectionFactory"
p:keySerializer-ref="stringRedisSerializer"
p:hashKeySerializer-ref="stringRedisSerializer"
p:valueSerialier-ref="userJsonRedisSerializer"
/>
</code></pre> |
12,866,413 | Comparing arrays for equality in C++ | <p>Can someone please explain to me why the output from the following code is saying that arrays are <strong>not equal</strong>?</p>
<pre><code>int main()
{
int iar1[] = {1,2,3,4,5};
int iar2[] = {1,2,3,4,5};
if (iar1 == iar2)
cout << "Arrays are equal.";
else
cout << "Arrays are not equal.";
return 0;
}
</code></pre> | 12,866,496 | 11 | 6 | null | 2012-10-12 20:12:32.403 UTC | 17 | 2020-11-30 23:27:23.787 UTC | 2016-04-19 23:11:39.62 UTC | null | 3,425,536 | null | 1,677,368 | null | 1 | 61 | c++|arrays|comparison|equality | 152,255 | <pre><code>if (iar1 == iar2)
</code></pre>
<p>Here <code>iar1</code> and <code>iar2</code> are <em>decaying</em> to pointers to the first elements of the respective arrays. Since they are two distinct arrays, the pointer values are, of course, different and your comparison tests not equal.</p>
<p>To do an element-wise comparison, you must either write a loop; or use <a href="http://en.cppreference.com/w/cpp/container/array" rel="noreferrer"><code>std::array</code></a> instead </p>
<pre><code>std::array<int, 5> iar1 {1,2,3,4,5};
std::array<int, 5> iar2 {1,2,3,4,5};
if( iar1 == iar2 ) {
// arrays contents are the same
} else {
// not the same
}
</code></pre> |
22,185,974 | Deploying Qt 5 App on Windows | <p>I've written a couple of applications in QML (part of Qt 5). In a question that I've made before (<a href="https://softwareengineering.stackexchange.com/questions/213698/deploying-qt-based-app-on-mac-os-x">https://softwareengineering.stackexchange.com/questions/213698/deploying-qt-based-app-on-mac-os-x</a>), I found the solution for deploying my app on OS X (using the macdeployqt tool). </p>
<p>Deploying Qt4 apps on Windows was easy:</p>
<ol>
<li>You compiled it in release mode.</li>
<li>You copied the necessary libraries (DLLs).</li>
<li>You tested and it worked.</li>
</ol>
<p>Unfortunately, this approach did not work in Qt5 (I even included the platforms folder with the qwindows.dll file and it did not work). After some days of trying, I gave up and compiled a static version of Qt5. </p>
<p>Again, it did not work. The app works on a PC with Qt installed, but it crashes on "clean" PCs. As a side note, Windows 8/8.1 systems don't give a warning or a message notifying me about the app's crash. But in Windows 7 a message notifies me that the application crashed.</p>
<p>I've tried running Dependency Walker (depends.exe) and all libraries in the static build of my application seemed fine.</p>
<p>In Windows 8, I don't get any error. But after profiling the app in depends.exe, I get an access violation originating from QtGui.dll. The exact error is</p>
<blockquote>
<p>Second chance exception 0xC0000005 (Access Violation) occurred in "QT5GUI.DLL" at address 0x61C2C000.</p>
</blockquote>
<p>Is there something that I am missing (say an extra DLL or config file)?</p>
<p>Application information:</p>
<ul>
<li>Written and compiled with Qt 5.2.1</li>
<li>Uses Quick/QML.</li>
<li>Uses the network module.</li>
<li>Uses the webkit module.</li>
<li>Uses the bluetooth module.</li>
<li>The QML files are written in Quick 2.2</li>
</ul> | 22,188,918 | 2 | 9 | null | 2014-03-04 01:06:58.867 UTC | 16 | 2019-05-31 21:20:14.64 UTC | 2017-04-12 07:31:21.16 UTC | null | -1 | Alex | 1,650,731 | null | 1 | 38 | c++|windows|deployment|qt | 35,470 | <p>After some hours digging in the Qt Forums, I found out that I need to copy the "qml" folder (normally located in C:/Qt/5.2.1/qml) to the application's root directory. After doing so, both the dynamic and static versions of my application worked on vanilla systems.</p>
<hr>
<p><strong>Program directory (MinGW 4.8 32-bit, dynamic):</strong></p>
<p>As <a href="https://stackoverflow.com/users/1717300/hyde">hyde</a> said, use the <code>windeployqt</code> tool (<code><qt path>\<version>\bin\windeployqt.exe</code>) to copy the necessary files to your application's folder. After that, copy the required QML components from <code><qt path>\<version>\qml\</code> to your application's folder. The resulting folder should look similar to:</p>
<ul>
<li>platforms (folder) </li>
<li>QtQuick (folder) </li>
<li>QtQuick.2 (folder)</li>
<li><em>Any other QML components that you need</em></li>
<li>app.exe</li>
<li>icudt51.dll</li>
<li>icuin51.dll</li>
<li>icuuc51.dll</li>
<li>libgcc_s_dw2-1.dll</li>
<li>libstdc++-6.dll</li>
<li>libwindthread-1.dll</li>
<li>Qt5Core.dll</li>
<li>Qt5Gui.dll</li>
<li>Qt5Qml.dll</li>
<li>Qt5Quick.dll</li>
<li>Qt5Network.dll</li>
<li>Qt5Widgets.dll</li>
</ul>
<hr>
<p><strong>Program directory (static)</strong></p>
<p>Compile the application statically, then copy the required QML components from <code><qt path>\<version>\qml\</code> to your application's folder. The resulting folder should look similar to:</p>
<ul>
<li>QtQuick (folder)</li>
<li>QtQuick.2 (folder)</li>
<li><em>Any other QML components that you need</em></li>
<li>app.exe</li>
</ul>
<hr>
<p>I think the cause for the crash was that the <code>Qt5Gui.dll</code> (dynamic and static) "tried" to load the QtQuick* folders during run time, but could not find them (thus crashing the application during load).</p> |
16,672,632 | Group By Sum Linq to SQL in C# | <p>Really stuck with Linq to SQL grouping and summing, have searched everywhere but I don't understand enough to apply other solutions to my own.</p>
<p>I have a view in my database called view_ProjectTimeSummary, this has the following fields:</p>
<pre><code>string_UserDescription
string_ProjectDescription
datetime_Date
double_Hours
</code></pre>
<p>I have a method which accepts a to and from date parameter and first creates this List<>:</p>
<pre><code>List<view_UserTimeSummary> view_UserTimeSummaryToReturn =
(from linqtable_UserTimeSummaryView
in datacontext_UserTimeSummary.GetTable<view_UserTimeSummary>()
where linqtable_UserTimeSummaryView.datetime_Week <= datetime_To
&& linqtable_UserTimeSummaryView.datetime_Week >= datetime_From
select linqtable_UserTimeSummaryView).ToList<view_UserTimeSummary>();
</code></pre>
<p>Before returning the List (to be used as a datasource for a datagridview) I filter the string_UserDescription field using a parameter of the same name:</p>
<pre><code>if (string_UserDescription != "")
{
view_UserTimeSummaryToReturn =
(from c in view_UserTimeSummaryToReturn
where c.string_UserDescription == string_UserDescription
select c).ToList<view_UserTimeSummary>();
}
return view_UserTimeSummaryToReturn;
</code></pre>
<p>How do I manipulate the resulting List<> to show the <strong>sum</strong> of the field double_Hours for that user and project between the to and from date parameters (and not separate entries for each date)?</p>
<p>e.g. a List<> with the following fields:</p>
<pre><code>string_UserDescription
string_ProjectDescription
double_SumOfHoursBetweenToAndFromDate
</code></pre>
<p>Am I right that this would mean I would have to return a different type of List<> (since it has less fields than the view_UserTimeSummary)?</p>
<p>I have read that to get the sum it's something like 'group / by / into b' but don't understand how this syntax works from looking at other solutions... Can someone please help me?</p>
<p>Thanks
Steve</p> | 16,672,936 | 1 | 0 | null | 2013-05-21 14:32:54.477 UTC | 5 | 2013-05-21 14:47:10.657 UTC | null | null | null | null | 2,405,800 | null | 1 | 16 | sql|linq|group-by|sum | 56,767 | <p>Start out by defining a class to hold the result:</p>
<pre><code>public class GroupedRow
{
public string UserDescription {get;set;}
public string ProjectDescription {get;set;}
public double SumOfHoursBetweenToAndFromDate {get;set;}
}
</code></pre>
<p>Since you've already applied filtering, the only thing left to do is group.</p>
<pre><code>List<GroupedRow> result =
(
from row in source
group row by new { row.UserDescription, row.ProjectDescription } into g
select new GroupedRow()
{
UserDescription = g.Key.UserDescription,
ProjectDescription = g.Key.ProjectDescription,
SumOfHoursBetweenToAndFromDate = g.Sum(x => x.Hours)
}
).ToList();
</code></pre>
<p>(or the other syntax)</p>
<pre><code>List<GroupedRow> result = source
.GroupBy(row => new {row.UserDescription, row.ProjectDescription })
.Select(g => new GroupedRow()
{
UserDescription = g.Key.UserDescription,
ProjectDescription = g.Key.ProjectDescription,
SumOfHoursBetweenToAndFromDate = g.Sum(x => x.Hours)
})
.ToList();
</code></pre> |
16,675,716 | check variable type inside Jinja2 in Flask | <p>The template file i created contains this:</p>
<pre><code>{% if type({'a':1,'b':2}) is dict %}
print "Oh Yes!!"
{% else %}
print "Oh No!!!"
{% endif %}
</code></pre>
<hr>
<p>Then Jinja2 responds by saying:</p>
<pre><code>TemplateAssertionError: no test named 'dict'
</code></pre>
<hr>
<p>I am completely new to Jinja2 and Flask</p> | 16,676,429 | 3 | 0 | null | 2013-05-21 17:11:29.553 UTC | 5 | 2016-06-28 21:29:59.533 UTC | null | null | null | null | 636,762 | null | 1 | 39 | variables|types|flask|jinja2 | 71,890 | <p>You are looking for the <a href="http://jinja.pocoo.org/docs/templates/#mapping"><code>mapping</code> test</a>:</p>
<pre><code>{% if {'a': 1, 'b': 2} is mapping %}
"Oh Yes!"
{% else %}
"Oh No!"
{% endif %}
</code></pre>
<p>Jinja is not Python though, so you don't have access to all the builtins (<code>type</code> and <code>print</code> do not exist, for example, unless you add them to <a href="http://jinja.pocoo.org/docs/api/#the-context">the context</a>. In Flask, you do this with the <a href="http://flask.pocoo.org/docs/api/#flask.Flask.context_processor"><code>context_processor</code> decorator</a>).</p>
<p>You don't actually need <code>print</code> at all. By default everything is output (unless you are in a child template that <code>extends</code> a parent, in which case you can do <a href="http://jinja.pocoo.org/docs/tricks/#null-master-fallback">interesting things like the NULL Master fallback</a> because only blocks with names available in the master template are output).</p> |
20,611,310 | Query across multiple databases on same server | <p>I am looking for a way of dealing with the following situation:</p>
<ol>
<li><p>We have a database server with multiple databases on it (all have the same schema, different data).</p></li>
<li><p>We are looking for a way to query across all the databases (and for it to be easy to configure, as more databases may be added at any time). This data access must be realtime.</p></li>
</ol>
<p>Say, as an example, you have an application that inserts orders - each application has its own DB etc. What we are then looking for is an efficient way for a single application to then access the order information in all the other databases in order to query it and subsequently action it.</p>
<p>My searches to date have not revealed very much, however I think I may just be missing the appropriate keywords in order to find the correct info...</p> | 20,611,545 | 5 | 8 | null | 2013-12-16 12:47:06.833 UTC | 8 | 2021-03-11 22:48:33.717 UTC | null | null | null | null | 117,215 | null | 1 | 44 | sql|sql-server | 146,429 | <p>It's not going to be the cleanest solution ever, but you could define a view on a "Master database" (if your individual databases are not going to stay constant) that includes the data from the individual databases, and allows you to execute queries on a single source.</p>
<p>For example...</p>
<pre><code>CREATE VIEW vCombinedRecords AS
SELECT * FROM DB1.dbo.MyTable
UNION ALL
SELECT * FROM DB2.dbo.MyTable
</code></pre>
<p>Which allows you to do...</p>
<pre><code>SELECT * FROM vCombinedRecords WHERE....
</code></pre>
<p>When your databases change, you just update the view definition to include the new tables.</p> |
4,635,777 | hibernate jpa criteriabuilder ignore case queries | <p>How to do a like ignore case query using criteria builder. For description property I want to do something like <code>upper(description) like '%xyz%'</code></p>
<p>I have the following query</p>
<pre><code>CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Person> personCriteriaQuery = criteriaBuilder.createQuery(Person.class);
Root<Person> personRoot = personCriteriaQuery.from(Person.class);
personCriteriaQuery.select(personRoot);
personCriteriaQuery.where(criteriaBuilder.like(personRoot.get(Person_.description), "%"+filter.getDescription().toUpperCase()+"%"));
List<Person> pageResults = entityManager.createQuery(personCriteriaQuery).getResultList();
</code></pre> | 4,635,835 | 2 | 3 | null | 2011-01-08 19:48:08 UTC | 10 | 2021-01-28 18:14:34.68 UTC | 2011-01-08 19:57:25.323 UTC | null | 103,154 | null | 373,201 | null | 1 | 75 | jpa | 53,874 | <p>There is a <code>CriteriaBuilder.upper()</code> method:</p>
<pre><code>personCriteriaQuery.where(criteriaBuilder.like(
criteriaBuilder.upper(personRoot.get(Person_.description)),
"%"+filter.getDescription().toUpperCase()+"%"));
</code></pre> |
10,184,694 | How to create hyperlink using XSLT? | <p>I'm new at XSLT. I want to create a hyperlink using XSLT.
Should look like this:</p>
<p>Read our <strong>privacy policy.</strong></p>
<p>"privacy policy" is the link and upon clicking this, should redirect to example "www.privacy.com"</p>
<p>Any ideas? :)</p> | 10,184,881 | 3 | 2 | null | 2012-04-17 03:35:33.207 UTC | 1 | 2018-08-09 09:10:18.617 UTC | null | null | null | null | 1,107,377 | null | 1 | 7 | xslt | 49,704 | <p><strong>This transformation</strong>:</p>
<pre><code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<html>
<a href="www.privacy.com">Read our <b>privacy policy.</b></a>
</html>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p><strong>when applied on <em>any</em> XML document (not used), produces the wanted result</strong>:</p>
<pre><code><html><a href="www.privacy.com">Read our <b>privacy policy.</b></a></html>
</code></pre>
<p><strong>and this is displayed by the browser as</strong>:</p>
<p>Read our <b>privacy policy.</b></p>
<p><strong>Now imagine that nothing is hardcoded in the XSLT stylesheet -- instead the data is in the source XML document</strong>:</p>
<pre><code><link url="www.privacy.com">
Read our <b>privacy policy.</b>
</link>
</code></pre>
<p><strong>Then this transformation</strong>:</p>
<pre><code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="link">
<a href="{@url}"><xsl:apply-templates/></a>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p><strong>when applied on the above XML document, produces the wanted, correct result</strong>:</p>
<pre><code><a href="www.privacy.com">
Read our <b>privacy policy.</b>
</a>
</code></pre> |
9,915,658 | How do you open .mat files in Octave? | <p>I have a <code>.mat</code> file that I want to open and see its contents. Since I don't have MATLAB, I downloaded GNU's Octave. I'm working on Mac's terminal so I'm not exactly sure how to open the <code>.mat</code> file to see its contents.</p>
<p>How to do this?</p> | 9,915,773 | 2 | 0 | null | 2012-03-28 21:07:31.993 UTC | 5 | 2020-12-31 07:14:08.89 UTC | 2020-12-31 07:14:08.89 UTC | null | 11,573,842 | user1257724 | null | null | 1 | 25 | matlab|terminal|octave|mat-file | 89,445 | <p>Not sure which version of <code>.mat</code> file you might have, or whether Octave keeps up with the latest Matlab formats.</p>
<p><a href="http://en.wikibooks.org/wiki/Octave_Programming_Tutorial/Saving_and_loading_a_MAT-file" rel="noreferrer">Here's a link that might be a good start</a>.</p>
<p>Bottom line is that you can say: <code>load MyMatFile.mat</code> right at the Octave prompt.</p>
<p>In case you wind up having to write code to read the <code>.mat</code> file ever: I've done this before and it was not difficult, but was time-consuming. <a href="http://www.mathworks.com/help/pdf_doc/matlab/matfile_format.pdf" rel="noreferrer">Mat file format for 2012a</a></p> |
10,199,355 | PHP include causes white space at the top of the page | <p>I have a problem on a site that I am making. There is this line of white space at the top of my page. I can not find out where it is coming from. It might be because of extra line breaks in my page thanks to php <code>include()</code> or maybe it is just some faulty css.</p> | 10,200,440 | 15 | 1 | null | 2012-04-17 21:21:15.193 UTC | 5 | 2018-08-12 16:05:37.65 UTC | 2017-09-06 13:05:30.153 UTC | null | 546,476 | null | 546,476 | null | 1 | 29 | php | 33,167 | <p>I got it! I must admit, this was a very strange one.</p>
<p><a href="http://studentguru.gr/b/solidus/archive/2009/12/30/lt-php-include-gt-strange-extra-white-space-at-the-beginning-of-page.aspx" rel="noreferrer">This</a> was my exact problem, and his solution fixed it perfectly.</p>
<p><br />
The problem was because of the <code>include()</code>.</p>
<p>When you save a page as UTF-8, a special signature called a byte-order mark (or BOM) is included at the beginning of the file, indicating that it is a UTF-8 file. You can only see BOMs with low level text editors (such as <a href="https://www.google.com.mx/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CCcQFjAA&url=http://en.wikipedia.org/wiki/MS-DOS_Editor&ei=XteOT57OD4aA2gXeoej5Cw&usg=AFQjCNH1f3kY7X_qRxcZCzhAmCIxLSyA7Q&sig2=gXbUz3XYRTXTZdp5eXjFuw" rel="noreferrer">DOS edit</a>). You need to remove this signature from the included file in order to get rid of the white space at the top of the page. <br /> <br /></p>
<p><img src="https://i.stack.imgur.com/CI2T1.png" alt="DOS edit"></p> |
9,996,428 | Django templates: overriding blocks of included children templates through an extended template | <p>I'm wondering if anyone knows how to deal with the following quirky template structure:</p>
<pre><code>### base.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title> {% block title %} Title of the page {% endblock %} </title>
</head>
<body>
<header>
{% block header %}
{% include "base/header.html" %}
{% endblock header %}
</header>
{% block content %}{% endblock %}
</body>
</html>
</code></pre>
<hr>
<pre><code>### base/header.html
<div id="menu-bar">
{% block nav %}
{% include "base/nav.html" %}
{% endblock %}
</div>
</code></pre>
<hr>
<pre><code>### base/nav.html
<nav id="menu">
<ul>
<li>
<a href="/profile/">My Profile</a>
</li>
<li>
<a href="/favs/">My Favorites</a>
</li>
{% block extra-content %}{% endblock %}
</ul>
</nav>
</code></pre>
<p>And, the heart of the matter:</p>
<hr>
<pre><code>### app/somepage.html
{% extends "base.html" %}
{% block content %}
<p>Content is overridden!</p>
{% endblock %}
{% block extra-content %}
<p>This will not show up, though...</p>
{% endblock %}
{% block nav %}
<p>Not even this.</p>
{% endblock %}
</code></pre>
<p>The problem is when extending a template you can only override the blocks declared in the parent only, not any of its children.</p>
<p>I suppose I could make base.html a husk of empty unused nested blocks covering all future contingencies, but would even that override properly? And is that the only way?</p>
<p>If you're wondering why I have a bi-directional include/extends workflow around base.html, I have many sub-templates that I want to get used all across the project: Headers, footers, navs, sidebars, etc. They all will be consistant in structure across the entire site, but in many cases a whole subdivision of the site will only need a few of those sub-templates. My idea was to define the sub-templates under the templates/base folder, and have templates/base-type1.html, templates/base-type2.html, etc to extend in other places. Each type would only reference the sub-templates needed, and override them to place content as needed.</p> | 9,996,580 | 3 | 4 | null | 2012-04-03 15:23:22.917 UTC | 5 | 2014-06-28 04:04:56.53 UTC | null | null | null | null | 1,293,695 | null | 1 | 37 | python|django|django-templates|django-inheritance | 23,446 | <p>You can solve this by extending your currently-included templates, then including the extension instead of the the currently-included base template.</p> |
10,173,544 | Custom Dialog in full screen? | <p>Is there any way to make my Dialog view full screen, i.e dialog occupy the entire screen (like an Activity). I tried using the LayoutParams and styles like
<code><item name="android:windowFullscreen">true</item></code> but nothing seems to be working. </p>
<p>I found a way of getting rid of the Title bar, but couldn't find a way to put a dialog in full screen. So can any one suggest me a way to do it.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyTheme" parent="@android:style/Theme.Dialog">
<item name="android:windowFullscreen">true</item>
<item name="android:windowFrame">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowBackground">@color/dialog_background</item>
</style>
</resources>
</code></pre> | 10,173,576 | 13 | 3 | null | 2012-04-16 11:51:18.94 UTC | 8 | 2022-05-31 19:56:40.063 UTC | 2012-04-16 11:57:10.277 UTC | null | 970,272 | null | 970,272 | null | 1 | 47 | android|dialog|fullscreen | 86,987 | <p>Give its constructor a non-dialog theme, such as <strong>android.R.style.Theme</strong> or <strong>android.R.style.Theme_Light</strong>.</p>
<p>Code by @Bob.</p>
<pre><code>Dialog dialog = new Dialog(context, android.R.style.Theme_Light);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.MyCustomDialogLayout);
dialog.show();
</code></pre> |
44,330,148 | Run bash command on jenkins pipeline | <p>Inside a groovy script (for a jenkins pipeline): How can I run a <code>bash</code> command instead of a <code>sh</code> command?</p>
<p><strong>I have tried the following:</strong></p>
<p>Call "<code>#!/bin/bash</code>" inside the <code>sh</code> call:</p>
<pre><code>stage('Setting the variables values') {
steps {
sh '''
#!/bin/bash
echo "hello world"
'''
}
}
</code></pre>
<p>Replace the <code>sh</code> call with a <code>bash</code> call: </p>
<pre><code>stage('Setting the variables values') {
steps {
bash '''
#!/bin/bash
echo "hello world"
'''
}
}
</code></pre>
<p><strong>Additional Info:</strong></p>
<p>My command is more complex than a <code>echo hello world</code>.</p> | 45,179,743 | 6 | 6 | null | 2017-06-02 13:27:59.03 UTC | 16 | 2022-05-13 15:42:31.24 UTC | 2018-11-07 19:47:54.53 UTC | null | 9,818,506 | null | 6,516,044 | null | 1 | 80 | linux|bash|shell|jenkins|groovy | 188,830 | <p>The Groovy script you provided is formatting the first line as a blank line in the resultant script. The shebang, telling the script to run with /bin/bash instead of /bin/sh, needs to be on the first line of the file or it will be ignored.</p>
<p>So instead, you should format your Groovy like this:</p>
<pre><code>stage('Setting the variables values') {
steps {
sh '''#!/bin/bash
echo "hello world"
'''
}
}
</code></pre>
<p>And it will execute with /bin/bash.</p> |
10,154,250 | Scroll part of content in fixed position container | <p>I have a <code>position: fixed</code> div in a layout, as a sidebar. I've been asked to have part of it's content stay fixed to the top of it (internally), and the rest to scroll <em>if it overflows the bottom of the div</em>.</p>
<p>I've had a look at <a href="https://stackoverflow.com/a/4646733/383609">this answer</a>, however the solution presented there doesn't work with <code>position: fixed</code> or <code>position: absolute</code> containers, which is a pain.</p>
<p>I've made a JSFiddle demonstration of my problem <a href="http://jsfiddle.net/jamwaffles/AKL35/1" rel="noreferrer">here</a>. The large amount of text should ideally scroll, instead of overflowing into the bottom of the page. The height of the header can vary with content, and may be animated.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
background: #eee;
font-family: sans-serif;
}
div.sidebar {
padding: 10px;
border: 1px solid #ccc;
background: #fff;
position: fixed;
top: 10px;
left: 10px;
bottom: 10px;
width: 280px;
}
div#fixed {
background: #76a7dc;
padding-bottom: 10px;
color: #fff;
}
div#scrollable {
overlow-y: scroll;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sidebar">
<div id="fixed">
Fixed content here, can be of varying height using jQuery $.animate()
</div>
<div id="scrollable">
Scrolling content<br><br>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div></code></pre>
</div>
</div>
</p>
<p>Without a fixed header, I can simply add <code>overflow-y: scroll</code> to <code>div.sidebar</code> and I can happily scroll all it's content if it overflows the bottom of the container. However, I'm running into issues with having a fixed, variable height header at the top of the sidebar, and having any content underneath that scroll if it's too long to fit into the container. </p>
<p><code>div.sidebar</code> <em>must</em> stay <code>position: fixed</code>, and I would very much like to do this without any hacks, as well as make it as cross browser as possible. I've attempted various things, but none of them work, and I'm unsure as to what to try from here.</p>
<p>How can I make a div inside a <code>position: fixed</code> container scroll only in the Y direction when it's content overflows the containing div, with a fixed header of varying, indeterminate height? I'd very much like to stay away from JS, but if I have to use it I will.</p> | 10,155,623 | 5 | 5 | null | 2012-04-14 14:04:07.163 UTC | 13 | 2018-11-16 16:27:03.273 UTC | 2018-11-16 16:27:03.273 UTC | null | 542,251 | null | 383,609 | null | 1 | 62 | css|overflow | 184,233 | <p>It seems to work if you use</p>
<pre><code>div#scrollable {
overflow-y: scroll;
height: 100%;
}
</code></pre>
<p>and add <code>padding-bottom: 60px</code> to <code>div.sidebar</code>. </p>
<p>For example: <a href="http://jsfiddle.net/AKL35/6/">http://jsfiddle.net/AKL35/6/</a></p>
<p>However, I am unsure why it must be <code>60px</code>.</p>
<p>Also, you missed the <code>f</code> from <code>overflow-y: scroll;</code> </p> |
9,721,830 | How to attach debugger to iOS app after launch? | <p>I have an issue I am troubleshooting which occurs very infrequently and doesn't seem to happen when I have things running under Xcode. </p>
<p>Is it possible to run an app normally (i.e. from Springboard) until my issue occurs, and then attach a debugger at that point?</p>
<p>I would prefer to do this without jailbreaking if possible.</p> | 9,722,089 | 4 | 2 | null | 2012-03-15 14:29:05.313 UTC | 37 | 2021-09-28 11:35:29.137 UTC | 2019-08-21 17:40:57.343 UTC | null | 1,265,393 | null | 787,684 | null | 1 | 111 | ios|xcode|debugging | 83,898 | <ul>
<li>Attach your device connected your Mac</li>
<li><em>Debug > Attach to Process by PID or Name</em></li>
<li>In the dialog sheet, enter the name of your App as it appears in the <code>Debug navigator</code> when started via Xcode (e.g. Target's name not bundle-id).</li>
</ul>
<p>If the app is already running, the debugger will attach to the running process. If it isn't running, it will wait for the app to launch and then attach.</p> |
9,764,298 | How to sort two lists (which reference each other) in the exact same way | <p>Say I have two lists:</p>
<pre><code>list1 = [3, 2, 4, 1, 1]
list2 = ['three', 'two', 'four', 'one', 'one2']
</code></pre>
<p>If I run <code>list1.sort()</code>, it'll sort it to <code>[1,1,2,3,4]</code> but is there a way to get <code>list2</code> in sync as well (so I can say item <code>4</code> belongs to <code>'three'</code>)? So, the expected output would be:</p>
<pre><code>list1 = [1, 1, 2, 3, 4]
list2 = ['one', 'one2', 'two', 'three', 'four']
</code></pre>
<p>My problem is I have a pretty complex program that is working fine with lists but I sort of need to start referencing some data. I know this is a perfect situation for dictionaries but I'm trying to avoid dictionaries in my processing because I do need to sort the key values (if I must use dictionaries I know how to use them).</p>
<p>Basically the nature of this program is, the data comes in a random order (like above), I need to sort it, process it and then send out the results (order doesn't matter but users need to know which result belongs to which key). I thought about putting it in a dictionary first, then sorting list one but I would have no way of differentiating of items in the with the same value if order is not maintained (it may have an impact when communicating the results to users). So ideally, once I get the lists I would rather figure out a way to sort both lists together. Is this possible?</p> | 9,764,364 | 14 | 1 | null | 2012-03-19 02:35:10.007 UTC | 71 | 2021-12-29 18:13:18.443 UTC | 2020-05-15 16:11:19.08 UTC | null | 7,851,470 | null | 640,558 | null | 1 | 202 | python|list|sorting | 191,380 | <p>One classic approach to this problem is to use the "decorate, sort, undecorate" idiom, which is especially simple using python's built-in <code>zip</code> function:</p>
<pre><code>>>> list1 = [3,2,4,1, 1]
>>> list2 = ['three', 'two', 'four', 'one', 'one2']
>>> list1, list2 = zip(*sorted(zip(list1, list2)))
>>> list1
(1, 1, 2, 3, 4)
>>> list2
('one', 'one2', 'two', 'three', 'four')
</code></pre>
<p>These of course are no longer lists, but that's easily remedied, if it matters:</p>
<pre><code>>>> list1, list2 = (list(t) for t in zip(*sorted(zip(list1, list2))))
>>> list1
[1, 1, 2, 3, 4]
>>> list2
['one', 'one2', 'two', 'three', 'four']
</code></pre>
<p>It's worth noting that the above may sacrifice speed for terseness; the in-place version, which takes up 3 lines, is a tad faster on my machine for small lists:</p>
<pre><code>>>> %timeit zip(*sorted(zip(list1, list2)))
100000 loops, best of 3: 3.3 us per loop
>>> %timeit tups = zip(list1, list2); tups.sort(); zip(*tups)
100000 loops, best of 3: 2.84 us per loop
</code></pre>
<p>On the other hand, for larger lists, the one-line version could be faster:</p>
<pre><code>>>> %timeit zip(*sorted(zip(list1, list2)))
100 loops, best of 3: 8.09 ms per loop
>>> %timeit tups = zip(list1, list2); tups.sort(); zip(*tups)
100 loops, best of 3: 8.51 ms per loop
</code></pre>
<p>As Quantum7 points out, <a href="https://stackoverflow.com/a/9764390/577088">JSF's suggestion</a> is a bit faster still, but it will probably only ever be a little bit faster, because Python uses the <a href="https://hg.python.org/cpython/file/e4c32152b25b/Objects/listobject.c#l1863" rel="noreferrer">very same DSU idiom internally</a> for all key-based sorts. It's just happening a little closer to the bare metal. (This shows just how well optimized the <code>zip</code> routines are!)</p>
<p>I think the <code>zip</code>-based approach is more flexible and is a little more readable, so I prefer it.</p>
<hr />
<p>Note that when elements of <code>list1</code> are equal, this approach will end up comparing elements of <code>list2</code>. If elements of <code>list2</code> don't support comparison, or don't produce a boolean when compared (for example, if <code>list2</code> is a list of NumPy arrays), this will fail, and if elements of <code>list2</code> are very expensive to compare, it might be better to avoid comparison anyway.</p>
<p>In that case, you can sort indices as suggested in jfs's answer, or you can give the sort a key function that avoids comparing elements of <code>list2</code>:</p>
<pre><code>result1, result2 = zip(*sorted(zip(list1, list2), key=lambda x: x[0]))
</code></pre>
<p>Also, the use of <code>zip(*...)</code> as a transpose fails when the input is empty. If your inputs might be empty, you will have to handle that case separately.</p> |
7,956,563 | Remember ajax added data when hitting back button | <p>I have a search page where every search result is added to the page with AJAX. This way I can let users search for e.g <em>Led Zeppelin</em>, then do another search for <em>Metallica</em> but add it to the same result list as the previous search. </p>
<p>My problem is when a user clicks on a link to a record, then hits the back button, back to the search result.<br>
<strong>FireFox (7)</strong> keeps the page as it looked when I left it, displaying the full result.<br>
<strong>IE (7,8)</strong> and <strong>Chrome (15)</strong> on the other hand will display the page as it were before adding any search results with AJAX, as if it doesn't remember that I added data to it. </p>
<p>Below is the code I use. I tried to add the <code>location.hash = "test";</code> but it didn't seem to work.</p>
<pre><code>// Add search result
$("#searchForm").submit(function (event) {
//location.hash = "test";
event.preventDefault();
$.post($(this).attr('action'), $(this).serialize(),
function (data) {
$("tbody").append(data);
});
});
</code></pre>
<p>I don't need a back button that keeps track of changes on the search page, like stepping through each different search result as it was added. I just want the browser to remember the last search result when I hit the back button. </p>
<p><strong>SOLVED</strong><br>
Changing to <code>document.location.hash = "latest search"</code> didn't change anything. I had to use the <code>localStorage</code> as Amir pointed out.</p>
<p>This goes into the rest of the jQuery code: </p>
<pre><code>// Replace the search result table on load.
if (('localStorage' in window) && window['localStorage'] !== null) {
if ('myTable' in localStorage && window.location.hash) {
$("#myTable").html(localStorage.getItem('myTable'));
}
}
// Save the search result table when leaving the page.
$(window).unload(function () {
if (('localStorage' in window) && window['localStorage'] !== null) {
var form = $("#myTable").html();
localStorage.setItem('myTable', form);
}
});
</code></pre> | 7,956,641 | 3 | 1 | null | 2011-10-31 16:26:20.443 UTC | 20 | 2014-06-06 13:22:09.827 UTC | 2011-11-01 14:24:18 UTC | null | 536,610 | null | 536,610 | null | 1 | 46 | jquery|ajax | 25,476 | <p>You have a few options. </p>
<ol>
<li>Use <a href="https://developer.mozilla.org/en/DOM/Storage">localstorage</a> to remember the last query</li>
<li>Use cookies (but don't)</li>
<li>Use the hash as you tried with <code>document.location.hash = "last search"</code> to update the url. You would look at the hash again and if it is set then do another ajax to populate the data. If you had done localstorage then you could just cache the last ajax request. </li>
</ol>
<p>I would go with the localstorage and the hash solution because that's what some websites do. You can also copy and paste a URL and it will just load the same query. This is pretty nice and I would say very accessible. </p>
<p>I am curious to know why it didn't work. Update your answer so we can help. </p> |
11,722,682 | Cool Styling for dropdown list in asp.net? | <p>I wonder if we can give the default dropdownlist a cool and classy look using css/styling. I do not want to use jquery/jscript as I am not familiar with these.
Can it be done using css/html styling ?</p>
<pre><code>I want it to look something like this :
</code></pre>
<p><img src="https://i.stack.imgur.com/9GNx5.jpg" alt="enter image description here"></p>
<p>or </p>
<p><img src="https://i.stack.imgur.com/kzRZy.jpg" alt="enter image description here"></p> | 11,722,753 | 1 | 3 | null | 2012-07-30 13:34:59.197 UTC | 2 | 2018-10-02 16:09:33.867 UTC | 2012-07-30 13:44:40.233 UTC | null | 499,631 | null | 1,529,191 | null | 1 | 6 | asp.net|css|drop-down-menu | 55,576 | <p>Sure you can.</p>
<p>I recommend checking out <a href="http://bavotasan.com/2011/style-select-box-using-only-css/">http://bavotasan.com/2011/style-select-box-using-only-css/</a></p>
<p>It's really just a mix of your standard commands: height, width, background, color, border. All put together to make it prettier. I'm not sure about offsetting it like in your example 2, but example 1 is easy.</p> |
11,713,250 | VB.NET What is Sender used for? | <p>I'm confused as to the purpose of the <code>sender</code> parameter in Winform controls, for example:</p>
<pre><code>Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
</code></pre>
<p>I understand i can verify what <code>sender</code> holds by doing something as so:</p>
<pre><code>If TypeOf sender Is Label Then
'Execute some code...
End If
</code></pre>
<p>But is there a good reason that sender is included in every single control when it generates the sub-routine for me? In other words, i double click on a Form and i get the <code>Private Sub form_load (sender....)</code> <em>and</em> <code>e As System.EventArg</code>s.</p>
<p><strong>What are some common usage of these two parameters? Are they always required?</strong></p>
<p>Thank you,</p>
<p>Dayan D.</p> | 11,713,276 | 3 | 0 | null | 2012-07-29 21:49:31.437 UTC | 2 | 2016-01-14 11:43:21.953 UTC | null | null | null | null | 1,455,028 | null | 1 | 8 | vb.net|sender | 39,151 | <p><code>sender</code> contains the sender of the event, so if you had one method bound to multiple controls, you can distinguish them.</p>
<p>For example, if you had ten buttons and wanted to change their text to "You clicked me!" when you clicked one of them, you <em>could</em> use one separate handler for each one using a different button name each time, but it would be much better to handle all of them at once:</p>
<pre><code>Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click, Button5.Click, Button6.Click, Button7.Click, Button8.Click, Button9.Click
DirectCast(sender, Button).Text = "You clicked me!"
End Sub
</code></pre> |
11,842,984 | Sort array based on count of occurrences in ascending order | <p>How can I arrange the elements in an array based on the number of occurrences of that value in ascending order in java.</p>
<p>This is what I've tried:</p>
<pre><code>int a[]={0,0,0,1,3,3,2,1,3,5,6,0};
int b=a.length;
for(int i=0;i<b;i++) {
for(int j=0;j<i;j++) {
int temp;
if( a[j]>a[i]) {
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(int r=0;r<a.length;r++) {
System.out.println(a[r]);
}
</code></pre> | 11,843,975 | 24 | 8 | null | 2012-08-07 09:29:16.31 UTC | 4 | 2021-11-12 07:52:07.187 UTC | 2012-10-02 12:53:41.013 UTC | null | 68,556 | null | 366,916 | null | 1 | 10 | java|arrays|sorting | 78,489 | <p>Here's one approach to start you off could be based on the idea of keeping a count of how many times each integer in the initial array has occurred in a map. Once all the numbers have been counted, sort the map by order of ascending value, and then print the output of the map:</p>
<pre><code>import java.util.ArrayList;
import java.util.HashMap;
import java.util.TreeMap;
public class SortCount {
public static void main(String[] args) {
int nums[] = {0,0,0,1,3,3,2,1,3,5,6,0};
HashMap<Integer,Integer> counts = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++) {
if(counts.containsKey(nums[
Integer c = counts.get(nums[i]) + 1;
counts.put(nums[i], c);
}
else {
counts.put(nums[i],1);
}
}
ValueComparator<Integer,Integer> bvc = new ValueComparator<Integer,Integer>(counts);
TreeMap<Integer,Integer> sortedMap = new TreeMap<Integer,Integer>(bvc);
sortedMap.putAll(counts);
ArrayList<Integer> output = new ArrayList<Integer>();
for(Integer i : sortedMap.keySet()) {
for(int c = 0; c < sortedMap.get(i); c++) {
output.add(i);
}
}
System.out.println(output.toString());
}
}
</code></pre>
<p>Which uses a <code>Comparator</code> class to compare the values in a <code>Map</code>:</p>
<pre><code>import java.util.Comparator;
import java.util.Map;
public class ValueComparator<T1,T2 extends Comparable<T2>> implements Comparator<T1> {
Map<T1,T2> base;
public ValueComparator(Map<T1,T2> base) {
this.base = base;
}
@Override
public int compare(T1 k1, T1 k2) {
T2 val1 = base.get(k1);
T2 val2 = base.get(k2);
return val1.compareTo(val2);
}
}
</code></pre> |
11,971,089 | Adding a vector to matrix rows in numpy | <p>Is there a fast way in numpy to add a vector to every row or column of a matrix.</p>
<p>Lately, I have been tiling the vector to the size of the matrix, which can use a lot of memory. For example</p>
<pre><code> mat=np.arange(15)
mat.shape=(5,3)
vec=np.ones(3)
mat+=np.tile(vec, (5,1))
</code></pre>
<p>The other way I can think of is using a python loop, but loops are slow:</p>
<pre><code> for i in xrange(len(mat)):
mat[i,:]+=vec
</code></pre>
<p>Is there a fast way to do this in numpy without resorting to C extensions?</p>
<p>It would be nice to be able to virtually tile a vector, like a more flexible version of broadcasting. Or to be able to iterate an operation row-wise or column-wise, which you may almost be able to do with some of the ufunc methods.</p> | 11,971,337 | 2 | 4 | null | 2012-08-15 14:23:26.127 UTC | 7 | 2022-04-16 07:20:10.533 UTC | null | null | null | null | 1,149,913 | null | 1 | 24 | vector|matrix|numpy | 50,018 | <p>For adding a 1d array to every row, broadcasting already takes care of things for you:</p>
<pre><code>mat += vec
</code></pre>
<p>However more generally you can use <code>np.newaxis</code> to coerce the array into a broadcastable form. For example:</p>
<pre><code>mat + np.ones(3)[np.newaxis,:]
</code></pre>
<p>While not necessary for adding the array to every row, this is necessary to do the same for column-wise addition:</p>
<pre><code>mat + np.ones(5)[:,np.newaxis]
</code></pre>
<p><strong>EDIT:</strong> as Sebastian mentions, for row addition, <code>mat + vec</code> already handles the broadcasting correctly. It is also faster than using <code>np.newaxis</code>. I've edited my original answer to make this clear.</p> |
11,914,422 | Ruby, check if date is a weekend? | <p>I have a DailyQuote model in my rails application which has a <strong>date</strong> and <strong>price</strong> for a stock. Data in the database has been captured for this model including weekends. The weekend price values have been set as 0. </p>
<p>I want to change all the weekend prices for Saturday and Sunday to whatever the price was on Friday. What is the best way to do this in Ruby? To identify if a date falls on a Sat or Sun and change its value to the Fri of that weekend?</p> | 11,914,517 | 7 | 1 | null | 2012-08-11 11:45:49.917 UTC | 7 | 2021-06-17 08:12:41.383 UTC | null | null | null | null | 777,280 | null | 1 | 33 | ruby-on-rails|ruby|ruby-on-rails-3 | 26,694 | <pre><code>require 'date'
today = Date.today
ask_price_for = (today.wday == 6) ? today - 1 : (today.wday == 0) ? today - 2 : today
</code></pre>
<p>or </p>
<pre><code>require 'date'
today = Date.today
ask_price_for = (today.saturday?) ? today - 1 : (today.sunday?) ? today - 2 : today
</code></pre>
<p><code>ask_price_for</code> now holds a date for which you would want to ask the price for.</p>
<p>Getting the actual price which is corresponding to you date depends on your Model and your ORM-Library (i.e. ActiveRecord).</p> |
11,811,027 | "replace" function examples | <p>I don't find the help page for the <code>replace</code> function from the <code>base</code> package to be very <em>helpful</em>. Worst part, it has no examples which could help understand how it works.</p>
<p>Could you please explain how to use it? An example or two would be great.</p> | 11,811,147 | 5 | 0 | null | 2012-08-04 18:23:13.497 UTC | 13 | 2022-08-21 17:04:35.807 UTC | 2018-11-13 17:20:43.883 UTC | null | 1,855,677 | null | 1,201,032 | null | 1 | 41 | r | 169,874 | <p>If you look at the function (by typing it's name at the console) you will see that it is just a simple functionalized version of the <code>[<-</code> function which is described at <code>?"["</code>. <code>[</code> is a rather basic function to R so you would be well-advised to look at that page for further details. Especially important is learning that the index argument (the second argument in <code>replace</code> can be logical, numeric or character classed values. Recycling will occur when there are differing lengths of the second and third arguments:</p>
<p>You should "read" the function call as" "within the first argument, use the second argument as an index for placing the values of the third argument into the first":</p>
<pre><code>> replace( 1:20, 10:15, 1:2)
[1] 1 2 3 4 5 6 7 8 9 1 2 1 2 1 2 16 17 18 19 20
</code></pre>
<p>Character indexing for a named vector:</p>
<pre><code>> replace(c(a=1, b=2, c=3, d=4), "b", 10)
a b c d
1 10 3 4
</code></pre>
<p>Logical indexing:</p>
<pre><code>> replace(x <- c(a=1, b=2, c=3, d=4), x>2, 10)
a b c d
1 2 10 10
</code></pre> |
11,676,790 | click command in selenium webdriver does not work | <p>I have just recently done an export of my selenium IDE code to selenium web driver. I have found that a lot of the commands that worked in IDE either fail to work or selenium web driver claims to not support at all. So far I've been tackling these issues one at a time which is less than ideal...</p>
<p>Currently I'm working on finding out why clicking on a button does not work with web driver while it had previously worked in selenium IDE. My browser is FF 13 and my OS is Ubuntu.</p>
<p>Code Snippet</p>
<pre><code>WebElement loginButton = driver.findElement(By.name("submit"));
loginButton.click();
</code></pre>
<p>I had previously tried</p>
<pre><code>driver.findElement(By.name("submit")).click();
</code></pre>
<p>however the above line failed as well. The element is getting selected, however it does not log us in as I would like. I found other pages with similar problems, but their problem seemed to be with Internet Explorer not Firefox. I don't even want to think about the problems IE will give me down the road.</p>
<p>thanks,</p>
<p>P.S.
A tip on a better way to migrate from selenium IDE to Selenium Webdriver without losing all the tests I've written could solve this issue as well.</p> | 11,688,478 | 10 | 2 | null | 2012-07-26 19:38:24.843 UTC | 11 | 2022-04-06 20:09:18.383 UTC | null | null | null | null | 881,221 | null | 1 | 51 | selenium|selenium-ide|selenium-webdriver | 156,979 | <p>If you know for sure that the element is present, you could try this to simulate the click - if <code>.Click()</code> isn't working</p>
<pre><code>driver.findElement(By.name("submit")).sendKeys(Keys.RETURN);
</code></pre>
<p>or</p>
<pre><code>driver.findElement(By.name("submit")).sendKeys(Keys.ENTER);
</code></pre> |
3,440,105 | Hide Command Window in C# Application | <p>Before you say its a duplicate question, please let me explain (as I've read all similar threads).</p>
<p>My application has both of these settings:</p>
<pre><code> procStartInfo.CreateNoWindow = true;
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
</code></pre>
<p>and is also has WindowsApplication as the output type. </p>
<p>The black window STILL comes up when I call a command line command. Is there anything else I can do to hide the window? It doesn't happen for all commands, XCOPY is a situation where it the black window does flash up. This only happens though when the destination I'm XCOPYing too already contains the file and it's prompting me if I want to replace it. Even if I pass in /Y it will still flash briefly.</p>
<p>I'm open to using vbscript if that will help, but any other ideas?</p>
<p>The client will call my executable and then pass in a command line command ie:</p>
<p><code>C:\MyProgram.exe start XCOPY c:\Test.txt c:\ProgramFiles\</code></p>
<p>Here's the full code of the application:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
string command = GetCommandLineArugments(args);
// /c tells cmd that we want it to execute the command that follows and then exit.
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo = procStartInfo;
process.Start();
}
private static string GetCommandLineArugments(string[] args)
{
string retVal = string.Empty;
foreach (string arg in args)
retVal += " " + arg;
return retVal;
}
}
</code></pre> | 3,440,832 | 5 | 9 | null | 2010-08-09 12:47:09.817 UTC | 3 | 2022-05-20 00:51:04.087 UTC | 2010-08-09 13:46:27.303 UTC | null | 276,112 | null | 276,112 | null | 1 | 15 | c#|.net|command-prompt|xcopy | 39,047 | <p>The problem is that you're using cmd.exe. Only <em>its</em> console window will be hidden, not the console window for the process you ask it to start. There's little point in using cmd.exe, unless you are trying to execute some of the commands it implements itself. Like COPY.</p>
<p>You can still suppress the window if you need cmd.exe, you'll have to use the /B option for Start. Type start /? at the command prompt to see options. Not that it helps, you can't use START COPY.</p>
<p>There's a specific quirk in xcopy.exe that might throw you off as well. It does <em>not</em> execute if you don't also redirect the input. It just fails to run without diagnostic.</p> |
3,609,166 | Mysql: Order by like? | <p>assume that we are performing search using keywords: keyword1, keyword2, keyword3</p>
<p>there are records in database with column "name":</p>
<pre>
1: John Doe
2: Samuel Doe
3: John Smith
4: Anna Smith
</pre>
<p>now Query:</p>
<pre><code>SELECT * FROM users WHERE (name LIKE "%John%" OR name LIKE "%Doe%")
</code></pre>
<p>it will select records: 1,2,3 (in this order)
but i want to order it by keyword
in example <code>keyword1=John, keyword2=Doe</code>
so it should be listed by keywords: 1,3,2 (because i want to perform search for "Doe" after searching for "John")</p>
<p>I was thinking about <code>SELECT DISTINCT FROM (...... UNION .....)</code>
but it will be much easier to order it somehow in another way (real query is really long)</p>
<p>are there any tricks to create such order?</p> | 3,609,182 | 5 | 0 | null | 2010-08-31 12:48:27.977 UTC | 18 | 2019-01-24 06:53:21.513 UTC | 2019-01-24 06:53:21.513 UTC | null | 712,765 | null | 251,920 | null | 1 | 35 | mysql|sql|sql-order-by|sql-like | 37,974 | <pre><code>order by case
when name LIKE "%John%" then 1
when name LIKE "%Doe%" then 2
else 3
end
</code></pre> |
4,044,275 | How Many default methods does a class have? | <p>Sorry, this might seem simple, but somebody asked me this, and I don't know for certain.</p>
<p>An empty C++ class comes with what functions?</p>
<p>Constructor,
Copy Constructor,
Assignment,
Destructor?</p>
<p>Is that it? Or are there more?</p> | 4,044,347 | 5 | 1 | null | 2010-10-28 15:15:14.03 UTC | 32 | 2022-03-30 09:14:09.147 UTC | 2010-10-28 15:43:51.877 UTC | null | 134,877 | user245019 | null | null | 1 | 38 | c++ | 37,538 | <p>In C++03 there are 4:</p>
<ul>
<li><p><strong>Default constructor</strong>: Declared only if
no user-defined constructor is
declared. Defined when used</p>
</li>
<li><p><strong>Copy constructor</strong> - declared only if the user hasn't declared one. Defined if used</p>
</li>
<li><p><strong>Copy-assignment operator</strong> same as above</p>
</li>
<li><p><strong>Destructor</strong> same as above</p>
</li>
</ul>
<p>In C++11 there are two more:</p>
<ul>
<li><strong>Move constructor</strong></li>
<li><strong>Move-assignment operator</strong></li>
</ul>
<p>It is also possible that the compiler won't be able to generate some of them. For example, if the class contains, for example, a reference (or anything else that cannot be copy-assigned), then the compiler won't be able to generate a copy-assignment operator for you. <a href="https://en.cppreference.com/w/cpp/language/classes" rel="nofollow noreferrer">For more information read this</a></p> |
3,614,380 | What's the standard way to work with dates and times in Scala? Should I use Java types or there are native Scala alternatives? | <p>What's the standard way to work with dates and times in Scala? Should I use Java types such as java.util.Date or there are native Scala alternatives?</p> | 3,614,459 | 5 | 0 | null | 2010-09-01 01:10:51.6 UTC | 40 | 2020-09-02 06:21:30.417 UTC | 2010-09-01 07:58:11.02 UTC | null | 189,058 | null | 274,627 | null | 1 | 166 | datetime|scala|jodatime | 106,217 | <p>From Java SE 8 onwards, users are asked to migrate to java.time (JSR-310). There are efforts on creating scala libraries wrapping java.time for scala such as <a href="https://github.com/reactivecodes/scala-time" rel="nofollow noreferrer">scala-time</a>. If targeting lower than SE 8 use one of the below. Also see <a href="http://blog.joda.org/2009/11/why-jsr-310-isn-joda-time_4941.html" rel="nofollow noreferrer">Why JSR-310 isn't Joda-Time</a></p>
<p><a href="https://github.com/lauris/awesome-scala" rel="nofollow noreferrer">Awesome scala</a> lists many of the popular Scala DateTime apis</p>
<hr />
<p><a href="https://github.com/nscala-time/nscala-time" rel="nofollow noreferrer">A new Scala wrapper for Joda Time</a>. This project forked from scala-time since it seems that scala-time is no longer maintained.</p>
<pre><code>import com.github.nscala_time.time.Imports._
DateTime.now // returns org.joda.time.DateTime = 2009-04-27T13:25:42.659-07:00
DateTime.now.hour(2).minute(45).second(10) // returns org.joda.time.DateTime = 2009-04-27T02:45:10.313-07:00
DateTime.now + 2.months // returns org.joda.time.DateTime = 2009-06-27T13:25:59.195-07:00
DateTime.nextMonth < DateTime.now + 2.months // returns Boolean = true
DateTime.now to DateTime.tomorrow // return org.joda.time.Interval = > 2009-04-27T13:47:14.840/2009-04-28T13:47:14.840
(DateTime.now to DateTime.nextSecond).millis // returns Long = 1000
2.hours + 45.minutes + 10.seconds
// returns com.github.nscala_time.time.DurationBuilder
// (can be used as a Duration or as a Period)
(2.hours + 45.minutes + 10.seconds).millis
// returns Long = 9910000
2.months + 3.days
// returns Period
</code></pre>
<p><a href="http://joda-time.sourceforge.net/" rel="nofollow noreferrer">Joda Time</a> is a good Java library, there is a Scala wrapper / implicit conversion library avaliable for Joda Time at <a href="http://github.com/jorgeortiz85/scala-time/tree/master" rel="nofollow noreferrer">scala-time</a> created by <a href="http://github.com/jorgeortiz85" rel="nofollow noreferrer">Jorge Ortiz</a>. (Note implicits have a performance hit, but it depends on what you do if you will notice. And if you run into a performance problem you can just revert to the Joda interface)</p>
<p>From the README:</p>
<pre><code>USAGE:
import org.scala_tools.time.Imports._
DateTime.now
// returns org.joda.time.DateTime = 2009-04-27T13:25:42.659-07:00
DateTime.now.hour(2).minute(45).second(10)
// returns org.joda.time.DateTime = 2009-04-27T02:45:10.313-07:00
DateTime.now + 2.months
// returns org.joda.time.DateTime = 2009-06-27T13:25:59.195-07:00
DateTime.nextMonth < DateTime.now + 2.months
// returns Boolean = true
DateTime.now to DateTime.tomorrow
// return org.joda.time.Interval =
// 2009-04-27T13:47:14.840/2009-04-28T13:47:14.840
(DateTime.now to DateTime.nextSecond).millis
// returns Long = 1000
2.hours + 45.minutes + 10.seconds
// returns org.scala_tools.time.DurationBuilder
// (can be used as a Duration or as a Period)
(2.hours + 45.minutes + 10.seconds).millis
// returns Long = 9910000
2.months + 3.days
// returns Period
</code></pre> |
4,021,893 | Saving a Dictionary<String, Int32> in C# - Serialization? | <p>I am writing a C# application that needs to read about 130,000 (String, Int32) pairs at startup to a Dictionary. The pairs are stored in a .txt file, and are thus easily modifiable by anyone, which is something dangerous in the context. I would like to ask if there is a way to save this dictionary so that the information can be reasonably safely stored, without losing performance at startup. I have tried using <code>BinaryFormatter</code>, but the problem is that while the original program takes between 125ms and 250ms at startup to read the information from the txt and build the dictionary, deserializing the resulting binary files takes up to 2s, which is not too much by itself but when compared to the original performance is a 8-16x decrease in speed.</p>
<p><strong>Note:</strong> Encryption is important, but the most important should be a way to save and read the dictionary from the disk - possibly from a binary file - without having to use Convert.ToInt32 on each line, thus improving performance.</p> | 4,022,629 | 6 | 2 | null | 2010-10-26 08:29:50.17 UTC | 12 | 2017-09-03 13:53:11.93 UTC | 2017-09-03 13:53:11.93 UTC | null | 1,033,581 | null | 477,505 | null | 1 | 17 | c#|performance|serialization|binary | 20,926 | <p>interesting question. I did some quick tests and you are right - BinaryFormatter is surprisingly slow:</p>
<ul>
<li>Serialize 130,000 dictionary entries: <strong>547ms</strong></li>
<li>Deserialize 130,000 dictionary entries: <strong>1046ms</strong></li>
</ul>
<p>When I coded it with a StreamReader/StreamWriter with comma separated values I got:</p>
<ul>
<li>Serialize 130,000 dictionary entries: <strong>121ms</strong> </li>
<li>Deserialize 130,000 dictionary entries: <strong>111ms</strong></li>
</ul>
<p>But then I tried just using a BinaryWriter/BinaryReader:</p>
<ul>
<li>Serialize 130,000 dictionary entries: <strong>22ms</strong></li>
<li>Deserialize 130,000 dictionary entries: <strong>36ms</strong></li>
</ul>
<p>The code for that looks like this:</p>
<pre><code>public void Serialize(Dictionary<string, int> dictionary, Stream stream)
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(dictionary.Count);
foreach (var kvp in dictionary)
{
writer.Write(kvp.Key);
writer.Write(kvp.Value);
}
writer.Flush();
}
public Dictionary<string, int> Deserialize(Stream stream)
{
BinaryReader reader = new BinaryReader(stream);
int count = reader.ReadInt32();
var dictionary = new Dictionary<string,int>(count);
for (int n = 0; n < count; n++)
{
var key = reader.ReadString();
var value = reader.ReadInt32();
dictionary.Add(key, value);
}
return dictionary;
}
</code></pre>
<p>As others have said though, if you are concerned about users tampering with the file, encryption, rather than binary formatting is the way forward.</p> |
3,298,963 | How to set a primary key in MongoDB? | <p>I want to set <strong>one of my fields as primary key</strong>. I am using <a href="http://www.mongodb.org/" rel="noreferrer">MongoDB</a> as my NoSQL.</p> | 3,299,005 | 9 | 0 | null | 2010-07-21 12:04:30.86 UTC | 17 | 2021-10-20 13:16:39.707 UTC | 2013-05-02 10:14:23.04 UTC | null | 363,448 | null | 397,902 | null | 1 | 98 | mongodb | 173,475 | <p><code>_id</code> field is reserved for primary key in mongodb, and that should be a unique value. If you don't set anything to <code>_id</code> it will automatically fill it with "MongoDB Id Object". But you can put any unique info into that field.</p>
<p>Additional info: <a href="http://www.mongodb.org/display/DOCS/BSON" rel="noreferrer">http://www.mongodb.org/display/DOCS/BSON</a></p>
<p>Hope it helps.</p> |
3,307,427 | Scala double definition (2 methods have the same type erasure) | <p>I wrote this in scala and it won't compile:</p>
<pre><code>class TestDoubleDef{
def foo(p:List[String]) = {}
def foo(p:List[Int]) = {}
}
</code></pre>
<p>the compiler notify:</p>
<pre><code>[error] double definition:
[error] method foo:(List[String])Unit and
[error] method foo:(List[Int])Unit at line 120
[error] have same type after erasure: (List)Unit
</code></pre>
<p>I know JVM has no native support for generics so I understand this error.</p>
<p>I could write wrappers for <code>List[String]</code> and <code>List[Int]</code> but I'm lazy :)</p>
<p>I'm doubtful but, is there another way expressing <code>List[String]</code> is not the same type than <code>List[Int]</code>?</p>
<p>Thanks.</p> | 3,309,490 | 11 | 2 | null | 2010-07-22 09:30:25.513 UTC | 27 | 2020-05-22 13:59:55.27 UTC | 2015-09-29 12:48:20.197 UTC | null | 1,360,888 | null | 398,882 | null | 1 | 74 | scala|compilation|overloading|typeclass|type-erasure | 16,718 | <p>I like Michael Krämer's idea to use implicits, but I think it can be applied more directly:</p>
<pre><code>case class IntList(list: List[Int])
case class StringList(list: List[String])
implicit def il(list: List[Int]) = IntList(list)
implicit def sl(list: List[String]) = StringList(list)
def foo(i: IntList) { println("Int: " + i.list)}
def foo(s: StringList) { println("String: " + s.list)}
</code></pre>
<p>I think this is quite readable and straightforward.</p>
<p><strong>[Update]</strong></p>
<p>There is another easy way which seems to work:</p>
<pre><code>def foo(p: List[String]) { println("Strings") }
def foo[X: ClassTag](p: List[Int]) { println("Ints") }
def foo[X: ClassTag, Y: ClassTag](p: List[Double]) { println("Doubles") }
</code></pre>
<p>For every version you need an additional type parameter, so this doesn't scale, but I think for three or four versions it's fine.</p>
<p><strong>[Update 2]</strong></p>
<p>For exactly two methods I found another nice trick:</p>
<pre><code>def foo(list: => List[Int]) = { println("Int-List " + list)}
def foo(list: List[String]) = { println("String-List " + list)}
</code></pre> |
3,319,016 | Convert list to dictionary using linq and not worrying about duplicates | <p>I have a list of Person objects. I want to convert to a Dictionary where the key is the first and last name (concatenated) and the value is the Person object.</p>
<p>The issue is that I have some duplicated people, so this blows up if I use this code:</p>
<pre><code>private Dictionary<string, Person> _people = new Dictionary<string, Person>();
_people = personList.ToDictionary(
e => e.FirstandLastName,
StringComparer.OrdinalIgnoreCase);
</code></pre>
<p>I know it sounds weird but I don't really care about duplicates names for now. If there are multiple names I just want to grab one. Is there anyway I can write this code above so it just takes one of the names and doesn't blow up on duplicates?</p> | 3,319,092 | 12 | 4 | null | 2010-07-23 14:20:07.357 UTC | 25 | 2021-10-29 16:46:50.933 UTC | 2013-09-27 14:55:06.35 UTC | null | 2,642,204 | null | 4,653 | null | 1 | 197 | c#|linq|dictionary | 189,137 | <p>Here's the obvious, non linq solution:</p>
<pre class="lang-cs prettyprint-override"><code>foreach(var person in personList)
{
if(!myDictionary.ContainsKey(person.FirstAndLastName))
myDictionary.Add(person.FirstAndLastName, person);
}
</code></pre>
<p>If you don't mind always getting the last one added, you can avoid the double lookup like this:</p>
<pre class="lang-cs prettyprint-override"><code>foreach(var person in personList)
{
myDictionary[person.FirstAndLastName] = person;
}
</code></pre> |
7,930,001 | Force link to open in mobile safari from a web app with javascript | <p>When calling <code>window.open()</code> in a iOS web app, the page opens in the web app instead of mobile safari.</p>
<p><strong>How can I force the webpage to open in mobile safari?</strong></p>
<p>Note: Using straight <code><a href></code> links is not an option.</p> | 8,833,025 | 4 | 1 | null | 2011-10-28 13:36:04.997 UTC | 16 | 2018-11-19 19:59:09.723 UTC | 2012-01-29 03:38:34.607 UTC | null | 918,414 | null | 294,619 | null | 1 | 43 | javascript|ios|web-applications|mobile-safari|iphone-standalone-web-app | 54,836 | <p>This is possible. Tested with iOS5 stand-alone web app:</p>
<p>HTML:</p>
<pre><code><div id="foz" data-href="http://www.google.fi">Google</div>
</code></pre>
<p>JavaScript:</p>
<pre><code>document.getElementById("foz").addEventListener("click", function(evt) {
var a = document.createElement('a');
a.setAttribute("href", this.getAttribute("data-href"));
a.setAttribute("target", "_blank");
var dispatch = document.createEvent("HTMLEvents");
dispatch.initEvent("click", true, true);
a.dispatchEvent(dispatch);
}, false);
</code></pre>
<p>Can be tested here: <a href="http://www.hakoniemi.net/labs/linkkitesti.html" rel="noreferrer">http://www.hakoniemi.net/labs/linkkitesti.html</a></p> |
8,043,296 | What's the difference between returning void and returning a Task? | <p>In looking at various C# Async CTP samples I see some async functions that return <code>void</code>, and others that return the non-generic <code>Task</code>. I can see why returning a <code>Task<MyType></code> is useful to return data to the caller when the async operation completes, but the functions that I've seen that have a return type of <code>Task</code> never return any data. Why not return <code>void</code>?</p> | 8,043,882 | 4 | 0 | null | 2011-11-07 22:07:55.073 UTC | 54 | 2017-04-28 14:24:12.243 UTC | 2012-03-03 13:41:37 UTC | null | 41,071 | null | 82,017 | null | 1 | 140 | c#|asynchronous|task-parallel-library|return-type|async-ctp | 43,421 | <p>SLaks and Killercam's answers are good; I thought I'd just add a bit more context.</p>
<p>Your first question is essentially about what methods can be marked <code>async</code>.</p>
<blockquote>
<p>A method marked as <code>async</code> can return <code>void</code>, <code>Task</code> or <code>Task<T></code>. What are the differences between them?</p>
</blockquote>
<p>A <code>Task<T></code> returning async method can be awaited, and when the task completes it will proffer up a T. </p>
<p>A <code>Task</code> returning async method can be awaited, and when the task completes, the continuation of the task is scheduled to run.</p>
<p>A <code>void</code> returning async method cannot be awaited; it is a "fire and forget" method. It does work asynchronously, and you have no way of telling when it is done. This is more than a little bit weird; as SLaks says, normally you would only do that when making an asynchronous event handler. The event fires, the handler executes; no one is going to "await" the task returned by the event handler because event handlers do not return tasks, and even if they did, what code would use the Task for something? It's usually not user code that transfers control to the handler in the first place.</p>
<p>Your second question, in a comment, is essentially about what can be <code>await</code>ed:</p>
<blockquote>
<p>What kinds of methods can be <code>await</code>ed? Can a void-returning method be <code>await</code>ed?</p>
</blockquote>
<p>No, a void-returning method cannot be awaited. The compiler translates <code>await M()</code> into a call to <code>M().GetAwaiter()</code>, where <code>GetAwaiter</code> might be an instance method or an extension method. The value awaited has to be one for which you can get an awaiter; clearly a void-returning method does not produce a value from which you can get an awaiter.</p>
<p><code>Task</code>-returning methods can produce awaitable values. We anticipate that third parties will want to create their own implementations of <code>Task</code>-like objects that can be awaited, and you will be able to await them. However, you will not be allowed to declare <code>async</code> methods that return anything but <code>void</code>, <code>Task</code> or <code>Task<T></code>. </p>
<p>(UPDATE: My last sentence there may be falsified by a future version of C#; there is a proposal to allow return types other than task types for async methods.)</p>
<p>(UPDATE: The feature mentioned above made it in to C# 7.)</p> |
7,814,910 | How to send an HTML email using SMTP in PHP | <p>I've been able to send an email using SMTP in PHP, but when I try to change the Content Type to HTML, the email doesn't get delivered. This is the code I'm trying to use:</p>
<pre><code> require_once "Mail.php";
$from = "FPM <[email protected]>";
$from_name = "FPM";
$host = "localhost";
$username = "username";
$password = "password";
$subject = "Subject";
$message = "Message";
$to = "<[email protected]>";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject,
'MIME-Version' => '1.0',
'Content-Type' => "text/html; charset=ISO-8859-1"
);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $message);
</code></pre>
<p>If I take the 'Content-Type' argument out of the headers, it sends the message just fine. I don't know why adding that causes a problem.</p> | 7,814,944 | 6 | 0 | null | 2011-10-18 23:21:47.47 UTC | 1 | 2018-02-02 20:31:40.687 UTC | null | null | null | null | 1,002,144 | null | 1 | 3 | php|html|email|smtp | 47,273 | <p>The problem most likely lies in the Mail class, but since we don't know what Mail class you're using, it's difficult to answer. If you're not already doing so, I'd really think about using PHPMailer: <a href="https://github.com/PHPMailer/PHPMailer" rel="nofollow noreferrer">https://github.com/PHPMailer/PHPMailer</a></p> |
4,553,405 | How can I bind the second argument in a function but not the first (in an elegant way)? | <p>Is there a way in Haskell to bind the second argument but not the first of a function without using lambda functions or defining another "local" function?</p>
<p>Example. I have a binary function like:</p>
<pre><code>sub :: Int -> Int -> Int
sub x y = x - y
</code></pre>
<p>Now if I want to bind the first argument, I can do so easily using (sub someExpression):</p>
<pre><code>mapSubFrom5 x = map (sub 5) x
*Main> mapSubFrom5 [1,2,3,4,5]
[4,3,2,1,0]
</code></pre>
<p>That works fine if I want to bind the first n arguments without "gap".</p>
<p>If I want to bind the second argument but not the first, the two options I am aware of are more verbose:</p>
<p>Either via another, local, function:</p>
<pre><code>mapSub5 x = map sub5 x
where sub5 x = sub x 5
*Main> mapSub5 [1,2,3,4,5]
[-4,-3,-2,-1,0]
</code></pre>
<p>Or using lambda:</p>
<pre><code>mapSub5 x = map (\x -> sub x 5) x
</code></pre>
<p>While both are working fine, I like the elegance of "sub 5" and wonder if there is a similarly elegant way to bind the n-th (n > 1) argument of a function?</p> | 4,553,701 | 3 | 0 | null | 2010-12-29 10:48:04.597 UTC | 3 | 2010-12-29 11:51:48.07 UTC | 2010-12-29 11:51:48.07 UTC | null | 105,459 | null | 299,399 | null | 1 | 40 | haskell|functional-programming | 9,861 | <p><code>flip</code>, which produces a new function with the first two arguments inversed, has already been mentioned as a straigtforward solution. </p>
<p>However, it's worth noting that Haskell defines a nice infix syntax for binary operators.</p>
<p>First of all, it's simply</p>
<pre><code>sub = (-)
</code></pre>
<p>With parentheses around, all operators are - syntactially too - ordinary functions. Now we can curry operators with some special syntax. Binding to the first operand:</p>
<pre><code>addOne = (1 +)
</code></pre>
<p>... and to the second</p>
<pre><code>half = (/ 2)
</code></pre>
<p>Thus your code becomes</p>
<pre><code>map (-5) [1..5]
</code></pre>
<p>Unfortunately, <code>-5</code> is a number literal, but you get the point. :) Now since we can turn any function into a binary operator by putting backticks around it like in</p>
<pre><code>f x y == x `f` y
</code></pre>
<p>we can use this special operator syntax to write </p>
<pre><code>map (`sub` 5) [1..5]
</code></pre>
<p><hr/>
<strong>Note:</strong> Currying the first argument is common, the second one - as in your case - nicely possible. But: I wouldn't do that for futher arguments. Haskell functions are written in a style that the common ones to curry are in the front for exactly that reason.</p>
<p>Using some special syntax for further arguments feels much too implicit for me. Just use the lambda and give the variables descriptive names. </p> |
4,601,057 | Why is Selection Sort not stable? | <p>This might be trivial, but I don't understand why the default implementation of <a href="http://en.wikipedia.org/wiki/Selection_sort">Selection Sort</a> is not stable?</p>
<p>At each iteration you find the minimum element in the remaining array. When finding this minimum, you can choose the first minimum you find, and only update it when an element is actually smaller than it. So, the chosen element at each iteration is the first minimum - meaning, it's first on the previous sort order. So, to my understanding, the current sort will not destroy an order generated by a previous sort on equal elements.</p>
<p>What am I missing?</p> | 4,601,092 | 3 | 0 | null | 2011-01-05 05:19:12.857 UTC | 20 | 2013-04-05 03:02:39.277 UTC | null | null | null | null | 11,236 | null | 1 | 44 | algorithm|sorting | 22,243 | <p>A small example:</p>
<p>Let b = B in</p>
<p>< B > , < b > , < a > , < C > (with a < b < c)</p>
<p>After one cycle the sequence is sorted but the order of B and b has changed: </p>
<p>< a > , < b > , < B > , < c ></p>
<p>But you can however implement Selections Sort stable if you, instead of switching, insert the minimum value. But for that to be efficient you should have a data structure that supports insertion at a low cost or otherwise you end up with quadratic complexity. </p> |
4,116,487 | Android - Getting context from a Broadcast receiver onReceive() to send to | <p>I basically want to make an intent and pass it to a service from my BroadcastReceiver's onReceive().</p>
<p>So far I always used View.getContext(), but here, I'm stuck.
How exactly can I get the context so I can use <code>public Intent (Context packageContext, Class<?> cls)</code>?</p> | 4,116,741 | 3 | 0 | null | 2010-11-07 04:29:32.99 UTC | 7 | 2019-07-15 14:20:40.25 UTC | 2019-07-15 14:20:40.25 UTC | null | 1,000,551 | null | 455,048 | null | 1 | 86 | android|android-intent|service|broadcastreceiver|android-context | 45,835 | <pre><code>public abstract void onReceive(Context context, Intent intent)
</code></pre>
<p><code>onReceive</code> gives you the context. What more do you want?</p> |
4,469,277 | Asp.net MVC TextArea | <p>How to size the TextArea and assign Model Value to it in Asp.net Mvc</p> | 4,469,312 | 4 | 0 | null | 2010-12-17 09:46:23.51 UTC | 3 | 2021-11-29 13:15:34.45 UTC | null | null | null | null | 501,839 | null | 1 | 32 | asp.net-mvc | 56,200 | <p>Try this:</p>
<pre><code> <%=Html.TextAreaFor(
m => m.Description, 15, 20,
new RouteValueDictionary(new { @class = "someClass"}))%>
</code></pre>
<p>Edit:<br>
This wont work as far as I know</p>
<pre><code><%=Html.TextAreaFor(m => m.Description, new { cols = "20", rows = "15" })%>
</code></pre>
<p>because of this:</p>
<pre><code>private const int TextAreaRows = 2;
private const int TextAreaColumns = 20;
// ...
public static string TextArea(
this HtmlHelper htmlHelper, string name,
IDictionary<string, object> htmlAttributes) {
Dictionary<string, object> implicitAttributes = new Dictionary<string, object>();
implicitAttributes.Add("rows", TextAreaRows.ToString(CultureInfo.InvariantCulture));
implicitAttributes.Add("cols", TextAreaColumns.ToString(CultureInfo.InvariantCulture));
return TextAreaHelper(htmlHelper, name, true /* useViewData */, null /* value */, implicitAttributes, null /* explicitParameters */, htmlAttributes);
}
</code></pre> |
4,523,959 | std::map default value for build-in type | <p>Recently, I was confused by the std::map operator[] function.
In the MSDN library, it says: "If the argument key value is not found, then it is inserted along with the default value of the data type."
I tryed to search much more exactly explanation for this issue. For example here:
<a href="https://stackoverflow.com/questions/2333728/stdmap-default-value">std::map default value</a>
In this page, Michael Anderson said that "the default value is constructed by the default constructor(zero parameter constructor)".</p>
<p>Now my quest comes to this:"what the default value for the build-in type?". Was it compiler related? Or is there a standard for this issue by the c++ stardard committee?</p>
<p>I did a test on visual studio 2008 for the "int" type, and found the "int" type is construted with the value 0.</p> | 4,524,064 | 4 | 2 | null | 2010-12-24 03:12:00.127 UTC | 6 | 2012-10-19 00:15:21.8 UTC | 2017-05-23 11:53:56.753 UTC | null | -1 | null | 552,942 | null | 1 | 34 | c++|default-value|stdmap | 17,961 | <p>This is defined in the standard, yes. map is performing "default initialization" in this case. As you say, for class types, that calls a no-arguments constructor.</p>
<p>For built-in types, in the '98 standard, see section 8.5, "Initializers":</p>
<blockquote>
<p>To default-initialize an object of type T means:</p>
<ul>
<li>if T is a non-POD ...</li>
<li>if T is an array type ...</li>
<li>otherwise, the storage for the object is zero-initialized</li>
</ul>
</blockquote>
<p>And, previously,</p>
<blockquote>
<p>To zero-initialize storage for an object of type T means:</p>
<ul>
<li>if T is a scalar type, the storage is set to the value 0 (zero) converted to T</li>
</ul>
</blockquote>
<p>Scalar types are:</p>
<ul>
<li>Arithmetic types (integer, floating point)</li>
<li>Enumeration types</li>
<li>Pointer types</li>
<li>Pointer to member types</li>
</ul>
<p>In particular, the behaviour you see with an integer (initialized to zero) is defined by the standard, and you can rely on it.</p> |
4,705,759 | How to get CPU usage and RAM usage without exec? | <p>How does VBulletin get the system information without the use of <code>exec</code>? Is there any other information I can get about the server without exec? I am interested in:</p>
<ul>
<li>bandwidth used</li>
<li>system type</li>
<li>CPU speed/usage/count</li>
<li>RAM usage</li>
</ul> | 4,705,767 | 5 | 1 | null | 2011-01-16 14:05:10.163 UTC | 21 | 2020-02-20 19:59:03.97 UTC | 2015-04-16 09:06:58.67 UTC | null | 1,877,859 | null | 506,822 | null | 1 | 32 | php|cpu-usage|ram|bandwidth|system-information | 53,379 | <p><strong>Use <a href="http://phpsysinfo.sourceforge.net/" rel="noreferrer">PHPSysInfo</a></strong> library</p>
<p>phpSysInfo is a open source PHP script that displays information about the host being accessed. It will displays things like:</p>
<ul>
<li>Uptime</li>
<li>CPU</li>
<li>Memory</li>
<li>SCSI, IDE, PCI</li>
<li>Ethernet</li>
<li>Floppy</li>
<li>Video Information</li>
</ul>
<p>It directly parsed parses <code>/proc</code> and does not use <code>exec</code>.</p>
<hr>
<p><strong>Another way is to use <a href="http://sourceforge.net/projects/linfo/" rel="noreferrer">Linfo</a></strong>. It is a very fast <strong>cross-platform</strong> php script that describes the host server in extreme detail, giving information such as ram usage, disk space, raid arrays, hardware, network cards, kernel, os, samba/cups/truecrypt status, temps, disks, and much more.</p> |
4,623,446 | How do you sort files numerically? | <p>I'm processing some files in a directory and need the files to be sorted numerically. I found some examples on sorting—specifically with using the <code>lambda</code> pattern—at <a href="http://wiki.python.org/moin/HowTo/Sorting" rel="noreferrer">wiki.python.org</a>, and I put this together:</p>
<pre class="lang-py prettyprint-override"><code>import re
file_names = """ayurveda_1.tif
ayurveda_11.tif
ayurveda_13.tif
ayurveda_2.tif
ayurveda_20.tif
ayurveda_22.tif""".split('\n')
num_re = re.compile('_(\d{1,2})\.')
file_names.sort(
key=lambda fname: int(num_re.search(fname).group(1))
)
</code></pre>
<p>Is there a better way to do this?</p> | 4,623,518 | 6 | 4 | null | 2011-01-07 07:34:12.573 UTC | 19 | 2021-10-28 23:55:28.41 UTC | 2021-10-28 23:55:28.41 UTC | null | 246,801 | null | 246,801 | null | 1 | 38 | python|sorting | 38,579 | <p>This is called "natural sorting" or "human sorting" (as opposed to lexicographical sorting, which is the default). <a href="http://nedbatchelder.com/blog/200712/human_sorting.html" rel="noreferrer">Ned B wrote up a quick version of one.</a></p>
<pre><code>import re
def tryint(s):
try:
return int(s)
except:
return s
def alphanum_key(s):
""" Turn a string into a list of string and number chunks.
"z23a" -> ["z", 23, "a"]
"""
return [ tryint(c) for c in re.split('([0-9]+)', s) ]
def sort_nicely(l):
""" Sort the given list in the way that humans expect.
"""
l.sort(key=alphanum_key)
</code></pre>
<p>It's similar to what you're doing, but perhaps a bit more generalized.</p> |
4,533,848 | Writing a jquery plugin in coffeescript - how to get "(function($)" and "(jQuery)"? | <p>I am writing a jquery plugin in coffeescript but am not sure how to get the function wrapper part right.</p>
<p>My coffeescript starts with this:</p>
<pre><code>$.fn.extend({
myplugin: ->
@each ->
</code></pre>
<p>Which creates the javascript with a function wrapper: </p>
<pre><code>(function() {
$.fn.extend({
myplugin: function() {
return this.each(function() {
</code></pre>
<p>but I want a '$' passed in like this: </p>
<pre><code>(function($) {
$.fn.extend({
</code></pre>
<p>Similar for the ending I have... nothing in particular in coffeescript.<br>
I get this in javascript:</p>
<pre><code>})();
</code></pre>
<p>But would like this:</p>
<pre><code>})(jQuery);
</code></pre>
<p>Does anyone know how to achieve this with the coffeescript compiler?
Or what is the best way to get this done within coffeescript?</p> | 4,534,417 | 8 | 0 | null | 2010-12-26 12:43:12.587 UTC | 10 | 2014-09-04 16:19:41.267 UTC | 2010-12-26 13:09:53.317 UTC | null | 43,453 | null | 43,453 | null | 1 | 36 | javascript|jquery|coffeescript | 10,701 | <p>The answer is that you don't need to call it like that in CoffeeScript -- your script is already safely wrapped in a closure, so there's no need for jQuery-passed-in-as-a-parameter-tricks. Just write:</p>
<pre><code>$ = jQuery
</code></pre>
<p>... at the top of your script, and you're good to go.</p> |
4,627,330 | Difference between fprintf, printf and sprintf? | <p>Can anyone explain in simple English about the differences between <code>printf</code>, <code>fprintf</code>, and <code>sprintf</code> with examples?</p>
<p>What stream is it in?</p>
<p>I'm really confused between the three of these while reading about "File Handling in C".</p> | 4,628,144 | 9 | 13 | null | 2011-01-07 15:49:47.45 UTC | 117 | 2022-08-05 10:02:03.847 UTC | 2015-01-16 20:59:36.727 UTC | null | 542,517 | null | 435,559 | null | 1 | 269 | c|io|stream|printf | 249,625 | <p>In C, a "stream" is an abstraction; from the program's perspective it is simply a producer (input stream) or consumer (output stream) of bytes. It can correspond to a file on disk, to a pipe, to your terminal, or to some other device such as a printer or tty. The <code>FILE</code> type contains information about the stream. Normally, you don't mess with a <code>FILE</code> object's contents directly, you just pass a pointer to it to the various I/O routines. </p>
<p>There are three standard streams: <code>stdin</code> is a pointer to the standard input stream, <code>stdout</code> is a pointer to the standard output stream, and <code>stderr</code> is a pointer to the standard error output stream. In an interactive session, the three usually refer to your console, although you can redirect them to point to other files or devices:</p>
<pre><code>$ myprog < inputfile.dat > output.txt 2> errors.txt
</code></pre>
<p>In this example, <code>stdin</code> now points to <code>inputfile.dat</code>, <code>stdout</code> points to <code>output.txt</code>, and <code>stderr</code> points to <code>errors.txt</code>. </p>
<p><code>fprintf</code> writes formatted text to the output stream you specify. </p>
<p><code>printf</code> is equivalent to writing <code>fprintf(stdout, ...)</code> and writes formatted text to wherever the standard output stream is currently pointing.</p>
<p><code>sprintf</code> writes formatted text to an array of <code>char</code>, as opposed to a stream. </p> |
4,533,116 | Minimum Hardware requirements for Android development | <p>Need information about minimum hardware requirement for better experience in developing Android application. </p>
<p>My current configuration is as follows. P4 3.0 GHz, 512 MB of ram. </p>
<p>Started with Hello Android development on my machine and experience was sluggish, was using Eclipse Helios for development. Emulator used to take lot of time to start. And running program too.<br>
Do I need to upgrade my machine for the development purpose or is there anything else I am missing on my machine(like heavy processing by some other application I might have installed). </p>
<p>And If I do need to upgrade, do I need to upgrade my processor too(that counts to new machine actually, which I am not in favor of), or only upgrading RAM will suffice. </p> | 4,533,162 | 10 | 2 | null | 2010-12-26 07:42:36.477 UTC | 4 | 2013-06-04 17:10:54.097 UTC | 2013-06-04 17:10:54.097 UTC | user1228 | null | null | 238,748 | null | 1 | 33 | android | 140,598 | <p>Firstly, there is an issue with the ADT plugin and Helios which causes lag with looking up Android classes - use Galileo instead (v3.5).</p>
<p>Secondly, the emulators become more resource hungry depending on the version of Android you're developing for. Example, I have a P4 2.4GHz, 1GB RAM PC with Win XP 32-bit and an Android v2.2 emulator takes at least 4-5 minutes to load up. An Android v1.6 emulator on the other hand loads up in less than 1 minute. Remember though that once the emulator is up and running, you can leave it loaded and it will be more responsive than first use.</p>
<p>Also bear in mind that if you give your emulator a 2GB SD card (for example) it will try to create that through virtual memory if there isn't enough physical memory.</p> |
4,205,181 | Insert into a MySQL table or update if exists | <p>I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.</p>
<p>For example:</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO table_name (ID, NAME, AGE) VALUES(1, "A", 19);
</code></pre>
<p>Let’s say the unique key is <code>ID</code>, and in my <strong>Database</strong>, there is a row with <code>ID = 1</code>. In that case, I want to update that row with these values. Normally this gives an error.<br />
If I use <code>INSERT IGNORE</code> it will ignore the error, but it still won’t update.</p> | 4,205,207 | 11 | 3 | null | 2010-11-17 14:08:52.573 UTC | 300 | 2022-04-04 20:13:22.66 UTC | 2020-08-12 12:55:51.41 UTC | null | 814,702 | null | 434,375 | null | 1 | 1,079 | mysql|sql|insert-update|upsert | 1,130,095 | <p>Use <a href="https://dev.mysql.com/doc/en/insert-on-duplicate.html" rel="noreferrer"><code>INSERT ... ON DUPLICATE KEY UPDATE</code></a></p>
<p><strong>QUERY:</strong></p>
<pre><code>INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name="A", age=19
</code></pre> |
4,258,700 | Collections.sort with multiple fields | <p>I have a list of "Report" objects with three fields (All String type)-</p>
<pre><code>ReportKey
StudentNumber
School
</code></pre>
<p>I have a sort code goes like-</p>
<pre><code>Collections.sort(reportList, new Comparator<Report>() {
@Override
public int compare(final Report record1, final Report record2) {
return (record1.getReportKey() + record1.getStudentNumber() + record1.getSchool())
.compareTo(record2.getReportKey() + record2.getStudentNumber() + record2.getSchool());
}
});
</code></pre>
<p>For some reason, I don't have the sorted order. One advised to put spaces in between fields, but why?</p>
<p>Do you see anything wrong with the code?</p> | 4,258,738 | 14 | 3 | null | 2010-11-23 17:03:46.317 UTC | 44 | 2021-10-20 15:07:41.317 UTC | null | null | null | null | 517,754 | null | 1 | 106 | java|sorting|collections | 199,348 | <blockquote>
<p>Do you see anything wrong with the code?</p>
</blockquote>
<p>Yes. Why are you adding the three fields together before you compare them?</p>
<p>I would probably do something like this: (assuming the fields are in the order you wish to sort them in)</p>
<pre><code>@Override public int compare(final Report record1, final Report record2) {
int c;
c = record1.getReportKey().compareTo(record2.getReportKey());
if (c == 0)
c = record1.getStudentNumber().compareTo(record2.getStudentNumber());
if (c == 0)
c = record1.getSchool().compareTo(record2.getSchool());
return c;
}
</code></pre> |
14,360,706 | When to use boost::optional and when to use std::unique_ptr in cases when you want to implement a function that can return "nothing"? | <p>From what I understand there are 2* ways you can implement a function that sometimes doesnt return a result(for example is person found in a list of ppl). </p>
<p>*- we ignore raw ptr version, pair with a bool flag, and exception when none found version.</p>
<pre><code>boost::optional<Person> findPersonInList();
</code></pre>
<p>or </p>
<pre><code>std::unique_ptr<Person> findPersonInList();
</code></pre>
<p>So are there any reasons to prefere one over the other?</p> | 14,360,982 | 7 | 7 | null | 2013-01-16 14:31:56.583 UTC | 8 | 2018-01-13 08:44:53.24 UTC | 2013-01-16 23:48:19.363 UTC | null | 636,019 | null | 700,825 | null | 1 | 23 | c++|boost|c++11|unique-ptr|boost-optional | 8,898 | <p>It depends: do you wish to return a <em>handle</em> or a <em>copy</em>.</p>
<p>If you wish to return a <em>handle</em>:</p>
<ul>
<li><code>Person*</code></li>
<li><code>boost::optional<Person&></code></li>
</ul>
<p>are both acceptable choices. I tend to use a <code>Ptr<Person></code> class which throws in case of null access, but that's my paranoia.</p>
<p>If you wish to return a <em>copy</em>:</p>
<ul>
<li><code>boost::optional<Person></code> for non polymorphic classes</li>
<li><code>std::unique_ptr<Person></code> for polymorphic classes</li>
</ul>
<p>because dynamic allocation incurs an overhead, so you only use it when necessary.</p> |
14,827,650 | pyplot scatter plot marker size | <p>In the pyplot document for scatter plot:</p>
<pre><code>matplotlib.pyplot.scatter(x, y, s=20, c='b', marker='o', cmap=None, norm=None,
vmin=None, vmax=None, alpha=None, linewidths=None,
faceted=True, verts=None, hold=None, **kwargs)
</code></pre>
<p>The marker size</p>
<blockquote>
<p>s:
size in points^2. It is a scalar or an array of the same length as x and y.</p>
</blockquote>
<p>What kind of unit is <code>points^2</code>? What does it mean? Does <code>s=100</code> mean <code>10 pixel x 10 pixel</code>?</p>
<p>Basically I'm trying to make scatter plots with different marker sizes, and I want to figure out what does the <code>s</code> number mean.</p> | 14,860,958 | 6 | 7 | null | 2013-02-12 07:37:29.047 UTC | 150 | 2020-11-28 22:00:04.76 UTC | 2019-02-01 15:01:14.993 UTC | null | 10,960,882 | null | 1,382,745 | null | 1 | 562 | matplotlib|marker|scatter | 1,380,423 | <p>This can be a somewhat confusing way of defining the size but you are basically specifying the <em>area</em> of the marker. This means, to double the width (or height) of the marker you need to increase <code>s</code> by a factor of 4. [because A = W<em>H => (2W)</em>(2H)=4A]</p>
<p>There is a reason, however, that the size of markers is defined in this way. Because of the scaling of area as the square of width, doubling the width actually appears to increase the size by more than a factor 2 (in fact it increases it by a factor of 4). To see this consider the following two examples and the output they produce.</p>
<pre class="lang-py prettyprint-override"><code># doubling the width of markers
x = [0,2,4,6,8,10]
y = [0]*len(x)
s = [20*4**n for n in range(len(x))]
plt.scatter(x,y,s=s)
plt.show()
</code></pre>
<p>gives</p>
<p><img src="https://i.stack.imgur.com/m8xcU.png" alt="enter image description here" /></p>
<p>Notice how the size increases very quickly. If instead we have</p>
<pre class="lang-py prettyprint-override"><code># doubling the area of markers
x = [0,2,4,6,8,10]
y = [0]*len(x)
s = [20*2**n for n in range(len(x))]
plt.scatter(x,y,s=s)
plt.show()
</code></pre>
<p>gives</p>
<p><img src="https://i.stack.imgur.com/Znaw8.png" alt="enter image description here" /></p>
<p>Now the apparent size of the markers increases roughly linearly in an intuitive fashion.</p>
<p>As for the exact meaning of what a 'point' is, it is fairly arbitrary for plotting purposes, you can just scale all of your sizes by a constant until they look reasonable.</p>
<p>Hope this helps!</p>
<p><strong>Edit:</strong> (In response to comment from @Emma)</p>
<p>It's probably confusing wording on my part. The question asked about doubling the width of a circle so in the first picture for each circle (as we move from left to right) it's width is double the previous one so for the area this is an exponential with base 4. Similarly the second example each circle has <em>area</em> double the last one which gives an exponential with base 2.</p>
<p>However it is the second example (where we are scaling area) that doubling area appears to make the circle twice as big to the eye. Thus if we want a circle to appear a factor of <code>n</code> bigger we would increase the area by a factor <code>n</code> not the radius so the apparent size scales linearly with the area.</p>
<p><strong>Edit</strong> to visualize the comment by @TomaszGandor:</p>
<p>This is what it looks like for different functions of the marker size:</p>
<p><a href="https://i.stack.imgur.com/3H1BQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3H1BQ.png" alt="Exponential, Square, or Linear size" /></a></p>
<pre class="lang-py prettyprint-override"><code>x = [0,2,4,6,8,10,12,14,16,18]
s_exp = [20*2**n for n in range(len(x))]
s_square = [20*n**2 for n in range(len(x))]
s_linear = [20*n for n in range(len(x))]
plt.scatter(x,[1]*len(x),s=s_exp, label='$s=2^n$', lw=1)
plt.scatter(x,[0]*len(x),s=s_square, label='$s=n^2$')
plt.scatter(x,[-1]*len(x),s=s_linear, label='$s=n$')
plt.ylim(-1.5,1.5)
plt.legend(loc='center left', bbox_to_anchor=(1.1, 0.5), labelspacing=3)
plt.show()
</code></pre> |
2,495,550 | Define a method that is a closure in Ruby | <p>I'm re-defining a method in an object in ruby and I need the new method to be a closure. For example:</p>
<pre><code>def mess_it_up(o)
x = "blah blah"
def o.to_s
puts x # Wrong! x doesn't exists here, a method is not a closure
end
end
</code></pre>
<p>Now if I define a Proc, it is a closure:</p>
<pre><code>def mess_it_up(o)
x = "blah blah"
xp = Proc.new {||
puts x # This works
end
# but how do I set it to o.to_s.
def o.to_s
xp.call # same problem as before
end
end
</code></pre>
<p>Any ideas how to do it?</p>
<p>Thanks.</p> | 2,495,650 | 3 | 0 | null | 2010-03-22 20:38:22.693 UTC | 9 | 2014-12-19 22:28:11.87 UTC | null | null | null | null | 6,068 | null | 1 | 10 | ruby|closures | 3,046 | <p>This works (tested in irb):</p>
<p><strong>NOTE: This changes only <code>str</code> - not all instances of String. Read below for details as to why this works</strong></p>
<pre><code>another_str = "please don't change me!"
str = "ha, try to change my to_s! hahaha!"
proc = Proc.new { "take that, Mr. str!" }
singleton_class = class << str; self; end
singleton_class.send(:define_method, :to_s) do
proc.call
end
puts str.to_s #=> "take that, Mr. str!"
puts another_str.to_s #=> "please don't change me!"
# What! We called String#define_method, right?
puts String #=> String
puts singleton_class #=> #<Class:#<String:0x3c788a0>>
# ... nope! singleton_class is *not* String
# Keep reading if you're curious :)
</code></pre>
<p>This works because you are opening str's <a href="http://www.contextualdevelopment.com/articles/2008/ruby-singleton" rel="noreferrer">singleton class</a> and defining a method there. Because this, as well as the call to <a href="http://ruby-doc.org/core/classes/Module.html#M001654" rel="noreferrer">Module#define_method</a>, have what some call a "flat scope", you're able to access variables that would be out of scope if you used <code>def to_s; 'whatever'; end</code>.</p>
<p>You may want to check out some of these other "metaprogramming spells" here:</p>
<p><a href="http://media.pragprog.com/titles/ppmetr/spells.pdf" rel="noreferrer">media.pragprog.com/titles/ppmetr/spells.pdf</a></p>
<p><br/>
<strong>Why does it only change <code>str</code>?</strong></p>
<p>Because Ruby has a couple interesting tricks up it's sleeves. In the Ruby object model, a method invocation results in the reciever searching not only it's class (and <em>it's</em> ancestors), but also it's singleton class (or as Matz would call it, it's eigenclass). This singleton class is what allows you to [re]define a method for a single object. These methods are called "singleton methods". In the example above, we are doing just that - defining a singleton method name <code>to_s</code>. It's functionaly identical to this:</p>
<pre><code>def str.to_s
...
end
</code></pre>
<p>The only difference is that we get to use a closure when calling <code>Module#define_method</code>, whereas <code>def</code> is a keyword, which results in a change of scope.</p>
<p><strong>Why can't it be simpler?</strong></p>
<p>Well, the good news is that you're programming in Ruby, so feel free to go crazy:</p>
<pre><code>class Object
def define_method(name, &block)
singleton = class << self; self; end
singleton.send(:define_method, name) { |*args| block.call(*args) }
end
end
str = 'test'
str.define_method(:to_s) { "hello" }
str.define_method(:bark) { "woof!" }
str.define_method(:yell) { "AAAH!" }
puts str.to_s #=> hello
puts str.bark #=> woof!
puts str.yell #=> AAAH!
</code></pre>
<p><strong>And, if you're curious...</strong></p>
<p>You know class methods? Or, in some languages, we'd call them static methods? Well, those don't <em>really</em> exist in Ruby. In Ruby, class methods are really just methods defined in the Class object's singleton class.</p>
<p>If that all sounds crazy, take a look at the links I provided above. A lot of Ruby's power can only be tapped into if you know how to metaprogram - in which case you'll really want to know about singleton classes/methods, and more generally, the Ruby object model.</p>
<p>HTH</p>
<p>-Charles</p> |
21,069,668 | Alternative to dict comprehension prior to Python 2.7 | <p>How can I make the following functionality compatible with versions of Python earlier than Python 2.7?</p>
<pre><code>gwfuncs = [reboot, flush_macs, flush_cache, new_gw, revert_gw, send_log]
gw_func_dict = {chr(2**i): func for i, func in enumerate(gwfuncs[:8])}
</code></pre> | 21,069,676 | 1 | 0 | null | 2014-01-12 00:19:30.683 UTC | 6 | 2020-09-23 15:03:33.807 UTC | 2020-09-23 15:03:33.807 UTC | null | 364,696 | null | 1,198,201 | null | 1 | 34 | python|dictionary|python-2.x|python-2.6|dictionary-comprehension | 10,708 | <p>Use:</p>
<pre><code>gw_func_dict = dict((chr(2**i), func) for i, func in enumerate(gwfuncs[:8]))
</code></pre>
<p>That's the <code>dict()</code> function with a generator expression producing <code>(key, value)</code> pairs.</p>
<p>Or, to put it generically, a dict comprehension of the form:</p>
<pre><code>{key_expr: value_expr for targets in iterable <additional loops or if expressions>}
</code></pre>
<p>can always be made compatible with Python < 2.7 by using:</p>
<pre><code>dict((key_expr, value_expr) for targets in iterable <additional loops or if expressions>)
</code></pre> |
56,128,114 | Using Rails-UJS in JS modules (Rails 6 with webpacker) | <p>i just switched to Rails 6 (6.0.0.rc1) which uses the <a href="https://github.com/rails/webpacker" rel="noreferrer">Webpacker</a> gem by default for Javascript assets together with Rails-UJS. I want to use Rails UJS in some of my modules in order to submit forms from a function with:</p>
<pre><code>const form = document.querySelector("form")
Rails.fire(form, "submit")
</code></pre>
<p>In former Rails versions with Webpacker installed, the <code>Rails</code> reference seemed to be "globally" available in my modules, but now i get this when calling <code>Rails.fire</code>…</p>
<pre><code>ReferenceError: Rails is not defined
</code></pre>
<p><strong>How can i make <code>Rails</code> from <code>@rails/ujs</code> available to a specific or to all of my modules?</strong></p>
<p>Below my setup…</p>
<p><em>app/javascript/controllers/form_controller.js</em></p>
<pre><code>import { Controller } from "stimulus"
export default class extends Controller {
// ...
submit() {
const form = this.element
Rails.fire(form, "submit")
}
// ...
}
</code></pre>
<p><em>app/javascript/controllers.js</em></p>
<pre><code>// Load all the controllers within this directory and all subdirectories.
// Controller files must be named *_controller.js.
import { Application } from "stimulus"
import { definitionsFromContext } from "stimulus/webpack-helpers"
const application = Application.start()
const context = require.context("controllers", true, /_controller\.js$/)
application.load(definitionsFromContext(context))
</code></pre>
<p><em>app/javascript/packs/application.js</em></p>
<pre><code>require("@rails/ujs").start()
import "controllers"
</code></pre>
<p>Thanks!</p> | 57,543,894 | 5 | 0 | null | 2019-05-14 10:17:59.497 UTC | 7 | 2020-12-09 07:07:02.78 UTC | null | null | null | null | 2,355,143 | null | 1 | 37 | ruby-on-rails|webpack|webpacker|rails-ujs | 17,317 | <p>in my <code>app/javascript/packs/application.js</code>:</p>
<pre><code>import Rails from '@rails/ujs';
Rails.start();
</code></pre>
<p>and then in whatever module, controller, component I'm writing:</p>
<pre><code>import Rails from '@rails/ujs';
</code></pre> |
24,865,916 | How to set multiple key-value pairs to one cookie? | <p>I am using this line to set multiple key-value pair at once to one cookie</p>
<pre><code>document.cookie="username=John Smith; test1=ew; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";
</code></pre>
<p>it seemed <code>test1</code> is not set to the cookie successfully, because when I write <code>document.cookie</code> in the console, it didn't print this key-value pair. Anyone know how to <strong>set multiple key-value pair</strong> to <strong>ONE cookie</strong>?</p> | 24,866,121 | 2 | 0 | null | 2014-07-21 13:07:47.047 UTC | 6 | 2019-09-26 06:37:43.473 UTC | null | null | null | null | 1,737,425 | null | 1 | 19 | javascript|cookies | 52,412 | <p>It does not make sense to store multiple key-value pairs into one cookie, because by definition <strong>a cookie represents one key-value pair</strong>.</p>
<p>I believe you don't understand well <a href="http://www.quirksmode.org/js/cookies.html#script">how <code>document.cookie</code> works</a>. It is not a standard JS string: when you set it, the cookie definition it contains is <strong>appended</strong> to the list of existing cookies. That is, you cannot set two cookies at the same time using this API.</p>
<p>You have two solutions:</p>
<ul>
<li><p>Use a cookie for each key-value you want to store:</p>
<pre><code>document.cookie = "myCookie=myValue";
document.cookie = "myOtherCookie=myOtherValue";
</code></pre></li>
<li><p>Store a single cookie with a custom serialization of your complex data, for example JSON:</p>
<pre><code>document.cookie = "myCookie=" + JSON.stringify({foo: 'bar', baz: 'poo'});
</code></pre></li>
</ul> |
24,897,801 | Enable Access-Control-Allow-Origin for multiple domains in Node.js | <p>I'm trying to allow CORS in node.js but the problem is that I can't set <code>*</code> to <code>Access-Control-Allow-Origin</code> if <code>Access-Control-Allow-Credentials</code> is set.</p>
<p>Also the specification said I can't do an array or comma separated value for <code>Access-Control-Allow-Origin</code> and the suggested method would be to do something similar to this <a href="https://stackoverflow.com/questions/1653308/access-control-allow-origin-multiple-origin-domains">Access-Control-Allow-Origin Multiple Origin Domains?</a></p>
<p>But I can't seem to do this way in node.js</p>
<pre><code>["http://example.com:9001", "http://example.com:5001"].map(domain => {
res.setHeader("Access-Control-Allow-Origin", domain);
});
res.header("Access-Control-Allow-Credentials", true);
</code></pre>
<p>The problem here is that it's bein override by the last value in the array, so the header will be set to <code>res.setHeader("Access-Control-Allow-Origin", "http://example.com:5001");</code></p>
<p>Error from the client browser:</p>
<blockquote>
<p>XMLHttpRequest cannot load <a href="http://example.com:9090/api/sync" rel="noreferrer">http://example.com:9090/api/sync</a>. The
'Access-Control-Allow-Origin' header has a value
'http://example.com:5001' that is not equal to the supplied origin.
Origin 'http://example.com:9001' is therefore not allowed access.</p>
</blockquote> | 32,481,816 | 4 | 0 | null | 2014-07-22 21:03:52.817 UTC | 36 | 2020-09-08 11:58:44.727 UTC | 2020-09-08 11:58:44.727 UTC | null | 990,356 | null | 775,119 | null | 1 | 96 | node.js|cors | 86,740 | <p>Here is what I use in my express application to allow multiple origins</p>
<pre><code>app.use((req, res, next) => {
const allowedOrigins = ['http://127.0.0.1:8020', 'http://localhost:8020', 'http://127.0.0.1:9000', 'http://localhost:9000'];
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
}
//res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8020');
res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.header('Access-Control-Allow-Credentials', true);
return next();
});
</code></pre> |
3,075,130 | What is the difference between .*? and .* regular expressions? | <p>I'm trying to split up a string into two parts using regex. The string is formatted as follows:</p>
<pre><code>text to extract<number>
</code></pre>
<p>I've been using <code>(.*?)<</code> and <code><(.*?)></code> which work fine but after reading into regex a little, I've just started to wonder why I need the <code>?</code> in the expressions. I've only done it like that after finding them through this site so I'm not exactly sure what the difference is.</p> | 3,075,150 | 3 | 1 | null | 2010-06-19 10:16:59.383 UTC | 101 | 2021-12-18 20:12:56.83 UTC | 2020-02-07 12:13:29.613 UTC | null | 1,243,762 | null | 370,965 | null | 1 | 197 | regex|regex-greedy|non-greedy | 147,662 | <p>It is the difference between greedy and non-greedy quantifiers.</p>
<p>Consider the input <code>101000000000100</code>.</p>
<p>Using <code>1.*1</code>, <code>*</code> is greedy - it will match all the way to the end, and then backtrack until it can match <code>1</code>, leaving you with <code>1010000000001</code>.<br>
<code>.*?</code> is non-greedy. <code>*</code> will match nothing, but then will try to match extra characters until it matches <code>1</code>, eventually matching <code>101</code>.</p>
<p>All quantifiers have a non-greedy mode: <code>.*?</code>, <code>.+?</code>, <code>.{2,6}?</code>, and even <code>.??</code>.</p>
<p>In your case, a similar pattern could be <code><([^>]*)></code> - matching anything but a greater-than sign (strictly speaking, it matches zero or more characters other than <code>></code> in-between <code><</code> and <code>></code>).</p>
<p>See <a href="http://www.rexegg.com/regex-quantifiers.html#cheat_sheet" rel="noreferrer"><strong>Quantifier Cheat Sheet</strong></a>.</p> |
38,931,468 | Nginx reverse proxy error:14077438:SSL SSL_do_handshake() failed | <p>So i am using following settings to create one reverse proxy for site as below. </p>
<pre><code> server {
listen 80;
server_name mysite.com;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
root /home/ubuntu/p3;
location / {
proxy_pass https://mysiter.com/;
proxy_redirect https://mysiter.com/ $host;
proxy_set_header Accept-Encoding "";
}
}
</code></pre>
<p>But getting BAD GATE WAY 502 error and below is the log.</p>
<pre><code>2016/08/13 09:42:28 [error] 26809#0: *60 SSL_do_handshake() failed (SSL: error:14077438:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert internal error) while SSL handshaking to upstream, client: 103.255.5.68, server: mysite.com, request: "GET / HTTP/1.1", upstream: "https://105.27.188.213:443/", host: "mysite.com"
2016/08/13 09:42:28 [error] 26809#0: *60 SSL_do_handshake() failed (SSL: error:14077438:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert internal error) while SSL handshaking to upstream, client: 103.255.5.68, server: mysite.com, request: "GET / HTTP/1.1", upstream: "https://105.27.188.213:443/", host: "mysite.com"
</code></pre>
<p>Any help will be greatly appreciated. </p> | 49,116,797 | 2 | 0 | null | 2016-08-13 09:50:09.133 UTC | 8 | 2018-03-05 18:05:55.457 UTC | null | null | null | null | 5,224,982 | null | 1 | 27 | ssl|nginx|proxy|reverse-proxy | 41,752 | <p>Seeing the exact same error on Nginx 1.9.0 and it looks like it was caused by the HTTPS endpoint using SNI.</p>
<p>Adding this to the proxy location fixed it:</p>
<p><code>proxy_ssl_server_name on;</code></p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Server_Name_Indication" rel="noreferrer">https://en.wikipedia.org/wiki/Server_Name_Indication</a></li>
<li><a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ssl_server_name" rel="noreferrer">http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ssl_server_name</a></li>
</ul> |
48,711,065 | Go to the TypeScript source file instead of the type definition file in VS Code | <p>I created a custom <code>npm</code> library that is used in some root projects. This library is written in TypeScript. All sources are under a <code>/src</code> folder.</p>
<p>The <code>tsconfig.json</code> of the library contains those compiler options : </p>
<pre><code>"sourceMap": true
"outDir": "dist"
</code></pre>
<p>The <code>package.json</code> file contains : </p>
<pre><code>"main": "dist/src/index.js",
"typings": "dist/src",
"files": [
"src",
"dist"
],
</code></pre>
<p>In the end, the generated package contains the generated <code>.js</code> files, the <code>d.ts</code> files and the <code>.ts</code> source files :</p>
<pre><code>- package.json
- /dist (`.js` and `d.ts` files)
- /src (`.ts` files)
</code></pre>
<p>In a root project where this custom library has been installed, I'm then able to add a breakpoint on a line calling a function imported from the library and stepping into it to debug its code, all in TypeScript. This is great!</p>
<p><strong>But</strong>, in Visual Studio Code, when I CTRL-Click on a function imported from the library, without debugging, it leads me <em>to the <code>d.ts</code> type definition file</em>. I would prefere it to lead <em>to the <code>.ts</code> source file</em>! The way it is currently, I have to browse by myself to the <code>/src</code> folder of the library, under <code>/node_modules</code>, if I need to see the actual source code.</p>
<p>Is there a way to go to the TypeScript source file directly in VSCode, instead of the type definition file?</p> | 51,261,384 | 4 | 0 | null | 2018-02-09 17:23:21.917 UTC | 7 | 2022-06-10 09:24:51.413 UTC | 2018-02-09 19:07:46.093 UTC | null | 215,552 | null | 843,699 | null | 1 | 47 | node.js|typescript|npm|visual-studio-code | 7,008 | <p>Since Typescript 2.9 it is possible to compile your library with the <code>declarationMap</code> flag</p>
<pre><code>./node_modules/typescript/bin/tsc -p . --declarationMap
</code></pre>
<p>Doing so creates a declaration map file (<code>dist/ActionApi.d.ts.map</code>) and a link to the map at the bottom of the corresponding d.ts file</p>
<pre><code>//# sourceMappingURL=ActionApi.d.ts.map
</code></pre>
<p>When VSCodes encounters such a declarationMap it knows where to go to and leads you directly to the source code. </p> |
63,499,520 | App Tracking Transparency How does effect apps showing ads? - IDFA iOS14 | <p>The recent WWDC state that about iOS 14:</p>
<blockquote>
<p>With iOS 14, iPadOS 14, and tvOS 14, you will need to receive the
user’s permission through the AppTrackingTransparency framework to
track them or access their device’s advertising identifier. Tracking
refers to the act of linking user or device data collected from your
app with user or device data collected from other companies’ apps,
websites, or offline properties for targeted advertising or advertising</p>
</blockquote>
<p>Reference: <a href="https://developer.apple.com/app-store/user-privacy-and-data-use/" rel="noreferrer">User Privacy and Data Use</a></p>
<p>As per this guidelines, We need to ask the user for tracking permission using <code>ATTrackingManager</code> (<a href="https://developer.apple.com/documentation/apptrackingtransparency" rel="noreferrer">AppTrackingTransparency</a>) framework.</p>
<p>I have a few apps on AppStore, Which is using <code>Google AdMob</code> & <code>FBAudienceNetwork</code> to deliver ads to the user.</p>
<h2>Question:</h2>
<ol>
<li><p>What's happen if I don't upgrade these apps as per the last WWDC guidelines? Is app continue ads serving to the user?</p>
</li>
<li><p>What's happening if User doesn't give tracking permission to the app?</p>
</li>
<li><p>App update does make any impact on revenue from ads?</p>
</li>
</ol>
<p>Try to answer this question respected to ads serving, revenue and impact of <code>App Tracking Transparency</code></p>
<h2>Below are all references which I had referred already.</h2>
<p><a href="https://developer.apple.com/app-store/user-privacy-and-data-use/" rel="noreferrer">User Privacy and Data Use</a></p>
<p><a href="https://developer.apple.com/documentation/apptrackingtransparency" rel="noreferrer">App Tracking Transparency</a></p>
<p><a href="https://support.google.com/admob/answer/9997589?hl=en-GB" rel="noreferrer">Google AdMob</a></p>
<p><a href="https://developers.google.com/admob/ios/ios14" rel="noreferrer">Google AdMob : Implementation</a></p>
<p><a href="https://developer.apple.com/documentation/adsupport" rel="noreferrer">AdSupport</a></p> | 63,522,856 | 3 | 0 | null | 2020-08-20 06:34:35.917 UTC | 16 | 2021-04-30 09:56:04.44 UTC | 2021-03-03 15:53:18.51 UTC | null | 1,752,496 | null | 5,036,586 | null | 1 | 41 | ios|swift|ads|ios14|idfa | 20,202 | <p>The firstly, i want to talk about the <strong>IDFA</strong>:</p>
<blockquote>
<p>The Identity for Advertisers (IDFA) is the individual and random identifier used by Apple to identify and measure iOS user devices.</p>
</blockquote>
<p><strong>Bellow IOS14</strong>, Every AdNetworks use <strong>IDFA</strong> for defund a specific user, then They use <strong>IDFA</strong> to be used to deliver personalized ads to user. so <strong>IDFA</strong> help the AdNetworks can show related ads to our users.</p>
<p><strong>In IOS 14</strong>, the IDFA is hidden and you and adnetwork can't get this IDFA, You must to ask user to allow tracking permission to continue use IDFA in IOS 14 system.</p>
<p>So my answers are:</p>
<blockquote>
<p>Question 1: What's happen if I don't upgrade these apps as per the last WWDC guidelines? Is app continue ads serving to the user?</p>
</blockquote>
<p>The short answers is <strong>YES</strong>, Your app still continue ads serving to the user. <strong>BUTTTTTT</strong>: the Adnetwork will do not know anythings about your user, <strong>so all ads will be random and unrelated ads</strong></p>
<p>-> clickRate will be reduced -> eCPM will be reduced -> <strong>Your revenue will be down too.</strong></p>
<blockquote>
<p>Question 2: What's happen if User doesn't give tracking permission to the app?</p>
</blockquote>
<p>Like the my answer 1 when user don't allow tracking permission, you can't get <strong>IDFA</strong> then <strong>Your revenue will be down again.</strong>.</p>
<p>But in this case, Apple created an another choose for Us and Networks. that is <a href="https://developer.apple.com/documentation/storekit/skadnetwork" rel="noreferrer">SKAdNetwork</a> which helps advertisers measure the success of ad campaigns while maintaining user privacy. But Nobody can make sure this API will better current <strong>IDFA</strong> System can make. So you should enable <strong>SKAdNetwork</strong> to track conversions in tracking don't allow case. To get maximum profit</p>
<blockquote>
<p>Question 3: App update does make any impact on revenue from ads?</p>
</blockquote>
<p>If your user allow the tracking permission, everything is OKAY like nothing happen. If not, you have the SKAdNetwork and let pray for SKAdNetwork will work nice like The Apple said.</p>
<blockquote>
<p>Question 4: What is Funding Choices?</p>
</blockquote>
<p><a href="https://support.google.com/fundingchoices/answer/9180084://" rel="noreferrer">Funding Choices</a> is the Google'Tool to help you to ask user allow tracking permission. <strong>Funding Choices</strong> and <a href="https://developers.google.com/ad-manager/mobile-ads-sdk/ios/quick-start" rel="noreferrer">SDK UMP</a> will create the explainer message alert which will automatically be shown immediately before the "Tracking permission" alert.
This is automatically and simple. If you don't like Funding Choices, you can create your explainer message yourself to ask user before the "tracking permission" alert is shown</p>
<p>This is all my knowledges after 3 days researching and working about IDFA, IOS14.....</p>
<p>I hope them can help you something. If i had any mistake, reply here!!!. Thanks</p> |
54,117,311 | Background concurrent copying GC freed - Flutter | <p>In my Flutter log I'm constantly getting this messages(just with some different numbers):</p>
<pre><code>Background concurrent copying GC freed 153040(3MB) AllocSpace objects, 12(4MB) LOS objects, 49% free, 4MB/8MB, paused 819us total 173.633ms
</code></pre>
<p>I recently implemented the bloc pattern and I'm not that familiar with streams, maybe I've done something wrong there...</p>
<p>I got about 5000 lines of code so I can't post it all here, just wanna know if you know this problem, maybe it's a common error.</p>
<p>EDIT: Oh yeah, btw I'm testing on Android Emulator, Android Pie. My platform is Windows.</p> | 54,189,289 | 7 | 0 | null | 2019-01-09 19:49:07.993 UTC | 6 | 2022-06-24 05:48:15.543 UTC | 2020-05-07 22:10:10.167 UTC | null | 436,341 | null | 8,757,322 | null | 1 | 35 | dart|flutter | 53,214 | <p>Obviously it was a dumb mistake by myself... I made some update function, that added something to the <code>Stream</code>, and then instantly got called again because it was also listening to the <code>Stream</code>. So there was an infinite loop of adding and reacting to the <code>Stream</code>.</p>
<p>Thanks to anyone helping anyways, there are some useful tips!</p> |
35,154,875 | convert string to uint in go lang | <p>I am trying to convert the string to uint on 32-bit ubuntu using the following code. But it always convert it in uint64 despite explicitly passing 32 as the argument in the function. Below in the code mw is the object of the <a href="https://github.com/gographics/imagick" rel="noreferrer">image magick</a> library. Which returns <code>uint</code> when <code>mw.getImageWidth()</code> and <code>mw.getImageHeight()</code> is called. Also, it accepts the <code>uint</code> type argument in the <a href="https://github.com/gographics/imagick/blob/master/imagick/magick_wand_image.go" rel="noreferrer">resize</a> function. </p>
<pre><code> width := strings.Split(imgResize, "x")[0]
height := strings.Split(imgResize, "x")[1]
var masterWidth uint = mw.GetImageWidth()
var masterHeight uint = mw.GetImageHeight()
mw := imagick.NewMagickWand()
defer mw.Destroy()
err = mw.ReadImageBlob(img)
if err != nil {
log.Fatal(err)
}
var masterWidth uint = mw.GetImageWidth()
var masterHeight uint = mw.GetImageHeight()
wd, _ := strconv.ParseUint(width, 10, 32)
ht, _ := strconv.ParseUint(height, 10, 32)
if masterWidth < wd || masterHeight < ht {
err = mw.ResizeImage(wd, ht, imagick.FILTER_BOX, 1)
if err != nil {
panic(err)
}
}
</code></pre>
<p>Error is :</p>
<pre><code># command-line-arguments
test.go:94: invalid operation: masterWidth < wd (mismatched types uint and uint64)
goImageCode/test.go:94: invalid operation: masterHeight < ht (mismatched types uint and uint64)
goImageCode/test.go:100: cannot use wd (type uint64) as type uint in argument to mw.ResizeImage
goImageCode/AmazonAWS.go:100: cannot use ht (type uint64) as type uint in argument to mw.ResizeImage
</code></pre> | 35,154,920 | 1 | 0 | null | 2016-02-02 13:30:12.81 UTC | 6 | 2016-02-02 19:42:00.033 UTC | 2016-02-02 19:42:00.033 UTC | null | 778,719 | null | 2,135,526 | null | 1 | 35 | go|go-imagick | 58,995 | <blockquote>
<p><a href="https://golang.org/pkg/strconv/" rel="noreferrer">Package strconv</a></p>
<p><a href="https://golang.org/pkg/strconv/#ParseUint" rel="noreferrer">func ParseUint</a></p>
<pre><code>func ParseUint(s string, base int, bitSize int) (n uint64, err error)
</code></pre>
<p>ParseUint is like ParseInt but for unsigned numbers. </p>
<p><a href="https://golang.org/pkg/strconv/#ParseInt" rel="noreferrer">func ParseInt</a></p>
<pre><code>func ParseInt(s string, base int, bitSize int) (i int64, err error)
</code></pre>
<p>ParseInt interprets a string s in the given base (2 to 36) and returns
the corresponding value i. If base == 0, the base is implied by the
string's prefix: base 16 for "0x", base 8 for "0", and base 10
otherwise.</p>
<p>The bitSize argument specifies the integer type that the result must
fit into. Bit sizes 0, 8, 16, 32, and 64 correspond to int, int8,
int16, int32, and int64.</p>
<p>The errors that ParseInt returns have concrete type *NumError and
include err.Num = s. If s is empty or contains invalid digits, err.Err
= ErrSyntax and the returned value is 0; if the value corresponding to s cannot be represented by a signed integer of the given size, err.Err
= ErrRange and the returned value is the maximum magnitude integer of the appropriate bitSize and sign.</p>
</blockquote>
<p>The <code>bitSize</code> argument specifies the integer type that the result must
fit into. The <code>uint</code> type size is implementation defined, either 32 or 64 bits. The <code>ParseUint</code> return type is always <code>uint64</code>. For example,</p>
<pre><code>package main
import (
"fmt"
"strconv"
)
func main() {
width := "42"
u64, err := strconv.ParseUint(width, 10, 32)
if err != nil {
fmt.Println(err)
}
wd := uint(u64)
fmt.Println(wd)
}
</code></pre>
<p>Output:</p>
<pre><code>42
</code></pre> |
29,031,782 | How to implement strategy pattern in C++ with std::function | <p>I'm reasing about the best way to implement the strategy pattern in C++. Up to now, I've always used the standard way, where the context has a pointer to the base strategy class as follows:</p>
<pre class="lang-cpp prettyprint-override"><code> class AbstractStrategy{
public:
virtual void exec() = 0;
}
class ConcreteStrategyA{
public:
void exec();
}
class ConcreteStrategyB{
public:
void exec();
}
class Context{
public:
Context(AbstractStrategy* strategy):strategy_(strategy){}
~Context(){
delete strategy;
}
void run(){
strategy->exec();
}
private:
AbstractStrategy* strategy_;
</code></pre>
<p>Since having pointers to objects can result in bad behavior, I was looking for a safer way to implement this pattern and I found <a href="https://stackoverflow.com/questions/28364689/should-safe-pointers-be-used-in-strategy-pattern" title="this">this question</a> where <code>std::function</code> are proposed as a better way to handle this pattern.</p>
<p>Could someone please explain better how <code>std::function</code> works, maybe with an example with the strategy pattern?</p> | 29,031,835 | 4 | 0 | null | 2015-03-13 12:04:31.85 UTC | 8 | 2015-03-13 12:30:29.71 UTC | 2017-05-23 12:18:07.123 UTC | null | -1 | null | 4,402,325 | null | 1 | 9 | c++|pointers|c++11|strategy-pattern|std-function | 2,901 | <p>Note that single-method objects are isomorphic to functions, and strategies are just single-method objects.</p>
<p>So basically, you get rid of all your classes, and you just use <code>std::function<void()></code> instead:</p>
<pre><code>class Context {
public:
template<typename F>
explicit Context(F strategy) : strategy(std::move(strategy)) { }
void run() { strategy(); }
private:
std::function<void()> strategy;
};
</code></pre>
<p>Then you can pass any callable to the constructor of <code>Context</code>:</p>
<pre><code>Context ctx([] { std::cout << "Hello, world!\n"; });
ctx.run();
</code></pre> |
26,069,334 | Changing tab bar font in Swift | <p>I have been trying to change the font for the tab bar items however I haven't been able to find any Swift examples. I know that this is how you change it in Objective-C:</p>
<pre><code>[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"AmericanTypewriter" size:20.0f], UITextAttributeFont, nil] forState:UIControlStateNormal];
</code></pre>
<p>But how can I translate this into Swift?</p> | 26,069,432 | 8 | 0 | null | 2014-09-26 22:43:42.377 UTC | 5 | 2022-03-06 08:07:16.31 UTC | null | null | null | null | 3,746,428 | null | 1 | 37 | swift|uitabbar|uifont | 44,329 | <p>The UITextAttributeFont was deprecated in iOS 7. You should use the NS variant instead:</p>
<pre><code>import UIKit
let appearance = UITabBarItem.appearance()
let attributes = [NSFontAttributeName:UIFont(name: "American Typewriter", size: 20)]
appearance.setTitleTextAttributes(attributes, forState: .Normal)
</code></pre> |
27,414,991 | Contravariance vs Covariance in Scala | <p>I just learned Scala. Now I am confused about Contravariance and Covariance.</p>
<p>From this <a href="http://www.stephanboyer.com/post/39/covariance-and-contravariance" rel="noreferrer">page</a>, I learned something below:</p>
<p>Covariance</p>
<p>Perhaps the most obvious feature of subtyping is the ability to replace a value of a wider type with a value of a narrower type in an expression. For example, suppose I have some types <code>Real</code>, <code>Integer <: Real</code>, and some unrelated type <code>Boolean</code>. I can define a function <code>is_positive :: Real -> Boolean</code> which operates on <code>Real</code> values, but I can also apply this function to values of type <code>Integer</code> (or any other subtype of <code>Real</code>). This replacement of wider (ancestor) types with narrower (descendant) types is called <code>covariance</code>. The concept of <code>covariance</code> allows us to write generic code and is invaluable when reasoning about inheritance in object-oriented programming languages and polymorphism in functional languages.</p>
<p>However, I also saw something from somewhere else:</p>
<pre><code>scala> class Animal
defined class Animal
scala> class Dog extends Animal
defined class Dog
scala> class Beagle extends Dog
defined class Beagle
scala> def foo(x: List[Dog]) = x
foo: (x: List[Dog])List[Dog] // Given a List[Dog], just returns it
scala> val an: List[Animal] = foo(List(new Beagle))
an: List[Animal] = List(Beagle@284a6c0)
</code></pre>
<p>Parameter <code>x</code> of <code>foo</code> is <code>contravariant</code>; it expects an argument of type <code>List[Dog]</code>, but we give it a <code>List[Beagle]</code>, and that's okay </p>
<p>[What I think is the second example should also prove <code>Covariance</code>. Because from the first example, I learned that "apply this function to values of type <code>Integer</code> (or any other subtype of <code>Real</code>)". So correspondingly, here we apply this function to values of type <code>List[Beagle]</code>(or any other subtype of <code>List[Dog]</code>). But to my surprise, the second example proves <code>Cotravariance</code>]</p>
<p>I think two are talking the same thing, but one proves <code>Covariance</code> and the other <code>Contravariance</code>. I also saw <a href="https://stackoverflow.com/questions/13321921/covariance-and-contravariance-in-scala-java">this question from SO</a>. However I am still confused. Did I miss something or one of the examples is wrong?</p> | 27,415,140 | 3 | 0 | null | 2014-12-11 03:42:04.493 UTC | 9 | 2021-01-12 19:01:40.393 UTC | 2017-05-23 12:25:29.957 UTC | null | -1 | null | 2,925,372 | null | 1 | 13 | scala|covariance|contravariance | 2,562 | <p>That you can pass a <code>List[Beagle]</code> to a function expecting a <code>List[Dog]</code> is nothing to do with contravariance of functions, it is still because List is covariant and that <code>List[Beagle]</code> is a <code>List[Dog]</code>.</p>
<p>Instead lets say you had a function:</p>
<pre><code>def countDogsLegs(dogs: List[Dog], legCountFunction: Dog => Int): Int
</code></pre>
<p>This function counts all the legs in a list of dogs. It takes a function that accepts a dog and returns an int representing how many legs this dog has.</p>
<p>Furthermore lets say we have a function:</p>
<pre><code>def countLegsOfAnyAnimal(a: Animal): Int
</code></pre>
<p>that can count the legs of any animal. We can pass our <code>countLegsOfAnyAnimal</code> function to our <code>countDogsLegs</code> function as the function argument, this is because if this thing can count the legs of any animal, it can count legs of dogs, because dogs are animals, this is because functions are contravariant. </p>
<p>If you look at the definition of <code>Function1</code> (functions of one parameter), it is </p>
<pre><code>trait Function1[-A, +B]
</code></pre>
<p>That is that they are contravariant on their input and covariant on their output. So <code>Function1[Animal,Int] <: Function1[Dog,Int]</code> since <code>Dog <: Animal</code></p> |
40,776,351 | What is the best way to listen for component resize events within an Angular2 component? | <p>I'm writing an Angular2 component that needs to dynamically change its content when resized. I am using the experimental Renderer in @angular/core (v2.1.0) and can wire up a click listener with the following:</p>
<pre><code>this.rollupListener = this.renderer.listen(this.rollUp, 'click', (event) => {
...
});
</code></pre>
<p>But unfortunately I cannot do the same for a resize event - both 'resize' or 'onresize' do not work:</p>
<pre><code>this.resizeListener = this.renderer.listen(this.container, 'resize', (event) => {
// this never fires :(
});
</code></pre>
<p>I am able to pick up on browser resize events using the following:</p>
<pre><code>@HostListener('window:resize', ['$event.target'])
onResize() {
...
}
</code></pre>
<p>But unfortunately not all component resizing in my application is due to a browser resize.</p>
<p>Basically, I'm looking for the JQuery equivalent of:</p>
<pre><code>$(this.container).resize(() => {
...
});
</code></pre> | 41,050,069 | 6 | 2 | null | 2016-11-24 00:31:22.713 UTC | 1 | 2021-10-18 08:19:54.653 UTC | 2016-11-28 19:02:17.16 UTC | null | 1,580,790 | null | 1,580,790 | null | 1 | 21 | angular | 39,848 | <p>I ended up implementing a service that uses the element-resize-detector library (<a href="https://github.com/wnr/element-resize-detector" rel="noreferrer">https://github.com/wnr/element-resize-detector</a>). Couldn't find a TypeScript definition file but with a little help (<a href="https://stackoverflow.com/questions/41027750/use-element-resize-detector-library-in-an-angular2-application/41043364#41043364">Use element-resize-detector library in an Angular2 application</a>), implemented the following:</p>
<p><strong>element-resize-detector.d.ts</strong></p>
<pre><code>declare function elementResizeDetectorMaker(options?: elementResizeDetectorMaker.ErdmOptions): elementResizeDetectorMaker.Erd;
declare namespace elementResizeDetectorMaker {
interface ErdmOptions {
strategy?: 'scroll' | 'object';
}
interface Erd {
listenTo(element: HTMLElement, callback: (elem: HTMLElement) => void);
removeListener(element: HTMLElement, callback: (elem: HTMLElement) => void);
removeAllListeners(element: HTMLElement);
uninstall(element: HTMLElement);
}
}
export = elementResizeDetectorMaker;
</code></pre>
<p><strong>resize.service.ts</strong></p>
<pre><code>import { Injectable } from '@angular/core';
import * as elementResizeDetectorMaker from 'element-resize-detector';
@Injectable()
export class ResizeService {
private resizeDetector: any;
constructor() {
this.resizeDetector = elementResizeDetectorMaker({ strategy: 'scroll' });
}
addResizeEventListener(element: HTMLElement, handler: Function) {
this.resizeDetector.listenTo(element, handler);
}
removeResizeEventListener(element: HTMLElement) {
this.resizeDetector.uninstall(element);
}
}
</code></pre>
<p><strong>my-component.ts</strong></p>
<pre><code>import { Component } from '@angular/core';
import { ResizeService } from '../resize/index';
@Component({
selector: 'my-component',
template: ``
})
export class MyComponent {
constructor(private el: ElementRef, private resizeService: ResizeService) {
}
ngOnInit() {
this.resizeService.addResizeEventListener(this.el.nativeElement, (elem) => {
// some resize event code...
});
}
ngOnDestroy() {
this.resizeService.removeResizeEventListener(this.el.nativeElement);
}
}
</code></pre> |
39,233,130 | Checkbox checked if boolean is true with Angular2 | <p>I would like to know how to make a checkbox checked if the value is true, and unchecked if false with <code>Angular2</code>.</p>
<pre><code>Adult <input type="checkbox" value="{{person.is_adult}}">
</code></pre>
<p>{{person.is_adult}} is a <code>boolean</code></p>
<p>Can someone please suggest anything? Thanks</p> | 39,233,189 | 3 | 0 | null | 2016-08-30 16:56:41.93 UTC | 2 | 2020-08-31 11:42:16.48 UTC | null | null | null | null | 6,676,988 | null | 1 | 20 | html|checkbox|angular|boolean | 65,617 | <p><code>{{}}</code> does string interpolation and stringifies <code>true</code> and <code>false</code> and Angular by default uses property binding and I assume the property expects boolean values not strings:</p>
<pre><code><input type="checkbox" [checked]="person.is_adult">
</code></pre>
<p>This might work as well</p>
<pre><code><input type="checkbox" attr.checked="{{person.is_adult}}">
</code></pre>
<p>because with attribute binding the browser might translate it from the attribute (which can only be strings) to boolean when reading it into its property.</p>
<p>It is also <code>checked</code> instead of <code>value</code></p>
<p>You can also use <code>ngModel</code></p>
<pre><code><input type="checkbox" [ngModel]"person.is_adult" name="isAdult">
<input type="checkbox" [(ngModel)]"person.is_adult" name="isAdult">
</code></pre>
<p>for one-way or two-way binding.<br>
Ensure your have the <code>FormsModule</code> imported if you use <code>ngModel</code>.</p> |
2,824,105 | Handling mach exceptions in 64bit OS X application | <p>I have been able to register my own mach port to capture mach exceptions in my applications and it works beautifully when I target 32 bit. However when I target 64 bit, my exception handler <code>catch_exception_raise()</code> gets called but the array of exception codes that is passed to the handler are 32 bits wide. This is expected in a 32 bit build but not in 64 bit.</p>
<p>In the case where I catch <code>EXC_BAD_ACCESS</code> the first code is the error number and the second code should be the address of the fault. Since the second code is 32 bits wide the high 32 bits of the 64 bit fault address is truncated.</p>
<p>I found a flag in <code><mach/exception_types.h></code> I can pass in <code>task_set_exception_ports()</code> called <code>MACH_EXCEPTION_CODES</code> which from looking at the Darwin sources appears to control the size of the codes passed to the handler. It looks like it is meant to be ored with the behavior passed in to <code>task_set_exception_ports()</code>.</p>
<p>However when I do this and trigger an exception, my mach port gets notified, I call <code>exc_server()</code> but my handler never gets called, and when the reply message is sent back to the kernel I get the default exception behavior.</p>
<p>I am targeting the 10.6 SDK.</p>
<p>I really wish apple would document this stuff better. Any one have any ideas?</p> | 2,839,113 | 1 | 2 | null | 2010-05-13 02:25:26.84 UTC | 9 | 2013-03-18 06:18:12.067 UTC | null | null | null | null | 339,880 | null | 1 | 16 | macos|osx-snow-leopard|darwin | 4,714 | <p>Well, I figured it out.</p>
<p>To handle mach exceptions, you have to register a mach port for the exceptions you are interested in. You then wait for a message to arrive on the port in another thread. When a message arrives, you call <code>exc_server()</code> whose implementation is provided by System.library. <code>exec_server()</code> takes the message that arrived and calls one of three handlers that you must provide. <code>catch_exception_raise()</code>, <code>catch_exception_raise_state()</code>, or <code>catch_exception_raise_state_identity()</code> depending on the arguments you passed to <code>task_set_exception_ports()</code>. This is how it is done for 32 bit apps.</p>
<p>For 64 bit apps, the 32 bit method still works but the data passed to you in your handler may be truncated to 32 bits. To get 64 bit data passed to your handlers requires a little extra work that is not very straight forward and as far as I can tell not very well documented. I stumbled onto the solution by looking at the sources for GDB.</p>
<p>Instead of calling <code>exc_server()</code> when a message arrives at the port, you have to call <code>mach_exc_server()</code> instead. The handlers also have to have different names as well <code>catch_mach_exception_raise()</code>, <code>catch_mach_exception_raise_state()</code>, and <code>catch_mach_exception_raise_state_identity()</code>. The parameters for the handlers are the same as their 32 bit counterparts.
The problem is that <code>mach_exc_server()</code> is not provided for you the way <code>exc_server()</code> is. To get the implementation for <code>mach_exc_server()</code> requires the use of the MIG (Mach Interface Generator) utility. MIG takes an interface definition file and generates a set of source files that include a server function that dispatches mach messages to handlers you provide. The 10.5 and 10.6 SDKs include a MIG definition file <mach_exc.defs> for the exception messages and will generate the <code>mach_exc_server()</code> function. You then include the generated source files in your project and then you are good to go.</p>
<p>The nice thing is that if you are targeting 10.6+ (and maybe 10.5) you can use the same exception handling for both 32 and 64 bit. Just OR the exception behavior with <code>MACH_EXCEPTION_CODES</code> when you set your exception ports. The exception codes will come through as 64 bit values but you can truncate them to 32 bits in your 32 bit build.</p>
<p>I took the <code>mach_exc.defs</code> file and copied it to my source directory, opened a terminal and used the command <code>mig -v mach_exc.defs</code>. This generated <code>mach_exc.h</code>, <code>mach_excServer.c</code>, and <code>mach_excUser.c</code>. I then included those files in my project, added the correct declaration for the server function in my source file and implemented my handlers. I then built my app and was good to go.</p>
<p>Well, this not the best description, but hopefully it helps someone else out.</p> |
34,171,568 | return value from python script to shell script | <p>I am new in Python. I am creating a Python script that returns a string "hello world." And I am creating a shell script. I am adding a call from the shell to a Python script.</p>
<ol>
<li>i need to pass arguments from the shell to Python.</li>
<li>i need to print the value returned from Python in the shell script.</li>
</ol>
<p>This is my code:</p>
<p><strong>shellscript1.sh</strong></p>
<pre><code>#!/bin/bash
# script for testing
clear
echo "............script started............"
sleep 1
python python/pythonScript1.py
exit
</code></pre>
<p><strong>pythonScript1.py</strong></p>
<pre><code>#!/usr/bin/python
import sys
print "Starting python script!"
try:
sys.exit('helloWorld1')
except:
sys.exit('helloWorld2')
</code></pre> | 34,171,914 | 3 | 0 | null | 2015-12-09 05:46:39.97 UTC | 5 | 2022-02-24 22:14:22.93 UTC | 2020-08-18 08:31:56.98 UTC | null | 6,395,052 | null | 4,182,755 | null | 1 | 36 | python|linux|bash|shell | 65,301 | <p>You can't return message as exit code, only numbers. In bash it can accessible via <code>$?</code>. Also you can use <code>sys.argv</code> to access code parameters:</p>
<pre><code>import sys
if sys.argv[1]=='hi':
print 'Salaam'
sys.exit(0)
</code></pre>
<p>in shell:</p>
<pre><code>#!/bin/bash
# script for tesing
clear
echo "............script started............"
sleep 1
result=`python python/pythonScript1.py "hi"`
if [ "$result" == "Salaam" ]; then
echo "script return correct response"
fi
</code></pre> |
21,365,301 | exact meaning of "library" keyword in dart | <p>I know that this keyword should be used in some custom library,
but when I dropped it, nothing happened (at least I didn't notice anything),
imports still worked fine, private members remained private.</p>
<p>Could somebody explain what the "library" keyword in Dart does?</p> | 21,365,360 | 2 | 0 | null | 2014-01-26 15:30:38.947 UTC | 2 | 2021-09-23 14:36:16.74 UTC | 2021-09-23 14:36:16.74 UTC | null | 171,933 | null | 2,776,733 | null | 1 | 43 | dart | 8,974 | <p><strong>update 2018-03-05</strong></p>
<p>For a while now, <code>part of</code> accepts a URI, which reduces the need of <code>library</code> to a few edge cases.</p>
<p><strong>update 2015-11-27</strong></p>
<p>With a recent change, two imported nameless libraries don't produce a warning anymore. The plan is to make the library declaration entirely optional.</p>
<hr />
<p>The library declaration is optional. If it is omitted the library name defaults to <code>""</code>.<br />
There are some situations (<code>pub build</code>) where you get an error if two libraries have the same name, so it's usually good practice to set proper library names.</p>
<p>In a simple command line app consisting of one library it's usually fine to omit the library declaration.</p>
<p>From the <a href="https://www.dartlang.org/docs/spec/latest/dart-language-specification.html#h.9ljawpv6s0wp" rel="noreferrer">Dart language spec</a></p>
<blockquote>
<p>An implicitly named library has the empty string as its name.</p>
<p>The name of a library is used to tie it to separately compiled parts
of the library (called parts) and can be used for printing and, more
generally, reflection. The name may be relevant for further language
evolution.</p>
<p>Libraries intended for widespread use should avoid name collisions.
Dart's pub package management system provides a mechanism for doing
so. Each pub package is guaranteed a unique name, effectively
enforcing a global namespace.</p>
</blockquote> |
32,551,919 | How to use Column.isin with list? | <pre><code>val items = List("a", "b", "c")
sqlContext.sql("select c1 from table")
.filter($"c1".isin(items))
.collect
.foreach(println)
</code></pre>
<p>The code above throws the following exception.</p>
<pre><code>Exception in thread "main" java.lang.RuntimeException: Unsupported literal type class scala.collection.immutable.$colon$colon List(a, b, c)
at org.apache.spark.sql.catalyst.expressions.Literal$.apply(literals.scala:49)
at org.apache.spark.sql.functions$.lit(functions.scala:89)
at org.apache.spark.sql.Column$$anonfun$isin$1.apply(Column.scala:642)
at org.apache.spark.sql.Column$$anonfun$isin$1.apply(Column.scala:642)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:245)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:245)
at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
at scala.collection.mutable.WrappedArray.foreach(WrappedArray.scala:35)
at scala.collection.TraversableLike$class.map(TraversableLike.scala:245)
at scala.collection.AbstractTraversable.map(Traversable.scala:104)
at org.apache.spark.sql.Column.isin(Column.scala:642)
</code></pre>
<p>Below is my attempt to fix it. It compiles and runs but doesn't return any match. Not sure why.</p>
<pre><code>val items = List("a", "b", "c").mkString("\"","\",\"","\"")
sqlContext.sql("select c1 from table")
.filter($"c1".isin(items))
.collect
.foreach(println)
</code></pre> | 32,560,177 | 5 | 0 | null | 2015-09-13 16:32:16.03 UTC | 13 | 2020-04-13 16:27:34.343 UTC | 2018-05-18 19:13:10.497 UTC | null | 1,305,344 | null | 1,364,137 | null | 1 | 81 | scala|apache-spark|apache-spark-sql | 87,635 | <p>According to documentation, <code>isin</code> takes a vararg, not a list. List is actually a confusing name here. You can try converting your List to vararg like this:</p>
<pre><code>val items = List("a", "b", "c")
sqlContext.sql("select c1 from table")
.filter($"c1".isin(items:_*))
.collect
.foreach(println)
</code></pre>
<p>Your variant with mkString compiles, because one single String is also a vararg (with number of arguments equal to 1), but it is proably not what you want to achieve.</p> |
31,343,732 | MVC Model with a list of objects as property | <p>I am working on an MVC application where the Model class <code>Item</code> has a <code>List<Colour></code> named <code>AvailableColours</code> as a property.</p>
<p><code>AvailableColours</code> is a user defined subset of <code>Colour</code> classes. I would like to display all <code>Colour</code> instances in a check box list, and when submitted, <code>AvailableColours</code> is a <code>List<Colour></code> containing the checked <code>Colour</code> classes.</p>
<p>What is the best way to do this in MVC?</p>
<p>Edit: My code so far, although I feel this is not the most MVC-ish way to do it!</p>
<p><strong>Model</strong></p>
<pre><code>public class Item
{
public int ID { get; set; }
public List<Colour> AvailableColours { get; set; }
}
</code></pre>
<p><strong>View</strong></p>
<pre><code>@model MyNamespace.Models.Item
@using MyNamespace.Models;
@{
ViewBag.Title = "Create";
var allColours = new List<Colour>(); //retrieved from database, but omitted for simplicity
}
<h2>Create New Item</h2>
@using (Html.BeginForm("Create", "Item", FormMethod.Post))
{
<div>
@Html.LabelFor(model => model.AvailableColours)
@foreach (var colour in allColours)
{
<input type="checkbox" name="colours" value="@colour.Description" />
}
</div>
<input type="submit" value="Submit" />
}
</code></pre>
<p><strong>Controller</strong></p>
<pre><code>[HttpPost]
public ActionResult Create(Item item, string[] colours)
{
try
{
foreach (var colour in colours)
{
item.AvailableColours.Add(GetColour(colour));//retrieves from database
return RedirectToAction("Index");
}
}
catch
{
return View();
}
}
</code></pre> | 31,344,240 | 3 | 0 | null | 2015-07-10 14:45:12.243 UTC | 8 | 2020-09-07 09:45:50.867 UTC | 2015-07-13 07:22:02.873 UTC | null | 3,797,366 | null | 3,797,366 | null | 1 | 12 | c#|asp.net|asp.net-mvc|asp.net-mvc-4|razor | 95,405 | <p><strong>Models</strong></p>
<pre><code>public class Item
{
public List<Colour> AvailableColours { get;set; }
}
public class Colour
{
public int ID { get; set; }
public string Description { get; set; }
public bool Checked { get; set; }
}
</code></pre>
<p>Note the <code>Checked</code> property</p>
<p><strong>View for loop</strong></p>
<pre><code>@using (Html.BeginForm("Create", "Item", FormMethod.Post))
{
<div>
@Html.LabelFor(model => model.AvailableColours)
@for(var i = 0; i < Model.AvailableColours.Count; i++)
{
@Html.HiddenFor(m => Model.AvailableColours[i].ID)
@Html.HiddenFor(m => Model.AvailableColours[i].Description)
@Html.CheckBoxFor(m => Model.AvailableColours[i].Checked)
@Model.AvailableColours[i].Description<br/>
}
</div>
<input type="submit" value="Submit" />
}
</code></pre>
<p>Note the for loop insted of foreach to enable model binding and the hidden fields to allow the values to be posted back to the controller</p>
<p><a href="http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/"><strong>Model Binding To A List</strong></a></p>
<p><strong>Controller post</strong></p>
<pre><code>[HttpPost]
public ActionResult Create(Item model)
{
//All the selected are available in AvailableColours
return View(model);
}
</code></pre> |
41,757,245 | Request.CreateResponse in asp.net core | <p>Below is my code (Partial code) and I want to migrate it into asp.net core.
My problem is "Request.CreateResponse" is not working in below code. I google it a lot but unable to find any solution. How can I solve it? Package Microsoft.AspNet.WebApi.Core is also not working.</p>
<pre><code> [HttpPost]
public HttpResponseMessage AddBusinessUsersToBusinessUnit(MyObject request)
{
return Request.CreateResponse(HttpStatusCode.Unauthorized);
}
</code></pre>
<p>Thanks in advance.</p> | 41,758,008 | 6 | 0 | null | 2017-01-20 06:16:27.727 UTC | 4 | 2021-08-06 08:42:47.62 UTC | 2017-01-20 07:17:16.503 UTC | user7364287 | null | user7364287 | null | null | 1 | 31 | asp.net|asp.net-core | 67,704 | <p>Finally I make a solution. :)</p>
<pre><code>[HttpPost]
public HttpResponseMessage AddBusinessUsersToBusinessUnit(MyObject request)
{
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
</code></pre> |
37,910,008 | Check if value exists in firebase DB | <p>Is there a method in firebase, which can check if value exist in DB? Firebase has method <a href="https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#exists" rel="noreferrer">.exists()</a>, but according to docs it checks only the keys.</p>
<p>I have the following structure:</p>
<pre><code>{
"users": {
"-KKUmYgLYREWCnWeHCvO": {
"fName": "Peter",
"ID": "U1EL9SSUQ",
"username": "peter01"
},
"-KKUmYgLYREWCnWeHCvO": {
"fName": "John",
"ID": "U1EL5623",
"username": "john.doe"
}
}
}
</code></pre>
<p>I want to check if ID with value <code>U1EL5623</code>exists.</p> | 37,910,159 | 4 | 0 | null | 2016-06-19 17:38:03.487 UTC | 25 | 2021-07-07 18:36:48.497 UTC | 2017-12-13 10:40:53.347 UTC | null | 4,661,692 | null | 4,661,692 | null | 1 | 59 | javascript|firebase|firebase-realtime-database | 91,725 | <p>The <code>exists()</code> method is part of the <code>snapshot</code> object which is returned by firebase queries. So <strong>keep in mind that you won't be able to avoid retrieving the data to verify if it exists or not</strong>.</p>
<pre><code>ref.child("users").orderByChild("ID").equalTo("U1EL5623").once("value",snapshot => {
if (snapshot.exists()){
const userData = snapshot.val();
console.log("exists!", userData);
}
});
</code></pre>
<hr />
<h2>Observations:</h2>
<p>In case you are in a different scenario which you have the exact ref path where the object might be, you wont need to add <code>orderByChild</code> and <code>equalTo</code>. In this case, you can fetch the path to the object directly so it wont need any search processing from firebase. Also, <strong>if you know one of the properties the object must have you can do as the snippet below and make it retrieve just this property and not the entire object. The result will be a much faster check.</strong></p>
<pre><code>//every user must have an email
firebase.database().ref(`users/${userId}/email`).once("value", snapshot => {
if (snapshot.exists()){
console.log("exists!");
const email = snapshot.val();
}
});
</code></pre> |
25,154,087 | Converting CGFloat to String in Swift | <p>This is my current way of converting a CGFloat to String in Swift: </p>
<pre><code>let x:Float = Float(CGFloat)
let y:Int = Int(x)
let z:String = String(y)
</code></pre>
<p>Is there a more efficient way of doing this? </p> | 25,154,126 | 2 | 0 | null | 2014-08-06 06:58:02.727 UTC | 5 | 2015-06-04 10:57:49.877 UTC | null | null | null | null | 3,662,058 | null | 1 | 34 | string|swift|cgfloat | 34,845 | <p>You can use <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html#//apple_ref/doc/uid/TP40014097-CH7-XID_425">string interpolation</a>:</p>
<pre><code>let x: CGFloat = 0.1
let string = "\(x)" // "0.1"
</code></pre>
<p>Or technically, you can use the printable nature of CGFloat directly:</p>
<pre><code>let string = x.description
</code></pre>
<p>The <code>description</code> property comes from it implementing the <code>Printable</code> protocol which is what makes string interpolation possible.</p> |
23,581,172 | What is zmq.ROUTER and zmq.DEALER in python zeromq? | <p>Can anyone tell what are the types of zmq.sockets?</p>
<p>In what situation one can use these sockets?</p>
<p>The main difference I need is <strong><code>zmq.DEALER</code></strong> and <strong><code>zmq.ROUTER</code></strong> in python zeroMQ?</p>
<p>Which type of socket can use these sockets?</p> | 23,592,408 | 1 | 0 | null | 2014-05-10 12:40:13.957 UTC | 11 | 2018-06-11 11:22:14.653 UTC | 2014-12-30 23:24:55.593 UTC | null | 3,666,197 | null | 3,248,869 | null | 1 | 24 | sockets|python-2.7|zeromq | 16,953 | <p>DEALER and ROUTER are sockets, which can allow easy scaling of REQ / REP pairs.</p>
<p>In direct communication, REQ and REP are talking in blocking manner.</p>
<h1>ROUTER - accept requests - from REQ side</h1>
<p>A router is able to accepts requests, adds an envelope with information about that requestee, and makes this new message available for further processing by interconnecting code). When the response comes back (in an envelop), it can pass the response back to the requestee.</p>
<h1>DEALER - talks to workers - on REP side</h1>
<p>Dealer cares about workers. Note, that to make the whole solution usable, workers have to connect to the dealer, not the other way around.</p>
<p>DEALER also allows non-blocking connection with REP.</p>
<p>Some connecting code passes a request in an envelope to the DEALER. The dealer manages the distribution of such requests to workers (without the envelope) and later responds back to the interconnecting code (again in an envelope).</p>
<h1>Interconnecting code</h1>
<p>An interconnecting code is to shuffle messages between ROUTER and DEALER sockets.</p>
<p>The simplest version is here: <a href="http://zguide.zeromq.org/py:rrbroker" rel="noreferrer">http://zguide.zeromq.org/py:rrbroker</a></p>
<pre><code># Simple request-reply broker
#
# Author: Lev Givon <lev(at)columbia(dot)edu>
import zmq
# Prepare our context and sockets
context = zmq.Context()
frontend = context.socket(zmq.ROUTER)
backend = context.socket(zmq.DEALER)
frontend.bind("tcp://*:5559")
backend.bind("tcp://*:5560")
# Initialize poll set
poller = zmq.Poller()
poller.register(frontend, zmq.POLLIN)
poller.register(backend, zmq.POLLIN)
# Switch messages between sockets
while True:
socks = dict(poller.poll())
if socks.get(frontend) == zmq.POLLIN:
message = frontend.recv_multipart()
backend.send_multipart(message)
if socks.get(backend) == zmq.POLLIN:
message = backend.recv_multipart()
frontend.send_multipart(message)
</code></pre> |
38,216,457 | Navigation Drawer Menu Item Title Color in Android | <p>I have a problem changing the Menu Item Title <code>Color</code> in the <code>Navigation Drawer</code> I set the <code>itemTextColor</code> but it only changes the <code>Color</code> of the Items not the <code>Title</code> of the menu.</p>
<p>Here is my
<strong>Activity_main.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer"
app:itemTextColor="#ffffff"
android:background="#283135"
/>
</android.support.v4.widget.DrawerLayout>
</code></pre>
<p><strong>activity_main_drawer.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_home"
android:icon="@mipmap/hospital"
android:title="Home"
/>
<item
android:id="@+id/nav_reminder"
android:icon="@mipmap/alarm"
android:title="Reminders" />
</group>
<item android:title="Tools">
<menu>
<item
android:id="@+id/nav_settings"
android:icon="@mipmap/settings"
android:title="Settings" />
<item
android:id="@+id/nav_help"
android:icon="@mipmap/information"
android:title="Help" />
<item
android:id="@+id/nav_about"
android:icon="@mipmap/team"
android:title="About Us" />
</menu>
</item>
</menu>
</code></pre>
<p><strong>Check this:</strong><a href="https://i.stack.imgur.com/E6wua.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/E6wua.jpg" alt="This is the one i am talking about"></a></p> | 38,216,675 | 6 | 0 | null | 2016-07-06 04:46:08.05 UTC | 10 | 2020-05-14 12:41:25.147 UTC | 2019-10-12 19:49:25.713 UTC | null | 2,016,562 | null | 6,534,603 | null | 1 | 23 | android|colors|navigation-drawer|menuitem|android-navigationview | 26,105 | <p>To give <code>Menu</code> item <code>title</code> <code>color</code> and <code>textSize</code> Create this way..</p>
<p>add this to your <code>styles.xml</code> file.</p>
<pre><code> <style name="TextAppearance44">
<item name="android:textColor">#FF0000</item>
<item name="android:textSize">20sp</item>
</style>
</code></pre>
<p>now in <code>activity_main_drawer.xml</code> file give <code>id</code> <code>attribute</code> to <code>title</code>..</p>
<pre><code><item android:title="Tools"
android:id="@+id/tools">
<menu>
<item
android:id="@+id/nav_settings"
android:icon="@mipmap/settings"
android:title="Settings" />
<item
android:id="@+id/nav_help"
android:icon="@mipmap/information"
android:title="Help" />
<item
android:id="@+id/nav_about"
android:icon="@mipmap/team"
android:title="About Us" />
</menu>
</item>
</code></pre>
<p>now In <code>MainActivity.java</code> file use this way..</p>
<pre><code> NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
Menu menu = navigationView.getMenu();
MenuItem tools= menu.findItem(R.id.tools);
SpannableString s = new SpannableString(tools.getTitle());
s.setSpan(new TextAppearanceSpan(this, R.style.TextAppearance44), 0, s.length(), 0);
tools.setTitle(s);
navigationView.setNavigationItemSelectedListener(this);
</code></pre>
<p>It will change your <code>tools</code> <code>color</code> to <code>Red</code> and <code>TextSize</code> to <code>20sp</code>.. Implement it..</p>
<p>In my case Output :</p>
<p><a href="https://i.stack.imgur.com/bBSCy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bBSCy.png" alt="enter image description here"></a></p> |
2,599,961 | Where is the Oracle Bug Database? | <p>They must have hidden the bug database somewhere. I could not find it with Google. Is the bug database public?</p> | 2,599,982 | 5 | 0 | null | 2010-04-08 12:59:41.307 UTC | 3 | 2015-03-18 14:34:36.233 UTC | null | null | null | null | 149,311 | null | 1 | 28 | oracle|bug-tracking | 46,515 | <p>Try <a href="http://metalink.oracle.com" rel="noreferrer">metalink.oracle.com</a></p>
<p>Oracle also has public <a href="http://forums.oracle.com" rel="noreferrer">forums</a>.</p> |
3,145,062 | Using AutoMapper to unflatten a DTO | <p>I've been trying to use AutoMapper to save some time going from my DTOs to my domain objects, but I'm having trouble configuring the map so that it works, and I'm beginning to wonder if AutoMapper might be the wrong tool for the job.</p>
<p>Consider this example of domain objects (one entity and one value):</p>
<pre><code>public class Person
{
public string Name { get; set; }
public StreetAddress Address { get; set; }
}
public class StreetAddress
{
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
}
</code></pre>
<p>My DTO (from a Linq-to-SQL object) is coming out looking roughly like this:</p>
<pre><code>public class PersonDTO
{
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
}
</code></pre>
<p>I'd like to be able to do this in my repository:</p>
<pre><code>return Mapper.Map<PersonDTO, Person>(result);
</code></pre>
<p>I've tried configuring AutoMapper every way I can figure, but I keep getting the generic <strong>Missing type map configuration or unsupported mapping</strong> error, with no details to tell me where I'm failing.</p>
<p>I've tried a number of different configurations, but here are a few:</p>
<pre><code>Mapper.CreateMap<PersonDTO, Person>()
.ForMember(dest => dest.Address, opt => opt.MapFrom(Mapper.Map<Person, Domain.StreetAddress>));
</code></pre>
<p>and</p>
<pre><code>Mapper.CreateMap<Person, Domain.Person>()
.ForMember(dest => dest.Address.Address1, opt => opt.MapFrom(src => src.Address))
.ForMember(dest => dest.Address.City, opt => opt.MapFrom(src => src.City))
.ForMember(dest => dest.Address.State, opt => opt.MapFrom(src => src.State));
</code></pre>
<p>I've read that <em>flattening</em> objects with AutoMapper is easy, but <em>unflattening</em> them isn't easy...or even possible. Can anyone tell me whether I'm trying to do the impossible, and if not what I'm doing wrong?</p>
<p>Note that my actual objects are a little more complicated, so it's possible I'm leaving out info that is the key to the error...if what I'm doing looks right I can provide more info or start simplifying my objects for testing.</p> | 3,155,413 | 7 | 3 | null | 2010-06-29 21:55:14.733 UTC | 11 | 2018-06-27 09:27:58.99 UTC | 2011-11-09 23:37:30.807 UTC | null | 221,708 | null | 240,439 | null | 1 | 39 | mapping|automapper | 20,526 | <p>use <a href="https://github.com/omuleanu/ValueInjecter" rel="nofollow noreferrer">https://github.com/omuleanu/ValueInjecter</a>, it does <strong>flattening</strong> and <strong>unflattening</strong>, and anything else you need, there is an <strong><em>asp.net mvc sample application in the download</em></strong> where all the features are demonstrated (also unit tests)</p> |
2,892,683 | How to find the submit button in a specific form in jQuery | <p>I try to get jQuery object of a submit button in a specific form (there are several forms on the same page).</p>
<p>I managed to get the form element itself. It looks something like this:</p>
<pre><code>var curForm = curElement.parents("form");
</code></pre>
<p>The current Element has the context HTMLInputElement. The several techniques I tried to get the according submit element of the form:</p>
<pre><code>var curSubmit = curForm.find("input[type='submit']");
var curSubmit = $(curForm).find("input[type='submit']");
var curSubmit = curForm.find(":submit");
var curSubmit = $(curForm).find(":submit");
var curSubmit = $(curSubmit, "input[type='submit']");
</code></pre>
<p>the result is always the same (and very strange). The result that I get is the same element as "curElement".</p>
<p>So how can I get the right submit button?</p> | 2,892,693 | 7 | 1 | null | 2010-05-23 17:20:57.933 UTC | 9 | 2020-06-11 21:55:05.137 UTC | null | null | null | null | 1,087,469 | null | 1 | 59 | javascript|jquery | 105,010 | <p>The following should work:</p>
<pre><code>var submit = curElement.closest('form').find(':submit');
</code></pre> |
3,149,216 | How to listen for a WebView finishing loading a URL? | <p>I have a <code>WebView</code> that is loading a page from the Internet. I want to show a <code>ProgressBar</code> until the loading is complete. </p>
<p>How do I listen for the completion of page loading of a <a href="http://developer.android.com/reference/android/webkit/WebView.html" rel="noreferrer"><code>WebView</code></a>?</p> | 3,149,260 | 18 | 4 | null | 2010-06-30 12:28:26.567 UTC | 123 | 2022-03-28 06:27:28.32 UTC | 2016-08-03 07:55:07.543 UTC | null | 1,276,636 | null | 114,066 | null | 1 | 493 | android|android-webview | 396,976 | <p>Extend <a href="http://developer.android.com/reference/android/webkit/WebViewClient.html" rel="noreferrer">WebViewClient</a> and call <a href="http://developer.android.com/reference/android/webkit/WebViewClient.html#onPageFinished%28android.webkit.WebView,%20java.lang.String%29" rel="noreferrer">onPageFinished</a>() as follows:</p>
<pre><code>mWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do your stuff here
}
});
</code></pre> |
2,618,967 | Switching to landscape mode in Android Emulator | <p>This is probably a pretty easy to answer question, but I can't find the solution myself after a couple hours of searching the documentation and Google. I set the orientation of my Android app to <code>landscape</code> in the <code>AndroidManifest.xml</code> file:</p>
<pre><code>android:screenOrientation="landscape"
</code></pre>
<p>However, when I run the app in the simulator, it appears sideways and in portrait mode. How can I switch the emulator to <code>landscape</code> mode on a <code>mac</code>? It's running the 1.6 SDK. </p> | 4,057,309 | 27 | 2 | null | 2010-04-11 22:33:02.507 UTC | 77 | 2021-05-30 03:49:02.503 UTC | 2013-01-15 11:33:55.207 UTC | null | 1,727,181 | null | 313,717 | null | 1 | 359 | android|android-emulator | 191,757 | <p>Try:</p>
<ul>
<li><kbd>ctrl</kbd>+<kbd>fn</kbd>+<kbd>F11</kbd> on Mac to change the landscape to portrait and vice versa. </li>
<li><kbd>left-ctrl</kbd>+<kbd>F11</kbd>on Windows 7.</li>
<li><kbd>ctrl</kbd>+<kbd>F11</kbd>on Linux.</li>
</ul>
<p>For Mac users, you only need to use the <kbd>fn</kbd> key if the setting "Use all <kbd>F1</kbd>, <kbd>F2</kbd> etc. keys as function keys" (under System Preferences -> Keyboard) is checked.</p>
<ul>
<li><kbd>left-ctrl</kbd>+<kbd>F11</kbd>on Windows 7
It works fine in Windows 7 for android emulator to change the landscape orientation to portrait and vice versa.</li>
</ul> |
2,939,914 | How do I vertically align text in a div? | <p>I am trying to find the most effective way to align text with a div. I have tried a few things and none seem to work.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.testimonialText {
position: absolute;
left: 15px;
top: 15px;
width: 150px;
height: 309px;
vertical-align: middle;
text-align: center;
font-family: Georgia, "Times New Roman", Times, serif;
font-style: italic;
padding: 1em 0 1em 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="testimonialText">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div></code></pre>
</div>
</div>
</p> | 2,939,979 | 33 | 4 | null | 2010-05-30 19:02:13.51 UTC | 351 | 2022-08-10 23:00:18.063 UTC | 2018-06-23 16:04:06.263 UTC | null | 4,813,913 | null | 271,534 | null | 1 | 1,491 | html|css|vertical-alignment | 2,157,882 | <h3>The correct way to do this in modern browsers is to use Flexbox.</h3>
<p>See <a href="https://stackoverflow.com/a/13515693/102937">this answer</a> for details.</p>
<p>See below for some older ways that work in older browsers.</p>
<hr />
<p><strong>Vertical Centering in CSS</strong>
<br/><a href="http://www.jakpsatweb.cz/css/css-vertical-center-solution.html" rel="noreferrer">http://www.jakpsatweb.cz/css/css-vertical-center-solution.html</a></p>
<p>Article summary:</p>
<p>For a CSS 2 browser, one can use <code>display:table</code>/<code>display:table-cell</code> to center content.</p>
<p>A sample is also available at <a href="http://jsfiddle.net/SVJaK/" rel="noreferrer">JSFiddle</a>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div { border:1px solid green;}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="display: table; height: 400px; overflow: hidden;">
<div style="display: table-cell; vertical-align: middle;">
<div>
everything is vertically centered in modern IE8+ and others.
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>It is possible to merge hacks for old browsers (Internet Explorer 6/7) into styles with using <code>#</code> to hide styles from newer browsers:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div { border:1px solid green;}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="display: table; height: 400px; #position: relative; overflow: hidden;">
<div style=
"#position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
<div style=" #position: relative; #top: -50%">
everything is vertically centered
</div>
</div>
</div></code></pre>
</div>
</div>
</p> |
42,427,639 | How to send POST request by Spring cloud Feign | <p>It's my Feign interface</p>
<pre><code>@FeignClient(
name="mpi",
url="${mpi.url}",
configuration = FeignSimpleEncoderConfig.class
)
public interface MpiClient {
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> getPAReq(@QueryMap Map<String, String> queryMap
);
}
</code></pre>
<p>and my custom configuration</p>
<pre><code>public class FeignSimpleEncoderConfig {
public static final int FIVE_SECONDS = 5000;
@Bean
public Logger.Level feignLogger() {
return Logger.Level.FULL;
}
@Bean
public Request.Options options() {
return new Request.Options(FIVE_SECONDS, FIVE_SECONDS);
}
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder() {
return Feign.builder()
.encoder(new FormEncoder());
}
}
</code></pre>
<p>If I send request like this I see that my request send Content-Type: application/json;charset=UTF-8.
But if I set content type </p>
<pre><code>consumes = "application/x-www-form-urlencoded"
</code></pre>
<p>I've this error message</p>
<pre><code>feign.codec.EncodeException: Could not write request: no suitable HttpMessageConverter found for request type [java.util.HashMap] and content type [application/x-www-form-urlencoded]
at org.springframework.cloud.netflix.feign.support.SpringEncoder.encode(SpringEncoder.java:108) ~[spring-cloud-netflix-core-1.1.7.RELEASE.jar:1.1.7.RELEASE]
</code></pre>
<p>How to send POST request, I think I should make something more with Encoder.
Thanks for your help.</p> | 42,444,482 | 3 | 0 | null | 2017-02-23 22:46:29.183 UTC | 8 | 2019-06-20 05:01:01.303 UTC | 2017-03-15 12:59:05.887 UTC | null | 5,546,244 | null | 5,546,244 | null | 1 | 13 | spring-cloud-netflix|netflix-feign|spring-cloud-feign | 38,883 | <p>First of all you should change your Feign interface like this:</p>
<pre><code>@FeignClient (
configuration = FeignSimpleEncoderConfig.class
)
public interface MpiClient {
@RequestMapping(method = RequestMethod.POST)
ResponseEntity<String> getPAReq(Map<String, ?> queryMap);
}
</code></pre>
<p>Then you should set the encoder during feign configuration:</p>
<pre><code>public class FeignSimpleEncoderConfig {
@Bean
public Encoder encoder() {
return new FormEncoder();
}
}
</code></pre> |
10,610,412 | CASE (Contains) rather than equal statement | <p>Is there a method to use contain rather than equal in case statement?</p>
<p>For example, I am checking a database table has an entry</p>
<pre><code>lactulose, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,
</code></pre>
<p>Can I use </p>
<pre><code>CASE When dbo.Table.Column = 'lactulose' Then 'BP Medication' ELSE '' END AS 'BP Medication'
</code></pre>
<p>This did not work.</p>
<p>Thanks in advance</p> | 10,610,453 | 2 | 0 | null | 2012-05-15 23:59:11.1 UTC | 3 | 2012-06-05 12:45:04.48 UTC | 2012-05-16 11:14:21.627 UTC | null | 61,305 | null | 373,721 | null | 1 | 22 | sql-server|sql-server-2008 | 139,827 | <pre><code>CASE WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%'
THEN 'BP Medication' ELSE '' END AS [BP Medication]
</code></pre>
<p>The leading <code>', '</code> and trailing <code>','</code> are added so that you can handle the match regardless of where it is in the string (first entry, last entry, or anywhere in between).</p>
<p>That said, why are you storing data you want to search on as a comma-separated string? This violates all kinds of forms and best practices. You should consider normalizing your schema.</p>
<p>In addition: don't use <code>'single quotes'</code> as identifier delimiters; this syntax is deprecated. Use <code>[square brackets]</code> (preferred) or <code>"double quotes"</code> if you must. See "string literals as column aliases" here: <a href="http://msdn.microsoft.com/en-us/library/bb510662%28SQL.100%29.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb510662%28SQL.100%29.aspx</a></p>
<p><strong>EDIT</strong> If you have multiple values, you can do this (you can't short-hand this with the other <code>CASE</code> syntax variant or by using something like <code>IN()</code>):</p>
<pre><code>CASE
WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%'
WHEN ', ' + dbo.Table.Column +',' LIKE '%, amlodipine,%'
THEN 'BP Medication' ELSE '' END AS [BP Medication]
</code></pre>
<p>If you have more values, it might be worthwhile to use a split function, e.g.</p>
<pre><code>USE tempdb;
GO
CREATE FUNCTION dbo.SplitStrings(@List NVARCHAR(MAX))
RETURNS TABLE
AS
RETURN ( SELECT DISTINCT Item FROM
( SELECT Item = x.i.value('(./text())[1]', 'nvarchar(max)')
FROM ( SELECT [XML] = CONVERT(XML, '<i>'
+ REPLACE(@List,',', '</i><i>') + '</i>').query('.')
) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
WHERE Item IS NOT NULL
);
GO
CREATE TABLE dbo.[Table](ID INT, [Column] VARCHAR(255));
GO
INSERT dbo.[Table] VALUES
(1,'lactulose, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(2,'lactulite, Lasix (furosemide), lactulose, propranolol, rabeprazole, sertraline,'),
(3,'lactulite, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(4,'lactulite, Lasix (furosemide), lactulose, amlodipine, rabeprazole, sertraline,');
SELECT t.ID
FROM dbo.[Table] AS t
INNER JOIN dbo.SplitStrings('lactulose,amlodipine') AS s
ON ', ' + t.[Column] + ',' LIKE '%, ' + s.Item + ',%'
GROUP BY t.ID;
GO
</code></pre>
<p>Results:</p>
<pre><code>ID
----
1
2
4
</code></pre> |
10,846,499 | Alter multiple columns in a single statement | <p>I am using a query to alter the charset of a column</p>
<pre><code>ALTER TABLE `media_value_report`
CHANGE `index_page_body` `index_page_body` TEXT CHARACTER
SET utf8 NULL DEFAULT NULL
</code></pre>
<p>i want to do this for other columns main_title, landing_page_body as well. But am getting a #1064 error while executing. Can i alter-change multiple columns in a single query?</p>
<p>I tried but i found in goog search that is not possible to alter in a single query. </p> | 10,846,845 | 1 | 0 | null | 2012-06-01 07:54:58.113 UTC | 6 | 2012-06-01 08:25:22.977 UTC | 2012-06-01 08:23:29.34 UTC | null | 50,552 | null | 898,749 | null | 1 | 70 | mysql|sql|mysql-error-1064|alter-table | 63,845 | <p>The <a href="http://dev.mysql.com/doc/refman/5.1/en/alter-table.html" rel="noreferrer">documentation suggests</a> you can chain alter_specifications with a comma:</p>
<pre><code>ALTER TABLE `media_value_report`
CHANGE col1_old col1_new varchar(10),
CHANGE col1_old col1_new varchar(10),
...
</code></pre> |
22,948,006 | Http Status Code in Android Volley when error.networkResponse is null | <p>I am using Google Volley on the Android platform.
I am having a problem in which the <code>error</code> parameter in <code>onErrorResponse</code> is returning a null <code>networkResponse</code>
For the RESTful API I am using, I need to determine the Http Status Code which is often arriving as 401 (SC_UNAUTHORIZED) or 500 (SC_INTERNAL_SERVER_ERROR), and I can occasionally check via:</p>
<pre><code>final int httpStatusCode = error.networkResponse.statusCode;
if(networkResponse == HttpStatus.SC_UNAUTHORIZED) {
// Http status code 401: Unauthorized.
}
</code></pre>
<p>This throws a <code>NullPointerException</code> because <code>networkResponse</code> is null.</p>
<p>How can I determine the Http Status Code in the function <code>onErrorResponse</code>?</p>
<p>Or, how can I ensure <code>error.networkResponse</code> is non-null in <code>onErrorResponse</code>?</p> | 23,163,279 | 8 | 0 | null | 2014-04-08 20:56:58.053 UTC | 18 | 2018-06-02 20:03:33.633 UTC | 2016-05-13 05:13:51.62 UTC | null | 4,997,836 | null | 376,829 | null | 1 | 44 | android|http-status-codes|android-volley | 68,735 | <h2>401 Not Supported by Volley</h2>
<p>It turns out that it is impossible to guarantee that error.networkResponse is non-null without modifying Google Volley code because of a bug in Volley that throws the Exception <code>NoConnectionError</code> for Http Status Code 401 (<code>HttpStatus.SC_UNAUTHORIZED</code>) in BasicNetwork.java (134) prior to setting the value of <code>networkResponse</code>.</p>
<h2>Work-Around</h2>
<p>Instead of fixing the Volley code, our solution in this case was to modify the Web Service API to send Http Error Code 403 (<code>HttpStatus.SC_FORBIDDEN</code>) for the particular case in question.</p>
<p>For this Http Status Code, the value of <code>error.networkResponse</code> is non-null in the Volley error handler: <code>public void onErrorResponse(VolleyError error)</code>. And, <code>error.networkResponse.httpStatusCode</code> correctly returns <code>HttpStatus.SC_FORBIDDEN</code>.</p>
<h2>Other-Suggestions</h2>
<p>Rperryng's suggestion of extending the <code>Request<T></code> class may have provided a solution, and is a creative and excellent idea. Thank you very much for the detailed example. I found the optimal solution for our case is to use the work-around because we are fortunate enough to have control of the web services API. </p>
<p>I might opt for fixing the Volley code in one location within BasicNetwork.java if I did not have access to making a simple change at the server. </p> |
23,103,962 | How to write DataFrame to postgres table | <p>There is <em>DataFrame.to_sql</em> method, but it works only for mysql, sqlite and oracle databases. I cant pass to this method postgres connection or sqlalchemy engine.</p> | 23,104,436 | 8 | 0 | null | 2014-04-16 08:29:32.08 UTC | 89 | 2022-08-16 16:38:55.34 UTC | 2022-04-28 05:24:46.153 UTC | null | 7,758,804 | null | 1,185,696 | null | 1 | 154 | python|postgresql|pandas|sqlalchemy | 222,884 | <p>Starting from pandas 0.14 (released end of May 2014), postgresql is supported. The <code>sql</code> module now uses <code>sqlalchemy</code> to support different database flavors. You can pass a sqlalchemy engine for a postgresql database (see <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#io-sql" rel="noreferrer">docs</a>). E.g.:</p>
<pre><code>from sqlalchemy import create_engine
engine = create_engine('postgresql://username:password@localhost:5432/mydatabase')
df.to_sql('table_name', engine)
</code></pre>
<hr />
<p>You are correct that in pandas up to version 0.13.1 postgresql was not supported. If you need to use an older version of pandas, here is a patched version of <code>pandas.io.sql</code>: <a href="https://gist.github.com/jorisvandenbossche/10841234" rel="noreferrer">https://gist.github.com/jorisvandenbossche/10841234</a>.<br />
I wrote this a time ago, so cannot fully guarantee that it always works, buth the basis should be there). If you put that file in your working directory and import it, then you should be able to do (where <code>con</code> is a postgresql connection):</p>
<pre><code>import sql # the patched version (file is named sql.py)
sql.write_frame(df, 'table_name', con, flavor='postgresql')
</code></pre> |
19,438,472 | JSON.NET deserialize a specific property | <p>I have the following <code>JSON</code> text:</p>
<pre><code>{
"PropOne": {
"Text": "Data"
}
"PropTwo": "Data2"
}
</code></pre>
<p>I want to deserialize <code>PropOne</code> into type <code>PropOneClass</code> without the overhead of deserializing any other properties on the object. Can this be done using JSON.NET?</p> | 19,438,910 | 6 | 0 | null | 2013-10-17 22:33:14.957 UTC | 6 | 2016-10-18 20:36:04.817 UTC | 2013-10-18 00:41:02.233 UTC | null | 160,823 | null | 160,823 | null | 1 | 30 | c#|json.net | 45,001 | <pre><code>public T GetFirstInstance<T>(string propertyName, string json)
{
using (var stringReader = new StringReader(json))
using (var jsonReader = new JsonTextReader(stringReader))
{
while (jsonReader.Read())
{
if (jsonReader.TokenType == JsonToken.PropertyName
&& (string)jsonReader.Value == propertyName)
{
jsonReader.Read();
var serializer = new JsonSerializer();
return serializer.Deserialize<T>(jsonReader);
}
}
return default(T);
}
}
public class MyType
{
public string Text { get; set; }
}
public void Test()
{
string json = "{ \"PropOne\": { \"Text\": \"Data\" }, \"PropTwo\": \"Data2\" }";
MyType myType = GetFirstInstance<MyType>("PropOne", json);
Debug.WriteLine(myType.Text); // "Data"
}
</code></pre>
<p>This approach avoids having to deserialize the entire object. But note that this will only improve performance if the json is <strong><em>significantly</em></strong> large, and the property you are deserializing is relatively early in the data. Otherwise, you should just deserialize the whole thing and pull out the parts you want, like jcwrequests answer shows.</p> |
17,959,575 | What is a good, unlimited alternative to Google Places API? | <p>For my project I've been relying on the Places API to search for POI's based on a desired query string and distance from a given point. As things are scaling up, however, I'm hitting the usage limits for Places really fast. Does anyone know of another API that doesn't have usage limits (or significantly more uses) that could substitute for the Places API?</p>
<p>Thanks</p> | 20,603,946 | 1 | 0 | null | 2013-07-31 00:13:28.323 UTC | 13 | 2019-04-05 19:01:26.087 UTC | null | null | null | null | 2,502,953 | null | 1 | 50 | google-maps-api-3|google-places-api | 57,978 | <p>First up, I hope you know that you can bump your Places API quota from 1,000 queries/day up to 100,000 queries/day just by <a href="https://developers.google.com/places/policies#usage_limits">verifying your identity</a>? This doesn't cost anything. And if even 100,000 QPD are not enough, you can purchase a <a href="https://developers.google.com/maps/documentation/business/places/">Google Places API for Business</a> license.</p>
<p>But to actually answer your question, I'm not aware of any alternative that's both good and unlimited. The main competitors with worldwide coverage are:</p>
<ul>
<li><a href="https://developer.foursquare.com/overview/venues.html">Foursquare Venues</a>, which is limited to 5,000 queries/hour. Here's a <a href="http://www.quora.com/What-are-the-pros-and-cons-of-each-Places-API">lengthy point-by-point comparison</a> of the two.</li>
<li>Factual's <a href="http://www.factual.com/products/global">Global Places</a>, limited to 10,000 queries/day.</li>
</ul> |
21,247,278 | About "*.d.ts" in TypeScript | <p>I am curious about <code>.d.ts</code> declaration files because I am new to the TypeScript programming language. I was told by someone that <code>.d.ts</code> files are are similar to <code>.h</code> header files in the C & C++ programming languages, however, the <code>.d.ts</code> files don't seem to work quite the same. Currently, I am failing to understand how to properly use the .d.ts files. It would appear that I cant add my <code>.js</code> or <code>.ts</code> files to the <code>.d.ts</code> files, so the only way my project will work is if it contains all three file types. That seems like a lot of files. To help me better understand how the .d.ts files are related to JavaScript & TypeScript, I have some questions I would like to ask.</p>
<hr />
<ol>
<li><p>What is the relationship between the three files? the relationship between them?</p>
</li>
<li><p>How can I use the <code>*.d.ts</code> file? Does it mean I can delete the <code>*.ts</code> file permanently?</p>
</li>
<li><p>If so, how can the <code>*.d.ts</code> file know which JS file is mapping to itself?</p>
</li>
</ol>
<hr />
<p>It would be very nice if someone can give me an example.</p> | 21,247,316 | 8 | 1 | null | 2014-01-21 01:05:15.707 UTC | 138 | 2022-07-02 01:16:16.34 UTC | 2022-04-29 05:13:50.497 UTC | null | 12,475,483 | user3221822 | null | null | 1 | 617 | typescript|.d.ts | 317,216 | <p>The "d.ts" file is used to provide typescript type information about an API that's written in JavaScript. The idea is that you're using something like jQuery or underscore, an existing javascript library. You want to consume those from your typescript code.</p>
<p>Rather than rewriting jquery or underscore or whatever in typescript, you can instead write the d.ts file, which contains only the type annotations. Then from your typescript code you get the typescript benefits of static type checking while still using a pure JS library.</p>
<p>This works thanks to TypeScript's constraint of not letting you add the ".ts" extension at the end of the <code>import</code> statement. Because of that, when you reference some file, let's say, <code>my-module.js</code>, if there is a <code>my-module.d.ts</code> next to it, then TypeScript will include its content:</p>
<pre class="lang-yaml prettyprint-override"><code>src/
my-module.js
my-module.d.ts
index.ts
</code></pre>
<p><sub><i>my-module.js</i></sub></p>
<pre class="lang-js prettyprint-override"><code>const thing = 42;
module.exports = { thing };
</code></pre>
<p><sub><i>my-module.d.ts</i></sub></p>
<pre><code>export declare const thing: number;
</code></pre>
<p><sub><i>index.ts</i></sub></p>
<pre><code>import { thing } from "./my-module"; // <- no extension
// runtime implementation of `thing` is taken from ".js"
console.log(thing); // 42
// type declaration of `thing` is taken from ".d.ts"
type TypeOfThing = typeof thing; // number
</code></pre> |
21,057,478 | Python ConfigParser Checking existence of both Section and Key Value | <p>Using ConfigParser's <code>has_section()</code> method I can check if a section exists in a file, such as:</p>
<pre><code>config.has_section(section_name)
</code></pre>
<p>What would be a command to check if a <strong>key</strong> exists as well?
So it would be possible to verify that both a section and key exists before querying the value using:</p>
<pre><code>value = config.get(section, key)
</code></pre>
<p>Thanks in advance!</p> | 21,057,828 | 1 | 1 | null | 2014-01-11 01:38:08.747 UTC | 2 | 2018-08-17 18:46:52.487 UTC | 2018-08-17 18:46:52.487 UTC | null | 5,377,495 | null | 1,107,049 | null | 1 | 30 | python|key|config|configparser | 34,445 | <p>In addition to <code>has_section</code>, there is also a <code>has_option</code> method:</p>
<pre><code>config.has_option(section, option)
</code></pre>
<p>From the <a href="https://docs.python.org/3/library/configparser.html" rel="noreferrer">Python documentation</a>:</p>
<blockquote>
<p><strong>has_option*</strong>(section, option)*<br> If the given section exists, and contains
the given option, return True; otherwise return False. If the
specified section is None or an empty string, DEFAULT is assumed.</p>
</blockquote> |
21,745,593 | Why jackson is serializing transient member also? | <p>I am serializing a POJO into JSON using Jackson 2.1.4 but I want to ignore a particular field from getting serialized. I used transient but still it is serializing that element.</p>
<pre><code>public class TestElement {
int x;
private transient String y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public String getY() {
return y;
}
public void setY(String y) {
this.y = y;
}
}
</code></pre>
<p>I am serializing as following:</p>
<pre><code>public static void main(String[] args) throws JsonProcessingException {
TestElement testElement = new TestElement();
testElement.setX(10);
testElement.setY("adasd");
ObjectMapper om = new ObjectMapper();
String serialized = om.writeValueAsString(testElement);
System.err.println(serialized);
}
</code></pre>
<p>Please don't suggest <code>@JsonIgnore</code> as I don't want to tie my model to jackson specific annotations. Can it be done using transient only? Is there any API on objectmapper for visibility settings?</p> | 21,749,892 | 4 | 0 | null | 2014-02-13 04:57:02.607 UTC | 11 | 2021-01-14 09:49:21.147 UTC | 2014-02-13 23:36:05.44 UTC | null | 51,591 | null | 2,362,514 | null | 1 | 54 | json|jackson|transient | 42,723 | <p>The reason Jackson serializes the <code>transient</code> member is because the getters are used to determine what to serialize, not the member itself - and since <code>y</code> has a public getter, that gets serialized.
If you want to change that default and have Jackson use fields - simply do:</p>
<pre><code>om.setVisibilityChecker(
om.getSerializationConfig()
.getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
);
</code></pre>
<p>Another way to ignore a property on serialization is to do it directly on the class:</p>
<pre><code>@JsonIgnoreProperties(value = { "y" })
public class TestElement {
...
</code></pre>
<p>And another way is directly on the field:</p>
<pre><code>public class TestElement {
@JsonIgnore
private String y;
...
</code></pre>
<p>Hope this helps.</p> |
37,071,788 | Tensorflow: How to modify the value in tensor | <p>Since I need to write some preprocesses for the data before using Tensorflow to train models, some modifications on the <code>tensor</code> is needed. However, I have no idea about how to modify the values in <code>tensor</code> like the way using <code>numpy</code>. </p>
<p>The best way of doing so is that it is able to modify <code>tensor</code> directly. Yet, it seems not possible in the current version of Tensorflow. An alternative way is changing <code>tensor</code> to <code>ndarray</code> for the process, and then use <code>tf.convert_to_tensor</code> to change back. </p>
<p>The key is how to change <code>tensor</code> to <code>ndarray</code>.<br>
1) <code>tf.contrib.util.make_ndarray(tensor)</code>:
<a href="https://www.tensorflow.org/versions/r0.8/api_docs/python/contrib.util.html#make_ndarray" rel="noreferrer">https://www.tensorflow.org/versions/r0.8/api_docs/python/contrib.util.html#make_ndarray</a><br>
It seems the easiest way as per the document, yet I cannot find this function in the current version of the Tensorflow. Second, the input of it is <code>TensorProto</code> rather than <code>tensor</code>.<br>
2) Use <code>a.eval()</code> to copy <code>a</code> to another <code>ndarray</code><br>
Yet, it works only at using <code>tf.InteractiveSession()</code> in notebook. </p>
<p>A simple case with codes shows below. The purpose of this code is making that the <code>tfc</code> has the same output as <code>npc</code> after the process. </p>
<p><strong>HINT</strong><br>
You should treat that <code>tfc</code> and <code>npc</code> are independent to each other. This meets the situation that at first the retrieved training data is in <code>tensor</code> format with <a href="https://www.tensorflow.org/versions/r0.8/api_docs/python/io_ops.html#placeholder" rel="noreferrer"><code>tf.placeholder()</code></a>. </p>
<hr>
<p><strong>Source code</strong></p>
<pre><code>import numpy as np
import tensorflow as tf
tf.InteractiveSession()
tfc = tf.constant([[1.,2.],[3.,4.]])
npc = np.array([[1.,2.],[3.,4.]])
row = np.array([[.1,.2]])
print('tfc:\n', tfc.eval())
print('npc:\n', npc)
for i in range(2):
for j in range(2):
npc[i,j] += row[0,j]
print('modified tfc:\n', tfc.eval())
print('modified npc:\n', npc)
</code></pre>
<hr>
<p><strong>Output:</strong></p>
<p>tfc:<br>
[[ 1. 2.]<br>
[ 3. 4.]]<br>
npc:<br>
[[ 1. 2.]<br>
[ 3. 4.]]<br>
modified tfc:<br>
[[ 1. 2.]<br>
[ 3. 4.]]<br>
modified npc:<br>
[[ 1.1 2.2]<br>
[ 3.1 4.2]] </p> | 37,074,501 | 2 | 0 | null | 2016-05-06 11:56:51.163 UTC | 13 | 2019-06-11 12:44:18.173 UTC | 2016-05-07 00:31:00.273 UTC | null | 3,030,046 | null | 3,030,046 | null | 1 | 16 | python|numpy|tensorflow | 56,973 | <p>Use assign and eval (or sess.run) the assign:</p>
<pre><code>import numpy as np
import tensorflow as tf
npc = np.array([[1.,2.],[3.,4.]])
tfc = tf.Variable(npc) # Use variable
row = np.array([[.1,.2]])
with tf.Session() as sess:
tf.initialize_all_variables().run() # need to initialize all variables
print('tfc:\n', tfc.eval())
print('npc:\n', npc)
for i in range(2):
for j in range(2):
npc[i,j] += row[0,j]
tfc.assign(npc).eval() # assign_sub/assign_add is also available.
print('modified tfc:\n', tfc.eval())
print('modified npc:\n', npc)
</code></pre>
<p>It outputs:</p>
<pre><code>tfc:
[[ 1. 2.]
[ 3. 4.]]
npc:
[[ 1. 2.]
[ 3. 4.]]
modified tfc:
[[ 1.1 2.2]
[ 3.1 4.2]]
modified npc:
[[ 1.1 2.2]
[ 3.1 4.2]]
</code></pre> |
37,119,429 | Android Retrofit 2, differences between addInterceptor & addNetworkInterceptor for editing responses | <p>I've been trying to implement an interceptor <strong>( OkHttp 3.2 & Retrofit 2 )</strong> for editing the JSON response before is returned as response. The server we request data returns different data dependes on success or error and that makes difficult to map the objects. </p>
<p>I was trying to do it by adding the interceptor to Retrofit as a NetworkInterceptor, however the string returned had no format. </p>
<pre><code>@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
try {
final String responseString = new String(response.body().bytes() );
LOGD("OkHttp-NET-Interceptor", "Response: " + responseString);
String newResponseString = editResponse( responseString );
LOGD("OkHttp-NET-Interceptor", "Response edited: " + newResponseString);
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), newResponseString))
.build();
}catch (Exception ex){
return response;
}
}
</code></pre>
<p><strong>responseString</strong> had a string without any understandable format. </p>
<p>After changing to the normal interceptor, the string had format a it was able to convert to JSONObject.</p>
<p>Could tell me someone which are the differences between the <strong>responses</strong>? </p>
<p>why this line <strong>new String(response.body().bytes() );</strong> return different content?</p> | 37,120,830 | 2 | 0 | null | 2016-05-09 15:17:26.787 UTC | 10 | 2021-08-03 11:37:22.497 UTC | 2017-10-03 09:43:44.553 UTC | null | 3,283,376 | null | 1,873,390 | null | 1 | 47 | android|interceptor|retrofit2|okhttp | 18,077 | <p>The differences are in the names. <code>NetworkInterceptor</code> hooks in at the network level and is an ideal place to put retry logic and anything that doesn't rely on the actual content of the response.</p>
<p>If what you do depends on the contents of the response (like in your case), using a <code>ApplicationInterceptor</code> is more useful, as it gives you the response after it's been processed by any other moving parts you may have such as a JSON deserializer. Otherwise you would have to implement the JSON deserializing yourself inside the <code>NetworkInterceptor</code> which doesn't make much sense considering it's done for you by Retrofit.</p>
<p><strong>Clarification</strong></p>
<p>Square have this useful diagram on their wiki that shows where each type of interceptor sits</p>
<p><a href="https://i.stack.imgur.com/YWurw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YWurw.png" alt="interceptor diagram"></a></p>
<p>Thus, the reason you receive a readable string in the <code>ApplicationInterceptor</code> is because Square are trying to de-couple the purposes of the two interceptor types. They don't think you should be making any application dependent decisions in the <code>NetworkInterceptor</code>, and so they don't provide an easy way for you to access the response string. It is possible to get ahold of, but like I said, they don't want you to make decisions that depend on the content of the response - rather, they want you to make decisions based or the network state, or headers etc.</p>
<p>The <code>ApplicationInterceptor</code> is where they want you to make decisions dependent upon the contents of the response, so they provide easier methods to access the content of the response so that you can make informed decisions to retry, or as they detail in their wiki, <a href="https://github.com/square/okhttp/wiki/Interceptors#rewriting-responses" rel="noreferrer">rewrite responses</a> (which I believe is what you're trying to do).</p> |
29,968,499 | Vertical rulers in Visual Studio Code | <h3>Rendering More than One Ruler in VS Code</h3>
<hr />
<p>VS Code's default configuration for a ruler is demonstrated below.</p>
<pre><code> "editor.ruler": 80
</code></pre>
<p>The issue I am having with the default VS Code configuration <em>(as shown above)</em> is that it only renders a single ruler. In the <strong>Sublime Text Editor</strong> I can render as many rulers as I like using the following Sublime configuration.</p>
<pre><code> "rulers": [72, 80, 100, 120]
</code></pre>
<p>Is it possible to render multiple rulers in V.S. Code. If it is possible, What does a multi-ruler configuration look like in <strong>VS Code</strong>?</p> | 29,972,073 | 11 | 2 | null | 2015-04-30 13:03:08.17 UTC | 219 | 2022-09-17 00:15:32.783 UTC | 2022-06-07 13:25:30.333 UTC | null | 12,475,483 | null | 220,060 | null | 1 | 1,329 | visual-studio-code|configuration | 597,094 | <p>Visual Studio Code 0.10.10 introduced this feature. To configure it, go to menu <em>File</em> → <em>Preferences</em> → <em>Settings</em> and add this to to your user or workspace settings:</p>
<pre class="lang-json prettyprint-override"><code>"editor.rulers": [80,120]
</code></pre>
<p>The color of the rulers can be customized like this:</p>
<pre class="lang-json prettyprint-override"><code>"workbench.colorCustomizations": {
"editorRuler.foreground": "#ff4081"
}
</code></pre> |
8,864,430 | Compare JavaScript Array of Objects to Get Min / Max | <p>I have an array of objects and I want to compare those objects on a specific object property. Here's my array:</p>
<pre><code>var myArray = [
{"ID": 1, "Cost": 200},
{"ID": 2, "Cost": 1000},
{"ID": 3, "Cost": 50},
{"ID": 4, "Cost": 500}
]
</code></pre>
<p>I'd like to zero in on the "cost" specifically and a get a min and maximum value. I realize I can just grab the cost values and push them off into a javascript array and then run the <a href="http://ejohn.org/blog/fast-javascript-maxmin/" rel="noreferrer" title="Fast JavaScript Max/Min">Fast JavaScript Max/Min</a>.</p>
<p>However is there an easier way to do this by bypassing the array step in the middle and going off the objects properties (in this case "Cost") directly?</p> | 8,864,464 | 17 | 0 | null | 2012-01-14 18:38:48.96 UTC | 36 | 2022-03-14 12:38:55.237 UTC | 2016-08-23 01:00:04.803 UTC | null | 6,581,424 | null | 306,528 | null | 1 | 144 | javascript|arrays|compare | 150,379 | <p>One way is to loop through all elements and compare it to the highest/lowest value.</p>
<p><em>(Creating an array, invoking array methods is overkill for this simple operation).</em></p>
<pre><code> // There's no real number bigger than plus Infinity
var lowest = Number.POSITIVE_INFINITY;
var highest = Number.NEGATIVE_INFINITY;
var tmp;
for (var i=myArray.length-1; i>=0; i--) {
tmp = myArray[i].Cost;
if (tmp < lowest) lowest = tmp;
if (tmp > highest) highest = tmp;
}
console.log(highest, lowest);
</code></pre> |
57,633,029 | NPM: how to specify registry to publish in the command line? | <p>I'm testing a new version of our npm packages registry. I'd like to run a job in our CI server specifying a registry different of the default. </p>
<p>I tried to execute <code>npm publish --registry "http://nexus.dsv.myhost/nexus/repository/npmjs-registry</code> but it didn't work. It was published to the default registry. </p>
<p>How do I specify a different registry while running <code>npm publish</code>. It is a scoped package.</p> | 67,691,043 | 2 | 0 | null | 2019-08-23 21:07:08.21 UTC | 3 | 2021-11-10 21:34:29.183 UTC | null | null | null | null | 10,335 | null | 1 | 28 | npm|nexus3 | 26,001 | <p>It sounds like you have a scope-specific registry configured somewhere in your npm config.</p>
<p>npm will merge your global, local and CLI-provided config. But any scope-specific config will take precedence over unscoped config regardless of where each of them are defined.</p>
<p>For example, if you have <code>@myscope:registry=xyz</code> in your <code>~/.npmrc</code> file, that will take precedence over <code>--registry=abc</code> provided on the CLI, because a scope-specific registry always overrides the unscoped registry.</p>
<p>However, you can also pass a scope-specific registry on the CLI itself like this:</p>
<pre class="lang-sh prettyprint-override"><code>npm publish --@myscope:registry=http://nexus.dsv.myhost/nexus/repository/npmjs-registry
</code></pre>
<p>Note that because of how <code>nopt</code> (which is what npm uses under the hood to parse the CLI options) parses freeform switches, the <code>=</code> sign here is required. If you use a space instead, it won't work as expected.</p> |
61,010,294 | How to cache yarn packages in GitHub Actions | <p>I am using GitHub Actions to build my TypeScript project.
Everytime I run action I am waiting 3 minutes for all dependencies to get installed.</p>
<p>Is there way to cache yarn dependencies, so build time will be faster?</p>
<p>I tried this:</p>
<pre class="lang-yaml prettyprint-override"><code> - name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v1
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Install yarn
run: npm install -g yarn
- name: Install project dependencies
run: yarn
</code></pre>
<p>but build time is still same.</p> | 61,026,157 | 4 | 0 | null | 2020-04-03 10:55:59.3 UTC | 11 | 2022-08-31 22:37:26.647 UTC | 2020-04-04 09:33:32.78 UTC | null | 6,782,707 | null | 10,426,052 | null | 1 | 35 | typescript|yarnpkg|github-actions | 22,384 | <p>As mentioned in the comment next to the <code>id</code> field for the caching step:</p>
<blockquote>
<p>Use this to check for <code>cache-hit</code> (<code>steps.yarn-cache.outputs.cache-hit != 'true'</code>)</p>
</blockquote>
<p>You're missing a conditional <code>if</code> property that determines whether the step should be run:</p>
<pre class="lang-yaml prettyprint-override"><code>- name: Install yarn
run: npm install -g yarn
- name: Install project dependencies
if: steps.yarn-cache.outputs.cache-hit != 'true' # Over here!
run: yarn
</code></pre>
<p>P.S. You should probably use the <a href="https://github.com/actions/setup-node" rel="noreferrer">Setup NodeJS</a> GitHub Action that additionally sets up Yarn for you:</p>
<pre class="lang-yaml prettyprint-override"><code>- uses: actions/setup-node@v1
with:
node-version: '10.x' # The version spec of the version to use.
</code></pre>
<p>See the <a href="https://github.com/actions/setup-node/blob/master/action.yml" rel="noreferrer"><code>action.yml</code> file</a> for a full list of valid inputs.</p>
<hr>
<p>EDIT: As it turns out, Yarn is included in the list of <a href="https://github.com/actions/virtual-environments/blob/master/images/linux/Ubuntu1804-README.md" rel="noreferrer">software installed on the GitHub-hosted Ubuntu 18.04.4 LTS (<code>ubuntu-latest</code>/<code>ubuntu-18.04</code>) runner</a>, so there's no need to include a step to globally install Yarn.</p> |
47,645,158 | MySQL Workbench left navigator panel missing on MAC? | <p>I connected to the server in mysql workbench but I see that something has changed? There used to be a navigator panel on the left hand side with all the schemas and the database options like this:
<a href="https://i.stack.imgur.com/zhnhg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zhnhg.png" alt="enter image description here"></a></p>
<p>But now on mine it only shows:</p>
<p><a href="https://i.stack.imgur.com/no41O.png" rel="noreferrer"><img src="https://i.stack.imgur.com/no41O.png" alt="enter image description here"></a></p>
<p>I have tried going to the preferences and clicking on all the options but nothing works???</p>
<p><a href="https://i.stack.imgur.com/LRBhK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LRBhK.png" alt="enter image description here"></a></p> | 47,649,653 | 1 | 2 | null | 2017-12-05 02:31:22.823 UTC | 5 | 2020-12-03 04:01:44.927 UTC | 2017-12-05 02:36:23.3 UTC | null | 5,422,791 | null | 5,422,791 | null | 1 | 28 | mysql-workbench | 17,561 | <p>There's a splitter between the Object/Session info and the schema tree/management part. In your case it's moved up all the way, so you only see the lower part. Drag the marked line down to make the upper part visible:</p>
<p><a href="https://i.stack.imgur.com/73vZ7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/73vZ7.png" alt="enter image description here"></a></p>
<p><strong>Update</strong></p>
<p>Starting with MySQL Workbench 8.0.14 the splitter has been changed to show in a different style which makes it much more easy to recognize it:</p>
<p><a href="https://i.stack.imgur.com/vHIzl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vHIzl.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/xdJMA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xdJMA.png" alt="enter image description here"></a></p> |
43,597,803 | How to differentiate build triggers in Jenkins Pipeline | <p>I'm hoping to add a conditional stage to my Jenkinsfile that runs depending on how the build was triggered. Currently we are set up such that builds are either triggered by: </p>
<ol>
<li>changes to our git repo that are picked up on branch indexing </li>
<li>a user manually triggering the build using the 'build now' button in the UI. </li>
</ol>
<p>Is there any way to run different pipeline steps depending on which of these actions triggered the build?</p> | 43,609,466 | 9 | 1 | null | 2017-04-24 21:12:20.117 UTC | 10 | 2022-01-14 19:00:49.443 UTC | null | null | null | null | 4,055,763 | null | 1 | 42 | jenkins|jenkins-pipeline | 51,236 | <p>The following code should works to determine if a user has started the pipeline or a timer/other trigger:</p>
<pre><code>def isStartedByUser = currentBuild.rawBuild.getCause(hudson.model.Cause$UserIdCause) != null
</code></pre> |
38,288 | How do I add a user in Ubuntu? | <p>Specifically, what commands do I run from the terminal?</p> | 38,289 | 3 | 5 | null | 2008-09-01 18:59:14.59 UTC | 28 | 2018-02-17 23:16:54.793 UTC | 2018-02-17 23:16:54.793 UTC | null | 736,054 | null | 3,624 | null | 1 | 64 | linux|ubuntu|sysadmin|user-management | 76,698 | <p>Without a home directory</p>
<pre><code>sudo useradd myuser
</code></pre>
<p>With home directory</p>
<pre><code>sudo useradd -m myuser
</code></pre>
<p>Then set the password</p>
<pre><code>sudo passwd myuser
</code></pre>
<p>Then set the shell</p>
<pre><code>sudo usermod -s /bin/bash myuser
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.