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,395,932 | Spark fillNa not replacing the null value | <p>I have the following dataset and its contain some null values, need to replace the null value using fillna in spark.</p>
<p>DataFrame:</p>
<pre><code>df = spark.read.format("com.databricks.spark.csv").option("header","true").load("/sample.csv")
>>> df.printSchema();
root
|-- Age: string (nullable = true)
|-- Height: string (nullable = true)
|-- Name: string (nullable = true)
>>> df.show()
+---+------+-----+
|Age|Height| Name|
+---+------+-----+
| 10| 80|Alice|
| 5| null| Bob|
| 50| null| Tom|
| 50| null| null|
+---+------+-----+
>>> df.na.fill(10).show()
</code></pre>
<p>when i'll give the na values it dosen't changed the same dataframe appeared again.</p>
<pre><code>+---+------+-----+
|Age|Height| Name|
+---+------+-----+
| 10| 80|Alice|
| 5| null| Bob|
| 50| null| Tom|
| 50| null| null|
+---+------+-----+
</code></pre>
<p>tried create a new dataframe and store the fill values in dataframe but the result showing like unchanged.</p>
<pre><code>>>> df2 = df.na.fill(10)
</code></pre>
<p>how to replace the null values? please give me the possible ways by using fill na.
Thanks in Advance.</p> | 40,396,979 | 2 | 2 | null | 2016-11-03 07:25:37.46 UTC | 1 | 2021-06-18 20:18:10.5 UTC | 2021-06-18 20:18:10.5 UTC | null | 426,332 | null | 5,928,554 | null | 1 | 25 | apache-spark|pyspark | 41,147 | <p>It seems that your <code>Height</code> column is not numeric. When you call <code>df.na.fill(10)</code> spark replaces only nulls with column that match type of <code>10</code>, which are numeric columns.</p>
<p>If <code>Height</code> column need to be string, you can try <code>df.na.fill('10').show()</code>, otherwise casting to <code>IntegerType()</code> is neccessary.</p> |
20,988,641 | How to clear cookies in angular.js | <p>Currently am using angulajs app.</p>
<p>I want to store some values in cookie. So i used <code>angular-cookies-min</code> script for add some values to cookies</p>
<p>I have used this below code for save values to cookie. </p>
<pre><code> $cookieStore.put("userInfo", userInfo);//userInfo is a array with some values.
</code></pre>
<p><strong>Now I want to clear the cookie? How can i do it?</strong> </p> | 20,988,750 | 3 | 0 | null | 2014-01-08 06:40:09.673 UTC | 1 | 2015-03-25 06:53:47.3 UTC | 2014-01-09 07:02:05.677 UTC | user2998788 | null | user2998788 | null | null | 1 | 21 | javascript|jquery|angularjs|session-cookies|angular-cookies | 67,122 | <p>Try this code for delete cookie </p>
<pre><code>$cookieStore.remove("userInfo");
</code></pre>
<p><strong>EDIT</strong>: Since v1.4 <code>$cookieStore</code> has been deprecated (see <a href="https://docs.angularjs.org/api/ngCookies/service/$cookieStore" rel="noreferrer">docs</a>), so from that version on you should use:</p>
<pre><code>$cookies.remove("userInfo");
</code></pre> |
32,368,016 | How to comment in laravel .env file? | <p>I am working on a project in Laravel where I am storing some settings in .env file setting like few parameters for testing purpose and few parameters are for live working so I was just checking that is there any way to comment in .env file of Laravel.</p>
<p>Here is an example</p>
<pre><code>/* Test Settings */
ACCESS_KEY=qwsdr
ACCESS_TOKEN=Bgcvfsx
/* Live Settings */
ACCESS_KEY=985AsdefG
ACCCESS_TOKEN=LFP994kL
</code></pre> | 32,368,522 | 3 | 0 | null | 2015-09-03 06:01:15.797 UTC | 16 | 2021-02-15 07:25:58.28 UTC | 2020-04-08 16:39:20.163 UTC | null | 1,970,470 | null | 2,541,634 | null | 1 | 230 | php|laravel|laravel-5|environment-variables | 139,880 | <p>You use hash commenting:</p>
<pre><code># Test Settings
ACCESS_KEY=qwsdr
ACCESS_TOKEN=Bgcvfsx
# Live Settings
ACCESS_KEY=985AsdefG
ACCCESS_TOKEN=LFP994kL
</code></pre>
<p>Documentation: <a href="https://github.com/vlucas/phpdotenv#comments" rel="noreferrer">https://github.com/vlucas/phpdotenv#comments</a></p> |
5,699,088 | What is the function of @this exactly? | <p>As far as I know the <strong>@this</strong> is to denote the current component triggering the event, such as :</p>
<pre><code><p:commandButton process="@this" ... />
</code></pre>
<p>And in JSF 2 Ajax, the <strong>@this</strong> can also mean the encapsulating component, like :</p>
<pre><code><h:inputText ...>
<f:ajax execute="@this" ... />
</h:inputText>
</code></pre>
<p>And I have one case where using <strong>p:datatable</strong>, including or excluding <strong>@this</strong> can have a different impact upon Ajax partial submit</p>
<p>Here's the example, in this case, the process is using <strong>@this</strong>, and this works as expected, where when process happens first, and then followed by <strong>setPropertyActionListener</strong> and last, the <strong>action</strong> is executed :</p>
<pre><code><p:column>
<p:commandLink
value="#{anggaranDetail.map['code']}"
process="@this infoAnggaranForm:Anggaran"
update="detailDialogForm:Anggaran detailDialogForm:SubAnggaran"
oncomplete="infoAnggaranDialog.hide()"
image="ui-icon ui-icon-search"
action="#{tInputBean.updateAnggaranSubAnggaran}">
<f:setPropertyActionListener value="#{anggaranDetail}"
target="#{infoAnggaranBean.selectedAnggaranDetail}" />
</p:commandLink>
</p:column>
</code></pre>
<p>But when I omit the <strong>@this</strong> from this example, the <strong>setPropertyActionListener</strong> and the <strong>action</strong> are never executed, as if they're not there.</p>
<p>I wonder why ? Perhaps <strong>@this</strong> has some other meaning other than the current component, perhaps the current record in this example ?</p>
<p>Im using tomcat 7, and these are my dependencies :</p>
<pre><code><dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.0.4-b09</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.0.4-b09</version>
<scope>compile</scope>
</dependency>
</code></pre> | 5,704,558 | 1 | 0 | null | 2011-04-18 06:01:32.677 UTC | 12 | 2015-02-18 09:41:08.13 UTC | 2011-10-12 11:07:20.613 UTC | null | 905,093 | null | 500,451 | null | 1 | 34 | jsf|jsf-2|primefaces | 41,824 | <p>The PrimeFaces <code>process</code> and standard JSF <code>execute</code> attributes should point to spaceseparated component identifiers of components which JSF should process during the entire JSF lifecycle upon an ajax request (get request parameters, validate them, update model, execute action). The <code>process</code> defaults to <code>@form</code>, the current form, and the <code>execute</code> defaults to <code>@this</code>, the current component. In command links/buttons this is mandatory to execute the actions associated with the link/button itself.</p>
<p>However, in your datatable you have <code>process="@this infoAnggaranForm:Anggaran"</code>, thus two components to process. If you omit <code>@this</code> but keep the other component, then it will only process/execute the other component and not the link/button component. If you omit the <code>process</code> attribute it will default to <code>@form</code>. If you have more other input components in the same form, then they will also be processed.</p>
<p>Depending on the concrete functional requirement, you could just keep it <code>process="@this infoAnggaranForm:Anggaran"</code>, or omit it. JSF will then process/execute at least both the button and the other component, exactly as you want.</p>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/25339056/understanding-process-and-update-attributes-of-primefaces/">Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes</a></li>
</ul> |
24,492,868 | What is the meaning of "dot parenthesis" syntax? | <p>I am studying a sample Go application that stores data in mongodb. The code at this line (<a href="https://github.com/zeebo/gostbook/blob/master/context.go#L36" rel="noreferrer">https://github.com/zeebo/gostbook/blob/master/context.go#L36</a>) seems to access an user ID stored in a gorilla session:</p>
<pre><code>if uid, ok := sess.Values["user"].(bson.ObjectId); ok {
...
}
</code></pre>
<p>Would someone please explain to me the syntax here? I understand that <code>sess.Values["user"]</code> gets a value from the session, but what is the part that follows? Why is the expression after the dot in parentheses? Is this a function invocation?</p> | 24,493,004 | 1 | 0 | null | 2014-06-30 14:47:57.353 UTC | 13 | 2022-05-16 07:15:54.38 UTC | 2020-11-27 14:33:01.473 UTC | null | 13,860 | null | 410,102 | null | 1 | 91 | go|syntax|type-assertion|language-concepts | 17,169 | <p><code>sess.Values["user"]</code> is an <code>interface{}</code>, and what is between parenthesis is called a <em><a href="http://golang.org/ref/spec#Type_assertions">type assertion</a></em>. It checks that the value of <code>sess.Values["user"]</code> is of type <code>bson.ObjectId</code>. If it is, then <code>ok</code> will be <code>true</code>. Otherwise, it will be <code>false</code>.</p>
<p>For instance:</p>
<pre><code>var i interface{}
i = int(42)
a, ok := i.(int)
// a == 42 and ok == true
b, ok := i.(string)
// b == "" (default value) and ok == false
</code></pre> |
24,929,735 | How to calculate DATE Difference in PostgreSQL? | <p>Here I need to calculate the difference of the two dates in the <code>PostgreSQL</code>. </p>
<p><strong>In SQL Server</strong>: Like we do in <code>SQL Server</code> its much easier.</p>
<pre><code>DATEDIFF(Day, MIN(joindate), MAX(joindate)) AS DateDifference;
</code></pre>
<p><strong>My Try</strong>: I am trying using the following script:</p>
<pre><code>(Max(joindate) - Min(joindate)) as DateDifference;
</code></pre>
<p><strong>Question</strong>: </p>
<ul>
<li><p>Is my method correct?</p></li>
<li><p>Is there any function in <code>PostgreSQL</code> to calculate this?</p></li>
</ul> | 24,930,139 | 6 | 0 | null | 2014-07-24 09:17:55.12 UTC | 13 | 2022-06-14 06:51:21.857 UTC | 2019-10-03 10:54:24.813 UTC | null | 10,877,860 | null | 3,382,347 | null | 1 | 60 | postgresql|datediff | 190,565 | <p>Your calculation is correct for <code>DATE</code> types, but if your values are timestamps, you should probably use <a href="http://www.postgresql.org/docs/9.3/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT" rel="noreferrer"><code>EXTRACT</code></a> (or DATE_PART) to be sure to get only the difference in <em>full</em> days;</p>
<pre><code>EXTRACT(DAY FROM MAX(joindate)-MIN(joindate)) AS DateDifference
</code></pre>
<p><a href="http://sqlfiddle.com/#!15/0d359/2" rel="noreferrer">An SQLfiddle to test with</a>. Note the timestamp difference being 1 second less than 2 full days.</p> |
51,450,521 | Failed to resolve: com.android.support:appcompat-v7:28.0 | <p>When I use <code>com.android.support:appcompat-v7:28.+</code> in my project's <code>build.gradle</code>(module) it works without any error. But when I just use <code>com.android.support:appcompat-v7:28</code>, just without <code>.+</code>, it gives me an error: </p>
<blockquote>
<p>Failed to resolve: com.android.support:appcompat-v7:28.0</p>
</blockquote>
<p>Just without the <code>.+</code> end of it. I added maven before but the result was the same. Any idea to solve it?</p> | 51,450,795 | 9 | 0 | null | 2018-07-20 21:21:44.01 UTC | 4 | 2021-07-08 03:38:01.143 UTC | 2018-07-20 21:44:36.99 UTC | null | 1,812,633 | null | 6,585,319 | null | 1 | 45 | android|gradle | 142,137 | <blockquote>
<p><code>28.0.0</code> is the final version of support libraries. Android has migrated to AndroidX. To use the latest android libraries, <a href="https://developer.android.com/jetpack/androidx/migrate" rel="noreferrer">Migrating to AndroidX</a></p>
</blockquote>
<hr>
<blockquote>
<p><em>Edit:</em> Versions <code>28.0.0-rc02</code> and <code>28.0.0</code> are now available.</p>
</blockquote>
<p>I don't see any <code>28.0</code> version on <a href="https://dl.google.com/dl/android/maven2/index.html" rel="noreferrer">Google Maven</a>. Only <code>28.0.0-alpha1</code> and <code>28.0.0-alpha3</code>. Just change it to either of those or how it was previously, i.e., with <code>.+</code> which just means any version under <code>28</code> major release.</p>
<p>For an alpha appcompat release <code>28.+</code> makes more sense.</p> |
25,548,765 | Binding, Context, ContextBinding and BindingContext in ui5 | <p>I have been pondering the internals of and relationship between context, contextbinding, and bindingcontext for a few days now and i am not sure whether there is a major misconception on my side. Maybe some of you can help me sort it out. I am putting my assumptions below. I might want to say first that I always work with oData models here.</p>
<p>This is what I believe to understand reading the documentation:</p>
<p>A <strong>context</strong> is a reference to a data object in a model.</p>
<p>A <strong>binding</strong> is basically an event provider which (in case of a one way binding) observes the status of a specific context and emits events when it is changed/data loaded ... and therefore allows for registering event handlers for events on that specific context. In terms of programming objects, there are property bindings and list bindings (is this true - or is list binding all that is ever relevant?). </p>
<p>At any rate, my understanding is that a list binding is the model-side of a component's aggregation binding, while a property binding is called property binding both from a component's and a model's point of view (confusing?).</p>
<p>Now what I do not quite get is:
The context binding <code>new sap.ui.model.ContextBinding(oModel, sPath, oContext, mParameters?, oEvents?):</code> takes a path and a <strong>context</strong> as a parameter. I am assuming that this oContext is not exactly the context described above but some metadata on the binding. is this correct? Or is this the definition of thep ath which the path parameter is relative to? </p>
<p>What also seems weird is when you want to create a context itself <code>new sap.ui.model.Contextabov(oModel, sPath, oContext)</code> takes a context again.
I believe that this is just an unfortunate naming thing i am looking at, but I am not quite sure.</p>
<p>Then there is contextbinding and bindingcontext. I'd assume that contextBinding is the binding to a specific context as described e. And a bindingcontext is the meta data regarding a context- or list binding.</p>
<p>From a programming point of view, I do not understand why the following works:</p>
<ul>
<li>create list binding to context via <code>model.bindList()</code> passing a path only.</li>
<li>attach change-event handler to binding</li>
<li>call <code>get_contexts()</code> on binding</li>
<li>receive data in change event handler (and see the oData-property filled in the model).</li>
</ul>
<p>and there seems to be no way of doing the same for a property binding which i'd assume I can generate via <code>model.bindProperty()</code>. I can generate the binding, but the binding I receive seems to have no handle to actually fetch data.</p>
<p>I hope the ramble explains my problem. In case you ask : what do you want to do? I actually do not want to do anything with it, I just do not quite understand how this works. Binding to ui controls and so forth works just fine, but I'd prefer to really understand what is underneath the hood. I have been reading debug files and unit tests a bit, but discussing it with you guys seems a great way as well.</p>
<p>If this is unclear I'll happily add anything that helps.</p>
<p>Cheers
Michel</p> | 25,565,444 | 2 | 0 | null | 2014-08-28 12:23:10.437 UTC | 11 | 2020-07-17 08:55:10.367 UTC | null | null | null | null | 1,326,343 | null | 1 | 19 | sapui5 | 29,790 | <p>your questions are answered below. Hope it helps.</p>
<blockquote>
<ol>
<li>Now what I do not quite get is: The context binding new <code>sap.ui.model.ContextBinding(oModel, sPath, oContext, mParameters?, oEvents?):</code> takes a path and a context as a parameter. I am assuming that this oContext is not exactly the context described above but some metadata on the binding. is this correct? Or is this the definition of thep ath which the path parameter is relative to?</li>
</ol>
</blockquote>
<p>the oContext is the context you mentioned above, to be precise, is <code>sap.ui.model.Context</code>.</p>
<blockquote>
<ol start="2">
<li>What also seems weird is when you want to create a context itself new <code>sap.ui.model.Context(oModel, sPath, oContext)</code> takes a context again. I believe that this is just an unfortunate naming thing i am looking at, but I am not quite sure.</li>
</ol>
</blockquote>
<p>I guess the documentation <a href="https://openui5.hana.ondemand.com/#docs/api/symbols/sap.ui.model.Context.html" rel="nofollow noreferrer">here</a> confused you. Actually, sap.ui.model.Context only takes oModel and sPath as parameters. The following code is what i get from <a href="https://openui5.hana.ondemand.com/resources/sap-ui-core-dbg.js" rel="nofollow noreferrer">sap-ui-core.js</a>. You can see the JSDoc part about parameters is actually inconsistent with the code. Maybe there is some kind of typo there.</p>
<pre><code> /**
* Constructor for Context class.
*
* @class
* The Context is a pointer to an object in the model data, which is used to
* allow definition of relative bindings, which are resolved relative to the
* defined object.
* Context elements are created either by the ListBinding for each list entry
* or by using createBindingContext.
*
* @param {sap.ui.model.Model} oModel the model
* @param {String} sPath the path
* @param {Object} oContext the context object
* @abstract
* @public
* @name sap.ui.model.Context
*/
var Context = sap.ui.base.Object.extend("sap.ui.model.Context",
/** @lends sap.ui.model.Context.prototype */ {
constructor : function(oModel, sPath){
sap.ui.base.Object.apply(this);
this.oModel = oModel;
this.sPath = sPath;
},
metadata : {
"abstract" : true,
publicMethods : [
"getModel", "getPath", "getProperty", "getObject"
]
}
});
</code></pre>
<blockquote>
<ol start="3">
<li>From a programming point of view, I do not understand why the following works:</li>
</ol>
<ul>
<li>create list binding to context via model.bindList() passing a path only.</li>
<li>attach change-event handler to binding</li>
<li>call get_contexts() on binding</li>
<li>receive data in change event handler (and see the oData-property filled in the model).</li>
</ul>
<p>and there seems to be no way of doing the same for a property binding which i'd assume I can generate via model.bindProperty(). I can generate the binding, but the binding I receive seems to have no handle to actually fetch data.</p>
</blockquote>
<p>Actually you can also <code>attachChange</code> event to <code>sap.ui.model.PropertyBinding</code>, and you can call getValue() to get the data.</p> |
43,172,345 | MySql Workbench installer requires Visual C++ 2015 Redistributable Package to be installed, but it already is installed | <p>I've looked everywhere online, but it doesn't look like anyone has been able to resolve this issue.</p>
<p>When I download and try to install MySql Workbench, I get prompted to install Visual C++ Redistributable package (2015) to be installed. The wizard then takes me directly to <a href="https://dev.mysql.com/resources/wb62_prerequisites.html" rel="noreferrer">this website</a> in order to install it. </p>
<p>However, whenever I try to install either, it just tells me they're already installed.</p>
<p>After googling this for about an hour, I found some other people had this problem which apparently was resolved by <a href="https://bugs.mysql.com/bug.php?id=62141" rel="noreferrer">following the instructions from this website</a>. I downloaded instaedit and followed the instructions, but I continue to get the same error.</p>
<p>I've been at this for two days now and am going to go crazy. If someone can help me with this I'd be very grateful. I'm using Windows 10,</p> | 51,444,345 | 23 | 0 | null | 2017-04-02 19:04:01.46 UTC | 6 | 2021-11-22 07:23:03.8 UTC | 2018-05-24 16:43:53.987 UTC | null | 7,089,884 | null | 7,089,884 | null | 1 | 36 | mysql|mysql-workbench | 100,186 | <p>It turns out that VC++ 2017 redistributables are the culprit because they delete the registry keys used by VC++ 2015 redistributables.
See <a href="https://developercommunity.visualstudio.com/content/problem/262841/vc-runtime-redistributable-update-deletes-registry.html" rel="noreferrer">this Microsoft Developer Community page</a> for solution (TL;DR; you have to <a href="https://web.archive.org/web/20170817125955/https://support.solarwinds.com/Success_Center/Network_Performance_Monitor_(NPM)/Repair_Microsoft_C___Redistributable" rel="noreferrer">repair</a> VC++ <strong>2017</strong> redistributables as this will restore missing 2015 registry keys).</p>
<p>This process is <a href="https://stackoverflow.com/questions/43172345/mysql-workbench-installer-requires-visual-c-2015-redistributable-package-to-be#comment98625496_51444345">as Eric describes</a>:</p>
<blockquote>
<p>The steps are essentially: go to Programs in Control Panel (or "Add or Remove Programs" in Windows 10's "Settings"), find the Microsoft Visual C++ 2017 Redistributable, click it and choose Change/Modify, then choose "Repair</p>
</blockquote> |
7,363,027 | How to check if a value is selected in a multi-value parameter | <p>In SSRS 2008, I use Multi-value parameters to, well, select multiple values for a particular parameter.</p>
<p>In my report I have conditional formatting: a particular label has to be blue if the item is selected; otherwise it will stay black. My intuition was trying it the SQL way - but I was wrong :-)</p>
<pre><code>Switch(
Fields!groupType.Value = "firstValue", "#00ffffff",
Fields!groepType.Value = "secondValue", "Tomato",
Fields!groepType.Value = "thirdValue", "DimGray",
Fields!groepType.Value IN Parameters!p_myMultipleValueParameter.Values, "Blue"
)
</code></pre>
<p>What is the right way to handle this?</p> | 18,189,913 | 1 | 0 | null | 2011-09-09 14:15:46.843 UTC | 10 | 2014-02-19 21:09:53.24 UTC | null | null | null | null | 195,687 | null | 1 | 28 | reporting-services|ssrs-2008 | 50,273 | <p>I think the cleanest way is probably the following</p>
<pre><code>Array.IndexOf(Parameters!p_myMultipleValueParameter.Value, Fields!groepType.Value) > -1
</code></pre>
<p>Running a join each time may be inefficient because of the overhead of allocating extra strings, especially if the function will be run over a large list, or once per row of a grid, say.</p> |
24,489,922 | WebLogic 12c - Destination unreachable exception | <p>First, I had installed jdk 1.6.0_43 and oracle weblogic 12.1.1, I was successfully able to deploy my application.</p>
<p>I then upgraded both my jdk (1.7.0_60) and weblogic (12.1.2), but was unable to deploy my application.</p>
<p>Now, I downgraded my weblogic (12.1.1) but retained my jdk 1.7.0_60, but i was still not able to deploy my application successfully.</p>
<p>In both the failure cases, I got the same error with the following message. Is there something with respect to java 7 I should be aware of? I tried searching for this a lot, but in vain..</p>
<pre><code> [exec] javax.naming.CommunicationException [Root exception is java.net.ConnectException: t3://localhost:9991: Destination unreachable; nested exception is:
[exec] java.net.ConnectException: Connection refused: connect; No available router to destination]
</code></pre> | 24,493,984 | 6 | 0 | null | 2014-06-30 12:13:42.22 UTC | 2 | 2021-06-08 14:02:36.35 UTC | null | null | null | null | 1,649,068 | null | 1 | 5 | java|java-7|java-6|weblogic12c | 63,107 | <p>No available router to destination -- Means you do not have a service running to listen on localhost:9991 </p>
<p>Go to admin console, check the servers which should be listening on 9991 is up and running.
I am sure it is not running.</p> |
2,416,980 | ConfigurationException in Java? | <p>Decided to use Apache's Common Configuration package to parse an XML File.</p>
<p>I decided to do a:</p>
<pre><code>XMLConfiguration xmlConfig = new XMLConfiguration(file);
</code></pre>
<p>To which Eclipse complained that I haven't caught an exception(<code>Unhandled exception type ConfigurationException</code>), so I hit the trusty <code>surround with try/catch</code> and it added the following code:</p>
<pre><code>try
{
XMLConfiguration xmlConfig = new XMLConfiguration(file);
}
catch (ConfigurationException ex)
{
ex.printStackTrace();
}
</code></pre>
<p>However now it's complaining:</p>
<pre><code>No exception of type ConfigurationException can be thrown; an exception type
must be a subclass of Throwable
</code></pre>
<p>I don't understand why it's gave me that error when Eclipse is the one that suggested to add it.</p> | 2,416,992 | 3 | 0 | null | 2010-03-10 12:57:35.043 UTC | 5 | 2014-01-02 17:44:46.353 UTC | 2010-03-10 13:00:17.39 UTC | null | 21,234 | null | 154,280 | null | 1 | 23 | java|apache-commons | 48,677 | <p><code>org.apache.commons.configuration.ConfigurationException</code> extends <code>org.apache.commons.lang.exception.NestableException</code>.</p>
<p>Do you have Commons Lang on your path also? If not, Eclipse will fail to resolve the <code>ConfigurationException</code> class, and you'll get that error.</p> |
2,815,721 | .NET: Is it possible to get HttpWebRequest to automatically decompress gzip'd responses? | <p>In <a href="https://stackoverflow.com/questions/2813989/how-do-i-read-a-secure-rss-feed-into-a-syndicationfeed-without-providing-credenti/2815624#2815624">this answer</a>, I described how I resorted to wrappnig a GZipStream around the response stream in a HttpWebResponse, in order to decompress it. </p>
<p>The relevant code looks like this: </p>
<pre><code>HttpWebRequest hwr = (HttpWebRequest) WebRequest.Create(url);
hwr.CookieContainer =
PersistentCookies.GetCookieContainerForUrl(url);
hwr.Accept = "text/xml, */*";
hwr.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
hwr.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-us");
hwr.UserAgent = "My special app";
hwr.KeepAlive = true;
using (var resp = (HttpWebResponse) hwr.GetResponse())
{
using(Stream s = resp.GetResponseStream())
{
Stream s2 = s;
if (resp.ContentEncoding.ToLower().Contains("gzip"))
s2 = new GZipStream(s2, CompressionMode.Decompress);
else if (resp.ContentEncoding.ToLower().Contains("deflate"))
s2 = new DeflateStream(s2, CompressionMode.Decompress);
... use s2 ...
}
}
</code></pre>
<p>Is there a way to get HttpWebResponse to provide a de-compressing stream, automatically? In other words, a way for me to eliminate the following from the above code: </p>
<pre><code> Stream s2 = s;
if (resp.ContentEncoding.ToLower().Contains("gzip"))
s2 = new GZipStream(s2, CompressionMode.Decompress);
else if (resp.ContentEncoding.ToLower().Contains("deflate"))
s2 = new DeflateStream(s2, CompressionMode.Decompress);
</code></pre>
<p>Thanks.</p> | 2,815,876 | 3 | 0 | null | 2010-05-12 02:03:35.203 UTC | 15 | 2015-09-07 12:04:04.79 UTC | 2017-05-23 11:46:55.11 UTC | null | -1 | null | 48,082 | null | 1 | 38 | .net|httpwebrequest|gzip | 26,727 | <p>Use the <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.automaticdecompression.aspx" rel="noreferrer">HttpWebRequest.AutomaticDecompression</a> property as follows:</p>
<pre><code>HttpWebRequest hwr = (HttpWebRequest) WebRequest.Create(url);
hwr.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
</code></pre>
<p>It's not necessary to manually add the <code>Accept-Encoding</code> HTTP header; it will automatically be added when that property is used.</p>
<p>(Also, I know this is just example code, but the <code>HttpWebResponse</code> object should be placed in a <code>using</code> block so it's disposed correctly when you've finished using it.)</p> |
3,021,206 | how do i see if a big JSON object contains a value? | <p>I'm using PHP to json encode a massive multi-dimensional array of events, so i get something like this:</p>
<pre><code>var ents = {"7":{"event_id":"7","nn":"The Whisky Drifters","nn_url":"the-whisky-drifters",
"venue":"The Grain Barge","date_num":"2010-06-11","date_txt":"Friday 11th June",
"gig_club":"1","sd":"A New Acoustic String Band...","ven_id":"44",
"art":0},"15":{"event_id":"15","nn":"Bass Kitchen","nn_url":"bass-kitchen",
"venue":"Timbuk2","date_num":"2010-06-11","date_txt":"Friday 11th June",
"gig_club":"2","sd":"Hexadecimal \/ DJ Derek \/ Id","ven_id":"21",
"art":1},
</code></pre>
<p>the first dimension is the id, see </p>
<pre><code>var ents = {"7":{
</code></pre>
<p>So it's possible to get the ids without examining the nested objects...</p>
<p><strong>What's the fastest, most efficient way to check if my JSON contains an id?</strong> </p> | 3,021,233 | 4 | 0 | null | 2010-06-11 08:13:25.473 UTC | 1 | 2015-04-15 16:26:22.83 UTC | 2015-04-15 16:26:22.83 UTC | null | 2,065,237 | null | 289,666 | null | 1 | 21 | javascript|jquery|json | 55,262 | <p>You can use the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty" rel="noreferrer"><code>hasOwnProperty</code></a> method:</p>
<pre><code>if (ents.hasOwnProperty('7')) {
//..
}
</code></pre>
<p>This method checks if the object contains the specified property regardless of its value.</p>
<p>Is faster than the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/in_Operator" rel="noreferrer"><code>in</code></a> operator because it doesn't checks for inherited properties.</p> |
2,597,104 | Break the nested (double) loop in Python | <p>I use the following method to break the double loop in Python.</p>
<pre><code>for word1 in buf1:
find = False
for word2 in buf2:
...
if res == res1:
print "BINGO " + word1 + ":" + word2
find = True
if find:
break
</code></pre>
<p>Is there a better way to break the double loop?</p> | 2,597,351 | 4 | 0 | null | 2010-04-08 02:06:55.34 UTC | 19 | 2014-11-26 00:04:53.253 UTC | 2010-12-29 10:17:04.033 UTC | null | 63,550 | null | 260,127 | null | 1 | 48 | python|nested-loops | 92,264 | <p>Probably not what you are hoping for, but usually you would want to have a <code>break</code> after setting <code>find</code> to <code>True</code></p>
<pre><code>for word1 in buf1:
find = False
for word2 in buf2:
...
if res == res1:
print "BINGO " + word1 + ":" + word2
find = True
break # <-- break here too
if find:
break
</code></pre>
<p>Another way is to use a generator expression to squash the <code>for</code> into a single loop</p>
<pre><code>for word1, word2 in ((w1, w2) for w1 in buf1 for w2 in buf2):
...
if res == res1:
print "BINGO " + word1 + ":" + word2
break
</code></pre>
<p>You may also consider using <code>itertools.product</code></p>
<pre><code>from itertools import product
for word1, word2 in product(buf1, buf2):
...
if res == res1:
print "BINGO " + word1 + ":" + word2
break
</code></pre> |
28,459,172 | How do I get HTTP Request body content in Laravel? | <p>I am making an API with <code>Laravel 5</code> and I'm testing it with <code>PHPUnit</code>. I need to test legacy functionality for compatibility, which is an XML POST. As of right now, my first test looks like:</p>
<pre><code>public function testPostMessages()
{
$response = $this->call('POST', 'xml');
$this->assertEquals(200, $response->getStatusCode());
}
</code></pre>
<p>This is passing just fine. Next on my list is actually sending the XML data with the POST. So for my second test, I have:</p>
<pre><code>public function testPostMessagesContent()
{
$response = $this->call('POST', 'xml');
$this->assertTrue(is_valid_xml($response->getContent()));
}
</code></pre>
<p>This test fails. However, I am not sending my XML data. <strong>How do I send my XML?</strong><br />
Now, after that I need to add in the functionality to get the content from the request. I know there is a <code>Request</code> object that I can interact with but I don't exactly know which method to call on it. <strong>How do I get my XML from inside my controller?</strong><br /></p>
<hr />
<h3>Update #1</h3>
<p>I was able to get some results in the meantime. My current test looks like this:</p>
<pre><code>public function testPostMessagesContent()
{
$response = $this->call('POST', 'xml', array('key' => 'value'), array(), array(), array('content' => 'content'));
$this->assertContains('~', $response->getContent());
}
</code></pre>
<p>I only have the tilde there because I know it won't match so that I can see the whole response. In <code>XmlController.php</code> I have:</p>
<pre><code>class XmlController extends Controller {
public function index(Request $request)
{
return $request;
}
}
</code></pre>
<p>My output from <code>PHPUnit</code> is as follows:</p>
<pre><code>1) XmlTest::testPostMessagesContent
Failed asserting that 'POST xml HTTP/1.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Accept-Language: en-us,en;q=0.5
Content-Type: application/x-www-form-urlencoded
Host: localhost
User-Agent: Symfony/2.X
' contains "~".
</code></pre>
<p>Where are my parameters and my content? I feel like I am simply just using <code>call()</code> incorrectly.</p>
<hr />
<h3>Update #2</h3>
<p>I updated my controller to use <code>Request:all()</code> like so:</p>
<pre><code>class XmlController extends Controller
{
public function index()
{
$content = Request::all();
return $content;
}
}
</code></pre>
<p>This returned my key-value pair, but not the content.</p>
<pre><code>1) XmlTest::testPostMessagesContent
Failed asserting that '{"key":"value"}' contains "~".
</code></pre>
<p>Key-value pairs are good; it's progress. However, what I really need is the content since I'll be receiving that data in the content portion of the request. If I use <code>Request::getContent()</code> I get back a blank string. Here's my call in the test:</p>
<pre><code>$response = $this->call('POST', 'xml', array('key' => 'value'), array(), array(), array('content' => 'content'));
</code></pre>
<p>Here's my test results:</p>
<pre><code>1) XmlTest::testPostMessagesContent
Failed asserting that '' contains "~".
</code></pre>
<hr />
<h3>Update #3</h3>
<p>I am not able to get the content body of an HTTP Request at all. Since XML wasn't working, I moved forward with the REST part of my API, which uses JSON. Here's one of my tests:</p>
<pre><code>public function testPostMessagesContent()
{
$response = $this->call('POST', 'messages', ['content' => 'content']);
$this->assertEquals('saved!', $response->getContent());
}
</code></pre>
<p>This test passes. If I use curl, I get a successful call as well:</p>
<pre><code>curl -X POST -d "content=my_new_content" "http://localhost:8000/messages"
</code></pre>
<p>This returns <code>'saved!'</code> That's awesome, but if I try to use curl in a standalone PHP script (to simulate a client), this is what is returned:</p>
<pre><code>Array ( [url] => http://localhost:8000/messages [content_type] => text/html; charset=UTF-8 [http_code] => 302 [header_size] => 603 [request_size] => 118 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.063977 [namelookup_time] => 0.000738 [connect_time] => 0.000866 [pretransfer_time] => 0.000943 [size_upload] => 12 [size_download] => 328 [speed_download] => 5126 [speed_upload] => 187 [download_content_length] => -1 [upload_content_length] => 12 [starttransfer_time] => 0.057606 [redirect_time] => 0 [certinfo] => Array ( ) [primary_ip] => ::1 [primary_port] => 8000 [local_ip] => ::1 [local_port] => 63248 [redirect_url] => http://localhost:8000 [request_header] => POST /messages HTTP/1.1 Host: localhost:8000 Accept: */* Content-type: text/xml Content-length: 12 ) Redirecting to http://localhost:8000.
</code></pre>
<p>This is my curl command adding the POST fields:</p>
<pre><code>curl_setopt($ch, CURLOPT_POSTFIELDS, 'content=test');
</code></pre>
<p>It seems to me that POSTFIELDS is getting added to the body of the request. In this case, I still have the same problem. I am not able to get body content of my HTTP headers. After commenting out my validation, I get:</p>
<pre><code>Array ( [url] => http://localhost:8000/messages [content_type] => text/html; charset=UTF-8 [http_code] => 200 [header_size] => 565 [request_size] => 118 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.070225 [namelookup_time] => 0.000867 [connect_time] => 0.00099 [pretransfer_time] => 0.001141 [size_upload] => 12 [size_download] => 6 [speed_download] => 85 [speed_upload] => 170 [download_content_length] => -1 [upload_content_length] => 12 [starttransfer_time] => 0.065204 [redirect_time] => 0 [certinfo] => Array ( ) [primary_ip] => ::1 [primary_port] => 8000 [local_ip] => ::1 [local_port] => 63257 [redirect_url] => [request_header] => POST /messages HTTP/1.1 Host: localhost:8000 Accept: */* Content-type: text/xml Content-length: 12 ) saved!
</code></pre>
<p>So I have my <code>'saved!'</code> message. Great! But, in my database now I have a blank row. Not great. It is still not seeing the body content, just the headers.<br /></p>
<hr />
<h3>Answer Criteria</h3>
<p>I'm looking for the answers to these questions:</p>
<ol>
<li>Why can't I get the body content of my request?</li>
<li>How do I get the body content of my request?</li>
</ol> | 31,669,672 | 4 | 0 | null | 2015-02-11 16:17:58.137 UTC | 8 | 2022-09-21 20:50:25.85 UTC | 2015-02-13 17:27:50.867 UTC | null | 3,794,177 | null | 3,794,177 | null | 1 | 82 | php|xml|laravel|phpunit | 159,148 | <p>Inside controller inject Request object. So if you want to access request body inside controller method 'foo' do the following:</p>
<pre class="lang-php prettyprint-override"><code>use Illuminate\Http\Request;
public function foo(Request $request){
$bodyContent = $request->getContent();
}
</code></pre> |
36,505,651 | how to animate icon fa-circle using CSS to look as recording video blinking red dot? | <p>I have this red icon in CSS:</p>
<pre><code><div><i class="fa fa-circle text-danger"></i>&nbsp; LIVE </div>
</code></pre>
<p>How can I animate it to blink on an interval?</p>
<p>You remember in webcams and recorders cameras you can see a red dot blinking when is actually recording? I want the same effect, how can I do that in CSS? is it hard?</p>
<p>For example:
<a href="http://jsbin.com/loxayazega/edit?html,output" rel="noreferrer">http://jsbin.com/loxayazega/edit?html,output</a></p> | 36,505,930 | 1 | 0 | null | 2016-04-08 17:21:02.2 UTC | 9 | 2016-04-08 17:44:54.073 UTC | null | null | null | null | 999,525 | null | 1 | 20 | html|css | 26,029 | <p><strong><em>Try using this CSS:</em></strong></p>
<p><em>you can change <code>blinker 1.5s</code> value to control blinking speed.</em></p>
<pre><code>.Blink {
animation: blinker 1.5s cubic-bezier(.5, 0, 1, 1) infinite alternate;
}
@keyframes blinker {
from { opacity: 1; }
to { opacity: 0; }
}
</code></pre>
<p>See <a href="http://jsfiddle.net/mdz87jy1/"><strong>JsFiddle</strong></a>. <em>I hope it works for you, thanks.</em></p> |
49,055,676 | Blurred Decoration Image in Flutter | <p>I have the background of my app set like so:</p>
<pre><code>class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Container(
decoration: new BoxDecoration(
image: new DecorationImage(
image: new ExactAssetImage('assets/lol/aatrox.jpg'),
fit: BoxFit.cover,
),
),
child: new BackdropFilter(filter: new ImageFilter.blur(sigmaX: 600.0, sigmaY: 1000.0)),
width: 400.0,
),
);
}
}
</code></pre>
<p>I'm wanting to blur the <code>DecorationImage</code>, so I added a <code>BackdropFilter</code> to the Container, but I don't see any change. What am I doing wrong?</p> | 49,057,331 | 7 | 0 | null | 2018-03-01 17:43:10.963 UTC | 13 | 2021-06-23 15:44:01.06 UTC | 2020-03-16 12:33:51.79 UTC | null | 3,017,217 | null | 3,017,217 | null | 1 | 51 | dart|flutter | 99,240 | <p>You could do something like this, by blurring the container child instead.</p>
<pre><code>class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Container(
decoration: new BoxDecoration(
image: new DecorationImage(
image: new ExactAssetImage('assets/dog.png'),
fit: BoxFit.cover,
),
),
child: new BackdropFilter(
filter: new ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
child: new Container(
decoration: new BoxDecoration(color: Colors.white.withOpacity(0.0)),
),
),
),
);
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/3VEzUm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3VEzUm.png" alt="screenshot" /></a></p> |
677,753 | Mapping between git committers and SVN users | <p>I'm using git-svn to store a "staging" version of some SVN repo, where other users are allowed to pull from this staging repo and commit there changes back to it, then the commits on the staging repo are periodically committed the upstream SVN repo. </p>
<p>I want to know if there's a way to map between the git committers' names and SVN usernames, so that their information would be kept intact when committing back to the SVN repo?</p> | 677,843 | 2 | 0 | null | 2009-03-24 14:54:11.497 UTC | 12 | 2012-10-18 14:14:42.98 UTC | 2009-08-26 23:23:20.753 UTC | Mohammed Gamal | 6,010 | user82057 | null | null | 1 | 29 | svn|git|git-svn | 9,441 | <p><a href="https://web.archive.org/web/1/http://blogs.techrepublic%2ecom%2ecom/opensource/?p=482" rel="noreferrer">Vincent Danen</a> does mention <a href="http://git-scm.com/docs/git-svn" rel="noreferrer">the -A option when using git svn</a>:</p>
<blockquote>
<p>So using ~/git as a top-level directory for Git repositories <code>[...]</code> create an authors.txt file.<br>
This file will map the names of Subversion committers to Git authors, resulting in a correct history of the imported Subversion repository.<br>
For projects with a small number of committers, this is quite easy. For larger projects with a lot of committers, this may take some time. The syntax of the file would be:</p>
</blockquote>
<pre><code>user = Joe User <[email protected]>
vdanen = Vincent Danen <[email protected]>
</code></pre>
<blockquote>
<p>The short name is the committer name for Subversion whereas the long form is the user’s full name and e-mail address, as used by Git.</p>
<p>The final step is to clone the Subversion repository, which creates a local Git repository based on it. Assuming your repository uses the standards of /trunk, /tags, and /branches, use:</p>
</blockquote>
<pre><code># git svn clone --no-metadata -A authors.txt -t tags -b branches -T trunk https://svn.example.com/svn/repo
</code></pre>
<hr>
<pre><code>-A<filename>
--authors-file=<filename>
</code></pre>
<p>Syntax is compatible with the file used by git-cvsimport:</p>
<pre><code>loginname = Joe User <[email protected]>
</code></pre>
<blockquote>
<p>If this option is specified and <code>git-svn</code> encounters an SVN committer name that does not exist in the authors-file, git-svn will abort operation.<br>
The user will then have to add the appropriate entry.<br>
Re-running the previous <code>git-svn</code> command after the authors-file is modified should continue operation.</p>
</blockquote>
<pre><code>config key: svn.authorsfile
</code></pre>
<hr>
<p>This should work for all <code>git-svn</code> commands, including <code>git-svn dcommit</code> (when you push <em>to</em> SVN) (Note: I have not tested it directly though).</p>
<p><a href="https://stackoverflow.com/users/82057/mohammed-gamal">Mohammed Gamal</a> does report (in the comments) it is working, but without the <code>--no-metadata</code> option.</p> |
3,058,272 | Explain "Leader/Follower" Pattern | <p>I can't seem to find a good and accessible explanation of "Leader/Follower" pattern. All explanations are simply completely meaningless as in <a href="https://www.dre.vanderbilt.edu/~schmidt/POSA/POSA2/conc-patterns.html" rel="nofollow noreferrer">1</a>.</p>
<p>Can anyone explain to the <em>the mechanics</em> of how this pattern works, and why and how it improves performance over more traditional asynchronous IO models? Examples and links to diagrams are appreciated too.</p> | 6,395,616 | 5 | 1 | null | 2010-06-17 01:08:31.453 UTC | 24 | 2020-05-16 10:31:19.58 UTC | 2020-05-16 10:31:19.58 UTC | null | 3,083,483 | null | 23,643 | null | 1 | 45 | design-patterns|concurrency | 12,721 | <p>As you might have read, the pattern consists of 4 components: ThreadPool, HandleSet, Handle, ConcreteEventHandler (implements the EventHandler interface).</p>
<p>You can think of it as a taxi station at night, where all the drivers are sleeping except for one, the leader. The ThreadPool is a station managing many threads - cabs.</p>
<p>The leader is waiting for an IO event on the HandleSet, like how a driver waits for a client.</p>
<p>When a client arrives (in the form of a Handle identifying the IO event), the leader driver wakes up another driver to be the next leader and serves the request from his passenger.</p>
<p>While he is taking the client to the given address (calling ConcreteEventHandler and handing over Handle to it) the next leader can concurrently serve another passenger.</p>
<p>When a driver finishes he take his taxi back to the station and falls asleep if the station is not empty. Otherwise he become the leader.</p>
<p>The pros for this pattern are:</p>
<ul>
<li>no communication between the threads are necessary, no synchronization,
nor shared memory (no locks, mutexes)
are needed.</li>
<li>more ConcreteEventHandlers can be added without affecting any other
EventHandler</li>
<li>minimizes the latency because of the multiple threads</li>
</ul>
<p>The cons are:</p>
<ul>
<li>complex</li>
<li>network IO can be a bottleneck</li>
</ul> |
2,479,348 | Is it possible to get identical SHA1 hash? | <p>Given two different strings S1 and S2 (S1 != S2) is it possible that:</p>
<pre><code>SHA1(S1) == SHA1(S2)
</code></pre>
<p>is True?</p>
<ol>
<li>If yes - with what probability? </li>
<li>If not - why not?</li>
<li>Is there a upper bound on the length of a input string, for which the probability of getting duplicates is 0? OR is the calculation of SHA1 (hence probability of duplicates) independent of the length of the string?</li>
</ol>
<p>The goal I am trying to achieve is to hash some sensitive ID string (possibly joined together with some other fields like parent ID), so that I can use the hash value as an ID instead (for example in the database).</p>
<p>Example:</p>
<pre><code>Resource ID: X123
Parent ID: P123
</code></pre>
<p>I don't want to expose the nature of my resource identifies to allow client to see "X123-P123".</p>
<p>Instead I want to create a new column hash("X123-P123"), let's say it's AAAZZZ. Then the client can request resource with id AAAZZZ and not know about my internal id's etc.</p> | 2,480,819 | 5 | 9 | null | 2010-03-19 17:33:50.147 UTC | 19 | 2017-05-22 20:39:20.037 UTC | 2015-06-07 04:40:49.337 UTC | null | 226,001 | null | 74,865 | null | 1 | 81 | cryptography|hash|sha1|checksum | 58,135 | <p>What you describe is called a <em>collision</em>. Collisions necessarily exist, since SHA-1 accepts many more distinct messages as input that it can produce distinct outputs (SHA-1 may eat any string of bits up to 2^64 bits, but outputs only 160 bits; thus, at least one output value must pop up several times). This observation is valid for any function with an output smaller than its input, regardless of whether the function is a "good" hash function or not.</p>
<p>Assuming that SHA-1 behaves like a "random oracle" (a conceptual object which basically returns random values, with the sole restriction that once it has returned output <em>v</em> on input <em>m</em>, it must always thereafter return <em>v</em> on input <em>m</em>), then the probability of collision, for any two distinct strings S1 and S2, should be 2^(-160). Still under the assumption of SHA-1 behaving like a random oracle, if you collect many input strings, then you shall begin to observe collisions after having collected about 2^80 such strings.</p>
<p>(That's 2^80 and not 2^160 because, with 2^80 strings you can make about 2^159 pairs of strings. This is often called the "birthday paradox" because it comes as a surprise to most people when applied to collisions on birthdays. See <a href="http://en.wikipedia.org/wiki/Birthday_paradox" rel="noreferrer">the Wikipedia page</a> on the subject.)</p>
<p>Now we strongly suspect that SHA-1 does <em>not</em> really behave like a random oracle, because the birthday-paradox approach is the optimal collision searching algorithm for a random oracle. Yet there is a published attack which should find a collision in about 2^63 steps, hence 2^17 = 131072 times faster than the birthday-paradox algorithm. Such an attack should not be doable on a true random oracle. Mind you, this attack has not been actually completed, it remains theoretical (some people <a href="http://boinc.iaik.tugraz.at/" rel="noreferrer">tried but apparently could not find enough CPU power</a>)(<strong>Update:</strong> as of early 2017, somebody <em>did</em> compute a <a href="https://shattered.io/" rel="noreferrer">SHA-1 collision</a> with the above-mentioned method, and it worked exactly as predicted). Yet, the theory looks sound and it really seems that SHA-1 is not a random oracle. Correspondingly, as for the probability of collision, well, all bets are off.</p>
<p>As for your third question: for a function with a <em>n</em>-bit output, then there necessarily are collisions if you can input more than 2^<em>n</em> distinct messages, i.e. if the maximum input message length is greater than <em>n</em>. With a bound <em>m</em> lower than <em>n</em>, the answer is not as easy. If the function behaves as a random oracle, then the probability of the existence of a collision lowers with <em>m</em>, and not linearly, rather with a steep cutoff around <em>m=n/2</em>. This is the same analysis than the birthday paradox. With SHA-1, this means that if <em>m < 80</em> then chances are that there is no collision, while <em>m > 80</em> makes the existence of at least one collision very probable (with <em>m > 160</em> this becomes a certainty).</p>
<p>Note that there is a difference between "there exists a collision" and "you find a collision". Even when a collision <em>must</em> exist, you still have your 2^(-160) probability every time you try. What the previous paragraph means is that such a probability is rather meaningless if you cannot (conceptually) try 2^160 pairs of strings, e.g. because you restrict yourself to strings of less than 80 bits.</p> |
2,953,351 | iPhone Landscape FAQ and Solutions | <p>There has been a lot of confusion and a set of corresponding set of questions here on SO how iPhone applications with proper handling for Landscape/Portrait mode autorotation can be implemented. It is especially difficult to implement such an application when starting in landscape mode is desired. The most common observed effect are scrambled layouts and areas of the screen where touches are no longer recognized.</p>
<p>A simple search for questions tagged <code>iphone</code> and <code>landscape</code> reveals these issues, which occur under certain scenarios:</p>
<ul>
<li><p><a href="https://stackoverflow.com/questions/1891395/landscape-only-iphone-app-with-multiple-nibs">Landscape only iPhone app with multiple nibs</a>:
App started in Landscape mode, view from first nib is rendered fine, everything view loaded from a different nib is not displayed correctly.</p></li>
<li><p>Iphone Landscape mode switching to Portraite mode on loading new controller:
Self explanatory</p></li>
<li><p><a href="https://stackoverflow.com/questions/1632117/iphone-in-landscape-only-after-first-addsubview-uitableviewcontroller-doesnt">iPhone: In landscape-only, after first addSubview, UITableViewController doesn’t rotate properly</a>: Same issue as above.</p></li>
<li><p><a href="https://stackoverflow.com/questions/525737/iphone-landscape-only-utility-template-application">iPhone Landscape-Only Utility-Template Application</a>: Layout errors, controller does not seem to recognize the view should be rotated but displays a clipped portrait view in landscape mode, causing half of the screen to stay blank.</p></li>
<li><p><a href="https://stackoverflow.com/questions/1906280/presentmodalviewcontroller-in-landscape-after-portrait-viewcontroller">presentModalViewController in landscape after portrait viewController</a>: Modal views are not correctly rendered either.</p></li>
</ul>
<p>A set of different solutions have been presented, some of them including completely custom animation via CoreGraphics, while others build on the observation that the first view controller loaded from the main nib is always displayed correct. </p>
<p>I have spent a significant amount of time investigating this issue and finally found a solution that is not only a partial solution but should work under all these circumstances. It is my intend with this CW post to provide sort of a FAQ for others having issues with UIViewControllers in Landscape mode. </p>
<p>Please provide feedback and help improve the quality of this Post by incorporating any related observations. Feel free to edit and post other/better answers if you know of any.</p> | 2,953,579 | 6 | 1 | 2010-06-01 21:08:27.867 UTC | 2010-06-01 21:08:27.867 UTC | 30 | 2012-12-12 04:46:20.227 UTC | 2017-05-23 12:31:29.733 UTC | null | -1 | null | 125,407 | null | 1 | 18 | iphone|uiviewcontroller|orientation|landscape | 18,586 | <h2>What's in the <a href="http://developer.apple.com/iphone/library/featuredarticles/ViewControllerPGforiPhoneOS/BasicViewControllers/BasicViewControllers.html#//apple_ref/doc/uid/TP40007457-CH101-SW23" rel="nofollow noreferrer">documentation</a>:</h2>
<p>In your view controller, override shouldAutorotateToInterfaceOrientation: to declare your supported interface orientations. This property will/should be checked by the controller infrastructure everytime the device orientation changes.</p>
<pre><code>- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation
{
return (orientation == UIInterfaceOrientationLandscapeRight);
}
</code></pre>
<p>This is the absolute minimum your view controller needs to do. If you want to launch your application in landscape mode, you need to add the following key to your <code>.plist</code> file:</p>
<pre><code><key>UIInterfaceOrientation</key>
<string>UIInterfaceOrientationLandscapeRight</string>
</code></pre>
<p>Apple recommends starting landscape only applications in Landscape Right mode (see <a href="http://developer.apple.com/library/ios/DOCUMENTATION/UserExperience/Conceptual/MobileHIG/UEBestPractices/UEBestPractices.html#//apple_ref/doc/uid/TP40006556-CH20-SW25" rel="nofollow noreferrer">the HIG</a> under User Experience Guidelines > Start Instantly).</p>
<h2>What's not in the documentation:</h2>
<h3>A little background:</h3>
<p>Everytime you try to load a different view controller other than that loaded from the main nib, your view controller is neither interrogated about it's supported interface orientations nor is its frame set correctly. Only the first view controller bound to the window will be layed out correctly.</p>
<p>Other people have suggested using a "MasterViewController" hooked up to the main window to which other controllers add their views as subviews instead of hooking directly into the window. While I have found this solutions is a viable option, it does not work correctly in the case of modal view controllers added to those said subviews. There's also a problem if you have <em>some</em> subviews that should be able to autorotate (what the master controller will prevent).</p>
<p>The usage of undocumented API's to force a certain interface orientation is not an option either.</p>
<h3>The solution:</h3>
<p>The best solution I have found so far is a modification of the "MasterViewController" workaround. Instead of using a custom "MasterViewController", a <code>UINavigationController</code> with hidden Navigation Bar and hidden Tab Bar is used. If all other views are pushed/popped from the navigation stack of this controller, auto-rotations of controllers on that stack will be managed correctly.</p>
<p>Modal controllers presented via <code>presentModalViewController:animated:</code> from any of the view controllers on the <code>UINavigationController</code>'s navigation stack will be rotated and rendered with correct layout. If you want your modal view controller to be rotatable to a different orientation than that of the parent view controller, you need to return the desired orientation from the <code>shouldAutorotateToInterfaceOrientation</code> method of the <strong>parent</strong> controller while the modal view is presented. In order to properly restore the interface orientation when the modal controller is dismissed, you need to make sure <code>shouldAutorotateToInterfaceOrientation</code> returns the desired orientation for the parent controller before you call <code>dismissModalViewController:animated:</code>. You can use a private <code>BOOL</code> on your view controller to manage that (e.g. <code>BOOL isModalMailControllerActive_</code>).</p>
<p>I'll add a piece of sample code soon, It's just to late now. Please let me know if any unresolved issues remain or anything is unclear about this post. Feel free to edit and improve.</p> |
2,733,813 | Iterating through a JSON object | <p>I am trying to iterate through a JSON object to import data, i.e. title and link. I can't seem to get to the content that is past the <code>:</code>. </p>
<p><strong>JSON:</strong> </p>
<pre><code>[
{
"title": "Baby (Feat. Ludacris) - Justin Bieber",
"description": "Baby (Feat. Ludacris) by Justin Bieber on Grooveshark",
"link": "http://listen.grooveshark.com/s/Baby+Feat+Ludacris+/2Bqvdq",
"pubDate": "Wed, 28 Apr 2010 02:37:53 -0400",
"pubTime": 1272436673,
"TinyLink": "http://tinysong.com/d3wI",
"SongID": "24447862",
"SongName": "Baby (Feat. Ludacris)",
"ArtistID": "1118876",
"ArtistName": "Justin Bieber",
"AlbumID": "4104002",
"AlbumName": "My World (Part II);\nhttp://tinysong.com/gQsw",
"LongLink": "11578982",
"GroovesharkLink": "11578982",
"Link": "http://tinysong.com/d3wI"
},
{
"title": "Feel Good Inc - Gorillaz",
"description": "Feel Good Inc by Gorillaz on Grooveshark",
"link": "http://listen.grooveshark.com/s/Feel+Good+Inc/1UksmI",
"pubDate": "Wed, 28 Apr 2010 02:25:30 -0400",
"pubTime": 1272435930
}
]
</code></pre>
<p>I tried using a dictionary:</p>
<pre><code>def getLastSong(user,limit):
base_url = 'http://gsuser.com/lastSong/'
user_url = base_url + str(user) + '/' + str(limit) + "/"
raw = urllib.urlopen(user_url)
json_raw= raw.readlines()
json_object = json.loads(json_raw[0])
#filtering and making it look good.
gsongs = []
print json_object
for song in json_object[0]:
print song
</code></pre>
<p>This code only prints the information before <code>:</code>.
(<em>ignore the Justin Bieber track</em> :))</p> | 2,733,844 | 9 | 0 | null | 2010-04-28 23:30:21.777 UTC | 40 | 2021-10-20 20:17:10.477 UTC | 2016-11-22 14:38:26.96 UTC | null | 1,304,273 | null | 327,508 | null | 1 | 148 | python|dictionary|loops | 632,088 | <p>Your loading of the JSON data is a little fragile. Instead of:</p>
<pre><code>json_raw= raw.readlines()
json_object = json.loads(json_raw[0])
</code></pre>
<p>you should really just do:</p>
<pre><code>json_object = json.load(raw)
</code></pre>
<p>You shouldn't think of what you get as a "JSON object". What you have is a list. The list contains two dicts. The dicts contain various key/value pairs, all strings. When you do <code>json_object[0]</code>, you're asking for the first dict in the list. When you iterate over that, with <code>for song in json_object[0]:</code>, you iterate over the keys of the dict. Because that's what you get when you iterate over the dict. If you want to access the value associated with the key in that dict, you would use, for example, <code>json_object[0][song]</code>.</p>
<p>None of this is specific to JSON. It's just basic Python types, with their basic operations as covered in any tutorial.</p> |
2,778,840 | socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions | <p>I'm trying to create a custom TCP stack using Python 2.6.5 on Windows 7 to serve valid http page requests on port 80 locally. But, I've run into a snag with what seems like Windows 7 tightened up security. This code worked on Vista.</p>
<p>Here's my sample code:</p>
<pre><code>import SocketServer
import struct
class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
headerText = """HTTP/1.0 200 OK
Date: Fri, 31 Dec 1999 23:59:59 GMT
Content-Type: text/html
Content-Length: 1354"""
bodyText = "<html><body>some page</body></html>"
self.request.send(headerText + "\n" + bodyText)
if __name__ == "__main__":
HOST, PORT = "localhost", 80
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
</code></pre>
<blockquote>
<p><b>C:\python>python TestServer.py</b>
Traceback (most recent call last):<br>
File "TestServer.py", line 19, in
server = SocketServer.TCPServer((HOST, PORT),
MyTCPHandler) File
"C:\Python26\lib\SocketServer.py",
line 400, in <strong>init</strong>
self.server_bind() File "C:\Python26\lib\SocketServer.py",
line 411, in server_bind
self.socket.bind(self.server_address)
File "", line 1, in bind</p>
<p>socket.error: [Errno 10013] An attempt
was made to access a socket in a way
forbidden by its access permissions</p>
</blockquote>
<p>How exactly do I get this to work on Windows 7?</p>
<p>[Edit on 5/5/2010 @ 2344 PDT] This <a href="https://stackoverflow.com/questions/550032/what-causes-python-socket-error">answer</a> explains that the error is caused by the need for elevated / superuser privileges when accessing ports lower than 1024. I'm going to try using a higher port number to see if that works. However, I still would like to know why my local admin account can't access port 80. </p> | 2,779,304 | 19 | 3 | null | 2010-05-06 06:12:27.76 UTC | 15 | 2022-02-22 11:14:40.82 UTC | 2017-05-23 12:32:14.49 UTC | null | -1 | null | 86,263 | null | 1 | 61 | python|sockets|windows-7|compatibility|socketserver | 242,452 | <p>On Windows Vista/7, with UAC, administrator accounts run programs in unprivileged mode by default.</p>
<p>Programs must prompt for administrator access before they run as administrator, with the ever-so-familiar UAC dialog. Since Python scripts aren't directly executable, there's no "Run as Administrator" context menu option.</p>
<p>It's possible to use <code>ctypes.windll.shell32.IsUserAnAdmin()</code> to detect whether the script has admin access, and <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb762154%28v=vs.85%29.aspx" rel="noreferrer"><code>ShellExecuteEx</code></a> with the 'runas' verb on python.exe, with sys.argv[0] as a parameter to prompt the UAC dialog if needed.</p> |
65,266,636 | Is ApplicationComponent deprecated? | <p>I just started using Dagger Hilt for dependency injection on Android and I get a warning on Android Studio saying <code>'ApplicationComponent' is deprecated. Deprecated in Java</code>.</p>
<p>I didn't find anything related to this warning while Googling, is it actually deprecated or is it safe to use?</p>
<p>I also noticed on Dagger's website that they don't mention it anywhere in the "<a href="https://dagger.dev/hilt/migration-guide" rel="noreferrer">Migrating to Hilt</a>" guide and they use <code>@InstallIn(SingletonComponent::class)</code> which seems to be working but I have no idea why.</p> | 65,272,745 | 2 | 0 | null | 2020-12-12 15:27:51.48 UTC | 7 | 2022-05-07 04:24:55.74 UTC | 2020-12-12 15:39:50.563 UTC | null | 286,934 | null | 6,090,706 | null | 1 | 48 | android|dagger|dagger-hilt | 10,262 | <p><code>ApplicationComponent</code> being renamed to <code>SingletonComponent</code>, to allow usage of Hilt in non-Android Gradle modules <a href="https://github.com/google/dagger/releases/tag/dagger-2.28.2" rel="noreferrer">link</a></p> |
40,150,403 | Material UI React Table onCellClick not working on TableRow | <p>I have material UI Table in my react component. I want to add onCellClick event to each of the row of my table. But when I add onCellClick to each TableRow then it doesn't get fired. But when I add it to my Table Tag then it get's fired. The problem with this is when I add it to Table tag the only one type of action can be taken for all the rows. What if I want to do different things with each row whenever I click them. That's why I want to have all the TableRow tags their own onClick type of event. How can I do this? </p>
<p>Here is my code with onCellClick event on Table Tag, which I don't want. </p>
<pre><code>class TagDetailTable extends Component {
handleButtonClick() {
browserHistory.push("TagList")
}
handleCellClick(){
console.log("cell clicked")
}
render() {
return (
<MuiThemeProvider>
<div>
<Table onCellClick= {this.handleCellClick}>
<TableHeader>
<TableRow>
<TableHeaderColumn>ID</TableHeaderColumn>
<TableHeaderColumn>Type</TableHeaderColumn>
<TableHeaderColumn>Category</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody>
<TableRow>
<TableRowColumn>1</TableRowColumn>
<TableRowColumn>Cigarette</TableRowColumn>
<TableRowColumn>Compliance</TableRowColumn>
</TableRow>
<TableRow >
<TableRowColumn>2</TableRowColumn>
<TableRowColumn>Cigarette</TableRowColumn>
<TableRowColumn>Compliance</TableRowColumn>
</TableRow>
<TableRow >
<TableRowColumn>3</TableRowColumn>
<TableRowColumn>Cigarette</TableRowColumn>
<TableRowColumn>Compliance</TableRowColumn>
</TableRow>
<TableRow >
<TableRowColumn>4</TableRowColumn>
<TableRowColumn>Alcohol</TableRowColumn>
<TableRowColumn>Compliance</TableRowColumn>
</TableRow>
<TableRow >
<TableRowColumn>5</TableRowColumn>
<TableRowColumn>Alcohol</TableRowColumn>
<TableRowColumn>Compliance</TableRowColumn>
</TableRow>
{/*<TableRow>*/}
{/*<TableRowColumn>4</TableRowColumn>*/}
{/*<TableRowColumn>Alcohol</TableRowColumn>*/}
{/*<TableRowColumn>Compliance</TableRowColumn>*/}
{/*</TableRow>*/}
{/*<TableRow>*/}
{/*<TableRowColumn>4</TableRowColumn>*/}
{/*<TableRowColumn>Alcohol</TableRowColumn>*/}
{/*<TableRowColumn>Compliance</TableRowColumn>*/}
{/*</TableRow>*/}
{/*<TableRow>*/}
{/*<TableRowColumn>4</TableRowColumn>*/}
{/*<TableRowColumn>Alcohol</TableRowColumn>*/}
{/*<TableRowColumn>Compliance</TableRowColumn>*/}
{/*</TableRow>*/}
</TableBody>
</Table>
<div className="backButton">
<RaisedButton backgroundColor="#293C8E" label="Back" onClick={this.handleButtonClick}
labelColor="white">
</RaisedButton>
</div>
</div>
</MuiThemeProvider>
);
}
}
</code></pre> | 40,151,381 | 3 | 0 | null | 2016-10-20 09:23:21.87 UTC | null | 2019-09-19 23:07:53.72 UTC | null | null | null | null | 3,761,761 | null | 1 | 3 | javascript|reactjs|material-ui | 38,081 | <p>Attaching OnCellClick to Row is not supported. See <a href="https://github.com/callemall/material-ui/issues/2819" rel="nofollow">https://github.com/callemall/material-ui/issues/2819</a> for more details.</p>
<p>However, you could use the function parameter of the handleCellClick. The signature of the function receiving the event is:</p>
<pre><code>handleCellClick(row,column,event)
{
if(row ==0)
console.log('Cigarette row clicked');
}
</code></pre> |
40,112,618 | Bootstrap4 adding scrollbar to div | <p>I am using <a href="http://v4-alpha.getbootstrap.com/components/navs/#stacked-pills" rel="noreferrer">stacked pills</a> inside a <code>div</code>. The problem is, sometimes the <code>div</code> contains a lot of pills. How can I add a scrollbar for it?</p>
<pre><code><div class="row col-md-2">
<ul class="nav nav-pills nav-stacked">
<li class="nav-item">
<a class="nav-link active" href="#">Active</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
</div>
</code></pre>
<p>Can I add a class for the div to make stacked pills scrollable?</p> | 40,395,206 | 4 | 0 | null | 2016-10-18 15:43:51.4 UTC | 8 | 2020-09-26 11:37:05.02 UTC | null | null | null | null | 1,596,786 | null | 1 | 65 | bootstrap-4 | 199,148 | <p>Yes, It is possible,
Just add a class like <code>anyclass</code>
and give some CSS style. <a href="https://jsfiddle.net/ashikjs/we2qwxa6/2/" rel="noreferrer">Live</a> </p>
<pre><code>.anyClass {
height:150px;
overflow-y: scroll;
}
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.anyClass {
height:150px;
overflow-y: scroll;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" rel="stylesheet"/>
<div class=" col-md-2">
<ul class="nav nav-pills nav-stacked anyClass">
<li class="nav-item">
<a class="nav-link active" href="#">Active</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li><li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li><li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li><li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li><li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
</div></code></pre>
</div>
</div>
</p> |
10,742,491 | Using an iterator to print out every member of a set | <p>I'm trying to use an iterator to print out every member of a set. As far as I can tell from other stackoverflow answers, I have the correct formatting. When I run this code, it correctly outputs that the size of myset is 3, but it only outputs ii once. If I uncomment the line with *iter, Visual Studio throws a runtime exception saying that that "map/set iterator is not dereferencable. Any idea why?</p>
<pre><code>int main()
{
set<int> myset;
myset.insert(5);
myset.insert(6);
myset.insert(7);
set<int>::iterator iter;
cout<<myset.size()<<endl;
int ii=0;
for(iter=myset.begin(); iter!=myset.end();++iter);{
//cout<<(*iter)<<endl;
ii+=1;
cout<<ii<<endl;
}
return 0;
}
</code></pre> | 10,742,584 | 1 | 0 | null | 2012-05-24 17:31:44.987 UTC | 1 | 2017-01-26 14:06:02.077 UTC | 2012-05-24 17:49:53.653 UTC | null | 1,128,737 | null | 1,415,670 | null | 1 | 6 | c++|iterator|set | 38,061 | <p>You have an extra <code>;</code> in this line:</p>
<pre><code>for(iter=myset.begin(); iter!=myset.end();++iter);{
</code></pre>
<p>This means that the loop's body is actually empty, and the following lines are executed once only.</p>
<p>So change that line to this:</p>
<pre><code>for(iter=myset.begin(); iter!=myset.end();++iter) {
</code></pre> |
10,308,985 | Django on Heroku - Broken Admin Static Files | <p>I have a Django app running on Heroku/Cedar, configured as per the instructions at <a href="https://devcenter.heroku.com/articles/django" rel="noreferrer">https://devcenter.heroku.com/articles/django</a></p>
<p>Using gunicorn as per Heroku's instructions fails to include the static files required for Django's admin to function. I can change the Procfile to "manage.py run_gunicorn" for local development, but that doesn't fly on Heroku.</p>
<p>I've searched all over for a fix - is there some way to include the admin static files without throwing them on S3 with my other static files?</p> | 10,309,093 | 9 | 0 | null | 2012-04-25 03:32:42.437 UTC | 9 | 2018-03-21 08:36:03.647 UTC | null | null | null | null | 747,460 | null | 1 | 17 | django|heroku|django-admin | 11,365 | <p>If you use runserver and configure your app with DEBUG=True, then it will serve the admin files just like on your development machine. However, this is definitely not the recommended way to do it, and I would suggest that you put them on S3.</p>
<p>Using the django-storages app it's very easy to configure collectstatic to automatically push all the admin files to S3. You can find directions <a href="http://django_compressor.readthedocs.org/en/latest/remote-storages/" rel="noreferrer">here</a></p> |
10,503,668 | MultiLine EditText in Android with the cursor starting on top | <p>I know it seems it's an already thousand times answered issue but I haven't found anything that works for me.</p>
<p>I have a MultiLine EditText on Android that adapts to the view size by "playing" with the weight (1) and the height (0dip). I am using gravity "top" but it starts in the middle.</p>
<p>I guess the problem it's related with the weight. Here's the code (the parent is a LinearLayout):</p>
<pre><code> <EditText
android:id="@+id/txtContacto"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_gravity="top"
android:inputType="textMultiLine"
android:weight="1">
</EditText>
</code></pre> | 10,503,683 | 1 | 0 | null | 2012-05-08 17:42:37.697 UTC | 4 | 2013-06-07 04:05:18.887 UTC | 2013-06-07 04:05:18.887 UTC | null | 739,270 | null | 1,344,727 | null | 1 | 60 | android|android-layout|android-edittext | 58,897 | <pre><code><EditText
android:id="@+id/txtContacto"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:gravity="top"
android:inputType="textMultiLine"
android:weight="1">
</EditText>
</code></pre>
<p>try the above code.. where layout gravity sets the edittext and gravity sets the content of edittext.</p> |
20,901,760 | Subtracting days, months or years from date using php | <p>I have a db table with a date field <code>startBefore</code> in <code>('Y-m-d')</code> format. There are also 3 other int fields representing years, months and days. What I would like to do is to fill these three fields the new <code>startAfter</code> date in <code>'Y-m-d'</code> format.</p>
<p>For example I have the '2001-11-14' as <code>startBefore</code> date and I would like to subtract 3 yrs, 7 months, 1 day to get the <code>startAfter</code> date.</p>
<p>Any ideas how I can accomplish this?</p>
<p>Thanks!</p> | 20,902,030 | 4 | 1 | null | 2014-01-03 10:43:55.86 UTC | 3 | 2014-01-03 11:01:33.39 UTC | 2014-01-03 10:49:19.08 UTC | null | 2,310,830 | null | 3,146,418 | null | 1 | 23 | php|date | 54,347 | <p>use <code>strtotime('date -years -months -days')</code></p>
<pre><code> <?php
$time = strtotime('2001-11-14 -3 years -7 months -5 days');
echo $date = date("Y-m-d", $time);
</code></pre> |
21,397,177 | Finding Location : Google Play Location Service or Android platform location APIs | <p>i am trying to get the users location for my new navigation app.
i want to check the users location frequently and it has to be accurate .
I use the following code from sample to get the location .</p>
<pre><code>public class MainActivity extends Activity implements LocationListener {
private LocationManager locationManager;
private String provider;
private TextView a;
private TextView b;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a = (TextView) findViewById(R.id.a);
b = (TextView) findViewById(R.id.b);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
a.setText("Location not available");
b.setText("Location not available");
}
}
@Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider,0, 1, this);
}
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
@Override
public void onLocationChanged(Location location) {
Double lat = location.getLatitude();
Double lng = location.getLongitude();
a.setText(String.valueOf(lat));
b.setText(String.valueOf(lng));
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
</code></pre>
<p>But location cordinates are not updating as i move,i get a constant value always ...
is there any better way to get location ? According to to android docs i can use Google Play Location Service or Android platform location APIs for this .
I checked the sample code for both and it implements the LocationListener interface to get the user location .So whats the actual difference between them?</p> | 21,508,757 | 2 | 2 | null | 2014-01-28 04:58:40.743 UTC | 9 | 2016-02-11 03:38:25.523 UTC | 2014-01-28 05:15:56.88 UTC | null | 2,616,191 | null | 2,616,191 | null | 1 | 11 | android|geolocation|gps|location | 21,299 | <p>Absolutely use the new google play location services. They work much better indoors than the old location manager. I have created a sample that uses the new google play location services and works in the background periodically. Check it out:</p>
<p><a href="https://github.com/nickfox/GpsTracker/tree/master/phoneClients/android" rel="nofollow noreferrer">https://github.com/nickfox/GpsTracker/tree/master/phoneClients/android</a></p> |
54,327,548 | Trying to repeat a http request after refresh token with a interceptor in angular 7 | <p>I'm trying to automate the refresh token requests upon receiving an error 401 with angular 7.</p>
<p>Between that I do not find much documentation of how to do it with angular 7 and that I do not have previous knowledge of angular or rxjs I am becoming a little crazy</p>
<p>I think it's almost completed, but for some reason the second next.handle(newReq) dont send the request (in google chrome network debugger only apears first request)</p>
<p>i'm gettin the response of refresh and making processLoginResponse(res) correctly</p>
<p>you can see here my interceptor</p>
<pre><code>intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let newReq = req.clone();
return next.handle(req).pipe(
catchError(error => {
if (error.status == 401) {
this._authenticationService.refresh().subscribe(
res => {
this._authenticationService.processLoginResponse(res);
newReq.headers.set("Authorization", "Bearer " + this._authenticationService.authResponse.token)
return next.handle(newReq)
},
error => {
this._authenticationService.logOut();
});
}
throw error;
})
);
</code></pre> | 54,328,099 | 3 | 1 | null | 2019-01-23 12:42:53.58 UTC | 9 | 2020-09-21 10:18:22.7 UTC | 2019-01-23 12:54:13.11 UTC | user10955671 | null | user10955671 | null | null | 1 | 12 | angular|jwt|angular-http-interceptors | 12,811 | <p>You have to distingiush among all the requests. For example you don't want to intercept your login request and also not the refresh token request. SwitchMap is your best friend because you need to cancel some calls to wait for your token is getting refreshed.</p>
<p>So what you do is check first for error responses with status 401 (unauthorized):</p>
<pre><code>return next.handle(this.addToken(req, this.userService.getAccessToken()))
.pipe(catchError(err => {
if (err instanceof HttpErrorResponse) {
// token is expired refresh and try again
if (err.status === 401) {
return this.handleUnauthorized(req, next);
}
// default error handler
return this.handleError(err);
} else {
return observableThrowError(err);
}
}));
</code></pre>
<p>In your handleUnauthorized function you have to refresh your token and also skip all further requests in the meantime:</p>
<pre><code> handleUnauthorized (req: HttpRequest<any>, next: HttpHandler): Observable<any> {
if (!this.isRefreshingToken) {
this.isRefreshingToken = true;
// Reset here so that the following requests wait until the token
// comes back from the refreshToken call.
this.tokenSubject.next(null);
// get a new token via userService.refreshToken
return this.userService.refreshToken()
.pipe(switchMap((newToken: string) => {
// did we get a new token retry previous request
if (newToken) {
this.tokenSubject.next(newToken);
return next.handle(this.addToken(req, newToken));
}
// If we don't get a new token, we are in trouble so logout.
this.userService.doLogout();
return observableThrowError('');
})
, catchError(error => {
// If there is an exception calling 'refreshToken', bad news so logout.
this.userService.doLogout();
return observableThrowError('');
})
, finalize(() => {
this.isRefreshingToken = false;
})
);
} else {
return this.tokenSubject
.pipe(
filter(token => token != null)
, take(1)
, switchMap(token => {
return next.handle(this.addToken(req, token));
})
);
}
}
</code></pre>
<p>We have an attribute on the interceptor class which checks if there is already a refresh token request running: <code>this.isRefreshingToken = true;</code> because you don't want to have multiple refresh request when you fire multiple unauthorized requests.</p>
<p>So everthing within the <code>if (!this.isRefreshingToken)</code> part is about refreshing your token and try the previous request again.</p>
<p>Everything which is handled in <code>else</code> is for all requests, in the meantime while your userService is refreshing the token, a tokenSubject gets returned and when the token is ready with <code>this.tokenSubject.next(newToken);</code> every skipped request will be retried.</p>
<p>Here this article was the origin inspiration for the interceptor: <a href="https://www.intertech.com/angular-4-tutorial-handling-refresh-token-with-new-httpinterceptor/" rel="noreferrer">https://www.intertech.com/angular-4-tutorial-handling-refresh-token-with-new-httpinterceptor/</a></p>
<p><strong>EDIT:</strong></p>
<p>TokenSubject is actually a Behavior Subject: <code>tokenSubject: BehaviorSubject<string> = new BehaviorSubject<string>(null);</code>, which means any new subscriber will get the current value in the stream, which would be the old token from last time we call <code>this.tokenSubject.next(newToken)</code>.</p>
<p>With<code>next(null)</code> every new subscriber does not trigger the <code>switchMap</code> part, thats why <code>filter(token => token != null)</code> is neccessary.</p>
<p>After <code>this.tokenSubject.next(newToken)</code> is called again with a new token every subscriber triggers the <code>switchMap</code> part with the fresh token. Hope it is more clearly now</p>
<p><strong>EDIT 21.09.2020</strong></p>
<p>Fix link</p> |
18,990,874 | Similar technology to Chrome's Native Client Messaging in Firefox? | <p>We want to replace a custom NPAPI interface between a browser based web application and an client side daemon process.</p>
<p>Is there a similar technology to Chrome's Native Client Messaging in Firefox?</p> | 20,300,890 | 2 | 0 | null | 2013-09-24 19:57:08.64 UTC | 11 | 2015-09-23 01:55:51.39 UTC | 2014-04-30 11:16:13.057 UTC | null | 336,656 | null | 1,300,209 | null | 1 | 15 | google-chrome|firefox|jsctypes|chrome-native-messaging | 3,739 | <p>js-ctypes[1] is probably the closest alternative for Mozilla.</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes">https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes</a></p>
<p>I have a C++ module that I compile as a binary executable for native-messaging or as a library for js-ctypes. The difference between the two is primarily that native-messaging calls a binary executable and performs stdin/stdout data exchange, and js-ctypes opens a static/shared library (via dlopen) and calls exposed methods of your library which can return compatible data types[2] and optionally call a passed JavaScript callback method.</p>
<p>[1] <a href="https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes">https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes</a></p>
<p>[2] <a href="https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/js-ctypes_reference/ctypes#Predefined_data_types">https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/js-ctypes_reference/ctypes#Predefined_data_types</a></p> |
18,860,243 | SDL_PollEvent vs SDL_WaitEvent | <p>So I was reading this article which contains 'Tips and Advice for Multithreaded Programming in SDL' - <a href="https://vilimpoc.org/research/portmonitorg/sdl-tips-and-tricks.html" rel="noreferrer">https://vilimpoc.org/research/portmonitorg/sdl-tips-and-tricks.html</a></p>
<p>It talks about SDL_PollEvent being inefficient as it can cause excessive CPU usage and so recommends using SDL_WaitEvent instead.</p>
<p>It shows an example of both loops but I can't see how this would work with a game loop. Is it the case that SDL_WaitEvent should only be used by things which don't require constant updates ie if you had a game running you would perform game logic each frame.</p>
<p>The only things I can think it could be used for are programs like a paint program where there is only action required on user input.</p>
<p>Am I correct in thinking I should continue to use SDL_PollEvent for generic game programming?</p> | 18,863,281 | 5 | 0 | null | 2013-09-17 21:31:11.243 UTC | 9 | 2022-01-22 13:39:38.403 UTC | null | null | null | null | 2,059,346 | null | 1 | 24 | sdl|sdl-2 | 19,102 | <p>If your game only updates/repaints on user input, then you could use SDL_WaitEvent. However, most games have animation/physics going on even when there is no user input. So I think SDL_PollEvent would be best for most games.</p>
<p>One case in which SDL_WaitEvent might be useful is if you have it in one thread and your animation/logic on another thread. That way even if SDL_WaitEvent waits for a long time, your game will continue painting/updating. (EDIT: This may not actually work. See Henrik's comment below)</p>
<p>As for SDL_PollEvent using 100% CPU as the article indicated, you could mitigate that by adding a sleep in your loop when you detect that your game is running more than the required frames-per-second.</p> |
28,174,609 | when I use iframe in ion-content, the ion-content scroll is not working | <pre><code><ion-view view-title="title">
<ion-content scroll="true">
<iframe src="{{link}}"></iframe>
</ion-content>
</ion-view>
</code></pre>
<p>look at the code above.</p>
<p>as the title says,when I use a iframe in the ion-content the scroll does't work.</p>
<p>How to solve this problem.</p> | 28,406,511 | 4 | 0 | null | 2015-01-27 15:56:05.963 UTC | 4 | 2020-01-08 00:32:03.54 UTC | 2020-01-08 00:32:03.54 UTC | null | 8,390,808 | null | 4,483,021 | null | 1 | 7 | javascript|html|css|ionic-framework|iframe | 40,694 | <p>It's a bug on ios. I have resolved this problem. Refer to the following</p>
<p><a href="https://stackoverflow.com/questions/26046373/iframe-scrolling-ios-8">Iframe scrolling iOS 8</a></p> |
9,000,164 | How to check BLAS/LAPACK linkage in NumPy and SciPy? | <p>I am builing my numpy/scipy environment based on blas and lapack more or less based on <a href="http://www.tfinley.net/notes/blas-lapack/" rel="noreferrer">this</a> walk through. </p>
<p>When I am done, how can I check, that my numpy/scipy functions really do use the previously built blas/lapack functionalities?</p> | 19,350,234 | 5 | 0 | null | 2012-01-25 09:15:34.407 UTC | 50 | 2020-06-15 20:15:13.663 UTC | 2019-05-14 21:28:38.593 UTC | null | 5,918,836 | null | 572,616 | null | 1 | 138 | python|numpy|scipy|lapack|blas | 88,077 | <p>The method <code>numpy.show_config()</code> (or <code>numpy.__config__.show()</code>) outputs information about linkage gathered at build time. My output looks like this. I think it means I am using the BLAS/LAPACK that ships with Mac OS. </p>
<pre><code>>>> import numpy as np
>>> np.show_config()
lapack_opt_info:
extra_link_args = ['-Wl,-framework', '-Wl,Accelerate']
extra_compile_args = ['-msse3']
define_macros = [('NO_ATLAS_INFO', 3)]
blas_opt_info:
extra_link_args = ['-Wl,-framework', '-Wl,Accelerate']
extra_compile_args = ['-msse3', '-I/System/Library/Frameworks/vecLib.framework/Headers']
define_macros = [('NO_ATLAS_INFO', 3)]
</code></pre> |
57,582,813 | SwiftUI -> Thread 1: Fatal error: No observable object of type MyObject.Type found (EnvironmentObject in sheet) | <p>I'm building an app with SwiftUI. When I was trying to display a sheet (previously Modal), this error message appears:</p>
<blockquote>
<p>Thread 1: Fatal error: No observable object of type BixiStationCombinedListViewModel.Type found.</p>
<p>A View.environmentObject(_:) for BixiStationCombinedListViewModel.Type may be missing as an ancestor of this view.</p>
</blockquote>
<p>This error occurs when I'm using a <code>@State</code> variable to display a modal that includes a <code>Map View</code> using MapKit.</p>
<p>I don't see why and how I should implement a new <code>Environment Object</code>.</p>
<p>Is it because the <code>Station</code> I select when tapping on the <code>CardView</code> should be stored globally and the info should be passed to the dedicated <code>View</code>?</p>
<p>The <code>View</code> handling the <code>@State</code>:</p>
<pre><code>struct CardView: View {
@EnvironmentObject var bixiModel: BixiStationCombinedListViewModel
@State private var isModalOpen: Bool = false
var station: BixiStationCombinedViewModel
var body: some View {
ZStack(alignment: .leading) {
Card()
StationTextInfo(station: station)
} .onTapGesture {
self.isModalOpen = true
print(self.isModalOpen)
}
.sheet(isPresented: self.$isModalOpen) {
BixiStationDetailView(station: self.station)
}
}
}
</code></pre>
<p>The <code>View</code> I'm trying to show within the sheet:</p>
<pre><code>struct BixiStationDetailView: View {
@EnvironmentObject var bixiModel: BixiStationCombinedListViewModel
var station: BixiStationCombinedViewModel
var body: some View {
VStack {
MapView(coordinate: station.coordinate, name: station.name)
}
}
}
</code></pre>
<p>Finally the Object:</p>
<pre><code>class BixiStationCombinedListViewModel: ObservableObject {
init() {
fetchDataFromApi()
}
@Published var stationsCombinedList = [BixiStationCombinedViewModel]()
var stationsInformationList = [BixiStationInformationViewModel]()
var stationsDataList = [BixiStationDataViewModel]()
func fetchDataFromApi() {
}
}
}
</code></pre>
<p>How can I get rid of the error message and display the proper <code>View</code>?</p> | 57,583,335 | 1 | 0 | null | 2019-08-20 23:52:53.217 UTC | 16 | 2022-06-22 00:49:47.343 UTC | 2022-06-22 00:49:47.343 UTC | null | 1,265,393 | null | 11,909,482 | null | 1 | 57 | ios|swift|observable|fatal-error|swiftui | 22,425 | <p>You have to pass your environment object to <code>BixiStationDetailView</code>, otherwise it won't have anything to bind to its <code>@EnvironmentObject</code>.</p>
<pre class="lang-swift prettyprint-override"><code>.sheet(isPresented: self.$isModalOpen) {
BixiStationDetailView(station: self.station)
.environmentObject(self.bixiModel)
}
</code></pre>
<p>Since you're presenting <code>BixiStationDetailView</code> as a sheet, it isn't a subview of your <code>CardView</code> and therefore doesn't inherit its <code>@EnvironmentObject</code>.</p> |
57,492,517 | Difference between yield and yield* in Dart | <p>I wanted to know what's the difference between this two. I find this SO post on javascript, <a href="https://stackoverflow.com/questions/17491779/delegated-yield-yield-star-yield-in-generator-functions">Delegated yield (yield star, yield *) in generator functions</a></p>
<p>From what I understand, <code>yield*</code> delegates to the another generator and after the another generator stop producing values, then it resumes generating its own values. </p>
<p>Explanation and examples on the dart side would be helpful.</p> | 57,492,636 | 4 | 0 | null | 2019-08-14 10:02:57.24 UTC | 7 | 2022-04-03 04:09:27.09 UTC | 2019-08-14 13:15:20.46 UTC | null | 6,618,622 | null | 9,779,791 | null | 1 | 49 | flutter|dart | 16,878 | <h3><code>yield</code></h3>
<p>It is used to emit values from a generator either async or sync.</p>
<p><strong>Example:</strong></p>
<pre><code>Stream<int> str(int n) async* {
for (var i = 1; i <= n; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}
void main() {
str(3).forEach(print);
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>1
2
3
</code></pre>
<hr />
<h3><code>yield*</code></h3>
<p>It delegates the call to another generator and after that generator stops producing the values, it resumes generating its own values.</p>
<p><strong>Example:</strong></p>
<pre><code>Stream<int> str(int n) async* {
if (n > 0) {
await Future.delayed(Duration(seconds: 1));
yield n;
yield* str(n - 1);
}
}
void main() {
str(3).forEach(print);
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>3
2
1
</code></pre> |
43,589,290 | Mongo service start or restart always fail | <p>I've installed mongodb then I've created a mongo service: </p>
<pre><code> [Unit]
Description=High-performance, schema-free document-oriented database
After=network.target
[Service]
User=mongodb
ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf
[Install]
WantedBy=multi-user.target
</code></pre>
<p>But When I launch the service and then I check the status, I get always this error:</p>
<pre><code>● mongodb.service - High-performance, schema-free document-oriented database
Loaded: loaded (/etc/systemd/system/mongodb.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Mon 2017-04-24 13:08:55 UTC; 6min ago
Process: 1094 ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf (code=exited, status=48)
Main PID: 1094 (code=exited, status=48)
Apr 24 13:08:54 ip-172-31-37-163 systemd[1]: Started High-performance, schema-free document-oriented database.
Apr 24 13:08:55 ip-172-31-37-163 systemd[1]: mongodb.service: Main process exited, code=exited, status=48/n/a
Apr 24 13:08:55 ip-172-31-37-163 systemd[1]: mongodb.service: Unit entered failed state.
Apr 24 13:08:55 ip-172-31-37-163 systemd[1]: mongodb.service: Failed with result 'exit-code'.
</code></pre> | 43,864,346 | 5 | 0 | null | 2017-04-24 13:22:21.237 UTC | 2 | 2020-12-04 03:05:54.02 UTC | null | null | null | null | 1,310,952 | null | 1 | 14 | linux|mongodb|ubuntu|ubuntu-16.04 | 43,733 | <p>The problem was in config file and changing </p>
<blockquote>
<p>bindIp: 127.0.0.1, X.X.X.X</p>
</blockquote>
<p>to </p>
<blockquote>
<p>bindIp: [127.0.0.1, X.X.X.X]</p>
</blockquote>
<p>Solved my issue </p> |
1,303,118 | Looking for a diagram to explain WSGI | <p>To help further my understanding of WSGI I'm looking for a diagram which explains the flow of an application, from webserver (eg. apache) through a number of middlewares to "code" (as in, the <code>print "hello world"</code> bit). </p>
<p>I've read various articles regarding WSGI from wsgi.org, but it's still not "clicking" for me and as for diagrams Google isn't bringing anything useful back except <a href="http://uswaretech.com/blog/wp-content/uploads/2009/06/django_request_response_lifecycle.png" rel="noreferrer">this</a> for django which, while interesting, is expecting the user to understand how middleware links-up and such.</p>
<p>Since "a picture is worth a thousand words", are there any diagrams out there which get a bit lower/more simplistic than this?</p> | 7,706,396 | 3 | 6 | null | 2009-08-19 23:10:07.19 UTC | 12 | 2021-02-24 09:10:14.92 UTC | 2009-08-20 05:32:14.943 UTC | null | 30,478 | null | 30,478 | null | 1 | 16 | python|diagram|wsgi | 5,027 | <p>As I gained nothing by looking at Ian's fancy tubes I decided to draw a diagram myself. I hope it will help someone understand how WSGI flow works. As long as you have suggestions how to make it better I'm open to modify it. It was created with <a href="https://www.lucidchart.com/users/registerLevel/155237?tP=1&t10=A" rel="nofollow noreferrer">LUCIDCHART</a> webapp. The original diagram you can find <a href="http://www.lucidchart.com/documents/view/4e8cd735-776c-4b7a-b8a0-780b0afc7621" rel="nofollow noreferrer">here</a> and the high quality PNG is <a href="http://www.lucidchart.com/publicSegments/view/4e9205ed-ad18-495e-bbb0-04c20a7f0d03/image.png" rel="nofollow noreferrer">here</a>.</p>
<p><img src="https://i.stack.imgur.com/glnJA.png" alt="WSGI Flow" /></p> |
1,081,219 | Optimizing CLLocationManager/CoreLocation to retrieve data points faster on the iPhone | <p>I'm currently using CoreLocation + CLLocationManager in order to compare a users current location to N amount of other locations. The problem I'm facing is I'm dealing with urban areas where locations are close to each other, so I need to pin point the location of the user as accurately as the device allows without sacrificing too much time. My calculations are darn accurate, the problem is, it takes far too long to collect 10 samples. I'll paste my filters/accuracy respective code below. If anyone can comment on how I can speed this up, that would be great. Until I speed it up, it's rather useless in my app as it currently takes around 3-4 minutes to gather info, a duration that's not accept by my target demographic.</p>
<p>Code looks something like this:</p>
<pre><code>[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if (newLocation.horizontalAccuracy > 0.0f &&
newLocation.horizontalAccuracy < 120.0f) { // roughly an accuracy of 120 meters, we can adjust this.
[myLocs addObject:newLocation];
}
</code></pre>
<p>Thanks for any optimization tricks to speed this up.</p> | 1,348,652 | 3 | 0 | null | 2009-07-04 00:43:36.007 UTC | 38 | 2017-04-19 16:42:29.643 UTC | 2009-07-04 00:52:54.273 UTC | anon | null | anon | null | null | 1 | 17 | iphone|cocoa-touch|core-location | 26,923 | <p>I've had lots of issues with CLLocationManager on the iPhone also.
From different Apps, and trial and error this is what I've figured out;</p>
<p>1) Use a singleton class for the locationManager, ONLY ONE Instance, follow the examples in:</p>
<p>Apple's LocateMe example</p>
<p>Tweetero : <a href="http://tweetero.googlecode.com/svn/trunk" rel="nofollow noreferrer">http://tweetero.googlecode.com/svn/trunk</a></p>
<p>I'm thinking you can only have one location manager running, there's only one GPS chip in the iPhone, thus if you launch multiple location manager object's they'll conflict, and you get errors from the GPS location manager stating it can't update.</p>
<p>2) Be extremely careful how you update the <code>locationManager.desiredAccuracy</code> and
<code>locationManager.distanceFilter</code> </p>
<p>Follow the example in Apple's code for this in the FlipsideViewController:</p>
<pre><code>[MyCLController sharedInstance].locationManager.desiredAccuracy = accuracyToSet;
[MyCLController sharedInstance].locationManager.distanceFilter = filterToSet;
</code></pre>
<p>This approach works, and causes no errors. If you update the desiredAccuracy or
distanceFilter in the main delegate loop:</p>
<pre><code>- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
</code></pre>
<p>Core Location will likely complain that it can't update the values, and give you errors.
Also, only use the constants for the <code>desiredAccuracy</code> supplied by Apple, and no others,
thus; </p>
<blockquote>
<p>kCLLocationAccuracyBest, kCLLocationAccuracyNearestTenMeters,<br>
kCLLocationAccuracyHundredMeters, kCLLocationAccuracyKilometer,<br>
kCLLocationAccuracyThreeKilometers</p>
</blockquote>
<p>Use of other values might give you errors from locationManager.
For <code>distanceFilter</code> you can use any value, but be aware people have stated it has issues,
the main value to default to is: -1 = Best, I've used 10.0 and it seems OK.</p>
<p>3) To force a new update, call the <code>startUpdates</code> method like in Tweetero, this forces
locationManager to do it's thing, and it should try and get you a new value.</p>
<p>4) The core location delegate routine is tricky to get accurate updates out of.
When your App first initializes you can be off in accuracy by 1000 meters or more, thus
one attempt is not going to do it. Three attempts after initialization usually gets you
to within 47 or so meters which is good. Remember that each successive attempt is going
to take longer and longer to improve your accuracy, thus it gets expensive quickly.
This is what you need to do:
Take a new value only if it is recent AND
If the new location has slightly better accuracy take the new location OR
If the new location has an accuracy < 50 meters take the new location OR
If the number of attempts has exceeded 3 or 5 AND the accuracy < 150 meters AND
the location has CHANGED, then this is a new location and the device moved so take this
value even if it's accuracy is worse.
Here's my Location code to do this:</p>
<pre><code>- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
locationDenied = NO;
if(![[NSUserDefaults standardUserDefaults] boolForKey:@"UseLocations"])
{
[self stopAllUpdates];
return;
}
NSDate* eventDate = newLocation.timestamp;
NSTimeInterval howRecent = abs([eventDate timeIntervalSinceNow]);
attempts++;
if((newLocation.coordinate.latitude != oldLocation.coordinate.latitude) && (newLocation.coordinate.longitude != oldLocation.coordinate.longitude))
locationChanged = YES;
else
locationChanged = NO;
#ifdef __i386__
//Do this for the simulator since location always returns Cupertino
if (howRecent < 5.0)
#else
// Here's the theory of operation
// If the value is recent AND
// If the new location has slightly better accuracy take the new location OR
// If the new location has an accuracy < 50 meters take the new location OR
// If the attempts is maxed (3 -5) AND the accuracy < 150 AND the location has changed, then this must be a new location and the device moved
// so take this new value even though it's accuracy might be worse
if ((howRecent < 5.0) && ( (newLocation.horizontalAccuracy < (oldLocation.horizontalAccuracy - 10.0)) || (newLocation.horizontalAccuracy < 50.0)
|| ((attempts >= attempt) && (newLocation.horizontalAccuracy <= 150.0) && locationChanged)))
#endif
{
attempts = 0;
latitude = newLocation.coordinate.latitude;
longitude = newLocation.coordinate.longitude;
[currentLocation release];
currentLocation = [newLocation retain];
goodLocation = YES;
[[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateLocationNotification" object: nil];
if (oldLocation != nil) {
distanceMoved = [newLocation getDistanceFrom:oldLocation];
currentSpeed = newLocation.speed;
distanceTimeDelta = [newLocation.timestamp timeIntervalSinceDate:oldLocation.timestamp];
}
}
// Send the update to our delegate
[self.delegate newLocationUpdate:currentLocation];
}
</code></pre>
<p>If you have a iPhone 3GS getting Heading updates is a lot easier, here's the code in the same module as above:</p>
<pre><code>//This is the Heading or Compass values
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
if (newHeading.headingAccuracy > 0)
{
[newHeading retain];
// headingType = YES for True North or NO for Magnetic North
if(headingType) {
currentHeading = newHeading.trueHeading;
} else {
currentHeading = newHeading.magneticHeading;
}
goodHeading = YES;
[[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateHeadingNotification" object: nil];
}
}
</code></pre>
<p>Hope this helps people!</p> |
39,839,051 | Using redux-form I'm losing focus after typing the first character | <p>I'm using <code>redux-form</code> and on blur validation. After I type the first character into an input element, it loses focus and I have to click in it again to continue typing. It only does this with the first character. Subsequent characters types remains focuses. Here's my basic sign in form example:</p>
<pre><code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import * as actions from '../actions/authActions';
require('../../styles/signin.scss');
class SignIn extends Component {
handleFormSubmit({ email, password }) {
this.props.signinUser({ email, password }, this.props.location);
}
renderAlert() {
if (this.props.errorMessage) {
return (
<div className="alert alert-danger">
{this.props.errorMessage}
</div>
);
} else if (this.props.location.query.error) {
return (
<div className="alert alert-danger">
Authorization required!
</div>
);
}
}
render() {
const { message, handleSubmit, prestine, reset, submitting } = this.props;
const renderField = ({ input, label, type, meta: { touched, invalid, error } }) => (
<div class={`form-group ${touched && invalid ? 'has-error' : ''}`}>
<label for={label} className="sr-only">{label}</label>
<input {...input} placeholder={label} type={type} className="form-control" />
<div class="text-danger">
{touched ? error: ''}
</div>
</div>
);
return (
<div className="row">
<div className="col-md-4 col-md-offset-4">
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))} className="form-signin">
<h2 className="form-signin-heading">
Please sign in
</h2>
{this.renderAlert()}
<Field name="email" type="text" component={renderField} label="Email Address" />
<Field name="password" type="password" component={renderField} label="Password" />
<button action="submit" className="btn btn-lg btn-primary btn-block">Sign In</button>
</form>
</div>
</div>
);
}
}
function validate(values) {
const errors = {};
if (!values.email) {
errors.email = 'Enter a username';
}
if (!values.password) {
errors.password = 'Enter a password'
}
return errors;
}
function mapStateToProps(state) {
return { errorMessage: state.auth.error }
}
SignIn = reduxForm({
form: 'signin',
validate: validate
})(SignIn);
export default connect(mapStateToProps, actions)(SignIn);
</code></pre> | 39,839,304 | 8 | 0 | null | 2016-10-03 19:31:02.357 UTC | 13 | 2021-04-16 09:00:47.757 UTC | null | null | null | null | 261,159 | null | 1 | 30 | validation|reactjs|redux|redux-form | 9,635 | <p>This happens because you're re-defining <code>renderField</code> as a new component every time you render which means it looks like a <em>new</em> component to React so it'll unmount the original one and re-mounts the new one.</p>
<p>You'll need to hoist it up:</p>
<pre class="lang-jsx prettyprint-override"><code>const renderField = ({ input, label, type, meta: { touched, invalid, error } }) => (
<div class={`form-group ${touched && invalid ? 'has-error' : ''}`}>
<label for={label} className="sr-only">{label}</label>
<input {...input} placeholder={label} type={type} className="form-control" />
<div class="text-danger">
{touched ? error: ''}
</div>
</div>
);
class SignIn extends Component {
...
render() {
const { message, handleSubmit, prestine, reset, submitting } = this.props;
return (
<div className="row">
<div className="col-md-4 col-md-offset-4">
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))} className="form-signin">
<h2 className="form-signin-heading">
Please sign in
</h2>
{this.renderAlert()}
<Field name="email" type="text" component={renderField} label="Email Address" />
<Field name="password" type="password" component={renderField} label="Password" />
<button action="submit" className="btn btn-lg btn-primary btn-block">Sign In</button>
</form>
</div>
</div>
);
}
}
...
</code></pre> |
42,805,652 | Setup AsyncHttpClient to use HTTPS | <p>I am using <code>com.loopj.android:android-async-http:1.4.9</code> for my request to server. It was working fine until I SSL/TLS is required in my server. So I need to modify my <code>AsyncHTTPClient</code> to use HTTPS in all URLs.</p>
<p>I checked this similar <a href="https://stackoverflow.com/questions/21833804/how-to-make-https-calls-using-asynchttpclient">how to make HTTPS calls using AsyncHttpClient?</a> but did not provide clear solution to the problem. The accepted solution was not secure as well because of this warning from the library itself: </p>
<blockquote>
<p>Warning! This omits SSL certificate validation on every device, use
with caution.</p>
</blockquote>
<p>So I went on and check other solutions. I ended up following the recommendation from: <a href="https://developer.android.com/training/articles/security-ssl.html" rel="nofollow noreferrer">https://developer.android.com/training/articles/security-ssl.html</a>. Thus, I have something similar to this:</p>
<pre><code>// Load CAs from an InputStream
// (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// From https://www.washington.edu/itconnect/security/ca/load-der.crt
InputStream caInput = new BufferedInputStream(new FileInputStream("load-der.crt"));
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
// Get SocketFactory from our SSLContext
//
// !!!PROBLEM IS HERE!!!
//
javax.net.ssl.SSLSocketFactory socketFactory = context.getSocketFactory();
</code></pre>
<p>As you can see in the last line, it gives an <code>SSLSocketFactory</code> from <code>javax.net.ssl</code> package. However the <code>AsyncHTTPClient</code> instance requires </p>
<p><code>asyncHTTPClient.setSSLSocketFactory(cz.msebera.android.httpclient.conn.ssl.SSLSocketFactory)</code></p>
<p><strong>EDIT:</strong></p>
<p>My server is using a self-signed certificate.</p> | 42,805,905 | 3 | 2 | null | 2017-03-15 09:25:58.987 UTC | 9 | 2017-03-26 10:57:35.05 UTC | 2017-05-23 12:17:29.513 UTC | null | -1 | null | 1,506,104 | null | 1 | 5 | android|ssl|tls1.2|asynchttpclient | 9,615 | <p>As you can see <a href="https://github.com/loopj/android-async-http/blob/master/library/src/main/java/com/loopj/android/http/AsyncHttpClient.java#L760" rel="nofollow noreferrer">here</a>, <code>setSSLFactory</code> requires an object of <code>SSLFactory</code>, so you can create your own <code>MySSLFactory</code> class. In the below example I have renamed it to <code>MyCustomSSLFactory</code>. The code for <strong>SSL Validaton</strong> is in the method <code>checkServerTrusted</code> of <code>X509TrustManager</code>. You can modify it as per your need if needed.</p>
<pre><code>import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import cz.msebera.android.httpclient.HttpVersion;
import cz.msebera.android.httpclient.conn.ClientConnectionManager;
import cz.msebera.android.httpclient.conn.scheme.PlainSocketFactory;
import cz.msebera.android.httpclient.conn.scheme.Scheme;
import cz.msebera.android.httpclient.conn.scheme.SchemeRegistry;
import cz.msebera.android.httpclient.conn.ssl.SSLSocketFactory;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.impl.conn.tsccm.ThreadSafeClientConnManager;
import cz.msebera.android.httpclient.params.BasicHttpParams;
import cz.msebera.android.httpclient.params.HttpParams;
import cz.msebera.android.httpclient.params.HttpProtocolParams;
import cz.msebera.android.httpclient.protocol.HTTP;
/**
* Created by prerak on 15/03/2017.
*/
public class MyCustomSSLFactory extends SSLSocketFactory {
final SSLContext sslContext = SSLContext.getInstance("TLS");
/**
* Creates a new SSL Socket Factory with the given KeyStore.
*
* @param truststore A KeyStore to create the SSL Socket Factory in context of
* @throws NoSuchAlgorithmException NoSuchAlgorithmException
* @throws KeyManagementException KeyManagementException
* @throws KeyStoreException KeyStoreException
* @throws UnrecoverableKeyException UnrecoverableKeyException
*/
public MyCustomSSLFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
chain[0].checkValidity();
} catch (Exception e) {
throw new CertificateException("Certificate not valid or trusted.");
}
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[]{tm}, null);
}
/**
* Gets a KeyStore containing the Certificate
*
* @param cert InputStream of the Certificate
* @return KeyStore
*/
public static KeyStore getKeystoreOfCA(InputStream cert) {
// Load CAs from an InputStream
InputStream caInput = null;
Certificate ca = null;
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
caInput = new BufferedInputStream(cert);
ca = cf.generateCertificate(caInput);
} catch (CertificateException e1) {
e1.printStackTrace();
} finally {
try {
if (caInput != null) {
caInput.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
} catch (Exception e) {
e.printStackTrace();
}
return keyStore;
}
/**
* Gets a Default KeyStore
*
* @return KeyStore
*/
public static KeyStore getKeystore() {
KeyStore trustStore = null;
try {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
} catch (Throwable t) {
t.printStackTrace();
}
return trustStore;
}
/**
* Returns a SSlSocketFactory which trusts all certificates
*
* @return SSLSocketFactory
*/
public static SSLSocketFactory getFixedSocketFactory() {
SSLSocketFactory socketFactory;
try {
socketFactory = new MyCustomSSLFactory(getKeystore());
socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
} catch (Throwable t) {
t.printStackTrace();
socketFactory = SSLSocketFactory.getSocketFactory();
}
return socketFactory;
}
/**
* Gets a DefaultHttpClient which trusts a set of certificates specified by the KeyStore
*
* @param keyStore custom provided KeyStore instance
* @return DefaultHttpClient
*/
public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) {
try {
SSLSocketFactory sf = new MyCustomSSLFactory(keyStore);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
/**
* Makes HttpsURLConnection trusts a set of certificates specified by the KeyStore
*/
public void fixHttpsURLConnection() {
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
}
}
</code></pre>
<p>Now you can initialise an object of <code>MyCustomSSLSocketFactory</code> by passing your custom <code>KeyStore</code> to it.</p>
<pre><code>MyCustomSSLFactory socketFactory = new MyCustomSSLFactory(keyStore);
</code></pre>
<p>And now you can set the socket factory as:</p>
<pre><code>asyncHTTPClient.setSSLSocketFactory(socketFactory);
</code></pre> |
35,940,528 | How to connect GraphQL and PostgreSQL | <p>GraphQL has mutations, Postgres has INSERT; GraphQL has queries, Postgres has SELECT's; etc., etc.. I haven't found an example showing how you could use both in a project, for example passing all the queries from front end (React, Relay) in GraphQL, but to a actually store the data in Postgres. </p>
<p>Does anyone know what Facebook is using as DB and how it's connected with GraphQL? </p>
<p>Is the only option of storing data in Postgres right now to build custom "adapters" that take the GraphQL query and convert it into SQL?</p> | 35,951,483 | 8 | 2 | null | 2016-03-11 12:40:20.427 UTC | 24 | 2021-08-30 17:31:44.797 UTC | 2017-05-10 12:18:51.11 UTC | null | 672,226 | null | 672,226 | null | 1 | 50 | postgresql|graphql | 37,232 | <p>GraphQL is database agnostic, so you can use whatever you normally use to interact with the database, and use the query or mutation's <code>resolve</code> method to call a function you've defined that will get/add something to the database.</p>
<h2>Without Relay</h2>
<p>Here is an example of a mutation using the promise-based <a href="http://knexjs.org/" rel="noreferrer">Knex SQL query builder</a>, first without Relay to get a feel for the concept. I'm going to assume that you have created a userType in your GraphQL schema that has three fields: <code>id</code>, <code>username</code>, and <code>created</code>: all required, and that you have a <code>getUser</code> function already defined which queries the database and returns a user object. In the database I also have a <code>password</code> column, but since I don't want that queried I leave it out of my <code>userType</code>.</p>
<pre><code>// db.js
// take a user object and use knex to add it to the database, then return the newly
// created user from the db.
const addUser = (user) => (
knex('users')
.returning('id') // returns [id]
.insert({
username: user.username,
password: yourPasswordHashFunction(user.password),
created: Math.floor(Date.now() / 1000), // Unix time in seconds
})
.then((id) => (getUser(id[0])))
.catch((error) => (
console.log(error)
))
);
// schema.js
// the resolve function receives the query inputs as args, then you can call
// your addUser function using them
const mutationType = new GraphQLObjectType({
name: 'Mutation',
description: 'Functions to add things to the database.',
fields: () => ({
addUser: {
type: userType,
args: {
username: {
type: new GraphQLNonNull(GraphQLString),
},
password: {
type: new GraphQLNonNull(GraphQLString),
},
},
resolve: (_, args) => (
addUser({
username: args.username,
password: args.password,
})
),
},
}),
});
</code></pre>
<p>Since Postgres creates the <code>id</code> for me and I calculate the <code>created</code> timestamp, I don't need them in my mutation query.</p>
<h2>The Relay Way</h2>
<p>Using the helpers in <code>graphql-relay</code> and sticking pretty close to the <a href="https://github.com/relayjs/relay-starter-kit" rel="noreferrer">Relay Starter Kit</a> helped me, because it was a lot to take in all at once. Relay requires you to set up your schema in a specific way so that it can work properly, but the idea is the same: use your functions to fetch from or add to the database in the resolve methods.</p>
<p>One important caveat is that the Relay way expects that the object returned from <code>getUser</code> is an instance of a class <code>User</code>, so you'll have to modify <code>getUser</code> to accommodate that.</p>
<p>The final example using Relay (<code>fromGlobalId</code>, <code>globalIdField</code>, <code>mutationWithClientMutationId</code>, and <code>nodeDefinitions</code> are all from <code>graphql-relay</code>):</p>
<pre><code>/**
* We get the node interface and field from the Relay library.
*
* The first method defines the way we resolve an ID to its object.
* The second defines the way we resolve an object to its GraphQL type.
*
* All your types will implement this nodeInterface
*/
const { nodeInterface, nodeField } = nodeDefinitions(
(globalId) => {
const { type, id } = fromGlobalId(globalId);
if (type === 'User') {
return getUser(id);
}
return null;
},
(obj) => {
if (obj instanceof User) {
return userType;
}
return null;
}
);
// a globalId is just a base64 encoding of the database id and the type
const userType = new GraphQLObjectType({
name: 'User',
description: 'A user.',
fields: () => ({
id: globalIdField('User'),
username: {
type: new GraphQLNonNull(GraphQLString),
description: 'The username the user has selected.',
},
created: {
type: GraphQLInt,
description: 'The Unix timestamp in seconds of when the user was created.',
},
}),
interfaces: [nodeInterface],
});
// The "payload" is the data that will be returned from the mutation
const userMutation = mutationWithClientMutationId({
name: 'AddUser',
inputFields: {
username: {
type: GraphQLString,
},
password: {
type: new GraphQLNonNull(GraphQLString),
},
},
outputFields: {
user: {
type: userType,
resolve: (payload) => getUser(payload.userId),
},
},
mutateAndGetPayload: ({ username, password }) =>
addUser(
{ username, password }
).then((user) => ({ userId: user.id })), // passed to resolve in outputFields
});
const mutationType = new GraphQLObjectType({
name: 'Mutation',
description: 'Functions to add things to the database.',
fields: () => ({
addUser: userMutation,
}),
});
const queryType = new GraphQLObjectType({
name: 'Query',
fields: () => ({
node: nodeField,
user: {
type: userType,
args: {
id: {
description: 'ID number of the user.',
type: new GraphQLNonNull(GraphQLID),
},
},
resolve: (root, args) => getUser(args.id),
},
}),
});
</code></pre> |
6,162,920 | Debugging jasmine-node tests with node-inspector | <p>Does anyone have any idea if this is possible? Most of the sample for node-inspector seemed geared toward debugging an invoked webpage. I'd like to be able to debug jasmine-node tests though.</p> | 7,656,706 | 3 | 0 | null | 2011-05-28 16:33:26.96 UTC | 12 | 2013-02-26 15:44:57.48 UTC | null | null | null | null | 258,972 | null | 1 | 31 | debugging|node.js|jasmine | 9,189 | <p>I ended up writing a little util called toggle:</p>
<pre><code>require('tty').setRawMode(true);
var stdin = process.openStdin();
exports.toggle = function(fireThis)
{
if (process.argv.indexOf("debug")!=-1)
{
console.log("debug flag found, press any key to start or rerun. Press 'ctrl-c' to cancel out!");
stdin.on('keypress', function (chunk, key) {
if (key.name == 'c' && key.ctrl == true)
{
process.exit();
}
fireThis();
});
}
else
{
console.log("Running, press any key to rerun or ctrl-c to exit.");
fireThis();
stdin.on('keypress', function (chunk, key) {
if (key.name == 'c' && key.ctrl == true)
{
process.exit();
}
fireThis();
});
}
}
</code></pre>
<p>You can drop it into your unit tests like:</p>
<pre><code>var toggle = require('./toggle');
toggle.toggle(function(){
var vows = require('vows'),
assert = require('assert');
vows.describe('Redis Mass Data Storage').addBatch({
....
</code></pre>
<p>And then run your tests like: node --debug myfile.js debug. If you run debug toggle will wait until you anything but ctrl-c. Ctrl-c exits. You can also rerun, which is nice.</p>
<p>w0000t.</p> |
5,899,227 | view multi-core or mlti-cpu utlization on linux | <p>I have a program running on Linux and I need to determine how it is utilizing all the CPUs/cores. Is there any program for viewing this information?</p> | 5,899,371 | 5 | 0 | null | 2011-05-05 14:19:27.663 UTC | 12 | 2015-06-11 14:22:31.453 UTC | 2015-06-11 14:22:31.453 UTC | null | 604,734 | null | 678,070 | null | 1 | 39 | linux|multicore | 69,251 | <p>When runnging the <code>top</code> command, press <code>f</code> then <code>j</code> to display the P column (last CPU used by process), in addition to the <code>1</code> command in top, you should view some multi core occupation informations :)</p> |
6,201,768 | PHP Zend date format | <p>I want to input a timestamp in below format to the database.</p>
<pre><code>yyyy-mm-dd hh:mm:ss
</code></pre>
<p><strong>How can I get in above format?</strong></p>
<p>When I use </p>
<pre><code>$date = new Zend_Date();
</code></pre>
<p>it returns <strong>month dd, yyyy hh:mm:ss PM</strong></p>
<p>I also use a JavaScript calender to insert a selected date and it returns in <strong>dd-mm-yyyy</strong> format</p>
<p>Now, I want to convert these both format into yyyy-mm-dd hh:mm:ss so can be inserted in database. <strong>Because date format not matching the database field format the date is not inserted and only filled with *<em>00-00-00 00:00:00</em>*</strong></p>
<p>Thanks for answer</p> | 6,201,949 | 6 | 4 | null | 2011-06-01 13:18:11.63 UTC | 2 | 2013-11-01 16:27:02.26 UTC | 2011-06-01 13:51:58.983 UTC | null | 208,809 | null | 685,713 | null | 1 | 14 | php|zend-framework|date|zend-date|formatdatetime | 44,826 | <p>Not sure if this will help you, but try using:</p>
<pre><code> // to show both date and time,
$date->get('YYYY-MM-dd HH:mm:ss');
// or, to show date only
$date->get('YYYY-MM-dd')
</code></pre> |
6,209,125 | ASP.NET MVC3: Debug and Release app settings not working | <p>My debug and release web.config app settings are not being read correctly.</p>
<p>Web.config:</p>
<pre><code><appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
</code></pre>
<p>Web.Debug.config</p>
<pre><code><appSettings>
<add key="ErrorEmailAddress" value="[email protected]" />
<add key="TestModeEmailAddress" value="[email protected]" />
</appSettings>
</code></pre>
<p>Web.Release.config</p>
<pre><code><appSettings>
<add key="ErrorEmailAddress" value="[email protected]" />
</appSettings>
</code></pre>
<p>However, calling:</p>
<pre><code>WebConfigurationManager.AppSettings["ErrorEmailAddress"]
</code></pre>
<p>is returning null (when debugging).</p>
<p>I have tried adding xdt:Transform="Insert" e.g.</p>
<pre><code><add key="ErrorEmailAddress" value="[email protected]" xdt:Transform="Insert" />
</code></pre>
<p>Any ideas?</p> | 6,221,653 | 6 | 0 | null | 2011-06-02 00:10:00.337 UTC | 7 | 2014-01-23 09:23:00.553 UTC | 2014-01-23 09:23:00.553 UTC | null | 686,490 | null | 239,849 | null | 1 | 29 | asp.net-mvc|web-config | 33,374 | <p>Ok I figured it out.</p>
<p>Answered here: <a href="https://stackoverflow.com/questions/3305096/how-can-i-use-web-debug-config-in-the-built-in-visual-studio-debugger-server">How can I use Web.debug.config in the built-in visual studio debugger server?</a></p>
<p>So the config files are only combined when you publish, not when you are running against a local server. Pretty stupid IMO, when else would you ever use Web.Debug.config?</p>
<p>I will do as is suggested here: <a href="https://stackoverflow.com/questions/3922291/use-visual-studio-web-config-transform-for-debugging">Use Visual Studio web.config transform for debugging</a></p>
<p>and just have Web.config as my default debugging config file, then have release for when releasing. Can't see a use for Web.Debug.config as this point.</p>
<p>Still, this is annoying because most of my settings I want to be set one way for all environments but when developing (eg customErrors On). This means I have to set them in Web.config for debugging, then in all my other environment configs change them.</p>
<p>Thanks everyone for responses.</p> |
5,849,402 | How can you execute a Node.js script via a cron job? | <p>Quite simply, I have node script that I want to execute once a month.</p>
<pre><code>30 6 1 * * node /home/steve/example/script.js
</code></pre>
<p>But this doesn't work, presumably because of path or the shell the command is being ran under. I've tried the following means of executing node via cron (tested with -v):</p>
<pre><code>steve@atom:~$ node -v
v0.4.2
steve@atom:~$ sh node -v
sh: Can't open node
steve@atom:~$ bash node -v
/usr/local/bin/node: /usr/local/bin/node: cannot execute binary file
steve@atom:~$ /usr/local/bin/node -v
v0.4.2
steve@atom:~$ sh /usr/local/bin/node -v
/usr/local/bin/node: 1: Syntax error: "(" unexpected
steve@atom:~$ bash /usr/local/bin/node -v
/usr/local/bin/node: /usr/local/bin/node: cannot execute binary file
</code></pre>
<p>I've ran out of ideas to try, any advice?</p> | 5,849,463 | 9 | 1 | null | 2011-05-01 15:40:37.893 UTC | 29 | 2022-03-13 14:06:31.19 UTC | 2011-05-02 14:33:41.777 UTC | null | 210,916 | null | 160,821 | null | 1 | 81 | node.js|cron|crontab | 93,238 | <p>just provide the full path to node <code>/usr/local/bin/node</code> in your cron job like:</p>
<pre><code>30 6 1 * * /usr/local/bin/node /home/steve/example/script.js
</code></pre> |
5,664,057 | Border Height on CSS | <p>I have a table TD and on the right of it I want to add a 1 pixel border, so I've done this:</p>
<pre><code>table td {
border-right:1px solid #000;
}
</code></pre>
<p>It works fine but the problem is that the border's height takes the total TD's height.</p>
<p>Is there a way to set the height of the border?</p> | 5,664,073 | 12 | 0 | null | 2011-04-14 13:32:49.807 UTC | 20 | 2019-05-19 10:30:48.18 UTC | 2012-06-13 13:34:30.75 UTC | null | 229,044 | null | 683,553 | null | 1 | 80 | html|css | 398,833 | <p>No, there isn't. The border will always be as tall as the element.</p>
<p>You can achieve the same effect by wrapping the contents of the cell in a <code><span></code>, and applying height/border styles to that. Or by drawing a short vertical line in an 1 pixel wide PNG which is the correct height, and applying it as a background to the cell:</p>
<pre><code>background:url(line.png) bottom right no-repeat;
</code></pre> |
5,874,317 | Thread-safe List<T> property | <p>I want an implementation of <code>List<T></code> as a property which can be used thread-safely without any doubt.</p>
<p>Something like this:</p>
<pre><code>private List<T> _list;
private List<T> MyT
{
get { // return a copy of _list; }
set { _list = value; }
}
</code></pre>
<p>It seems still I need to return a copy (cloned) of collection so if somewhere we are iterating the collection and at the same time the collection is set, then no exception is raised.</p>
<p>How to implement a thread-safe collection property?</p> | 5,874,347 | 15 | 6 | null | 2011-05-03 19:01:55.64 UTC | 32 | 2021-04-10 19:11:14.617 UTC | 2012-06-02 04:28:25.15 UTC | null | 58,074 | null | 313,421 | null | 1 | 166 | c#|collections|properties|thread-safety | 267,313 | <p>If you are targetting .Net 4 there are a few options in <a href="http://msdn.microsoft.com/en-us/library/system.collections.concurrent.aspx" rel="noreferrer">System.Collections.Concurrent</a> Namespace</p>
<p>You could use <code>ConcurrentBag<T></code> in this case instead of <code>List<T></code></p> |
5,998,245 | How do I get the current time in milliseconds in Python? | <p>How do I get the current time in milliseconds in Python?</p> | 5,998,359 | 16 | 4 | null | 2011-05-13 22:02:54.457 UTC | 92 | 2022-08-13 14:01:20.393 UTC | 2022-07-17 06:49:11.29 UTC | null | 365,102 | null | 128,967 | null | 1 | 731 | python|datetime|time | 1,129,052 | <p>Using <a href="https://docs.python.org/3/library/time.html#time.time" rel="noreferrer"><code>time.time()</code></a>:</p>
<pre><code>import time
def current_milli_time():
return round(time.time() * 1000)
</code></pre>
<p>Then:</p>
<pre><code>>>> current_milli_time()
1378761833768
</code></pre> |
5,070,013 | Select N+1 in next Entity Framework | <p>One of the few valid complaints I hear about EF4 vis-a-vis NHibernate is that EF4 is poor at handling lazily loaded collections. For example, on a lazily-loaded collection, if I say:</p>
<pre><code>if (MyAccount.Orders.Count() > 0) ;
</code></pre>
<p>EF will pull the whole collection down (if it's not already), while NH will be smart enough to issue a <code>select count(*)</code> </p>
<p>NH also has some nice batch fetching to help with the <code>select n + 1</code> problem. As I understand it, the closest EF4 can come to this is with the Include method.</p>
<p>Has the EF team let slip any indication that this will be fixed in their next iteration? I know they're hard at work on POCO, but this seems like it would be a popular fix.</p> | 5,070,644 | 1 | 2 | null | 2011-02-21 18:57:30.06 UTC | 13 | 2021-07-12 18:57:01.167 UTC | 2011-02-21 20:25:22.563 UTC | null | 352,552 | null | 352,552 | null | 1 | 12 | entity-framework | 14,348 | <p>What you describe is not N+1 problem. The example of N+1 problem is <a href="https://web.archive.org/web/20161112185536/http://blogs.microsoft.co.il/gilf/2010/08/18/select-n1-problem-how-to-decrease-your-orm-performance/" rel="nofollow noreferrer">here</a>. N+1 means that you execute N+1 selects instead of one (or two). In your example it would most probably mean:</p>
<pre><code>// Lazy loads all N Orders in single select
foreach(var order in MyAccount.Orders)
{
// Lazy loads all Items for single order => executed N times
foreach(var orderItem in order.Items)
{
...
}
}
</code></pre>
<p>This is easily solved by:</p>
<pre><code>// Eager load all Orders and their items in single query
foreach(var order in context.Accounts.Include("Orders.Items").Where(...))
{
...
}
</code></pre>
<p>Your example looks valid to me. You have collection which exposes <code>IEnumerable</code> and you execute <code>Count</code> operation on it. Collection is lazy loaded and count is executed in memory. The ability for translation Linq query to SQL is available only on <code>IQueryable</code> with expression trees representing the query. But <code>IQueryable</code> represents query = each access means new execution in DB so for example checking Count in loop will execute a DB query in each iteration.</p>
<p>So it is more about implementation of dynamic proxy.</p>
<hr />
<p>Counting related entities without loading them will is already possible in Code-first CTP5 (final release will be called EF 4.1) when using <code>DbContext</code> instead of <code>ObjectContext</code> but not by direct interaction with collection. You will have to use something like:</p>
<pre><code>int count = context.Entry(myAccount).Collection(a => a.Orders).Query().Count();
</code></pre>
<p><code>Query</code> method returns prepared <code>IQueryable</code> which is probably what EF runs if you use lazy loading but you can further modify query - here I used <code>Count</code>.</p> |
25,037,263 | Apache Kafka error on windows - Couldnot find or load main class QuorumPeerMain | <p>I just downloaded Kafka 2.8.0 from Apache website, and I am trying to setup using the instructions given on the website. But when I try to start zookeper server, I am getting below error:</p>
<blockquote>
<p>Error: Could not find or load main class org.apache.zookeeper.server.quorum.QuorumPeerMain</p>
</blockquote>
<p>My environment is Windows 7 64 bit. I tried to follow below e-mail chain: <a href="http://mail-archives.apache.org/mod_mbox/kafka-users/201405.mbox/%3CCALUpvHXCtTKQFe59h_SN-6jZRScqWrgv0TWsjZ-HjV7AO19GOA@mail.gmail.com%3E" rel="noreferrer">Apache Email Chain</a> . But still it's having same issue. Can anyone guide me in this? As I am very new to this and couldn't find many information on Google/Apache Kafka email chain.</p> | 29,956,869 | 16 | 1 | null | 2014-07-30 12:47:43.367 UTC | 9 | 2022-02-09 21:54:24.16 UTC | 2016-11-08 21:21:36.983 UTC | user6022341 | null | null | 1,506,071 | null | 1 | 22 | apache-kafka|apache-zookeeper | 58,093 | <p>Run these commands from your Kafka root folder:</p>
<p><code>cd bin\windows</code></p>
<p>Then run Zookeper server:</p>
<p><code>zookeeper-server-start.bat ..\..\config\zookeeper.properties</code></p>
<p>Then run Kafka server:</p>
<p><code>kafka-server-start.bat ..\..\config\server.properties</code></p>
<hr />
<p>The gotcha here is to run the <strong>.bat</strong> files from the <strong>/bin/windows</strong> folder, so after you run your servers with the steps above and want to follow up with the tutorial, make sure you are running the correct batch files to create topics and whatnot, e.g.:</p>
<p><strong>Create a topic:</strong></p>
<p><code>kafka-topics.bat --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test</code></p>
<p><strong>List topics:</strong></p>
<p><code>kafka-topics.bat --list --zookeeper localhost:2181</code></p> |
65,456,958 | Dart null safety doesn't work with class fields | <p>I have migrated my Dart code to NNBD / Null Safety. Some of it looks like this:</p>
<pre class="lang-dart prettyprint-override"><code>class Foo {
String? _a;
void foo() {
if (_a != null) {
_a += 'a';
}
}
}
class Bar {
Bar() {
_a = 'a';
}
String _a;
}
</code></pre>
<p>This causes two analysis errors. For <code>_a += 'a';</code>:</p>
<blockquote>
<p>An expression whose value can be 'null' <strong>must be null-checked</strong> before it can be dereferenced.
Try checking that the value isn't 'null' before dereferencing it.</p>
</blockquote>
<p>For <code>Bar() {</code>:</p>
<blockquote>
<p>Non-nullable instance field '_a' must be initialized.
Try adding an initializer expression, <strong>or add a field initializer in this constructor</strong>, or mark it 'late'.</p>
</blockquote>
<p>In both cases I have already done exactly what the error suggests! What's up with that?</p>
<p>I'm using Dart 2.12.0-133.2.beta (Tue Dec 15).</p>
<p>Edit: I found <a href="https://dart.dev/null-safety" rel="noreferrer">this page</a> which says:</p>
<blockquote>
<p>The analyzer can’t model the flow of your whole application, so it can’t predict the values of global variables or class fields.</p>
</blockquote>
<p>But that doesn't make sense to me - there's only one possible flow control path from <code>if (_a != null)</code> to <code>_a += 'a';</code> in this case - there's no async code and Dart is single-threaded - so it doesn't matter that <code>_a</code> isn't local.</p>
<p>And the error message for <code>Bar()</code> explicitly states the possibility of initialising the field in the constructor.</p> | 65,457,221 | 4 | 0 | null | 2020-12-26 13:39:03.837 UTC | 9 | 2021-06-30 12:24:37.92 UTC | 2020-12-26 13:44:13.527 UTC | null | 265,521 | null | 265,521 | null | 1 | 15 | dart|dart-null-safety | 34,477 | <p>The problem is that class fields can be overridden even if it is marked as <code>final</code>. The following example illustrates the problem:</p>
<pre><code>class A {
final String? text = 'hello';
String? getText() {
if (text != null) {
return text;
} else {
return 'WAS NULL!';
}
}
}
class B extends A {
bool first = true;
@override
String? get text {
if (first) {
first = false;
return 'world';
} else {
return null;
}
}
}
void main() {
print(A().getText()); // hello
print(B().getText()); // null
}
</code></pre>
<p>The <code>B</code> class overrides the <code>text</code> final field so it returns a value the first time it is asked but returns <code>null</code> after this. You cannot write your <code>A</code> class in such a way that you can prevent this form of overrides from being allowed.</p>
<p>So we cannot change the return value of <code>getText</code> from <code>String?</code> to <code>String</code> even if it looks like we checks the <code>text</code> field for <code>null</code> before returning it.</p> |
32,837,507 | Spring Boot Elasticsearch Configuration | <p>I've got a working Spring Boot Elasticsearch Application which uses one of two profiles: application.dev.properties or application.prod.properties. That part works fine. I am having issue with getting the external elasticsearch to read from the application.xxx.properties.</p>
<p>This works:</p>
<pre><code>@Configuration
@PropertySource(value = "classpath:config/elasticsearch.properties")
public class ElasticsearchConfiguration {
@Resource
private Environment environment;
@Bean
public Client client() {
TransportClient client = new TransportClient();
TransportAddress address = new InetSocketTransportAddress(
environment.getProperty("elasticsearch.host"),
Integer.parseInt(environment.getProperty("elasticsearch.port"))
);
client.addTransportAddress(address);
return client;
}
@Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchTemplate(client());
}
}
</code></pre>
<p>but obviously doesn't solve my multi-environment issue.</p>
<p>I've also tried @Value annotations for host and port variables without success.</p>
<p>How can I convert the above to read its values from the application properties file or choose a different @PropertySource file based on whichever profile I want to run?</p>
<pre><code>spring.data.elasticsearch.properties.host = 10.10.1.10
spring.data.elasticsearch.properties.port = 9300
</code></pre>
<p>Thanks</p> | 32,838,087 | 2 | 1 | null | 2015-09-29 06:53:57.64 UTC | 5 | 2018-10-08 16:16:01.093 UTC | 2018-10-08 16:16:01.093 UTC | null | 6,727,427 | null | 2,334,386 | null | 1 | 15 | java|spring-boot|elasticsearch | 41,703 | <p>Remove your configuration class and properties. </p>
<p>Add the following dependency</p>
<pre><code><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
</code></pre>
<p>Just add the <code>spring.data.elasticsearch</code> properties to an <code>application-prod.properties</code> and <code>application-dev.properties</code> and change for the desired environment. This is described in the <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-nosql.html#boot-features-elasticsearch" rel="noreferrer">ElasticSearch section</a> of the Spring Boot guide. </p>
<pre><code>spring.data.elasticsearch.cluster-nodes=10.10.1.10:9300
</code></pre>
<p>The value in either file will of course differ (or put the default in the <code>application.properties</code> and simply override with an <code>application-dev.properties</code>. </p>
<p>Spring Boot will based on the <code>spring.profiles.active</code> <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html" rel="noreferrer">load the desired properties</a> file.</p>
<p>There is no need to hack around yourself.</p> |
9,466,916 | TCPDF: How can I place an image into an HTML block? | <p>I've been working with TCPDF for a few months now; off and on. It's worked fairly well for most of my HTML templates, but I've always had problems placing images into the PDF's. The images are usually placed into the body, not the header. My placement is either a fixed position from the top-left corner or it is relative to the bottom of the document. In either case, I've had issues. When the text changes in the HTML, I have to reposition the image. Multiple column tables can make things even more difficult. Note: "class pdf extends TCPDF".</p>
<pre><code>$this->pdf->AddPage();
$this->pdf->writeHTML($pdf_html);
$cur_page = $this->pdf->getPage();
$x_pos = $this->pdf->GetX();
$y_pos = $this->pdf->GetY();
// Place image relative to end of HTML
$this->pdf->SetXY($x_pos, $y_pos - 54);
$this->pdf->Image('myimage.png');
</code></pre>
<p>Does anyone know a fool-proof way of placing an Image into a PDF that is generated from HTML. I thought about splitting the HTML into two parts, but I'm not sure if it would work well either.</p> | 9,780,352 | 3 | 0 | null | 2012-02-27 14:44:03.173 UTC | 3 | 2019-12-23 15:31:45.063 UTC | 2012-07-01 11:00:42.793 UTC | null | 367,456 | null | 816,260 | null | 1 | 16 | php|pdf-generation|tcpdf | 52,569 | <p>I am using html img tag and its working well. </p>
<pre><code>$toolcopy = ' my content <br>';
$toolcopy .= '<img src="/images/logo.jpg" width="50" height="50">';
$toolcopy .= '<br> other content';
$pdf->writeHTML($toolcopy, true, 0, true, 0);
</code></pre> |
9,115,675 | Nested "from" LINQ query expressed with extension methods | <p>How can I write this LINQ query by using the extension method syntax?</p>
<pre><code>var query = from a in sequenceA
from b in sequenceB
select ...;
</code></pre> | 9,117,009 | 3 | 0 | null | 2012-02-02 16:09:10.54 UTC | 11 | 2015-03-05 20:34:39.43 UTC | null | null | null | null | 880,990 | null | 1 | 28 | c#|linq | 7,295 | <p>For your future reference, all questions of this form are answered by section 7.16 of the C# specification.</p>
<p>Your specific question is answered by this paragraph:</p>
<hr>
<p>A query expression with a second <code>from</code> clause followed by a <code>select</code> clause</p>
<pre><code>from x1 in e1
from x2 in e2
select v
</code></pre>
<p>is translated into</p>
<pre><code>( e1 ) . SelectMany( x1 => e2 , ( x1 , x2 ) => v )
</code></pre>
<hr>
<p>So your query:</p>
<pre><code>var query = from a in sequenceA
from b in sequenceB
select ...;
</code></pre>
<p>Is the same as</p>
<pre><code>var query = ( sequenceA ) . SelectMany( a => sequenceB , ( a , b ) => ... )
</code></pre>
<p>(Note that of course this assumes that the "..." is an expression, and not, say, an expression followed by a query continuation.)</p>
<p>hdv's answer points out that</p>
<pre><code>var query = ( sequenceA ) . SelectMany(
a => ( sequenceB ) . Select( b => ... ) );
</code></pre>
<p>would also be a <em>logically</em> valid translation, though it is not the translation we actually perform. In the early days of LINQ implementation, this was the translation we chose. However, as you pile on more <code>from</code> clauses, it makes the lambdas nest more and more deeply, which then presents the compiler with an <em>enormous</em> problem in type inference. This choice of translation wrecks compiler performance, so we introduced the <em>transparent identifier</em> mechanism to give us a much cheaper way to represent the seamntics of deeply nested scopes. </p>
<p>If these subjects interest you:</p>
<p>For more thoughts on why deeply nested lambdas present a hard problem for the compiler to solve, see:</p>
<p><a href="http://blogs.msdn.com/b/ericlippert/archive/2007/03/26/lambda-expressions-vs-anonymous-methods-part-four.aspx" rel="noreferrer">http://blogs.msdn.com/b/ericlippert/archive/2007/03/26/lambda-expressions-vs-anonymous-methods-part-four.aspx</a></p>
<p><a href="http://blogs.msdn.com/b/ericlippert/archive/2007/03/28/lambda-expressions-vs-anonymous-methods-part-five.aspx" rel="noreferrer">http://blogs.msdn.com/b/ericlippert/archive/2007/03/28/lambda-expressions-vs-anonymous-methods-part-five.aspx</a></p>
<p>For more information about transparent identifiers, see this post from Wes Dyer, who implemented them in C# 3.0:</p>
<p><a href="http://blogs.msdn.com/b/wesdyer/archive/2006/12/22/transparent-identifiers.aspx" rel="noreferrer">http://blogs.msdn.com/b/wesdyer/archive/2006/12/22/transparent-identifiers.aspx</a></p>
<p>And my series of articles about them:</p>
<p><a href="http://ericlippert.com/2014/07/31/transparent-identifiers-part-one/" rel="noreferrer">http://ericlippert.com/2014/07/31/transparent-identifiers-part-one/</a></p> |
52,009,124 | Not able to completely remove Kubernetes CustomResource | <p>I'm having trouble deleting custom resource definition.
I'm trying to upgrade kubeless from v1.0.0-alpha.7 to <strong>v1.0.0-alpha.8</strong>.</p>
<p>I tried to remove all the created custom resources by doing </p>
<pre class="lang-sh prettyprint-override"><code>$ kubectl delete -f kubeless-v1.0.0-alpha.7.yaml
deployment "kubeless-controller-manager" deleted
serviceaccount "controller-acct" deleted
clusterrole "kubeless-controller-deployer" deleted
clusterrolebinding "kubeless-controller-deployer" deleted
customresourcedefinition "functions.kubeless.io" deleted
customresourcedefinition "httptriggers.kubeless.io" deleted
customresourcedefinition "cronjobtriggers.kubeless.io" deleted
configmap "kubeless-config" deleted
</code></pre>
<p>But when I try,</p>
<pre class="lang-sh prettyprint-override"><code>$ kubectl get customresourcedefinition
NAME AGE
functions.kubeless.io 21d
</code></pre>
<p>And because of this when I next try to upgrade by doing, I see,</p>
<pre class="lang-sh prettyprint-override"><code>$ kubectl create -f kubeless-v1.0.0-alpha.8.yaml
Error from server (AlreadyExists): error when creating "kubeless-v1.0.0-alpha.8.yaml": object is being deleted: customresourcedefinitions.apiextensions.k8s.io "functions.kubeless.io" already exists
</code></pre>
<p>I think because of this mismatch in the function definition , the hello world example is failing.</p>
<pre class="lang-sh prettyprint-override"><code>$ kubeless function deploy hellopy --runtime python2.7 --from-file test.py --handler test.hello
INFO[0000] Deploying function...
FATA[0000] Failed to deploy hellopy. Received:
the server does not allow this method on the requested resource (post functions.kubeless.io)
</code></pre>
<p>Finally, here is the output of,</p>
<pre class="lang-sh prettyprint-override"><code>$ kubectl describe customresourcedefinitions.apiextensions.k8s.io
Name: functions.kubeless.io
Namespace:
Labels: <none>
Annotations: kubectl.kubernetes.io/last-applied-configuration={"apiVersion":"apiextensions.k8s.io/v1beta1","description":"Kubernetes Native Serverless Framework","kind":"CustomResourceDefinition","metadata":{"anno...
API Version: apiextensions.k8s.io/v1beta1
Kind: CustomResourceDefinition
Metadata:
Creation Timestamp: 2018-08-02T17:22:07Z
Deletion Grace Period Seconds: 0
Deletion Timestamp: 2018-08-24T17:15:39Z
Finalizers:
customresourcecleanup.apiextensions.k8s.io
Generation: 1
Resource Version: 99792247
Self Link: /apis/apiextensions.k8s.io/v1beta1/customresourcedefinitions/functions.kubeless.io
UID: 951713a6-9678-11e8-bd68-0a34b6111990
Spec:
Group: kubeless.io
Names:
Kind: Function
List Kind: FunctionList
Plural: functions
Singular: function
Scope: Namespaced
Version: v1beta1
Status:
Accepted Names:
Kind: Function
List Kind: FunctionList
Plural: functions
Singular: function
Conditions:
Last Transition Time: 2018-08-02T17:22:07Z
Message: no conflicts found
Reason: NoConflicts
Status: True
Type: NamesAccepted
Last Transition Time: 2018-08-02T17:22:07Z
Message: the initial names have been accepted
Reason: InitialNamesAccepted
Status: True
Type: Established
Last Transition Time: 2018-08-23T13:29:45Z
Message: CustomResource deletion is in progress
Reason: InstanceDeletionInProgress
Status: True
Type: Terminating
Events: <none>
</code></pre> | 52,012,367 | 5 | 2 | null | 2018-08-24 17:18:09.353 UTC | 10 | 2022-09-19 08:31:24.173 UTC | 2020-04-24 05:16:52.12 UTC | null | 7,016,115 | null | 578,116 | null | 1 | 62 | kubernetes|kubeless | 56,087 | <p>So it turns out , the root cause was that Custom resources with finalizers can "deadlock".
The CustomResource "functions.kubeless.io" had a </p>
<p><code>Finalizers:
customresourcecleanup.apiextensions.k8s.io</code> </p>
<p>and this is can leave it in a bad state when deleting. </p>
<p><a href="https://github.com/kubernetes/kubernetes/issues/60538" rel="noreferrer">https://github.com/kubernetes/kubernetes/issues/60538</a></p>
<p>I followed the steps mentioned in <a href="https://github.com/kubernetes/kubernetes/issues/60538#issuecomment-369099998" rel="noreferrer">this workaround</a> and it now gets deleted. Hope this helps anyone else who runs into this. </p> |
52,060,516 | How to change Android minSdkVersion in flutter project | <p>I was trying to start a flutter project for an App using bluetooth to communicate. For that, I was using <a href="https://github.com/pauldemarco/flutter_blue" rel="noreferrer">flutter blue</a>.</p>
<p>Unfortunately, when trying to run (on an Android device) the first example I created I was met with the following error:</p>
<pre><code>FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed : uses-sdk:minSdkVersion 16 cannot be smaller than version 19 declared in library [:flutter_blue] /home/maldus/Projects/flutter/polmac/build/flutter_blue/intermediates/manifests/full/debug/AndroidManifest.xml as the library might be using APIs not available in 16
Suggestion: use a compatible library with a minSdk of at most 16,
or increase this project's minSdk version to at least 19,
or use tools:overrideLibrary="com.pauldemarco.flutterblue" to force usage (may lead to runtime failures)
</code></pre>
<p>If I were on Android Studio, I'd know how to bump up the Android minSdkVersion, but on a flutter project (using VSCode) I was a little lost.</p>
<p>Is it possible to increase the minSdkVersion with flutter, and how?</p> | 52,060,517 | 25 | 2 | null | 2018-08-28 14:39:47.427 UTC | 51 | 2022-09-21 20:06:17.467 UTC | null | null | null | null | 4,862,613 | null | 1 | 277 | android|flutter|android-sdk-tools | 235,382 | <p>It is indeed possible to increase minSdkVersion, but it took me way too much time to find it out because google searches mostly yields as result discussions about the absolute minimum Sdk version flutter should be able to support, not how to increase it in your own project.</p>
<p>Like in an Android Studio project, you have to edit the <code>build.gradle</code> file. In a flutter project, it is found at the path <code>./android/app/build.gradle</code>.</p>
<p>The parameter that needs to be changed is, of course, <code>minSdkVersion 16</code>, bumping it up to what you need (in this case 19).</p>
<pre><code>defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.projectname"
minSdkVersion 19 //*** This is the part that needs to be changed, previously was 16
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
</code></pre>
<p>Seems obvious now, but took me long enough to figure it out on my own.</p> |
31,056,215 | How to access default jackson serialization in a custom serializer | <p>I want to create a custom serializer which does a tiny bit of work and then leaves the rest for default serialization. </p>
<p>For example:</p>
<pre><code>@JsonSerialize(using = MyClassSerializer.class)
public class MyClass {
...
}
public class MyClassSerializer extends JsonSerializer<MyClass> {
@Override
public void serialize(MyClass myClass, JsonGenerator generator,
SerializerProvider provider)
throws JsonGenerationException, IOException {
if (myClass.getSomeProperty() == someCalculationResult) {
provider.setAttribute("special", true);
}
generator.writeObject(myClass);
}
}
</code></pre>
<p>With the idea of creating other custom serializers for aggregated objects which behave differently based on the 'special' attribute value. However, the above code does not work, as it unsurprisingly goes into an infinite recursion.</p>
<p>Is there a way to tell jackson to use default serialization once I have set the attribute? I don't really want enumerate all the properties like many custom serializers as the class is fairly complex and I don't want to have to do dual maintenance with the serializer every time I change the class.</p> | 31,057,934 | 4 | 2 | null | 2015-06-25 16:49:21.147 UTC | 8 | 2021-12-13 10:10:11.673 UTC | 2019-12-03 17:22:40.183 UTC | null | 710,530 | null | 710,530 | null | 1 | 32 | java|json|jackson | 24,321 | <p>A <strong><code>BeanSerializerModifier</code></strong> will provide you access to the default serialization.</p>
<h2>Inject a default serializer into the custom serializer</h2>
<pre><code>public class MyClassSerializer extends JsonSerializer<MyClass> {
private final JsonSerializer<Object> defaultSerializer;
public MyClassSerializer(JsonSerializer<Object> defaultSerializer) {
this.defaultSerializer = checkNotNull(defaultSerializer);
}
@Override
public void serialize(MyClass myclass, JsonGenerator gen, SerializerProvider provider) throws IOException {
if (myclass.getSomeProperty() == true) {
provider.setAttribute("special", true);
}
defaultSerializer.serialize(myclass, gen, provider);
}
}
</code></pre>
<h2>Create a <code>BeanSerializerModifier</code> for <code>MyClass</code></h2>
<pre><code>public class MyClassSerializerModifier extends BeanSerializerModifier {
@Override
public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
if (beanDesc.getBeanClass() == MySpecificClass.class) {
return new MyClassSerializer((JsonSerializer<Object>) serializer);
}
return serializer;
}
}
</code></pre>
<h2>Register the serializer modifier</h2>
<pre><code>ObjectMapper om = new ObjectMapper()
.registerModule(new SimpleModule()
.setSerializerModifier(new MyClassSerializerModifier()));
</code></pre> |
22,571,259 | Split a string into N equal parts? | <p>I have a string I would like to split into N equal parts. </p>
<p>For example, imagine I had a string with length 128 and I want to split it in to 4 chunks of length 32 each; i.e., first 32 chars, then the second 32 and so on.</p>
<p>How can I do this?</p> | 22,571,385 | 6 | 1 | null | 2014-03-21 23:25:00.623 UTC | 9 | 2021-06-13 16:29:05.767 UTC | 2015-09-11 22:13:21.51 UTC | null | 2,359,271 | null | 218,183 | null | 1 | 68 | python | 97,656 | <pre><code>import textwrap
print(textwrap.wrap("123456789", 2))
#prints ['12', '34', '56', '78', '9']
</code></pre>
<p>Note: be careful with whitespace etc - this may or may not be what you want.</p>
<pre><code>"""Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in 'text' so it fits in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(), and
all other whitespace characters (including newline) are converted to
space. See TextWrapper class for available keyword args to customize
wrapping behaviour.
"""
</code></pre> |
22,836,874 | How to stub time.sleep() in Python unit testing | <p>I want to make a stub to prevent time.sleep(..) to sleep to improve the unit test execution time.</p>
<p>What I have is:</p>
<pre><code>import time as orgtime
class time(orgtime):
'''Stub for time.'''
_sleep_speed_factor = 1.0
@staticmethod
def _set_sleep_speed_factor(sleep_speed_factor):
'''Sets sleep speed.'''
time._sleep_speed_factor = sleep_speed_factor
@staticmethod
def sleep(duration):
'''Sleeps or not.'''
print duration * time._sleep_speed_factor
super.sleep(duration * time._sleep_speed_factor)
</code></pre>
<p>However, I get the following error on the second code line above (class definition):</p>
<pre><code>TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given).
</code></pre>
<p>How to fix the error?</p> | 22,839,439 | 6 | 1 | null | 2014-04-03 11:53:59.043 UTC | 7 | 2022-06-02 21:56:01.627 UTC | 2014-04-03 16:46:04.877 UTC | null | 168,868 | null | 1,187,220 | null | 1 | 29 | python|class|time|constructor|python-unittest | 30,140 | <p>You can use <a href="https://pypi.python.org/pypi/mock/">mock</a> library in your tests.</p>
<pre><code>import time
from mock import patch
class MyTestCase(...):
@patch('time.sleep', return_value=None)
def my_test(self, patched_time_sleep):
time.sleep(666) # Should be instant
</code></pre> |
7,403,536 | List of available attributes for http://axschema.org and http://schemas.openid.net | <p>I have searched high, low, far and wide but can not find anything on the Internet that lists the available attributes for these schemas. Does anyone know where the documentation is for these? so far I know of:</p>
<p><a href="http://axschema.org/namePerson/first">http://axschema.org/namePerson/first</a></p>
<p><a href="http://axschema.org/namePerson/last">http://axschema.org/namePerson/last</a></p>
<p><a href="http://axschema.org/contact/email">http://axschema.org/contact/email</a></p>
<p><a href="http://schemas.openid.net/ax/api/user_id">http://schemas.openid.net/ax/api/user_id</a></p> | 7,657,061 | 2 | 1 | null | 2011-09-13 14:28:36.613 UTC | 14 | 2012-09-18 21:48:04.103 UTC | null | null | null | null | 749,658 | null | 1 | 19 | openid|schema|google-openid|openid-provider | 9,887 | <p>Well I cannot see axschema.org online anymore. But based on <a href="http://groups.google.com/group/axschema/browse_thread/thread/49312a23a7d5ecce#" rel="noreferrer">http://groups.google.com/group/axschema/browse_thread/thread/49312a23a7d5ecce#</a> I think [<a href="http://openid.net/schema]" rel="noreferrer">http://openid.net/schema]</a> superseeds [<a href="http://axschema.org]" rel="noreferrer">http://axschema.org]</a>. </p>
<p>Here is the list, also on <a href="http://openid.net/specs/openid-attribute-properties-list-1_0-01.html" rel="noreferrer">http://openid.net/specs/openid-attribute-properties-list-1_0-01.html</a>.</p>
<pre><code>http://openid.net/schema/namePerson/prefix
http://openid.net/schema/namePerson/first
http://openid.net/schema/namePerson/last
http://openid.net/schema/namePerson/middle
http://openid.net/schema/namePerson/suffix
http://openid.net/schema/namePerson/friendly
http://openid.net/schema/person/guid
http://openid.net/schema/birthDate/birthYear
http://openid.net/schema/birthDate/birthMonth
http://openid.net/schema/birthDate/birthday
http://openid.net/schema/gender
http://openid.net/schema/language/pref
http://openid.net/schema/contact/phone/default
http://openid.net/schema/contact/phone/home
http://openid.net/schema/contact/phone/business
http://openid.net/schema/contact/phone/cell
http://openid.net/schema/contact/phone/fax
http://openid.net/schema/contact/postaladdress/home
http://openid.net/schema/contact/postaladdressadditional/home
http://openid.net/schema/contact/city/home
http://openid.net/schema/contact/state/home
http://openid.net/schema/contact/country/home
http://openid.net/schema/contact/postalcode/home
http://openid.net/schema/contact/postaladdress/business
http://openid.net/schema/contact/postaladdressadditional/business
http://openid.net/schema/contact/city/business
http://openid.net/schema/contact/state/business
http://openid.net/schema/contact/country/business
http://openid.net/schema/contact/postalcode/business
http://openid.net/schema/contact/IM/default
http://openid.net/schema/contact/IM/AIM
http://openid.net/schema/contact/IM/ICQ
http://openid.net/schema/contact/IM/MSN
http://openid.net/schema/contact/IM/Yahoo
http://openid.net/schema/contact/IM/Jabber
http://openid.net/schema/contact/IM/Skype
http://openid.net/schema/contact/internet/email
http://openid.net/schema/contact/web/default
http://openid.net/schema/contact/web/blog
http://openid.net/schema/contact/web/Linkedin
http://openid.net/schema/contact/web/Amazon
http://openid.net/schema/contact/web/Flickr
http://openid.net/schema/contact/web/Delicious
http://openid.net/schema/company/name
http://openid.net/schema/company/title
http://openid.net/schema/media/spokenname
http://openid.net/schema/media/greeting/audio
http://openid.net/schema/media/greeting/video
http://openid.net/schema/media/biography
http://openid.net/schema/media/image
http://openid.net/schema/media/image/16x16
http://openid.net/schema/media/image/32x32
http://openid.net/schema/media/image/48x48
http://openid.net/schema/media/image/64x64
http://openid.net/schema/media/image/80x80
http://openid.net/schema/media/image/128x128
http://openid.net/schema/media/image/160x120
http://openid.net/schema/media/image/320x240
http://openid.net/schema/media/image/640x480
http://openid.net/schema/media/image/120x160
http://openid.net/schema/media/image/240x320
http://openid.net/schema/media/image/480x640
http://openid.net/schema/media/image/favicon
http://openid.net/schema/timezone
</code></pre> |
7,451,635 | How to detect supported video formats for the HTML5 video tag? | <p>I am making an application in HTML5 using the video tag, in the application the user chooses a video file and I play that file. This all happens locally because I only link to that file in the user's machine. </p>
<p>I want to allow only formats the browser can play to be played in my application, and to show an error for unsupported formats. The problem is that different browsers can play different formats. </p>
<p>I know I can check for the browser and match it with the formats I know it can play, but what if the browser updates to support another format? I'll have to update my application with the new information and meanwhile users won't be able to play supported formats. Is there a way to check just for the supported video formats?</p> | 7,451,727 | 2 | 0 | null | 2011-09-17 00:29:45.843 UTC | 16 | 2015-09-07 02:30:47.653 UTC | 2011-09-17 00:36:19.1 UTC | null | 458,152 | null | 458,152 | null | 1 | 25 | javascript|html|cross-browser|html5-video | 42,450 | <p>You can check codecs for different video types with <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType" rel="noreferrer"><code>HTMLVideoElement.prototype.canPlayType</code></a>. There is also a great HTML5 feature detection library, <a href="http://www.modernizr.com/" rel="noreferrer">Modernizr</a>.</p>
<pre><code>var testEl = document.createElement( "video" ),
mpeg4, h264, ogg, webm;
if ( testEl.canPlayType ) {
// Check for MPEG-4 support
mpeg4 = "" !== testEl.canPlayType( 'video/mp4; codecs="mp4v.20.8"' );
// Check for h264 support
h264 = "" !== ( testEl.canPlayType( 'video/mp4; codecs="avc1.42E01E"' )
|| testEl.canPlayType( 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"' ) );
// Check for Ogg support
ogg = "" !== testEl.canPlayType( 'video/ogg; codecs="theora"' );
// Check for Webm support
webm = "" !== testEl.canPlayType( 'video/webm; codecs="vp8, vorbis"' );
}
</code></pre> |
35,404,932 | std::vector::emplace_back and std::move | <p>Is there any advantage of using <code>std::vector::emplace_back</code> and <code>std::move</code> together? or it is just redundant since <code>std::vector::emplace_back</code> will do an inplace-construction?</p>
<p>Cases for clarification:</p>
<pre><code>std::vector<std::string> bar;
</code></pre>
<p><strong>First:</strong></p>
<pre><code>bar.emplace_back(std::move(std::string("some_string")));
</code></pre>
<p><strong>Second:</strong></p>
<pre><code>std::string str("some_string");
bar.emplace_back(std::move(str));
</code></pre>
<p><strong>Third:</strong></p>
<pre><code>bar.emplace_back(std::move("some_string"));
</code></pre> | 35,405,013 | 4 | 1 | null | 2016-02-15 08:51:59.23 UTC | 12 | 2019-01-14 08:25:59.98 UTC | null | null | null | null | 4,523,099 | null | 1 | 34 | c++|c++11|vector|move-semantics | 23,536 | <p>In the second version, there is an advantage. Calling <code>emplace_back</code> will call the move constructor of <code>std::string</code> when <code>std::move</code> is used, which could save on a copy (so long as that string isn't stored in a SSO buffer). Note that this is essentially the same as <code>push_back</code> in this case.</p>
<p><code>std::move</code> in the first version is unnecessary, as the string is already a prvalue.</p>
<p><code>std::move</code> in the third version is irrelevant, as a string literal cannot be moved from.</p>
<p>The simplest and most efficient method is this:</p>
<pre><code>bar.emplace_back("some_string");
</code></pre>
<p>That requires no unnecessary <code>std::string</code> constructions as the literal is perfect-forwarded to the constructor.</p> |
35,773,028 | How to change body in OkHttp Response? | <p>I'm using retrofit. To catch response i'm using Interceptor:</p>
<pre><code>OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(myinterceptor);
</code></pre>
<p>here is code of interceptor:</p>
<pre><code>new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if (path.equals("/user")){
String stringJson = response.body().string();
JSONObject jsonObject = new JSONObject(stringJson);
jsonObject.put("key",1);
//here I need to set this new json to response and then return this response
</code></pre>
<p>How to change body in OkHttp Response?</p> | 35,773,177 | 5 | 2 | null | 2016-03-03 13:05:50.02 UTC | 10 | 2019-12-26 13:00:23.45 UTC | 2017-02-21 12:56:54.597 UTC | null | 13,075 | null | 2,425,851 | null | 1 | 24 | java|android|retrofit|interceptor|okhttp | 31,514 | <p>Add this </p>
<pre><code>MediaType contentType = response.body().contentType();
ResponseBody body = ResponseBody.create(contentType, jsonObject);
return response.newBuilder().body(body).build();
</code></pre>
<p>after your response modification. <code>jsonObject</code> is the modified JSON you want to return.</p> |
21,160,226 | No Idea why : The ResourceConfig instance does not contain any root resource classes | <p>I'm new to jersey and web services and I'm try to run a simple RESTful web service. I followed <a href="http://www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/" rel="noreferrer">http://www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/</a> but my project doesn't use maven and I download the jersey.1.17.1.jar and include it to my project path.</p>
<p>When I want to call the service on <code>http://localhost:8080/sycotext/rest/service/SOMETEXT</code> I get this error : </p>
<pre><code>HTTP Status 500 - Servlet.init() for servlet sycoText-servlet threw exception
</code></pre>
<p>this is the stack trace : </p>
<pre><code>javax.servlet.ServletException: Servlet.init() for servlet sycoText-servlet threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:76)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:934)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:515)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1010)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:640)
org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1618)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1576)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:724)
root cause
com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
com.sun.jersey.server.impl.application.RootResourceUriRules.<init>(RootResourceUriRules.java:99)
com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1331)
com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:168)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:774)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:770)
com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:770)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:765)
com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:489)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:319)
com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:76)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:934)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:515)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1010)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:640)
org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1618)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1576)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:724)
</code></pre>
<p>here is my code :</p>
<pre><code>package ir.sycotech.text.server.service;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
@Path("/service")
public class SycoTextService {
@GET
@Path("/{param}")
public Response getMsg(@PathParam("param") String msg) {
String output = "Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
</code></pre>
<p>and here is my web.xml : </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<servlet>
<servlet-name>sycoText-servlet</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>ir.sycotech.text.server.service</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sycoText-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
</code></pre>
<p>I have specified my packagename correctly in the web.xml file and I don't know why I got this error, I will be really appreciate if anyone knows what is the problem</p> | 21,166,333 | 9 | 3 | null | 2014-01-16 11:15:58.423 UTC | 3 | 2017-11-22 09:36:58.357 UTC | 2017-11-21 15:07:06.513 UTC | null | 2,333,214 | null | 1,923,688 | null | 1 | 16 | java|rest|jersey | 70,254 | <p>The error:</p>
<blockquote>
<p>com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.</p>
</blockquote>
<p>means that Jersey can't find service classes. That can be caused by a wrongly named package for the <code>com.sun.jersey.config.property.packages</code> parameter or if the package name is correct but it does not contain resource classes (people sometimes forget to add the <code>@Path</code> annotation on the class).</p>
<p>But I can't find anything wrong with your setup. So this should work!</p>
<p>Check that your application deployed correctly and that your <code>WEB-INF/classes</code> folder actually contains your class with the proper folder path for the package.</p>
<p>Do a full clean and rebuild then try again. </p> |
2,230,202 | How can I hierarchically group data using LINQ? | <p>I have some data that has various attributes and I want to hierarchically group that data. For example:</p>
<pre><code>public class Data
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
</code></pre>
<p>I would want this grouped as:</p>
<pre><code>A1
- B1
- C1
- C2
- C3
- ...
- B2
- ...
A2
- B1
- ...
...
</code></pre>
<p>Currently, I have been able to group this using LINQ such that the top group divides the data by A, then each subgroup divides by B, then each B subgroup contains subgroups by C, etc. The LINQ looks like this (assuming an <code>IEnumerable<Data></code> sequence called <code>data</code>):</p>
<pre><code>var hierarchicalGrouping =
from x in data
group x by x.A
into byA
let subgroupB = from x in byA
group x by x.B
into byB
let subgroupC = from x in byB
group x by x.C
select new
{
B = byB.Key,
SubgroupC = subgroupC
}
select new
{
A = byA.Key,
SubgroupB = subgroupB
};
</code></pre>
<p>As you can see, this gets somewhat messy the more subgrouping that's required. Is there a nicer way to perform this type of grouping? It seems like there should be and I'm just not seeing it.</p>
<p><strong>Update</strong><br>
So far, I have found that expressing this hierarchical grouping by using the fluent LINQ APIs rather than query language arguably improves readability, but it doesn't feel very DRY.</p>
<p>There were two ways I did this: one using <code>GroupBy</code> with a result selector, the other using <code>GroupBy</code> followed by a <code>Select</code> call. Both could be formatted to be more readable than using query language but don't still don't scale well.</p>
<pre><code>var withResultSelector =
data.GroupBy(a => a.A, (aKey, aData) =>
new
{
A = aKey,
SubgroupB = aData.GroupBy(b => b.B, (bKey, bData) =>
new
{
B = bKey,
SubgroupC = bData.GroupBy(c => c.C, (cKey, cData) =>
new
{
C = cKey,
SubgroupD = cData.GroupBy(d => d.D)
})
})
});
</code></pre>
<p></p>
<pre><code>var withSelectCall =
data.GroupBy(a => a.A)
.Select(aG =>
new
{
A = aG.Key,
SubgroupB = aG
.GroupBy(b => b.B)
.Select(bG =>
new
{
B = bG.Key,
SubgroupC = bG
.GroupBy(c => c.C)
.Select(cG =>
new
{
C = cG.Key,
SubgroupD = cG.GroupBy(d => d.D)
})
})
});
</code></pre>
<p><strong>What I'd like...</strong><br>
I can envisage a couple of ways that this could be expressed (assuming the language and framework supported it). The first would be a <code>GroupBy</code> extension that takes a series of function pairs for key selection and result selection, <code>Func<TElement, TKey></code> and <code>Func<TElement, TResult></code>. Each pair describes the next sub-group. This option falls down because each pair would potentially require <code>TKey</code> and <code>TResult</code> to be different than the others, which would mean <code>GroupBy</code> would need finite parameters and a complex declaration.</p>
<p>The second option would be a <code>SubGroupBy</code> extension method that could be chained to produce sub-groups. <code>SubGroupBy</code> would be the same as <code>GroupBy</code> but the result would be the previous grouping further partitioned. For example:</p>
<pre><code>var groupings = data
.GroupBy(x=>x.A)
.SubGroupBy(y=>y.B)
.SubGroupBy(z=>z.C)
</code></pre>
<p></p>
<pre><code>// This version has a custom result type that would be the grouping data.
// The element data at each stage would be the custom data at this point
// as the original data would be lost when projected to the results type.
var groupingsWithCustomResultType = data
.GroupBy(a=>a.A, x=>new { ... })
.SubGroupBy(b=>b.B, y=>new { ... })
.SubGroupBy(c=>c.C, c=>new { ... })
</code></pre>
<p>The difficulty with this is how to implement the methods efficiently as with my current understanding, each level would re-create new objects in order to extend the previous objects. The first iteration would create groupings of A, the second would then create objects that have a key of A and groupings of B, the third would redo all that and add the groupings of C. This seems terribly inefficient (though I suspect my current options actually do this anyway). It would be nice if the calls passed around a meta-description of what was required and the instances were only created on the last pass, but that sounds difficult too. Note that his is similar to what can be done with <code>GroupBy</code> but without the nested method calls.</p>
<p>Hopefully all that makes sense. I expect I am chasing rainbows here, but maybe not.</p>
<p><strong>Update - another option</strong><br>
Another possibility that I think is more elegant than my previous suggestions relies on each parent group being just a key and a sequence of child items (as in the examples), much like <code>IGrouping</code> provides now. That means one option for constructing this grouping would be a series of key selectors and a single results selector.</p>
<p>If the keys were all limited to a set type, which is not unreasonable, then this could be generated as a sequence of key selectors and a results selector, or a results selector and a <code>params</code> of key selectors. Of course, if the keys had to be of different types and different levels, this becomes difficult again except for a finite depth of hierarchy due to the way generics parameterization works.</p>
<p>Here are some illustrative examples of what I mean:</p>
<p>For example:</p>
<pre><code>public static /*<grouping type>*/ SubgroupBy(
IEnumerable<Func<TElement, TKey>> keySelectors,
this IEnumerable<TElement> sequence,
Func<TElement, TResult> resultSelector)
{
...
}
var hierarchy = data.SubgroupBy(
new [] {
x => x.A,
y => y.B,
z => z.C },
a => new { /*custom projection here for leaf items*/ })
</code></pre>
<p>Or:</p>
<pre><code>public static /*<grouping type>*/ SubgroupBy(
this IEnumerable<TElement> sequence,
Func<TElement, TResult> resultSelector,
params Func<TElement, TKey>[] keySelectors)
{
...
}
var hierarchy = data.SubgroupBy(
a => new { /*custom projection here for leaf items*/ },
x => x.A,
y => y.B,
z => z.C)
</code></pre>
<p>This does not solve implementation inefficiencies, but it should solve the complex nesting. However, what would the return type of this grouping be? Would I need my own interface or can I use <code>IGrouping</code> somehow. How much do I need to define or does the variable depth of the hierarchy still make this impossible?</p>
<p>My guess is that this should be the same as the return type from any <code>IGrouping</code> call but how does the type system infer that type if it isn't involved in any of the parameters that are passed?</p>
<p>This problem is stretching my understanding, which is great, but my brain hurts.</p> | 2,351,132 | 3 | 7 | 2010-02-10 19:26:15.313 UTC | 2010-02-09 15:32:27.033 UTC | 10 | 2021-06-26 17:14:33.48 UTC | 2010-02-10 19:24:20.71 UTC | null | 23,234 | null | 23,234 | null | 1 | 16 | linq|c#-3.0|grouping|group-by | 7,860 | <p><a href="http://blogs.msdn.com/mitsu/archive/2007/12/22/playing-with-linq-grouping-groupbymany.aspx" rel="nofollow noreferrer">Here is a description</a> how you can implement an hierarchical grouping mechanism.</p>
<p>From this description:</p>
<p><strong>Result class:</strong></p>
<pre><code>public class GroupResult
{
public object Key { get; set; }
public int Count { get; set; }
public IEnumerable Items { get; set; }
public IEnumerable<GroupResult> SubGroups { get; set; }
public override string ToString()
{ return string.Format("{0} ({1})", Key, Count); }
}
</code></pre>
<p><strong>Extension method:</strong></p>
<pre><code>public static class MyEnumerableExtensions
{
public static IEnumerable<GroupResult> GroupByMany<TElement>(
this IEnumerable<TElement> elements,
params Func<TElement, object>[] groupSelectors)
{
if (groupSelectors.Length > 0)
{
var selector = groupSelectors.First();
//reduce the list recursively until zero
var nextSelectors = groupSelectors.Skip(1).ToArray();
return
elements.GroupBy(selector).Select(
g => new GroupResult
{
Key = g.Key,
Count = g.Count(),
Items = g,
SubGroups = g.GroupByMany(nextSelectors)
});
}
else
return null;
}
}
</code></pre>
<p><strong>Usage:</strong></p>
<pre><code>var result = customers.GroupByMany(c => c.Country, c => c.City);
</code></pre>
<p><strong>Edit:</strong></p>
<p>Here is an improved and properly typed version of the code.</p>
<pre><code>public class GroupResult<TItem>
{
public object Key { get; set; }
public int Count { get; set; }
public IEnumerable<TItem> Items { get; set; }
public IEnumerable<GroupResult<TItem>> SubGroups { get; set; }
public override string ToString()
{ return string.Format("{0} ({1})", Key, Count); }
}
public static class MyEnumerableExtensions
{
public static IEnumerable<GroupResult<TElement>> GroupByMany<TElement>(
this IEnumerable<TElement> elements,
params Func<TElement, object>[] groupSelectors)
{
if (groupSelectors.Length > 0)
{
var selector = groupSelectors.First();
//reduce the list recursively until zero
var nextSelectors = groupSelectors.Skip(1).ToArray();
return
elements.GroupBy(selector).Select(
g => new GroupResult<TElement> {
Key = g.Key,
Count = g.Count(),
Items = g,
SubGroups = g.GroupByMany(nextSelectors)
});
} else {
return null;
}
}
}
</code></pre> |
8,780,912 | How can I perform a least-squares fitting over multiple data sets fast? | <p>I am trying to make a gaussian fit over many data points. E.g. I have a 256 x 262144 array of data. Where the 256 points need to be fitted to a gaussian distribution, and I need 262144 of them.</p>
<p>Sometimes the peak of the gaussian distribution is outside the data-range, so to get an accurate mean result curve-fitting is the best approach. Even if the peak is inside the range, curve-fitting gives a better sigma because other data is not in the range.</p>
<p>I have this working for one data point, using code from <a href="http://www.scipy.org/Cookbook/FittingData" rel="nofollow noreferrer">http://www.scipy.org/Cookbook/FittingData</a> .</p>
<p>I have tried to just repeat this algorithm, but it looks like it is going to take something in the order of 43 minutes to solve this. Is there an already-written fast way of doing this in parallel or more efficiently?</p>
<pre><code>from scipy import optimize
from numpy import *
import numpy
# Fitting code taken from: http://www.scipy.org/Cookbook/FittingData
class Parameter:
def __init__(self, value):
self.value = value
def set(self, value):
self.value = value
def __call__(self):
return self.value
def fit(function, parameters, y, x = None):
def f(params):
i = 0
for p in parameters:
p.set(params[i])
i += 1
return y - function(x)
if x is None: x = arange(y.shape[0])
p = [param() for param in parameters]
optimize.leastsq(f, p)
def nd_fit(function, parameters, y, x = None, axis=0):
"""
Tries to an n-dimensional array to the data as though each point is a new dataset valid across the appropriate axis.
"""
y = y.swapaxes(0, axis)
shape = y.shape
axis_of_interest_len = shape[0]
prod = numpy.array(shape[1:]).prod()
y = y.reshape(axis_of_interest_len, prod)
params = numpy.zeros([len(parameters), prod])
for i in range(prod):
print "at %d of %d"%(i, prod)
fit(function, parameters, y[:,i], x)
for p in range(len(parameters)):
params[p, i] = parameters[p]()
shape[0] = len(parameters)
params = params.reshape(shape)
return params
</code></pre>
<p>Note that the data isn't necessarily 256x262144 and i've done some fudging around in nd_fit to make this work.</p>
<p>The code I use to get this to work is</p>
<pre><code>from curve_fitting import *
import numpy
frames = numpy.load("data.npy")
y = frames[:,0,0,20,40]
x = range(0, 512, 2)
mu = Parameter(x[argmax(y)])
height = Parameter(max(y))
sigma = Parameter(50)
def f(x): return height() * exp (-((x - mu()) / sigma()) ** 2)
ls_data = nd_fit(f, [mu, sigma, height], frames, x, 0)
</code></pre>
<p>Note: The solution posted below by @JoeKington is great and solves really fast. However it doesn't appear to work unless the significant area of the gaussian is inside the appropriate area. I will have to test if the mean is still accurate though, as that is the main thing I use this for.
<img src="https://imgur.com/E38eJ.png" alt="Analysis of gaussian distribution estimations"></p> | 8,783,634 | 1 | 1 | null | 2012-01-08 20:17:06.357 UTC | 13 | 2012-01-11 20:37:57.483 UTC | 2012-01-11 01:46:59.533 UTC | null | 94,104 | null | 94,104 | null | 1 | 11 | python|scipy|curve-fitting|gaussian|least-squares | 9,901 | <p>The easiest thing to do is to linearlize the problem. You're using a non-linear, iterative method which will be slower than a linear least squares solution.</p>
<p>Basically, you have:</p>
<p><code>y = height * exp(-(x - mu)^2 / (2 * sigma</code>^2))</p>
<p>To make this a linear equation, take the (natural) log of both sides:</p>
<pre><code>ln(y) = ln(height) - (x - mu)^2 / (2 * sigma^2)
</code></pre>
<p>This then simplifies to the polynomial:</p>
<pre><code>ln(y) = -x^2 / (2 * sigma^2) + x * mu / sigma^2 - mu^2 / sigma^2 + ln(height)
</code></pre>
<p>We can recast this in a bit simpler form:</p>
<pre><code>ln(y) = A * x^2 + B * x + C
</code></pre>
<p>where:</p>
<pre><code>A = 1 / (2 * sigma^2)
B = mu / (2 * sigma^2)
C = mu^2 / sigma^2 + ln(height)
</code></pre>
<p>However, there's one catch. This will become unstable in the presence of noise in the "tails" of the distribution. </p>
<p>Therefore, we need to use only the data near the "peaks" of the distribution. It's easy enough to only include data that falls above some threshold in the fitting. In this example, I'm only including data that's greater than 20% of the maximum observed value for a given gaussian curve that we're fitting.</p>
<p>Once we've done this, though, it's rather fast. Solving for 262144 different gaussian curves takes only ~1 minute (Be sure to removing the plotting portion of the code if you run it on something that large...). It's also quite easy to parallelize, if you want...</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import itertools
def main():
x, data = generate_data(256, 6)
model = [invert(x, y) for y in data.T]
sigma, mu, height = [np.array(item) for item in zip(*model)]
prediction = gaussian(x, sigma, mu, height)
plot(x, data, linestyle='none', marker='o')
plot(x, prediction, linestyle='-')
plt.show()
def invert(x, y):
# Use only data within the "peak" (20% of the max value...)
key_points = y > (0.2 * y.max())
x = x[key_points]
y = y[key_points]
# Fit a 2nd order polynomial to the log of the observed values
A, B, C = np.polyfit(x, np.log(y), 2)
# Solve for the desired parameters...
sigma = np.sqrt(-1 / (2.0 * A))
mu = B * sigma**2
height = np.exp(C + 0.5 * mu**2 / sigma**2)
return sigma, mu, height
def generate_data(numpoints, numcurves):
np.random.seed(3)
x = np.linspace(0, 500, numpoints)
height = 100 * np.random.random(numcurves)
mu = 200 * np.random.random(numcurves) + 200
sigma = 100 * np.random.random(numcurves) + 0.1
data = gaussian(x, sigma, mu, height)
noise = 5 * (np.random.random(data.shape) - 0.5)
return x, data + noise
def gaussian(x, sigma, mu, height):
data = -np.subtract.outer(x, mu)**2 / (2 * sigma**2)
return height * np.exp(data)
def plot(x, ydata, ax=None, **kwargs):
if ax is None:
ax = plt.gca()
colorcycle = itertools.cycle(mpl.rcParams['axes.color_cycle'])
for y, color in zip(ydata.T, colorcycle):
ax.plot(x, y, color=color, **kwargs)
main()
</code></pre>
<p><img src="https://i.stack.imgur.com/3h9Db.png" alt="enter image description here"></p>
<p>The only thing we'd need to change for a parallel version is the main function. (We also need a dummy function because <code>multiprocessing.Pool.imap</code> can't supply additional arguments to its function...) It would look something like this:</p>
<pre><code>def parallel_main():
import multiprocessing
p = multiprocessing.Pool()
x, data = generate_data(256, 262144)
args = itertools.izip(itertools.repeat(x), data.T)
model = p.imap(parallel_func, args, chunksize=500)
sigma, mu, height = [np.array(item) for item in zip(*model)]
prediction = gaussian(x, sigma, mu, height)
def parallel_func(args):
return invert(*args)
</code></pre>
<p><strong>Edit:</strong> In cases where the simple polynomial fitting isn't working well, try weighting the problem by the y-values, <a href="http://scipy-central.org/item/28/2/fitting-a-gaussian-to-noisy-data-points" rel="noreferrer">as mentioned in the link/paper</a> that @tslisten shared (and Stefan van der Walt implemented, though my implementation is a bit different).</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import itertools
def main():
def run(x, data, func, threshold=0):
model = [func(x, y, threshold=threshold) for y in data.T]
sigma, mu, height = [np.array(item) for item in zip(*model)]
prediction = gaussian(x, sigma, mu, height)
plt.figure()
plot(x, data, linestyle='none', marker='o', markersize=4)
plot(x, prediction, linestyle='-', lw=2)
x, data = generate_data(256, 6, noise=100)
threshold = 50
run(x, data, weighted_invert, threshold=threshold)
plt.title('Weighted by Y-Value')
run(x, data, invert, threshold=threshold)
plt.title('Un-weighted Linear Inverse'
plt.show()
def invert(x, y, threshold=0):
mask = y > threshold
x, y = x[mask], y[mask]
# Fit a 2nd order polynomial to the log of the observed values
A, B, C = np.polyfit(x, np.log(y), 2)
# Solve for the desired parameters...
sigma, mu, height = poly_to_gauss(A,B,C)
return sigma, mu, height
def poly_to_gauss(A,B,C):
sigma = np.sqrt(-1 / (2.0 * A))
mu = B * sigma**2
height = np.exp(C + 0.5 * mu**2 / sigma**2)
return sigma, mu, height
def weighted_invert(x, y, weights=None, threshold=0):
mask = y > threshold
x,y = x[mask], y[mask]
if weights is None:
weights = y
else:
weights = weights[mask]
d = np.log(y)
G = np.ones((x.size, 3), dtype=np.float)
G[:,0] = x**2
G[:,1] = x
model,_,_,_ = np.linalg.lstsq((G.T*weights**2).T, d*weights**2)
return poly_to_gauss(*model)
def generate_data(numpoints, numcurves, noise=None):
np.random.seed(3)
x = np.linspace(0, 500, numpoints)
height = 7000 * np.random.random(numcurves)
mu = 1100 * np.random.random(numcurves)
sigma = 100 * np.random.random(numcurves) + 0.1
data = gaussian(x, sigma, mu, height)
if noise is None:
noise = 0.1 * height.max()
noise = noise * (np.random.random(data.shape) - 0.5)
return x, data + noise
def gaussian(x, sigma, mu, height):
data = -np.subtract.outer(x, mu)**2 / (2 * sigma**2)
return height * np.exp(data)
def plot(x, ydata, ax=None, **kwargs):
if ax is None:
ax = plt.gca()
colorcycle = itertools.cycle(mpl.rcParams['axes.color_cycle'])
for y, color in zip(ydata.T, colorcycle):
#kwargs['color'] = kwargs.get('color', color)
ax.plot(x, y, color=color, **kwargs)
main()
</code></pre>
<p><img src="https://i.stack.imgur.com/NdQvA.png" alt="enter image description here">
<img src="https://i.stack.imgur.com/3jbvd.png" alt="enter image description here"></p>
<p>If that's still giving you trouble, then try iteratively-reweighting the least-squares problem (The final "best" reccomended method in the link @tslisten mentioned). Keep in mind that this will be considerably slower, however.</p>
<pre><code>def iterative_weighted_invert(x, y, threshold=None, numiter=5):
last_y = y
for _ in range(numiter):
model = weighted_invert(x, y, weights=last_y, threshold=threshold)
last_y = gaussian(x, *model)
return model
</code></pre> |
27,279,032 | Swift convert object that is NSNumber to Double | <p>I have this code in Swift and it works, but I would think there is a better way to get my object from NSNumber and convert it to a Double:</p>
<pre><code>var rating: NSNumber
var ratingDouble: Double
rating = self.prodResult?.prodsInfo.prodList[indexPath.row].avgRating as NSNumber!!
ratingDouble = Double(rating.doubleValue)
</code></pre> | 27,279,483 | 1 | 2 | null | 2014-12-03 18:29:11.537 UTC | 3 | 2018-10-09 17:58:07.843 UTC | null | null | null | null | 72,041 | null | 1 | 32 | ios|swift | 39,815 | <p><strong>Update</strong></p>
<p>Swift's behavior here has changed quite a bit since 1.0. Not that it was that easy before, but Swift has made it harder to convert between number types because it wants you to be explicit about what to do with precision loss. Your new choices now look like this:</p>
<pre><code>var rating: NSNumber
var ratingDouble: Double
ratingDouble = rating as! Double // 1
ratingDouble = Double(exactly: rating)! // 2
ratingDouble = Double(truncating: rating) // 3
ratingDouble = rating.doubleValue // 4
if let x = rating as? Double { // 5
ratingDouble = x
}
if let x = Double(exactly: rating) { // 6
ratingDouble = x
}
</code></pre>
<ol>
<li><p>This calls <a href="https://github.com/apple/swift/blob/a28c9d62138e5386ba9341332af218cd232c455e/stdlib/public/SDK/Foundation/NSNumber.swift#L509" rel="noreferrer"><code>Double._forceBridgeFromObjectiveC</code></a> which calls <code>Double(exactly:)</code> with <code>Double</code>, <code>Int64</code>, or <code>UInt64</code> based on the stored type in <code>rating</code>. It will fail and crash the app if the number isn't exactly representable as a <code>Double</code>. E.g. <code>UInt64.max</code> has more digits than <code>Double</code> can store, so it'll crash.</p></li>
<li><p>This is exactly the same as 1 except that it may also crash on <code>NaN</code> since that check isn't included.</p></li>
<li><p>This function always returns a <code>Double</code> but will lose precision in cases where 1 and 2 would crash. <a href="https://github.com/apple/swift/blob/a28c9d62138e5386ba9341332af218cd232c455e/stdlib/public/SDK/Foundation/NSNumber.swift#L484" rel="noreferrer">This literally just calls <code>doubleValue</code> when passing in an <code>NSNumber</code>.</a></p></li>
<li><p>Same as 3.</p></li>
<li><p>This is like 1 except that instead of crashing the app, it'll return nil and the inside of the statement won't be evaluated.</p></li>
<li><p>Same as 5, but like 2 will return nil if the value is <code>NaN</code>.</p></li>
</ol>
<p>If you know your data source is dealing in doubles, 1-4 will probably all serve you about the same. 3 and 4 would be my first choices though.</p>
<hr>
<p><strong>Old Answer for Swift 1 and 2</strong></p>
<p>There are several things you can do:</p>
<pre><code>var rating: NSNumber
var ratingDouble: Double
ratingDouble = rating as Double // 1
ratingDouble = Double(rating) // 2
ratingDouble = rating.doubleValue // 3
</code></pre>
<ol>
<li>The first item takes advantage of <code>Objective-C</code>bridging which allows <code>AnyObject</code> and <code>NSNumber</code> to be cast as <a href="https://developer.apple.com/library/ios/documentation/swift/conceptual/buildingcocoaapps/WorkingWithCocoaDataTypes.html#//apple_ref/doc/uid/TP40014216-CH6-XID_45" rel="noreferrer"><code>Double|Float|Int|UInt|Bool</code></a>.</li>
<li>The second item presumably goes through a constructor with the signature <code>init(_ number: NSNumber)</code>. I couldn't find it in the module or docs but passing <code>AnyObject</code> in generated an error that it cannot be implicitly downcast to <code>NSNumber</code> so it must be there and not just bridging.</li>
<li>The third item doesn't employ language features in the same way. It just takes advantage of the fact that <code>doubleValue</code> returns a <code>Double</code>.</li>
</ol>
<p>One benefit of 1 is that it also works for <code>AnyObject</code> so your code could be:</p>
<pre><code>let ratingDouble = self.prodResult!.prodsInfo.prodList[indexPath.row].avgRating! as Double
</code></pre>
<p>Note that I removed the <code>?</code> from your function and moved the <code>!</code> in. Whenever you use ! you are eschewing the safety of <code>?</code> so there's no reason to do both together.</p> |
19,535,644 | How to use the priority queue STL for objects? | <pre><code>class Person
{
public:
int age;
};
</code></pre>
<p>I want to store objects of the class Person in a priority queue.</p>
<pre><code>priority_queue< Person, vector<Person>, ??? >
</code></pre>
<p>I think I need to define a class for the comparison thing, but I am not sure about it.</p>
<p>Also, when we write,</p>
<pre><code>priority_queue< int, vector<int>, greater<int> >
</code></pre>
<p>How does the greater work?</p> | 19,535,699 | 5 | 1 | null | 2013-10-23 07:38:16.383 UTC | 44 | 2020-05-17 14:02:04.857 UTC | null | null | null | null | 2,441,151 | null | 1 | 82 | c++|stl | 137,306 | <p>You need to provide a valid strict weak ordering comparison for the type stored in the queue, <code>Person</code> in this case. The default is to use <code>std::less<T></code>, which resolves to something equivalent to <code>operator<</code>. This relies on it's own stored type having one. So if you were to implement</p>
<pre><code>bool operator<(const Person& lhs, const Person& rhs);
</code></pre>
<p>it should work without any further changes. The implementation could be</p>
<pre><code>bool operator<(const Person& lhs, const Person& rhs)
{
return lhs.age < rhs.age;
}
</code></pre>
<p>If the the type does not have a natural "less than" comparison, it would make more sense to provide your own predicate, instead of the default <code>std::less<Person></code>. For example,</p>
<pre><code>struct LessThanByAge
{
bool operator()(const Person& lhs, const Person& rhs) const
{
return lhs.age < rhs.age;
}
};
</code></pre>
<p>then instantiate the queue like this:</p>
<pre><code>std::priority_queue<Person, std::vector<Person>, LessThanByAge> pq;
</code></pre>
<p>Concerning the use of <code>std::greater<Person></code> as comparator, this would use the equivalent of <code>operator></code> and have the effect of creating a queue with the priority inverted WRT the default case. It would require the presence of an <code>operator></code> that can operate on two <code>Person</code> instances.</p> |
1,189,236 | Data structures for message passing within a program? | <p>I'm trying to write a simple RPG. So far, each time I try to start it instantly becomes a mess and I don't know how to organize anything. So I'm starting over, trying to prototype a new structure that is basically the MVC framework. My app starts execution in the Controller, where it will create the View and Model. Then it will enter the game loop, and the first step in the game loop is to collect user input.</p>
<p>User input will be collected by a part of the View, because it can vary (a 3D View will directly poll user input, whereas maybe a remote View will receive it over a telnet connection, or a command-line view would use System.in). The input will be translated into messages, and each message will be given to Controller (by a method call) which can then interpret the message to modify Model data, or send data over the network (as I am hoping to have a networking option).</p>
<p>This message handling technique can also be used, in the event of a networked game, to process network messages. Am I keeping the spirit of the MVC so far?</p>
<p>Anyway my question is, what is the best way to represent these messages?</p>
<p>Here is a use case, with each message in italics: Let's say the user starts the game and <em>chooses character 2</em>. Then the user <em>moves to coordinates (5,2)</em>. Then he <em>says to public chat, "hi!"</em>. Then he chooses to <em>save and quit</em>.</p>
<p>How should the view wrap up these messages into something the controller can understand? Or do you think I should have separate controller methods like chooseCharacter(), moveCharacterTo(), publicChat()? I'm not sure that such simple implementation would work when I move to a networked game. But at the other end of the extreme, I don't want to just send strings to the Controller. It's just tough because the choose-character action takes one integer, the move-to takes two integers, and the chat takes a string (and a scope (public private global) and in the case of private, a destination user); there's no real set data type to it all.</p>
<p>Also any general suggestions are very welcome; am I worrying about this at the right time? Am I headed down the right path to a well-laid-out MVC app? Is there anything I've forgotten?</p>
<p>Thanks!</p> | 1,191,261 | 4 | 3 | null | 2009-07-27 16:35:46.297 UTC | 48 | 2009-11-04 22:39:55.003 UTC | null | null | null | null | 47,493 | null | 1 | 36 | java|model-view-controller | 8,955 | <p><em>(Disclaimer: I never programmed games in Java, only in C++. But the general idea should be applicable in Java too.
The ideas I present are not my own, but a mash-up of solutions I found in books or "on the internet", see references section.
I employ all this myself and so far it results in a clean design where I know exactly where to put new features I add.)</em></p>
<p>I am afraid this will be a long answer, it might not be clear when reading for the first time, as I can't describe it just top-down very well, so there will be references back and forth, this is due to my lacking explaining skill, not because the design is flawed. In hindsight I overreached and may even be off-topic. But now that I have written all this, I can't bring myself to just throw it away. Just ask if something is unclear.</p>
<p>Before starting to design any of the packages and classes, start with an analysis. What are the features you want to have in the game. Don't plan for a "maybe I'll add this later", because almost certainly the design decisions you make up-front before you start to add this feature in earnest, the stub you planned for it will be insufficient.</p>
<p>And for motivation, I speak from experience here, don't think of your task as writing a game engine, write a game! Whatever you ponder about what would be cool to have for a future project, reject it unless you put it in the game you are writing right now. No untested dead code, no motivation problems due to not being able to solve a problem that isn't even an issue for the immediate project ahead. There is no perfect design, but there is one good enough. Worth keeping this in mind.</p>
<p>As said above, I don't believe that MVC is of any use when designing a game. Model/View separation is not an issue, and the controller stuff is pretty complicated, too much so as to be just called "controller".
If you want to have subpackages named model, view, control, go ahead. The following can be integrated into this packaging scheme, though others are at least as sensible.</p>
<p>It is hard to find a starting point into my solution, so I just start top-most:</p>
<p>In the main program, I just create the Application object, init it and start it. The application's <code>init()</code> will create the feature servers (see below) and inits them. Also the first game state is created and pushed on top. (also see below)</p>
<p>Feature servers encapsulate orthogonal game features. These can be implemented independently and are loosely coupled by messages. Example features: Sound, visual representation, collision detection, artificial intelligence/decision making, physics, and so on. How the features themselves are organized is described below.</p>
<h2>Input, control flow and the game loop</h2>
<p>Game states present a way to organize input control. I usually have a single class that collects input events or capture input state and poll it later (InputServer/InputManager) . If using the event based approach the events are given to the single one registered active game state.</p>
<p>When starting the game this will be the main menu game state. A game state has <code>init/destroy</code> and <code>resume/suspend</code> function. <code>Init()</code> will initialize the game state, in case of the main menu it will show the top most menu level. <code>Resume()</code> will give control to this state, it now takes the input from the InputServer. <code>Suspend()</code> will clear the menu view from the screen and <code>destroy()</code> will free any resources the main menu needs.</p>
<p>GameStates can be stacked, when a user starts the game using the "new game" option, then the MainMenu game state gets suspended and the PlayerControlGameState will be put onto the stack and now receives the input events. This way you can handle input depending on the state of your game. With only one controller active at any given time you simplify control flow enormously.</p>
<p>Input collection is triggered by the game loop. The game loop basically determines the frame time for the current loop, updates feature servers, collects input and updates the game state. The frame time is either given to an update function of each of these or is provided by a Timer singleton. This is the canonical time used to determine time duration since last update call.</p>
<h2>Game objects and features</h2>
<p>The heart of this design is interaction of game objects and features.
As shown above a feature in this sense is a piece of game functionality that can be implemented independently of each other. A game object is anything that interacts with the player or any other game objects in any way. Examples: The player avatar itself is a game object. A torch is a game object, NPCs are game objects as are lighting zones and sound sources or any combination of these.</p>
<p>Traditionally RPG game objects are the top class of some sophisticated class hierarchy, but really this approach is just wrong. Many orthogonal aspects can't be put into a hierarchy and even using interfaces in the end you have to have concrete classes. An item is a game object, a pick-able item is a game object a chest is a container is an item, but making a chest pick-able or not is an either or decision with this approach, as you have to have a single hierarchy. And it gets more complicated when you want to have a talking magic riddle chest that only opens when a riddle is answered. There just is no one all fitting hierarchy.</p>
<p>A better approach is to have just a single game object class and put each orthogonal aspect, which usually is expressed in the class hierarchy, into its own component/feature class. Can the game object hold other items? Then add the ContainerFeature to it, can it talk, add the TalkTargetFeature to it and so on.</p>
<p>In my design a GameObject only has an intrinsic unique id, name and location property, everything else is added as a feature component. Components can be added at run-time through the GameObject interface by calling addComponent(), removeComponent(). So to make it visible add a VisibleComponent, make it make sounds, add an AudableComponent, make it a container, add a ContainerComponent.</p>
<p>The VisibleComponent is important for your question, as this is the class that provides the link between model and view. Not everything needs a view in the classical sense. A trigger zone will not be visible, an ambient sound zone won't either. Only game objects having the VisibleComponent will be visible.
The visual representation is updated in the main loop, when the VisibleFeatureServer is updated. It then updates the view according to the VisibleComponents registered to it. Whether it queries the state of each or just queues messages received from them depends on your application and the underlying visualization library.</p>
<p>In my case I use Ogre3D. Here, when a VisibleComponent is attached to a game object it creates a SceneNode that is attached to the scene graph and to the scene node an Entity (representation of a 3d mesh). Every TransformMessage (see below) is processed immediately. The VisibleFeatureServer then makes Ogre3d redraw the scene to the RenderWindow (In essence, details are more complicated, as always)</p>
<h2>Messages</h2>
<p>So how do these features and game states and game objects communicate with each other?
Via messages. A Message in this design is simply any subclass of the Message class. Each concrete Message can have its own interface that is convenient for its task.</p>
<p>Messages can be sent from one GameObject to other GameObjects, from a GameObject to its components and from FeatureServers to the components they are responsible for.</p>
<p>When a FeatureComponent is created and added to a game object it registers itself to the game object by calling myGameObject.registerMessageHandler(this, MessageID) for every message it wants to receive. It also registers itself to its feature server for every message it wants to receive from there.</p>
<p>If the player tries to talk to a character it has in its focus, then the user will somehow trigger the talk action. E.g.: If the char in focus is a friendly NPC, then by pressing the mouse button the standard interaction is triggered. The target game objects standard action is queried by sending it a GetStandardActionMessage. The target game object receives the message and, starting with first registered one, notifies its feature components that want to know about the message. The first component for this message will then set the standard action to the one that will trigger itself (TalkTargetComponent will set standard action to Talk, which it will receive too first.) and then mark message as consumed. The GameObject will test for consumption and see that it is indeed consumed and return to caller. The now modified message is then evaluated and the resulting action invoked</p>
<p>Yes this example seems complicated but it already is one of the more complicated ones. Others like TransformMessage for notifying about position and orientation change are easier to process. A TransformMassage is interesting to many feature servers. VisualisationServer needs it to update GameObject's visual representation on screen. SoundServer to update 3d sound position and so on.</p>
<p>The advantage of using messages rather than invoking methods should be clear. There is lower coupling between components. When invoking a method the caller needs to know the callee. But by using messages this is completely decoupled. If there is no receiver, then it doesn't matter. Also how the receiver processes the message if at all is not a concern of the caller.
Maybe delegates are a good choice here, but Java misses a clean implementation for these and in case of the network game, you need to use some kind of RPC, which has a rather high latency. And low latency is crucial for interactive games.</p>
<h2>Persistence and marshalling</h2>
<p>This brings us to how to pass messages over the network. By encapsulating GameObject/Feature interaction to messages, we only have to worry about how to pass messages over the network. Ideally you bring messages into a universal form and put them into a UDP package and send it. Receiver unpacks message to a instance of the proper class and channels it to the receiver or broadcasts it, depending on the message.
I don't know whether Java's built-in serialization is up to the task. But even if not, there are lots of libs that can do this.</p>
<p>GameObjects and components make their persistent state available via properties (C++ doesn't have Serialization built-in.)
They have an interface similar to a PropertyBag in Java with which their state can be retrieved and restored.</p>
<h2>References</h2>
<ul>
<li><a href="http://flohofwoe.blogspot.com/" rel="noreferrer">The Brain Dump</a>: The blog of a professional game developer. Also authors of the open source Nebula engine, a game engine used in commercially successful games. Most of the design I presented here is taken from Nebula's application layer.</li>
<li><a href="http://flohofwoe.blogspot.com/2007/11/nebula3s-application-layer-provides.html" rel="noreferrer">Noteworthy article</a> on above blog, it lays out the application layer of the engine. Another angle to what I tried to describe above.</li>
<li><a href="http://www.ogre3d.org/forums/viewtopic.php?f=1&t=36015" rel="noreferrer">A lengthy discussion</a> on how to lay out game architecture. Mostly Ogre specific, but general enough to be useful for others too.</li>
<li><a href="http://gamearchitect.net/Articles/GameObjects1.html" rel="noreferrer">Another argument for component based designs</a>, with useful references at the bottom.</li>
</ul> |
229,179 | NULL in MySQL (Performance & Storage) | <p>What exactly does null do performance and storage (space) wise in MySQL?</p>
<p>For example:</p>
<p>TINYINT: 1 Byte
TINYINT w/NULL 1 byte + somehow stores NULL?</p> | 230,923 | 4 | 0 | null | 2008-10-23 10:02:48.15 UTC | 40 | 2016-12-06 00:37:09.89 UTC | null | null | null | Steve | 21,559 | null | 1 | 86 | sql|mysql|null | 38,028 | <p>It depends on which storage engine you use.</p>
<p>In MyISAM format, each row header contains a bitfield with one bit for each column to encode NULL state. A column that is NULL still takes up space, so NULL's don't reduce storage. See <a href="https://dev.mysql.com/doc/internals/en/myisam-introduction.html" rel="noreferrer">https://dev.mysql.com/doc/internals/en/myisam-introduction.html</a></p>
<p>In InnoDB, each column has a "field start offset" in the row header, which is one or two bytes per column. The high bit in that field start offset is on if the column is NULL. In that case, the column doesn't need to be stored at all. So if you have a lot of NULL's your storage should be significantly reduced.
See <a href="https://dev.mysql.com/doc/internals/en/innodb-field-contents.html" rel="noreferrer">https://dev.mysql.com/doc/internals/en/innodb-field-contents.html</a></p>
<p><strong>EDIT:</strong></p>
<p>The NULL bits are part of the row headers, you don't choose to add them.</p>
<p>The only way I can imagine NULLs improving performance is that in InnoDB, a page of data may fit more rows if the rows contain NULLs. So your InnoDB buffers may be more effective.</p>
<p>But I would be very surprised if this provides a significant performance advantage in practice. Worrying about the effect NULLs have on performance is in the realm of micro-optimization. You should focus your attention elsewhere, in areas that give greater bang for the buck. For example adding well-chosen indexes or increasing database cache allocation.</p> |
331,744 | JPA Multiple Embedded fields | <p>Is it possible for a JPA entity class to contain two embedded (<code>@Embedded</code>) fields? An example would be:</p>
<pre><code>@Entity
public class Person {
@Embedded
public Address home;
@Embedded
public Address work;
}
public class Address {
public String street;
...
}
</code></pre>
<p>In this case a <code>Person</code> can contain two <code>Address</code> instances - home and work. I'm using JPA with Hibernate's implementation. When I generate the schema using Hibernate Tools, it only embeds one <code>Address</code>. What I'd like is two embedded <code>Address</code> instances, each with its column names distinguished or pre-pended with some prefix (such as home and work). I know of <code>@AttributeOverrides</code>, but this requires that each attribute be individually overridden. This can get cumbersome if the embedded object (<code>Address</code>) gets big as each column needs to be individually overridden.</p> | 331,849 | 4 | 0 | null | 2008-12-01 18:31:39.28 UTC | 13 | 2017-03-27 18:01:11.21 UTC | 2008-12-01 18:38:44.507 UTC | sblundy | 4,893 | Steve Kuo | 24,396 | null | 1 | 87 | java|hibernate|jpa|jakarta-ee | 43,690 | <p>If you want to have the same embeddable object type twice in the same entity, the column name defaulting will not work: at least one of the columns will have to be explicit. Hibernate goes beyond the EJB3 spec and allows you to enhance the defaulting mechanism through the NamingStrategy. DefaultComponentSafeNamingStrategy is a small improvement over the default EJB3NamingStrategy that allows embedded objects to be defaulted even if used twice in the same entity.</p>
<p>From Hibernate Annotations Doc: <a href="http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#d0e714" rel="noreferrer">http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#d0e714</a></p> |
19,569,052 | Matplotlib - How to remove a specific line or curve | <p>I want to remove a specific line in a plot of multiple lines. Bellow is a given example which is not sufficient for me because it removes only the last plotted line and not the line that I want to remove. How can I do that? How can I address a specific line(by name, by number, by reference) throughout the program and delete that line?</p>
<pre><code>self.axes.lines.remove(self.axes.lines[0])
</code></pre> | 19,569,289 | 5 | 0 | null | 2013-10-24 14:41:37.647 UTC | 5 | 2021-03-26 18:27:03.303 UTC | null | null | null | null | 2,474,581 | null | 1 | 16 | python|matplotlib|line | 46,156 | <p>Almost all of the plotting functions return a reference to the <code>artist</code> object created ex:</p>
<pre><code>ln, = plot(x, y) # plot actually returns a list of artists, hence the ,
im = imshow(Z)
</code></pre>
<p>If you have the reference you can remove an artist via the <code>remove</code> <a href="http://matplotlib.org/api/artist_api.html#matplotlib.artist.Artist.remove" rel="noreferrer">(doc)</a> function ex:</p>
<pre><code>ln.remove()
im.remove()
</code></pre> |
60,020,217 | NPM Error : Error: EROFS: read-only file system, mkdir '/npm' | <p>I created an index.js, index.html and package.json file and I wanted to add express. When I write 'npm install express' in the terminal, I'm getting the error below. So far, I tried 'sudo npm install -g express', deleting node and npm completely and re-install. I also went through other questions over here but none of them worked out for me. Whatever I write with npm I get the same error. (I'm using macOS)</p>
<p>Do you have any suggestions? </p>
<p>This is the error I am getting:</p>
<pre><code>Error: EROFS: read-only file system, mkdir '/npm'
TypeError: Cannot read property 'loaded' of undefined
at exit (/usr/local/lib/node_modules/npm/lib/utils/error-handler.js:97:27)
at errorHandler (/usr/local/lib/node_modules/npm/lib/utils/error-handler.js:216:3)
at /usr/local/lib/node_modules/npm/bin/npm-cli.js:78:20
at cb (/usr/local/lib/node_modules/npm/lib/npm.js:225:22)
at /usr/local/lib/node_modules/npm/lib/npm.js:263:24
at /usr/local/lib/node_modules/npm/lib/config/core.js:81:7
at Array.forEach (<anonymous>)
at /usr/local/lib/node_modules/npm/lib/config/core.js:80:13
at f (/usr/local/lib/node_modules/npm/node_modules/once/once.js:25:25)
at afterExtras (/usr/local/lib/node_modules/npm/lib/config/core.js:171:20)
/usr/local/lib/node_modules/npm/lib/utils/error-handler.js:97
var doExit = npm.config.loaded ? npm.config.get('_exit') : true
^
TypeError: Cannot read property 'loaded' of undefined
at exit (/usr/local/lib/node_modules/npm/lib/utils/error-handler.js:97:27)
at process.errorHandler (/usr/local/lib/node_modules/npm/lib/utils/error-handler.js:216:3)
at process.emit (events.js:223:5)
at process._fatalException (internal/process/execution.js:150:25)
</code></pre> | 60,021,002 | 2 | 0 | null | 2020-02-01 19:03:48.853 UTC | 2 | 2022-02-24 05:53:28.573 UTC | 2020-02-01 19:21:07.7 UTC | null | 2,633,152 | null | 12,739,614 | null | 1 | 6 | node.js|npm|permissions | 41,831 | <p>The error means that you have no permission to install anything with npm at the path <code>/npm</code>.<br>
To verify this run <code>npm root -g</code>. This should return <code>/npm</code>.</p>
<p>Note that <code>/npm</code> ist not the default installation path on MacOS (see <a href="https://stackoverflow.com/a/35638528/1754076">https://stackoverflow.com/a/35638528/1754076</a>).</p>
<p>Checkout your npm configuration file and change the default installation path to something where you do have write access. You can also use npm itself to <a href="https://stackoverflow.com/a/28205851/1754076">change the default installation path</a>.</p> |
21,512,182 | bound element inside ngIf does not update binding | <p>I have written a angularjs directive.
in this directive's template I have added an ngIf directive and within it I display an input that is bound to my directive's scope.</p>
<pre><code><div ng-if="bool"><input ng-model="foo"></div>
</code></pre>
<p>I noticed, after a lot of trial and error that the ngIf directive cause the model to not get updated when the input text is changed. If I change it to ngShow everything works as expected.</p>
<p>I am looking for an explanation of this difference</p>
<p><a href="http://jsfiddle.net/elewinso/WaFs2/" rel="noreferrer">I have created a jsfiddle here</a></p> | 21,512,370 | 3 | 0 | null | 2014-02-02 15:13:42.84 UTC | 9 | 2015-09-18 07:37:25.833 UTC | null | null | null | null | 1,616,042 | null | 1 | 28 | javascript|angularjs|angularjs-directive | 20,269 | <p>It's happening because ngIf creates a new child scope, so if you want to bind to the same scope as the other inputs, we can go one level down with $parent. Check <a href="https://github.com/angular/angular.js/wiki/Understanding-Scopes">here</a> to understand more about scope inheritance</p>
<pre><code> angular.module('testApp', [])
.directive('testDir', function () {
return {
restrict: 'A',
template: '<input ng-model="foo"><input ng-model="foo">' +
'<div ng-if="bool"><input ng-model="$parent.foo"></div>',
link: function (scope, elem, attrs) {
scope.foo = "bar";
scope.bool = true;
}
}
});
</code></pre>
<p>Take a look to new <a href="http://jsfiddle.net/LSWVE/">jsfiddle</a></p> |
20,838,162 | How does ThreadPoolExecutor().map differ from ThreadPoolExecutor().submit? | <p>I was just very confused by some code that I wrote. I was surprised to discover that:</p>
<pre><code>with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
results = list(executor.map(f, iterable))
</code></pre>
<p>and </p>
<pre><code>with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
results = list(map(lambda x: executor.submit(f, x), iterable))
</code></pre>
<p>produce different results. The first one produces a list of whatever type <code>f</code> returns, the second produces a list of <code>concurrent.futures.Future</code> objects that then need to be evaluated with their <code>result()</code> method in order to get the value that <code>f</code> returned. </p>
<p>My main concern is that this means that <code>executor.map</code> can't take advantage of <code>concurrent.futures.as_completed</code>, which seems like an extremely convenient way to evaluate the results of some long-running calls to a database that I'm making as they become available. </p>
<p>I'm not at all clear on how <code>concurrent.futures.ThreadPoolExecutor</code> objects work -- naively, I would prefer the (somewhat more verbose):</p>
<pre><code>with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
result_futures = list(map(lambda x: executor.submit(f, x), iterable))
results = [f.result() for f in futures.as_completed(result_futures)]
</code></pre>
<p>over the more concise <code>executor.map</code> in order to take advantage of a possible gain in performance. Am I wrong to do so?</p> | 20,849,064 | 4 | 0 | null | 2013-12-30 11:00:36.95 UTC | 32 | 2021-06-01 06:17:27.253 UTC | 2014-07-24 15:14:43.063 UTC | null | 2,073,595 | null | 2,284,221 | null | 1 | 102 | python|multithreading|python-3.x|python-multithreading|concurrent.futures | 79,625 | <p>The problem is that you transform the result of <code>ThreadPoolExecutor.map</code> to a list. If you don't do this and instead iterate over the resulting generator directly, the results are still yielded in the original order but the loop continues before all results are ready. You can test this with this example:</p>
<pre class="lang-py prettyprint-override"><code>import time
import concurrent.futures
e = concurrent.futures.ThreadPoolExecutor(4)
s = range(10)
for i in e.map(time.sleep, s):
print(i)
</code></pre>
<p>The reason for the order being kept may be because it's sometimes important that you get results in the same order you give them to map. And results are probably not wrapped in future objects because in some situations it may take just too long to do another map over the list to get all results if you need them. And after all in most cases it's very likely that the next value is ready before the loop processed the first value. This is demonstrated in this example:</p>
<pre class="lang-py prettyprint-override"><code>import concurrent.futures
executor = concurrent.futures.ThreadPoolExecutor() # Or ProcessPoolExecutor
data = some_huge_list()
results = executor.map(crunch_number, data)
finals = []
for value in results:
finals.append(do_some_stuff(value))
</code></pre>
<p>In this example it may be likely that <code>do_some_stuff</code> takes longer than <code>crunch_number</code> and if this is really the case it's really not a big loss of performance while you still keep the easy usage of map.</p>
<p>Also since the worker threads(/processes) start processing at the beginning of the list and work their way to the end to the list you submitted the results should be finished in the order they're already yielded by the iterator. Which means in most cases <code>executor.map</code> is just fine, but in some cases, for example if it doesn't matter in which order you process the values and the function you passed to <code>map</code> takes very different times to run, the <code>future.as_completed</code> may be faster.</p> |
19,011,464 | How to have a fixed-size layout that also keeps the window from resizing? | <p>I have a container widget. </p>
<p>It's size policies are "Fixed" (both vertical and horizontal).
it has setMaxmimumWidth and setMaximumHeight defined.</p>
<p>I put an QHBoxLayout container there. adding widgets to it (with fixed width/height too).
But when i call "Show", none of this gets respected. The height is random almost, doesn't match any of the internal widgets in the layout, twice the size of the tallest item, <strong>and the width of my container is stretched far beyond the fixed width I set it.</strong></p>
<p>What am I missing? Why can't the container stay with fixed width/height as I defined it? why is the layout interfering with it and not respecting its constraints?</p> | 19,011,496 | 1 | 0 | null | 2013-09-25 17:30:03.173 UTC | 5 | 2014-07-31 12:46:32.313 UTC | 2013-09-25 17:53:33.743 UTC | null | 1,329,652 | null | 282,918 | null | 1 | 26 | qt | 57,921 | <p>The confusion comes from the fact that widgets that have fixed sizes do indeed have fixed sizes. The following holds: if a layout has only fixed-size widgets, then the layout's overall size is nominally fixed, and the widgets inside of it can't grow. If you set it as a layout on a window, it can constrain the window from growing if you set the <code>SetFixedSize</code> constraint on it. <em>It is useless to set any sort of size policies on a window with a layout that has only fixed size items</em> - unless you want to grow the <strong>spacing</strong> between the widgets.</p>
<p>If you want your widgets to stay fixed size, but the <strong>spacing between them to grow</strong>, the only change necessary to the code below is to set all widgets to fixed size policy. Since they can't grow, the spacing is the only thing that can. Literally set all policies in the example to <code>QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)</code> and you'll get this behavior.</p>
<p>If you want widgets of a certain minimum size and grow-able, and the overall container widget of a certain minimum size, then just set it so. This means:</p>
<ol>
<li><p>Set the minimum, maximum or fixed size or width/height on the container widget.</p></li>
<li><p>Set the minimum, maximum or fixed sizes or widths/heights on the widgets.</p></li>
<li><p>Set the size policies on the widgets to reflect the behavior you want. You may want, for example, some of the widgets to grow in certain directions only, or not at all.</p></li>
</ol>
<p>At least one widget will need to grow in a given direction if you set the minimum size on the container. Thus, if you set the width on the container, at least one laid out widget must be able to expand horizontally to fill it. If you set the height on the container, at least one laid out widget must be able to expand vertically to fill it.</p>
<p>The below works fine under Qt 4.8.5 and 5.1.1. The window can be expanded but not contracted - it has a minimum size. You can change the <code>setMinimumSize</code> to <code>setFixedSize</code> to obtain a window with fixed size, or you can set both minimum and maximum sizes.</p>
<p><img src="https://i.stack.imgur.com/TD6hU.png" alt="screenshot"></p>
<pre><code>#include <QApplication>
#include <QWidget>
#include <QHBoxLayout>
#include <QLabel>
#include <QFontDatabase>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget window;
QHBoxLayout layout(&window);
QLabel lbl1("one");
lbl1.setStyleSheet("QLabel { background-color: #FF8080 }");
lbl1.setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
QLabel lbl2("two");
lbl2.setStyleSheet("QLabel { background-color: #80FF80 }");
lbl2.setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
lbl2.setMinimumHeight(300);
QLabel lbl3("three");
lbl3.setStyleSheet("QLabel { background-color: #8080FF }");
lbl3.setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
lbl3.setMinimumWidth(300);
layout.addWidget(&lbl1);
layout.addWidget(&lbl2);
layout.addWidget(&lbl3);
window.setMinimumSize(800, 800);
// Any combination of setMinimumSize and setMaximumSize is OK.
// If the minimum and maximum are the same, just do setFixedSize
window.show();
return a.exec();
}
</code></pre> |
38,841,109 | CSRF validation does not work on Django using HTTPS | <p>I am developing an application which the frontend is an AngularJS API that makes requests to the backend API developed in Django Rest Framework.</p>
<pre><code>The frontend is on the domain: https://front.bluemix.net
And my backend is on the domain: https://back.bluemix.net
</code></pre>
<p>I am having problems making requests from the frontend API to the backend API. The error is this:</p>
<pre><code>Error: CSRF Failed: Referer checking failed - https://front.bluemix.net does not match any trusted origins.
</code></pre>
<p>I am using CORS and I have already included the following lines in my settings.py in the Django backend API:</p>
<pre><code>ALLOWED_HOSTS = []
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net/']
CORS_REPLACE_HTTPS_REFERER = True
CSRF_COOKIE_DOMAIN = 'bluemix.net'
CORS_ORIGIN_WHITELIST = (
'https://front.bluemix.net/',
'front.bluemix.net',
'bluemix.net',
)
</code></pre>
<p>Anyone knows how to solve this problem?</p> | 38,842,030 | 5 | 3 | null | 2016-08-09 02:26:11.36 UTC | 9 | 2022-06-09 05:35:24.27 UTC | 2022-04-27 20:56:37.543 UTC | null | 8,172,439 | null | 3,721,266 | null | 1 | 33 | python|django|django-rest-framework|ibm-cloud|django-csrf | 37,861 | <h4>Django 4.0 and above</h4>
<p>For Django 4.0 and above, <code>CSRF_TRUSTED_ORIGINS</code> must include <a href="https://docs.djangoproject.com/en/4.0/ref/settings/#csrf-trusted-origins" rel="noreferrer">scheme and host</a>, e.g.:</p>
<pre><code>CSRF_TRUSTED_ORIGINS = ['https://front.bluemix.net']
</code></pre>
<h4>Django 3.2 and lower</h4>
<p>For Django 3.2 and lower, <code>CSRF_TRUSTED_ORIGINS</code> must contain <a href="https://docs.djangoproject.com/en/3.2/ref/settings/#csrf-trusted-origins" rel="noreferrer">only the hostname</a>, without a scheme:</p>
<pre><code>CSRF_TRUSTED_ORIGINS = ['front.bluemix.net']
</code></pre>
<p>You probably also need to put something in <code>ALLOWED_HOSTS</code>...</p> |
34,637,896 | gitk will not start on Mac: unknown color name "lime" | <p>I've installed git on a mac via <code>brew install git</code>. When I try to start gitk I get the following error:</p>
<pre><code>Error in startup script: unknown color name "lime"
(processing "-fore" option)
invoked from within
"$ctext tag conf m2 -fore [lindex $mergecolors 2]"
(procedure "makewindow" line 347)
invoked from within
"makewindow"
(file "/usr/local/bin/gitk" line 12434)
</code></pre>
<p>It appears that my Mac doesn't have a color named <code>lime</code>. </p>
<p>Can I add a lime color to the environment, or is there a better fix? </p>
<p>The git version is 2.7.0, and the Mac is running Yosemite 10.10.5</p> | 34,886,815 | 10 | 0 | null | 2016-01-06 16:27:12.393 UTC | 27 | 2018-06-20 12:57:50.583 UTC | null | null | null | null | 1,014,251 | null | 1 | 127 | gitk | 22,149 | <p>You can check your version of Tcl/Tk by running <code>wish</code> and using the command <code>info patchlevel</code>. It appears that git 2.7.0, Tcl/Tk 8.5.9, and OS X 10.11 El Capitan do not work well together.</p>
<p>I solved this problem by doing <code>brew cask install tcl</code>, which installed 8.6.4, and <code>gitk</code> works now.</p> |
25,974,975 | Cython C-array initialization | <p>I would like to do</p>
<pre><code>cdef int mom2calc[3]
mom2calc[0] = 1
mom2calc[1] = 2
mom2calc[2] = 3
</code></pre>
<p>in a more compact way. Something similar to</p>
<pre><code>cdef int mom2calc[3] = [1, 2, 3]
</code></pre>
<p>which is an invalid Cython syntax.</p>
<p>Note:</p>
<pre><code>cdef int* mom2calc = [1, 2, 3]
</code></pre>
<p>is not an option because I cannot (automatically) converted it to a memory view.</p> | 25,988,004 | 2 | 0 | null | 2014-09-22 13:09:28.33 UTC | 3 | 2019-07-29 17:20:57.39 UTC | null | null | null | null | 794,329 | null | 1 | 28 | cython | 21,385 | <pre class="lang-python prettyprint-override"><code>cdef int mom2calc[3]
mom2calc[:] = [1, 2, 3]
</code></pre>
<p>This works on raw pointers (although it isn't bounds checked then), memory views and fixed-sized arrays. It only works in one dimension, but that's often enough:</p>
<pre class="lang-python prettyprint-override"><code>cdef int mom2calc[3][3]
mom2calc[0][:] = [1, 2, 3]
mom2calc[1][:] = [4, 5, 6]
mom2calc[2][:] = [7, 8, 9]
</code></pre> |
45,165,105 | How to vertically align comma separated values in Notepad++? | <p>As shown in the picture "<em>Before</em>" below, each column separated by comma is not aligned neatedly. Is there any method to align each column vertically like the display effect in Excel? </p>
<p>The effect I wish is shown in the picture "<em>After</em>".
<a href="https://i.stack.imgur.com/DAUFJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DAUFJ.png" alt="Before"></a>
<a href="https://i.stack.imgur.com/tIrUj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tIrUj.png" alt="After"></a></p>
<p>Thanks to @Martin S , I can align the file like the picture "<em>Method_1</em>". As he has mentioned, some characters still cannot align well. I was wondering if this method could be improved?
<a href="https://i.stack.imgur.com/phvqR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/phvqR.png" alt="Method_1"></a></p> | 47,073,476 | 4 | 0 | null | 2017-07-18 11:10:53.583 UTC | 1 | 2021-10-26 14:02:45.707 UTC | 2017-07-19 01:17:27.663 UTC | null | 6,648,436 | null | 6,648,436 | null | 1 | 31 | csv|notepad++ | 115,103 | <p>You can use the TextFX plugin:
Edit > Line Up multiple lines by ...</p>
<p>Note: This doesn't work if the file is read only.</p>
<p><a href="http://tomaslind.net/2016/02/18/how-to-align-columns-in-notepad/" rel="noreferrer">http://tomaslind.net/2016/02/18/how-to-align-columns-in-notepad/</a></p>
<p>Update 2019: <a href="https://sourceforge.net/projects/npp-plugins/files/TextFX/" rel="noreferrer">Download link from SourceForge</a></p> |
39,216,897 | Plot PCA loadings and loading in biplot in sklearn (like R's autoplot) | <p>I saw this tutorial in <code>R</code> w/ <code>autoplot</code>. They plotted the loadings and loading labels:</p>
<pre><code>autoplot(prcomp(df), data = iris, colour = 'Species',
loadings = TRUE, loadings.colour = 'blue',
loadings.label = TRUE, loadings.label.size = 3)
</code></pre>
<p><a href="https://i.stack.imgur.com/QRuAn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QRuAn.png" alt="enter image description here"></a>
<a href="https://cran.r-project.org/web/packages/ggfortify/vignettes/plot_pca.html" rel="noreferrer">https://cran.r-project.org/web/packages/ggfortify/vignettes/plot_pca.html</a></p>
<p>I prefer <code>Python 3</code> w/ <code>matplotlib, scikit-learn, and pandas</code> for my data analysis. However, I don't know how to add these on? </p>
<p><strong>How can you plot these vectors w/ <code>matplotlib</code>?</strong> </p>
<p>I've been reading <a href="https://stackoverflow.com/questions/22984335/recovering-features-names-of-explained-variance-ration-in-pca-with-sklearn">Recovering features names of explained_variance_ratio_ in PCA with sklearn</a> but haven't figured it out yet</p>
<p>Here's how I plot it in <code>Python</code></p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn import decomposition
import seaborn as sns; sns.set_style("whitegrid", {'axes.grid' : False})
%matplotlib inline
np.random.seed(0)
# Iris dataset
DF_data = pd.DataFrame(load_iris().data,
index = ["iris_%d" % i for i in range(load_iris().data.shape[0])],
columns = load_iris().feature_names)
Se_targets = pd.Series(load_iris().target,
index = ["iris_%d" % i for i in range(load_iris().data.shape[0])],
name = "Species")
# Scaling mean = 0, var = 1
DF_standard = pd.DataFrame(StandardScaler().fit_transform(DF_data),
index = DF_data.index,
columns = DF_data.columns)
# Sklearn for Principal Componenet Analysis
# Dims
m = DF_standard.shape[1]
K = 2
# PCA (How I tend to set it up)
Mod_PCA = decomposition.PCA(n_components=m)
DF_PCA = pd.DataFrame(Mod_PCA.fit_transform(DF_standard),
columns=["PC%d" % k for k in range(1,m + 1)]).iloc[:,:K]
# Color classes
color_list = [{0:"r",1:"g",2:"b"}[x] for x in Se_targets]
fig, ax = plt.subplots()
ax.scatter(x=DF_PCA["PC1"], y=DF_PCA["PC2"], color=color_list)
</code></pre>
<p><a href="https://i.stack.imgur.com/9dO1P.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9dO1P.png" alt="enter image description here"></a></p> | 62,477,182 | 3 | 0 | null | 2016-08-29 23:55:31.26 UTC | 19 | 2022-04-19 12:57:53.6 UTC | 2022-04-19 12:57:53.6 UTC | null | 5,025,009 | null | 678,572 | null | 1 | 21 | python|machine-learning|scikit-learn|pca|dimensionality-reduction | 43,183 | <p>Try the ‘pca’ library. This will plot the explained variance, and create a biplot.</p>
<pre><code>pip install pca
from pca import pca
# Initialize to reduce the data up to the number of componentes that explains 95% of the variance.
model = pca(n_components=0.95)
# Or reduce the data towards 2 PCs
model = pca(n_components=2)
# Fit transform
results = model.fit_transform(X)
# Plot explained variance
fig, ax = model.plot()
# Scatter first 2 PCs
fig, ax = model.scatter()
# Make biplot with the number of features
fig, ax = model.biplot(n_feat=4)
</code></pre> |
22,266,734 | Django excluding one queryset from another | <p>I have the following two models:</p>
<pre><code>class DeliveryTime(models.Model):
delivery_time = models.CharField(max_length=15)
class BlockedDeliveryTime(models.Model):
delivery_date = models.DateField()
delivery_time = models.ForeignKey(DeliveryTime)
</code></pre>
<p>I want to return all the available delivery times for a day i.e. all <code>DeliveryTime</code> excluding the <code>BlockedDeliveryTime</code>.</p>
<pre><code> blocked_delivery_times = BlockedDeliveryTime.objects.filter(delivery_date=delivery_date)
delivery_times = DeliveryTime.objects.all()
</code></pre>
<p>From <code>delivery_times</code> queryset I want to remove all <code>blocked_delivery_times.delivery_time</code></p>
<p>How can I do that? Any suggestions? </p> | 22,266,776 | 3 | 1 | null | 2014-03-08 08:00:42.497 UTC | 7 | 2018-08-13 10:55:14.357 UTC | 2018-08-13 10:55:14.357 UTC | null | 9,663,023 | null | 1,513,283 | null | 1 | 47 | django|django-queryset | 34,194 | <pre><code>blocked_delivery_times = BlockedDeliveryTime.objects.filter(delivery_date=delivery_date) \
.values('delivery_time')
delivery_times = DeliveryTime.objects.exclude(id__in=blocked_delivery_times)
</code></pre> |
23,809,392 | What does php's CURLOPT_USERPWD do | <p>I was wondering what <a href="http://www.php.net/manual/en/function.curl-setopt.php" rel="noreferrer">CURLOPT_USERPWD</a> is actually doing to the url, header or data of a request. Is it INSTEAD OF the <code>Authorization: Basic <base64 of user:pass></code> or does it work along side this?</p>
<p>Is it modifying the url to this?:</p>
<p><code>username:[email protected]</code></p>
<p>I saw some code like this so I am wondering, as it seems if I request that url in a NodeJS equivalent request it is not working with just an Authorization header (I have a theory the server is broken and ignoring the Auth header and using the username:password in the url):</p>
<pre><code> curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$encodedAuth = base64_encode(self::$pfAdapterUser.":".self::$pfAdapterPasswd);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authentication : Basic ".$encodedAuth));
curl_setopt($ch, CURLOPT_USERPWD, self::$pfAdapterUser.":".self::$pfAdapterPasswd);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
</code></pre>
<p>Thanks</p> | 26,285,941 | 1 | 1 | null | 2014-05-22 14:15:12.617 UTC | 1 | 2019-01-28 18:49:39.173 UTC | null | null | null | null | 414,062 | null | 1 | 30 | php|curl|basic-authentication | 46,688 | <blockquote>
<p>Is it modifying the url to this?:</p>
<p><code>username:[email protected]</code></p>
</blockquote>
<p>No, the url still the same. You can check with</p>
<pre><code>curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
</code></pre>
<p>This</p>
<pre><code>$encodedAuth = base64_encode(self::$pfAdapterUser.":".self::$pfAdapterPasswd);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Basic ".$encodedAuth));
</code></pre>
<p>And this</p>
<pre><code>curl_setopt($ch, CURLOPT_USERPWD, self::$pfAdapterUser.":".self::$pfAdapterPasswd);
</code></pre>
<p>are doing the same thing so there's no need to use them together (although it won't break), use one and it will work fine.</p> |
37,582,848 | What is the difference between BelongsTo And HasOne in Laravel | <p>Can any body tell me what is the main difference between<br>
the <strong>BelongsTo</strong> and <strong>HasOne</strong> relationship in <strong>eloquent</strong>.</p> | 37,583,651 | 5 | 1 | null | 2016-06-02 04:46:17 UTC | 19 | 2019-10-18 11:44:35.13 UTC | 2016-06-02 05:40:29.66 UTC | null | 1,594,915 | null | 6,096,965 | null | 1 | 62 | php|laravel|laravel-5|eloquent | 33,733 | <p>BelongsTo is a inverse of HasOne.</p>
<blockquote>
<p>We can define the inverse of a hasOne relationship using the belongsTo method.
Take simple example with <code>User</code> and <code>Phone</code> models.</p>
</blockquote>
<p>I'm giving hasOne relation from User to Phone.</p>
<pre><code>class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}
</code></pre>
<p>Using this relation, I'm able to get Phone model data using User model.</p>
<p>But it is not possible with Inverse process using <strong>HasOne</strong>. Like Access User model using Phone model. </p>
<p>If I want to access User model using Phone, then it is necessary to add <strong>BelongsTo</strong> in Phone model.</p>
<pre><code>class Phone extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo('App\User');
}
}
</code></pre>
<p>You can refer this <a href="https://laravel.com/docs/5.1/eloquent-relationships" rel="noreferrer">link</a> for more detail.</p> |
51,817,841 | Create database view from django model | <p>I learned sql "view" as a virtual table to facilitate the SQL operations, like</p>
<pre><code>MySQL [distributor]> CREATE VIEW CustomerEMailList AS
-> SELECT cust_id, cust_name, cust_email
-> FROM Customers
-> WHERE cust_email IS NOT NULL;
Query OK, 0 rows affected (0.026 sec)
MySQL [distributor]> select * from customeremaillist;
+------------+---------------+-----------------------+
| cust_id | cust_name | cust_email |
+------------+---------------+-----------------------+
| 1000000001 | Village Toys | [email protected] |
| 1000000003 | Fun4All | [email protected] |
| 1000000004 | Fun4All | [email protected] |
| 1000000005 | The Toy Store | [email protected] |
| 1000000006 | toy land | [email protected] |
+------------+---------------+-----------------------+
5 rows in set (0.014 sec)
</code></pre>
<p>When I checked the Django documentation subsequently, there are no such functionality to create a virtual "model table" which could simplify the data manipulation.</p>
<p>Should I forget the virtual table "view" when using Django ORM?</p> | 51,818,386 | 3 | 1 | null | 2018-08-13 08:09:31.587 UTC | 13 | 2021-05-19 21:23:35.847 UTC | null | null | null | null | 7,301,792 | null | 1 | 21 | django | 22,644 | <p>Django has - as far as I know at the moment - no builtin support for views.</p>
<p>But you <em>can</em> construct such views, by using the <a href="https://pypi.org/project/django-database-view/" rel="noreferrer"><strong><code>django-database-view</code></strong></a> package.</p>
<p>After installing the package (for example with pip):</p>
<pre><code> pip install django-database-view
</code></pre>
<p>Furthermore the <code>dbview</code> app has to be registered in the <code>settings.py</code> file:</p>
<pre><code># settings.py
INSTALLED_APPS = (
# ...
'dbview',
# ...
)
</code></pre>
<p>Now you can construct a view, this looks a bit <em>similar</em> to the construction of a model, except that you need to implement a <code>view(..)</code> function that specifies the query behind the view. Something similar to:</p>
<pre><code>from django.db import models
from dbview.models import DbView
class CustomerEMailList(DbView):
cust = models.OneToOneField(Customer, primary_key=True)
cust_name = models.CharField()
cust_email = models.CharField()
@classmethod
def view(klass):
qs = (Customers.objects.filter(cust_email__isnull=False)
.values('cust_id', 'cust_name', 'cust_email'))
return str(qs.query)
</code></pre>
<p>Now we can make a migrations:</p>
<pre><code>./manage.py makemigrations
</code></pre>
<p>Now in the migration, we need to <strong>make a change</strong>: the calls to <strong><code>migrations.CreateModel</code></strong> that are related to the constructed view(s), should be changed to the <strong><code>CreateView</code></strong> of the <code>dbview</code> module. Something that looks like:</p>
<pre><code>from django.db import migrations
from dbview import CreateView
class Migration(migrations.Migration):
dependencies = []
operations = [
CreateView(
name='CustomerEMailList',
fields=[
# ...
],
),
]
</code></pre> |
51,609,922 | How to drill down charts with ChartJS? | <p>I was very surprised that I found almost no information about this topic.</p>
<p>I have a ChartJS pie chart that I want to drill down into after clicking a slice of the pie.</p>
<p>How would you do that?</p>
<p>Thank you</p> | 51,643,857 | 1 | 3 | null | 2018-07-31 09:24:51.347 UTC | 8 | 2021-11-30 16:58:19.463 UTC | 2021-08-20 10:45:37.983 UTC | null | 9,778,828 | null | 9,778,828 | null | 1 | 13 | javascript|jquery|chart.js|pie-chart|drilldown | 17,185 | <p>I've solved my problem using this awesome answer:</p>
<p><a href="https://stackoverflow.com/questions/26257268/click-events-on-pie-charts-in-chart-js">Click events on Pie Charts in Chart.js</a></p>
<p>The code:</p>
<pre><code> $(document).ready(function() {
var canvas = document.getElementById("myChart");
var ctx = canvas.getContext("2d");
var myNewChart = new Chart(ctx, {
type: 'pie',
data: data
});
canvas.onclick = function(evt) {
var activePoints = myNewChart.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
var value = chartData.datasets[0].data[idx];
var color = chartData.datasets[0].backgroundColor[idx]; //Or any other data you wish to take from the clicked slice
alert(label + ' ' + value + ' ' + color); //Or any other function you want to execute. I sent the data to the server, and used the response i got from the server to create a new chart in a Bootstrap modal.
}
};
});
</code></pre>
<p>That works perfectly. Just instead of alerting the information, i send it to the server using AJAX, and displaying a new chart in a bootstrap modal.</p> |
29,531,786 | Making a request parameter binding case insensitive | <p>I have a requirement where I have to make requestParams to bind properly even if the cases of the param name changes. Note:I am using spring 3.2</p>
<p>For eg: <code>http://localhost:8080/sample/home?*</code>*userName**=xxx or <code>http://localhost:8080/sample/home?</code><strong>username</strong>=xxx or
<code>http://localhost:8080/sample/home?</code><strong>usernaMe</strong>=xxx should map properly to my
@RequestParam value.</p>
<pre><code>@RequestMapping(value = "home", method = RequestMethod.GET)
public goToHome(@RequestParam(value = "userName", required = false) String userName) {
}
</code></pre>
<p>All the three urls should call the above method and bind the user name properly.
Please give me suggestions on how to implement this by implementing new argument handler resolver? Overriding spring config classes to implement generically is preferred over changing the logic in the code for all @RequestParam.</p> | 29,533,456 | 3 | 1 | null | 2015-04-09 06:56:41.367 UTC | 9 | 2019-04-03 17:44:25.46 UTC | 2015-04-09 10:39:57.137 UTC | null | 1,391,249 | null | 2,425,282 | null | 1 | 12 | java|spring|spring-mvc | 14,428 | <p>Spring has a <a href="http://docs.spring.io/spring-framework/docs/4.1.6.RELEASE/javadoc-api/org/springframework/util/LinkedCaseInsensitiveMap.html" rel="noreferrer"><code>LinkedCaseInsensitiveMap</code></a> Which you could use to do case insensitive lookups. </p>
<p>An implementation could look like the following.</p>
<pre><code>package biz.deinum.web.filter;
import org.springframework.util.LinkedCaseInsensitiveMap;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
/**
* Wrapper for an {@link HttpServletRequest} to make the lookup of parameters case insensitive. The functionality
* is achieved by using the {@link LinkedCaseInsensitiveMap} from Spring.
*
* @author Marten Deinum
*/
public class CaseInsensitiveRequestFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
filterChain.doFilter(new CaseInsensitiveHttpServletRequestWrapper(request), response);
}
private static class CaseInsensitiveHttpServletRequestWrapper extends HttpServletRequestWrapper {
private final LinkedCaseInsensitiveMap<String[]> params = new LinkedCaseInsensitiveMap<>();
/**
* Constructs a request object wrapping the given request.
*
* @param request
* @throws IllegalArgumentException if the request is null
*/
private CaseInsensitiveHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
params.putAll(request.getParameterMap());
}
@Override
public String getParameter(String name) {
String[] values = getParameterValues(name);
if (values == null || values.length == 0) {
return null;
}
return values[0];
}
@Override
public Map<String, String[]> getParameterMap() {
return Collections.unmodifiableMap(this.params);
}
@Override
public Enumeration<String> getParameterNames() {
return Collections.enumeration(this.params.keySet());
}
@Override
public String[] getParameterValues(String name) {
return (String[])params.get(name);
}
}
}
</code></pre> |
4,710,102 | Stop PostgreSQL log files from filling up disk | <p>I'm running PostgreSQL 8.4 on an Ubuntu server. I realized that my disk is out of space because the log file had became too large. Can I adjust what gets written to the log file?</p> | 4,710,988 | 1 | 2 | null | 2011-01-17 04:48:31.25 UTC | 1 | 2017-07-07 12:09:40.837 UTC | 2017-07-07 12:09:40.837 UTC | null | 1,709,587 | null | 357,236 | null | 1 | 6 | postgresql | 38,668 | <p>Edit <code>/etc/postgresql/8.4/main/postgresql.conf</code> and change or disable the various <code>log_*</code> parameters. Then reload postgresql.</p>
<p>You might also want to check what gets written to the logs. By default, there should not be that much logging. Possibly, your application is throwing lots of errors, which is what's filling up your hard disks.</p> |
4,279,876 | plpgsql function returns table(..) | <p>I'm trying to get this plpgsql function to work:</p>
<pre><code>CREATE OR REPLACE FUNCTION outofdate(actualdate varchar)
RETURNS TABLE(designacion varchar(255),timebeingrotten varchar(255))
AS $BODY$
SELECT designacao, actualdate - prazo
FROM alimento
WHERE prazo < actualdate;
$BODY$
LANGUAGE 'plpgsql' volatile;
SELECT *
From outofdate('12/12/2012');
</code></pre>
<p>It keeps giving me an error on line 2 - table ..</p>
<blockquote>
<p>ERROR: syntax error at or near
"TABLE" LINE 2: RETURNS
TABLE(designacion
varchar(255),timebeingrotten varch...
^</p>
<p><em><strong></em>***<em></strong> Error <strong></em>**<em>*</em></strong></p>
<p>ERROR: syntax error at or near "TABLE"
SQL state: 42601 Character: 67</p>
</blockquote> | 4,290,462 | 1 | 0 | null | 2010-11-25 18:18:55.073 UTC | 7 | 2011-12-24 19:27:39.307 UTC | 2011-12-24 19:22:20.87 UTC | null | 939,860 | null | 520,516 | null | 1 | 15 | postgresql|plpgsql | 41,260 | <p>I am not sure, but maybe you use a older version of pg without support of <code>RETURNS TABLE</code> syntax. Next problem in your example is wrong syntax for PL/pgSQL language - look to manual for syntax - every function must contain a block with <code>BEGIN ... END</code>. Records can be returned via <code>RETURN QUERY</code> statement. Have a look at this <a href="http://www.pgsql.cz/index.php/PL/pgSQL_%28en%29" rel="noreferrer">tutorial</a>.</p>
<pre><code>CREATE OR REPLACE FUNCTION foo(a int)
RETURNS TABLE(b int, c int) AS $$
BEGIN
RETURN QUERY SELECT i, i+1 FROM generate_series(1, a) g(i);
END;
$$ LANGUAGE plpgsql;
</code></pre>
<p>Call:</p>
<pre><code>SELECT * FROM foo(10);
</code></pre> |
20,083,098 | Improve pandas (PyTables?) HDF5 table write performance | <p>I've been using pandas for research now for about two months to great effect. With large numbers of medium-sized trace event datasets, pandas + PyTables (the HDF5 interface) does a tremendous job of allowing me to process heterogenous data using all the Python tools I know and love.</p>
<p>Generally speaking, I use the Fixed (formerly "Storer") format in PyTables, as my workflow is write-once, read-many, and many of my datasets are sized such that I can load 50-100 of them into memory at a time with no serious disadvantages. (NB: I do much of my work on Opteron server-class machines with 128GB+ system memory.)</p>
<p>However, for large datasets (500MB and greater), I would like to be able to use the more scalable random-access and query abilities of the PyTables "Tables" format, so that I can perform my queries out-of-memory and then load the much smaller result set into memory for processing. The big hurdle here, however, is the write performance. Yes, as I said, my workflow is write-once, read-many, but the relative times are still unacceptable. </p>
<p>As an example, I recently ran a large Cholesky factorization that took 3 minutes, 8 seconds (188 seconds) on my 48 core machine. This generated a trace file of ~2.2 GB - the trace is generated in parallel with the program, so there is no additional "trace creation time."</p>
<p>The initial conversion of my binary trace file into the pandas/PyTables format takes a decent chunk of time, but largely because the binary format is deliberately out-of-order in order to reduce the performance impact of the trace generator itself. This is also irrelevant to the performance loss when moving from the Storer format to the Table format.</p>
<p>My tests were initially run with pandas 0.12, numpy 1.7.1, PyTables 2.4.0, and numexpr 0.20.1. My 48 core machine runs at 2.8GHz per core, and I am writing to an ext3 filesystem which is probably (but not certainly) on a SSD.</p>
<p>I can write the entire dataset to a Storer format HDF5 file (resulting filesize: 3.3GB) in 7.1 seconds. The same dataset, written to the Table format (resulting file size is also 3.3GB), takes 178.7 seconds to write. </p>
<p>The code is as follows:</p>
<pre><code>with Timer() as t:
store = pd.HDFStore('test_storer.h5', 'w')
store.put('events', events_dataset, table=False, append=False)
print('Fixed format write took ' + str(t.interval))
with Timer() as t:
store = pd.HDFStore('test_table.h5', 'w')
store.put('events', events_dataset, table=True, append=False)
print('Table format write took ' + str(t.interval))
</code></pre>
<p>and the output is simply</p>
<pre><code>Fixed format write took 7.1
Table format write took 178.7
</code></pre>
<p>My dataset has 28,880,943 rows, and the columns are basic datatypes:</p>
<pre><code>node_id int64
thread_id int64
handle_id int64
type int64
begin int64
end int64
duration int64
flags int64
unique_id int64
id int64
DSTL_LS_FULL float64
L2_DMISS float64
L3_MISS float64
kernel_type float64
dtype: object
</code></pre>
<p>...so I don't think there should be any data-specific issues with the write speed. </p>
<p>I've also tried adding BLOSC compression, to rule out any strange I/O issues that might affect one scenario or the other, but compression seems to decrease the performance of both equally.</p>
<p>Now, I realize that the pandas documentation says that the Storer format offers significantly faster writes, and slightly faster reads. (I do experience the faster reads, as a read of the Storer format seems to take around 2.5 seconds, while a read of the Table format takes around 10 seconds.) But it really seems excessive that the Table format write should take 25 times as long as the Storer format write.</p>
<p>Can any of the folks involved with PyTables or pandas explain the architectural (or otherwise) reasons why writing to the queryable format (which clearly requires very little extra data) should take an order of magnitude longer? And is there any hope for improving this in the future? I'd love to jump in to contributing to one project or the other, as my field is high performance computing and I see a significant use case for both projects in this domain.... but it would be helpful to get some clarification on the issues involved first, and/or some advice on how to speed things up from those who know how the system is built.</p>
<p>EDIT:</p>
<p>Running the former tests with %prun in IPython gives the following (somewhat reduced for readability) profile output for the Storer/Fixed format:</p>
<pre><code>%prun -l 20 profile.events.to_hdf('test.h5', 'events', table=False, append=False)
3223 function calls (3222 primitive calls) in 7.385 seconds
Ordered by: internal time
List reduced from 208 to 20 due to restriction <20>
ncalls tottime percall cumtime percall filename:lineno(function)
6 7.127 1.188 7.128 1.188 {method '_createArray' of 'tables.hdf5Extension.Array' objects}
1 0.242 0.242 0.242 0.242 {method '_closeFile' of 'tables.hdf5Extension.File' objects}
1 0.003 0.003 0.003 0.003 {method '_g_new' of 'tables.hdf5Extension.File' objects}
46 0.001 0.000 0.001 0.000 {method 'reduce' of 'numpy.ufunc' objects}
</code></pre>
<p>and the following for the Tables format:</p>
<pre><code> %prun -l 40 profile.events.to_hdf('test.h5', 'events', table=True, append=False, chunksize=1000000)
499082 function calls (499040 primitive calls) in 188.981 seconds
Ordered by: internal time
List reduced from 526 to 40 due to restriction <40>
ncalls tottime percall cumtime percall filename:lineno(function)
29 92.018 3.173 92.018 3.173 {pandas.lib.create_hdf_rows_2d}
640 20.987 0.033 20.987 0.033 {method '_append' of 'tables.hdf5Extension.Array' objects}
29 19.256 0.664 19.256 0.664 {method '_append_records' of 'tables.tableExtension.Table' objects}
406 19.182 0.047 19.182 0.047 {method '_g_writeSlice' of 'tables.hdf5Extension.Array' objects}
14244 10.646 0.001 10.646 0.001 {method '_g_readSlice' of 'tables.hdf5Extension.Array' objects}
472 10.359 0.022 10.359 0.022 {method 'copy' of 'numpy.ndarray' objects}
80 3.409 0.043 3.409 0.043 {tables.indexesExtension.keysort}
2 3.023 1.512 3.023 1.512 common.py:134(_isnull_ndarraylike)
41 2.489 0.061 2.533 0.062 {method '_fillCol' of 'tables.tableExtension.Row' objects}
87 2.401 0.028 2.401 0.028 {method 'astype' of 'numpy.ndarray' objects}
30 1.880 0.063 1.880 0.063 {method '_g_flush' of 'tables.hdf5Extension.Leaf' objects}
282 0.824 0.003 0.824 0.003 {method 'reduce' of 'numpy.ufunc' objects}
41 0.537 0.013 0.668 0.016 index.py:607(final_idx32)
14490 0.385 0.000 0.712 0.000 array.py:342(_interpret_indexing)
39 0.279 0.007 19.635 0.503 index.py:1219(reorder_slice)
2 0.256 0.128 10.063 5.031 index.py:1099(get_neworder)
1 0.090 0.090 119.392 119.392 pytables.py:3016(write_data)
57842 0.087 0.000 0.087 0.000 {numpy.core.multiarray.empty}
28570 0.062 0.000 0.107 0.000 utils.py:42(is_idx)
14164 0.062 0.000 7.181 0.001 array.py:711(_readSlice)
</code></pre>
<p>EDIT 2:</p>
<p>Running again with a pre-release copy of pandas 0.13 (pulled Nov 20 2013 at about 11:00 EST), write times for the Tables format improve significantly but still don't compare "reasonably" to the write speeds of the Storer/Fixed format.</p>
<pre><code>%prun -l 40 profile.events.to_hdf('test.h5', 'events', table=True, append=False, chunksize=1000000)
499748 function calls (499720 primitive calls) in 117.187 seconds
Ordered by: internal time
List reduced from 539 to 20 due to restriction <20>
ncalls tottime percall cumtime percall filename:lineno(function)
640 22.010 0.034 22.010 0.034 {method '_append' of 'tables.hdf5Extension.Array' objects}
29 20.782 0.717 20.782 0.717 {method '_append_records' of 'tables.tableExtension.Table' objects}
406 19.248 0.047 19.248 0.047 {method '_g_writeSlice' of 'tables.hdf5Extension.Array' objects}
14244 10.685 0.001 10.685 0.001 {method '_g_readSlice' of 'tables.hdf5Extension.Array' objects}
472 10.439 0.022 10.439 0.022 {method 'copy' of 'numpy.ndarray' objects}
30 7.356 0.245 7.356 0.245 {method '_g_flush' of 'tables.hdf5Extension.Leaf' objects}
29 7.161 0.247 37.609 1.297 pytables.py:3498(write_data_chunk)
2 3.888 1.944 3.888 1.944 common.py:197(_isnull_ndarraylike)
80 3.581 0.045 3.581 0.045 {tables.indexesExtension.keysort}
41 3.248 0.079 3.294 0.080 {method '_fillCol' of 'tables.tableExtension.Row' objects}
34 2.744 0.081 2.744 0.081 {method 'ravel' of 'numpy.ndarray' objects}
115 2.591 0.023 2.591 0.023 {method 'astype' of 'numpy.ndarray' objects}
270 0.875 0.003 0.875 0.003 {method 'reduce' of 'numpy.ufunc' objects}
41 0.560 0.014 0.732 0.018 index.py:607(final_idx32)
14490 0.387 0.000 0.712 0.000 array.py:342(_interpret_indexing)
39 0.303 0.008 19.617 0.503 index.py:1219(reorder_slice)
2 0.288 0.144 10.299 5.149 index.py:1099(get_neworder)
57871 0.087 0.000 0.087 0.000 {numpy.core.multiarray.empty}
1 0.084 0.084 45.266 45.266 pytables.py:3424(write_data)
1 0.080 0.080 55.542 55.542 pytables.py:3385(write)
</code></pre>
<p>I noticed while running these tests that there are long periods where writing seems to "pause" (the file on disk is not actively growing), and yet there is also low CPU usage during some of these periods.</p>
<p>I begin to suspect that some known ext3 limitations may interact badly with either pandas or PyTables. Ext3 and other non-extent-based filesystems sometimes struggle to unlink large files promptly, and similar system performance (low CPU usage, but long wait times) is apparent even during a simple 'rm' of a 1GB file, for instance. </p>
<p>To clarify, in each test case, I made sure to remove the existing file, if any, before starting the test, so as not to incur any ext3 file removal/overwrite penalty.</p>
<p>However, when re-running this test with index=None, performance improves drastically (~50s vs the ~120 when indexing). So it would seem that either this process continues to be CPU-bound (my system has relatively old AMD Opteron Istanbul CPUs running @ 2.8GHz, though it does also have 8 sockets with 6 core CPUs in each, all but one of which, of course, sit idle during the write), or that there is some conflict between the way PyTables or pandas attempts to manipulate/read/analyze the file when already partially or fully on the filesystem that causes pathologically bad I/O behavior when the indexing is occurring.</p>
<p>EDIT 3:</p>
<p>@Jeff's suggested tests on a smaller dataset (1.3 GB on disk), after upgrading PyTables from 2.4 to 3.0.0, have gotten me here:</p>
<pre><code>In [7]: %timeit f(df)
1 loops, best of 3: 3.7 s per loop
In [8]: %timeit f2(df) # where chunksize= 2 000 000
1 loops, best of 3: 13.8 s per loop
In [9]: %timeit f3(df) # where chunksize= 2 000 000
1 loops, best of 3: 43.4 s per loop
</code></pre>
<p>In fact, my performance seems to beat his in all scenarios except for when indexing is turned on (the default). However, indexing still seems to be a killer, and if the way I'm interpreting the output from <code>top</code> and <code>ls</code> as I run these tests is correct, there remain periods of time when there is neither significant processing nor any file writing happening (i.e., CPU usage for the Python process is near 0, and the filesize remains constant). I can only assume these are file reads. Why file reads would be causing slowdowns is hard for me to understand, as I can reliably load an entire 3+ GB file from this disk into memory in under 3 seconds. If they're not file reads, then what is the system 'waiting' on? (No one else is logged into the machine, and there is no other filesystem activity.)</p>
<p>At this point, with upgraded versions of the relevant python modules, the performance for my original dataset is down to the following figures. Of special interest are the system time, which I assume is at least an upper-bound on the time spent performing IO, and the Wall time, which seems to perhaps account for these mysterious periods of no write/no CPU activity.</p>
<pre><code>In [28]: %time f(profile.events)
CPU times: user 0 ns, sys: 7.16 s, total: 7.16 s
Wall time: 7.51 s
In [29]: %time f2(profile.events)
CPU times: user 18.7 s, sys: 14 s, total: 32.7 s
Wall time: 47.2 s
In [31]: %time f3(profile.events)
CPU times: user 1min 18s, sys: 14.4 s, total: 1min 32s
Wall time: 2min 5s
</code></pre>
<p>Nevertheless, it would appears that indexing causes significant slowdown for my use case. Perhaps I should attempt limiting the fields indexed instead of simply performing the default case (which may very well be indexing on all of the fields in the DataFrame)? I am not sure how this is likely to affect query times, especially in the cases where a query selects based on a non-indexed field.</p>
<p>Per Jeff's request, a ptdump of the resulting file.</p>
<pre><code>ptdump -av test.h5
/ (RootGroup) ''
/._v_attrs (AttributeSet), 4 attributes:
[CLASS := 'GROUP',
PYTABLES_FORMAT_VERSION := '2.1',
TITLE := '',
VERSION := '1.0']
/df (Group) ''
/df._v_attrs (AttributeSet), 14 attributes:
[CLASS := 'GROUP',
TITLE := '',
VERSION := '1.0',
data_columns := [],
encoding := None,
index_cols := [(0, 'index')],
info := {1: {'type': 'Index', 'names': [None]}, 'index': {}},
levels := 1,
nan_rep := 'nan',
non_index_axes :=
[(1, ['node_id', 'thread_id', 'handle_id', 'type', 'begin', 'end', 'duration', 'flags', 'unique_id', 'id', 'DSTL_LS_FULL', 'L2_DMISS', 'L3_MISS', 'kernel_type'])],
pandas_type := 'frame_table',
pandas_version := '0.10.1',
table_type := 'appendable_frame',
values_cols := ['values_block_0', 'values_block_1']]
/df/table (Table(28880943,)) ''
description := {
"index": Int64Col(shape=(), dflt=0, pos=0),
"values_block_0": Int64Col(shape=(10,), dflt=0, pos=1),
"values_block_1": Float64Col(shape=(4,), dflt=0.0, pos=2)}
byteorder := 'little'
chunkshape := (4369,)
autoindex := True
colindexes := {
"index": Index(6, medium, shuffle, zlib(1)).is_csi=False}
/df/table._v_attrs (AttributeSet), 15 attributes:
[CLASS := 'TABLE',
FIELD_0_FILL := 0,
FIELD_0_NAME := 'index',
FIELD_1_FILL := 0,
FIELD_1_NAME := 'values_block_0',
FIELD_2_FILL := 0.0,
FIELD_2_NAME := 'values_block_1',
NROWS := 28880943,
TITLE := '',
VERSION := '2.7',
index_kind := 'integer',
values_block_0_dtype := 'int64',
values_block_0_kind := ['node_id', 'thread_id', 'handle_id', 'type', 'begin', 'end', 'duration', 'flags', 'unique_id', 'id'],
values_block_1_dtype := 'float64',
values_block_1_kind := ['DSTL_LS_FULL', 'L2_DMISS', 'L3_MISS', 'kernel_type']]
</code></pre>
<p>and another %prun with the updated modules and the full dataset:</p>
<pre><code>%prun -l 25 %time f3(profile.events)
CPU times: user 1min 14s, sys: 16.2 s, total: 1min 30s
Wall time: 1min 48s
542678 function calls (542650 primitive calls) in 108.678 seconds
Ordered by: internal time
List reduced from 629 to 25 due to restriction <25>
ncalls tottime percall cumtime percall filename:lineno(function)
640 23.633 0.037 23.633 0.037 {method '_append' of 'tables.hdf5extension.Array' objects}
15 20.852 1.390 20.852 1.390 {method '_append_records' of 'tables.tableextension.Table' objects}
406 19.584 0.048 19.584 0.048 {method '_g_write_slice' of 'tables.hdf5extension.Array' objects}
14244 10.591 0.001 10.591 0.001 {method '_g_read_slice' of 'tables.hdf5extension.Array' objects}
458 9.693 0.021 9.693 0.021 {method 'copy' of 'numpy.ndarray' objects}
15 6.350 0.423 30.989 2.066 pytables.py:3498(write_data_chunk)
80 3.496 0.044 3.496 0.044 {tables.indexesextension.keysort}
41 3.335 0.081 3.376 0.082 {method '_fill_col' of 'tables.tableextension.Row' objects}
20 2.551 0.128 2.551 0.128 {method 'ravel' of 'numpy.ndarray' objects}
101 2.449 0.024 2.449 0.024 {method 'astype' of 'numpy.ndarray' objects}
16 1.789 0.112 1.789 0.112 {method '_g_flush' of 'tables.hdf5extension.Leaf' objects}
2 1.728 0.864 1.728 0.864 common.py:197(_isnull_ndarraylike)
41 0.586 0.014 0.842 0.021 index.py:637(final_idx32)
14490 0.292 0.000 0.616 0.000 array.py:368(_interpret_indexing)
2 0.283 0.142 10.267 5.134 index.py:1158(get_neworder)
274 0.251 0.001 0.251 0.001 {method 'reduce' of 'numpy.ufunc' objects}
39 0.174 0.004 19.373 0.497 index.py:1280(reorder_slice)
57857 0.085 0.000 0.085 0.000 {numpy.core.multiarray.empty}
1 0.083 0.083 35.657 35.657 pytables.py:3424(write_data)
1 0.065 0.065 45.338 45.338 pytables.py:3385(write)
14164 0.065 0.000 7.831 0.001 array.py:615(__getitem__)
28570 0.062 0.000 0.108 0.000 utils.py:47(is_idx)
47 0.055 0.001 0.055 0.001 {numpy.core.multiarray.arange}
28570 0.050 0.000 0.090 0.000 leaf.py:397(_process_range)
87797 0.048 0.000 0.048 0.000 {isinstance}
</code></pre> | 20,543,819 | 2 | 1 | null | 2013-11-19 22:08:16.547 UTC | 21 | 2013-12-12 12:38:25.39 UTC | 2013-11-20 21:28:11.97 UTC | null | 1,807,456 | null | 1,807,456 | null | 1 | 34 | python|performance|pandas|hdf5|pytables | 16,333 | <p>That's an interesting discussion. I think Peter is getting awesome performance for the Fixed format because the format writes in a single shot and also that he has a really good SSD (it can write at more than 450 MB/s).</p>
<p>Appending to table is a more complex operation (the dataset has to be enlarged, and new records must be checked so that we can ensure that they follow the schema of the table). This is why appending rows in tables is generally slower (but still, Jeff is getting ~ 70 MB/s, which is pretty good). That Jeff is getting more speed than Peter is probably due to the fact that he has a better processor.</p>
<p>Finally, indexing in PyTables uses a single processor, yes, and that normally is an expensive operation, so you should really disable it if you are not going to query data on-disk.</p> |
7,238,929 | Stream.Seek(0, SeekOrigin.Begin) or Position = 0 | <p>When you need to reset a stream to beginning (e.g. <code>MemoryStream</code>) is it best practice to use</p>
<pre><code>stream.Seek(0, SeekOrigin.Begin);
</code></pre>
<p>or </p>
<pre><code>stream.Position = 0;
</code></pre>
<p>I've seen both work fine, but wondered if one was more correct than the other?</p> | 7,239,011 | 3 | 3 | null | 2011-08-30 05:07:52.43 UTC | 25 | 2022-03-24 01:44:08.563 UTC | 2012-11-03 00:12:04.71 UTC | null | 41,956 | null | 384,443 | null | 1 | 213 | c#|.net|stream | 81,381 | <p>Use <code>Position</code> when setting an absolute position and <code>Seek</code> when setting a relative position. Both are provided for convenience so you can choose one that fits the style and readability of your code. Accessing <code>Position</code> requires the stream be seekable so they're safely interchangeable.</p> |
7,117,873 | Do 'if' statements in JavaScript require curly braces? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/4797286/are-curly-braces-necessary-in-one-line-statements-in-javascript">Are curly braces necessary in one line statements in JavaScript?</a> </p>
</blockquote>
<p>I am almost positive of this, but I want to make sure to avoid faulty code. In JavaScript do single <code>if</code> statements need curly braces?</p>
<pre><code>if(foo)
bar;
</code></pre>
<p>Is this OK?</p> | 7,117,939 | 4 | 0 | null | 2011-08-19 06:43:35.36 UTC | 8 | 2014-05-31 18:40:10.887 UTC | 2017-05-23 12:34:18.457 UTC | null | -1 | null | 654,928 | null | 1 | 41 | javascript|if-statement | 30,211 | <p>Yes, it works, but only up to a single line just after an 'if' or 'else' statement. If multiple lines are required to be used then curly braces are necessary.</p>
<p><strong>The following will work</strong></p>
<pre><code>if(foo)
Dance with me;
else
Sing with me;
</code></pre>
<p><strong>The following will NOT work the way you want it to work.</strong></p>
<pre><code>if(foo)
Dance with me;
Sing with me;
else
Sing with me;
You don't know anything;
</code></pre>
<p><strong>But if the above is corrected as in the below given way, then it works for you:</strong></p>
<pre><code>if(foo){
Dance with me;
Sing with me;
}else{
Sing with me;
You don't know anything;
}
</code></pre> |
21,725,768 | Chef libraries or definitions? | <p>Being relatively new to Chef, I am required to create libraries or definitions from existing recipes.</p>
<p>There recipes use bash resource, ruby block resource (which notifies another ruby block resource with delayed timing), template resource again which notifies a ruby block etc.</p>
<p><strong>What would be the best approach to this? Library or definition?</strong> </p>
<p>I have read that if I use definition, I won't be able to notify a resource within the definition, does that mean I can notify a resource in a different definition file? </p>
<p>I also read that in libraries you cant use the resources directly. If this is true, how can I use a resource within my library?</p> | 21,733,093 | 2 | 2 | null | 2014-02-12 10:51:21.187 UTC | 18 | 2020-08-21 01:13:47.8 UTC | 2017-02-04 20:50:42.55 UTC | null | 6,862,601 | null | 2,786,512 | null | 1 | 19 | ruby|chef-infra | 7,504 | <p>So, this is "primarily opinion based", but I'll answer it anyway. There are 4 distinct choices here:</p>
<ol>
<li>Definition</li>
<li>LWRP</li>
<li>HWRP</li>
<li>"Library"</li>
</ol>
<p>A definition is just a wrapper around one or more resources with some parameterization. However, definitions are <em>not</em> added to the resource collection. Meaning you can't "notify" or trigger events on a definition. They are solely for wrapping and naming a series of repeatable steps found in a recipe.</p>
<p>An LWRP (Light-weight resource and provider) is a Chef-specific DSL that actually compiles into an HWRP (Heavy-weight resource and provider) at runtime. Both LWRPs and HWRPs are Chef <em>extensions</em>. In addition to wrapping a series of repeatable tasks, *WRPs will create a top-level resource in Chef (like <code>template</code> or <code>package</code>) that's available for use in your recipe and other cookbook's recipes as well.</p>
<p>The difference between and LWRP and HWRP is really the Ruby. HWRPs use full-blown Ruby classes. If you aren't a Ruby developer, they may be a bit intimidating. Nonetheless, you should give it a try before writing and LWRP. LWRPs use a Chef-specific DSL for creating resources. At the end of the day, they compile to (roughly) the same code as the Heavy-weight counterpart. I'll link some references at the end. You have access to Chef resources inside either implementation, as well as the run_context.</p>
<p>Finally, "libraries" (notice the quotes) are often misunderstood and abused. They are Ruby code, evaluated as Ruby, so they can do pretty much anything. HWRPs are actually a form of a library. Sometimes people use libraries as "helpers". They will create a helper module with methods like <code>best_ip_for</code> or <code>aggregate_some_data</code> and then "mix" (Rubyism) that library into their recipes or resources to DRY things up. Other times, libraries can be use to "hack" Chef itself. The <a href="https://github.com/opscode-cookbooks/partial_search/blob/f91a489dc98f815ec317c36304a4045c8f075c78/libraries/partial_search.rb" rel="noreferrer">partial-search</a> cookbook is a good example of this. <a href="http://www.youtube.com/watch?v=SYZ2GzYAw_Q" rel="noreferrer">Facebook talked about how they limited the number of attributes sent back to the server</a> last year at ChefConf too. Libraries are really an undefined territory because they are the keys to the kingdom.</p>
<p>So, while I haven't actually answered your question (because it's opinion-based), I hope I've given you enough information about the best direction moving forward. Keep in mind that every infrastructure is a special snowflake and there is no <strong>right</strong> answer; there's only a <strong>best</strong> answer. I'd suggest sharing this information with your team and weighing the pros and cons of each approach. You can also try the Chef mailing list, on which people will give you many opinions.</p>
<p>Resources:</p>
<ul>
<li><a href="https://docs.chef.io/lwrp_custom.html" rel="noreferrer">LWRPs</a></li>
<li><a href="http://tech.yipit.com/2013/05/09/advanced-chef-writing-heavy-weight-resource-providers-hwrp/" rel="noreferrer">HWRPs</a></li>
<li><a href="http://docs.chef.io/libraries.html" rel="noreferrer">Libraries</a></li>
</ul> |
2,060,395 | Is there any Scala feature that allows you to call a method whose name is stored in a string? | <p>Assuming you have a string containing the name of a method, an object that supports that method and some arguments, is there some language feature that allows you to call that dynamically? </p>
<p>Kind of like Ruby's <code>send</code> parameter.</p> | 2,060,503 | 4 | 0 | null | 2010-01-13 21:26:03.16 UTC | 11 | 2019-06-01 02:31:58.913 UTC | 2011-02-24 15:59:59.54 UTC | null | 571,593 | null | 31,610 | null | 1 | 24 | scala|dynamic|language-features | 20,705 | <p>You can do this with reflection in Java:</p>
<pre><code>class A {
def cat(s1: String, s2: String) = s1 + " " + s2
}
val a = new A
val hi = "Hello"
val all = "World"
val method = a.getClass.getMethod("cat",hi.getClass,all.getClass)
method.invoke(a,hi,all)
</code></pre>
<p>And if you want it to be easy in Scala you can make a class that does this for you, plus an implicit for conversion:</p>
<pre><code>case class Caller[T>:Null<:AnyRef](klass:T) {
def call(methodName:String,args:AnyRef*):AnyRef = {
def argtypes = args.map(_.getClass)
def method = klass.getClass.getMethod(methodName, argtypes: _*)
method.invoke(klass,args: _*)
}
}
implicit def anyref2callable[T>:Null<:AnyRef](klass:T):Caller[T] = new Caller(klass)
a call ("cat","Hi","there")
</code></pre>
<p>Doing this sort of thing converts compile-time errors into runtime errors, however (i.e. it essentially circumvents the type system), so use with caution.</p>
<p>(Edit: and see the use of NameTransformer in the link above--adding that will help if you try to use operators.)</p> |
1,905,397 | How to get client's timezone? | <p>I'm writting an application using Zend_Framework (so the solution can rely on it).</p>
<p>How to get client's timezone?</p>
<p>For example, if someone in Moscow, Russia, I want to get 3*60*60 (because there is UTC+3). If he is in UK, I want zero. If he uses UTC-3:30 (Canada?), I want -3.5*60*60.</p>
<p>(it's not a question about a format - I'm ok with getting 'Europe/Moscow' or 'UTC-3' for St. Petersburg, Russia, it's rather about getting timezone client uses. But delta in seconds is preferred)</p>
<p>The only solution which comes to mind is letting javascript get the local time for me and redirect.</p> | 1,913,578 | 4 | 1 | null | 2009-12-15 05:44:04.063 UTC | 10 | 2017-07-29 08:44:17.393 UTC | null | null | null | null | 145,357 | null | 1 | 30 | php|zend-framework|timezone | 77,773 | <p>Check out <s><a href="http://www.incoherent.ch/blog/2008/02/20/php5-time-zone-solution/" rel="nofollow noreferrer">this article on how to detect the timezone</a></s> by setting a Cookie through JavaScript that will hold the client's timezone. It's rather lenghty, but that is because it is quite verbose. I've implemented a solution along these lines in one of my own apps and it works quite well.</p>
<p>You could also send the timezone via Ajax to the server and have it do whatever you need to do it with then. Or, if you are not doing any serverside calculations with it, just apply the timezone client side where needed. Really depends on your usecase.</p>
<p>In addition to that, I suggest you let the visitor set his timezone himself and store that in the Cookie or a Session.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.