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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
40,470,895 | PhpStorm saving with Linux line ending on Windows | <p><em>Environment: Windows + PhpStorm</em></p>
<p><strong>Issue</strong>: PhpStorm saves file with Windows line endings - and for shell script it's issue so there is need to always convert after copying to server.</p>
<p><strong>Question</strong>: Is possible to configure <strong>PhpStorm</strong> to save file with <strong>Linux line endings</strong> - <code>\n</code> and not <code>\n\r</code> (new line + carriage return)?</p> | 40,472,391 | 1 | 0 | null | 2016-11-07 17:20:29.553 UTC | 9 | 2020-06-22 12:00:24.75 UTC | 2016-11-07 18:33:04.39 UTC | null | 783,119 | null | 1,571,491 | null | 1 | 45 | windows|phpstorm|line-endings | 50,087 | <p>You can safely use <code>\n</code> line ending for <code>.php</code> and most of other files as well -- PHP on Windows will read such files just fine.</p>
<hr />
<p><strong>To set default line ending</strong> for all <strong>new</strong> files: go to <code>Settings/Preferences | Editor | Code Style</code> and change <code>Line separator (for new files)</code> option to the desired style (e.g. <code>Unix and OS X (\n)</code>).</p>
<p><a href="https://i.stack.imgur.com/UsyYt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UsyYt.png" alt="enter image description here" /></a></p>
<hr />
<p><strong>To change line ending for a particular existing file:</strong> open the file and either change it via appropriate section in Status Bar .. or via <code>File | File Properties | Line Separators</code></p>
<p><a href="https://i.stack.imgur.com/RQa9H.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RQa9H.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/jgvyZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jgvyZ.png" alt="enter image description here" /></a></p>
<hr />
<p><strong>P.S.</strong></p>
<p>If you do have <strong>EditorConfig plugin</strong> installed and enabled ... you might also configure this via <a href="http://editorconfig.org/" rel="noreferrer">.editorconfig file</a> -- there you may specify what line ending to use (this can be done on per file extension level .. so it's more flexible than PhpStorm's own setting).</p>
<p>This will also work in another editor/IDE that supports such file.</p> |
33,575,563 | C++ lambda capture this vs capture by reference | <p>If I need to generate a lambda that calls a member function, should I capture by reference or capture 'this'? My understanding is that '&' captures only the variables used, but 'this' captures all member variable. So better to use '&'?</p>
<pre><code>class MyClass {
public:
int mFunc() {
// accesses member variables
}
std::function<int()> get() {
//return [this] () { return this->mFunc(); };
// or
//return [&] () { return this->mFunc(); };
}
private:
// member variables
}
</code></pre> | 33,576,211 | 4 | 0 | null | 2015-11-06 20:55:46.373 UTC | 8 | 2020-07-30 07:10:04.4 UTC | null | null | null | null | 1,262,000 | null | 1 | 39 | c++|c++11|lambda|std-function | 57,410 | <p>For the specific example you've provided, capturing by <code>this</code> is what you want. Conceptually, capturing <code>this</code> by reference doesn't make a whole lot of sense, since you can't change the value of <code>this</code>, you can only use it as a pointer to access members of the class or to get the address of the class instance. Inside your lambda function, if you access things which implicitly use the <code>this</code> pointer (e.g. you call a member function or access a member variable without explicitly using <code>this</code>), the compiler treats it as though you had used <code>this</code> anyway. You can list multiple captures too, so if you want to capture both members and local variables, you can choose independently whether to capture them by reference or by value. The following article should give you a good grounding in lambdas and captures:</p>
<p><a href="https://crascit.com/2015/03/01/lambdas-for-lunch/" rel="noreferrer">https://crascit.com/2015/03/01/lambdas-for-lunch/</a></p>
<p>Also, your example uses <code>std::function</code> as the return type through which the lambda is passed back to the caller. Be aware that <code>std::function</code> isn't always as cheap as you may think, so if you are able to use a lambda directly rather than having to wrap it in a <code>std::function</code>, it will likely be more efficient. The following article, while not directly related to your original question, may still give you some useful material relating to lambdas and <code>std::function</code> (see the section <em>An alternative way to store the function object</em>, but the article in general may be of interest):</p>
<p><a href="https://crascit.com/2015/06/03/on-leaving-scope-part-2/" rel="noreferrer">https://crascit.com/2015/06/03/on-leaving-scope-part-2/</a></p> |
36,077,266 | How do I raise a FileNotFoundError properly? | <p>I use a third-party library that's fine but does not handle inexistant files the way I would like. When giving it a non-existant file, instead of raising the good old </p>
<pre><code>FileNotFoundError: [Errno 2] No such file or directory: 'nothing.txt'
</code></pre>
<p>it raises some obscure message:</p>
<pre><code>OSError: Syntax error in file None (line 1)
</code></pre>
<p>I don't want to handle the missing file, don't want to catch nor handle the exception, don't want to raise a custom exception, neither want I to <code>open</code> the file, nor to create it if it does not exist.</p>
<p>I only want to check it exists (<code>os.path.isfile(filename)</code> will do the trick) and if not, then just raise a proper FileNotFoundError.</p>
<p>I tried this:</p>
<pre><code>#!/usr/bin/env python3
import os
if not os.path.isfile("nothing.txt"):
raise FileNotFoundError
</code></pre>
<p>what only outputs:</p>
<pre><code>Traceback (most recent call last):
File "./test_script.py", line 6, in <module>
raise FileNotFoundError
FileNotFoundError
</code></pre>
<p>This is better than a "Syntax error in file None", but how is it possible to raise the "real" python exception with the proper message, without having to reimplement it?</p> | 36,077,407 | 1 | 0 | null | 2016-03-18 06:06:00.903 UTC | 17 | 2016-03-18 06:34:43.223 UTC | null | null | null | null | 3,926,735 | null | 1 | 90 | python|python-3.x|file-not-found | 83,995 | <p>Pass in arguments:</p>
<pre><code>import errno
import os
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), filename)
</code></pre>
<p><code>FileNotFoundError</code> is a subclass of <a href="https://docs.python.org/3/library/exceptions.html#OSError" rel="noreferrer"><code>OSError</code></a>, which takes several arguments. The first is an error code from the <a href="https://docs.python.org/3/library/errno.html" rel="noreferrer"><code>errno</code> module</a> (file not found is always <code>errno.ENOENT</code>), the second the error message (use <a href="https://docs.python.org/3/library/os.html#os.strerror" rel="noreferrer"><code>os.strerror()</code></a> to obtain this), and pass in the filename as the 3rd.</p>
<p>The final string representation used in a traceback is built from those arguments:</p>
<pre><code>>>> print(FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), 'foobar'))
[Errno 2] No such file or directory: 'foobar'
</code></pre> |
34,751,794 | Displaying EC2 Instance name using Boto 3 | <p>I'm not sure how to display the name of my instance in AWS EC2 using <code>boto3</code></p>
<p>This is some of the code I have:</p>
<pre><code>import boto3
ec2 = boto3.resource('ec2', region_name='us-west-2')
vpc = ec2.Vpc("vpc-21c15555")
for i in vpc.instances.all():
print(i)
</code></pre>
<p>What I get in return is </p>
<pre><code>...
...
...
ec2.Instance(id='i-d77ed20c')
</code></pre>
<p><a href="https://i.stack.imgur.com/uq24o.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uq24o.png" alt="enter image description here"></a></p>
<p>I can change <code>i</code> to be <code>i.id</code> or <code>i.instance_type</code> but when I try <code>name</code> I get:</p>
<p><code>AttributeError: 'ec2.Instance' object has no attribute 'name'</code></p>
<p>What is the correct way to get the instance name?</p> | 34,752,072 | 2 | 0 | null | 2016-01-12 19:02:43.617 UTC | 4 | 2018-10-03 07:29:49.117 UTC | 2016-01-12 19:52:20.067 UTC | null | 5,451,492 | null | 1,815,710 | null | 1 | 27 | python|python-3.x|amazon-web-services|amazon-ec2|boto3 | 43,134 | <p>There may be other ways. But from your code point of view, the following should work.</p>
<pre><code>>>> for i in vpc.instances.all():
... for tag in i.tags:
... if tag['Key'] == 'Name':
... print tag['Value']
</code></pre>
<p>One liner solution if you want to use Python's powerful list comprehension:</p>
<pre><code>inst_names = [tag['Value'] for i in vpc.instances.all() for tag in i.tags if tag['Key'] == 'Name']
print inst_names
</code></pre> |
32,109,319 | How to implement the ReLU function in Numpy | <p>I want to make a simple neural network which uses the ReLU function. Can someone give me a clue of how can I implement the function using numpy.</p> | 32,109,519 | 9 | 0 | null | 2015-08-20 03:58:56.267 UTC | 27 | 2022-03-27 15:16:47.027 UTC | 2020-07-20 01:06:41.103 UTC | null | 1,079,075 | null | 4,467,507 | null | 1 | 93 | python|numpy|machine-learning|neural-network | 171,266 | <p>There are a couple of ways.</p>
<pre><code>>>> x = np.random.random((3, 2)) - 0.5
>>> x
array([[-0.00590765, 0.18932873],
[-0.32396051, 0.25586596],
[ 0.22358098, 0.02217555]])
>>> np.maximum(x, 0)
array([[ 0. , 0.18932873],
[ 0. , 0.25586596],
[ 0.22358098, 0.02217555]])
>>> x * (x > 0)
array([[-0. , 0.18932873],
[-0. , 0.25586596],
[ 0.22358098, 0.02217555]])
>>> (abs(x) + x) / 2
array([[ 0. , 0.18932873],
[ 0. , 0.25586596],
[ 0.22358098, 0.02217555]])
</code></pre>
<p>If timing the results with the following code:</p>
<pre><code>import numpy as np
x = np.random.random((5000, 5000)) - 0.5
print("max method:")
%timeit -n10 np.maximum(x, 0)
print("multiplication method:")
%timeit -n10 x * (x > 0)
print("abs method:")
%timeit -n10 (abs(x) + x) / 2
</code></pre>
<p>We get:</p>
<pre><code>max method:
10 loops, best of 3: 239 ms per loop
multiplication method:
10 loops, best of 3: 145 ms per loop
abs method:
10 loops, best of 3: 288 ms per loop
</code></pre>
<p>So the multiplication seems to be the fastest.</p> |
31,874,670 | Merge parent branch into child branch | <p>I'm using bitbucket and sourcetree and I've done this:</p>
<p>I have a develop branch. From this branch I have created a feature branch.</p>
<p>After creating I have fix some errors on develop branch and push it to this branch only.</p>
<p>How can I have these fixes in the feature branch? I think I have to merge develop branch into feature branch but I'm not sure because I'm new in git and I don't want to do something wrong that makes me lose develop branch. but now I want to have these fixes on my feature branch.</p>
<p>What do I have to do?</p> | 31,884,954 | 2 | 0 | null | 2015-08-07 09:45:28.48 UTC | 8 | 2015-08-07 19:06:34.393 UTC | null | null | null | null | 68,571 | null | 1 | 22 | git|merge|branch|atlassian-sourcetree | 38,967 | <p>You want to bring changes from development branch to feature branch. So first switch to feature branch and merge development branch into it. In case you want the commits from develop branch too, use the non fast forward merge <code>--no-ff</code> approach. Else do not use <code>--no-ff</code>.</p>
<pre><code>git checkout feature
git merge --no-ff develop
</code></pre>
<p>As you are merging develop branch into feature branch, stay assured that develop branch will remain untouched. You may get merge conflicts in feature branch which can be easily solved following the steps on this link: <a href="http://softwarecave.org/2014/03/03/git-how-to-resolve-merge-conflicts/" rel="noreferrer">http://softwarecave.org/2014/03/03/git-how-to-resolve-merge-conflicts/</a></p> |
22,749,570 | Wildfly configuration with DataSource | <p>this is the first time I am trying to setup datasource in my Wildfly server. I tried to follow some tutorials which I found on Google but it still doesn't work.</p>
<p>I am working on a web service but I keep getting some errors when I deploy my .war file.</p>
<p>Here is the latest log when app is deployed:</p>
<pre><code>22:16:33,049 INFO [org.jboss.as.server.deployment] (MSC service thread 1-2) JBAS015877: Stopped deployment IslamicPostsWS.war (runtime-name: IslamicPostsWS.war) in 7ms
22:16:33,184 INFO [org.jboss.as.server] (XNIO-1 task-2) JBAS018558: Undeployed "IslamicPostsWS.war" (runtime-name: "IslamicPostsWS.war")
22:16:33,186 INFO [org.jboss.as.controller] (XNIO-1 task-2) JBAS014774: Service status report
JBAS014777: Services which failed to start: service jboss.deployment.unit."IslamicPostsWS.war".POST_MODULE
22:16:35,518 INFO [org.jboss.as.server.deployment] (MSC service thread 1-6) JBAS015877: Stopped deployment IslamicPostsWS (runtime-name: IslamicPostsWS) in 7ms
22:16:35,660 INFO [org.jboss.as.server] (XNIO-1 task-6) JBAS018558: Undeployed "IslamicPostsWS" (runtime-name: "IslamicPostsWS")
22:16:38,358 INFO [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 2) JBAS015018: Deployment IslamicPostsWS was previously deployed by this scanner but has been removed from the server deployment list by another management tool. Marker file C:\Users\Ilhami\workspace-services\.metadata\.plugins\org.jboss.ide.eclipse.as.core\WildFly_8.0_Runtime_Server1396040937545\deploy\IslamicPostsWS.undeployed is being added to record this fact.
22:17:00,406 INFO [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015876: Starting deployment of "IslamicPostsWS.war" (runtime-name: "IslamicPostsWS.war")
22:17:00,540 ERROR [org.jboss.as.controller.management-operation] (DeploymentScanner-threads - 2) JBAS014613: Operation ("deploy") failed - address: ([("deployment" => "IslamicPostsWS.war")]) - failure description: {
"JBAS014771: Services with missing/unavailable dependencies" => ["jboss.naming.context.java.module.IslamicPostsWS.IslamicPostsWS.DefaultDataSource is missing [jboss.naming.context.java.jboss.datasources.ExampleDS]"],
"JBAS014879: One or more services were unable to start due to one or more indirect dependencies not being available." => {
"Services that were unable to start:" => [
"jboss.deployment.unit.\"IslamicPostsWS.war\".component.\"com.sun.faces.config.ConfigureListener\".START",
"jboss.deployment.unit.\"IslamicPostsWS.war\".component.\"javax.faces.webapp.FacetTag\".START",
"jboss.deployment.unit.\"IslamicPostsWS.war\".component.\"javax.servlet.jsp.jstl.tlv.PermittedTaglibsTLV\".START",
"jboss.deployment.unit.\"IslamicPostsWS.war\".component.\"javax.servlet.jsp.jstl.tlv.ScriptFreeTLV\".START",
"jboss.deployment.unit.\"IslamicPostsWS.war\".component.\"org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher\".START",
"jboss.deployment.unit.\"IslamicPostsWS.war\".component.\"org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap\".START",
"jboss.deployment.unit.\"IslamicPostsWS.war\".deploymentCompleteService",
"jboss.deployment.unit.\"IslamicPostsWS.war\".jndiDependencyService",
"jboss.naming.context.java.module.IslamicPostsWS.IslamicPostsWS.env.jdbc.TestDB",
"jboss.undertow.deployment.default-server.default-host./IslamicPostsWS",
"jboss.undertow.deployment.default-server.default-host./IslamicPostsWS.UndertowDeploymentInfoService"
],
"Services that may be the cause:" => [
"jboss.jdbc-driver.com_mysql_jdbc_Driver",
"jboss.naming.context.java.jboss.datasources.ExampleDS"
]
}
}
22:17:00,683 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018559: Deployed "IslamicPostsWS.war" (runtime-name : "IslamicPostsWS.war")
22:17:00,683 INFO [org.jboss.as.controller] (DeploymentScanner-threads - 2) JBAS014774: Service status report
JBAS014775: New missing/unsatisfied dependencies:
service jboss.naming.context.java.jboss.datasources.ExampleDS (missing) dependents: [service jboss.naming.context.java.module.IslamicPostsWS.IslamicPostsWS.DefaultDataSource]
</code></pre>
<p>persistence.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="JPADB">
<jta-data-source>java:jboss/datasources/DBTest</jta-data-source>
<properties>
<property name="showSql" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
</persistence>
</code></pre>
<p>Just tell me if you need more files.</p> | 22,764,683 | 6 | 0 | null | 2014-03-30 20:40:23.927 UTC | 2 | 2021-06-05 01:12:51.957 UTC | null | null | null | null | 3,342,117 | null | 1 | 9 | java|web-services|dependencies|jndi|wildfly | 64,838 | <p>can you post your datasource definition?</p>
<p>I think it would be the best to test the datasource deployment 'standalone'. I mean separated from an actual application deployment, just to test whether your datasource works or not.
You can test this f.i. using the web console (localhost:9990/console).</p>
<p>It also looks like there are problems with the pre-configured example DS of wildfly. Did you remove this DS? In standalone.xml there is also a reference on ExampleDS which might be broken.</p> |
2,723,803 | Hibernate criteria query using Max() projection on key field and group by foreign primary key | <p>I'm having difficulty representing this query (which works on the database directly) as a criteria query in Hibernate (version 3.2.5):</p>
<pre><code>SELECT s.*
FROM ftp_status s
WHERE (s.datetime,s.connectionid) IN (SELECT MAX(f.datetime),
f.connectionid
FROM ftp_status f
GROUP BY f.connectionid);
</code></pre>
<p>so far this is what I've come up with that doesn't work, and throws a <code>could not resolve property: datetime of: common.entity.FtpStatus</code> error message:</p>
<pre><code>Criteria crit = s.createCriteria(FtpStatus.class);
crit = crit.createAlias("connections", "c");
crit = crit.createAlias("id", "f");
ProjectionList proj = Projections.projectionList();
proj = proj.add(Projections.max("f.datetime"));
proj = proj.add(Projections.groupProperty("c.connectionid"));
crit = crit.setProjection(proj);
List<FtpStatus> dtlList = crit.list();
</code></pre>
<p>Here's the relevant reference configuration that Netbeans 6.8 generated directly from the database:</p>
<p>FtpStatus.hbm.xml - </p>
<pre><code><hibernate-mapping>
<class name="common.entity.FtpStatus" table="ftp_status" catalog="common">
<composite-id name="id" class="common.entity.FtpStatusId">
<key-property name="siteid" type="int">
<column name="siteid" />
</key-property>
<key-property name="connectionid" type="int">
<column name="connectionid" />
</key-property>
<key-property name="datetime" type="timestamp">
<column name="datetime" length="19" />
</key-property>
</composite-id>
<many-to-one name="connections" class="common.entity.Connections" update="false" insert="false" fetch="select">
<column name="connectionid" not-null="true" />
</many-to-one>
<many-to-one name="sites" class="common.entity.Sites" update="false" insert="false" fetch="select">
<column name="siteid" not-null="true" />
</many-to-one>
<property name="upInd" type="boolean">
<column name="up_ind" not-null="true" />
</property>
<property name="lastMessage" type="string">
<column name="last_message" length="65535" not-null="true" />
</property>
</class>
</hibernate-mapping>
</code></pre>
<p>Connections.hbm.xml - </p>
<pre><code><hibernate-mapping>
<class name="common.entity.Connections" table="connections" catalog="common">
<id name="connectionid" type="java.lang.Integer">
<column name="connectionid" />
<generator class="identity" />
</id>
<property name="ip" type="string">
<column name="ip" length="15" not-null="true" />
</property>
<property name="port" type="int">
<column name="port" not-null="true" />
</property>
<property name="user" type="string">
<column name="user" length="8" not-null="true" />
</property>
<property name="password" type="string">
<column name="password" length="50" not-null="true" />
</property>
<set name="ftpStatuses" inverse="true">
<key>
<column name="connectionid" not-null="true" />
</key>
<one-to-many class="common.entity.FtpStatus" />
</set>
</class>
</hibernate-mapping>
</code></pre>
<p>I know I'm missing something, but my googling on hibernate hasn't revealed it yet. Alternatively a SQL query directly using <code>s.createSQLQuery()</code> or <code>s.createQuery()</code> is also acceptable, but I've had even less success writing that one..... </p> | 8,358,721 | 1 | 0 | null | 2010-04-27 18:15:24.053 UTC | 1 | 2017-11-08 14:40:18.737 UTC | 2010-04-27 19:38:20.387 UTC | null | 231,627 | null | 231,627 | null | 1 | 7 | hibernate|group-by|projection|foreign-keys|many-to-one | 49,471 | <p>The <code>Criteria</code> you supplied seems to generate only the inner query part. You can combine the inner query e.g. by using <code>DetachedCriteria</code>:</p>
<pre><code>DetachedCriteria maxDateQuery = DetachedCriteria.forClass(FtpStatus.class);
ProjectionList proj = Projections.projectionList();
proj.add(Projections.max("datetime"));
proj.add(Projections.groupProperty("connectionid"));
maxDateQuery.setProjection(proj);
Criteria crit = s.createCriteria(FtpStatus.class);
crit.add(Subqueries.propertiesEq(new String[] {"datetime", "connectionid"}, maxDateQuery));
List<FtpStatus> dtlList = crit.list();
</code></pre>
<p>Note that support for multicolumn subqueries is not implemented until in <a href="https://hibernate.atlassian.net/browse/HHH-6766" rel="nofollow noreferrer">Hibernate 4.0.0.CR5 (HHH-6766)</a>.</p>
<p>As what comes to native SQL queries, Hibernate's <code>createSQLString</code> should work straight away with the query string you specified, or with the entities involved in the query added, if one want's to have explicit column names in the resulting query.</p>
<pre><code>String queryString = "SELECT {status.*}"
+ " FROM ftp_status status"
+ " WHERE (datetime, connectionid) IN ("
+ " SELECT MAX(datetime), connectionid"
+ " FROM ftp_status"
+ " GROUP BY connectionid"
+ " )";
SQLQuery query = s.createSQLQuery(queryString).addEntity("status", FtpStatus.class);
List<FtpStatus> dtlList = query.list();
</code></pre> |
46,478,708 | Angular reactive form hidden input not binding? | <p>I have a reactive form where I create the controls from my data model. Initially, everything is sorted by a datapoint called the "processingOrder" in numerical order.</p>
<p>Within my form array, I am using <code>*ngFor</code> to iterate over controls and store the index in a hidden <code>form control</code>. If I move a record up or down in my table, the index thats being applied to the hidden field should reflect the change in my model right?</p>
<pre><code><form [formGroup]="rulesForm" (ngSubmit)="onSubmit(form)">
<div formGroupName="ruleData">
<div formArrayName="rules">
<div *ngFor="let child of rulesForm.controls.ruleData.controls.rules.controls; let i = index">
<div formGroupName="{{i}}">
<input type="text" placeholder="Rule Name" formControlName="name"/> &nbsp;
<input type="text" placeholder="Rule Description" formControlName="description"/> &nbsp;
<input type="text" placeholder="Processing Order" formControlName="processingOrder"/> &nbsp;
<button class="button" (click)="move(-1, i)">Move Up</button> &nbsp;
<button class="button" (click)="move(1, i)">Move Down</button>
<!-- Why doesn't this update my model when it gets a new index? -->
<input type="hidden" formControlName="processingOrder" [value]="i">
</div>
</div>
</div>
</div>
<button type="submit">Submit</button>
</form>
</code></pre>
<p>I would have expected that in my plunker, the processing order numbers should always remain in the 1-5 order and each time a rule is moved up or down, the model is updated to the new index it received.</p>
<p><a href="https://plnkr.co/edit/ZCgHPEaUM00aLxM6Sf9t?p=preview" rel="noreferrer">https://plnkr.co/edit/ZCgHPEaUM00aLxM6Sf9t?p=preview</a></p> | 46,479,703 | 2 | 0 | null | 2017-09-28 21:38:34.6 UTC | 4 | 2021-10-04 20:00:11.637 UTC | null | null | null | null | 2,628,921 | null | 1 | 12 | angular | 44,859 | <p><a href="https://angular.io/api/forms/FormControlName" rel="noreferrer"><code>formControlName</code></a> directive has <a href="https://angular.io/api/forms/FormControlName#inputs" rel="noreferrer"><code>ngModel</code></a> input which is bound to control's model and when changed from the code will update all its instances on view. So, just replace <code>[value]="i"</code> with <code>[ngModel]="i + 1"</code>:</p>
<pre><code><input type="hidden" formControlName="processingOrder" [ngModel]="i + 1">
</code></pre>
<p>binding to HTML input's property <code>value</code> (<code>[value]="i + 1"</code>) will update current input on the view but won't update control's model, thus won't affect another instances with the same control name.</p>
<p>You also can remove hidden input and place <code>[value]="i + 1"</code> on the text input:</p>
<pre><code><input type="text"
placeholder="Processing Order"
[ngModel]="i + 1"
formControlName="processingOrder"/>
</code></pre>
<p>please note that <code>processingOrder</code> value will always be overridden by <code>ngFor</code>'s index <code>i</code></p>
<p><strong>2021 UPDATE :)</strong>
be aware of <code>ngModel</code> (with reactive form directives) <a href="https://angular.io/api/forms/FormControlName#use-with-ngmodel-is-deprecated" rel="noreferrer">deprecation</a> since NG6:</p>
<blockquote>
<p>Support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in Angular v6 and is scheduled for removal in a future version of Angular.</p>
</blockquote> |
50,766,461 | What's the difference between namedtuple and NamedTuple? | <p>The <a href="https://docs.python.org/3/library/typing.html#typing.NamedTuple" rel="noreferrer"><code>typing</code> module documentation</a> says that the two code snippets below are equivalent.</p>
<pre class="lang-py prettyprint-override"><code>from typing import NamedTuple
class Employee(NamedTuple):
name: str
id: int
</code></pre>
<p>and</p>
<pre class="lang-py prettyprint-override"><code>from collections import namedtuple
Employee = namedtuple('Employee', ['name', 'id'])
</code></pre>
<p>Are they the exact same thing or, if not, what are the differences between the two implementations?</p> | 50,767,206 | 1 | 0 | null | 2018-06-08 18:25:21.167 UTC | 8 | 2022-07-28 06:38:36.79 UTC | 2018-06-08 19:15:11.623 UTC | null | 7,386,332 | null | 1,452,488 | null | 1 | 83 | python|python-3.x | 9,480 | <p>The type generated by subclassing <code>typing.NamedTuple</code> is equivalent to a <code>collections.namedtuple</code>, but with <code>__annotations__</code>, <code>_field_types</code> and <code>_field_defaults</code> attributes added. The generated code will behave the same, for all practical purposes, since nothing in Python currently acts on those typing related attributes (your IDE might use them, though).</p>
<p>As a developer, using the <code>typing</code> module for your namedtuples allows a more natural declarative interface:</p>
<ul>
<li>You can easily specify default values for the fields (<em><strong>edit</strong>: in Python 3.7, <code>collections.namedtuple</code> <a href="https://docs.python.org/3/library/collections.html#collections.namedtuple" rel="nofollow noreferrer">got a new <code>defaults</code> keyword</a> so this is no longer an advantage</em>)</li>
<li>You don't need to repeat the type name twice ("Employee")</li>
<li>You can customize the type directly (e.g. adding a docstring or some methods)</li>
</ul>
<p>As before, your class will be a subclass of <code>tuple</code>, and instances will be instances of <code>tuple</code> as usual. Interestingly, your class will not be a subclass of <code>NamedTuple</code>. If you want to know why, read on for more info about the implementation detail.</p>
<pre><code>from typing import NamedTuple
class Employee(NamedTuple):
name: str
id: int
</code></pre>
<h3>Behaviour in Python <= 3.8</h3>
<pre><code>>>> issubclass(Employee, NamedTuple)
False
>>> isinstance(Employee(name='guido', id=1), NamedTuple)
False
</code></pre>
<p><code>typing.NamedTuple</code> is a class, it uses <a href="https://github.com/python/cpython/blob/301e3cc8a5bc68c5347ab6ac6f83428000d31ab2/Lib/typing.py#L1386" rel="nofollow noreferrer">metaclasses</a> and a custom <code>__new__</code> to handle the annotations, and then it <a href="https://github.com/python/cpython/blob/301e3cc8a5bc68c5347ab6ac6f83428000d31ab2/Lib/typing.py#L1336" rel="nofollow noreferrer">delegates to <code>collections.namedtuple</code> to build and return the type</a>. As you may have guessed from the lowercased name convention, <code>collections.namedtuple</code> is not a type/class - it's a factory function. It works by building up a string of Python source code, and then calling <a href="https://github.com/python/cpython/blob/301e3cc8a5bc68c5347ab6ac6f83428000d31ab2/Lib/collections/__init__.py#L397" rel="nofollow noreferrer"><code>exec</code></a> on this string. The <a href="https://github.com/python/cpython/blob/301e3cc8a5bc68c5347ab6ac6f83428000d31ab2/Lib/collections/__init__.py#L447" rel="nofollow noreferrer">generated constructor is plucked out of a namespace</a> and <a href="https://github.com/python/cpython/blob/301e3cc8a5bc68c5347ab6ac6f83428000d31ab2/Lib/collections/__init__.py#L464" rel="nofollow noreferrer">included in a 3-argument invocation of the metaclass <code>type</code></a> to build and return your class. This explains the weird inheritance breakage seen above, <code>NamedTuple</code> uses a metaclass in order to use a <em>different</em> metaclass to instantiate the class object.</p>
<h3>Behaviour in Python >= 3.9</h3>
<p><code>typing.NamedTuple</code> is changed from a type (<code>class</code>) to a function (<code>def</code>)</p>
<pre><code>>>> issubclass(Employee, NamedTuple)
TypeError: issubclass() arg 2 must be a class or tuple of classes
>>> isinstance(Employee(name="guido", id=1), NamedTuple)
TypeError: isinstance() arg 2 must be a type or tuple of types
</code></pre>
<p>Multiple inheritance using <code>NamedTuple</code> is now disallowed (it did not work properly in the first place).</p>
<p>See <a href="https://bugs.python.org/issue40185" rel="nofollow noreferrer">bpo40185</a> / <a href="https://github.com/python/cpython/pull/19371" rel="nofollow noreferrer">GH-19371</a> for the change.</p> |
38,665,741 | Why is EPPlus telling me that I "Can't set color when patterntype is not set" when I have set PatternType? | <p>I've got this code to try to style a header row: </p>
<pre><code>worksheet.Cells["A32:D32"].Style.Font.Name = "Georgia";
worksheet.Cells["A32:D32"].Style.Font.Bold = true;
worksheet.Cells["A32:D32"].Style.Font.Size = 16;
worksheet.Cells["A32:D32"].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells["A32:D33"].Style.Fill.BackgroundColor.SetColor(Color.CornflowerBlue);
</code></pre>
<p>It fails on the last line above with "<em>System.ArgumentException was unhandled. . .Message=Can't set color when patterntype is not set.
Source=EPPlus. . .</em>"</p>
<p>What could the real problem be? I <em>am</em> doing what it claimes I'm not, right?</p>
<p>For more context:</p>
<pre><code>worksheet.Cells["A32"].LoadFromCollection(bookDataList, true);
// style header row
worksheet.Cells["A32:D32"].Style.Font.Name = "Georgia";
worksheet.Cells["A32:D32"].Style.Font.Bold = true;
worksheet.Cells["A32:D32"].Style.Font.Size = 16;
worksheet.Cells["A32:D32"].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells["A32:D33"].Style.Fill.BackgroundColor.SetColor(Color.CornflowerBlue);
// style the rest
worksheet.Cells["A33:D59"].Style.Font.Name = "Candara";
worksheet.Cells["A33:D59"].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells["A33:D59"].Style.Fill.BackgroundColor.SetColor(Color.Cornsilk);
</code></pre>
<p>Note that I had the "style the rest" code prior to adding the "style header row" and did not run into this problem. The code is exactly the same as to setting PatternType and then BackgroundColor (except for the color used, and the range of cells the code is applied to).</p> | 38,702,798 | 1 | 1 | null | 2016-07-29 18:52:56.78 UTC | 2 | 2016-08-01 15:34:39.71 UTC | null | null | null | null | 875,317 | null | 1 | 29 | c#|excel|epplus|epplus-4 | 24,005 | <p>Look closely at the two lines:</p>
<pre><code>worksheet.Cells["A32:D32"].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells["A32:D33"].Style.Fill.BackgroundColor.SetColor(Color.CornflowerBlue);
</code></pre>
<p>The second line has <strong>D33</strong> instead of <strong>D32</strong> so if D33 is not set yet it would throw that error.</p> |
32,554,624 | Casting a number to a string in TypeScript | <p>Which is the the best way (if there is one) to cast from number to string in Typescript?</p>
<pre><code>var page_number:number = 3;
window.location.hash = page_number;
</code></pre>
<p>In this case the compiler throws the error:</p>
<blockquote>
<p>Type 'number' is not assignable to type 'string'</p>
</blockquote>
<p>Because <code>location.hash</code> is a string.</p>
<pre><code>window.location.hash = ""+page_number; //casting using "" literal
window.location.hash = String(number); //casting creating using the String() function
</code></pre>
<p>So which method is better?</p> | 32,607,656 | 7 | 0 | null | 2015-09-13 21:15:48.703 UTC | 21 | 2022-05-20 06:00:19.54 UTC | 2015-09-13 21:46:52.527 UTC | null | 419,956 | null | 1,316,510 | null | 1 | 248 | javascript|casting|typescript | 459,789 | <p>"Casting" is different than conversion. In this case, <code>window.location.hash</code> will auto-convert a number to a string. But to avoid a TypeScript compile error, you can do the string conversion yourself:</p>
<pre><code>window.location.hash = ""+page_number;
window.location.hash = String(page_number);
</code></pre>
<p>These conversions are ideal if you don't want an error to be thrown when <code>page_number</code> is <code>null</code> or <code>undefined</code>. Whereas <code>page_number.toString()</code> and <code>page_number.toLocaleString()</code> will throw when <code>page_number</code> is <code>null</code> or <code>undefined</code>.</p>
<p>When you only need to cast, not convert, this is how to cast to a string in TypeScript:</p>
<pre><code>window.location.hash = <string>page_number;
// or
window.location.hash = page_number as string;
</code></pre>
<p>The <code><string></code> or <code>as string</code> cast annotations tell the TypeScript compiler to treat <code>page_number</code> as a string at compile time; it doesn't convert at run time. </p>
<p>However, the compiler will complain that you can't assign a number to a string. You would have to first cast to <code><any></code>, then to <code><string></code>:</p>
<pre><code>window.location.hash = <string><any>page_number;
// or
window.location.hash = page_number as any as string;
</code></pre>
<p>So it's easier to just convert, which handles the type at run time and compile time:</p>
<pre><code>window.location.hash = String(page_number);
</code></pre>
<p>(Thanks to @RuslanPolutsygan for catching the string-number casting issue.)</p> |
5,716,804 | Can/Does WPF have multiple GUI threads? | <p>Can/Does WPF have multiple GUI threads? Or does it always only have one GUI thread (even if I have multiple windows/dialogs)?</p>
<p>I'm asking because I have events coming from other threads and I'd like to handle them in the GUI thread (because I need to modify the controls of my main window accordings to the events).</p>
<p>Btw: I know I need to use a <code>Dispatcher</code> object for this purpose. So, I could rephrase my question and ask: Is there always only one <code>Dispatcher</code> object for all GUI elements in WPF?</p> | 5,818,728 | 1 | 1 | null | 2011-04-19 13:06:32.697 UTC | 22 | 2012-06-30 02:15:24.72 UTC | 2012-06-30 02:15:24.72 UTC | null | 918,414 | null | 614,177 | null | 1 | 37 | .net|wpf|multithreading|user-interface | 16,626 | <p>Based on the link in the first answer I did some verification on my own. I'd like to share the results here. First of all:</p>
<p><strong>There can be multiple GUI threads (and therefor multiple <code>Dispatcher</code> instances).</strong></p>
<p>However:</p>
<p><strong>Simply creating a new window (modal or not) <em>does not</em> create a new GUI thread.</strong> One needs to create the thread explicitly (by creating a new instance of <code>Thread</code>). </p>
<p><em>Note:</em> Instead of using separate threads, modal dialogs are likely being realized by using <a href="http://msdn.microsoft.com/library/system.windows.threading.dispatcher.pushframe.aspx" rel="noreferrer">Dispatcher.PushFrame()</a> which blocks the caller of this method while still allowing events to be dispatched.</p>
<p>I've created a simple WPF class (again, based on the link from the first answer) to verify all this stuff. I share it here so you can play around with it a little bit.</p>
<p>MainWindow.xaml:</p>
<pre><code><Window x:Class="WindowThreadingTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="250" Height="130">
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Thread's ID is "/>
<TextBlock x:Name="m_threadId"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Thread's threading apartment is "/>
<TextBlock x:Name="m_threadTA"/>
</StackPanel>
<Button Click="OnCreateNewWindow" Content="Open New Window"/>
<Button Click="OnAccessTest" Content="Access Test"/>
</StackPanel>
</Window>
</code></pre>
<p>MainWindow.xaml.cs:</p>
<pre><code>using System;
using System.Threading;
using System.Windows;
using System.Windows.Media;
namespace WindowThreadingTest {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
private static uint s_windowNumber = 0;
private readonly MainWindow m_prevWindow;
public MainWindow() : this(null) { }
public MainWindow(MainWindow prevWindow) {
InitializeComponent();
this.m_prevWindow = prevWindow;
this.Title = String.Format("Window {0}", ++s_windowNumber);
Thread thread = Thread.CurrentThread;
this.m_threadId.Text = thread.ManagedThreadId.ToString();
this.m_threadTA.Text = thread.GetApartmentState().ToString();
}
private void OnCreateNewWindow(object sender, RoutedEventArgs e) {
CreateNewWindow(true, false, true);
}
private void CreateNewWindow(bool newThread, bool modal, bool showInTaskbar) {
MainWindow mw = this;
if (newThread) {
Thread thread = new Thread(() => {
MainWindow w = new MainWindow(this);
w.ShowInTaskbar = showInTaskbar;
if (modal) {
// ShowDialog automatically starts the event queue for the new windows in the new thread. The window isn't
// modal though.
w.ShowDialog();
} else {
w.Show();
w.Closed += (sender2, e2) => w.Dispatcher.InvokeShutdown();
System.Windows.Threading.Dispatcher.Run();
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
} else {
MainWindow w = new MainWindow(this);
w.ShowInTaskbar = showInTaskbar;
if (modal) {
// Even modal dialogs run in the same thread.
w.ShowDialog();
} else {
w.Show();
}
}
}
private void OnAccessTest(object sender, RoutedEventArgs e) {
if (m_prevWindow == null) {
return;
}
this.Background = Brushes.Lavender;
try {
m_prevWindow.Background = Brushes.LightBlue;
} catch (InvalidOperationException excpt) {
MessageBox.Show("Exception: " + excpt.Message, "Invalid Operation");
}
m_prevWindow.Dispatcher.Invoke((Action)(() => m_prevWindow.Background = Brushes.Green));
this.Dispatcher.Invoke((Action)(() => {
try {
m_prevWindow.Background = Brushes.Red;
} catch (InvalidOperationException excpt) {
MessageBox.Show("Exception: " + excpt.Message, "Invalid Dispatcher Operation");
}
}));
}
}
}
</code></pre> |
25,078,452 | How to send data using redirect with Laravel | <p>I developed an API to show a pop up message when the page loaded.</p>
<p>Not all the pages use the pop up API. For example, if the user go to the <code>show($id)</code> page, that doesn't required the pop up api to fire. but in some special cases, I need the pop up to be fired.</p>
<p>Here is my code, ** this code is just to illustrate my point, not an actual working code**</p>
<pre><code>public function store(){
validating the input
saving them
$id = get the id
return Redirect::route('clients.show, $id')
}
</code></pre>
<p>and in the show function I do this:</p>
<pre><code>public function show($id){
$client =Client::find($id)
return View::make('clients.profife')->with(array(
'data' => $client
))
</code></pre>
<h3>My question</h3>
<p>Is there a way so I can send a data from the <code>store</code> function to the <code>show</code> function <strong>using Redirect::route</strong> ? and then in the <code>show</code> function, I check if this <code>show</code> function, I check if this data has been sent of what and then I decide whether to fire the pop up api or not.</p>
<p>}</p> | 25,078,560 | 4 | 0 | null | 2014-08-01 10:41:48.74 UTC | 7 | 2022-02-25 11:19:05.78 UTC | 2017-11-29 13:58:51.757 UTC | null | 199,700 | null | 3,802,174 | null | 1 | 39 | php|laravel|laravel-4|laravel-blade | 109,112 | <p>In store()</p>
<pre><code>return Redirect::route('clients.show, $id')->with( ['data' => $data] );
</code></pre>
<p>and in <code>show()</code> read it with </p>
<pre><code>Session::get('data');
</code></pre> |
25,409,175 | Declare a Range relative to the Active Cell with VBA | <p>I need to declare a range object relative to the Active Cell. The problem is, the number of rows and columns I want to select is different each time the macro runs.</p>
<p>For example, I have two variables: <code>numRows</code> and <code>numCols</code>.</p>
<p>I want to select a range that has the ActiveCell in the upper-left corner hand has the cell with row ActiveCell.Row + NumRows and column ActiveCell.Column + NumCols in the bottom right (and then I intend to copy this data to an array to speed up my macro).</p>
<p>Any suggestions on how to do this?</p> | 25,409,205 | 2 | 0 | null | 2014-08-20 15:50:51.483 UTC | 2 | 2019-10-27 07:30:30.713 UTC | 2015-01-30 14:29:30.763 UTC | null | 1,505,120 | null | 3,960,972 | null | 1 | 10 | vba|excel | 109,371 | <p>There is an <a href="http://msdn.microsoft.com/en-us/library/office/ff840060(v=office.15).aspx" rel="noreferrer"><strong>.Offset</strong> property</a> on a Range class which allows you to do just what you need</p>
<p><code>ActiveCell.Offset(numRows, numCols)</code></p>
<p>follow up on a comment:</p>
<pre><code>Dim newRange as Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))
</code></pre>
<p>and you can verify by <code>MsgBox newRange.Address</code></p>
<p>and <a href="https://stackoverflow.com/questions/18481330/2-dimensional-array-from-range/18481730#18481730">here's how to assign this range to an array</a></p> |
30,291,607 | Get Javascript console when emulating WebView app | <p>I'm pretty new to Android Dev, I'm trying to create a WebView based app. I got the basics, I emulate the app directly on my phone and wanted to know if there is a way to get a <code>Javascript console</code> like in Chrome PC version.</p>
<p>My device is running Android 4.2.1 API Level 17. I can't emulate app on my computer, it doesn't work.</p>
<p>I've already watched <a href="https://stackoverflow.com/questions/2314886/how-can-i-debug-javascript-on-android">this topic on Stackoverflow</a>, but hasn't helped me.</p>
<p>So, what I tried (examples from the Stackoverflow topic) :</p>
<ul>
<li><p>Remote debugging from my device to my computer : I can't cause my device is running Android 4.2.1 and need, at least, Android 4.4+.</p></li>
<li><p>JavaScript Console : I can't access and didn't implemented a browser bar into my WebView app (and don't want to implement one...)</p></li>
<li><p>Original Answer : I put some <code>console.log('test')</code> and <code>console.error('test')</code> on a <code>window.onload function</code> to see if I can find them on the <code>logcat</code> and <code>ADB logs</code> but I can't find them, even if I put <code>adb logcat</code> to search them.</p></li>
</ul>
<p>Can someone help me? I really don't know how to get a console, and really need it...</p>
<p>Thanks!</p> | 30,294,054 | 1 | 0 | null | 2015-05-17 20:07:14.657 UTC | 3 | 2015-05-18 01:55:55.55 UTC | 2017-05-23 11:47:21.15 UTC | null | -1 | null | 3,669,565 | null | 1 | 35 | android|webview | 24,425 | <p>The answer you a referring to is for Android Browser app, not for WebView component.</p>
<p>In order to get output from <code>console.log()</code> family of functions, you need to set a <code>WebChromeClient</code> for your WebView and override <code>onConsoleMessage()</code> <a href="http://developer.android.com/reference/android/webkit/WebChromeClient.html#onConsoleMessage(android.webkit.ConsoleMessage)" rel="noreferrer">(doc)</a> method, like this:</p>
<pre><code>webView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
android.util.Log.d("WebView", consoleMessage.message());
return true;
}
});
</code></pre> |
57,043,414 | How to update Formik Field from external actions | <p>I am trying to update a Formik field from a modal screen. The modal returns the data and set them into the pageState. Considering that my Fomik Form has "enableReinitialize", the field update works fine.
However, if the form is in "dirty" state, which means, some other fields in the form were updated, this process to update a field does not work anymore. The field itself is a readonly field and the only way to the user populate the data is clicking on a button and selecting the data from the Modal.</p>
<p>Does anybody knows a workaround to this issue?</p>
<p>React 16.8.6
Formik 1.5.8</p>
<p>A summary of my form:</p>
<pre><code><Formik
enableReinitialize={true}
initialValues={props.quoteData}
validationSchema={QuoteFormSchema}
onSubmit={values => {
props.onSubmit(values);
}}
>
{({ values, setFieldValue }) => (
<Label for='customerName'>Customer:</Label>
<Field
type='text'
name='customerName'
id='customerName'
value={values.customerName}
onClick={props.showCustomerModal}
onChange={e => {
setFieldValue('customerName', e.target.value);
}}
component={customInputFormModal}
/>
</code></pre>
<p>I need to update the Formik field as soon as a new data is selected from the modal. Even if the form is dirty or not.</p>
<p>I also tried on ComponentDidUpdate() to set the data from the state directly to the field. However, the Formik state (using tags) does not show any changes...</p>
<p>Also, I tried: </p>
<p>1) to use OnChange + setValue. However, it seems to work only from the user input (having the field enabled and allowing the user type some data). Setting data direct in the field does not work.</p>
<p>2) Formik-effect. However without any success.</p> | 57,045,785 | 2 | 0 | null | 2019-07-15 15:59:11.673 UTC | 3 | 2021-12-19 11:23:19.81 UTC | 2019-07-15 16:05:18.067 UTC | null | 11,375,160 | null | 11,375,160 | null | 1 | 31 | formik | 37,346 | <p>I solved my problem rendering my modal component inside my Fomik functional component. And then, for the callBack of my modal component I just wrote a method that will receive the Formiks setFieldValue reference. Then was possible to manually set the data into Formik's state:</p>
<p>My Modal Component inside Formik's component:</p>
<pre><code><Formik
enableReinitialize={true}
initialValues={props.quoteData}
validationSchema={QuoteFormSchema}
onSubmit={values => {
props.onSubmit(values);
}}
>
{({ values, setFieldValue }) => (
<Form id='myForm'>
<CustomerPopup
showModal={showModal}
close={() => toggleCustomerModal()}
onSelect={data => onSelectCustomerHandler(data, setFieldValue)}
/>
</code></pre>
<p>My method to update Formik's state:</p>
<pre><code>// Handle Customer Selection from Modal Component
const onSelectCustomerHandler = (data, setFieldValue) => {
setFieldValue('customerName', data.name);
setFieldValue('customerId', data.id);
toggleCustomerModal();
};
</code></pre> |
42,779,871 | Angular core/feature/shared modules: what goes where | <p>First of all, it's not a duplicate of any other question and I've read the angular guide on that. However I still have several questions.</p>
<p>The feature module is the easiest one - you have a feature - group it into feature module. Let's say that in addition to obvious feature I have the pages which every application has:</p>
<ol>
<li>Main Landing page (not app.template.html but something which it renders first in its router-outlet)</li>
<li>Error pages, like 404</li>
<li>Contacts page, about us page</li>
</ol>
<p>I could probably move everything to feature module called 'static' but I don't like the name and also don't like grouping mostly unrelated things into the same module, i.e. error page and contact page. So, what is a pattern for mentioned pages?</p>
<p>Now, shared vs core module.
I have the following items:</p>
<ol>
<li>CsrfService (sounds like core one to me)</li>
<li>Logger (angular2-logger service)</li>
<li>HttpModule(core or shared?)</li>
<li>Logged-in-guard and AuthService (I have NavbarComponent/NavbarModule and LoginComponent using the AuthService), so are those a feature (login/auth) or are those a core/shared?</li>
</ol>
<p>So, the main question is how to choose decide for the items I listed and for new items like those.</p> | 42,781,220 | 1 | 0 | null | 2017-03-14 07:18:11.48 UTC | 24 | 2018-08-21 08:57:01.457 UTC | null | null | null | null | 2,728,956 | null | 1 | 38 | angular | 21,404 | <p>The answers to your question are subjective, however there are some recommendations from official docs you can follow: <a href="https://angular.io/guide/ngmodule-faq#what-kinds-of-modules-should-i-have-and-how-should-i-use-them" rel="noreferrer">What kinds of modules should I have and how should I use them?</a>. If you haven't read docs on <code>NgModule</code> and FAQ, I'd suggest spending a few hours studying them, things will be much clearer (at least they were for me :)</p>
<p>I'm using the following setup and it works quite well <strong><em>for me</em></strong>:</p>
<ul>
<li>app/<strong>shared</strong> - This is the module where I keep small stuff that every other module will need. I have 3 submodules there <code>directives</code>, <code>components</code> and <code>pipes</code>, just to keep things organized a little better. Examples: <code>filesize.pipe</code>, <code>click-outside.directive</code>, <code>offline-status.component</code>...</li>
<li>app/<strong>public</strong> - In this module I keep public routes and top-level components. Examples: <code>about.component</code>, <code>contact.component</code>, <code>app-toolbar.component</code></li>
<li>app/<strong>core</strong> - Services that app needs (and cannot work without) go here. Examples: <code>ui.service</code>, <code>auth.service</code>, <code>auth.guard</code>, <code>data.service</code>, <code>workers.service</code>....</li>
<li>app/<strong>protected</strong> - Similar to <strong>public</strong>, only for authorized users. This module has protected routes and top-level components. Examples: <code>user-profile.component</code>, <code>dashboard.component</code>, <code>dashboard-sidebar.component</code>...</li>
<li>app/<strong>features</strong> - This is the module where app functionalities are. They are organized in several submodules. If you app plays music, this is where <code>player</code>, <code>playlist</code>, <code>favorites</code> submodules would go. If you look at the <a href="https://github.com/angular/material2/tree/master/src/lib" rel="noreferrer"><code>@angular/material2</code></a> this would be an equivalent to their <code>MaterialModule</code> and many submodules, like <code>MdIconModule</code>, <code>MdSidenavModule</code> etc. </li>
<li>app/<strong>dev</strong> - I use this module when developing, don't ship it in production. </li>
</ul>
<p>General advice would be: </p>
<ul>
<li>organize features by functionality, not by pages</li>
<li>keep similar routes in their own module (good for lazy loading)</li>
<li>services that app needs to function go to <strong>core</strong></li>
<li>things you import more than once (or twice) are probably good for <strong>shared</strong></li>
<li>read docs in detail, lots of good stuff there</li>
</ul>
<p>To answer your specific questions: I would put all those routes in one module - <code>static</code>, <code>public</code>, whatever the name. <code>CsrfService</code> - core, <code>Logger</code> - core or dev, <code>HttpModule</code> - core, you only need one instance (probably), <code>auth</code> - core. Don't put services in shared.</p>
<p>If you can't decide how/what to group in a feature, make a new app, copy specific feature folder and it should work there as well. If it doesn't, you'll need to organize things better.</p> |
38,627,259 | How to make a callback to Google Maps init in separate files of a web app | <p>When I had my Google Maps API snippet:</p>
<pre class="lang-html prettyprint-override"><code><script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
</code></pre>
<p>in <code>index.html</code>, I got the error:</p>
<blockquote>
<p>Uncaught InvalidValueError: initMap is not a function</p>
</blockquote>
<p>I want to keep all of my <code>bower_component</code>, CSS, API, and script declarations in my <code>index.html</code> file on my Yeoman-scaffolded AngularJS web app. The map I was actually trying to recreate would be on another route, let's call it route "afterlogin", just a <a href="https://developers.google.com/maps/documentation/javascript/examples/map-simple" rel="nofollow noreferrer">basic map</a>. I separated the js and the html html components into <code>afterlogin.js</code> and <code>afterlogin.html</code></p>
<p>There are a number of potential causes for this. One of which was presented here as a matter of adjusting the call to match the namespace, <a href="https://stackoverflow.com/a/34466824/1923016">https://stackoverflow.com/a/34466824/1923016</a> . Would this require an angular service? If so, how would the service work into the <code>initMap</code> function and its call in the Google maps api snippet?</p>
<p>One of the complications is the order. I'm new to web app dev, but from what I can tell the <code>index.html</code> loads first, uses the url in the snippet to make the callback to the <code>initMap</code> function which is not featured in <code><script>...</script></code> in the <code>index.html</code> file nor in the <code>app.js</code> file. Instead, since the init function is in a route's js code, it cannot be seen, hence the need for some kind of "namespace" version of the call. This leads to a console error even from the login route, which is not even where the <code>div</code> for the map is.</p>
<p><strong>---- EDIT: ----</strong></p>
<p>Also note that in this case, this did not do the trick:</p>
<pre><code>window.initMap = function(){
//...
}
</code></pre>
<p>This also does not apply, as the function is never called: <a href="https://stackoverflow.com/questions/36795150/uncaught-invalidvalueerror-initmap-is-not-a-function">Uncaught InvalidValueError: initMap is not a function</a></p>
<p><strong>-- -- -- -- -- --</strong></p>
<p><strong>afterlogin.js</strong></p>
<pre><code>angular.module('myappproject').controller('AfterloginCtrl', function ($scope) {
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: {lat: -33.8666, lng: 151.1958}
});
var marker = new google.maps.Marker({
map: map,
// Define the place with a location, and a query string.
place: {
location: {lat: -33.8666, lng: 151.1958},
query: 'Google, Sydney, Australia'
},
// Attributions help users find your site again.
attribution: {
source: 'Google Maps JavaScript API',
webUrl: 'https://developers.google.com/maps/'
}
});
// Construct a new InfoWindow.
var infoWindow = new google.maps.InfoWindow({
content: 'Google Sydney'
});
// Opens the InfoWindow when marker is clicked.
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
}
});
</code></pre>
<p><strong>afterlogin.html</strong></p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>after login page</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>
</code></pre> | 38,627,705 | 3 | 5 | null | 2016-07-28 04:43:04.03 UTC | 4 | 2022-06-15 01:53:49.17 UTC | 2020-10-17 19:57:37.9 UTC | null | 863,110 | null | 1,923,016 | null | 1 | 11 | javascript|html|angularjs|google-maps|google-maps-api-3 | 44,960 | <p>Since the Google Maps SDK script load a synchronic (due the <code>async</code> attribute), there is the <code>callback</code> parameter in the URL.</p>
<p>To solve the problem, you need to understand the <code>async</code> mechanism in google sdk</p>
<blockquote>
<p>The async attribute lets the browser render the rest of your website while the Maps JavaScript API loads. When the API is ready, it will call the function specified using the callback parameter.</p>
</blockquote>
<p><sup><a href="https://developers.google.com/maps/documentation/javascript/tutorial#Loading_the_Maps_API" rel="noreferrer">https://developers.google.com/maps/documentation/javascript/tutorial#Loading_the_Maps_API</a></sup> </p>
<p>So the solution is to load the script synchronic:</p>
<blockquote>
<p>In the script tag that loads the Maps JavaScript API, it is possible to omit the async attribute and the callback parameter. This will cause the loading of the API to block until the API is downloaded.</p>
<p>This will probably slow your page load. But it means you can write subsequent script tags assuming that the API is already loaded.</p>
</blockquote>
<p><sup><a href="https://developers.google.com/maps/documentation/javascript/tutorial#sync" rel="noreferrer">https://developers.google.com/maps/documentation/javascript/tutorial#sync</a></sup></p>
<ol>
<li>You can remove the <code>async</code> attribute that way, the page will stop running until the script will complete downloaded and run on the page. So, when the browser will get to your code, all the SDK object will be available.</li>
<li>Now, since there is not code that calls to the <code>initMap</code> function (remember: who called it, it was the sdk script which call it only in the <code>async</code> mode), you need to call it by yourself. So, just call it in the end of the controller.</li>
</ol> |
26,108,214 | What does `Chef::Config[:file_cache_path]` do exactly? | <p>First off, I apologize for asking such a dumb question. But the reason I ask is because I'm having a hard time finding an answer. I've tried searching Chef's docs, but I have not found a clear explanation.</p>
<p>So what exactly does<code>Chef::Config[:file_cache_path]</code> provide? I've read that its better to use this instead of harding coding a filepath. But what does it evaluate to?</p>
<p>In this particular snippet</p>
<pre><code>newrelic_agent = Chef::Config[:file_cache_path] + '/rewrelic_nginx_agent.tar.gz'
remote_file newrelic_agent do
source 'http://nginx.com/download/newrelic/newrelic_nginx_agent.tar.gz'
mode "0744"
end
</code></pre>
<p>Thanks in advance.</p> | 26,108,265 | 1 | 0 | null | 2014-09-29 20:23:15.067 UTC | 6 | 2014-09-29 20:26:24.25 UTC | null | null | null | null | 2,177,668 | null | 1 | 29 | chef-infra | 26,290 | <p>The specific value varies by platform and method of install, but that config value defaults to somewhere you can write out temp files. Generally it will be something like <code>/var/chef/cache</code>. This is used for caching cookbooks and files in them, but as you noted you can also use it from your own code for the same kind of thing.</p> |
55,017,476 | Android/Kotlin: Error: "Expecting a top level declaration > Task :app:buildInfoGeneratorDebug" | <p>I try to write a class to manage a SQLite DB, but I have the error message "Expecting a top level declaration > Task :app:buildInfoGeneratorDebug".</p>
<pre><code> package com.xexxxwxxxxs.GMP
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.content.Context
import android.content.ContentValues
class DBHandler(context: Context, name: String?, factory: SQLiteDatabase.CursorFactory?, version: Int) : SQLiteOpenHelper(context, DATABASE_NAME, factory, DATABASE_VERSION)
{
override fun onCreate(db: SQLiteDatabase)
{
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int)
{
}
companion object
{
private val DATABASE_VERSION = 1
private val DATABASE_NAME = "GMP.db"
}
}
</code></pre>
<p>Do you have any ideas?</p>
<p>Thanks in advance</p> | 55,017,803 | 4 | 0 | null | 2019-03-06 07:09:19.163 UTC | 2 | 2022-07-02 19:13:52.65 UTC | null | null | null | null | 3,581,620 | null | 1 | 17 | android|sqlite|kotlin|companion-object | 49,101 | <p>I just delete the last curly brace and write it again. It's working :)</p> |
44,955,463 | Creating a promise chain in a for loop | <p>I would expect the code below to print one number on the console, then wait a second and then print another number. Instead, it prints all 10 numbers immediately and then waits ten seconds. What is the correct way to create a promise chain that behaves as described?</p>
<pre><code>function getProm(v) {
return new Promise(resolve => {
console.log(v);
resolve();
})
}
function Wait() {
return new Promise(r => setTimeout(r, 1000))
}
function createChain() {
let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
let chain = Promise.resolve();
for (let i of a) {
chain.then(()=>getProm(i))
.then(Wait)
}
return chain;
}
createChain();
</code></pre> | 44,955,506 | 3 | 0 | null | 2017-07-06 17:27:49.537 UTC | 11 | 2022-04-18 09:25:55.393 UTC | null | null | null | null | 8,266,512 | null | 1 | 35 | javascript|es6-promise | 17,089 | <p>You have to assign the return value of <code>.then</code> back to <code>chain</code>:</p>
<pre><code>chain = chain.then(()=>getProm(i))
.then(Wait)
</code></pre>
<p>Now you will basically be doing </p>
<pre><code>chain
.then(()=>getProm(1))
.then(Wait)
.then(()=>getProm(2))
.then(Wait)
.then(()=>getProm(3))
.then(Wait)
// ...
</code></pre>
<p>instead of </p>
<pre><code>chain
.then(()=>getProm(1))
.then(Wait)
chain
.then(()=>getProm(2))
.then(Wait)
chain
.then(()=>getProm(3))
.then(Wait)
// ...
</code></pre>
<p>You can see that the first one is actually a chain, while the second one is parallel.</p> |
38,836,690 | C++ function argument safety | <p>In a function that takes several arguments of the same type, how can we guarantee that the caller doesn't mess up the ordering?</p>
<p>For example</p>
<pre><code>void allocate_things(int num_buffers, int pages_per_buffer, int default_value ...
</code></pre>
<p>and later</p>
<pre><code>// uhmm.. lets see which was which uhh..
allocate_things(40,22,80,...
</code></pre> | 38,836,803 | 7 | 13 | null | 2016-08-08 19:03:04.65 UTC | 8 | 2016-08-30 21:47:12.9 UTC | 2016-08-08 19:37:59.03 UTC | null | 1,413,395 | null | 1,583,225 | null | 1 | 58 | c++|c++14 | 3,839 | <p>A typical solution is to put the parameters in a structure, with named fields.</p>
<pre><code>AllocateParams p;
p.num_buffers = 1;
p.pages_per_buffer = 10;
p.default_value = 93;
allocate_things(p);
</code></pre>
<p>You don't have to use fields, of course. You can use member functions or whatever you like.</p> |
2,366,921 | Reflection.Emit vs CodeDOM | <p><strong>What are some pros/cons for using the Reflection.Emit library versus CodeDOM for dynamically generating code at runtime?</strong></p>
<p>I am trying to generate some (relatively complicated) dynamic classes in a system based on metadata available at runtime in XML form. I will be generating classes that extend existing classes in the application assembly, implementing additional interfaces, adding methods, and overriding virtual and abstract members.</p>
<p>I want to make sure I select the appropriate technique before I get too deep into the implementation. Any information about how these different code-generation techniques differ would be helpful. Also, any information on open-source libraries that simplify or streamline working wither either API would be useful as well.</p> | 2,367,507 | 3 | 3 | null | 2010-03-02 21:29:16.427 UTC | 19 | 2013-04-12 12:58:30.817 UTC | null | null | null | null | 91,671 | null | 1 | 53 | c#|.net|code-generation|reflection.emit|codedom | 15,150 | <p>I think the key points about CodeDOM and Reflection.Emit are following:</p>
<ul>
<li><p><strong>CodeDom</strong> generates C# source code and is usually used when generating code to be included as part of a solution and compiled in the IDE (for example, LINQ to SQL classes, WSDL, XSD all work this way). In this scenario you can also use partial classes to customize the generated code. It is less efficient, because it generates C# source and then runs the compiler to parse it (again!) and compile it. You can generate code using relatively high-level constructs (similar to C# expressions & statements) such as loops.</p></li>
<li><p><strong>Reflection.Emit</strong> generates an IL so it directly produces an assembly that can be also stored only in memory. As a result is a lot more efficient.You have to generate low-level IL code (values are stored on stack; looping has to be implemented using jumps), so generating any more complicated logic is a bit difficult.</p></li>
</ul>
<p>In general, I think that Reflection.Emit is usually considered as the preferred way to generate code at runtime, while CodeDOM is preferred when generating code before compile-time. In your scenario, both of them would probably work fine (though CodeDOM may need higher-privileges, because it actually needs to invoke C# compiler, which is a part of any .NET installation).</p>
<p>Another option would be to use the <a href="http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression(VS.100).aspx" rel="noreferrer"><code>Expression</code> class</a>. In .NET 4.0 it allows you to generate code equivalent to C# expressions and statements. However, it doesn't allow you to generate a classes. So, you may be able to combine this with Reflection.Emit (to generate classes that delegate implementation to code generated using <code>Expression</code>). For some scenarios you also may not really need a full class hierarchy - often a dictionary of dynamically generated delegates such as <code>Dictionary<string, Action></code> could be good enough (but of course, it depends on your exact scenario).</p> |
2,421,388 | Using group by on multiple columns | <p>I understand the point of <code>GROUP BY x</code>.</p>
<p>But how does <code>GROUP BY x, y</code> work, and what does it mean?</p> | 2,421,441 | 3 | 1 | null | 2010-03-10 23:11:23.113 UTC | 401 | 2021-09-23 19:02:10.66 UTC | 2020-07-22 14:47:34.607 UTC | null | 8,528,014 | null | 117,700 | null | 1 | 1,411 | sql|group-by|multiple-columns | 1,847,201 | <p><code>Group By X</code> means <strong>put all those with the same value for X in the one group</strong>.</p>
<p><code>Group By X, Y</code> means <strong>put all those with the same values for both X and Y in the one group</strong>.</p>
<p>To illustrate using an example, let's say we have the following table, to do with who is attending what subject at a university:</p>
<pre><code>Table: Subject_Selection
+---------+----------+----------+
| Subject | Semester | Attendee |
+---------+----------+----------+
| ITB001 | 1 | John |
| ITB001 | 1 | Bob |
| ITB001 | 1 | Mickey |
| ITB001 | 2 | Jenny |
| ITB001 | 2 | James |
| MKB114 | 1 | John |
| MKB114 | 1 | Erica |
+---------+----------+----------+
</code></pre>
<p>When you use a <code>group by</code> on the subject column only; say:</p>
<pre><code>select Subject, Count(*)
from Subject_Selection
group by Subject
</code></pre>
<p>You will get something like:</p>
<pre><code>+---------+-------+
| Subject | Count |
+---------+-------+
| ITB001 | 5 |
| MKB114 | 2 |
+---------+-------+
</code></pre>
<p>...because there are 5 entries for ITB001, and 2 for MKB114</p>
<p>If we were to <code>group by</code> two columns:</p>
<pre><code>select Subject, Semester, Count(*)
from Subject_Selection
group by Subject, Semester
</code></pre>
<p>we would get this:</p>
<pre><code>+---------+----------+-------+
| Subject | Semester | Count |
+---------+----------+-------+
| ITB001 | 1 | 3 |
| ITB001 | 2 | 2 |
| MKB114 | 1 | 2 |
+---------+----------+-------+
</code></pre>
<p>This is because, when we group by two columns, it is saying <strong>"Group them so that all of those with the same Subject and Semester are in the same group, and then calculate all the aggregate functions</strong> (Count, Sum, Average, etc.) <strong>for each of those groups"</strong>. In this example, this is demonstrated by the fact that, when we count them, there are <strong>three</strong> people doing ITB001 in semester 1, and <strong>two</strong> doing it in semester 2. Both of the people doing MKB114 are in semester 1, so there is no row for semester 2 (no data fits into the group "MKB114, Semester 2")</p>
<p>Hopefully that makes sense.</p> |
2,462,170 | C#: Get IP Address from Domain Name? | <p>How can I get an IP address, given a domain name?
For example: <code>www.test.com</code> </p> | 2,462,183 | 4 | 2 | null | 2010-03-17 12:32:18.787 UTC | 4 | 2021-12-13 10:57:25.127 UTC | 2010-04-26 22:59:51.333 UTC | null | 164,901 | null | 283,405 | null | 1 | 36 | c#|ip-address | 37,153 | <p>You can use the <code>System.Net.Dns</code> class:</p>
<pre class="lang-csharp prettyprint-override"><code>Dns.GetHostAddresses("www.test.com");
</code></pre> |
28,988,627 | Pandas Correlation Groupby | <p>Assuming I have a dataframe similar to the below, how would I get the correlation between 2 specific columns and then group by the 'ID' column? I believe the Pandas 'corr' method finds the correlation between all columns. If possible I would also like to know how I could find the 'groupby' correlation using the .agg function (i.e. np.correlate).</p>
<p>What I have:</p>
<pre><code>ID Val1 Val2 OtherData OtherData
A 5 4 x x
A 4 5 x x
A 6 6 x x
B 4 1 x x
B 8 2 x x
B 7 9 x x
C 4 8 x x
C 5 5 x x
C 2 1 x x
</code></pre>
<p>What I need:</p>
<pre><code>ID Correlation_Val1_Val2
A 0.12
B 0.22
C 0.05
</code></pre> | 28,990,872 | 4 | 0 | null | 2015-03-11 14:00:43.383 UTC | 19 | 2022-07-14 19:27:58.623 UTC | 2022-05-05 23:13:55.973 UTC | null | 4,685,471 | null | 4,643,220 | null | 1 | 38 | python|pandas|group-by|correlation | 46,846 | <p>You pretty much figured out all the pieces, just need to combine them:</p>
<pre><code>>>> df.groupby('ID')[['Val1','Val2']].corr()
Val1 Val2
ID
A Val1 1.000000 0.500000
Val2 0.500000 1.000000
B Val1 1.000000 0.385727
Val2 0.385727 1.000000
</code></pre>
<p>In your case, printing out a 2x2 for each ID is excessively verbose. I don't see an option to print a scalar correlation instead of the whole matrix, but you can do something simple like this if you only have two variables:</p>
<pre><code>>>> df.groupby('ID')[['Val1','Val2']].corr().iloc[0::2,-1]
ID
A Val1 0.500000
B Val1 0.385727
</code></pre>
<h3>For the more general case of 3+ variables</h3>
<p>For 3 or more variables, it is not straightforward to create concise output but you could do something like this:</p>
<pre><code>groups = list('Val1', 'Val2', 'Val3', 'Val4')
df2 = pd.DataFrame()
for i in range( len(groups)-1):
df2 = df2.append( df.groupby('ID')[groups].corr().stack()
.loc[:,groups[i],groups[i+1]:].reset_index() )
df2.columns = ['ID', 'v1', 'v2', 'corr']
df2.set_index(['ID','v1','v2']).sort_index()
</code></pre>
<p>Note that if we didn't have the <code>groupby</code> element, it would be straightforward to use an upper or lower triangle function from numpy. But since that element is present, it is not so easy to produce concise output in a more elegant manner as far as I can tell.</p> |
49,142,401 | How to scroll without moving my cursor in Visual Studio Code from the Keyboard | <p>I used to be able to scroll in <code>Visual Studio 2015</code> using some keyboard shortcuts in Windows doing something like <kbd>ctrl</kbd><kbd>shift</kbd><kbd>down</kbd>. It would effectively behave like a line by line viewport bump that did not modify where my cursor was inserted at. This is much like how scrolling with a mouse wheel does not move the cursor except its achieved from the keyboard.</p>
<p>I can't figure out how to do this on Visual Studio Code on a Mac.</p> | 51,139,853 | 8 | 0 | null | 2018-03-07 00:50:33.747 UTC | 4 | 2022-03-07 08:06:14.617 UTC | null | null | null | null | 1,330,381 | null | 1 | 40 | visual-studio-code | 14,210 | <p>On my Mac <kbd>Ctrl</kbd>+<kbd>Page Up/Down </kbd> works similar to mouse scroll. This doesn't affect the cursor position. </p> |
49,007,357 | How to make the whole Card component clickable in Material UI using React JS? | <p>Im using <a href="https://material-ui-next.com/demos/cards/" rel="noreferrer">Material UI Next</a> in a React project. I have the Card component which has an image(Card Media) and text(Card Text) inside it. I also have a button underneath the text. My question is..how to make the whole card clickable? ie. Whether a user presses on the card text, or the card image or the button, it should trigger the onClick event which I call on the button.</p> | 49,014,926 | 10 | 0 | null | 2018-02-27 11:14:13.25 UTC | 20 | 2022-06-23 15:39:52.823 UTC | null | null | null | null | 5,898,523 | null | 1 | 45 | javascript|css|reactjs|material-design|material-ui | 84,729 | <blockquote>
<p><strong>Update for v3 — 29 of August 2018</strong></p>
<p>A specific <a href="https://material-ui.com/api/card-action-area/" rel="noreferrer"><em>CardActionArea</em> component</a> has been added to cover specifically this case in <strong>version 3.0.0 of Material UI</strong>.</p>
<p>Please use the following solution only if you are stuck with v1.</p>
</blockquote>
<p>What you probably want to achieve is a <a href="https://material.io/guidelines/components/cards.html#cards-actions" rel="noreferrer"><strong>Card Action</strong> (see specification)</a> on the top part of the card.</p>
<p>The Material Components for Web library has this as its <a href="https://material-components-web.appspot.com/card.html" rel="noreferrer">first usage example for the Card Component</a>.</p>
<p>You can easily reproduce that exact behaviour by composing MUI <code>Card*</code> components with the mighty <code>ButtonBase</code> component. <strong><em>A running example can be found <a href="https://codesandbox.io/s/q9wnzv7684" rel="noreferrer">here on CodeSandbox</a>: <a href="https://codesandbox.io/s/q9wnzv7684" rel="noreferrer">https://codesandbox.io/s/q9wnzv7684</a></em></strong>.</p>
<p>The relevant code is this:</p>
<pre><code>import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Typography from '@material-ui/core/Typography';
import ButtonBase from '@material-ui/core/ButtonBase';
const styles = {
cardAction: {
display: 'block',
textAlign: 'initial'
}
}
function MyCard(props) {
return (
<Card>
<ButtonBase
className={props.classes.cardAction}
onClick={event => { ... }}
>
<CardMedia ... />
<CardContent>...</CardContent>
</ButtonBase>
</Card>
);
}
export default withStyles(styles)(MyCard)
</code></pre>
<p>Also I <strong>strongly suggest</strong> to keep the <code>CardActions</code> component outside of the <code>ButtonBase</code>.</p> |
1,315,924 | jQuery - Calling a function inline | <p>I am trying to pass one variable to a jQuery function inline (i.e.: using an <code>onMouseOver="function();"</code> within the actual link (which is an area tag from an image map)).</p>
<p>The function is only being called if I place it before the <code>$(document).ready(function(){</code> line, but doing this is causing all sorts of problems with jQuery.</p>
<p>All I want is for a simple tag (such as <code><area shape="circle" coords="357,138,17" onMouseOver="change('5');" id="5" /></code> to launch a function that is contained within the normal jQuery body of code.</p>
<p>To illustrate the point, the following works:</p>
<pre><code><script type="text/javascript">
function myfunction(x) { alert(x); //Alerts 2
}
</script>
<img src="/shared_images/loading.gif" border="0" usemap="#Map">
<map name="Map"><area shape="rect" coords="171,115,516,227"
onMouseOver="myfunction('2')"></map>
</code></pre>
<p>But the following doesn't</p>
<pre><code><script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function myfunction(x) { alert(x); //Nothing happens
}
}
</script>
<img src="/shared_images/loading.gif" border="0" usemap="#Map">
<map name="Map"><area shape="rect" coords="171,115,516,227"
onMouseOver="myfunction('2')"></map>
</code></pre> | 1,315,934 | 2 | 0 | null | 2009-08-22 12:57:01.22 UTC | 1 | 2021-12-27 09:22:03.623 UTC | 2021-12-27 09:22:03.623 UTC | null | 4,370,109 | null | 160,793 | null | 1 | 6 | javascript|jquery|inline|jquery-events | 55,736 | <p>In your second example, you've declared <code>myfunction</code> <em>inside</em> the anonymous function you're passing to <code>.ready()</code>. That means <code>myfunction</code> is a local variable, which is only in scope inside that anonymous function, and you cannot call it from anywhere else.</p>
<p>There are two solutions.</p>
<p>First, you can declare it outside (before or after) the call to <code>.ready()</code>. This <em>should not</em> cause any interference with jQuery. If it does, something else is wrong (perhaps a simple syntax error?) that we'd welcome you to bring up in a StackOverflow question.</p>
<p>Second, you shouldn't be using <code>onMouseOver=""</code> to attach event handlers (as that mixes JavaScript with HTML), so let's do away with it entirely. Replace your JavaScript with this:</p>
<pre><code>$(document).ready(function() {
$("#that-area-down-there").mouseover(function() {
alert(2);
});
});
</code></pre>
<p>And your HTML with this:</p>
<pre><code><area shape="rect" coords="171,115,516,227" id="that-area-down-there" />
</code></pre>
<p>(Presumably you'll want to replace that <code>id</code> with something more meaningful in context, of course.)</p> |
710,596 | How do I backup a nexus repository manager | <p>The nexus book: <a href="http://www.sonatype.com/books/nexus-book/reference/" rel="noreferrer">http://www.sonatype.com/books/nexus-book/reference/</a>. Does not seem to spend any time on how one should go about backing up a nexus repository. If I am installing my snapshot and releases into this local repository, it seems that it would behoove me to back it up. However, I'm not really interested in backing up anything that can easily be downloaded from a remote repository. </p>
<p>Some google searches do not seem to reveal the canonical answer either, so perhaps for posterity it can be recorded here.</p>
<p>Thanks,
Nathan</p> | 711,198 | 2 | 0 | null | 2009-04-02 16:50:01.497 UTC | 14 | 2016-02-24 06:35:42.573 UTC | 2009-07-30 20:17:03.597 UTC | null | 123,582 | Nathan Feger | 8,563 | null | 1 | 25 | maven-2|backup|nexus | 12,254 | <p>When you install Nexus, you'll end up with two directories:</p>
<pre><code>nexus-webapp-1.3.1.1/
sonatype-work/
</code></pre>
<p>We've separated the application from the data and configuration. The Nexus application is in <code>nexus-webapp-1.3.1.1/</code> and the data and configuration is in <code>sonatype-work/nexus</code>. This was mainly done to facilitate easier upgrades, but it also has the side-effect of making it very easy to backup a Nexus installation.</p>
<p><strong>The Simple Answer</strong></p>
<p>Nexus doesn't store repositories in a database or do anything that would preclude a simple backup of the file system under <code>sonatype-work/nexus</code>. If you need to create a complete backup, just archive the contents of the <code>sonatype-work/nexus</code>. </p>
<p><strong>Better Answer</strong></p>
<p>If you want a more intelligent approach to backing up a Nexus installation, you will certainly want to backup everything under <code>sonatype-work/nexus/conf</code>, <code>sonatype-work/nexus/storage</code>, <code>sonatype-work/nexus/template-store</code>. If you want to backup the metadata and file attributes that Nexus keeps for proxy repository, backup <code>sonatype-work/nexus/proxy</code>, although this isn't required as the information about the proxy repository will be generated on-demand as attributes are requested. </p>
<p>You don't need to backup <code>sonatype-work/nexus/logs</code> and you don't need to backup the Lucene indexes in <code>sonatype-work/nexus/indexer</code>.</p>
<p><strong>Nexus Pro Answer</strong></p>
<p>There is a Nexus Professional plugin which can automate the process of creating a backup of the Nexus configuration data. This plugin is going to address the contents of the <code>sonatype-work/nexus/conf</code> directory. If you need to backup the <code>sonatype-work/nexus/storage</code> directory, you will need to configure some backup system to backup the contents of that filesystem. Once again, as with Nexus Open Source, there is currently no real benefit in backing up the contents of <code>sonatype-work/nexus/indexer</code> or <code>sonatype-work/nexus/logs</code>.</p>
<p><strong>Excluding Storage for Remote Repositories</strong></p>
<p>In your question you mention that you want to exclude the storage devoted to the local cache of a remote repository. If you are interested in doing this, you'll have to take a further level of granularity and just exclude the directories under <code>sonatype-work/nexus/storage</code> that correspond to the remote repositories.</p>
<p><strong>Do you need to shut Nexus down for a backup?</strong></p>
<p>Brian Fox told me no, the only real chance for file contention is going to be the files in the <code>indexer/</code> directory. You shouldn't have a problem backing up the sonatype-work filesystem with a running instance of Nexus.</p>
<p>BTW, thanks for the question, this answer will likely be incorporated into the next version of the Nexus book.</p> |
1,120,448 | Refresh environment variables for open VS solution | <p>Using visual studio 2008, I had a solution open and realized I need to install another program that the project I was working on used. I did this with visual studio open and attempted to debug the program, however the environment variables added by the program I installed were not visible. I could not get them to refresh until I exited VS and reloaded the solution. Is there a way to get visual studio to "refresh" its environment variable list without exiting and reloading the solution?</p>
<p>As an additional note, I did use <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="noreferrer">process explorer</a> to look at the environment variables for the application and could confirm that it was not aware of the environment variable I needed.</p> | 1,120,463 | 2 | 1 | null | 2009-07-13 16:12:35.35 UTC | 5 | 2009-07-13 16:14:51.43 UTC | null | null | null | null | 4,660 | null | 1 | 30 | visual-studio|visual-studio-2008 | 14,799 | <p>Nope. Environment variable changes on Windows only take effect for new processes. You'll have to exit Visual Studio and restart it.</p> |
162,497 | Spring MVC Form tags: Is there a standard way to add "No selection" item? | <p>There is a select dropdown and I want to add "No selection" item to the list which should give me 'null' when submitted.
I'm using SimpleFormController derived controller.</p>
<pre><code>protected Map referenceData(HttpServletRequest httpServletRequest, Object o, Errors errors) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("countryList", Arrays.asList(Country.values()));
return map;
}
</code></pre>
<p>And the jspx part is</p>
<pre class="lang-html prettyprint-override"><code><form:select path="country" items="${countryList}" title="country"/>
</code></pre>
<p>One possible solution seems to be in adding a null value to the beginning of the list and then using a custom PropertyEditor to display this 'null' as 'No selection'.
Is there a better solution?</p>
<p>@Edit: I have solved this with a custom validation annotation which checks if the selected value is "No Selection". Is there a more standard and easier solution?</p> | 171,260 | 2 | 0 | null | 2008-10-02 14:13:18.85 UTC | 4 | 2020-07-31 04:32:29.06 UTC | 2020-07-31 04:32:29.06 UTC | skaffman | 214,143 | Aleksey Kudryavtsev | 578 | null | 1 | 31 | java|forms|spring|spring-mvc | 16,118 | <p>One option:</p>
<pre class="lang-html prettyprint-override"><code><form:select path="country" title="country" >
<form:option value="">&nbsp;</form:option>
<form:options items="${countryList}" />
</form:select>
</code></pre> |
493,490 | Converting a string to a class name | <p>I have a string variable that represents the name of a custom class. Example: </p>
<pre><code>string s = "Customer";
</code></pre>
<p>I will need to create an arraylist of customers. So, the syntax needed is:</p>
<pre><code>List<Customer> cust = new ..
</code></pre>
<p>How do I convert the string s to be able to create this arraylist on runtime?</p> | 493,517 | 2 | 1 | null | 2009-01-29 21:21:18.373 UTC | 16 | 2021-05-02 19:22:02.507 UTC | 2015-01-06 12:16:51.903 UTC | Jon Skeet | 469,319 | Bob Smith | 58,348 | null | 1 | 51 | c#|.net | 91,214 | <p>Well, for one thing <code>ArrayList</code> isn't generic... did you mean <code>List<Customer></code>?</p>
<p>You can use <code>Type.GetType(string)</code> to get the <code>Type</code> object associated with a type by its name. If the assembly isn't either mscorlib or the currently executing type, you'll need to include the assembly name. Either way you'll need the namespace too.</p>
<p>Are you sure you really need a generic type? Generics mostly provide <em>compile-time</em> type safety, which clearly you won't have much of if you're finding the type at execution time. You <em>may</em> find it useful though...</p>
<pre><code>Type elementType = Type.GetType("FullyQualifiedName.Of.Customer");
Type listType = typeof(List<>).MakeGenericType(new Type[] { elementType });
object list = Activator.CreateInstance(listType);
</code></pre>
<p>If you need to <em>do</em> anything with that list, you may well need to do more generic reflection though... e.g. to call a generic method.</p> |
2,594,799 | C# float to decimal conversion | <p>Any smart way to convert a float like this:</p>
<pre><code>float f = 711989.98f;
</code></pre>
<p>into a decimal (or double) without losing precision?</p>
<p>I've tried:</p>
<pre><code>decimal d = (decimal)f;
decimal d1 = (decimal)(Math.Round(f,2));
decimal d2 = Convert.ToDecimal(f);
</code></pre> | 2,594,878 | 5 | 2 | null | 2010-04-07 18:12:13.37 UTC | 0 | 2022-07-26 03:14:03.497 UTC | 2017-03-01 02:48:48.347 UTC | null | 173,467 | null | 311,245 | null | 1 | 21 | c#|floating-point|precision | 69,770 | <p>It's too late, the 8th digit was lost in the compiler. The float type can store only 7 significant digits. You'll have to rewrite the code, assigning to double or decimal will of course solve the problem.</p> |
2,902,621 | Fetching custom Authorization header from incoming PHP request | <p>So I'm trying to parse an incoming request in PHP which has the following header set:</p>
<pre><code>Authorization: Custom Username
</code></pre>
<p>Simple question: how on earth do I get my hands on it? If it was <code>Authorization: Basic</code>, I could get the username from <code>$_SERVER["PHP_AUTH_USER"]</code>. If it was <code>X-Custom-Authorization: Username</code>, I could get the username from <code>$_SERVER["HTTP_X_CUSTOM_AUTHORIZATION"]</code>. But neither of these are set by a custom Authorization, <code>var_dump($_SERVER)</code> reveals no mention of the header (in particular, <code>AUTH_TYPE</code> is missing), and PHP5 functions like <code>get_headers()</code> only work on responses to outgoing requests. I'm running PHP 5 on Apache with an out-of-the box Ubuntu install.</p> | 2,902,713 | 5 | 0 | null | 2010-05-25 07:00:09.2 UTC | 18 | 2020-09-14 12:54:58.333 UTC | null | null | null | null | 218,340 | null | 1 | 45 | php|http-headers|authorization | 106,267 | <p>If you're only going to use Apache you might want to have a look at <a href="http://php.net/apache_request_headers" rel="noreferrer"><code>apache_request_headers()</code></a>.</p> |
2,378,069 | DDD with Grails | <p>I cannot find any info about doing <a href="http://domaindrivendesign.org/" rel="noreferrer">Domain Driven Design</a> (DDD) with Grails. </p>
<p>I'm looking for any best practices, experience notes or even open source projects that are good examples of DDD with Grails.</p> | 7,100,122 | 7 | 0 | 2010-04-06 15:08:02.523 UTC | 2010-03-04 09:25:16.82 UTC | 14 | 2012-01-10 16:49:53.307 UTC | 2010-03-06 09:55:36.727 UTC | null | 36,746 | null | 36,746 | null | 1 | 14 | grails|domain-driven-design | 4,873 | <p>Grails is <strong>par-excellence</strong> platform for implementing applications in Domain Driven Design style . At the center of Grails approach are Domain Classes that drive the whole development process. As you are probably guessing, the choice of word domain in Grails is not just a coincidence.</p>
<p>You start by defining your Domain Classes and then you can use Grails to do all heavy lifting in providing persistence and generating the GUI. It's worth noting that when the DDD book was written, it was before the Grails or other similar frameworks were created, so a lot of problematic dealt with in a book has to do with issues resolved or greatly reduced by the framework. </p>
<h1>Some of DDD concepts resolved by Grails</h1>
<p>I will use <a href="http://www.google.cl/url?sa=t&source=web&cd=1&ved=0CBsQFjAA&url=http://domaindrivendesign.org/sites/default/files/discussion/PatternSummariesUnderCreativeCommons.doc&ei=bThMTqrNB4iitgefocGYCg&usg=AFQjCNF5onwbylXKXK4flanjiad6bWCiHg" rel="noreferrer">DDD pattern summary</a> to address different DDD elements. (Quotes italicized in the text below).</p>
<h2>Domain Model</h2>
<p>Domain model is structured through Domain classes, Services, Repositories and other DDD Patterns. Let’s take a look at each of these in detail.</p>
<h2>Entities</h2>
<p><em>“When an object is distinguished by its identity, rather than its attributes, make this primary to its definition in the model”</em></p>
<p>These are Domain Classes in Grails. They come with persistence already resolved through GORM. Model can be finely tuned using the GORM DSL. Take a look at hasOne vs. belongsTo property. It can be used to define the lifecycle of entities and their relationships. belongsTo will result in cascading deletes to related entities and other will not. So, if you have a Car object, you can say that Motor “belongsTo” a Car and in that case Car is an Aggregate Root and Motor an aggregate. Note that am I talking here about lifecycle relationship between entities and not the persistence.</p>
<h2>Value Objects</h2>
<p><em>“When you care only about the attributes of an element of the model, classify it as a VALUE OBJECT. Make it express the meaning of the attributes it conveys and give it related functionality. Treat the VALUE OBJECT as immutable. Don’t give it any identity…”</em></p>
<p>In Grails, you can use <a href="http://grails.org/doc/latest/guide/5.%20Object%20Relational%20Mapping%20%28GORM%29.html#5.2.2Composition" rel="noreferrer">“embedded”</a> property in GORM field to manage a value object. Value object can be accessed only through an entity it belongs to, does not have its own ID and is mapped to same table as the entity it belongs to. Groovy also supports <a href="http://groovy.codehaus.org/Immutable+AST+Macro" rel="noreferrer">@Immutable</a> annotation but I am not sure how it plays with Grails.</p>
<h2>Services</h2>
<p><em>“When a significant process or transformation in the domain is not a natural responsibility of an ENTITY or VALUE OBJECT, add an operation to the model as a standalone interface declared as a SERVICE. Make the SERVICE stateless.”</em></p>
<p>Just like Entities, Services are natively supported in Grails. You place your Grails Service inside the services directory in your Grails project. Services come with following out of the box:</p>
<ul>
<li>Dependency Injection</li>
<li>Transaction Support</li>
<li>A simple mechanism for exposing services as web services, so that they can be accessed remotely.</li>
</ul>
<h2>Modules</h2>
<p><em>“Choose MODULES that tell the story of the system and contain a cohesive set of concepts. “</em></p>
<p>Grails <a href="http://www.grails.org/doc/latest/guide/12.%20Plug-ins.html" rel="noreferrer">plug-in</a> mechanism provides this and much more: a very simple way to install and create plugins, defines how application can override plugins etc.</p>
<h2>Aggregates</h2>
<p><em>“Cluster the ENTITIES and VALUE OBJECTS into AGGREGATES and define boundaries around each. Choose one ENTITY to be the root of each AGGREGATE, and control all access to the objects inside the boundary through the root. Allow external objects to hold references to the root only.”</em></p>
<p>I already mentioned some lifecycle control mechanisms. You can use Grails Services and language access control mechanism to enforce access control. You can have a Grails Service playing the role of DDD Repository that permits access to Aggregate Root only. While Controllers in Grails can access GORM operations on Entities directly, I'd argue that for better layered design, Controllers should be injected with services that delegate to GORM Active Record operations.</p>
<h2>Factories</h2>
<p><em>“Shift the responsibility for creating instances of complex objects and AGGREGATES to a separate object, which may itself have no responsibility in the domain model but is still part of the domain design.”</em></p>
<p><a href="http://groovy.codehaus.org/Builders" rel="noreferrer">Groovy builders</a> are excellent alternative for constructing complex objects through rich DSL. In DDD, Factories are more loose term and does not translate directly to <a href="http://en.wikipedia.org/wiki/Design_Patterns" rel="noreferrer">GoF</a> Abstract Factory or Factory Method. Groovy builders are DSL implementation of GoF Builder pattern.</p>
<h2>Repositories</h2>
<p><em>“For each type of object that needs global access, create an object that can provide the illusion of an in-memory collection of all objects of that type. Set up access through a well-known global interface. Provide methods to add and remove objects, which will encapsulate the actual insertion or removal of data in the data store. Provide methods that select objects based on some criteria and return fully instantiated objects or collections of objects whose attribute values meet the criteria, thereby encapsulating the actual storage and query technology. Provide repositories only for AGGREGATE roots that actually need direct access. Keep the client focused on the model, delegating all object storage and access to the REPOSITORIES.”</em></p>
<p>Grails Service can be used to implement a dedicated Repository object that simply delegates its operation to Grails GORM. Persistence is resolved with GORM magic. Each Domain class provides a set of dynamic methods that resolve typical CRUD operations including ad-hock querying.</p>
<h2>Assertions</h2>
<p><em>“State post-conditions of operations and invariants of classes and AGGREGATES. If ASSERTIONS cannot be coded directly in your programming language, write automated unit tests for them.”</em></p>
<ul>
<li>Take a look at Groovy <a href="https://github.com/andresteingress/gcontracts/wiki/" rel="noreferrer">@Invariant, @Requires, @Ensures</a> annotations, these can be used to declare DbC style Invariants and Pre and Postconditions</li>
<li>When you create your domain classes with Grails command line, test classes are created automatically and these are another mechanism for expressing assertions in your domain.</li>
</ul>
<h2>Declarative Style of Design</h2>
<p><em>“A supple design can make it possible for the client code to use a declarative style of design. To illustrate, the next section will bring together some of the patterns in this chapter to make the SPECIFICATION more supple and declarative.”</em></p>
<p>This is where Grails excels because of dynamic nature of Groovy language and Builder pattern support for creating custom DSLs.</p>
<h2>Layered Architecture</h2>
<p>Comes “out-of-the-box” with Grails through proposed “<a href="http://www.grails.org/doc/latest/guide/2.%20Getting%20Started.html#2.6%20Convention%20over%20Configuration" rel="noreferrer">Convention over Configuration</a>” application structure in a form of a layered MVC based implementation.</p> |
2,589,736 | fast way to check if an array of chars is zero | <p>I have an array of bytes, in memory. What's the fastest way to see if all the bytes in the array are zero?</p> | 2,589,876 | 7 | 1 | null | 2010-04-07 02:59:47.62 UTC | 10 | 2018-02-12 12:53:11.47 UTC | null | null | null | null | 15,055 | null | 1 | 21 | c|optimization|memory|performance|32-bit | 33,673 | <p>Nowadays, <strong>short of using <a href="http://en.wikipedia.org/wiki/SIMD" rel="noreferrer">SIMD</a> extensions</strong> (such as <a href="http://en.wikipedia.org/wiki/Streaming_SIMD_Extensions" rel="noreferrer">SSE</a> on x86 processors), you might as well <strong>iterate over the array</strong> and compare each value to 0.</p>
<p><strong>In the distant past</strong>, performing a comparison and conditional branch for each element in the array (in addition to the loop branch itself) would have been deemed expensive and, depending on how often (or early) you could expect a non-zero element to appear in the array, you might have elected to completely <strong>do without conditionals inside the loop</strong>, using solely bitwise-or to detect any set bits and deferring the actual check until after the loop completes:</p>
<pre><code>int sum = 0;
for (i = 0; i < ARRAY_SIZE; ++i) {
sum |= array[i];
}
if (sum != 0) {
printf("At least one array element is non-zero\n");
}
</code></pre>
<p>However, with today's pipelined super-scalar processor designs complete with <a href="http://en.wikipedia.org/wiki/Branch_prediction" rel="noreferrer">branch prediction</a>, all non-SSE approaches are virtualy indistinguishable within a loop. If anything, comparing each element to zero and breaking out of the loop early (as soon as the first non-zero element is encountered) could be, in the long run, more efficient than the <code>sum |= array[i]</code> approach (which always traverses the entire array) unless, that is, you expect your array to be almost always made up exclusively of zeroes (in which case making the <code>sum |= array[i]</code> approach truly branchless by using GCC's <code>-funroll-loops</code> could give you the better numbers -- see the numbers below for an Athlon processor, <strong>results may vary with processor model and manufacturer</strong>.)</p>
<pre><code>#include <stdio.h>
int a[1024*1024];
/* Methods 1 & 2 are equivalent on x86 */
int main() {
int i, j, n;
# if defined METHOD3
int x;
# endif
for (i = 0; i < 100; ++i) {
# if defined METHOD3
x = 0;
# endif
for (j = 0, n = 0; j < sizeof(a)/sizeof(a[0]); ++j) {
# if defined METHOD1
if (a[j] != 0) { n = 1; }
# elif defined METHOD2
n |= (a[j] != 0);
# elif defined METHOD3
x |= a[j];
# endif
}
# if defined METHOD3
n = (x != 0);
# endif
printf("%d\n", n);
}
}
$ uname -mp
i686 athlon
$ gcc -g -O3 -DMETHOD1 test.c
$ time ./a.out
real 0m0.376s
user 0m0.373s
sys 0m0.003s
$ gcc -g -O3 -DMETHOD2 test.c
$ time ./a.out
real 0m0.377s
user 0m0.372s
sys 0m0.003s
$ gcc -g -O3 -DMETHOD3 test.c
$ time ./a.out
real 0m0.376s
user 0m0.373s
sys 0m0.003s
$ gcc -g -O3 -DMETHOD1 -funroll-loops test.c
$ time ./a.out
real 0m0.351s
user 0m0.348s
sys 0m0.003s
$ gcc -g -O3 -DMETHOD2 -funroll-loops test.c
$ time ./a.out
real 0m0.343s
user 0m0.340s
sys 0m0.003s
$ gcc -g -O3 -DMETHOD3 -funroll-loops test.c
$ time ./a.out
real 0m0.209s
user 0m0.206s
sys 0m0.003s
</code></pre> |
2,726,920 | C# XOR on two byte variables will not compile without a cast | <p>Why does the following raise a compile time error: 'Cannot implicitly convert type 'int' to 'byte':</p>
<pre><code> byte a = 25;
byte b = 60;
byte c = a ^ b;
</code></pre>
<p>This would make sense if I were using an arithmentic operator because the result of a + b could be larger than can be stored in a single byte.</p>
<p>However applying this to the XOR operator is pointless. XOR here it a bitwise operation that can never overflow a byte.</p>
<p>using a cast around both operands works:</p>
<pre><code>byte c = (byte)(a ^ b);
</code></pre> | 2,727,077 | 7 | 2 | null | 2010-04-28 04:57:09.487 UTC | 9 | 2022-06-20 08:21:38.763 UTC | null | null | null | null | 5,023 | null | 1 | 33 | c#|operators | 42,343 | <p>I can't give you the rationale, but I can tell why the compiler has that behavior from the stand point of the rules the compiler has to follow (which might not really be what you're interesting in knowing).</p>
<p>From an old copy of the C# spec (I should probably download a newer version), emphasis added:</p>
<blockquote>
<p>14.2.6.2 Binary numeric promotions This clause is informative. </p>
<p>Binary numeric promotion occurs for
the operands of the predefined <code>+</code>, <code>?</code>,
<code>*</code>, <code>/</code>, <code>%</code>, <code>&</code>, <code>|</code>, <code>^</code>, <code>==</code>, <code>!=</code>, <code>></code>, <code><</code>, <code>>=</code>, and <code><=</code> binary operators. Binary
numeric promotion implicitly converts
both operands to a common type which,
in case of the non-relational
operators, also becomes the result
type of the operation. Binary numeric
promotion consists of applying the
following rules, in the order they
appear here: </p>
<ul>
<li>If either operand is of type decimal, the other operand is
converted to type decimal, or a
compile-time error occurs if the other
operand is of type float or double. </li>
<li>Otherwise, if either operand is of type double, the other operand is
converted to type double. </li>
<li>Otherwise, if either operand is of type float, the other operand is
converted to type float. </li>
<li>Otherwise, if either operand is of type ulong, the other operand is
converted to type ulong, or a
compile-time error occurs if the other
operand is of type sbyte, short, int,
or long. </li>
<li>Otherwise, if either operand is of type long, the other operand is
converted to type long. </li>
<li>Otherwise, if either operand is of type uint and the other operand is of
type sbyte, short, or int, both
operands are converted to type long. </li>
<li>Otherwise, if either operand is of type uint, the other operand is
converted to type uint. </li>
<li>Otherwise, <strong>both operands are converted to type int</strong>.</li>
</ul>
</blockquote>
<p>So, basically operands smaller than an <code>int</code> will be converted to <code>int</code> for these operators (and the result will be an <code>int</code> for the non-relational ops).</p>
<p>I said that I couldn't give you a rationale; however, I will make a guess at one - I think that the designers of C# wanted to make sure that operations that might lose information if narrowed would need to have that narrowing operation made explicit by the programmer in the form of a cast. For example:</p>
<pre><code>byte a = 200;
byte b = 100;
byte c = a + b; // value would be truncated
</code></pre>
<p>While this kind of truncation wouldn't happen when performing an xor operation between two byte operands, I think that the language designers probably didn't want to have a more complex set of rules where some operations would need explicit casts and other not.</p>
<hr>
<p>Just a small note: the above quote is 'informational' not 'normative', but it covers all the cases in an easy to read form. Strictly speaking (in a normative sense), the reason the <code>^</code> operator behaves this way is because the closest overload for that operator when dealing with <code>byte</code> operands is (from 14.10.1 "Integer logical operators"):</p>
<pre><code>int operator ^(int x, int y);
</code></pre>
<p>Therefore, as the informative text explains, the operands are promoted to <code>int</code> and an <code>int</code> result is produced.</p> |
2,516,448 | strtolower() for unicode/multibyte strings | <p>I have some text in a non-English/foreign language in my page,
but when I try to make it lowercase, it characters are converted into black diamonds containing question marks.</p>
<pre><code>$a = "Երկիր Ավելացնել";
echo $b = strtolower($a);
//returns ����� ���������
</code></pre>
<p>I've set my charset in a metatag, but this didn't fix it.</p>
<pre><code><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</code></pre>
<p>What can I do to convert my string to lowercase without corrupting it?</p> | 2,516,460 | 8 | 3 | null | 2010-03-25 14:46:15.923 UTC | 3 | 2022-08-02 17:13:30.087 UTC | 2021-08-13 22:48:41.027 UTC | null | 2,943,403 | null | 291,772 | null | 1 | 34 | php|unicode|utf-8|lowercase|multibyte | 26,266 | <p>Have you tried using <a href="https://www.php.net/manual/en/function.mb-strtolower.php" rel="nofollow noreferrer"><code>mb_strtolower()</code></a>?</p> |
3,155,461 | How to delete multiple buffers in Vim? | <p>Assuming I have multiple files opened as buffers in Vim. The files have <code>*.cpp</code>, <code>*.h</code> and some are <code>*.xml</code>. I want to close all the XML files with <code>:bd *.xml</code>. However, Vim does not allow this (E93: More than one match...).</p>
<p>Is there any way to do this?</p>
<p>P.S. I know that <code>:bd file1 file2 file3</code> works. So can I somehow evaluate <code>*.xml</code> to <code>file1.xml file2.xml file3.xml</code>?</p> | 9,499,234 | 8 | 0 | null | 2010-07-01 06:16:06.51 UTC | 41 | 2017-09-17 04:11:39.99 UTC | 2013-01-23 14:56:31.783 UTC | null | 225,037 | null | 264,936 | null | 1 | 139 | vim|buffer | 22,008 | <p>You can use <code><C-a></code> to complete all matches. So if you type <code>:bd *.xml</code> and then hit <code><C-a></code>, vim will complete the command to <code>:bd file1.xml file2.xml file3.xml</code>.</p> |
2,890,773 | System.EnterpriseServices.Wrapper.dll error | <hr>
<blockquote>
<p>Parser Error Description: An error occurred during the parsing of a
resource required to service this request. Please review the following
specific parse error details and modify your source file
appropriately. </p>
<p>Parser Error Message: Could not load file or assembly
'System.EnterpriseServices.Wrapper.dll' or one of its dependencies.<br>
(Exception from HRESULT: 0x800700C1)</p>
<p>Source Error: </p>
<p>Line 1: <%@ Application Codebehind="Global.asax.cs"
Inherits="PMP.MvcApplication" Language="C#" %></p>
</blockquote>
<hr>
<p>Yesterday, I shut up my Windows 7, an Windows update was pending there without any process for nearly one hour, then I shut my laptop. When I re-opened my Windows 7 and ran the PMP MVC application, this error occurred. I finished that pending windows update. That did not fix the issue.</p>
<p>I googled to find that should re-install .net framework 1.1/2.1, I tried but nothing good happened. This error always here. I spent 4 hrs re-installing VS 2010, but it didn't resolve the issue.</p>
<p>How can I fix this issue?</p>
<p>[Update]:</p>
<p>I tried this,</p>
<pre><code>"C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\gacutil.exe" /i Microsoft.NET/Framework/v2.0.50727/System.EnterpriseServices.dll
"C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\gacutil.exe" /i Microsoft.NET/Framework/v2.0.50727/System.EnterpriseServices.dll
</code></pre>
<p>to found that <code>gacutil.exe</code> in v6.0A is 0kb. Then replace the file in <code>v7.0A</code> to <code>v6.0A</code>. This didn't solve the issue either.</p> | 3,672,702 | 10 | 0 | null | 2010-05-23 05:44:11.893 UTC | 3 | 2021-08-13 20:07:08.603 UTC | 2017-04-25 14:31:43.233 UTC | null | 2,622,612 | null | 343,117 | null | 1 | 15 | asp.net|global-asax | 40,480 | <p>Copy the file <code>System.EnterpriseServices.Wrapper.dll</code></p>
<p>from</p>
<p><code>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727</code></p>
<p>to</p>
<p><code>C:\WINDOWS\WinSxS\x86_System.EnterpriseServices_b03f5f7f11d50a3a_2.0.0.0_x-ww_7d5f3790\</code></p> |
2,504,411 | Proper indentation for multiline strings? | <p>What is the proper indentation for Python multiline strings within a function?</p>
<pre><code> def method():
string = """line one
line two
line three"""
</code></pre>
<p>or</p>
<pre><code> def method():
string = """line one
line two
line three"""
</code></pre>
<p>or something else?</p>
<p>It looks kind of weird to have the string hanging outside the function in the first example.</p> | 2,504,457 | 12 | 2 | null | 2010-03-23 23:35:28.27 UTC | 109 | 2022-03-23 21:31:28.533 UTC | 2021-12-31 22:53:12.843 UTC | null | 355,230 | null | 216,605 | null | 1 | 560 | python|string | 388,147 | <p>You probably want to line up with the <code>"""</code></p>
<pre><code>def foo():
string = """line one
line two
line three"""
</code></pre>
<p>Since the newlines and spaces are included in the string itself, you will have to postprocess it. If you don't want to do that and you have a whole lot of text, you might want to store it separately in a text file. If a text file does not work well for your application and you don't want to postprocess, I'd probably go with</p>
<pre><code>def foo():
string = ("this is an "
"implicitly joined "
"string")
</code></pre>
<p>If you want to postprocess a multiline string to trim out the parts you don't need, you should consider the <a href="http://docs.python.org/3/library/textwrap.html" rel="noreferrer"><code>textwrap</code></a> module or the technique for postprocessing docstrings presented in <a href="http://www.python.org/dev/peps/pep-0257/" rel="noreferrer">PEP 257</a>:</p>
<pre><code>def trim(docstring):
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = sys.maxint
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < sys.maxint:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return '\n'.join(trimmed)
</code></pre> |
2,897,619 | Using HTML5/JavaScript to generate and save a file | <p>I've been fiddling with WebGL lately, and have gotten a Collada reader working. Problem is it's pretty slow (Collada is a very verbose format), so I'm going to start converting files to a easier to use format (probably JSON). I already have the code to parse the file in JavaScript, so I may as well use it as my exporter too! The problem is saving.</p>
<p>Now, I know that I can parse the file, send the result to the server, and have the browser request the file back from the server as a download. But in reality the server has nothing to do with this particular process, so why get it involved? I already have the contents of the desired file in memory. Is there any way that I could present the user with a download using pure JavaScript? (I doubt it, but might as well ask...)</p>
<p>And to be clear: I am not trying to access the filesystem without the users knowledge! The user will provide a file (probably via drag and drop), the script will transform the file in memory, and the user will be prompted to download the result. All of which should be "safe" activities as far as the browser is concerned.</p>
<p><b>[EDIT]:</b> I didn't mention it upfront, so the posters who answered "Flash" are valid enough, but part of what I'm doing is an attempt to highlight what can be done with pure HTML5... so Flash is right out in my case. (Though it's a perfectly valid answer for anyone doing a "real" web app.) That being the case it looks like I'm out of luck unless I want to involve the server. Thanks anyway!</p> | 4,551,467 | 19 | 1 | null | 2010-05-24 14:16:34.777 UTC | 196 | 2022-04-04 22:24:29.68 UTC | 2019-04-21 16:18:51.16 UTC | null | 860,099 | null | 25,968 | null | 1 | 360 | javascript|html|download | 473,675 | <p>OK, creating a data:URI definitely does the trick for me, thanks to Matthew and Dennkster pointing that option out! Here is basically how I do it:</p>
<p>1) get all the content into a string called "content" (e.g. by creating it there initially or by reading innerHTML of the tag of an already built page).</p>
<p>2) Build the data URI:</p>
<pre><code>uriContent = "data:application/octet-stream," + encodeURIComponent(content);
</code></pre>
<p>There will be length limitations depending on browser type etc., but e.g. Firefox 3.6.12 works until at least 256k. Encoding in Base64 instead using encodeURIComponent might make things more efficient, but for me that was ok.</p>
<p>3) open a new window and "redirect" it to this URI prompts for a download location of my JavaScript generated page:</p>
<pre><code>newWindow = window.open(uriContent, 'neuesDokument');
</code></pre>
<p>That's it.</p> |
25,024,797 | Max and Min date in pandas groupby | <p>I have a dataframe that looks like:</p>
<pre><code>data = {'index': ['2014-06-22 10:46:00', '2014-06-24 19:52:00', '2014-06-25 17:02:00', '2014-06-25 17:55:00', '2014-07-02 11:36:00', '2014-07-06 12:40:00', '2014-07-05 12:46:00', '2014-07-27 15:12:00'],
'type': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'C'],
'sum_col': [1, 2, 3, 1, 1, 3, 2, 1]}
df = pd.DataFrame(data, columns=['index', 'type', 'sum_col'])
df['index'] = pd.to_datetime(df['index'])
df = df.set_index('index')
df['weekofyear'] = df.index.weekofyear
df['date'] = df.index.date
df['date'] = pd.to_datetime(df['date'])
type sum_col weekofyear date
index
2014-06-22 10:46:00 A 1 25 2014-06-22
2014-06-24 19:52:00 B 2 26 2014-06-24
2014-06-25 17:02:00 C 3 26 2014-06-25
2014-06-25 17:55:00 A 1 26 2014-06-25
2014-07-02 11:36:00 B 1 27 2014-07-02
2014-07-06 12:40:00 C 3 27 2014-07-06
2014-07-05 12:46:00 A 2 27 2014-07-05
2014-07-27 15:12:00 C 1 30 2014-07-27
</code></pre>
<p>I'm looking to groupby the weekofyear, then sum up the sum_col. In addition, I need to find the earliest, and the latest date for the week. The first part is pretty easy:</p>
<pre><code>gb = df.groupby(['type', 'weekofyear'])
gb['sum_col'].agg({'sum_col' : np.sum})
</code></pre>
<p>I've tried to find the min/max date with this, but haven't been successful:</p>
<pre><code>gb = df.groupby(['type', 'weekofyear'])
gb.agg({'sum_col' : np.sum,
'date' : np.min,
'date' : np.max})
</code></pre>
<p>How would one find the earliest/latest date that appears?</p> | 25,025,065 | 3 | 0 | null | 2014-07-29 20:52:45.057 UTC | 12 | 2022-06-17 14:22:09.283 UTC | null | null | null | null | 3,325,052 | null | 1 | 51 | python|pandas|dataframe | 97,255 | <p>You need to combine the functions that apply to the same column, like this:</p>
<pre><code>In [116]: gb.agg({'sum_col' : np.sum,
...: 'date' : [np.min, np.max]})
Out[116]:
date sum_col
amin amax sum
type weekofyear
A 25 2014-06-22 2014-06-22 1
26 2014-06-25 2014-06-25 1
27 2014-07-05 2014-07-05 2
B 26 2014-06-24 2014-06-24 2
27 2014-07-02 2014-07-02 1
C 26 2014-06-25 2014-06-25 3
27 2014-07-06 2014-07-06 3
30 2014-07-27 2014-07-27 1
</code></pre> |
45,721,213 | How to specify working directory for ENTRYPOINT in Dockerfile | <p>The Docker image (Windows-based) includes an application directory at <code>C:\App</code>. Inside that directory reside several sub-folders and files, including a batch file called <code>process.bat</code>. The Dockerfile (used to build the image) ends like this:</p>
<pre><code>ENTRYPOINT [ "C:\\App\\process.bat" ]
</code></pre>
<p>When I instantiate this image using the command: <code>docker run company/app</code>, the batch file runs, but it fails at the point where other files under <code>C:\App</code> are referenced. Essentially, the working directory is still <code>C:\</code> from the Docker container's entry-point.</p>
<p>Is there a way to set the working directory within the Dockerfile? Couple of alternatives do exist:</p>
<ul>
<li>Add <code>-w C:\App</code> to the docker run</li>
<li>In the batch file, I can add a line at the beginning <code>cd /D C:\App</code></li>
</ul>
<p>But is there a way to specify the working directory in the Dockerfile?</p> | 45,721,476 | 2 | 0 | null | 2017-08-16 19:07:43.99 UTC | 6 | 2018-02-12 10:44:14.957 UTC | null | null | null | null | 371,392 | null | 1 | 41 | docker|dockerfile | 61,351 | <p><code>WORKDIR /App</code> is a command you can use in your dockerfile to change the working directory.</p> |
45,379,121 | How to access elements on external website using Espresso | <p>Using espresso, we click a Login button which launches an external website (Chrome Custom Tab) where you can login and then it redirects back to our android application. </p>
<p>Is there a way in Espresso to:<br>
1) Verify the correct URL is being launched<br>
2) Access the elements on the website so that I can enter the login information and continue to login</p>
<p><a href="https://i.stack.imgur.com/GyFyH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GyFyH.png" alt="enter image description here"></a></p>
<p>When I try viewing it in the Espresso Launch Navigator, nothing shows up for the page, and if I try to record, it doesn't pick up on me entering anything on the page.</p>
<p>This is what I have so far (it is in Kotlin (not Java)):
<a href="https://i.stack.imgur.com/krt27.png" rel="noreferrer"><img src="https://i.stack.imgur.com/krt27.png" alt="enter image description here"></a></p>
<p>And here is the error that gets displayed:
<a href="https://i.stack.imgur.com/vTVVH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vTVVH.png" alt="enter image description here"></a></p>
<p>It launches my application, select the login button, opens the website but then it isn't able to access the elements. </p>
<p>I also tried:</p>
<p><a href="https://i.stack.imgur.com/WI0IH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WI0IH.png" alt="enter image description here"></a></p>
<p>Update: This is using Chrome Custom Tabs (not a Web View) so Espresso Web is not working. </p> | 45,467,933 | 2 | 1 | null | 2017-07-28 17:18:53.393 UTC | 8 | 2022-07-27 10:13:38.943 UTC | 2017-11-15 08:16:17.57 UTC | null | 1,000,551 | null | 4,713,905 | null | 1 | 11 | android|android-espresso|android-uiautomator|chrome-custom-tabs|android-espresso-recorder | 4,908 | <p>I was able to resolve this issue using both Espresso and UI Automator. You are able to combine the two. The selection of the login button I used Espresso (and the rest of the app, I will use Espresso). To handle the Chrome Custom tab for logging in, I used UIAutomator:</p>
<p><a href="https://i.stack.imgur.com/SSlPn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SSlPn.png" alt="enter image description here"></a></p> |
10,260,291 | Installing Core-Plot in Xcode 4.2 for iOS project | <p>I am trying to install Core Plot into my iOS app. I have followed the instructions on the Core Plot website but they are very brief and have no screenshots. I have pasted the instructions below and explained where I am stuck...</p>
<blockquote>
<p>First, drag the CorePlot-CocoaTouch.xcodeproj file into your iPhone
application's Xcode project. Show the project navigator in the
left-hand list and click on your project.</p>
<p>Select your application target from under the "Targets" source list
that appears. Click on the "Build Phases" tab and expand the "Target
Dependencies" group. Click on the plus button, select the
CorePlot-CocoaTouch library, and click Add. This should ensure that
the Core Plot library will be built with your application.</p>
</blockquote>
<p>Done!</p>
<blockquote>
<p>Core Plot is built as a static library for iPhone, so you'll need to
drag the libCorePlot-CocoaTouch.a static library from under the
CorePlot-CocoaTouch.xcodeproj group to the "Link Binaries With
Libraries" group within the application target's "Build Phases" group
you were just in.</p>
</blockquote>
<p>Done!</p>
<blockquote>
<p>You'll also need to point to the right header location. Under your
Build settings, set the Header Search Paths to the relative path from
your application to the framework/ subdirectory within the Core Plot
source tree. Make sure to make this header search path recursive. You
need to add -ObjC to Other Linker Flags as well (as of Xcode 4.2,
-all_load does not seem to be needed, but it may be required for older Xcode versions).</p>
</blockquote>
<p>I dont understand this bit!</p>
<blockquote>
<p>Core Plot is based on Core Animation, so if you haven't already, add
the QuartzCore framework to your application project.</p>
</blockquote>
<p>Done!</p>
<blockquote>
<p>Finally, you should be able to import all of the Core Plot classes and
data types by inserting the following line in the appropriate source
files within your project:</p>
<pre><code>#import "CorePlot-CocoaTouch.h"
</code></pre>
</blockquote>
<p>Done!</p>
<p>Is anyone able to put the instruction I am struggling with into more laymans terms?</p> | 10,261,140 | 2 | 0 | null | 2012-04-21 15:25:34.38 UTC | 9 | 2014-05-28 03:45:23.377 UTC | 2012-04-21 16:46:27.957 UTC | null | 19,679 | null | 1,190,768 | null | 1 | 10 | iphone|objective-c|ios|xcode4.2|core-plot | 7,259 | <p>Seeing as how I wrote those instructions, I can take a stab at clarifying the part you're having trouble with.</p>
<p>You'll need to set the header search path so that when you include <code>CorePlot-CocoaTouch.h</code>, Xcode knows where to pull that from. This is located within the Build Settings for your application project under the Header Search Paths build setting. It looks like the following:</p>
<p><img src="https://i.stack.imgur.com/e0YWZ.png" alt="Header search paths"></p>
<p>Double-click on the field for the header search paths and bring up this popup:</p>
<p><img src="https://i.stack.imgur.com/izjGE.png" alt="Header search paths popup"></p>
<p>The path you specify here is the relative path from your Xcode project file to the directory where you installed Core Plot. In my case, I had both my application project directory and Core Plot located within the same ~/Development directory, so the relative path involved stepping back a level (the <code>../</code>) and going to the <code>core-plot</code> directory that I had cloned the framework into. You then need to point to the <code>framework</code> subdirectory, where the actual framework source is stored.</p>
<p>Finally, checking the little box to the left of the path makes the header search recursive, so it will find headers contained in subdirectories of this one.</p>
<p>As far as the linker flags go, find your Other Linker Flags within these same Build Settings and add <code>-ObjC</code> to the list of linker flags:</p>
<p><img src="https://i.stack.imgur.com/0KutH.png" alt="ObjC linker flag"></p>
<p>This is needed so that symbols from the categories we use in the static library get pulled into your project properly. As I indicate, we used to need to add <code>-all_load</code> to this as well to work around a linker bug, but LLVM in Xcode 4.2 fixes this. That's good, because <code>-all_load</code> sometimes introduced duplicate symbols and broke building against certain third-party frameworks.</p>
<p>Hopefully, this should clear up that particular section of the instructions. I tried to do my best to make those easy to follow and keep them up to date with the latest Xcode versions, but perhaps I wasn't detailed enough. If you got through all the rest of the steps fine, you should be good to go.</p> |
19,537,645 | Get environment variable value in Dockerfile | <p>I'm building a container for a ruby app. My app's configuration is contained within environment variables (loaded inside the app with <a href="http://github.com/bkeepers/dotenv">dotenv</a>).</p>
<p>One of those configuration variables is the public ip of the app, which is used internally to make links.
I need to add a dnsmasq entry pointing this ip to 127.0.0.1 inside the container, so it can fetch the app's links as if it were not containerized.</p>
<p>I'm therefore trying to set an <code>ENV</code> in my Dockerfile which would pass an environment variable to the container.</p>
<p>I tried a few things.</p>
<pre><code>ENV REQUEST_DOMAIN $REQUEST_DOMAIN
ENV REQUEST_DOMAIN `REQUEST_DOMAIN`
</code></pre>
<p>Everything passes the "REQUEST_DOMAIN" string instead of the value of the environment variable though.
Is there a way to pass environment variables values from the host machine to the container?</p> | 34,600,106 | 8 | 0 | null | 2013-10-23 09:16:03.447 UTC | 67 | 2022-09-07 11:11:25.177 UTC | null | null | null | null | 122,080 | null | 1 | 335 | docker | 359,607 | <p>You should use the <a href="https://docs.docker.com/engine/reference/builder/#arg" rel="noreferrer"><code>ARG</code> directive</a> in your Dockerfile which is meant for this purpose.</p>
<blockquote>
<p>The <code>ARG</code> instruction defines a variable that users can pass at build-time to the builder with the docker build command using the <code>--build-arg <varname>=<value></code> flag.</p>
</blockquote>
<p>So your <em>Dockerfile</em> will have this line:</p>
<pre><code>ARG request_domain
</code></pre>
<p>or if you'd prefer a default value:</p>
<pre><code>ARG request_domain=127.0.0.1
</code></pre>
<p>Now you can reference this variable inside your Dockerfile:</p>
<pre><code>ENV request_domain=$request_domain
</code></pre>
<p>then you will build your container like so:</p>
<pre><code>$ docker build --build-arg request_domain=mydomain Dockerfile
</code></pre>
<p><br>
<strong>Note 1:</strong> Your image will not build if you have referenced an <code>ARG</code> in your Dockerfile but excluded it in <code>--build-arg</code>. </p>
<p><strong>Note 2:</strong> If a user specifies a build argument that was not defined in the Dockerfile, the build outputs a warning:</p>
<blockquote>
<p>[Warning] One or more build-args [foo] were not consumed.</p>
</blockquote> |
19,417,246 | How can I style the ProgressBar component in JavaFX | <p>I am trying to add custom css styling to the JavaFX ProgressBar component but I couldn't find any information on the topic. I am looking for the css class names and the css commands that are required to: </p>
<ul>
<li>set the color of the progress bar itself </li>
<li>set the background color of the progress bar (not the same as setting the background color) </li>
<li>add a custom text node on top of the progress bar (to show the different states)</li>
</ul> | 19,418,709 | 3 | 0 | null | 2013-10-17 02:28:07.87 UTC | 18 | 2021-11-04 16:58:46.713 UTC | 2013-10-17 02:33:52.143 UTC | null | 1,096,470 | null | 1,096,470 | null | 1 | 18 | java|css|javafx-2 | 41,440 | <p>I have marked this answer as <a href="https://meta.stackexchange.com/questions/11740/what-are-community-wiki-posts">community wiki</a>. </p>
<p>If you have ideas for JavaFX ProgressBar styling outside of the original initial styling queries, please edit this post to add your styling ideas (or to link to them).</p>
<blockquote>
<p>set the color of the progress bar itself</p>
</blockquote>
<p>Answered in:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/13357077/javafx-progressbar-how-to-change-bar-color/13372086#13372086">JavaFX ProgressBar: how to change bar color?</a></li>
</ul>
<p>The answer demonstrates</p>
<ol>
<li>Dynamic styling of the progress bar, so that the bar's color changes depending upon the amount of progress made.</li>
<li>Static styling of the progress bar, which just sets the bar's color forever to a defined color.</li>
</ol>
<p>JavaFX 7 (caspian) on a Windows PC:</p>
<p><img src="https://i.stack.imgur.com/8Gt9x.png" alt="colored progress bar"></p>
<p>JavaFX 8 (modena) on a Mac:</p>
<p><img src="https://i.stack.imgur.com/vQpZ4.png" alt="progress bar mac"></p>
<p>Sometimes people like barbershop pole style gradients, like the <a href="http://getbootstrap.com/2.3.2/components.html#progress" rel="noreferrer">bootstrap striped style</a>:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/18539642/progressbar-animated-javafx">ProgressBar Animated Javafx</a></li>
</ul>
<p><img src="https://i.stack.imgur.com/ti0st.png" alt="barbershop quartet"></p>
<blockquote>
<p>set the background color of the progress bar (not the same as setting the background color)</p>
</blockquote>
<p>Define an appropriate css style for the progress bar's "track":</p>
<pre><code>.progress-bar > .track {
-fx-text-box-border: forestgreen;
-fx-control-inner-background: palegreen;
}
</code></pre>
<p><img src="https://i.stack.imgur.com/rCEvj.png" alt="progress-bar background color"></p>
<blockquote>
<p>add a custom text node on top of the progress bar (to show the different states)</p>
</blockquote>
<p>Answered in:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/14059474/draw-a-string-onto-a-progressbar-like-jprogressbar">Draw a String onto a ProgressBar, like JProgressBar?</a></li>
</ul>
<p><img src="https://i.stack.imgur.com/0TdjS.png" alt="string on a progress bar"></p>
<blockquote>
<p>how to change the height of a progress bar:</p>
</blockquote>
<p>Answered in: </p>
<ul>
<li><a href="https://stackoverflow.com/questions/21740259/how-to-get-narrow-progres-bar-in-javafx">How to get narrow progres bar in JavaFX?</a></li>
</ul>
<p>Sample CSS: </p>
<pre><code>.progress-bar .bar {
-fx-padding: 1px;
-fx-background-insets: 0;
}
</code></pre>
<p>José Pereda gives a nice comprehensive solution for narrow progress bars in his answer to:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/27260431/how-to-get-a-small-progressbar-in-javafx/">How to get a small ProgressBar in JavaFX</a></li>
</ul>
<p><img src="https://i.stack.imgur.com/zx01u.png" alt="small progress"></p>
<blockquote>
<p>I am looking for the css class names and the css commands </p>
</blockquote>
<p>The place to look is in the default JavaFX style sheet.</p>
<ul>
<li><a href="http://hg.openjdk.java.net/openjfx/8/master/rt/file/88d3bef80ffc/modules/controls/src/main/resources/com/sun/javafx/scene/control/skin/modena/modena.css" rel="noreferrer">modena.css</a> for <a href="https://jdk8.java.net/download.html" rel="noreferrer">Java 8</a>.</li>
<li><a href="http://hg.openjdk.java.net/openjfx/2.2/master/rt/raw-file/tip/javafx-ui-controls/src/com/sun/javafx/scene/control/skin/caspian/caspian.css" rel="noreferrer">caspian.css</a> for Java 7.</li>
</ul>
<p>The ProgressBar style definitions for caspian (Java 7) are:</p>
<pre><code>.progress-bar {
-fx-skin: "com.sun.javafx.scene.control.skin.ProgressBarSkin";
-fx-background-color:
-fx-box-border,
linear-gradient(to bottom, derive(-fx-color,30%) 5%, derive(-fx-color,-17%));
-fx-background-insets: 0, 1;
-fx-indeterminate-bar-length: 60;
-fx-indeterminate-bar-escape: true;
-fx-indeterminate-bar-flip: true;
-fx-indeterminate-bar-animation-time: 2;
}
.progress-bar .bar {
-fx-background-color:
-fx-box-border,
linear-gradient(to bottom, derive(-fx-accent,95%), derive(-fx-accent,10%)),
linear-gradient(to bottom, derive(-fx-accent,38%), -fx-accent);
-fx-background-insets: 0, 1, 2;
-fx-padding: 0.416667em; /* 5 */
}
.progress-bar:indeterminate .bar {
-fx-background-color: linear-gradient(to left, transparent, -fx-accent);
}
.progress-bar .track {
-fx-background-color:
-fx-box-border,
linear-gradient(to bottom, derive(-fx-color,-15%), derive(-fx-color,2.2%) 20%, derive(-fx-color,60%));
-fx-background-insets: 0, 1;
}
.progress-bar:disabled {
-fx-opacity: -fx-disabled-opacity;
}
</code></pre>
<p>The progress bar style definitions for modena (Java 8) are:</p>
<pre><code>.progress-bar {
-fx-indeterminate-bar-length: 60;
-fx-indeterminate-bar-escape: true;
-fx-indeterminate-bar-flip: true;
-fx-indeterminate-bar-animation-time: 2;
}
.progress-bar > .bar {
-fx-background-color: linear-gradient(to bottom, derive(-fx-accent, -7%), derive(-fx-accent, 0%), derive(-fx-accent, -3%), derive(-fx-accent, -9%) );
-fx-background-insets: 3 3 4 3;
-fx-background-radius: 2;
-fx-padding: 0.75em;
}
.progress-bar:indeterminate > .bar {
-fx-background-color: linear-gradient(to left, transparent, -fx-accent);
}
.progress-bar > .track {
-fx-background-color:
-fx-shadow-highlight-color,
linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border),
linear-gradient(to bottom,
derive(-fx-control-inner-background, -7%),
derive(-fx-control-inner-background, 0%),
derive(-fx-control-inner-background, -3%),
derive(-fx-control-inner-background, -9%)
);
-fx-background-insets: 0, 0 0 1 0, 1 1 2 1;
-fx-background-radius: 4, 3, 2; /* 10, 9, 8 */
}
</code></pre>
<p>The <a href="http://docs.oracle.com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html" rel="noreferrer">JavaFX CSS reference guide</a> contains general information on the use of CSS in JavaFX (which differs somewhat from the use of CSS in HTML).</p> |
40,876,478 | how do you add a property to an existing type in typescript? | <p>
I'm trying to add a property to the javascript 'Date' prototype.</p>
<p>in javascript, i'd just do this:</p>
<pre><code>Object.defineProperty(Date.prototype, "fullYearUTC", {
get: function () { return this.getUTCFullYear(); },
enumerable: true,
configurable: true
});
</code></pre>
<p>I thought I'd just be able to do the following in typescript:</p>
<pre><code>class Date
{
get fullYearUTC(): number { return this.getUTCFullYear() }
}
</code></pre>
<p>but I get the error</p>
<pre><code>Cannot redeclare block-scoped variable 'Date'.
</code></pre>
<p>why doesn't this work?</p>
<p><em>(please no comments on whether or not you think doing this is a good idea. this question is not about that.)</em></p> | 40,876,614 | 2 | 0 | null | 2016-11-29 21:55:15.123 UTC | 4 | 2021-01-23 23:29:22.767 UTC | 2017-02-08 12:14:22.74 UTC | null | 4,886,740 | null | 204,555 | null | 1 | 29 | typescript | 31,696 | <p>You can not create a class named <code>Date</code>, you can have your own date object which extends it:</p>
<pre><code>class MyDate extends Date {
get fullYearUTC(): number {
return this.getUTCFullYear();
}
}
</code></pre>
<p>But if you want to modify the existing <code>Date</code> you need to keep doing what you did with your javascript code.<br>
As for adding it to the ts type, you need to use it as an interface:</p>
<pre><code>interface Date {
readonly fullYearUTC: number;
}
</code></pre>
<p>Or you can augment the global namespace:</p>
<pre><code>declare global {
interface Date {
readonly fullYearUTC: number;
}
}
</code></pre> |
40,789,120 | Angular2 cast string to JSON | <p>What is the right syntax to cast a string to JSON in Angular2?
I tried:</p>
<pre><code>var someString;
someString.toJSON(); //or someString.toJson();
</code></pre>
<p>it says: <code>someString.toJSON is not a function</code></p>
<p>I'm lost because it was working with Angular1.</p>
<hr>
<p>If I try to add an attribute directly on my string (which is formatted like a true JSON):</p>
<pre><code>var someString;
someString.att = 'test';
</code></pre>
<p>it says: <code>TypeError: Cannot create property 'att' on string '...'</code></p> | 40,789,285 | 2 | 0 | null | 2016-11-24 14:39:08.66 UTC | null | 2016-11-24 14:47:24.313 UTC | null | null | null | null | 3,933,603 | null | 1 | 15 | json|angular | 64,231 | <p>Angular2 uses JavaScript functions unlike Angular1.</p>
<p>Angular1 implements its own functions which is a bad thing.</p>
<p>In Angular2 just use pure JavaScript.</p>
<pre><code>var json = JSON.parse(string);
</code></pre> |
47,113,948 | java.lang.NoSuchMethodError: No static method getFont(Landroid/content/Context;ILandroid/util/TypedValue;ILandroid/widget/TextView;) | <p>After I updated my Android Studio to 3.0 I am getting <code>No static method getFont()</code> error. The project on which I am working is on github, <a href="https://github.com/ik024/GithubBrowser" rel="noreferrer">https://github.com/ik024/GithubBrowser</a></p>
<pre><code>// Top-level build file where you can add configuration options common
to all sub-projects/modules.
buildscript {
repositories {
jcenter()
maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
classpath 'com.jakewharton:butterknife-gradle-plugin:9.0.0-SNAPSHOT'
}
}
allprojects {
repositories {
jcenter()
maven { url 'https://maven.google.com' }
maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
}
ext{
arch_version = "1.0.0-alpha9"
support_version = "26.0.2"
dagger_version = "2.11"
junit_version = "4.12"
espresso_version = "2.2.2"
retrofit_version = "2.3.0"
mockwebserver_version = "3.8.0"
apache_commons_version = "2.5"
mockito_version = "1.10.19"
constraint_layout_version = "1.0.2"
timber_version = "4.5.1"
butterknife_version = "9.0.0-SNAPSHOT"
rxbinding_version = "2.0.0"
retrofit_version = "2.3.0"
okhttp_version = "3.6.0"
rxjava2_adapter_version = "1.0.0"
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p>app gradle</p>
<pre><code>apply plugin: 'com.android.application'
apply plugin: 'com.jakewharton.butterknife'
android {
compileSdkVersion 26
buildToolsVersion '26.0.2'
defaultConfig {
applicationId "com.ik.githubbrowser"
minSdkVersion 17
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/rxjava.properties'
}
testOptions {
unitTests.returnDefaultValues = true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile "com.android.support.constraint:constraint-layout:$constraint_layout_version"
compile "com.android.support:appcompat-v7:$support_version"
compile "com.android.support:recyclerview-v7:$support_version"
compile "com.android.support:cardview-v7:$support_version"
compile "com.android.support:design:$support_version"
compile "com.android.support:support-v4:$support_version"
compile "android.arch.persistence.room:runtime:$arch_version"
compile "android.arch.lifecycle:runtime:$arch_version"
compile "android.arch.lifecycle:extensions:$arch_version"
compile "android.arch.persistence.room:rxjava2:$arch_version"
compile "com.squareup.retrofit2:retrofit:$retrofit_version"
compile "com.squareup.retrofit2:converter-gson:$retrofit_version"
compile "com.squareup.retrofit2:adapter-rxjava:$retrofit_version"
compile "com.jakewharton.retrofit:retrofit2-rxjava2-adapter:$rxjava2_adapter_version"
compile "com.squareup.okhttp3:okhttp:$okhttp_version"
compile "com.squareup.okhttp3:logging-interceptor:$okhttp_version"
compile "com.jakewharton.timber:timber:$timber_version"
compile "com.jakewharton:butterknife:$butterknife_version"
compile "com.jakewharton.rxbinding2:rxbinding:$rxbinding_version"
compile "com.google.dagger:dagger:$dagger_version"
compile "com.google.dagger:dagger-android:$dagger_version"
compile "com.google.dagger:dagger-android-support:$dagger_version"
testCompile "junit:junit:$junit_version"
testCompile "com.squareup.okhttp3:mockwebserver:$mockwebserver_version"
testCompile("android.arch.core:core-testing:$arch_version", {
exclude group: 'com.android.support', module: 'support-compat'
exclude group: 'com.android.support', module: 'support-annotations'
exclude group: 'com.android.support', module: 'support-core-utils'
})
androidTestCompile "com.android.support:appcompat-v7:$support_version", {
exclude group: 'com.android.support', module: 'support-annotations'
exclude group: 'com.android.support', module: 'support-fragment'
exclude group: 'com.android.support', module: 'support-core-ui'
}
androidTestCompile "com.android.support:recyclerview-v7:$support_version", {
exclude group: 'com.android.support', module: 'support-annotations'
exclude group: 'com.android.support', module: 'support-fragment'
exclude group: 'com.android.support', module: 'support-core-ui'
}
androidTestCompile "com.android.support:support-v4:$support_version", {
exclude group: 'com.android.support', module: 'support-annotations'
exclude group: 'com.android.support', module: 'support-fragment'
exclude group: 'com.android.support', module: 'support-core-ui'
}
androidTestCompile "com.android.support:design:$support_version", {
exclude group: 'com.android.support', module: 'support-annotations'
exclude group: 'com.android.support', module: 'support-fragment'
exclude group: 'com.android.support', module: 'support-core-ui'
}
androidTestCompile("com.android.support.test.espresso:espresso-core:$espresso_version", {
exclude group: 'com.android.support', module: 'support-annotations'
exclude group: 'com.google.code.findbugs', module: 'jsr305'
})
androidTestCompile("com.android.support.test.espresso:espresso-contrib:$espresso_version", {
exclude group: 'com.android.support', module: 'support-annotations'
exclude group: 'com.google.code.findbugs', module: 'jsr305'
exclude group: 'com.android.support', module: 'support-fragment'
exclude group: 'com.android.support', module: 'support-core-ui'
})
androidTestCompile("android.arch.core:core-testing:$arch_version", {
exclude group: 'com.android.support', module: 'support-annotations'
})
androidTestCompile 'org.mockito:mockito-android:2.7.15', {
exclude group: 'com.android.support', module: 'support-annotations'
}
annotationProcessor "com.google.dagger:dagger-android-processor:$dagger_version"
annotationProcessor "com.google.dagger:dagger-compiler:$dagger_version"
annotationProcessor "android.arch.persistence.room:compiler:$arch_version"
annotationProcessor "android.arch.lifecycle:compiler:$arch_version"
annotationProcessor "com.jakewharton:butterknife-compiler:$butterknife_version"
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.0.2'
}
</code></pre>
<p>Error:</p>
<blockquote>
<p>FATAL EXCEPTION: main Process: com.ik.githubbrowser, PID: 4248
java.lang.NoSuchMethodError: No static method
getFont(Landroid/content/Context;ILandroid/util/TypedValue;ILandroid/widget/TextView;)Landroid/graphics/Typeface;
in class Landroid/support/v4/content/res/ResourcesCompat; or its super
classes (declaration of
'android.support.v4.content.res.ResourcesCompat' appears in
/data/app/com.ik.githubbrowser-YvwoGrxR8QaUEZ3IEqFVLQ==/split_lib_dependencies_apk.apk)
at
android.support.v7.widget.TintTypedArray.getFont(TintTypedArray.java:119)
at
android.support.v7.widget.AppCompatTextHelper.updateTypefaceAndStyle(AppCompatTextHelper.java:208)
at
android.support.v7.widget.AppCompatTextHelper.loadFromAttributes(AppCompatTextHelper.java:110)
at
android.support.v7.widget.AppCompatTextHelperV17.loadFromAttributes(AppCompatTextHelperV17.java:38)
at
android.support.v7.widget.AppCompatTextView.(AppCompatTextView.java:81)
at
android.support.v7.widget.AppCompatTextView.(AppCompatTextView.java:71)
at
android.support.v7.widget.AppCompatTextView.(AppCompatTextView.java:67)
at android.support.v7.widget.Toolbar.setTitle(Toolbar.java:753) at
android.support.v7.widget.ToolbarWidgetWrapper.setTitleInt(ToolbarWidgetWrapper.java:261)
at
android.support.v7.widget.ToolbarWidgetWrapper.setWindowTitle(ToolbarWidgetWrapper.java:243)
at
android.support.v7.widget.ActionBarOverlayLayout.setWindowTitle(ActionBarOverlayLayout.java:621)
at
android.support.v7.app.AppCompatDelegateImplV9.onTitleChanged(AppCompatDelegateImplV9.java:631)
at
android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
at
android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at
android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at
com.ik.githubbrowser.ui.search_user.SearchUserActivity.onCreate(SearchUserActivity.java:49)
at android.app.Activity.performCreate(Activity.java:6975) at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0) at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105) at
android.os.Looper.loop(Looper.java:164) at
android.app.ActivityThread.main(ActivityThread.java:6541) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)</p>
</blockquote> | 47,126,127 | 16 | 0 | null | 2017-11-04 18:13:35.603 UTC | 14 | 2021-12-14 14:50:46.533 UTC | 2018-02-27 07:24:30.437 UTC | null | 4,443,323 | null | 3,064,175 | null | 1 | 59 | android|android-studio-3.0|android-gradle-3.0 | 57,487 | <p>Fix <strong><em>res/values/styles.xml</em></strong> and <strong><em>Manifest.xml</em></strong> like so:This solution is tested and don't forget to clean and build :</p>
<p><strong><em>1.Manifest.xml</em></strong></p>
<p>change the theme of HomeActivity to :</p>
<pre><code> <activity
android:name=".ui.home.HomeActivity"
android:theme="@style/Base.Theme.AppCompat.Light" />
<activity android:name=".BaseActivity"></activity>
</code></pre>
<p><strong><em>2. res/values/styles.xml</em></strong>
Make all your themes preceeded with Base :styles.xml will be like this :</p>
<pre><code><resources>
<!-- Base application theme. -->
<!--<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">-->
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="Base.Theme.AppCompat.Light">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="Base.ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="Base.ThemeOverlay.AppCompat.Light" />
</code></pre>
<p></p>
<p>Detailed explanation as requested: <code>Theme.AppCompat.Light.DarkActionBar</code> is a subclass of the superclass <code>Base</code> anyway. Ctrl+click (Android Studio) on it and you will be taken to the source:</p>
<pre><code><style name="Theme.AppCompat.Light.DarkActionBar" parent="Base.Theme.AppCompat.Light.DarkActionBar" />
</code></pre>
<p><strong><em>3. GithubBrowser-Master.gradle</em></strong></p>
<p>make <code>support_version = "27.0.0"</code>
and not <code>support_version = "26.0.2</code></p>
<p><strong><em>4.app.gradle</em></strong> :</p>
<pre><code>compileSdkVersion 27
buildToolsVersion '27.0.0'
</code></pre>
<p>and not </p>
<pre><code> compileSdkVersion 26
buildToolsVersion '26.0.2'
</code></pre> |
47,505,778 | Wrapping blocking I/O in project reactor | <p>I have a spring-webflux API which, at a service layer, needs to read from an existing repository which uses JDBC.</p>
<p>Having done some reading on the subject, I would like to keep the execution of the blocking database call separate from the rest of my non-blocking async code.</p>
<p>I have defined a dedicated jdbcScheduler:</p>
<pre><code>@Bean
public Scheduler jdbcScheduler() {
return Schedulers.fromExecutor(Executors.newFixedThreadPool(maxPoolSize));
}
</code></pre>
<p>And an AsyncWrapper utility to use it:</p>
<pre><code>@Component
public class AsyncJdbcWrapper {
private final Scheduler jdbcScheduler;
@Autowired
public AsyncJdbcWrapper(Scheduler jdbcScheduler) {
this.jdbcScheduler = jdbcScheduler;
}
public <T> Mono<T> async(Callable<T> callable) {
return Mono.fromCallable(callable)
.subscribeOn(jdbcScheduler)
.publishOn(Schedulers.parallel());
}
}
</code></pre>
<p>Which is then used to wrap jdbc calls like so:</p>
<pre><code>Mono<Integer> userIdMono = asyncWrapper.async(() -> userDao.getUserByUUID(request.getUserId()))
.map(userOption -> userOption.map(u -> u.getId())
.orElseThrow(() -> new IllegalArgumentException("Unable to find user with ID " + request.getUserId())));
</code></pre>
<p>I've got two questions:</p>
<p>1) Am I correctly pushing the execution of blocking calls to another set of threads? Being fairly new to this stuff I'm struggling with the intricacies of subscribeOn()/publishOn().</p>
<p>2) Say I want to make use of the resulting mono, e.g call an API with the result of the userIdMono, on which scheduler will that be executed? The one specifically created for the jdbc calls, or the main(?) thread that reactor usually operates within? e.g.</p>
<pre><code>userIdMono.map(id -> someApiClient.call(id));
</code></pre> | 47,529,124 | 1 | 0 | null | 2017-11-27 07:28:39.43 UTC | 8 | 2017-11-28 10:22:31.497 UTC | 2017-11-27 09:02:28.137 UTC | null | 22,982 | null | 676,424 | null | 1 | 11 | java|project-reactor | 7,643 | <p>1) Use of <code>subscribeOn</code> is correctly putting the JDBC work on the <code>jdbcScheduler</code></p>
<p>2) Neither, the results of the <code>Callable</code> - while computed on the jdbcScheduler, are <code>publishOn</code> the <code>parallel</code> Scheduler, so your <code>map</code> will be executed on a thread from the <code>Schedulers.parallel()</code> pool (rather than hogging the <code>jdbcScheduler</code>).</p> |
46,955,197 | Package management initialization failed: Access Denied Error when opening Visual Studio 2017 | <p>I'm getting the following error when opening VS 2017 on Windows 7 64-bit:</p>
<blockquote>
<p>Package management initialization failed: Access Denied.</p>
<p>You can get more information by examining the file: <br>
C:\Users\<username>\AppData\Roaming\Microsoft\VisualStudio\15.<version>\ActivityLog.xml</p>
</blockquote>
<hr>
<p>It all started after I added my solution to SVN. I had no problems until I tried to add a file and got the following error:</p>
<blockquote>
<p>Value does not fall within the expected range</p>
</blockquote>
<p>I followed the steps mentioned in <a href="https://stackoverflow.com/questions/23901514/value-does-not-fall-within-the-expected-range-when-trying-to-add-a-reference-i">this answer</a> and did a <strong>'devenv /setup'</strong>, after that I started getting the <strong>Package management initialization failed: Access Denied.</strong> error when opening VS. Now Visual Studio doesn't even start.</p>
<p>Has anyone else experienced this problem and resolved it?</p>
<p><strong>Edit:</strong></p>
<p>I tried starting as an administrator and it worked. But otherwise it doesn't.</p> | 46,956,050 | 5 | 0 | null | 2017-10-26 13:07:36.753 UTC | 7 | 2021-12-10 12:54:45.617 UTC | 2018-06-07 07:18:51.627 UTC | null | 1,393,400 | null | 1,393,400 | null | 1 | 40 | visual-studio|visual-studio-2017 | 15,290 | <p>It turns out that this is a <a href="https://social.msdn.microsoft.com/Forums/sqlserver/en-US/ac06667a-56e6-4f95-9926-413a2d949f76/vs-2017-package-management-initialization-failed?forum=vssetup#answersList" rel="noreferrer">bug</a>, that hasn't yet been resolved. This error also occurs when <a href="https://developercommunity.visualstudio.com/content/problem/126255/package-management-initialization-failed-access-de.html" rel="noreferrer">starting Visual Studio after an update</a>.</p>
<p>But there is a workaround from <a href="https://developercommunity.visualstudio.com/content/problem/31263/vs2017-fails-to-start-with-unknown-error.html" rel="noreferrer">this thread</a> that worked for me,</p>
<p>Delete the <code>privateregistry.bin</code> file from the following folder:</p>
<blockquote>
<p>C:\users\%username%\Appdata\Local\Microsoft\VisualStudio\15.0_<version id>\</p>
</blockquote>
<p>This is however a temporary fix and resets the user's preferences. That's why it worked when I started it as an administrator, since the problem is user specific.</p>
<hr>
<h3>Update</h3>
<p>This bug is supposedly fixed in the latest versions of Visual Studio. But for the bug fix to work, the old <code>privateregistry.bin</code> file still needs to be deleted.</p> |
8,858,598 | How to install PHP extensions on nginx? | <p>I recently discovered NginX, and decided to try it out on my server. I have NginX running and able to serve PHP and HTML files. But now I want to try to install drupal. When trying to install it and check the requirements, I am stopped by one requirement.</p>
<blockquote>
<p>PHP extensions Disabled</p>
<p>Drupal requires you to enable the PHP extensions in the following list (see the system requirements page for more information):</p>
<p>gd</p>
</blockquote>
<p>I have tried to install gd by doing <code>apt-get install php5-gd</code>, and it says it is already installed. So I created a <code>phpinfo()</code> file, and checked to see if gd was enabled and I wasn't able to find it. Does this have to do with NginX or PHP? What do I do to fix this?</p> | 8,858,703 | 6 | 0 | null | 2012-01-13 23:23:08.637 UTC | 5 | 2017-04-11 08:02:23.183 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 830,545 | null | 1 | 15 | php|drupal|nginx|php-gd | 53,891 | <p>Since you are using Nginx - that must mean you are running PHP with PHP-FPM. </p>
<p>After you install stuff you need to: </p>
<pre><code>sudo /etc/init.d/php-fpm restart
</code></pre>
<p>or </p>
<pre><code>service php5-fpm restart
</code></pre>
<p>in newer ubuntu versions</p>
<p>so that PHP will pickup the new extensions.</p> |
8,561,983 | Retrieving command line history | <p>I use ubuntu 11.04, and the question must be common to any bash shell. Pressing the up arrow key on your terminal will retrieve the previous command you had executed at your terminal.</p>
<p>My question is where(in which file) will all these command history be stored? Can I read that file?</p> | 8,562,145 | 2 | 0 | null | 2011-12-19 13:23:34.627 UTC | 11 | 2016-07-11 11:07:34.057 UTC | null | null | null | null | 236,188 | null | 1 | 27 | linux|bash|ubuntu-11.04 | 57,241 | <p>the history filename was stored in variable : $HISTFILE </p>
<pre><code>echo $HISTFILE
</code></pre>
<p>will give you the right file.</p>
<p><strong>Usually</strong> in bash it would be ~/.bash_history, however it could be changed by configuration. </p>
<p>also notice that sometimes the very last commands is not stored in that file. running </p>
<pre><code>history -a
</code></pre>
<p>will persistent.</p>
<pre><code>history -r
</code></pre>
<p>will clean those command not yet written to the file.</p> |
8,684,551 | Generate a UUID string with ARC enabled | <p>I need to generate a UUID string in some code with ARC enabled.</p>
<p>After doing some research, this is what I came up with:</p>
<pre><code>CFUUIDRef uuid = CFUUIDCreate(NULL);
NSString *uuidStr = (__bridge_transfer NSString *)CFUUIDCreateString(NULL, uuid);
CFRelease(uuid);
</code></pre>
<p>Am I correctly using <code>__bridge_transfer</code> to avoid leaking any objects under ARC?</p> | 10,469,233 | 3 | 0 | null | 2011-12-30 22:11:39.6 UTC | 24 | 2013-11-28 10:58:40.777 UTC | 2012-05-06 07:50:57.61 UTC | null | 151,019 | null | 19,851 | null | 1 | 71 | objective-c|automatic-ref-counting | 28,342 | <p>Looks fine to me. This is what I use (available as a <a href="https://gist.github.com/1501325">gist</a>)</p>
<pre><code>- (NSString *)uuidString {
// Returns a UUID
CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
NSString *uuidString = (__bridge_transfer NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuid);
CFRelease(uuid);
return uuidString;
}
</code></pre>
<p><strong>Edited to add</strong></p>
<p>If you are on OS X 10.8 or iOS 6 you can use the new <a href="http://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSUUID_Class/Reference/Reference.html">NSUUID</a> class to generate a string UUID, without having to go to Core Foundation:</p>
<pre><code>NSString *uuidString = [[NSUUID UUID] UUIDString];
// Generates: 7E60066C-C7F3-438A-95B1-DDE8634E1072
</code></pre>
<p>But mostly, if you just want to generate a unique string for a file or directory name then you can use <code>NSProcessInfo</code>'s <code>globallyUniqueString</code> method like:</p>
<pre><code>NSString *uuidString = [[NSProcessInfo processInfo] globallyUniqueString];
// generates 56341C6E-35A7-4C97-9C5E-7AC79673EAB2-539-000001F95B327819
</code></pre>
<p>It's not a formal UUID, but it is unique for your network and your process and is a good choice for a lot of cases.</p> |
8,708,342 | Redirect console output to string in Java | <p>I have one method whose <strong>return type is <code>void</code></strong> and it prints directly on console.</p>
<p>However I need that output in a String so that I can work on it.</p>
<p>As I can't make any changes to the method with return type <code>void</code> I have to redirect that output to a String.</p>
<p>How can I redirect it in Java?</p> | 8,708,357 | 4 | 0 | null | 2012-01-03 05:34:43.237 UTC | 38 | 2021-09-23 14:00:01.467 UTC | 2020-10-16 08:01:50.037 UTC | null | 40,342 | null | 985,319 | null | 1 | 81 | java|string|redirect|console|stdout | 116,849 | <p>If the function is printing to <code>System.out</code>, you can capture that output by using the <code>System.setOut</code> method to change <code>System.out</code> to go to a <code>PrintStream</code> provided by you. If you create a <code>PrintStream</code> connected to a <code>ByteArrayOutputStream</code>, then you can capture the output as a <code>String</code>.</p>
<p>Example:</p>
<pre><code>// Create a stream to hold the output
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
// IMPORTANT: Save the old System.out!
PrintStream old = System.out;
// Tell Java to use your special stream
System.setOut(ps);
// Print some output: goes to your special stream
System.out.println("Foofoofoo!");
// Put things back
System.out.flush();
System.setOut(old);
// Show what happened
System.out.println("Here: " + baos.toString());
</code></pre>
<p>This program prints just one line: </p>
<pre class="lang-none prettyprint-override"><code>Here: Foofoofoo!
</code></pre> |
55,271,798 | Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist` | <p>Recently, when I compile my scss files I get an error. The error message says:</p>
<blockquote>
<p>Browserslist: caniuse-lite is outdated. Please run next command <code>npm update caniuse-lite browserslist</code></p>
</blockquote>
<p>First, as the message says, I ran <code>npm update caniuse-lite browserslist</code> but it didn't fix the issue.
I deleted the whole node_modules directory and installed again, also I updated the whole folder by <code>npm update</code> but none of them solved the issue.
I also reinstalled autoprefixer and browserslist but none of them solved the issue.</p>
<p>If I remove</p>
<pre><code>"options": {
"autoPrefix": "> 1%"
}
</code></pre>
<p>from my <code>compilerconfig.json</code>, everything works fine which means probably it is related to autoprefixer. Also, I manually changed the package version to the latest version on <code>package.json</code> and reinstalled but no luck.</p> | 55,283,201 | 23 | 0 | null | 2019-03-20 23:49:44.05 UTC | 31 | 2022-09-12 14:36:05.89 UTC | 2022-09-12 14:36:05.89 UTC | null | 2,884,291 | null | 2,989,995 | null | 1 | 204 | npm|sass|autoprefixer|web-compiler | 335,868 | <p>It sounds like you are using Visual Studio's Web Compiler extension. There is an open issue for this found here: <a href="https://github.com/madskristensen/WebCompiler/issues/413" rel="noreferrer">https://github.com/madskristensen/WebCompiler/issues/413</a></p>
<p>There is a workaround posted in that issue:</p>
<ol>
<li>Close Visual Studio</li>
<li>Head to <code>C:\Users\USERNAME\AppData\Local\Temp\WebCompilerX.X.X</code> (X is the version of WebCompiler)</li>
<li>Delete following folders from <code>node_modules</code> folder: <code>caniuse-lite</code> and <code>browserslist</code>
Open up CMD (inside <code>C:\Users\USERNAME\AppData\Local\Temp\WebCompilerX.X.X</code>) and run: <code>npm i caniuse-lite browserslist</code></li>
</ol> |
946,114 | How to use IDispatch in plain C to call a COM object | <p>I need to compile some code of mine using the gcc compiler included in the R tools (R the statistical program for windows), the problem is that I need to use IDispatch in my code to create an access the methods of a COM object, and the gcc compiler doesn't support much of the code that I'm using to do so, which is basically C++ code.</p>
<p>So my question is how can I use IDispatch in C to create the COM object without having to depend on MFC, .NET, C#, WTL, or ATL. I believe that if I do so I will be able to compile my code without any problem. </p> | 946,294 | 3 | 0 | null | 2009-06-03 17:42:23.32 UTC | 15 | 2009-06-04 11:57:52.41 UTC | 2009-06-03 18:08:59.413 UTC | null | 16,794 | null | 58,434 | null | 1 | 16 | c|com|gcc|activex|idispatch | 7,416 | <p>There is a great article on CodeProject entitled "COM in plain C".</p>
<p>Here is <a href="http://www.codeproject.com/KB/COM/com_in_c1.aspx" rel="noreferrer">the link to Part 1</a>.</p>
<p>There is a lot of very good info on working with COM in C in that article and the author's subsequent follow-ups (I think there are 3 or 4 in the series).</p>
<p><strong>Edit:</strong><br>
I was wrong, there are 8 parts!</p>
<p><a href="http://www.codeproject.com/KB/COM/com_in_c2.aspx" rel="noreferrer">Part 2</a><br>
<a href="http://www.codeproject.com/KB/COM/com_in_c3.aspx" rel="noreferrer">Part 3</a><br>
<a href="http://www.codeproject.com/KB/COM/com_in__c4.aspx" rel="noreferrer">Part 4</a><br>
<a href="http://www.codeproject.com/KB/COM/com_in_c5.aspx" rel="noreferrer">Part 5</a><br>
<a href="http://www.codeproject.com/KB/COM/com_in_c6.aspx" rel="noreferrer">Part 6</a><br>
<a href="http://www.codeproject.com/KB/COM/com_in_c7.aspx" rel="noreferrer">Part 7</a><br>
<a href="http://www.codeproject.com/KB/COM/com_in_c8.aspx" rel="noreferrer">Part 8</a></p> |
477,820 | What's the idiomatic Python equivalent to Django's 'regroup' template tag? | <p><a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup" rel="noreferrer">http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup</a></p>
<p>I can think of a few ways of doing it with loops but I'd particularly like to know if there is a neat one-liner.</p> | 477,839 | 3 | 0 | null | 2009-01-25 15:29:44.457 UTC | 12 | 2015-06-08 04:34:08.243 UTC | null | null | null | andybak | 45,955 | null | 1 | 20 | python|django|django-templates | 4,640 | <p>Combine <a href="http://docs.python.org/library/itertools.html#itertools.groupby" rel="noreferrer"><code>itertools.groupby</code></a> with <a href="http://docs.python.org/library/operator.html#operator.itemgetter" rel="noreferrer"><code>operator.itemgetter</code></a> to get a pretty nice solution:</p>
<pre><code>from operator import itemgetter
from itertools import groupby
key = itemgetter('gender')
iter = groupby(sorted(people, key=key), key=key)
for gender, people in iter:
print '===', gender, '==='
for person in people:
print person
</code></pre> |
17,612 | How do you place a file in recycle bin instead of delete? | <p>Programmatic solution of course...</p> | 17,620 | 3 | 1 | null | 2008-08-20 08:43:00.393 UTC | 8 | 2013-04-28 03:27:06.143 UTC | 2013-04-28 03:27:06.143 UTC | Brian Leahy | 1,012,641 | Brian Leahy | 580 | null | 1 | 29 | c#|.net|c++|windows|io | 10,832 | <p><a href="http://www.daveamenta.com/2008-05/c-delete-a-file-to-the-recycle-bin/" rel="noreferrer">http://www.daveamenta.com/2008-05/c-delete-a-file-to-the-recycle-bin/</a></p>
<p>From above:</p>
<pre><code>using Microsoft.VisualBasic;
string path = @"c:\myfile.txt";
FileIO.FileSystem.DeleteDirectory(path,
FileIO.UIOption.OnlyErrorDialogs,
RecycleOption.SendToRecycleBin);
</code></pre> |
35,261,567 | How to solve error: ';' expected in Java? | <p>I have a <code>error: ';' expected</code> issue with my Java code below. I don't know how to solve it?</p>
<p><code>SortThread</code> and <code>MergeThread</code> have been created as a class, and compiled well.</p>
<p>The only problem is </p>
<pre><code>SortThread t1.join() = new SortThread(a);
SortThread t2.join() = new SortThread(b);
MergeThread m.start() = new MergeThread(t1.get(),t2.get());
</code></pre>
<p>These three line codes has <code>error: ';' expected</code> issues.</p>
<p>In this main, it will create two array, a and b.
m array will merge a&b, and main will display m.</p>
<p>Any hints or solutions are very helpful for me.</p>
<pre><code>import java.util.Random;
public class Main{
public static void main(String[] args){
Random r = new Random(System.currentTimeMillis());
int n = r.nextInt(101) + 50;
int[] a = new int[n];
for(int i = 0; i < n; i++)
a[i] = r.nextInt(100);
n = r.nextInt(101) + 50;
int[] b = new int[n];
for(int i = 0; i < n; i++)
b[i] = r.nextInt(100);
SortThread t1.join() = new SortThread(a);
SortThread t2.join() = new SortThread(b);
MergeThread m.start() = new MergeThread(t1.get(),t2.get());
System.out.println(Arrays.toString(m.get()));
}
}
</code></pre> | 35,261,574 | 1 | 2 | null | 2016-02-08 02:22:00.927 UTC | 1 | 2016-02-08 02:24:13.553 UTC | 2016-02-08 02:24:13.553 UTC | null | 3,763,242 | null | 3,763,242 | null | 1 | 1 | java | 56,421 | <p>You can't call the methods before you finish initializing the variables you're calling.</p>
<pre><code>SortThread t1.join() = new SortThread(a);
SortThread t2.join() = new SortThread(b);
MergeThread m.start() = new MergeThread(t1.get(),t2.get());
</code></pre>
<p>should be something like</p>
<pre><code>SortThread t1 = new SortThread(a);
t1.start(); // <-- you probably want to start before you join.
SortThread t2 = new SortThread(b);
t2.start();
t1.join();
t2.join();
MergeThread m = new MergeThread(t1.get(),t2.get());
m.start();
m.join();
</code></pre> |
24,176,605 | Using Predicate in Swift | <p>I'm working through the tutorial here (learning Swift) for my first app:
<a href="http://www.appcoda.com/search-bar-tutorial-ios7/">http://www.appcoda.com/search-bar-tutorial-ios7/</a></p>
<p>I'm stuck on this part (Objective-C code):</p>
<pre><code>- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
searchResults = [recipes filteredArrayUsingPredicate:resultPredicate];
}
</code></pre>
<p>Can anyone advise how to create an equivalent for NSPredicate in Swift?</p> | 24,177,043 | 8 | 0 | null | 2014-06-12 04:47:19.47 UTC | 24 | 2018-04-09 06:44:30.62 UTC | 2015-08-11 14:44:44.513 UTC | null | 295,027 | null | 2,813,723 | null | 1 | 98 | ios|objective-c|swift|ios7|predicate | 142,537 | <p>This is really just a syntax switch. OK, so we have this method call:</p>
<pre><code>[NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
</code></pre>
<p>In Swift, constructors skip the "blahWith…" part and just use the class name as a function and then go straight to the arguments, so <code>[NSPredicate predicateWithFormat: …]</code> would become <code>NSPredicate(format: …)</code>. (For another example, <code>[NSArray arrayWithObject: …]</code> would become <code>NSArray(object: …)</code>. This is a regular pattern in Swift.)</p>
<p>So now we just need to pass the arguments to the constructor. In Objective-C, NSString literals look like <code>@""</code>, but in Swift we just use quotation marks for strings. So that gives us:</p>
<pre><code>let resultPredicate = NSPredicate(format: "name contains[c] %@", searchText)
</code></pre>
<p>And in fact that is exactly what we need here.</p>
<p>(Incidentally, you'll notice some of the other answers instead use a format string like <code>"name contains[c] \(searchText)"</code>. That is not correct. That uses string interpolation, which is different from predicate formatting and will generally not work for this.)</p> |
6,065,140 | jquery click change class | <p>I am studying jquery, I want make a effection as: first click, slider down the div#ccc and change the link class to 'aaa'; click again, slider up the div#ccc and change the link class back to 'bbb'. now slider down can work, but removeClass, addClass not work. how to modify so that two effection work perfect? thanks.</p>
<pre><code><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$("#click").click(function() {
$("#ccc").slideDown('fast').show();
$(this).removeClass('bbb').addClass('aaa');
});
$("#click").click(function() {
$("#ccc").slideDown('fast').hide();
$(this).removeClass('aaa').addClass('bbb');
});
});
</script>
<style>
#ccc{display:none;}
</style>
<div id="click" class="bbb">click</div>
<div id="ccc">hello world</div>
</code></pre> | 6,065,174 | 3 | 0 | null | 2011-05-19 21:35:27.117 UTC | null | 2011-05-19 22:06:11.543 UTC | null | null | null | null | 547,726 | null | 1 | 6 | jquery|click|addclass|removeclass | 41,824 | <p>You need to use a single toggle event. You are setting the click event twice and that won't work.</p>
<p><a href="http://jsfiddle.net/jesus_tesh/2m9mx/" rel="noreferrer">jsfiddle</a></p> |
6,011,636 | 403 - Forbidden on basic MVC 3 deploy on iis7.5 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2374957/asp-net-mvc-on-iis-7-5">ASP.NET MVC on IIS 7.5</a> </p>
</blockquote>
<p>I am trying to deploy a basic MVC 3 application to my 2008 R2 Server running iis 7.5 but receive a "403 - Forbidden" error trying to view my page.</p>
<p>I have anonymous authentication enabled, and my app pool is using the "ApplicationPoolIdentity" in integrated pipeline mode with .net 4.0. I don't know what "user" the "ApplicationPoolIdentity" is, but I've given IUSR read/write rights to the website folder.</p>
<p>I don't have any other authentication schemes in place, the server is not even running in a domain.</p>
<p>If I put a default html page in there, it loads fine. It's only my methods/controllers that I cannot get to function.</p>
<p>How else can I troubleshoot this?</p>
<p>Thanks,</p> | 6,011,811 | 3 | 1 | null | 2011-05-15 22:17:24.743 UTC | 9 | 2012-06-11 10:51:49.06 UTC | 2017-05-23 12:08:41.553 UTC | null | -1 | null | 708,430 | null | 1 | 27 | asp.net|asp.net-mvc-3|iis-7.5 | 25,141 | <p>Run <code>aspnet_regiis -i</code>. Often I've found you need to do that to get 4.0 apps to work. Open a command prompt:</p>
<pre><code>cd \
cd Windows\Microsoft .NET\Framework\v4.xxx.xxx
aspnet_regiis -i
</code></pre>
<p>Once it has installed and registered, make sure you application is using an application pool that is set to .NET 4.0.</p> |
45,785,898 | How to use the code returned from Cognito to get AWS credentials? | <p>Right now, I'm struggling to understand AWS Cognito so maybe someone could help me out. I set a domain to serve Cognito's hosted UI for my User Pool like what's described <a href="http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-ux.html" rel="noreferrer">here</a>. So when I go to <code>https://<my-domain>.auth.us-east-1.amazoncognito.com/login?response_type=code&client_id=<MY_POOL_CLIENT_ID>&redirect_uri=https://localhost:8080</code> I get a login page where my users can login to my app with Google. That part is working great.</p>
<p>I'm confused about what to do with the code that is returned from that page once my user logs in. So once I get redirected to Google and authorize the application to view my information, I get redirected back to one of my URLs with a code in the query params. Right now I'm redirecting to localhost, so the redirect URL look like this:</p>
<p><code>https://localhost:8080/?code=XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX</code></p>
<p>What exactly is this code? Also, how do I use it to get access to AWS resources for my user?</p> | 63,096,171 | 6 | 2 | null | 2017-08-20 19:12:51.523 UTC | 17 | 2022-05-07 15:55:16.907 UTC | 2022-03-25 13:34:12.657 UTC | null | 1,461,269 | null | 1,461,269 | null | 1 | 43 | javascript|amazon-web-services|amazon-cognito|aws-sdk | 20,811 | <p><em>First off, screw authentication a thousand times. No one deserves to spend half a day looking at this shit.</em></p>
<p>Authentication for API Gateway Authorized with Cognito</p>
<p><strong>Ingredients</strong></p>
<ol>
<li><p><code>client_id</code> and <code>client_secret</code>: In Cognito > General Settings > App clients you can find the App client id, then click on Show Details to find the App client secret</p>
</li>
<li><p>For the header <code>Authorization: Basic YWJjZGVmZzpvMWZjb28zc...</code> you need to encode those two with: <code>Base64Encode(client_id:client_secret)</code>, for example in Python:</p>
<pre><code>import base64
base64.b64encode('qcbstohg3o:alksjdlkjdasdksd')`
</code></pre>
<p><em>side note: Postman also has an option to generate this in Authorization > <strong>Basic Auth</strong></em></p>
</li>
<li><p><code>redirect_uri</code>: passed in the body, it is the callback url that you configured in App integration > App client settings.<br />
This MUST match with what you configured or you will get a totally
unhelpful message <code>{ "error": "invalid_grant" }</code></p>
</li>
</ol>
<p><strong>Example of a request to get a token from the code:</strong></p>
<pre><code>curl --location --request POST 'https://mycognitodomain.auth.us-east-1.amazoncognito.com/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic <base64 encoded client_id:client_secret>' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'client_id=<client_id>' \
--data-urlencode 'code=<use the code you received post login>' \
--data-urlencode 'redirect_uri=https://myapp.com'
</code></pre>
<p>This will return your tokens:</p>
<pre><code>{
"access_token":"eyJz9sdfsdfsdfsd",
"refresh_token":"dn43ud8uj32nk2je",
"id_token":"dmcxd329ujdmkemkd349r",
"token_type":"Bearer",
"expires_in":3600
}
</code></pre>
<p>Then take the <code>id_token</code> and plug into your API call:</p>
<pre><code>curl --location --request GET 'https://myapigateway.execute-api.us-east-1.amazonaws.com/' \
--header 'Authorization: <id_token>'
</code></pre>
<p><strong>Ok, this is tagged as JavaScript but since we also suffer in Python</strong></p>
<p><em>Friendly reminder: this is an example, please don't hardcode your secrets.</em></p>
<pre class="lang-py prettyprint-override"><code>import requests
# In: General Settings > App clients > Show details
client_id = "ksjahdskaLAJS ..."
client_secret = "dssaKJHSAKJHDSsjdhksjHSKJDskdjhsa..."
# URL in your application that receives the code post-authentication
# (Cognito lets you use localhost for testing purposes)
callback_uri = "http://localhost:8001/accounts/amazon-cognito/login/callback/"
# Find this in: App Integration > Domain
cognito_app_url = "https://my-application-name.auth.us-west-2.amazoncognito.com"
# this is the response code you received - you can get a code to test by going to
# going to App Integration > App client settings > Lunch Hosted UI
# and doing the login steps, even if it redirects you to an invalid URL after login
# you can see the code in the querystring, for example:
# http://localhost:8001/accounts/amazon-cognito/login/callback/?code=b2ca649e-b34a-44a7-be1a-121882e27fe6
code="b2ca649e-b34a-44a7-be1a-121882e27fe6"
token_url = f"{cognito_app_url}/oauth2/token"
auth = requests.auth.HTTPBasicAuth(client_id, client_secret)
params = {
"grant_type": "authorization_code",
"client_id": client_id,
"code": code,
"redirect_uri": callback_uri
}
response = requests.post(token_url, auth=auth, data=params)
print(response.json()) # don't judge me, this is an example
</code></pre> |
46,041,811 | Performance of various numpy fancy indexing methods, also with numba | <p>Since for my program fast indexing of <code>Numpy</code> arrays is quite necessary and fancy indexing doesn't have a good reputation considering performance, I decided to make a few tests. Especially since <code>Numba</code> is developing quite fast, I tried which methods work well with numba.</p>
<p>As inputs I've been using the following arrays for my small-arrays-test:</p>
<pre><code>import numpy as np
import numba as nb
x = np.arange(0, 100, dtype=np.float64) # array to be indexed
idx = np.array((0, 4, 55, -1), dtype=np.int32) # fancy indexing array
bool_mask = np.zeros(x.shape, dtype=np.bool) # boolean indexing mask
bool_mask[idx] = True # set same elements as in idx True
y = np.zeros(idx.shape, dtype=np.float64) # output array
y_bool = np.zeros(bool_mask[bool_mask == True].shape, dtype=np.float64) #bool output array (only for convenience)
</code></pre>
<p>And the following arrays for my large-arrays-test (<code>y_bool</code> needed here to cope with dupe numbers from <code>randint</code>):</p>
<pre><code>x = np.arange(0, 1000000, dtype=np.float64)
idx = np.random.randint(0, 1000000, size=int(1000000/50))
bool_mask = np.zeros(x.shape, dtype=np.bool)
bool_mask[idx] = True
y = np.zeros(idx.shape, dtype=np.float64)
y_bool = np.zeros(bool_mask[bool_mask == True].shape, dtype=np.float64)
</code></pre>
<p>This yields the following timings without using numba:</p>
<pre><code>%timeit x[idx]
#1.08 µs ± 21 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
#large arrays: 129 µs ± 3.45 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit x[bool_mask]
#482 ns ± 18.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
#large arrays: 621 µs ± 15.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit np.take(x, idx)
#2.27 µs ± 104 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# large arrays: 112 µs ± 5.76 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit np.take(x, idx, out=y)
#2.65 µs ± 134 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# large arrays: 134 µs ± 4.47 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit x.take(idx)
#919 ns ± 21.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# large arrays: 108 µs ± 1.71 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit x.take(idx, out=y)
#1.79 µs ± 40.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# larg arrays: 131 µs ± 2.92 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit np.compress(bool_mask, x)
#1.93 µs ± 95.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# large arrays: 618 µs ± 15.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit np.compress(bool_mask, x, out=y_bool)
#2.58 µs ± 167 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# large arrays: 637 µs ± 9.88 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit x.compress(bool_mask)
#900 ns ± 82.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# large arrays: 628 µs ± 17.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit x.compress(bool_mask, out=y_bool)
#1.78 µs ± 59.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# large arrays: 628 µs ± 13.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit np.extract(bool_mask, x)
#5.29 µs ± 194 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# large arrays: 641 µs ± 13 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code></pre>
<p>And with <code>numba</code>, using jitting in <code>nopython</code>-mode, <code>cach</code>ing and <code>nogil</code> I decorated the ways of indexing, which are supported by <code>numba</code>:</p>
<pre><code>@nb.jit(nopython=True, cache=True, nogil=True)
def fancy(x, idx):
x[idx]
@nb.jit(nopython=True, cache=True, nogil=True)
def fancy_bool(x, bool_mask):
x[bool_mask]
@nb.jit(nopython=True, cache=True, nogil=True)
def taker(x, idx):
np.take(x, idx)
@nb.jit(nopython=True, cache=True, nogil=True)
def ndtaker(x, idx):
x.take(idx)
</code></pre>
<p>This yields the following results for small and large arrays:</p>
<pre><code>%timeit fancy(x, idx)
#686 ns ± 25.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# large arrays: 84.7 µs ± 1.82 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit fancy_bool(x, bool_mask)
#845 ns ± 31 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# large arrays: 843 µs ± 14.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit taker(x, idx)
#814 ns ± 21.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# large arrays: 87 µs ± 1.52 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit ndtaker(x, idx)
#831 ns ± 24.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# large arrays: 85.4 µs ± 2.69 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code></pre>
<hr>
<p><strong>Summary</strong></p>
<p>While for numpy without numba it is clear that small arrays are by far best indexed with boolean masks (about a factor 2 compared to <code>ndarray.take(idx)</code>), for larger arrays <code>ndarray.take(idx)</code> will perform best, in this case around 6 times faster than boolean indexing. The breakeven-point is at an array-size of around <code>1000</code> cells with and index-array-size of around <code>20</code> cells.<br>
For arrays with <code>1e5</code> elements and <code>5e3</code> index array size, <code>ndarray.take(idx)</code> will be around <strong>10 times faster</strong> than boolean mask indexing. So it seems that boolean indexing seems to slow down considerably with array size, but catches up a little after some array-size-threshold is reached.</p>
<p>For the numba jitted functions there is a small speedup for all indexing functions except for boolean mask indexing. Simple fancy indexing works best here, but is still slower than boolean masking without jitting.<br>
For larger arrays boolean mask indexing is a lot slower than the other methods, and even slower than the non-jitted version. The three other methods all perform quite good and around 15% faster than the non-jitted version.</p>
<p>For my case with many arrays of different sizes, fancy indexing with numba is the best way to go. Perhaps some other people can also find some useful information in this quite lengthy post.</p>
<p>Edit:<br>
I'm sorry that I forgot to ask my question, which I in fact have. I was just rapidly typing this at the end of my workday and completely forgot it...
Well, do you know any better and faster method than those that I tested? Using Cython my timings were between Numba and Python.<br>
As the index array is predefined once and used without alteration in long iterations, any way of pre-defining the indexing process would be great. For this I thought about using strides. But I wasn't able to pre-define a custom set of strides. Is it possible to get a predefined view into the memory using strides?</p>
<p>Edit 2:<br>
I guess I'll move my question about predefined constant index arrays which will be used on the same value array (where only the values change but not the shape) for a few million times in iterations to a new and more specific question. This question was too general and perhaps I also formulated the question a little bit misleading. I'll post the link here as soon as I opened the new question!<br>
<a href="https://stackoverflow.com/questions/46099352/increasing-performance-of-highly-repeated-numpy-array-index-operations">Here is the link to the followup question.</a></p> | 46,043,964 | 1 | 3 | null | 2017-09-04 17:29:35.63 UTC | 13 | 2019-12-09 19:03:46.377 UTC | 2017-09-07 14:49:36.947 UTC | null | 6,345,518 | null | 6,345,518 | null | 1 | 27 | python|performance|numpy|indexing|numba | 8,209 | <p>Your summary isn't completely correct, you already did tests with differently sized arrays but one thing that you didn't do was to change the number of elements indexed.</p>
<p>I restricted it to pure indexing and omitted <code>take</code> (which effectively is integer array indexing) and <code>compress</code> and <code>extract</code> (because these are effectively boolean array indexing). The only difference for these are the constant factors. The constant factor for the methods <code>take</code> and <code>compress</code> will be less than the overhead for the numpy functions <code>np.take</code> and <code>np.compress</code> but otherwise the effects will be negligible for reasonably sized arrays.</p>
<p>Just let me present it with different numbers:</p>
<pre><code># ~ every 500th element
x = np.arange(0, 1000000, dtype=np.float64)
idx = np.random.randint(0, 1000000, size=int(1000000/500)) # changed the ratio!
bool_mask = np.zeros(x.shape, dtype=np.bool)
bool_mask[idx] = True
%timeit x[idx]
# 51.6 µs ± 2.02 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit x[bool_mask]
# 1.03 ms ± 37.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# ~ every 50th element
idx = np.random.randint(0, 1000000, size=int(1000000/50)) # changed the ratio!
bool_mask = np.zeros(x.shape, dtype=np.bool)
bool_mask[idx] = True
%timeit x[idx]
# 1.46 ms ± 55.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit x[bool_mask]
# 2.69 ms ± 154 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# ~ every 5th element
idx = np.random.randint(0, 1000000, size=int(1000000/5)) # changed the ratio!
bool_mask = np.zeros(x.shape, dtype=np.bool)
bool_mask[idx] = True
%timeit x[idx]
# 14.9 ms ± 495 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit x[bool_mask]
# 8.31 ms ± 181 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code></pre>
<p>So what happened here? It's simple: Integer array indexing only needs to access as many elements as there are values in the index-array. That means if there are few matches it will be quite fast but slow if there are many indices. Boolean array indexing, however, always needs to walk through the whole boolean array and check for "true" values. That means it should be roughly "constant" for the array.</p>
<p>But, wait, it's not really constant for boolean arrays and why does integer array indexing take longer (last case) than boolean array indexing even if it has to process ~5 times less elements?</p>
<p>That's where it gets more complicated. In this case the boolean array had <code>True</code> at random places which means that it will be subject to <strong>branch prediction failures</strong>. These will be more likely if <code>True</code> and <code>False</code> will have equal occurrences but at random places. That's why the boolean array indexing got slower - because the ratio of <code>True</code> to <code>False</code> got more equal and thus more "random". Also the result array will be larger if there are more <code>True</code>s which also consumes more time.</p>
<p>As an example for this branch prediction thing use this as example (could differ with different system/compilers):</p>
<pre><code>bool_mask = np.zeros(x.shape, dtype=np.bool)
bool_mask[:1000000//2] = True # first half True, second half False
%timeit x[bool_mask]
# 5.92 ms ± 118 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
bool_mask = np.zeros(x.shape, dtype=np.bool)
bool_mask[::2] = True # True and False alternating
%timeit x[bool_mask]
# 16.6 ms ± 361 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
bool_mask = np.zeros(x.shape, dtype=np.bool)
bool_mask[::2] = True
np.random.shuffle(bool_mask) # shuffled
%timeit x[bool_mask]
# 18.2 ms ± 325 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code></pre>
<p>So the distribution of <code>True</code> and <code>False</code> will critically affect the runtime with boolean masks even if they contain the same amount of <code>True</code>s! The same effect will be visible for the <code>compress</code>-functions.</p>
<p>For integer array indexing (and likewise <code>np.take</code>) another effect will be visible: <strong>cache locality</strong>. The indices in your case are randomly distributed, so your computer has to do a lot of "RAM" to "processor cache" loads because it's very unlikely two indices will be near to each other. </p>
<p>Compare this:</p>
<pre><code>idx = np.random.randint(0, 1000000, size=int(1000000/5))
%timeit x[idx]
# 15.6 ms ± 703 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
idx = np.random.randint(0, 1000000, size=int(1000000/5))
idx = np.sort(idx) # sort them
%timeit x[idx]
# 4.33 ms ± 366 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code></pre>
<p>By sorting the indices the chances immensely increased that the next value will already be in the cache and this can lead to huge speedups. That's a very important factor if you know that the indices will be sorted (for example if they were created by <code>np.where</code> they are sorted, which makes the result of <code>np.where</code> especially efficient for indexing).</p>
<p>So, it's not like integer array indexing is slower for small arrays and faster for large arrays it depends on much more factors. Both do have their use-cases and depending on the circumstances one might be (considerably) faster than the other.</p>
<hr>
<p>Let me also talk a bit about the numba functions. First some general statements:</p>
<ul>
<li><code>cache</code> won't make a difference, it just avoids recompiling the function. In interactive environments this is essentially useless. It's faster if you would package the functions in a module though.</li>
<li><code>nogil</code> by itself won't provide any speed boost. It will be faster if it's called in different threads because each function execution can release the GIL and then multiple calls can run in parallel.</li>
</ul>
<p>Otherwise I don't know how numba effectivly implements these functions, however when you use NumPy features in numba it could be slower or faster - but even if it's faster it won't be much faster (except maybe for small arrays). Because if it could be made faster the NumPy developers would also implement it. My rule of thumb is: If you can do it (vectorized) with NumPy don't bother with numba. Only if you can't do it with vectorized NumPy functions or NumPy would use too many temporary arrays then numba will shine!</p> |
6,265,024 | Function Returning Boolean? | <p>I have simple function in VBA and I would need to check whether or not it has been successfully performed. I do not know VBA much, so I have no idea whether or not its possible. I want to do something like this: <code>bool X=MyFunction()</code>. </p>
<p>I am using VBA in the <a href="http://en.wikipedia.org/wiki/HP_QuickTest_Professional" rel="noreferrer">QTP</a> descriptive programming. This does not work:</p>
<pre><code>Function A as Boolean
A=true
End Function
</code></pre>
<p>It says: <code>Expected statement</code></p>
<p>But I cannot see any return type in my method etc.</p> | 6,265,063 | 5 | 0 | null | 2011-06-07 12:19:02.907 UTC | 0 | 2012-08-28 14:45:01.05 UTC | 2012-08-28 14:45:01.05 UTC | null | 1,146,308 | null | 787,426 | null | 1 | 16 | function|vba | 107,070 | <pre><code>function MyFunction() as Boolean
.....
.....
MyFunction = True 'worked
end function
dim a as boolean = MyFunction()
</code></pre> |
6,202,074 | Convert string to int if string is a number | <p>I need to convert a string, obtained from excel, in VBA to an interger. To do so I'm using <code>CInt()</code> which works well. However there is a chance that the string could be something other than a number, in this case I need to set the integer to 0. Currently I have:</p>
<pre><code>If oXLSheet2.Cells(4, 6).Value <> "example string" Then
currentLoad = CInt(oXLSheet2.Cells(4, 6).Value)
Else
currentLoad = 0
End If
</code></pre>
<p>The problem is that I cannot predict all possible non numeric strings which could be in this cell. Is there a way I can tell it to convert if it's an integer and set to 0 if not?</p> | 6,202,469 | 6 | 0 | null | 2011-06-01 13:38:15.617 UTC | 8 | 2020-04-02 18:21:05.98 UTC | 2020-03-20 19:40:52.277 UTC | null | 11,636,588 | null | 779,501 | null | 1 | 72 | excel|vba | 651,141 | <p>Use <code>IsNumeric</code>. It returns true if it's a number or false otherwise.</p>
<pre><code>Public Sub NumTest()
On Error GoTo MyErrorHandler
Dim myVar As Variant
myVar = 11.2 'Or whatever
Dim finalNumber As Integer
If IsNumeric(myVar) Then
finalNumber = CInt(myVar)
Else
finalNumber = 0
End If
Exit Sub
MyErrorHandler:
MsgBox "NumTest" & vbCrLf & vbCrLf & "Err = " & Err.Number & _
vbCrLf & "Description: " & Err.Description
End Sub
</code></pre> |
6,072,197 | Mysql:Trim all fields in database | <pre><code>UPDATE mytable SET mycolumn= LTRIM(RTRIM(mycolumn));
</code></pre>
<p>works fine on trimming columns removing trailer spaces, but how can i adjust it to trim all columns <strong>without having to write each column name</strong> in table ?? cause i kind have a huge database.</p> | 28,275,037 | 7 | 0 | null | 2011-05-20 12:56:10.997 UTC | 3 | 2021-02-19 23:47:54.28 UTC | 2011-05-20 13:23:11.193 UTC | null | 741,156 | null | 741,156 | null | 1 | 28 | mysql|trim | 16,833 | <p>Some years late, but might help others:
This code trims <strong>all</strong> fields of a the table <code>your_table</code>.
Could be expanded to work on the whole database in the same way....</p>
<pre><code>SET SESSION group_concat_max_len = 1000000;
SELECT concat('update your_table set ',
group_concat(concat('`',COLUMN_NAME, '` = trim(`',COLUMN_NAME,'`)')),';')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'your_table'
INTO @trimcmd;
PREPARE s1 from @trimcmd;
EXECUTE s1;
DEALLOCATE PREPARE s1;
</code></pre> |
5,929,878 | Why is the size 127 (prime) better than 128 for a hash-table? | <p>Supposing simple uniform hashing, that being, any given value is equally like to hash into any of the slots of the hash. Why is it better to use a table of size 127 and not 128? I really don't understand what's the problem with the power of 2 numbers. Or how it actually makes any difference at all.</p>
<blockquote>
<p>When using the division method,
we usually avoid certain values
of m (table size). For example, m
should not be a power of 2, since if m
= 2^p , then h(k) is just the p lowest-order bits of k.</p>
</blockquote>
<p>Let's suppose the possible elements are only between 1 and 10000 and I picked the table size as 128. How can 127 be better?
So 128 is 2^6 (1000000) and 127 is 0111111. What difference does this make? All numbers (when hashed) are still going to be the p lowest-order bits of k for 127 too. Did I get something wrong?</p>
<p>I'm looking for some examples as I really can't understand why is this bad. Thanks a lot in advance!</p>
<p>PS: I am aware of:
<a href="https://stackoverflow.com/questions/3980117/hash-table-why-size-should-be-prime">Hash table: why size should be prime?</a></p> | 5,930,358 | 9 | 8 | null | 2011-05-08 19:47:48.72 UTC | 17 | 2017-06-01 09:01:22.01 UTC | 2017-05-23 12:18:06.173 UTC | null | -1 | null | 234,167 | null | 1 | 55 | algorithm|hash|primes | 13,203 | <blockquote>
<p>All numbers (when hashed) are still going to be the p lowest-order bits of k for 127 too. </p>
</blockquote>
<p>That is wrong (or I misunderstood..). <code>k % 127</code> depends on all bits of k. <code>k % 128</code> only depends on the 7 lowest bits. </p>
<hr>
<p>EDIT:</p>
<p>If you have a perfect distribution between 1 and 10,000. <code>10,000 % 127</code> and <code>10,000 % 128</code> both will turn this in a excellent smaller distribution. All buckets will contain 10,000 /128 = 78 (or 79) items.</p>
<p>If you have a distribution between 1 and 10,000 that is biased, because {x, 2x, 3x, ..} occur more often. Then a prime size will give a much, much better distribution as explained in this <a href="https://stackoverflow.com/questions/3980117/hash-table-why-size-should-be-prime/3980446#3980446">answer</a>. (Unless x is exactly that prime size.)</p>
<p>Thus, cutting off the high bits (using a size of 128) is no problem whatsoever <strong>if</strong> the distribution in the lower bits is good enough. But, with real data and real badly designed hash functions, you will need those high bits.</p> |
5,924,777 | How to get last day of last week in sql? | <p>How to get last date of the lastweek in sql? I mean last sunday date using query? </p> | 5,925,176 | 10 | 0 | null | 2011-05-07 23:54:37 UTC | 7 | 2016-10-27 12:09:47.877 UTC | null | null | null | null | 158,008 | null | 1 | 37 | sql|sql-server|tsql | 89,853 | <p>Regardless of the actual DATEFIRST setting, the last Sunday could be found like this:</p>
<pre><code>SELECT DATEADD(day,
-1 - (DATEPART(weekday, GETDATE()) + @@DATEFIRST - 2) % 7,
GETDATE()
) AS LastSunday
</code></pre>
<p>Replace <code>GETDATE()</code> with a parameter <code>@date</code> to get the last Sunday before a particular date.</p> |
25,075,683 | Spring MVC validator annotation + custom validation | <p>I'm working on spring mvc application, where I should aplly validation based on Spring MVC validator. I first step for that I added annotation for class and setup controller and it works fine. And now I need to implement custom validator for perform complex logic, but i want to use existing annotation and just add additional checking.</p>
<p>My User class:</p>
<pre><code>public class User
{
@NotEmpty
private String name;
@NotEmpty
private String login; // should be unique
}
</code></pre>
<p>My validator:</p>
<pre><code>@Component
public class UserValidator implements Validator
{
@Autowired
private UserDAO userDAO;
@Override
public boolean supports(Class<?> clazz)
{
return User.class.equals(clazz) || UsersForm.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors)
{
/*
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "NotEmpty.user");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login", "NotEmpty.user");
*/
User user = (User) target;
if (userDAO.getUserByLogin(user.getLogin()) != null) {
errors.rejectValue("login", "NonUniq.user");
}
}
}
</code></pre>
<p>My controller:</p>
<pre><code>@Controller
public class UserController
{
@Autowired
private UserValidator validator;
@InitBinder
protected void initBinder(final WebDataBinder binder)
{
binder.setValidator(validator);
}
@RequestMapping(value = "/save")
public ModelAndView save(@Valid @ModelAttribute("user") final User user,
BindingResult result) throws Exception
{
if (result.hasErrors())
{
// handle error
} else
{
//save user
}
}
}
</code></pre>
<p>So, Is it possible to use custom validator and annotation together? And if yes how?</p> | 32,066,557 | 3 | 1 | null | 2014-08-01 08:10:03.117 UTC | 10 | 2015-08-18 07:56:17.99 UTC | null | null | null | null | 1,646,082 | null | 1 | 32 | java|spring|validation|spring-mvc | 34,717 | <p>I know this is a kind of old question but, for googlers...</p>
<p>you should use <code>addValidators</code> instead of <code>setValidator</code>. Like following:</p>
<pre><code>@InitBinder
protected void initBinder(final WebDataBinder binder) {
binder.addValidators(yourCustomValidator, anotherValidatorOfYours);
}
</code></pre>
<p>PS: <code>addValidators</code> accepts multiple parameters (ellipsis)</p>
<p>if you checkout the source of <code>org.springframework.validation.DataBinder</code> you will see:</p>
<pre><code>public class DataBinder implements PropertyEditorRegistry, TypeConverter {
....
public void setValidator(Validator validator) {
assertValidators(validator);
this.validators.clear();
this.validators.add(validator);
}
public void addValidators(Validator... validators) {
assertValidators(validators);
this.validators.addAll(Arrays.asList(validators));
}
....
}
</code></pre>
<p>as you see <code>setValidator</code> clears existing (default) validator so <code>@Valid</code> annotation won't work as expected.</p> |
19,793,738 | Joining two datasets to create a single tablix in report builder 3 | <p>I am attempting to join two datasets in to one tablix for a report. The second dataset requires a personID from the first dataset as its parameter.</p>
<p>If i preview this report only the first dataset is shown. but for my final result what i would like to happen is for each row of a student there is a rowgrouping (?) of that one students modules with their month to month attendance. Can this be done in report builder?
<img src="https://i.stack.imgur.com/50nVR.jpg" alt="image of two datasets i would like to join"></p> | 19,798,563 | 2 | 0 | null | 2013-11-05 16:21:21.817 UTC | 4 | 2018-06-21 10:17:03.48 UTC | null | null | null | null | 1,395,607 | null | 1 | 16 | ssrs-2008|reportbuilder3.0 | 107,346 | <p>The best practice here is to do the join within one dataset (i.e. joining in SQL) </p>
<hr>
<p>But in cases that you need data from two separate cubes(SSAS) the only way is the following:</p>
<ol>
<li>Select the main dataset for the Tablix</li>
<li><p>Use the <a href="http://technet.microsoft.com/en-us/library/ee210531.aspx" rel="noreferrer">lookup function</a> to lookup values from the second dataset like this:</p>
<pre><code>=Lookup(Fields!ProductID.Value, Fields!ID.Value, Fields!Name.Value, "Product")
</code></pre>
<p><strong>Note</strong>: The granularity of the second dataset must match the first one.</p></li>
</ol> |
52,551,718 | What use is @TestInstance annotation in JUnit 5? | <p>Can you give a simple explanation of <code>@TestInstance</code> annotation and how it is useful in JUnit 5?</p>
<p>I think we can achieve the same effect probably by <strong>making our fields <em><code>static</code></em></strong>.</p> | 52,552,268 | 5 | 0 | null | 2018-09-28 08:55:25.63 UTC | 11 | 2022-09-20 16:27:33.6 UTC | 2020-09-27 09:35:33.49 UTC | null | 8,583,692 | null | 8,583,692 | null | 1 | 54 | java|unit-testing|testing|junit|junit5 | 34,892 | <p>I think <a href="https://junit.org/junit5/docs/current/user-guide/#writing-tests-test-instance-lifecycle" rel="noreferrer">the docs</a> provide a useful summary:</p>
<blockquote>
<p>If you would prefer that JUnit Jupiter execute all test methods on the same test instance, simply annotate your test class with @TestInstance(Lifecycle.PER_CLASS). When using this mode, a new test instance will be created once per test class. Thus, if your test methods rely on state stored in instance variables, you may need to reset that state in @BeforeEach or @AfterEach methods.</p>
<p>The "per-class" mode has some additional benefits over the default "per-method" mode. Specifically, with the "per-class" mode it becomes possible to declare @BeforeAll and @AfterAll on non-static methods as well as on interface default methods. The "per-class" mode therefore also makes it possible to use @BeforeAll and @AfterAll methods in @Nested test classes.</p>
</blockquote>
<p>But you've probably read that already and you are correct in thinking that making a field static will have the same effect as declaring the field as an instance variable and using <code>@TestInstance(Lifecycle.PER_CLASS)</code>.</p>
<p>So, perhaps the answer to the question "how it could be useful in JUnit 5" is that using a <code>@TestInstance</code> ...</p>
<ul>
<li>Is explicit about your intentions. It could be assumed that use of the static keyword was accidental whereas use of <code>@TestInstance</code> is less likely to be accidental or a result of thoughless copy-n-paste.</li>
<li>Delegates the responsibility for managing scope and lifecycle and clean up to the framework rather than having to remember to manage that yourself.</li>
</ul> |
41,666,130 | export default vs module.exports differences | <p>This works:</p>
<pre><code>import {bar} from './foo';
bar();
// foo.js
module.exports = {
bar() {}
}
</code></pre>
<p>And this works:</p>
<pre><code>import foo from './foo';
foo.bar();
// foo.js
export default {
bar() {}
}
</code></pre>
<p>So why doesn't this work?</p>
<pre><code>import {bar} from './foo';
bar();
// foo.js
export default {
bar() {}
}
</code></pre>
<p>It throws <code>TypeError: (0 , _foo.bar) is not a function</code>.</p> | 41,666,401 | 3 | 0 | null | 2017-01-15 20:46:53.873 UTC | 24 | 2022-02-20 22:17:40.863 UTC | null | null | null | null | 29,493 | null | 1 | 37 | javascript|ecmascript-6 | 40,480 | <p>When you have</p>
<pre><code>export default {
bar() {}
}
</code></pre>
<p>The actual object exported is of the following form:</p>
<pre><code>exports: {
default: {
bar() {}
}
}
</code></pre>
<p>When you do a simple import (e.g., <code>import foo from './foo';</code>) you are actually getting the default object inside the import (i.e., <code>exports.default</code>). This will become apparent when you run babel to compile to ES5.</p>
<p>When you try to import a specific function (e.g., <code>import { bar } from './foo';</code>), as per your case, you are actually trying to get <code>exports.bar</code> instead of <code>exports.default.bar</code>. Hence why the bar function is undefined.</p>
<p>When you have just multiple exports:</p>
<pre><code>export function foo() {};
export function bar() {};
</code></pre>
<p>You will end up having this object:</p>
<pre><code>exports: {
foo() {},
bar() {}
}
</code></pre>
<p>And thus <code>import { bar } from './foo';</code> will work. This is the similar case with <code>module.exports</code> you are essentially storing an exports object as above. Hence you can import the bar function.</p>
<p>I hope this is clear enough.</p> |
21,760,762 | asp.net Web Api routing not working | <p>Here is my routing configuration:</p>
<pre><code>config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
</code></pre>
<p>And, here is my controller:</p>
<pre><code>public class ProductsController : ApiController
{
[AcceptVerbs("Get")]
public object GetProducts()
{
// return all products...
}
[AcceptVerbs("Get")]
public object Product(string name)
{
// return the Product with the given name...
}
}
</code></pre>
<p>When I try <code>api/Products/GetProducts/</code>, it works. <code>api/Products/Product?name=test</code> also works, but <code>api/Products/Product/test</code> does not work. What am I doing wrong?</p>
<p><strong>UPDATE:</strong></p>
<p>Here's what I get when I try <code>api/Products/Product/test</code>:</p>
<pre><code>{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:42676/api/Products/Product/test'.",
"MessageDetail": "No action was found on the controller 'Products' that matches the request."
}
</code></pre> | 21,761,061 | 3 | 0 | null | 2014-02-13 17:05:35.783 UTC | 6 | 2014-02-13 18:59:50.393 UTC | 2014-02-13 17:17:36.847 UTC | null | 781,366 | null | 781,366 | null | 1 | 12 | asp.net|asp.net-web-api|routing | 40,734 | <p>This is because of your routing settings and its default values. You have two choices.</p>
<p>1) By changing the route settings to match the Product() parameter to match the URI.</p>
<pre><code>config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{name}", // removed id and used name
defaults: new { name = RouteParameter.Optional }
);
</code></pre>
<p>2) The other and recommended way is to use the correct method signature attribute.</p>
<pre><code>public object Product([FromUri(Name = "id")]string name){
// return the Product with the given name
}
</code></pre>
<p>This is because the method is expecting a parameter <strong>id</strong> when requesting
<em>api/Products/Product/test</em> rather than looking for a <strong>name</strong> parameter.</p> |
39,939,143 | Parse JSON response with Swift 3 | <p>I have JSON looking like this:</p>
<pre><code>{"posts":
[
{
"id":"1","title":"title 1"
},
{
"id":"2","title":"title 2"
},
{
"id":"3","title":"title 3"
},
{
"id":"4","title":"title 4"
},
{
"id":"5","title":"title 5"
}
],
"text":"Some text",
"result":1
}
</code></pre>
<p>How can I parse that JSON with Swift 3?</p>
<p>I have this:</p>
<pre><code>let url = URL(string: "http://domain.com/file.php")!
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print("request failed \(error)")
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: String], let result = json["result"] {
// Parse JSON
}
} catch let parseError {
print("parsing error: \(parseError)")
let responseString = String(data: data, encoding: .utf8)
print("raw response: \(responseString)")
}
}
task.resume()
}
</code></pre> | 39,939,465 | 4 | 0 | null | 2016-10-09 01:46:41.84 UTC | 3 | 2019-11-26 20:59:40.13 UTC | 2016-10-09 01:58:09.5 UTC | null | 5,644,794 | null | 3,051,755 | null | 1 | 13 | ios|json|swift|swift3 | 53,273 | <p>Use this to parse your data:</p>
<pre><code>let url = URL(string: "http://example.com/file.php")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
let posts = json["posts"] as? [[String: Any]] ?? []
print(posts)
} catch let error as NSError {
print(error)
}
}).resume()
</code></pre>
<p>Use <code>guard</code> to check if you have data and that error is empty.</p>
<h2>Swift 5.x version</h2>
<pre><code>let url = URL(string: "http://example.com/file.php")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any]
let posts = json?["posts"] as? [[String: Any]] ?? []
print(posts)
} catch {
print(error)
}
}).resume()
</code></pre> |
36,977,735 | Display Gradle output in console in Intellij IDEA 2016.1.1 | <p>When running Gradle task from IDEA:</p>
<p><a href="https://i.stack.imgur.com/gDzFW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gDzFW.png" alt="IDEA Gradle window" /></a></p>
<p>console output looks like:</p>
<p><a href="https://i.stack.imgur.com/89cMd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/89cMd.png" alt="enter image description here" /></a></p>
<p>As one can see, <code>bootRun</code> task failed. But I can't find the reason of the fail.</p>
<p>Is there a way to make Gradle output be displayed in Intellij Console when starting tasks from Gradle window?</p> | 37,002,644 | 3 | 0 | null | 2016-05-02 08:01:51.317 UTC | 10 | 2022-02-22 06:06:16.49 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 4,423,968 | null | 1 | 112 | intellij-idea|gradle | 28,193 | <p>You can click the icon marked in the image bellow</p>
<blockquote>
<p>Toggle tasks executions/text mode</p>
</blockquote>
<p>That will switch to the console log of your build and you can see what went wrong.</p>
<p><a href="https://i.stack.imgur.com/jRaqN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jRaqN.png" alt="enter image description here"></a></p>
<p><strong>UPDATE:</strong> As of 2019.2.3, you don't need to toggle task/console view as you can see now both at the same time:</p>
<p><a href="https://i.stack.imgur.com/ToPgm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ToPgm.png" alt="enter image description here"></a></p> |
24,057,040 | Content-Security-Policy Spring Security | <p>assuming a working hello world example of spring security and spring mvc.</p>
<p>when i take a trace with wireshark i see the following flags on the http request</p>
<pre><code>X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
Set-Cookie: JSESSIONID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX; Path=/; Secure; HttpOnly
</code></pre>
<p>i would like to add this to my headers:</p>
<pre><code>Content-Security-Policy: script-src 'self'
</code></pre>
<p>I know that the X-Frame-Options is doing almost the same job, but still it makes me sleep better.
Now i guess that i would need to do it under the configure function of my spring security configuration however i do not know how exactly, i.e. i suppose
.headers().something.something(self) </p>
<pre><code> @Override
protected void configure(HttpSecurity http) throws Exception {
http
// .csrf().disable()
// .headers().disable()
.authorizeRequests()
.antMatchers( "/register",
"/static/**",
"/h2/**",
"/resources/**",
"/resources/static/css/**",
"/resources/static/img/**" ,
"/resources/static/js/**",
"/resources/static/pdf/**"
).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
</code></pre> | 24,102,032 | 3 | 0 | null | 2014-06-05 09:55:54.46 UTC | 6 | 2018-05-23 07:30:16.36 UTC | 2017-09-21 16:56:57.533 UTC | null | 352,708 | null | 1,816,260 | null | 1 | 22 | spring|security|spring-security|content-security-policy | 55,354 | <p>Simply use the addHeaderWriter method like this: </p>
<pre><code>@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// ...
.headers()
.addHeaderWriter(new StaticHeadersWriter("X-Content-Security-Policy","script-src 'self'"))
// ...
}
}
</code></pre>
<p>Note that as soon as you specify any headers that should be included, then only those headers will be include.</p>
<p>To include the default headers you can do:</p>
<pre><code>http
.headers()
.contentTypeOptions()
.xssProtection()
.cacheControl()
.httpStrictTransportSecurity()
.frameOptions()
.addHeaderWriter(new StaticHeadersWriter("X-Content-Security-Policy","script-src 'self'"))
// ...
</code></pre>
<p>You can refer to the <a href="http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#headers-custom">spring security documentation</a>.</p> |
21,809,749 | Drop Column with foreign key in MySQL | <p>I have the following 2 tables:</p>
<pre><code>CREATE TABLE `personal_info` (
`p_id` int(11) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
`initials` text NOT NULL,
`surname` text NOT NULL,
`home_lang` int(11) NOT NULL,
PRIMARY KEY (`p_id`),
KEY `home_lang` (`home_lang`),
CONSTRAINT `personal_info_ibfk_1` FOREIGN KEY (`home_lang`) REFERENCES `language_list` (`ll_id`)
) ENGINE=InnoDB AUTO_INCREMENT=44 DEFAULT CHARSET=latin1
CREATE TABLE `language_list` (
`ll_id` int(11) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
PRIMARY KEY (`ll_id`)
) ENGINE=InnoDB AUTO_INCREMENT=73 DEFAULT CHARSET=latin1
</code></pre>
<p>I am trying to remove a column from a table with the following:</p>
<pre><code>ALTER TABLE `personal_info` DROP `home_lang`
</code></pre>
<p>But cannot do it since I recieve this error:</p>
<pre><code>#1025 - Error on rename of '.\MyDB\#sql-112c_82' to '.\MyDB\personal_info' (errno: 150)
</code></pre>
<p>I have tried to first remove the index and then remove the column with this:</p>
<pre><code>ALTER TABLE personal_info DROP INDEX home_lang
</code></pre>
<p>But then I get the following error:</p>
<pre><code>#1553 - Cannot drop index 'home_lang': needed in a foreign key constraint
</code></pre>
<p>So I tried to drop the foreign key:</p>
<pre><code>ALTER TABLE personal_info DROP FOREIGN KEY home_lang
</code></pre>
<p>But received this error:</p>
<pre><code>#1025 - Error on rename of '.\MyDB\personal_info' to '.\MyDB\#sql2-112c-8d' (errno: 152)
</code></pre>
<p>I have also tried to first set all the values to null:</p>
<pre><code>update personal_info set home_lang = null
</code></pre>
<p>But then received this error:</p>
<pre><code>#1452 - Cannot add or update a child row: a foreign key constraint fails (`MyDB`.`personal_info`, CONSTRAINT `personal_info_ibfk_1` FOREIGN KEY (`home_lang`) REFERENCES `language_list` (`ll_id`))
</code></pre>
<p>And now I am stuck. I have tried a few things but just cannot get the column removed. I am not allowed to alter the DB in any way other than removing the column. </p> | 21,809,780 | 3 | 1 | null | 2014-02-16 10:01:40.5 UTC | 2 | 2019-11-18 09:34:06.093 UTC | null | null | null | null | 1,759,954 | null | 1 | 21 | mysql|sql|database|database-design | 55,039 | <p>Your <code>DROP FOREIGN KEY</code> syntax is using the wrong key name. It's trying to drop your "plain" index on the <code>home_lang</code> field. It's NOT the foreign key itself.</p>
<pre><code>CONSTRAINT `personal_info_ibfk_1` FOREIGN KEY (`home_lang`) REFERENCES `language_list` (`ll_id`)
^^^^^^^^^^^^^^^^^^^^^--- THIS is the name of the foreign key
</code></pre>
<p>Try:</p>
<pre><code>ALTER TABLE personal_info DROP FOREIGN KEY `personal_info_ibfk_1`
</code></pre> |
33,078,003 | Android 6.0 Permission Error | <p>I'm getting this error:</p>
<pre><code>getDeviceId: Neither user 10111 nor current process has android.permission.READ_PHONE_STATE.
at android.os.Parcel.readException(Parcel.java:1599)
at android.os.Parcel.readException(Parcel.java:1552)
</code></pre>
<p>I had given it in manifest though. Is there any changes regarding <strong>Android 6.XX Marshmallow</strong> devices? I need to give <code>READ_PHONE_STATE</code> permission for getting device's IMEI. Pls. Help.</p> | 33,078,679 | 5 | 1 | null | 2015-10-12 09:44:36.027 UTC | 9 | 2018-11-08 05:02:10.703 UTC | 2015-10-16 10:14:46.297 UTC | null | 2,527,204 | null | 3,500,742 | null | 1 | 21 | android | 45,714 | <p>Yes permissions have changed on Android M. Permissions are now requested at runtime as opposed to install time previous to Android M.</p>
<p>You can check out the docs <a href="https://developer.android.com/training/permissions/index.html" rel="noreferrer">here</a></p>
<blockquote>
<p>This release introduces a new permissions model, where users can now directly manage app permissions at runtime. This model gives users improved visibility and control over permissions, while streamlining the installation and auto-update processes for app developers. Users can grant or revoke permissions individually for installed apps.</p>
<p>On your apps that target Android 6.0 (API level 23) or higher, make sure to check for and request permissions at runtime. To determine if your app has been granted a permission, call the new checkSelfPermission() method. To request a permission, call the new requestPermissions() method. Even if your app is not targeting Android 6.0 (API level 23), you should test your app under the new permissions model.</p>
<p>For details on supporting the new permissions model in your app, see Working with System Permissionss. For tips on how to assess the impact on your app, see Permissions Best Practices.</p>
</blockquote>
<p>To check for permissions you have to check like this, taken from <a href="https://github.com/googlesamples/android-RuntimePermissions" rel="noreferrer">github</a></p>
<pre><code>public class MainActivity extends SampleActivityBase
implements ActivityCompat.OnRequestPermissionsResultCallback {
public static final String TAG = "MainActivity";
/**
* Id to identify a camera permission request.
*/
private static final int REQUEST_CAMERA = 0;
// Whether the Log Fragment is currently shown.
private boolean mLogShown;
private View mLayout;
/**
* Called when the 'show camera' button is clicked.
* Callback is defined in resource layout definition.
*/
public void showCamera(View view) {
// Check if the Camera permission is already available.
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// Camera permission has not been granted.
requestCameraPermission();
} else {
// Camera permissions is already available, show the camera preview.
showCameraPreview();
}
}
/**
* Requests the Camera permission.
* If the permission has been denied previously, a SnackBar will prompt the user to grant the
* permission, otherwise it is requested directly.
*/
private void requestCameraPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
// Provide an additional rationale to the user if the permission was not granted
// and the user would benefit from additional context for the use of the permission.
// For example if the user has previously denied the permission.
Snackbar.make(mLayout, R.string.permission_camera_rationale,
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, new View.OnClickListener() {
@Override
public void onClick(View view) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA);
}
})
.show();
} else {
// Camera permission has not been granted yet. Request it directly.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA);
}
}
/**
* Display the {@link CameraPreviewFragment} in the content area if the required Camera
* permission has been granted.
*/
private void showCameraPreview() {
getSupportFragmentManager().beginTransaction()
.replace(R.id.sample_content_fragment, CameraPreviewFragment.newInstance())
.addToBackStack("contacts")
.commit();
}
/**
* Callback received when a permissions request has been completed.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA) {
// Received permission result for camera permission.est.");
// Check if the only required permission has been granted
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Camera permission has been granted, preview can be displayed
Snackbar.make(mLayout, R.string.permision_available_camera,
Snackbar.LENGTH_SHORT).show();
} else {
Snackbar.make(mLayout, R.string.permissions_not_granted,
Snackbar.LENGTH_SHORT).show();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLayout = findViewById(R.id.sample_main_layout);
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
RuntimePermissionsFragment fragment = new RuntimePermissionsFragment();
transaction.replace(R.id.sample_content_fragment, fragment);
transaction.commit();
}
}
}
</code></pre> |
9,530,493 | how to create pinterest style hiding/unhiding nav/tab bar? | <p>How do I create a hiding/unhiding nav bar like what pinterest and many other apps is doing? I know the basic idea is to use the UIScrollView delegate and detect whether I am scrolling up or down and show the nav bar based on that. So should I also adjust the navcontroller view height if the nav bar is hidden? How does this work?</p> | 9,545,487 | 3 | 0 | null | 2012-03-02 09:00:57.02 UTC | 9 | 2013-06-05 22:20:22.803 UTC | null | null | null | null | 721,937 | null | 1 | 12 | iphone|objective-c|ios|ipad|uinavigationcontroller | 13,179 | <p>I have a sample project located on github that does exactly the pinterest/piictu style 'hide the UINavigationController / UITabBarController stuff'</p>
<p><a href="https://github.com/tonymillion/ExpandingView" rel="noreferrer">https://github.com/tonymillion/ExpandingView</a></p> |
9,100,606 | Cannot read configuration file due to insufficient permissions | <p>I am trying to test my Web Service on an IIS instance on my local machine before I promote to a windows server 2008 environment. I get this when I attempt to browse to the service. I have created a custom application pool that this service will run under btw. So I am guessing that that application ID does not have permissions to access that folder etc... I get this little detail btw...</p>
<p>"This error occurs when there is a problem reading the configuration file for the Web server or Web application. In some cases, the event logs may contain more information about what caused this error."</p>
<p>I am thinking I need to give that application identity permissions, but I am unsure how to accomplish this. </p>
<p>Is there another way to get this done?</p> | 9,766,024 | 9 | 0 | null | 2012-02-01 17:45:53.263 UTC | 4 | 2022-08-30 09:47:03.62 UTC | null | null | null | null | 729,820 | null | 1 | 31 | iis|applicationpoolidentity | 100,930 | <p>Not sure whether this is too late for you.</p>
<p>The <strong>IIS</strong> website is run by either <strong>USERS</strong> or <strong>IIS_IUSRS</strong>.</p>
<p>Try to do following:</p>
<ul>
<li>From Windows Explorer</li>
<li>Right click on the folder pointed by the web</li>
<li>Go to security tab</li>
<li>Add <strong><code>computername\IIS_IUSRS</code></strong> or <strong><code>computername\USERS</code></strong> with <strong>Read</strong> permission.</li>
</ul> |
9,133,024 | www-data permissions? | <p>So I have a directory in /var/www (called cake) and I need to allow www-data to write to it, but I also want to write to it (without having to use sudo). I'm afraid to change the permissions to 777 in case some other user on my machine (or a hacker) attempts to modify files in that directory. How do I only allow access for myself and Apache's www-data?</p> | 9,133,067 | 3 | 0 | null | 2012-02-03 17:43:02.97 UTC | 98 | 2021-03-01 07:56:20.16 UTC | null | null | null | null | 1,015,599 | null | 1 | 122 | apache|permissions|sudo | 254,531 | <pre><code>sudo chown -R yourname:www-data cake
</code></pre>
<p>then</p>
<pre><code>sudo chmod -R g+s cake
</code></pre>
<p>First command changes owner and group.</p>
<p>Second command adds s attribute which will keep new files and directories within cake having the same group permissions.</p> |
34,211,131 | New React Native project with old version of react native | <p>I am trying to create a new react native project which should utilize an older version of react-native.</p>
<p>The result I would like would be to do something like: <code>react-native init MyProject</code> but have the version of react-native it uses be <code>0.13.2</code>.</p>
<p>However, there doesn't seem to be any options with <code>react-native-cli</code> for initializing with old versions of react-native.</p>
<p>Performing <code>react-native init MyProject</code> and then dowgrading react-native in <code>package.json</code> also does not work because the <code>init</code> command installs a bunch of xcode templates which are used to build the app and there is no <code>dowgrade</code> command which will dowgrade these templates. (There is an <code>upgrade</code> command.)</p>
<p>I tried downgrading my version of react-native-cli to <code>0.1.4</code> which was current when react-native <code>0.13</code> was current, but this did not work. From looking at the cli source, it seems it always initializes with just the newest version of react-native.</p>
<p>I realize this is pretty weird to want to start a new project at an old version, but I have a weird set of requirements that are forcing this.</p> | 41,526,461 | 9 | 1 | null | 2015-12-10 20:28:46.433 UTC | 16 | 2022-04-22 03:26:22.757 UTC | null | null | null | null | 1,617,560 | null | 1 | 62 | ios|xcode|reactjs|react-native | 38,901 | <p>There is a new parameter in <code>react-native init</code> that allows just this. Try: </p>
<pre><code>react-native init --version="[email protected]" MyNewApp
</code></pre>
<p>Here my <a href="https://github.com/facebook/react-native/issues/4723" rel="noreferrer">source</a>. I have successfully tested it with <code>react-native-cli</code> 2.0.1.</p> |
10,339,930 | Why can I edit the contents of a final array in Java? | <p>The following code in Java uses a <code>final</code> array of <code>String</code>.</p>
<pre><code>final public class Main {
public static final String[] CONSTANT_ARRAY = {"I", "can", "never", "change"};
public static void main(String[] args) {
for (int x = 0; x < CONSTANT_ARRAY.length; x++) {
System.out.print(CONSTANT_ARRAY[x] + " ");
}
}
}
</code></pre>
<p>It displays the following output on the console.</p>
<blockquote>
<pre><code>I can never change
</code></pre>
</blockquote>
<p>If we try to reassign the declared <code>final</code> array of type <code>String</code>, we cause an error:</p>
<pre><code>final public class Main {
public static final String[] CONSTANT_ARRAY = {"I", "can", "never", "change"};
public static void main(String[] args) {
CONSTANT_ARRAY={"I", "can", "never", "change"}; //Error - can not assign to final variable CONSTANT_ARRAY.
for (int x = 0; x < CONSTANT_ARRAY.length; x++) {
System.out.print(CONSTANT_ARRAY[x] + " ");
}
}
}
</code></pre>
<blockquote>
<p>Error: cannot assign to final variable <code>CONSTANT_ARRAY</code>.</p>
</blockquote>
<p>However, the following code works:</p>
<pre><code>final public class Main {
public static final String[] CONSTANT_ARRAY = {"I", "can", "never", "change"};
public static void main(String[] args) {
CONSTANT_ARRAY[2] = "always"; //Compiles fine.
for (int x = 0; x < CONSTANT_ARRAY.length; x++) {
System.out.print(CONSTANT_ARRAY[x] + " ");
}
}
}
</code></pre>
<p>It displays</p>
<blockquote>
<pre><code>I can always change
</code></pre>
</blockquote>
<p>This mean that we could manage to modify the value of the <code>final</code> array of type <code>String</code>. Can we modify the entire array in this way without violating the immutable rule of <code>final</code>?</p> | 10,340,003 | 9 | 1 | null | 2012-04-26 19:18:48.9 UTC | 20 | 2022-08-19 18:24:58.063 UTC | 2022-08-19 18:24:58.063 UTC | null | 2,756,409 | null | 1,037,210 | null | 1 | 64 | java|arrays|final | 72,829 | <p><code>final</code> in Java affects the <em>variable</em>, it has nothing to do with the object you are assigning to it.</p>
<pre><code>final String[] myArray = { "hi", "there" };
myArray = anotherArray; // Error, you can't do that. myArray is final
myArray[0] = "over"; // perfectly fine, final has nothing to do with it
</code></pre>
<p><strong>Edit to add from comments:</strong> Note that I said <em>object you are assigning to it</em>. In Java an array is an object. This same thing applies to any other object:</p>
<pre><code>final List<String> myList = new ArrayList<String>():
myList = anotherList; // error, you can't do that
myList.add("Hi there!"); // perfectly fine.
</code></pre> |
10,521,061 | How to get an MD5 checksum in PowerShell | <p>I would like to calculate an <a href="http://en.wikipedia.org/wiki/MD5">MD5</a> checksum of some content. How do I do this in PowerShell?</p> | 10,521,162 | 19 | 1 | null | 2012-05-09 17:24:26.913 UTC | 63 | 2022-01-14 07:41:27.777 UTC | 2014-07-05 09:20:35.1 UTC | null | 63,550 | null | 184,773 | null | 1 | 214 | powershell|powershell-2.0 | 353,743 | <p>Starting in PowerShell version 4, this is easy to do for files out of the box with the <a href="https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Get-FileHash?view=powershell-4.0" rel="noreferrer"><code>Get-FileHash</code></a> cmdlet:</p>
<pre><code>Get-FileHash <filepath> -Algorithm MD5
</code></pre>
<p>This is certainly preferable since it avoids the problems the solution for older PowerShell offers as identified in the comments (uses a stream, closes it, and supports large files).</p>
<p>If the content is a string:</p>
<pre><code>$someString = "Hello, World!"
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$utf8 = New-Object -TypeName System.Text.UTF8Encoding
$hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($someString)))
</code></pre>
<hr />
<p><strong>For older PowerShell version</strong></p>
<p>If the content is a file:</p>
<pre><code>$someFilePath = "C:\foo.txt"
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))
</code></pre> |
18,919,845 | How to Set up PHP Test Server in Dreamweaver? | <p>I am trying to setup a PHP server so that I could use the "Live" feature in Dreamweaver, in addition to being able to preview in my browser without having to upload the .php file via an FTP application every time, which is not efficient when I want to do quick small previews.</p>
<p>I have setup a new website and selected a folder for the site on my local drive.</p>
<p>For the server, I have the following information (I don't know how much of it is relevant):</p>
<ul>
<li>Remote: Yes </li>
<li>Test: Yes </li>
<li>Server Name: Server </li>
<li>Connect using: FTP </li>
<li>FTP Address: <em>my domain name</em></li>
<li>Username: <em>my username</em> </li>
<li>Password: <em>my password</em> </li>
<li>Port: 21 </li>
<li>Root directory: <em>blank</em> </li>
<li>Use passive FTP: Yes </li>
<li>Use IPV6 Transfer Mode: No </li>
<li>Use proxy: No </li>
<li>Use FTP performance optimization: Yes </li>
<li>Maintain Synchronization Information: Yes</li>
<li>Automatically upload files to server on save: Yes </li>
<li>Enable file checkout: No </li>
<li>Server model: PHP MySQL</li>
</ul>
<p>When I test the server, it is successful and I am able to get the site/server to show up in "Manage Sites". However, when I want to test my .php file on the "Live" preview panel or as a preview in Chrome, I get the error message: "Dynamically-related files could not be resolved because the site definition is not correct for this server." When I upload the .php file to my FTP manually, the page displays properly but when I try doing this it either does not work or the Chrome preview mode just spits out the entire raw code.</p>
<p>I tried and Googled, but I could not find a solution to this problem. Any help would be greatly appreciated.</p>
<p><em><strong>Side note:</strong> I have my hosting from GoDaddy and the server from there is based on MySQL.</em></p>
<p>Thank you.</p> | 19,004,953 | 2 | 2 | null | 2013-09-20 14:55:42.66 UTC | 2 | 2015-04-26 10:29:53.77 UTC | null | null | null | null | 2,431,040 | null | 1 | 4 | php|mysql|sql-server|testing|dreamweaver | 44,824 | <p>To set up PHP server with dreamweaver follow the following steps</p>
<p>Step 1. </p>
<p>Make Sure you have MAMA(For MAC OX) or WAMP (Window OS) install. If you dont know where to get then click this link
<a href="http://www.mamp.info/en/downloads/" rel="noreferrer">http://www.mamp.info/en/downloads/</a> and install in you system. (make sure if you are using skype close it because skype and mamp use same port. Later you can chage the port for Skype) </p>
<p>Step 2:</p>
<p>Open Dreamweaver and choose</p>
<pre><code>Site > New Site
</code></pre>
<p><img src="https://i.stack.imgur.com/724uc.png" alt="enter image description here"></p>
<p>Step 3:</p>
<p>Type your site name and click on browse button to locate you htdocs folder (which is normally inside you mamp/wamp folder on you root directory).
<img src="https://i.stack.imgur.com/pNU3y.png" alt="enter image description here"></p>
<p>Step 4:</p>
<p>Select Server from left hand side and click on add (+) sign.</p>
<p><img src="https://i.stack.imgur.com/BOZgT.png" alt="enter image description here"></p>
<p>Follow the following:</p>
<pre><code>Server Name: localhost
Connect Using: Local/Network
Server Folder: (this is wehre your site located (i.e. inside htdocs folder)
Web URL: http://localhost/yourSiteName (yourSiteName is name of your folder)
Click Save.
</code></pre>
<p><img src="https://i.stack.imgur.com/e3u79.png" alt="enter image description here"></p>
<p>Step 5:</p>
<p>Check <strong>Testing</strong> and click <strong>SAVE</strong></p>
<p><img src="https://i.stack.imgur.com/1Z4VQ.png" alt="enter image description here"></p>
<p>Step 6:</p>
<p>Last but not least Open File Panel</p>
<pre><code>Window > Files
</code></pre>
<p><img src="https://i.stack.imgur.com/lNpRv.png" alt="enter image description here"></p>
<p>Now create a new file and Save it inside you folder.</p>
<p>Thats it you are set mate.</p>
<p>hope thats helps
Cheers!</p> |
36,748,923 | How to escape a backslash in Powershell | <p>I'm writing a powershell program to replace strings using</p>
<pre><code>-replace "$in", "$out"
</code></pre>
<p>It doesn't work for strings containing a backslash, how can I do to escape it?</p> | 36,749,463 | 2 | 1 | null | 2016-04-20 15:45:08.153 UTC | 1 | 2017-07-29 02:19:52.78 UTC | null | null | null | null | 4,472,146 | null | 1 | 13 | windows|powershell | 40,562 | <p>The <code>-replace</code> operator uses regular expressions, which treat backslash as a special character. You can use double backslash to get a literal single backslash.</p>
<p>In your case, since you're using variables, I assume that you won't know the contents at design time. In this case, you should run it through <code>[RegEx]::Escape()</code>:</p>
<pre><code>-replace [RegEx]::Escape($in), "$out"
</code></pre>
<p>That method escapes any characters that are special to regex with whatever is needed to make them a literal match (other special characters include <code>.</code>,<code>$</code>,<code>^</code>,<code>()</code>,<code>[]</code>, and more.</p> |
18,191,779 | HTML5/JS - Start several webworkers | <p>I'm currently writing on a program, where I have to deal with huge arrays. I can however split those arrays. My plan now is, to process the arrays in different web workers. I have however never worked with them and do have several questions:</p>
<p><strong>1.</strong> How would I run several web workers? I tried a for-loop looking like that:</p>
<pre><code>for(i = 0; i < eD.threads; i++){
//start workers here
var worker = new Worker("js/worker/imageValues.js");
worker.postMessage(brightness, cD.pixels[i]);
}
</code></pre>
<p>Here I do get the error, that the object couldn't be cloned. Which seems logical. I guess it would be better to save them in an Array?</p>
<p><strong>2.</strong> How would I control that all have finished their work? (I need to reassembly the array and work with it later)</p>
<p><strong>3.</strong> How many web workers really bring an improvement?</p>
<p><strong>4.</strong> Is there any advanced tutorial, besides the MDN-entry?</p>
<p>Thank you!</p> | 18,192,122 | 2 | 4 | null | 2013-08-12 16:11:54.807 UTC | 11 | 2016-06-30 15:49:27.617 UTC | null | null | null | null | 1,994,642 | null | 1 | 9 | javascript|arrays|html|performance|web-worker | 13,669 | <blockquote>
<p>1. How would I run several web workers? I tried a for-loop looking like that:</p>
</blockquote>
<p>There's no problem with creating more than one worker, even if you don't keep track of them in an array. See below.</p>
<blockquote>
<p>2. How would I control that all have finished their work? (I need to reassembly the array and work with it later)</p>
</blockquote>
<p>They can post a message back to you when they're done, with the results. Example below.</p>
<blockquote>
<p>3. How many web workers really bring an improvement?</p>
</blockquote>
<p>How long is a piece of string? :-) The answer will depend entirely on the target machine on which this is running. A lot of people these days have four or more cores on their machines. Of course, the machine is doing a lot of other things as well. You'll have to tune for your target environment.</p>
<blockquote>
<p>4. Is there any advanced tutorial, besides the MDN-entry?</p>
</blockquote>
<p>There isn't a lot "advanced" about web workers. :-) I found <a href="http://www.html5rocks.com/en/tutorials/workers/basics/" rel="noreferrer">this article</a> was sufficient.</p>
<p>Here's an example running five workers and watching for them to be done:</p>
<p>Main window:</p>
<pre><code>(function() {
var n, worker, running;
display("Starting workers...");
running = 0;
for (n = 0; n < 5; ++n) {
workers = new Worker("worker.js");
workers.onmessage = workerDone;
workers.postMessage({id: n, count: 10000});
++running;
}
function workerDone(e) {
--running;
display("Worker " + e.data.id + " is done, result: " + e.data.sum);
if (running === 0) { // <== There is no race condition here, see below
display("All workers complete");
}
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</code></pre>
<p><code>worker.js</code>:</p>
<pre><code>this.onmessage = function(e) {
var sum, n;
sum = 0;
for (n = 0; n < e.data.count; ++n) {
sum += n;
}
this.postMessage({id: e.data.id, sum: sum});
};
</code></pre>
<p>About the race condition that doesn't exist: If you think in terms of true pre-emptive threading, then you might think: I could create a worker, increment <code>running</code> to <code>1</code>, and then before I create the next worker I could get the message from the first one that it's done, decrement <code>running</code> to <code>0</code>, and mistakenly think all the workers were done.</p>
<p>That can't happen in the environment web workers work in. Although the environment is welcome to start the worker as soon as it likes, and a worker could well finish before the code starting the workers finished, all that would do is <em>queue</em> a call to the <code>workerDone</code> function for the main JavaScript thread. There is no pre-empting. And so we know that all workers have been started before the first call to <code>workerDone</code> is actually executed. Thus, when <code>running</code> is <code>0</code>, we know they're all finished.</p>
<p>Final note: In the above, I'm using <code>onmessage = ...</code> to hook up event handlers. Naturally that means I can only have one event handler on the object I'm doing that with. If you need to have multiple handlers for the <code>message</code> event, use <code>addEventListener</code>. All browsers that support web workers support <code>addEventListener</code> on them (youdon't have to worry about the IE <code>attachEvent</code> thing).</p> |
18,216,291 | Jquery "if this and if that" then do this | <p>This should be so simple, but it's not working for me. I want to say:</p>
<p>If this doesn't have the class "current" AND if the body class does not equal "home", then do this....</p>
<p>Here is what I'm trying (among other things) to no avail. Only the first conditional works.</p>
<pre><code>$(".nav1 > ul > li").mouseleave(function() {
if ( (!$(this).hasClass("current")) || (!$(body).hasClass("home")) ){
$(this).find(".nav-overlay").show();
}
});
</code></pre>
<p>What am I doing wrong? Thank you!</p>
<p>UPDATE FOR CLARITY:</p>
<p>I only want to show ".nav-overlay" when the following conditions are true:</p>
<ol>
<li>You are not on the homepage (body class="home")
AND </li>
<li>The ".nav1 > ul > li" class does not equal "current"</li>
</ol> | 18,216,326 | 2 | 3 | null | 2013-08-13 18:16:09.023 UTC | 3 | 2013-08-13 18:28:56.743 UTC | 2013-08-13 18:28:56.743 UTC | null | 2,274,595 | null | 2,274,595 | null | 1 | 17 | jquery|conditional-statements | 92,263 | <p>Try <code>$("body")</code> and <code>&&</code>:</p>
<pre><code> if ( (!$(this).hasClass("current")) && (!$("body").hasClass("home")) ){
//...
</code></pre>
<p>Or this way , it is shorter:</p>
<pre><code> if ( !$(this).is(".current") && !$("body").is(".home") ){
//...
</code></pre> |
35,525,574 | How to use database connections pool in Sequelize.js | <p>I need some clarification about what the pool is and what it does. The docs say Sequelize will setup a connection pool on initialization so you should ideally only ever create one instance per database.</p>
<pre><code>var sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql'|'mariadb'|'sqlite'|'postgres'|'mssql',
pool: {
max: 5,
min: 0,
idle: 10000
},
// SQLite only
storage: 'path/to/database.sqlite'
});
</code></pre> | 44,193,117 | 3 | 1 | null | 2016-02-20 16:02:19.363 UTC | 10 | 2018-11-05 19:34:58.463 UTC | 2016-02-20 16:35:41.077 UTC | null | 405,623 | null | 5,508,854 | null | 1 | 34 | node.js|sequelize.js | 48,330 | <p>When your application needs to retrieve data from the database, it creates a database connection. Creating this connection involves some overhead of time and machine resources for both your application and the database. Many database libraries and ORM's will try to reuse connections when possible, so that they do not incur the overhead of establishing that DB connection over and over again. The <code>pool</code> is the collection of these saved, reusable connections that, in your case, Sequelize pulls from. Your configuration of </p>
<pre><code>pool: {
max: 5,
min: 0,
idle: 10000
}
</code></pre>
<p>reflects that your pool should:</p>
<ol>
<li>Never have more than five open connections (<code>max: 5</code>)</li>
<li>At a minimum, have zero open connections/maintain no minimum number of connections (<code>min: 0</code>)</li>
<li>Remove a connection from the pool after the connection has been idle (not been used) for 10 seconds (<code>idle: 10000</code>)</li>
</ol>
<p>tl;dr: Pools are a good thing that help with database and overall application performance, but if you are too aggressive with your pool configuration you may impact that overall performance negatively.</p> |
35,364,214 | Does MySQL overwrite a column of same value on update? | <p>When updating a table in MySQL, for example:</p>
<blockquote>
<p><strong>Table</strong> <code>user</code></p>
</blockquote>
<pre><code>user_id | user_name
1 John
2 Joseph
3 Juan
</code></pre>
<p>If I run the query</p>
<pre><code>UPDATE `user` SET user_name = 'John' WHERE user_id = 1
</code></pre>
<p>Will MySQL write the same value again or ignore it since it's the same content?</p> | 35,364,215 | 1 | 2 | null | 2016-02-12 13:47:52.913 UTC | 3 | 2020-07-28 17:35:08.783 UTC | 2020-07-28 17:34:15.757 UTC | null | 63,550 | null | 4,802,649 | null | 1 | 30 | mysql|sql-update | 15,675 | <p>As the <a href="http://dev.mysql.com/doc/refman/5.7/en/update.html" rel="noreferrer">MySQL manual for the UPDATE statement</a> implies,</p>
<blockquote>
<p>If you set a column to the value it currently has, MySQL notices this
and does not update it.</p>
</blockquote>
<p>So, if you run this query, MySQL will understand that the value you're trying to apply is the same as the current one for the specified column, and it won't write anything to the database.</p> |
28,276,706 | PostgreSQL error Fatal: role “username” does not exist | <p>I'm setting up my PostgreSQL 9.1 in windows.</p>
<p>I can't do anything with PostgreSQL: can't createdb, can't createuser; all operations return the error message</p>
<p>Fatal: role root does not exist<br>
root is my account name, which I created while installing <code>Postgresql</code></p>
<p>But I am able to connect using: </p>
<pre><code> username : postgres
</code></pre>
<p>How can I connect to postgres using role <code>root</code>?<br>
There is a solution mentioned for linux platforms using su command <a href="https://stackoverflow.com/questions/11919391/postgresql-error-fatal-role-username-does-not-exist">here</a> but not able to figure out solution for windows7</p>
<p>Thanks in Advance</p> | 28,276,875 | 3 | 1 | null | 2015-02-02 11:26:51.943 UTC | 9 | 2022-04-14 08:38:35.093 UTC | 2017-05-23 12:17:23.06 UTC | null | -1 | null | 1,355,500 | null | 1 | 23 | postgresql|windows-7|windows-7-x64|roles | 61,803 | <p>If you want to login to Postgres using the username <code>root</code> you need to first create such a user.</p>
<p>You first need to login as the Postgres super user. This is typically <code>postgres</code> (and is specified during installation):</p>
<pre><code>psql -U postgres <user-name>
</code></pre>
<p>Then you can create roles and databases:</p>
<pre><code>psql (9.4.0)
Type "help" for help.
postgres=# create user root with password 'verysecret';
CREATE ROLE
postgres=# \q
c:\
c:\>psql -U root postgres
psql (9.4.0)
Type "help" for help.
postgres=>
</code></pre>
<p>Logged in as the superuser you can also grant the <code>root</code> user the necessary privileges.</p>
<p>All parameters for <code>psql</code> <a href="http://www.postgresql.org/docs/current/static/app-psql.html" rel="nofollow noreferrer">are documented in the manual</a>.</p>
<p>Creating users and databases is also documented in the manual:</p>
<ul>
<li><a href="http://www.postgresql.org/docs/current/static/app-psql.html#R2-APP-PSQL-CONNECTING" rel="nofollow noreferrer">connecting to the database</a></li>
<li><a href="http://www.postgresql.org/docs/current/static/sql-createuser.html" rel="nofollow noreferrer">create user</a></li>
<li><a href="http://www.postgresql.org/docs/current/static/sql-createdatabase.html" rel="nofollow noreferrer">create database</a></li>
</ul> |
2,324,089 | Can someone explain what a wire-level protocol is? | <p>I am not very clear about the idea of wire-level protocols. I heard BitTorrent uses it and read that a wirelevel protocol can be considered an opposite of API. I read RMI calls can be considered wirelevel protocols but am still a little confused. Can someone explain this in a better way?</p> | 2,324,113 | 3 | 1 | null | 2010-02-24 06:23:15.86 UTC | 9 | 2018-01-16 06:12:01.367 UTC | null | null | null | null | 184,046 | null | 1 | 37 | networking|terminology|protocols|p2p|bittorrent | 15,194 | <p>I wouldn't say that something uses a wire-level protocol or doesn't - I'd talk about <em>which</em> wire-level protocol it uses.</p>
<p>Basically, if something's communicating with a remote machine (even conceptually) then there's some data going across the network connection (the wire). The description of that data is the "wire-level protocol". Even within that, you would often stop short of describing individual network packets - so the wire protocol for a TCP-based protocol would usually be defined in terms of opening a connection, the data <em>streams</em> between the two computers, and probably details of when each side would be expected to close the connection.</p> |
8,476,103 | Accessing database connection string using app.config in C# winform | <p>I can't seem to be able to access the app.config database connection string in my c# winforms app. </p>
<p>app.config code</p>
<pre><code> <connectionStrings>
<add name="MyDBConnectionString" providerName="System.Data.SqlClient"
connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; Integrated Security=true" />
</connectionStrings>
</code></pre>
<p>C# code: </p>
<pre><code>SqlConnection conn = new SqlConnection();
conn.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["MyDBConnectionString"];
</code></pre>
<p>When I try the C# code, I get a message:<br>
<em>Warning 1 'System.Configuration.ConfigurationSettings.AppSettings' is obsolete: '
This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings'</em></p>
<p>However, when I try to use: </p>
<pre><code>conn.ConnectionString = System.Configuration!System.Configuration.ConfigurationManager.AppSettings["MyDBConnectionString"];
</code></pre>
<p>I get an error: <em>Only assignment, call, increment, decrement, and new object expressions can be used as a statement</em></p> | 8,476,144 | 10 | 1 | null | 2011-12-12 14:48:50.787 UTC | 4 | 2022-07-12 20:45:12.943 UTC | null | null | null | null | 371,267 | null | 1 | 20 | c#|sql|winforms|database-connection|app-config | 106,898 | <p>This is all you need:</p>
<pre><code>System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
</code></pre> |
8,694,871 | node.js store objects in redis | <p>Here is the thing - I want to store native JS (node.js) objects (flash sockets references) in redis under a certain key. When I do that with simple <code>client.set()</code> it's stored as a string. When I try to get value I get <code>[object Object]</code> - just a string.</p>
<p>Any chance to get this working? Here's my code:</p>
<pre><code> addSocket : function(sid, socket) {
client.set(sid, socket);
},
getSocket : function(sid) {
client.get(sid, function(err, reply) {
// cant't get an object here. All I get is useless string
});
},
</code></pre> | 8,694,891 | 8 | 1 | null | 2012-01-01 19:05:50.057 UTC | 11 | 2022-02-14 06:10:22.797 UTC | null | null | null | null | 591,939 | null | 1 | 68 | object|node.js|redis | 86,047 | <p><em>Downvoters: the context here is SET command and ability to store arbitrary objects.</em></p>
<p>No, you can't do that. You should accept the fact that Redis stores everything as a string (the protocol is text-based, after all). Redis may perform some optimizations and convert some values to integers, but that's its business, not yours.</p>
<p>If you want to store <strong>arbitrary</strong> objects in Redis, make sure that you serialize them before saving and de-serialize after retrieving. </p>
<p>I'm not sure if you can do that with socket objects, though. They simply describe a system resource (an open connection), after all (TCP sockets, for example). If you manage to serialize the description and deserialize it on another machine, that other machine won't have the connection.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.