PDEs on Manifolds

Question: I am wondering if there is a general coordinate-independent way to define a Partial Differential Equation on a Smooth manifold.
It is definitely true that in each coordinate neighborhood you could define a function to satisfy a differential equation, but when you change coordinates then the differential equation will most likely have a different form.
For example, in $\mathbb{R}^3$ one says a function is harmonic if it satisfies
$ \frac{\partial^2}{\partial x^2} f + \frac{\partial}{\partial y^2} f + \frac{\partial}{\partial z^2} f = 0 $
but it is not true that in spherical coordinates a function is harmonic if
$ \frac{\partial^2}{\partial r^2} f + \frac{\partial}{\partial \theta^2} f + \frac{\partial}{\partial \phi^2} f = 0 $
The change of variables to spherical coordinates gives you a much different PDE. So basically, how can you define a differential operator which is coordinate independent on a smooth manifold, so that you can have some notion of a PDE on a manifold.
Answer: Ryan already gave a very good answer. I just want to give a few clarifications on how one should think about PDEs in general. Most importantly: you should not think a differential operator as defined by "a formula". What do I mean by that? In your question, you wrote that the Laplacian in Euclidean coordinates is $\frac{\partial^2}{\partial x^2} + \frac{\partial^2}{\partial y^2} + \frac{\partial^2}{\partial z^2}$, but in Spherical coordinates it is not $\frac{\partial^2}{\partial r^2} + \frac{\partial^2}{\partial \theta^2} + \frac{\partial^2}{\partial \phi^2}$. But why should one have thought that the two expressions are the same?
To illustrate, think of the function on the plane $f(x,y) = x^2 + y^2$. This represents the square of the distance of a point from the origin. In radial coordinates, the same function is written as $f(r,\theta) = r^2$. Not $r^2 + \theta^2$, which is a very different beast.  Just like how the direct replacement $x \to r$ and $y\to \theta$ changes the function you are considering, the replacements $\frac{\partial}{\partial x} \to \frac{\partial}{\partial r}$ etc changes the operator you are considering.
Now: to think geometrically (on manifolds), a (real valued) function is an assignment of a number to each point on the manifold. Then in any coordinate system there is a representation of the function by a formula. Since we like to work with formulas, we can interpret the notion of a function as a "map". This map takes as its input a coordinate system, and outputs a formula that represents your function in that coordinate system. (If you are familiar with category theory, this is similar to how one can think in terms of arrows instead of dots.)
Similarly, a partial differential operator can be thought of as an object in itself. Our usual way of writing it as partial derivatives in some coordinate system with coefficients is just a convenient representation of the real object upstairs. Therefore, analogous to how a function is merely a "map" from coordinate system to the formulaic representation, you can think of a partial differential operator also as a "map" which takes as its input a coordinate system and outputs an expression which is a sum of partial derivatives with some coefficients.
The jet bundle formulation is just a sophisticated, rigorous way of formulating this idea. The main difficulty is making sure the intuition above is compatible with the change of variables formulas. Suppose we are given a coordinate system $A$, and an expression in terms of partial derivatives which we'll call $L_A$. The question becomes: does there exist some abstract partial differential operator $L$ such that its representation in the coordinate system $A$ is precisely $L_A$? And if there is such an operator, is the fact that, for some function $f$ (written in coordinate system $A$ as $f_A$), $L_A f_A = 0$ invariant under change of coordinate system? (That given any other coordinate system $B$, $L_Bf_B = 0$ also.) The tools of jet bundles allows you to make such a consistent definition/description of partial differential equations.
Comment: Wow, I got two fantastic answers. Thank you Willie Wong and Ryan Budney. I gave the "answer accepted" to Ryan only because he was the first to answer.
Comment: Reading this was very helpful for me. I wonder if you could suggest a good textbook/paper reference for this "map from coordinate system to formula" point of view (in particular, I'd be interested in one which addresses the two questions — extension and coordinate invariance — described in the final paragraph of your answer), or any reference concerning partial differential operators on manifolds which you think might be helpful to someone with a background in smooth manifold theory (but not much PDE theory) trying to find his way in the world of (mostly elliptic) PDO and PDE on manifolds.
Comment: This is usually either implicitly or explicitly stated in texts on PDEs and PDOs on manifolds. Recommendation depends a lot on personal background/taste etc., and not knowing you personally I'll just make a stab in the dark. Michael Taylor's PDE books do deal with stuff on manifolds. With elliptic focus you may want to look at Aubin's _Nonlinear Analysis on Manifolds_. If you are working on Lie Groups (instead of Riemannian manifolds) then Robinson's _Elliptic Operators and Lie Groups_ is pretty thorough.
Comment: If you are more into the geometric aspects, a nice place to read about jet bundles and the like is Kolar-Slovak-Michor https://www.mat.univie.ac.at/~michor/preprint-shadows/kmsbookh.html ; in the end of the day, the geometry offer convenient ways of thinking about and formulating things, but PDE theorems often still require getting hands dirty and working with coordinates. @MatthewKvalheim
Comment: Thanks so much!
Answer: You could view the concept of a "Jet bundle" to be precisely what you need to make partial differential equations coordinate-independent on manifolds, as points in jet bundles represent precisely the Taylor polynomials of functions in local coordinates.  Take a look at Chapter 4 in Hirsch's "Differential Topology" textbook for details.
The underlying problem of course is that the tangent bundle of a manifold is not trivial in general so you have to do something new to make sense of partial differential equations.
Perhaps the simplest would be to view a vector field as a 1st order differential equation via the directional derivative operator.  From there you can take mixed directional derivatives.  This isn't ideal because you can't express "natural" differential equations like the Laplacian in this manner (for example, think of $S^2$ -- every vector field has a zero...).  edit: as pointed out, on $S^2$ there is a formulation of the Laplacian in terms of iterated 1st order DE's. I suppose I should have phrased things as "even if you can express a PDE as iterated 1st order DEs on a manifold, it may not be desirable due to the breaking of symmetries brought on by bringing in vector fields."
The most direct approach is to think of partial differential equations as functions on jet bundles.  But you can frequently express interesting differential equations in other manners -- having a connection on a manifold is one of the simplest ways of turning 2nd derivatives into tangential data.  The relevant formulation is called an Ehresmann Connection. But there's all kinds of other structures on manifolds where PDEs can lurk.  Differential forms give you a standard language -- exterior derivative and Hodge star operators on Riemann manifolds give you a language where you can express the Laplacian.
I think this is a very good question in that to a large extent the language you need to express a PDE on a manifold very much informs on what you actually know geometrically about the PDE.  So it's a key step in getting insight into the nature of a PDE.  Having a PDE at the jet bundle level basically means you know nothing about it, other than it's a PDE.
Comment: @Ryan: that's not true strictly speaking, what Mariano mentions is true if you allow the standard set of three rotation vector fields: let $\omega_{x,y,z}$ be the vector field representing rotations around the three axes. Then $\triangle f = \omega_x\omega_x f + \omega_y\omega_y f + \omega_z\omega_z f$ up to a constant factor which you can absorb into $\omega$. I mean, even on $\mathbb{R}^2$ there cannot be two real vector fields such that $D_vD_w f = \triangle f$.
Comment: Can't one write the Laplacian on the sphere as a combination of vector fields? I would have thought that one gets it by considering the action of the Casimir in $U(\mathfrak{so(3)})$ on it, or something :)
Comment: (I mean on the round sphere only, of course)
Comment: I suppose it depends on how complicated a formula you allow -- but if you're just taking directional derivatives you've got the problem that every vector field on $S^2$ has to have a zero.  So there's no formula of the form $\Delta f = D_vD_wf$ for vector fields $v$ and $w$ on $S^2$.
Comment: Perhaps the main issue one might have with expressing PDEs in terms of iterated 1st order DE's via vector fields is that because vector fields have to have zeros, any such expression kills the symmetry of $S^2$.
Comment: @willie: I take it you're not responding to my comment but to the answer above the comment.
Comment: Uh... the Casimir operator that Mariano was talking about is generated *from* the symmetry of the sphere... ; and yes, I am responding to your comment (sort of) in the context of Mariano's comment.
Comment: The vector fields have zeros, and those aren't invariant under the isometry group.  It may be generated "from" the symmetry of $S^2$ but it's very much like how $\sin$ and $\cos$ are generated from the symmetry of $S^1$ -- they're not invariant under the symmetries of $S^1$.
Comment: I think the fact that you cannot *factor* a general differential operator (like, say, the Laplacian) into a simple iteration of vector fields is better explained not by the fact vector fields have to have zeroes on the sphere (I think that is a red herring, since the same fact is true for Laplacian on any manifold with dimension greater than 1), but by the fact that differential operators corresponding to iterated vector fields have very precise and restrictive characterstic variety (union of several flat planes in the tangent space), and so cannot include any operator whose
Comment: (cont'd) character variety is curved. This is also why the wave operator in two dimensions can be factored as two vector fields, but not in three or higher dimensions. As for the Laplacian: its characteristic set is empty, so it cannot be represented as (single) iteration of vector fields. This of course doesn't rule out representation by a sum of such iterations. (Which you won't want anyway, since such a representation is always possible in a coordinate neighborhood.)
Comment: I think we're straying from my point.  The idea was bringing in vector fields destroys symmetry for pretty simple reasons. Zeros is one, but you lose isotropy symmetry for more tautological reasons.
Comment: At least in the algebro-geometric context this always happens, by the way: on a smooth affine variety, derivations and functions generate the algebra of differential operators.
Comment: Right, I suppose this is true on manifolds as well -- by partitions of unity it boils down to a local statement, and it's true locally basically by design.

PDEs on Manifolds


Understanding the number of iterations to find a solution using the Bisection method

Question: I was asked to find the root of an equation using the Bisection method and only for loops with Python 3. This thread shows how to use the method, but not with the explanation for the number in range().
As an example, I have the function

f(x) = x2 - 2*x - 3

and I want to find its negative root, starting with the interval [-4, 1].
I managed to write the function with a for loop, but I don't understand which range I should use, or how to come up with it.
Here is my code, that solves the problem:
...
a = -4
b = 1
c = (a + b)/2

for i in range(1000):
    if f(c) == 0:
        break
    if f(a) * f(c) < 0:
        b = c
    elif f(a) * f(c) > 0:
        a = c
    c = (a + b) / 2

return c, f(c), i

c = -1 (found the negative root), f(c) = 0 confirming that the program works, and i = 52 which indicates that after 52 "tries" of bisection, it found the right answer.
I put a very large number in range() to make sure I found the root, but why does it need only 52 iterations?
Plus, if my interval changed to [-2, 1], I would need 53 tries. Why is that so?
Comment: Have you at least read the theory behind the bisection method, or, in other words, do you know what's happening with your code?
Comment: Um, the accepted answer on the page you link to *does* use a for-loop, no?
Comment: Who voted to close this question simply doesn't understand the topic. It's very clear what he/she is asking.
Comment: By the way, in general, you should not check for this condition `f(c) == 0`, instead you should check that `f(c)` is close enough to zero, i.e. something like this `f(c) < 1e-09`. This is because when using floating-point numbers, you get "roundoff" errors, i.e. you lose precision when doing computations with floats, because of the finite nature of computers...
Comment: @nbro you are totally right and normally I do that using math.isclose(), but in this case I was forced to avoid more sophisticated functions. I tried doing what you suggest (first condition f(c) < 0.000000001), but I get c = -0.25 instead, which got me even more confused!
Comment: @AVLZ Use `abs(f(c)) < 0.000000001` instead.
Comment: @AVLZ Yes, Stefan is right, I forgot to specify the absolute value, so it should be `abs(f(c)) < 1e-09` (for my explanation above).
Answer: With each iteration, you cut the search interval in half.  At each iteration, you check to see whether f(c), the functional value at the midpoint, is 0, within the accuracy of the computer's floating-point representation.
If you were to choose the interval [-101, 99] you would get the solution in only 1 iteration, as that's when you hit c = -1.  The program will stop whenever it gets close enough to the actual root that the evaluation comes up 0.000000
You started with a range of width 5.  What is 5 divided by 2, 52 times?  What is the accuracy of a floating-point number on your implementation?  I'm going to bet that you are close to the minimum difference between two floats.
If you really want to see this in action, add one simple line inside the loop, right at the top:
print a, b, c, f(c)

This will show you the progress of finding the root.
print statements are a low-tech, effective way to trace a program.
COMMENT RESPONSE
Good point: I haven't called out the specific case hard enough.
You finished in 52 iterations because that's how many it took for the program to "stumble" across the proper value.  When you changed and made it in 53 iterations with a smaller range ... the simple way is to say that you got a little lucky the first time.  As I did point out, if you start with something that has -1 as its midpoint, such as [-101, 99], then you'll finish in only one iteration, despite having a much larger interval.
Comment: This doesn't really explain its special case, but it's only a general explanation of the method, which isn't what the OP is asking.
Comment: Thanks, I did notice that with an interval that had zero as its midpoint I would need only 1 iteration (the first condition would be true the first time). While I understand the method on a superficial level and why it ultimately works, I still don't get why 52 is the answer in this case or 53 in the case of the other interval I mentioned. I'm guessing it has to do with the limited accuracy of floating point on Python, but how exactly?
Comment: It's a matter of when that pure bisection gets sufficiently close to the actual root, which you see in the answer you chose.
Answer: If you print([a, b]) in the loop, you can see the range evolve:
[-4, 1]
[-1.5, 1]
[-1.5, -0.25]
[-1.5, -0.875]
[-1.1875, -0.875]
[-1.03125, -0.875]
...
...
...
[-1.0000000000000284, -0.9999999999999929]
[-1.0000000000000107, -0.9999999999999929]
[-1.0000000000000018, -0.9999999999999929]
[-1.0000000000000018, -0.9999999999999973]
[-1.0000000000000018, -0.9999999999999996]
[-1.0000000000000007, -0.9999999999999996]

The calculated mean of -1.0000000000000007 and -0.9999999999999996 is exactly -1. Why? Because you've reached the limit of the what floats can represent. Here are the exact values involved:
>>> '%.60f' % -1.0000000000000007
'-1.000000000000000666133814775093924254179000854492187500000000'

>>> '%.60f' % -0.9999999999999996
'-0.999999999999999555910790149937383830547332763671875000000000'

>>> '%.60f' % (-1.0000000000000007 + -0.9999999999999996)
'-2.000000000000000000000000000000000000000000000000000000000000'

>>> '%.60f' % ((-1.0000000000000007 + -0.9999999999999996) / 2)
'-1.000000000000000000000000000000000000000000000000000000000000'

Floats store 52 bits of fraction, meaning 52 bits after the leading 1-bit. Meaning you lose what's smaller than about 1/252 of your value. After 52 steps, your initial range of size 5 has become about size 5/252. That's about 1/252 of your value -1. So around there, you reach a pretty good chance to stumble upon exactly -1 because of the imprecision.
It could take two or maybe three steps more, because 5/252 is still a bit larger than 1/252. You got lucky there. With your other initial range [-2, 1] you just got less lucky. There your range shrinks until [-1.0000000000000002, -0.9999999999999999] before you reach -1.
If you start with [-4000000, 1] instead, then you'll need 72 steps. It's 20 steps more because the initial range is a million times larger, which is about 220.
Another case: If you use function x**2 - 1000000 and initial range [999.3, 1000.3], then it takes 41 steps. Why? The final value (i.e., the root) is 1000 and the initial range has size 1. That's 1/1000, so about 1/210. So to get to 1/252 you only need about 42 bisections.
Comment: This was exactly what I wanted to understand!! After seeing your answer I re-read the Python Tutorial (15.) and it also helps to understand this question, but I wouldn't have got there without your explanation. Many thanks!
Btw your last example was very useful to understand how the denominator of powers of 2 links to the steps. I checked with [-4000, 1] and guessed the number of additional steps to be around 10 since 2^10 = 1024 ~ 4 * 1000.
Comment: @AVLZ Yeah, I'm quite happy with that last example. Shows quite well how the different parts matter, I think. Here's a challenge: Guess how many steps it'll take for function `x**2 - 1000000` and initial range `[999.3, 1000.3]`.
Comment: I checked that it's 41, but I don't get it. Especially because [999.6, 1000.6] would need 42 steps -> it's the same range, and the midpoint is closer to the root, yet it needs more tries. Does it have to do with the fact that the midpoint is above and not below the root?
Comment: @AVLZ I don't think there's a meaningful reason of that 41 vs 42, I think that's just luck, like the 52 vs 53 in your original examples. But do you understand why you should expect around 42 here?
Comment: Not really, though I've tried to apply the same rationale as in the other function's examples. Something like the range being 1/4 of length so I should expect 2^2 = 4 steps less? But it doesn't do the trick.
Comment: @AVLZ No, the final value is 1000 and the initial range has size 1. That's 1/1000, so about 1/(2^10). So to get to 1/(2^52) you only need about 42 bisections.


HighLight / ScrollTo - ListView, ScrollView on React-Native

Question: I'm playing a bit with react-native and I got stuck at a stage where I can't figure it out by myself. I have a list of items and I would like to scroll automatically to some item.
I know I could use the ScrollView and the contentOffset={{x:0,y:0}} and set and offset, however it would be a little bit more complicate because I would need to track the position of each item, I'm wondering if there is an easy way to do it, so I could sort of focus on specific row in ListView.
Is there such a thing available on the libs?
Comment: I just came across this. Check it out and let me know if it's helpful https://github.com/facebook/react-native/commit/ff6a2c39989121b8671ab7cf74a90d048fdc9acf
Comment: Great question, I'd be interested to hear the solution as well
Comment: Thanks Chris for the hint!
Answer: The ScrollView does not provide a method to scroll to a specific list item - but it does provide the methods scrollTo({x, y, animated}).
If your list items are of equal height, you can use them to implement scrolling to a specific item by calling scrollTo({y:itemIndex * ROW_HEIGHT}).
In order to be able to access the ScrollView instance, you need to capture using the ref property callback:
<ScrollView ref={view => this._scrollView = view} />

And set the scroll position elsewhere with:
scrollToRow(itemIndex) {
  this._scrollView.scrollTo({y:itemIndex * ROW_HEIGHT});
}

Comment: But what if your rows are of variable height?
Comment: https://facebook.github.io/react-native/docs/scrollview#scrollto parameters have changed, updated answer
Comment: @chandlervdw may be you can use https://facebook.github.io/react-native/docs/direct-manipulation.html#measurecallback to measure position, or to measure the heights of all previous rows to the one you want on screen and add them up.
(I know this comment is from >1yr ago, but this shows in google)
Comment: I just found out that SectionList does have a scrollToLocation that receives the index of the section and item. ListView doesn't have this, i don't know why. May be you can use SectionList, including only one section and rendering as nothing, and then use this method. Of course it's not very elegant, but it will probably work better than anything else for rows of variable height (https://facebook.github.io/react-native/docs/sectionlist.html#scrolltolocation)
Comment: For horizontal items, we can use
scrollToRow(itemIndex) {
  this._scrollView.scrollTo({x:itemIndex * ROW_HEIGHT});
}
Answer: I have published react-native-scroll-into-view, a library which enable "scrollIntoView" feature for React Native ScrollView.
For other lists like SectionList you can still use item index like mentionned in other answers.
Comment: Brilliant solution!
Comment: This is a better solution for items in the ScrollView have variable heights.
Answer: If you use FlatList instead of ScrollView, by using ref you will get access to the scrollToIndex method.
https://reactnative.dev/docs/flatlist#scrolltoindex


Problem about Bipartite Graphs.

Question: Problem: Prove that the only connected bipartite graphs that are chordal are trees.
My Attempt: Consider a connected bipartite graph $G$. This graph is a tree if and only if it does not contain a cycle. So what we need to show is that the condition of "chordality" does not allow the graph $G$ to contain cycles. However, if a bipartite graph contains cycles of length at least 6 then it can be chordal, but not necessarily a tree. For example, the graph given below is chordal and also a connected bipartite graph, yet it is not a tree.

Note: This problem is from the book Introductory Combinatorics by Richard A. Brualdi, Problem no. 44, Chapter 12. Page 502.
Comment: However, that would create a 4-cycle in which we cannot draw chord and thus the bipartite graph cannot be chordal. We could generalize this argument.
Comment: Yes, you got the point.
Comment: What definition of chordality are you using? Using the one from Wikipedia (https://en.wikipedia.org/wiki/Chordal_graph) your above example isn't chordal: The 4-cycle 1,5,3,6(,1) does not contain a chord.
Comment: A graph is chordal if a cycle of length 4 or more in it contains a chord, i.e. there is an edge between nonconsecutive vertices in that cycle.
Comment: There is a 6 cycle in this graph WITH a chord.
Comment: 1-4-2-5-3-6-1 is the 6- cycle and the chord is 1-5.
Comment: So the connected bipartite graph is chordal yet it is not a tree?
Comment: What you are thinking is that chordal means "There is *one* cycle of length 4 or more with a chord in it". What chordal really means is (as from Wikipedia above): "a chordal graph is one in which *all* cycles of four or more vertices have a chord" (emphasis mine).
Comment: Oohhh! I got it. But what about a bipartite graph that has cycles of length at least 6. I know that it is not possible to draw chord in a 4 cycle in a bipartite graph, but it is possible to draw a chord in 6 cycle graph.
Comment: Great! Thank you for your help @Ingix.
Answer: Use strong induction in the number of nodes. Let $2n$  be the number of nodes, ($a_{1},a_{2},...a_{n})$ in one side and $(b_{1},b_{2},...b_{n})$ in the other. The goal is to prove that there is no cycle in your graph. Is easy to see that for n=1 and n=2 works. For n=2 you use the fact that if $[a_{i_{1}},b_{i_{1}},a_{i_{2}},b_{i_{2}}]$ is the cycle. But you cant have a chord because the only chords that are possible are the edge $a_{1}-a_{2}$ and $b_{1}-b_{2}$. Contradiction, because the graph is bipartite. now suppose n>2 and you have a cycle with more than 4 nodes. By hypothesis, the chord must break the cycle into two smallest cycles. And by strong induction you can't have a smaller cycle. So there is no cycle in the graph. And because is a connected graph with no cycles, by definition is a tree. QED

Problem about Bipartite Graphs.


how to join multiple 3 xmls in one file?

Question: how to join multiple 3 xmls in one file?
In XML FILE : 01.xml
 <xmlResponse>
        <Person>
            <FirstName>FirstName_1</FirstName>
            <LastName>LastName_1</LastName>
        </Person>
        <Person>
            <FirstName>FirstName_2</FirstName>
            <LastName>LastName_2</LastName>
        </Person>
    </xmlResponse>

In XML FILE : 02.xml
<xmlResponse>
    <Person>
        <FirstName>FirstName_2</FirstName>
        <LastName>LastName_2</LastName>
    </Person>
    <Person>
        <FirstName>FirstName_3</FirstName>
        <LastName>LastName_3</LastName>
    </Person>
    <Person>
        <FirstName>FirstName_4</FirstName>
        <LastName>LastName_4</LastName>
    </Person>
</xmlResponse>

In XML FILE : 03.xml
<xmlResponse>
    <Person>
        <FirstName>FirstName_5</FirstName>
        <LastName>LastName_5</LastName>
    </Person>
</xmlResponse>

I need output like below (01.xml + 02.xml + 03.XML)
<xmlResponse>
    <Person>
        <FirstName>FirstName_1</FirstName>
        <LastName>LastName_1</LastName>
    </Person>
    <Person>
        <FirstName>FirstName_2</FirstName>
        <LastName>LastName_2</LastName>
    </Person>
    <Person>
        <FirstName>FirstName_2</FirstName>
        <LastName>LastName_2</LastName>
    </Person>
    <Person>
        <FirstName>FirstName_3</FirstName>
        <LastName>LastName_3</LastName>
    </Person>
    <Person>
        <FirstName>FirstName_4</FirstName>
        <LastName>LastName_4</LastName>
    </Person>
    <Person>
        <FirstName>FirstName_5</FirstName>
        <LastName>LastName_5</LastName>
    </Person>
</xmlResponse>

hoping your response,
tks...
Comment: Could you give a hint on the direction you would like to take to do this? E.g. do you want to use some XML library, or only strip the first and last lines in each of the files and concatenate the contents?
Comment: We also need to know if XMLs are distinct or has some intersection
Answer: You could use XSLT buts it an overkill for this task under ASP Classic (or actually anything else).
(Assuming you haven't mis-tagged your question)
Function GetDom(pathToFile)
    Set GetDom = CreateObject("MSXML2.DOMDocument.3.0")
    GetDom.async = False
    GetDom.setProperty "SelectionLanguage", "XPath"
    GetDom.load pathToFile
End Function

Sub CopyElements(xmlPrimeRoot, xmlDonor)
    Dim elem
    For Each elem In xmlDonor.documentElement.selectNodes("*")
        xmlPrimeRoot.appendChild elem
    Next
End Sub

Dim xmlPrime: Set xmlPrime = GetDom(pathToFile1)

CopyElements xmlPrime.documentElement, GetDom(pathToFile2)
CopyElements xmlPrime.documentElement, GetDom(pathToFile3)

xmlPrime.save pathToDestinationFile

If the target output is the ASP response then the last line can be
xmlPrime.save Response

Answer: Try this XSLT 2.0 style-sheet ...
<?xml version="1.0"?>
<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:fn="http://www.w3.org/2005/xpath-functions"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  version="2.0"
  exclude-result-prefixes="xsl xs fn">

<xsl:output indent="yes" encoding="UTF-8" />
<xsl:param name="doc2" />
<xsl:param name="doc3" />
<xsl:variable name="doc2-doc" select="document($doc2)" />
<xsl:variable name="doc3-doc" select="document($doc3)" />

<xsl:template  match="/">
 <xmlResponse>
    <xsl:apply-templates />
    <xsl:apply-templates select="$doc2-doc/*" />
    <xsl:apply-templates select="$doc3-doc/*" />
 </xmlResponse>
</xsl:template>

<xsl:template match="element()">
  <xsl:copy>
    <xsl:apply-templates select="@*,node()"/>
   </xsl:copy>
</xsl:template>
<xsl:template match="attribute()|text()|comment()|processing-instruction()">
  <xsl:copy/>
</xsl:template>

</xsl:stylesheet>

For the transformation, the input document will be your first document (File 01.xml), and the other two will be passed in as transform parameters.
If you are limited to XSLT 1.0, some modification will be required, but it should not be too difficult.


bash variable not available after running script

Question: I have a shell script that assigns my IP address to a variable, but after running the script, I cannot access the variable in bash. If I put an echo in the script, it will print the variable, but it does not save it after the script is done running.
Is there a way to change the script to access it after it runs?
ip=$(/sbin/ifconfig | grep "inet " | awk '{print $2}' | grep -v 127 | cut -d":" -f2)

I am using terminal on a Mac.
Answer: A script by default runs in a a child process, which means the current (calling) shell cannot see its variables.
You have the following options:

Make the script output the information (to stdout), so that the calling shell can capture it and assign it to a variable of its own. This is probably the cleanest solution.
ip=$(my-script)

Source the script to make it run in the current shell as opposed to a child process. Note, however, that all modifications to the shell environment you make in your script then affect the current shell.
. my-script # any variables defined (without `local`) are now visible

Refactor your script into a function that you define in the current shell (e.g., by placing it in ~/.bashrc); again, all modifications made by the function will be visible to the current shell:
# Define the function
my-func() { ip=$(/sbin/ifconfig | grep "inet " | awk '{print $2}' | grep -v 127 | cut -d":" -f2); }

# Call it; $ip is implicitly defined when you do.
my-func

As an aside: You can simplify your command as follows:
/sbin/ifconfig | awk '/inet / && $2 !~ /^127/ { print $2 }'


$I(X:Y|Z=z) \leq I(X:Y|Z)$?

Question: $X,Y$ and $Z$ are discrete random variables. $I$ is the mutual information. The question is in the title. If the inequality is true, how would you show it? Thanks.
My intuition: having more information on the conditional variable $Z$ ($e.g.$ $Z=z$) decreases the correlations between $X$ and $Y$, as visualized by the decrease in the intersection surface.
Answer: I think the inequality does not hold for all $z$ (the support of $Z$)
$I(X;Y|Z=z)$ is a function of the random variable $Z$, $g(Z)$ it can take different values for different realizations $z$.
$I(X;Y|Z)$ is the expected value of that function, $E_Z[g(Z)]$, a weighted average that must lie between the largest and smallest value g(Z) can take.

$I(X:Y|Z=z) \leq I(X:Y|Z)$?


If else statement error , Javascript

Question: Im javascript beginner and tried to perform some if else statements. Basically you can see my own code in line two! until line seven. But dreamwaever marks it always red! So what did i wrong
    this.toDataURL = function() {
    if this.path == []
    {
     document.getElementById("canvascontent").value = "Oh yeah";
    }
    else
    {
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    canvas.width = innerWidth;
    canvas.height = innerHeight;
    ctx.drawImage(layer0, 0, 0);
    ctx.drawImage(layer1, 0, 0);
    ctx.drawImage(layer2, 0, 0);
    var url = canvas.toDataURL('image/png');
    document.getElementById("canvascontent").value = url;
    }
};

Comment: `if` statements in Javascript require parentheses around the conditional statement. https://en.wikipedia.org/wiki/JavaScript_syntax#If_..._else
Comment: seems you were in hurry
Comment: I've half a mind to downvote all the answers just for jumping for the easy rep and missing the glaring mistake in the logic (`this.path == []` will *always* be false).
Comment: While 4 people were quick to point out the syntax error of missing parenthesis, there is a bigger problem here that needs to be pointed out.  Comparing arrays in javascript via `==` is going to return false all the time.
Comment: @RobertHarvey I don't feel this should be downvoted...  He even disclaims that he is a beginner.  He has enough of an understanding to ask the question.  Let's not keep beginners from asking questions.
Comment: @user1477388: We didn't keep him from asking a question.  We didn't even prevent him from getting an answer.  For the record, I didn't downvote.
Comment: @Juhana totally agreed
Comment: Yes sorry, i was confused, because i interchanged it with ruby syntax sorry! But thanks for @tymeJV answer
Comment: @WarrenKrewenki "Comparing arrays in javascript via `==` is going to return false all the time." - how is that true? You can easily compare array references and the result be true. I can't see a use case for it, but maybe you meant comparing an array to `[]` will always be false, which is true. Unless you were trying to compare to the use of `===` which has no difference here
Answer: You forgot () around your if statement:
if (this.path == []) {

Answer: You forgot to surrond your if statement with parenthesis:
if (this.path == []) {

Answer: if (this.path == []) //You missed to enclose if statement.

Usually
if ( statement ) {
}
else {
}

Answer: You forgot () parenthesis
if (this.path == []) {

Comment: No, those are braces.  These `[]` are brackets.
Comment: Those are parentheses, not brackets. These `{}` are brackets.

If else statement error , Javascript


Selecionar uma option com botão externo

Question: Boa tarde pessoal,
Eu preciso que, quando eu aperto em um botão, o mesmo faça com que uma específica
option seja selecionada no select. Por exemplo, eu possuo 3 botões e 3 options:

<button>1</button>
<button>2</button>
<button>3</button>

<select>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

Se eu clicar no botão 1 irá selecionar a option 1, se eu clicar no botão 2 irá selecionar a option 2, e se eu clicar no botão 3 irá selecionar a option 3.

Não sei muito de JavaScript, mas acho que provavelmente irei precisar usar.
Agradeço qualquer ajuda.
Answer: A minha dica é colocar um ID em cada btn, e nos option vc coloca o value igual ao valor do ID, tipo o btn1, tem o id=n1, e o option1 tem o value=n1, dessa forma vc diz que o value deve ser = ao id do elemento clicado, simples assim, veja

let btn = document.querySelectorAll('button');
let select = document.querySelector('select');

function troca(e) {
    select.value = e.currentTarget.id;
}

btn.forEach( (el) => {
    el.addEventListener('click', troca);
})
<button id="n1">1</button>
<button id="n2">2</button>
<button id="n3">3</button>

<select>
    <option value="n1">1</option>
    <option value="n2">2</option>
    <option value="n3">3</option>
</select>
Comment: Isso mesmo que eu precisava, obrigado!
Comment: @JeanFranz opa! Legal que resolveu ai :D valeu a força!
Comment: se for uma tag `a` muda alguma coisa ou é só alterar o `button` por `a`?
Comment: @JeanFranz muda sim, vc pode usar o href como referencia no lugar do id por exemplo, e coloca e.preventDefault na função pro link não interferir, ou então vc coloca o id no A e deixa o href=# mesmo, teoricamente vai funcionar normal

Selecionar uma option com botão externo


Calling function defined in module not in scope for onload

Question: I'm having a problem with modules/scope. I need to declare script tags as type="module" but then functions declared in that scope are not global, so can't be called with onload etc.
First file: index.html

 *** replace with function call ***

Second file: sayHi.js
export function sayHi(user) {
  return (`Hello, ${user}!`);
}

The x function is not in scope outside of the  block, so I get the error:
(index):36 Uncaught ReferenceError: x is not defined
    at onload ((index):36)

How do I make x global?
Answer: While it's possible to create global variables from a module script, there is likely no need for this in your situation.
Since the evaluation of module scripts is automatically deferred, you can directly access the element in the script:

If this doesn't work for you for whatever reason, bind an event handler from inside the script instead:

Answer: It seems like that's how modules work:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

Last but not least, let's make this clear — module features are
imported into the scope of a single script — they aren't available in
the global scope. Therefore, you will only be able to access imported
features in the script they are imported into, and you won't be able
to access them from the JavaScript console, for example. You'll still
get syntax errors shown in the DevTools, but you'll not be able to use
some of the debugging techniques you might have expected to use.

But this SO post should provide you with a workaround:

 *** replace with function call ***


How to migrate password with hash

Question:
I'm doing a user migration from Drupal 7 to Drupal 8 (the data is in json format)
Most of the fields have been imported to the new website. Now, I'm in the process to migrate the password; this field is, of course, encrypted/hashed (as far as I understood, Drupal uses SHA512 by default with a salt).
So far, I have found this answer and adapted my code like below:
<code>$users_json = file_get_contents("../import/users.json");
$users_array = json_decode($users_json, true);

foreach($users_array as $user){

    $values = array(
        'name' => $user["name"],
        'pass' => [
            'value' => $user["pass"],
            'pre_hashed' => TRUE,
        ],
        'status' => $user["status"],
        'mail' => $user["mail"],
    );

    $userStorage = \Drupal::entityTypeManager()->getStorage('user');
    $userEntity = $userStorage->create($values);

    $role = $user["roles"][0];
    $userEntity->addRole($role);

}
</code>
Now, my question is: Is it a good approach? How do I import this kind of field? Do I have to decrypt/de-hash the password?
Comment: Does this answer your question? [How do I migrate users passwords?](https://drupal.stackexchange.com/questions/209163/how-do-i-migrate-users-passwords)
Answer: You can follow document.

The $P$ is the so called hash type identifier which indicates that the
hash is a portable Phpass hash. The string after that consists of salt
and a hash. The portable Phpass hashes can be migrated to Drupal 8
as-is. When the user logs in to your Drupal 8 site for the first time,
Drupal will re-hash the password. The salted hash used in this example
is for a password 'test'.

If the source system was a PHP based application that used crypt() or
password_hash(), these hashes should work as-is and they can be
migrated 1:1 like in the Phpass example above. When the user logs in
to your Drupal 8 site for the first time, Drupal will re-hash the
password.

Here is my example convert old pass using md5
<code><?php

namespace Drupal\my_module;

use Drupal\Core\Password\PhpassHashedPassword;
use Drupal\Core\Password\PasswordInterface;

/**
 * Provides custom password hash comparison for migrated passwords.
 */
class MyModulePasswordService extends PhpassHashedPassword implements PasswordInterface {

  public function check ($password, $hash) {
    // Check old pass is md5
    if (preg_match('/^[a-f0-9]{32}$/', $hash)) {
      $pwd_sercet = "pwd_sercet";
      $pass_hash = md5($pwd_sercet . $password);
      return ($pass_hash == $hash);
    }
    return parent::check($password, $hash);
  }
}
</code>

How to migrate password with hash


Parametric equations for a great circle on the unit sphere

Question: I want to define a great circle on the unit sphere, given two points on its surface.
The great circle is the intersection of a plane and a sphere, such that the plane touches the sphere's origin and the two points given (call them $p_1$ and $p_2$). Coordinates are Cartesian. I'm using parametrized equations in order to plug them into gnuplot.
With parameters $u_1$, $v_1$ and $u_2$, $v_2$ the two surfaces are:
$$x=cos(u_1)cos(v_1), y=cos(u_1)sin(v_1), z=sin(u_1)$$
$$x=u_2, y=v_2, z=\sqrt{{c_1^{-2}}-1}(u_2sin(c_2)+v_2cos(c_2)) $$
I'm not sure yet how $c_1$ and $c_2$ are supposed to be derived from the points' coordinates, but OK.
Solving this system of equations for the parameters I got the following:
$$u_1=arccos(\frac{u_2}{cos(v_1)})$$
$$v_1=arccos(\frac{u_2}{cos(u_1)})$$
$$u_2=cos(u_1)cos(v_1)$$
$$v_2=cos(u_1)sin(v_1)$$
Here I'm stuck; I don't know what I'm looking for. $c_1$ and $c_2$ disappeared because of the relationships I plugged in above. How can I turn these equations into the parameters that describe the great circle?
Comment: Note that if the two points on the sphere are collinear with the center of the sphere ("opposite poles"), then the described "great circle" is not unique.
Comment: @Aaron Brick Note that the original equatorial plane should be rotated through $\phi,\theta$ in spherical coordinates.
Comment: Your "solution" is just a partial list of the relationships among your surfaces' parameters. It does not take into account that the $z$ coordinates at the intersection points must also be equal, so it does not actually describe the great circle. In any case, in the end you really want to have only _one_ parameter in the parameterization of the circle, and it will not be any of the parameters you started with. You seem to have gotten these formulas from somewhere; is there any particular reason why you're using these formulas (and not others) for this purpose?
Comment: By the way, I think $u_2$ was supposed to occur in the formula for $z$ for the plane, possibly in a term $u_2\sin(c_2).$
Comment: @DavidK Thanks, you were right about the u2. The reason I started with the parametrizations instead of the implicit versions is that I want to graph the arc in gnuplot, which expects parameters for a 3D plot. I guess I could plot the points calculated with some other solution, if that were simpler.
Comment: With the parameterizations in the question, you would be able to plot the sphere and the plane in gnuplot. I don't know how well that would show the great circle, and in any case you'd have the plots of the plane and sphere visible, which I imagine might be unwanted clutter (at least the plane, since you only got that in order to put a great circle through the two given points). The great circle, even though it is in 3D, is still just a curve, not a surface; that's why I think it's probably better to plot it with just one parameter instead of two like the surfaces.
Answer: If $\mathbf u$ and $\mathbf v$ are a pair of orthogonal unit vectors, then $\mathbf r(t) = \mathbf u\cos t+\mathbf v\sin t$ is a parameterization of a unit circle that lies in the plane spanned by these vectors. By definition, $p_1$ and $p_2$ are already unit vectors and if they're not antipodes, span a unique plane. It's convenient to take $\mathbf u = p_1$ so that $\mathbf r(0)=p_1$ and then use cross products to generate $\mathbf v$: $(p_1\times p_2)\times p_2$ lies in the span of $p_1$ and $p_2$ and is orthogonal to $p_1$. Normalize this vector and set $\mathbf v$ to the result. For this choice of $\mathbf v$, the circle will be traced toward $p_2$ along the shorter of the two arcs as $t$ increases. On the other hand, if $p_1\times p_2=0$, then the two points are either antipodes or coincide and you can take any unit vector orthogonal to $p_1$ as $\mathbf v$—the plane of the great circle is not uniquely determined.
You could also start with the unit circle $\mathbf r(t) = (\cos t,\sin t)$ in the $x$-$y$ plane and tilt it into place, but computing the required rotation or reflection takes at least as much work as the above.
Comment: You have a small typo in your answer: $(p_1 \times p_2) \times p_2$ is *not* orthogonal to $p_1$; $(p_1 \times p_2) \times p_1$ is. Wanted to point that out for anyone looking at this answer.
Answer: Your equation for the sphere is OK, but your equation for the plane excludes e.g. the plane $\{(x,y,z)|y=0\}$. What you want is the plane
$$
P = \{u_2 p_1 + v_2 p_2\} \le \mathbb R^3,
$$
where $u_2, v_2$ are the parameters. That is,
$$
x = u_2 p_1^1 + v_2 p_2^1, ~~~ y = u_2 p_1^2 + v_2 p_2^2, ~~~ z = u_2 p_1^3 + v_2 p_2^3,
$$
where the upper indices don't stand for exponents, but the components of $p_1, p_2$.
Of this plane, you can then find an orthonormal basis $w_1, w_2$ by applying the Gram‒Schmidt procedure, and then the parametric equation is
$$
u_3 \mapsto \cos(u_3) w_1 + \sin(u_3) w_2.
$$
Comment: Note also hardmath's comment above: For Gram‒Schmidt to work, $p_1, p_2$ needn't be collinear.
Comment: Even though, as I'm noticing just now, in this case one may insert for $w_2$ *any* unit vector orthogonal to $w_1$.


How can I store value in the array on the JavaScript?

Question: My JavaScript code is:

The result of console.log(photoList[i].id) is 3 and 5.
I want to store it in the an array like this : [3,5]. So if it meets the if condition, then the value is stored in the an array
How can I do it?
Comment: `result = photoList.filter(x => x.name === proto.cover1 || x.name === proto.cover2)`
Comment: Create an array variable and use `push` function.
Answer: You can create an array and push in it.Like

Answer: You could make an array of the cover values and filter photoList and get only the id value of the objects.

var photo = { cover1: "arsenal.jpg", cover2: "liverpool.jpg" },
    photoList = [{ id: 1, name: "chelsea.jpg" }, { id: 2, name: "mu.jpg" }, { id: 3, name: "arsenal.jpg" }, { id: 4, name: "city.jpg" }, { id: 5, name: "liverpool.jpg"}],
    covers = Object.values(photo),
    result = photoList
        .filter(({ name }) => covers.includes(name))
        .map(({ id }) => id);

console.log(result);
Answer: You could use reduce method and inside check values of other object using some method.

var photo = {"cover1":"arsenal.jpg", "cover2":"liverpool.jpg"};
var photoList = [{"id":1, "name":"chelsea.jpg"},{"id":2, "name":"mu.jpg"},{"id":3, "name":"arsenal.jpg"},{"id":4, "name":"city.jpg"},{"id":5, "name":"liverpool.jpg"}];

const result = photoList.reduce((r, {id, name}) => {
  const match = Object.values(photo).some(e => e == name)
  if(match) r.push(id);
  return r;
}, [])

console.log(result)
Answer: Try the following with Array's map() and filter():

var photo = {"cover1":"arsenal.jpg", "cover2":"liverpool.jpg"};
var photoList = [
    {"id":1, "name":"chelsea.jpg"},
    {"id":2, "name":"mu.jpg"},
    {"id":3, "name":"arsenal.jpg"},
    {"id":4, "name":"city.jpg"},
    {"id":5, "name":"liverpool.jpg"}
];

var res = photoList.map(function(p){
  if(p.name === photo.cover1 || p.name === photo.cover2)
   return p.id;
}).filter(x => x);

console.log(res);
Answer: You can create the array before the loop, and then, from the if block, push the values you want to it.
Your code should look like this:

Answer: use filter from array
var newarray = photoList.filter( (currentphoto) => {
    return currentphoto.name === photo.cover1 || currentphoto.name === photo.cover2;
})

that's enough
Answer: You the reduce method more more detail http://underscorejs.org/#reduce.
And use some method.
var photo = {"cover1":"arsenal.jpg", "cover2":"liverpool.jpg"};
var photoList = [{"id":1, "name":"chelsea.jpg"},{"id":2, "name":"mu.jpg"},{"id":3, "name":"arsenal.jpg"},{"id":4, "name":"city.jpg"},{"id":5, "name":"liverpool.jpg"}];

const result = photoList.reduce((r, {id, name}) => {
  const match = Object.values(photo).some(e => e == name)
  if(match) r.push(id);
  return r;
}, [])

console.log(result)


What is the difference between 2 strings initialization in Swift `=String()` and `: String!`

Question: String 1:
var string1=String()

String 2:
var editTag: String!

Comment: @SohilR.Memon This isn't exactly the same question - so, no duplicate.
Comment: you can follow this for more info http://stackoverflow.com/questions/24006975/why-create-implicitly-unwrapped-optionals
Answer: The top one declares and creates an instance of String.
The bottom declares an implicitly-unwrapped optional variable which can hold a String but doesn't create an instance of String.
Because the bottom is an optional it has a value of nil until it contains an instance of the class. By implicitly unwrapping it with a ! you make a promise that it will  be filled with an instance, usually in the init function or similar. Because of this there's no need to check if it's filled or unwrap it before using it.
Comment: It's worth mentioning, that the second form also _defines_ an optional value which is initialized to `nil`.
Answer: The first line declares a string variable and initialises it with an empty string.
The second line also declares a string variable but in this case it is an implicitly unwrapped variable. At this point the variable is not actually initialised and any attempt to access it would produce an "unexpectedly found nil" exception.
Declaring a variable in this way allows you to not initialise the variable in the initialiser function (which normally you would have to do). You might use this when you are going to initialise a variable in a function such as viewDidLoad or provide a value from another view controller's prepareForSegue method.
Answer: The first one will create a n instance for string, like alloc init in objective c.
The second one will declare unwrapped version of string but there will be no instance of this string and accessing this variable when there is no value in this string ,it will crash.


Is the number of row operations to get to row echelon form fixed?

Question: I was looking at LU factorization (with no row exchanges) and it struck me how the multipliers $\it l_{ij}$ remain unchanged in the L matrix. I was then wondering if this means that the amount of row operations needed to get any matrix to row echelon form is already predetermined and if there were any formal proofs of this. I'm still a noobie in the subject, be gentle with me.
Answer: Yes, for a $n\times n$-matrix you can bound the number of row operations by $\frac{n(n-1)}{2}$ without counting row exchanges.
Because of the structure of Gauß elimination you perform $(n-1)+(n-2)+\ldots+2+1=\sum_{i=1}^{n-1}i=\frac{n(n-1)}{2}$ row operations using that method.
However there are other procedures to compute LU decomposition that are not based on row operations and overall have less arithmetic operations compared to Gauß elimination. Gauß elimination can be shown to take about $\frac{2}{3}n^3$ arithmetic operations (see wikipedia), while other methods use asymptotically less arithmetic operations as indicated in another wikipedia article.
Comment: Thanks very much! Super quick as well!


Setting innerHTML in a webview replaces the entire document instead of just the element

Question: Note: This is scaloid, so the syntax is a bit different from Java, but all the classes are the usual Android classes from Java.
I'm initializing a webview using:
webView.settings.setJavaScriptEnabled(true)
webView.setWebChromeClient(new WebChromeClient)

and then I call
val jsUrl = "javascript:document.getElementById('" + getTagId(word) + "').innerHTML = '" + guess + "'"
webView.loadUrl(jsUrl)

where getTagId(word) is an existing ID (I've debugged this) and guess is a short string like "abc".
It works perfectly in my desktop browser, but in the webview it replaces the entire document instead of just replacing the element.
I've tried to debug and make sure that the element is actually found by replacing the call with
"javascript:alert(document.getElementById('" + getTagId(word) + "').innerHTML)"

and it shows an alert with the right content! Only the replacement goes wrong.
This bug is driving me crazy :-( What am I missing?
P.S. I'm working on this open-source project: https://github.com/ilyakogan/gluckentext
Answer: I still don't know why this didn't work, but I ended up adding a JS function and calling it from the native Android code, instead of calling getElementById directly from the native code.
I added this to the HTML:

and then wrote this in the native code (Scala in my case, Java in the general case):
val jsUrl = "javascript:markSolved(" + getTagId(answeredWord) + ")"
webView.loadUrl(jsUrl)

Answer: You can just wrap custom Js code in module:
view.loadUrl("javascript:(function(){document.getElementById('uname').value = 'test';})()");

Works for me


Indicial equation of $4xy''+2y'+y=0$?

Question: We consider $$4xy''+2y'+y=0$$ and search for a power series solution $$y=\sum_{r=0}^{\infty} a_rx^{r+m},$$ where we assume $a_0\neq 0$. By differentiating and substituting into the differential equation we get $$\sum_{r=0}^{\infty} 2a_r(r+m)(2r+2m-1)x^{r+m-1}+\sum_{r=0}^{\infty} a_rx^{r+m}=0.$$ The lowest power of $x$ is $x^m$ whose coefficient gives the indicial equation $$2m(2m-1)a_0+a_0=0.$$
But shouldn't the roots of the indicial equation be $m=0$ or $m=1/2$?
I would appreciate any help or suggestion on this.
Thank you.
Answer: The lowest power appearing in the equation (as you have it), is actually $x^{m-1}$, so the indicial equation (coming from $r=0$) would be:
$$2a_0 m (2m-1)=0$$
so indeed your roots are $m=0$ and $m=1/2$.
Comment: Now I see my mistake. Thanks a lot.

Indicial equation of $4xy''+2y'+y=0$?


PhoneGap Parse JS logout function returns 404

Question: I am developing a PhoneGap + Parse application.
I have a login page and a logout button. I call the following code on logout button click.
$('#signout').click(function(event){
  $(":mobile-pagecontainer").pagecontainer("change", "#signin", { reload:true, transition:'flow', changeHash:true });

  Parse.User.logOut();
  console.log('logged out');

});

I get the following message in my browser console.
POST http://192.168.2.2:3000/proxy/https%3A%2F%2Fapi.parse.com%2F1%2Flogin 404 (Not Found)

What does this mean? What should be corrected for the logout functionality to work properly?
Comment: platform? cordova CLI version? cordova platform version?
Comment: I used phonegap exe to setup the project
Comment: phonegap exe? what is that?
Comment: Its a windows desktop application i used to create the project boilerplate code
Comment: you mean phonegap desktop app?
Comment: and login works fine? you just get that error on logout?
Comment: Yes. I am able to login, sign up user. But logout gives me this error
Comment: I don't know what is happening in your app, but usually login gives 404 error when user is not found. But you called logout..
Comment: Now when I intended the code snippet correctly I can see you enter singin page with forced reload of page. Does that page itself somehow clear session on start and when the code reaches logout, there is no more user to sign out?
Comment: @mico I dont think so. Because when I restart the phonegap server or open the url from a browser after closing it, parse still has the user logged in. I suppose thats how parse works.
Comment: Can you please post your js file with login and sign up code snippet ?
Answer: $('#signout').click(function (event) {
    $(":mobile-pagecontainer").pagecontainer("change", "#signin", {
        reload : true,
        transition : 'flow',
        changeHash : true,
        beforechange : function (event, ui) {
            Parse.User.logOut();
            console.log('logged out');
        }
    });
});

Haven't tested this but using beforechange might help you logout from Parse and then transitions the page to signin.
Answer: $('#signout').on('click',function(event){
  event.preventDefault();
  Parse.User.logOut();
  $(":mobile-pagecontainer").pagecontainer("change", "#signin", { reload:true, transition:'flow', changeHash:true });
  console.log('logged out');
});

Answer: re the POST for a login....
I think you want your framework ( jquery/cordova ) to issue a GET not a POST.
in addition the GET is going to require the following Headers and parms
-H "X-Parse-Application-Id: AbR" \
  -H "X-Parse-REST-API-Key: uI9" \
  -H "X-Parse-Revocable-Session: 1" \
  -G \
  --data-urlencode 'username=e6' \
  --data-urlencode 'password=e8'

above from parse , REST manual applies to what you have on the WIRE via http protocol and in your console log.
So, in your framework code, prior to whatever issues the get, you would need to urlEncode both the username , password values.
Then append the query string below..
?username=$encodedNameVal&password=$encodedPasswrdVal

to the end of the Domain/path you are passing to GET...
api.parse.com/1/login

not familiar with PG , but i dont need to be in order to interpret the 404 u have.
Comment: Re your framework and devel/debug... You are going to want to track NET request in your console/devTools and to realize that the framework should be issuing http commands to parse.com that you can parallel over at any CURL/WGET CLI.  if you have a module that logsout/logsin you may want to fire up those respective REST commands on the CLI , watch them working / OR NOT. and then look for their likeness being issued by your runtime framework.. It can help understand your apps at a critical , low level you must have command of for debugging.


Field values added programmatically dispear after a certain time

Question: I created a module that creates a block to show a schedule information. I need taxonomy terms to configure the block. I want that those terms are filled with preconfigured values when I install the module.
I have in my config/install folder the definition of my taxonomy:
core.entity_form_display.taxonomy_term.schedule_channels.default.yml
core.entity_view_display.taxonomy_term.schedule_channels.default.yml
field.field.taxonomy_term.schedule_channels.field_channel_id.yml
field.storage.taxonomy_term.field_channel_id.yml
taxonomy.vocabulary.schedule_channels.yml

Here the content of the file field.storage.taxonomy_term.field_channel_id.yml:
langcode: en
status: true
dependencies:
  module:
    - taxonomy
id: taxonomy_term.field_channel_id
field_name: field_channel_id
entity_type: taxonomy_term
type: string
settings:
  max_length: 50
  is_ascii: false
  case_sensitive: false
module: core
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

Also in my schedule_block.install I have:

class schedule_block_class{

  const schedule_block_channels_terms = array(
    array(
      'name' => 'Brava',
      'field_channel_id' => 'BRA001'
    ),
    array(
      'name' => 'DJazz',
      'field_channel_id' => 'DJA001'
    ));
  const schedule_block_channels_vid = 'schedule_channels';
}

function schedule_block_install(){
  $schedule_block_terms = schedule_block_class::schedule_block_channels_terms;
  $schedule_block_vid = schedule_block_class::schedule_block_channels_vid;
  foreach($schedule_block_terms as $schedule_block_term){
    $term = Term::create(array(
      'name' => $schedule_block_term['name'],
      'field_channel_id' => $schedule_block_term['field_channel_id'],
      'description' => '',
      'parent' => array(0),
      'vid' => $schedule_block_vid
    ));
    $term->save();
  }
}

function schedule_block_uninstall(){

  $schedule_block_terms = schedule_block_class::schedule_block_channels_terms;
  $schedule_block_vid = schedule_block_class::schedule_block_channels_vid;
  $terms = array();
  foreach($schedule_block_terms as $schedule_block_term){
    if($terms_name = taxonomy_term_load_multiple_by_name($schedule_block_term['name'], $schedule_block_vid)){
      $terms = array_merge($terms, $terms_name);
    }
  }
  foreach($terms as $term){
    $term->delete();
  }
  $taxo = \Drupal\taxonomy\Entity\Vocabulary::load(schedule_block_class::schedule_block_channels_vid);
  if(!is_null($taxo)){
    $taxo->delete();
  }
}

When I install my module, my taxonomy vocabulary is created and my terms are loaded with my values
... BUT ...
After about 24h the values have disappeared. Checking in the table taxonomy_term__field_channel_id confirms that there is no more any values. I still have my taxo vocab, and all the needed tables are present.
Why the values are not permanent?
Comment: I've recently seen a problem with drupal thinking that a field got deleted and it constantly does cleanup when cron runs. Check the keys for deleted fields and storages in state (key value table)
Comment: @Berdir Yes in the key_value table in the row state/field.field.deleted and the row state/field.storage.deleted I see my field names in the value column.
Answer: (Re comments)
That's the reason then. Those fields being in state, which means drupal thinks they were deleted and is trying to delete conent in them.
Remove them from there. Probably OK to drop the whole rows, check all the other fields in there. You might have some deleted field tables that you need to clean up manually.
I've seen someone else have this problem, what we couldn't figure out is how it happened. Please open a core issue (probably critical) and try to describe what you did.. delete fields, config import, create through manual config import. Anything you can think of that might have caused this.
Comment: Ok that is what is happening: When developing a module .install you often have to uninstall/reinstall. When you uninstall the module, the fields are marked for deletion (see key_value table at the row with collection to state and field.field.deleted and field.storage.deleted). If you reinstall your module without running the cron manually, your fields values will be deleted at the next cron pass. I don't know if you could consider this a bug.
Comment: Yes, that's definitely a bug. it is supposed to work because the table is renamed on uninstall and then it deletes from that. But somehow that doesn't happen and it deletes from the real table.


Supermicro BMC IPMI - How to get hardware specs without OS access

Question: This is my first post in Serverfault for the purpose of trying to get the hardware specs for our supermicro 1U rack server so here it goes:
I have downloaded the IPMIView, IPMICFG, and SMCIPMI utilities -> https://www.supermicro.com/en/solutions/management-software/ipmi-utilities. I have only executed the IPMIView tool but have not been able to get hardware specs - namely, disk storage, ram, cpu, gpu, and nic specs. Only baseboard architecture and product model specs. I have done some reading on the other utilities in the user manuals. I am working on re-imaging the server because the prior OS is encrypted and not going to bother decrypting it, just going to overwrite it with a UA-I image through remote console kvm java application Virtual Media and load-boot from the iso. However, I must get hardware specs and thus far from what I have read I it appears that I cannot get the information I want via supermicro's IPMI utilities and I must have an OS installed to pull this data. Is this correct? Or can I do something about this? All the utilities from what I have learned only function at the BMC interface. Thank you in advance for any insight.
Image showing Summary
Answer: You can enter IPMI through web interface and check Hardware info in System -> Hardware information.
Comment: So when I have tried selecting System it just prompts "You need the latest Java(TM) Runtime Environment. Would you like to update now?" and redirects me to System Information->Summary which successfully loads, however it is just firmware, ip address, mac address, etc. I click Cancel for it to do this because when I click OK for the JRE update it just results in "To protect your security, www.oracle.com will not allow Firefox to display the page if another site has embedded it. To see this page, you need to open it in a new window." FRU reading and System information displays, but no System->HW
Comment: Web service is provided through HTTP protocol which is considered as unsafe nowadays, so you should configure your browser to allow it - that is the reason I guess. I use Google Chrome and it promts once that the page is unsafe but allows to go on it, so I suggest you to also use another browser instead of firefox. I edited the post to add a screenshot of the Hardware info tab, so you can be sure you're going in the right direction
Comment: Yep, I tried other browsers and also configured the exception site list in the java control panel security section to allow various iterations of the IP URI. It still for some reason does not display hardware info like what you have showing in your screen shot. I think it is because it is an X9 series BMC chipset and the last firmware release was in 2013 for this model board controller architecture, at least I suppose. I can only get FRU Information and Summary to render, no System HW info.
Comment: Then my last suggestion will be to use console IPMI utility which seems to provide some extended functionality. The one is called SMCIPMITool [here](https://www.supermicro.com/en/solutions/management-software/ipmi-utilities), also available commands are present here. Also if you are able to reboot into BIOS, you can obtain some info there through KVM console, atleast RAM size, CPU and disks are available there usually. If you wanna extended information, you can boot from some LiveCD by mounting virtual image in KVM
Comment: Thanks for the info, will go at it.


FIREBASE: getting null while fetching the data from database

Question:
Attached is the firebase db structure screenshot.

I want to get the data using node script. below is my code.

var db = admin.database();
var ref = db.ref("test/name");

console.log(ref)

ref.on("value", function(snapshot) {
    console.log("==========");
  console.log(snapshot.val());
}, function (errorObject) {
  console.log("The read failed: " + errorObject.code);
});

console.log(snapshot.val()); always print null
Below is the result of  console.log(ref)
path: Path { pieces_: [ 'test', 'name' ], pieceNum_: 0 },
  queryParams_: QueryParams {
    limitSet_: false,
    startSet_: false,
    startNameSet_: false,
    endSet_: false,
    endNameSet_: false,
    limit_: 0,
    viewFrom_: '',
    indexStartValue_: null,
    indexStartName_: '',
    indexEndValue_: null,
    indexEndName_: '',
    index_: PriorityIndex {}
  },

What is the issue in the code?
referring this document:  https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot
Answer: You are using firestore but your code is for the realtime database, you need to change the code to the following:
var db = admin.firestore();
var ref = db.doc("test/name");

console.log(ref)

let getDoc = ref.get()
  .then(doc => {
    if (!doc.exists) {
      console.log('No such document!');
    } else {
      console.log('Document data:', doc.data());
    }
  })
  .catch(err => {
    console.log('Error getting document', err);
  });

https://firebase.google.com/docs/firestore/query-data/get-data


Adding new Gender Profile Info in Wowonder

Question: im using a Wowonder script Social network and i want to add Unspecified gender in my profile settings but it shows error on my page.
<?php
$gender = ucfirst(strtolower($wo['user_profile']['gender'])); echo ($gender == 'Male') ? $wo['lang']['male'] : $wo['lang']['female'] : $wo['lang']['unspecified'];
?>

Thank you
Comment: `echo ($gender == 'Male') ? $wo['lang']['male'] : (($gender == 'Female') ? $wo['lang']['female'] : $wo['lang']['unspecified']);`
Answer: Here I post it as a answer:
echo ($gender == 'Male') ? $wo['lang']['male'] : (($gender == 'Female') ? $wo['lang']['female'] : $wo['lang']['unspecified']);

Comment: hello when im going to add another gender seems it didnt work this is the code
echo ($gender == 'Male') ? $wo['lang']['male'] : ($gender == 'Female') ? $wo['lang']['female'] : (($gender == 'Dragon') ? $wo['lang']['dragon'] : $wo['lang']['princess']);
Comment: `echo ($gender == 'Male') ? $wo['lang']['male'] : (($gender == 'Female') ? $wo['lang']['female'] : (($gender == 'Dragon') ? $wo['lang']['dragon'] : $wo['lang']['princess']))`


AddTransient won't draw image AutoCAD 2023 .net c#

Question: I want to draw a transient line by a specific distance when I hover over another line, but when I use the method ctm.AddTransient(line, AcGi.TransientDrawingMode.Main, 128, ints), it is not drawing any transient line. In another code I am using the method with block references as ctm.AddTransient(bref, AcGi.TransientDrawingMode.DirectShortTerm, 128, ints) and it works without problems.
Now I am working on a code which I changed some parts from another source in order to understand how I can achieve my goal.
I have used both AcGi.TransientDrawingMode.Main and AcGi.TransientDrawingMode.DirectShortTerm modes, tried to change the transient line's coordinates to a fixed coordinate and added the method ctm.UpdateTransient(bref, ints) to the code in order to find a solution but none of them worked.
Here is the full code for you to examine. I am a newbie so please be more specific about your suggestions and I will try to understand them as much as I can. Thank you for your help.
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using System;
using AcGi = Autodesk.AutoCAD.GraphicsInterface;

public class PointMonitorTooltips

{

    [CommandMethod("SM")]

    public static void StartMonitor()

    {

        Editor ed =

          Application.DocumentManager.MdiActiveDocument.Editor;

        ed.PointMonitor +=

          new PointMonitorEventHandler(ed_PointMonitor);

    }

    [CommandMethod("XM")]

    public static void StopMonitor()

    {

        Editor ed =

          Application.DocumentManager.MdiActiveDocument.Editor;

        ed.TurnForcedPickOn();

        ed.PointMonitor -=

          new PointMonitorEventHandler(ed_PointMonitor);

    }

    static void ed_PointMonitor(object sender, PointMonitorEventArgs e)
    {
        Editor ed = (Editor)sender;

        AcGi.TransientManager ctm = AcGi.TransientManager.CurrentTransientManager;

        IntegerCollection ints = new IntegerCollection(new int[] { });

        try
        {
            FullSubentityPath[] paths = e.Context.GetPickedEntities();

            // Open a transaction to create the transient line
            using (Transaction tr = ed.Document.TransactionManager.StartTransaction())
            {
                foreach (FullSubentityPath path in paths)
                {
                    ObjectId[] ids = path.GetObjectIds();

                    if (ids.Length > 0)
                    {
                        ObjectId id = ids[ids.GetUpperBound(0)];

                        // Get the entity
                        Entity ent = (Entity)tr.GetObject(id, OpenMode.ForRead);
                        Type objtype = ent.GetType();

                        // Create a transient line based on the entity's position and orientation
                        if (objtype == typeof(Line))
                        {

                            Line linecoor = (Line)ent.Clone();

                            Point3d start = linecoor.StartPoint;
                            start = start.Add(new Vector3d(5.0, 5.0, 0.0));

                            Point3d end = linecoor.EndPoint;
                            end = end.Add(new Vector3d(5.0, 5.0, 0.0));

                            Line line = new Line(start, end);

                            // Add the transient line
                            ed.WriteMessage("\nAdding transient line..."); // This part constantly sending messages

                            ctm.AddTransient(line, AcGi.TransientDrawingMode.Main, 128, ints); // This is the part that is not working
                        }
                    }
                }

                tr.Commit();
            }
        }

        catch
        {
            // Exception handling code here
        }

    }

}

Answer: I just had a similar problem myself. Take a look at these two test clasess:
public class TestCommand1
{
    private DBObjectCollection _markers = new DBObjectCollection();
    private IntegerCollection intColl = new IntegerCollection();

    [CommandMethod("TempMarker1")]
    public void TestTransient1()
    {
        try
        {
            var locationDrawing = new Point3d(0, 0, 0);
            var circleMarker = new Circle(locationDrawing, Vector3d.ZAxis, 5) { ColorIndex = 1 };
            TransientManager.CurrentTransientManager.AddTransient(circleMarker, TransientDrawingMode.DirectTopmost, 128, intColl);
            _markers.Add(circleMarker);
        }
        catch (Exception ex)
        {
            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message);
        }
    }
}

and
public class TestCommand2
{
    private DBObjectCollection _markers = new DBObjectCollection();
    private IntegerCollection intColl = new IntegerCollection();

    [CommandMethod("TempMarker2")]
    public void TestTransient2()
    {
        try
        {
            var locationDrawing = new Point3d(10, 10, 0);
            var circleMarker = new Circle(locationDrawing, Vector3d.ZAxis, 5) { ColorIndex = 1 };
            TransientManager.CurrentTransientManager.AddTransient(circleMarker, TransientDrawingMode.DirectTopmost, 128, intColl);
        }
        catch (Exception ex)
        {
            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message);
        }
    }
}

You will notice that the only difference between the two examples is that the first one adds circle object into a collection and thus keeps a reference to the object created. In the second example circle is only added to TransientManager.
When you start these commands in AutoCAD you will see this:

For the first example - circle object persists in the drawing after
added.
For the second example - object appears only for a second and    then
it disappears.

So my guess is this is related to garbage collector mechanism.


How can i merge two array into a single array?

Question: In my second array I have some value in comma separated and I explode these values and create new array.  Now I'm trying to add these two arrays:
<code>(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => 0
                    [1] => 0
                    [2] => 1
                    [3] => 0
                )

            [1] => Array
                (
                    [0] => 1
                    [1] => 0
                    [2] => 0
                    [3] => 0
                )

        )

    [1] => Array
        (
            [qid] => 1
            [question] => here is the first question
            [answer1] => ans1
            [answer2] => ans2
            [answer3] => ans3
            [answer4] => ans4
            [correct_answer] => 0,0,1,0
            [creadted_date] => 2015-01-16
        )

    [2] => Array
        (
            [qid] => 2
            [question] => here is the second ques
            [answer1] => ans1
            [answer2] => ans2
            [answer3] => ans3
            [answer4] => ans4
            [correct_answer] => 1,0,0,0
            [creadted_date] => 2015-01-16
        )

)
</code>
Like this:
<code> [1] => Array
        (
            [qid] => 1
            [question] => here is the first question
            [answer1] => ans1
            [answer2] => ans2
            [answer3] => ans3
            [answer4] => ans4
            [c1] => 0
            [c2] => 0
            [c3] => 1
            [c4] => 0
            [correct_answer] => 0,0,1,0
            [creadted_date] => 2015-01-16
        )
[2] => Array
        (
            [qid] => 1
            [question] => here is the first question
            [answer1] => ans1
            [answer2] => ans2
            [answer3] => ans3
            [answer4] => ans4
            [c1] => 0
            [c2] => 0
            [c3] => 1
            [c4] => 0
            [correct_answer] => 0,0,1,0
            [creadted_date] => 2015-01-16
        )
</code>
Comment: have you tried anything? have you looked into a good php book? have you ever heared of array_merge?
Comment: So what's the problem exactely? You can easily merge arrays using `array_merge()`.
Comment: i'm new in php. that's why i'm having problem
Comment: if you are new then get a book/tutorial/lesson and refrain from using SO for this kind of stuff...
Answer: array_merge() ought to do the job.
Based on your example, this should do the trick:
<code>array_merge(array[1],array[0][0]);
array_merge(array[2],array[0][1]);
</code>
Answer: Have you taken a look at the php function array_merge
http://php.net/manual/en/function.array-merge.php
also, It might help to see some code as to how you are getting this multidimensional array


Are there derivatives of the following functions or not? Justify your answer. In the case of a positive answer and calculate the derivatives.

Question:
Are there derivatives of the following functions or not? Justify your answer. In the case of a positive answer and calculate the derivatives.

a) $f:(a,b) \to \mathbb R, f(x) = \frac{1}{x-a}$. Calculate $f'(a)$ if it exists.

b)$f: X \to \mathbb R, X={(-1)^n \frac{1}{n}; n \in \mathbb N} \cup {0}, f(x) = x$. Calculate $f'(0)$ if derivative exists.

what i managed to do
a) Yes. $\frac{d}{da}[\frac{1}{x-a}]= - \frac{\frac{d}{da}[x-a]}{(x-a)^2}= - \frac{\frac{d}{da}[x] - \frac{d}{da}[a]}{(x-a)^2}= - \frac{0 – 1}{(x-a)^2}= - \frac{1}{(x-a)^2}$
b)$\frac{\frac{d}{dx}[(-1)^x] x - (-1)^x \frac{d}{x}[x]}{x^2} = \frac{ln (-1)(-1)^x x - (-1)^x1}{x^2}=\frac{ln(-1)x(-1)^x - (-1)^x}{x^ 2}$ for $x = 0$ we have $\lim_{x \to 0}\frac{ln(-1)x(-1)^x - (-1)^x}{x^2}$ does not exist.
Are the answers correct?
Thanks.
Comment: Assuming that $(a,b)$ means $\{t \text{ real}: a<t<b\}$, I think we should consider $f(a)$ and also consider the definition of $f'(a)$
Answer: I think that before starting any computation, you should come back to the definition.
Question a $f$ is not even defined at $a$. So it does not make sense to speak of its derivative at $a$. Regarding your answer, you're confusing $a$, which is a parameter of the map $f$, and $x$, which is the variable. In fact, it would be better to define $f_a(x) = \frac{1}{x-a}$.
Question b is tricky... To define continuity and derivability at a point $x_0 \in X$, you need to have a topology defined on $X$ and $x_0$ should belong to an open subset $U \subseteq X$. Even if you endow $X$ with the usual distance inherited from the one of $\mathbb R$, $X$ doesn't contain any open subset. Hence you can't speak of the derivative of $f$ at any point and $0$ in particular.


Determinant of a matrix?

Question: Can somebody please help me check the solutions to these 2 questions because I do not have the answers to them in my notes:
The determinant of the following matrix:
$$
\begin{pmatrix}
4&0&1\\19&1&-3\\7&1&0
\end{pmatrix}
$$
is
$$0 + 0 +19 - 7-0-(-12) = 24$$
and the determinant of
$$
\begin{pmatrix}
0&2&0\\3&0&4\\2&3&0
\end{pmatrix}
$$
is
$$0+16+0-0-0-0 = 16$$
Comment: yes, your computations are both correct.
Comment: Tip: [http://www.wolframalpha.com/input/?i=determinant+of+{{4%2C0%2C1}%2C{19%2C1%2C-3}%2C{7%2C1%2C0}}](http://www.wolframalpha.com/input/?i=determinant+of+{{4%2C0%2C1}%2C{19%2C1%2C-3}%2C{7%2C1%2C0}})
Answer: Yes, both answers are correct.  In the future it might be quicker to use sage or Wolfram Alpha to check things like this.

Determinant of a matrix?


Trying to access cart items using foreach in a plugin but getting critical error on edit and setting pages in admin wordpress

Question: I'm using Dokan-woocommerce-wordpress.
trying to access the vendor ID of items added in cart, using foreach inside a plugin file.
// Get Vendor UPI ID and Murchant Code
        global $woocommerce;
        $items = $woocommerce->cart->get_cart();

        foreach( $items as $my_cart_item ){
            $my_product_id = $my_cart_item['product_id'];
        }

        $vendor_id = get_post_field( 'post_author', $my_product_id );
        $store_details = get_user_meta($vendor_id, 'dokan_profile_settings');
        $upi_id = $store_details[0]['vendor_upi_id'];
        $murchant_code = $store_details[0]['vendor_upi_murchant_code'];

The above code is giving the desired output but something from here is causing critical error and "edit" pages not opening in wordpress admin.

This is the error log msg
PHP Warning:  Invalid argument supplied for foreach() in /home3/cardocte/public_html/shreeroyals.com/wp-content/plugins/upi-qr-code-payment-for-woocommerce/includes/payment.php on line 57

Please suggest any solution for it.
Comment: There has been a critical error on this website. **Please check your site admin email inbox for instructions.** What is in that email or in the error log files?
In any case what causes the problem and therefore the shortest way to the solution.
In short, important information that is missing in your question.
Comment: Thanks @7uc1f3r for indicating, I've updated the question with error log msg
Comment: Where do you execute this stuff?
Comment: I'm executing above code inside a plugin file. Its a QR code based payment plugin
Answer: I found a solution. It seems that get_cart() causes problems if it is executed in the admin area so wrapping the above snippet in conditional: if( ! is_admin() ) { } fixed the issue for me.


Maven/Nexus password with euro sign problem

Question: We have a user that's unable to connect from Maven to Nexus, because it always receives a "Not authorized" error, and we found out that his password has a € (euro sign).
During my analysis and tests to find out how I could set the password correctly in Maven's settings.xml, I tested the following alternatives with the password being 123456€

password in plain text

<password>123456€</password>
<password>"123456€"</password>
<password>'123456€'</password>
<password><![CDATA[123456€]]></password>

encrypted the password using the following alternatives

mvn -ep 123456€
mvn -ep "123456€"
mvn -ep '123456€'
also used mvn -ep only and then typed all 3 variants

and in all these tests I was unable to download the artifact from Nexus.
Is this a Maven or Nexus problem? and how can I overcome it?
Comment: You usually call `mvn -ep` and type your password interactively (not giving on command line) ... there is printed out some thing like `{.....}` which  you have to copy at the position `{...}`... not in plain text etc. ...
Comment: yes @khmarbaise, that's what almost all of our users do, and that was my first try when analyzing the situation. That's the 4th example that I put on the original question of the encrypted tries part.
Comment: The problem seemed to be that the euro symbol is from a specific code page (ISO-8859-15 ? If I correctly remember (https://en.wikipedia.org/wiki/ISO/IEC_8859-15)) which I suppose is not the same as the system is running on neither the System which Maven hosts nor the system on which Nexus is running furthermore it depends on the OS (Windows, Mac, Linux etc.) .... so I doubt that this will ever run... I think the same will happen with german umlauts like äöü etc. cause they belong to ISO-8859-1 (https://en.wikipedia.org/wiki/ISO/IEC_8859-1) I would go for the path as J Fabian Meier suggested.
Answer: Actually, I would solve this problem by saying that passwords need to consists of a-z, A-Z, 1-9 and maybe some well-defined other symbols as -_/().


Does dimension reduction always lose some information?

Question: Like the title says, does dimension reduction always lose some information? Consider for example PCA. If the data I have is very sparse, I would assume a "better encoding" could be found (is this somehow related to the rank of the data?), and nothing would be lost.
Comment: No, of course not: some of the singular values in PCA can be true zeros, for instance. This is less related to the "sparseness" of the data than it is to whether they "fill out" the dimensions used to record them.
Comment: Ok, I see. Could you write your comment as a short answer (maybe even with a small example, if you have time)?
Comment: Consider the case where you have two dimensional data, where the y-value for each point is '0'. Your first principle component will be the X axis, and you won't lose anything by projecting your data down into this single dimension because it's effectively one dimensional already.
Answer: Dimensionality reduction does not always lose information. In some cases, it is possible to re-represent the data in lower-dimensional spaces without discarding any information.
Suppose you have some data where each measured value is associated with two ordered covariates. For example, suppose you measured signal quality $Q$ (indicated by color white=good, black=bad) on a dense grid of $x$ and $y$ positions relative to some emitter. In that case, your data might look something like the left-hand plot [*1]:

It is, at least superficially, a two dimensional piece of data: $Q(x,y)$. However, we might know a priori (based on the underlying physics) or assume that the it depends only on the distance from the origin: r = $\sqrt{x^2 + y^2}$. (Some exploratory analysis might also lead you to this conclusion if even the underlying phenomenon isn't well understood). We could then rewrite our data as $Q(r)$ instead of $Q(x,y)$, which would effectively reduce the dimensionality down to a single dimension. Obviously, this is only lossless if the data is radially symmetric, but this is a reasonable assumption for many physical phenomena.
This transform $Q(x,y) \rightarrow Q(r)$ is non-linear (there's a square root and two squares!), so it is somewhat different from the sort of dimensionality reduction performed by PCA, but I think it's a nice example of how you can sometimes remove a dimension without losing any information.
For another example, suppose you perform a singular value decomposition on some data (SVD is a close cousin to--and the often the underlying guts of--principal components analysis). SVD takes your data matrix $M$ and factors it into three matrices such that $M = USV^{T}$. The columns of U and V are the left and right singular vectors, respectively, which form a set of orthonormal bases for $M$. The diagonal elements of $S$ (i.e., $S_{i,i})$ are singular values, which are effectively weights on the $i$th basis set formed by the corresponding columns of $U$ and $V$ (the rest of $S$ is zeros). By itself, this doesn't give you any dimensionality reduction (in fact, there are now 3 $NxN$ matrices instead of the single $NxN$ matrix you started with). However, sometimes some diagonal elements of $S$ are zero. This means that the corresponding bases in $U$ and $V$ aren't needed to reconstruct $M$, and so they can be dropped. For example, suppose the $Q(x,y)$ matrix above contains 10,000 elements (i.e., it's 100x100). When we perform an SVD on it, we find that only one pair of singular vectors has a non-zero value [*2], so we can re-represent the original matrix as the product of two 100 element vectors (200 coefficients, but you can actually do a bit better [*3]).
For some applications, we know (or at least assume) that the useful information is captured by principal components with high singular values (SVD) or loadings (PCA). In these cases, we might discard the singular vectors/bases/principal components with smaller loadings even if they are non-zero, on the theory that these contain annoying noise rather than a useful signal. I've occasionally seen people reject specific components based on their shape (e.g., it resembles a known source of additive noise) regardless of the loading. I am not sure if you would consider this a loss of information or not.
There are some neat results about the information-theoretic optimality of PCA. If your signal is Gaussian and corrupted with additive Gaussian noise, then PCA can maximize the mutual information between the signal and its dimensionality-reduced version (assuming the noise has a identity-like covariance structure).

Footnotes:

This a cheesy and totally non-physical model. Sorry!
Due to floating point imprecision, some of these values will be not-quite-zero instead.
On further inspection, in this particular case, the two singular vectors are the same AND symmetric about their center, so we could actually represent the entire matrix with only 50 coefficients. Note that the first step falls out of the SVD process automatically; the second requires some inspection/a leap of faith. (If you want to think about this in terms of PCA scores, the score matrix is just $US$ from the original SVD decomposition; similar arguments about zeros not contributing at all apply).
Comment: +1: the edits make your points much clearer.  Thanks for the extra effort!
Comment: Matt, my question really amounted to this: you show us a picture without any description or reference and refer to it as "data": I would like to know in what sense you are thinking of it as data. Your comment confuses this issue, because a "heat map" representation is usually *not* data, but is something created out of data. If those were irregular 2D point data, for instance, and you fit a radially symmetric density to them, then the *picture* could be construed as one-dimensional, as you argue, but it would not be a lossless dimensionality reduction of the *data*.
Comment: Perhaps I should have said 'gridded' or 'raster' instead. I was imagining a situation where data are collected on a grid and each grid points is associated with a (scalar) value, but the values are not necessarily light intensity as in a (photographic) image. That said, I am clearly not rocking this answer--let me try editing it into something more coherent!
Comment: I don't think your graph is right. 1) It's an ellipse not a circle, so $I(r)$ will change based on the angle with the axes. But this may be an artifact. 2) A PCA where some of the eigenvalues are 0 indicates collinearity in the data; this would be a plot that's a straight line, not a spherical bump. 3) In real life, data is never perfectly symmetrical anyway.
Comment: In particular, note that $r = \sqrt{(x^2 + y^2)}$ in your example. This is a _nonlinear_ combination of the variables, so it isn't relevant when talking about PCA (which would detect _linear_ combinations in the data).
Comment: Matt, your non-linear example is intriguing and seems like it might shed some light on the matter.  But in what sense is your "bump" a "piece of data"? Do you mean it literally in that as a *raster image* it is a 2D array of intensity values? @Hong (1) it only *looks* elliptical due to a distorted aspect ratio. (2) This answer only compares PCA to the "bump" ("similarly"); it does not claim they are the same. (3) "In real life," data don't line up perfectly on linear subspaces, either.
Comment: @HongOoi, it's an artifact--the aspect ratio got distorted. You're correct that $I(x,y) \rightarrow I(r)$ is a non-linear transformation. However, it *is* a form of dimensionality reduction, and in many cases, a fairly intuitive one (absolute position $\rightarrow$ distance from some epicenter). It wasn't clear to me if the OP was interested in dimensionality reduction generally or just PCA. Finally, I'd suggest that this transform is very realistic for real-world data: LOTS of phenomena vary with distance from a point (maybe more than from linear subspaces? :-))
Comment: @whuber, it could be anything! This obviously works really well for spatial data, whether it's an actual image or a heat map-like representation (e.g., pollutant concentration per location). I've recently had some luck with this approach where the axes were not positions per se but the "distance" value still had a reasonable interpretation.
Answer: I think the question behind your question is "what makes information?".  It is a good question.
Grammar technicality:
Does PCA always lose information?  Nope. Does it sometimes lose information?  Youbetcha.  You can reconstruct the original data from components.  If it always lost information then this would not be possible.
It is useful because it often does not lose important information when you use it to reduce dimension of your data.  When you lose data it is often the higher frequency data and often that is less important.  The large-scale, general trends, are captured in the components associated with the larger eigenvalues.
Answer: No.  If one or more of the dimensions of an $n \times p$ matrix are a function of the other dimensions, the appropriate dimension reduction technique will not lose any information.
In the most straightforward case, if one dimension is a linear combination of the others, reducing the dimensionality by one can be done without losing any information - because the dropped dimension could be re-created if necessary from what is left.
Consider this three dimensional case where x3 is an exact linear combination of x1 and x2.  It's not obvious from eyeballing the original data, although it's clear x3 is related to both the other two:

But if we look at the principal components, the third is zero (within numerical error).

The plot of the first two principal components is the same as the plot of x1 against x2, just rotated (ok, not as obvious I meant, I'll try to explain better later):

We've reduced the dimensionality by one yet kept all the information, by any reasonable definition.
This extends beyond linear dimension-reduction too, although naturally gets more complex to illustrate.  The point is that the overall answer is "no", not when some of the dimensions are functions of a combination of the others.
R code:
<code>library(GGally)

n <- 10^3
dat <- data.frame(x1=runif(n, 0, 3), x2=rnorm(n))
dat$x3 <- with(dat, x1 + x2)

ggpairs(dat)

pc <- princomp(dat)
plot(pc)

par(mfrow=c(1,2))
with(dat, plot(dat$x1, dat$x2, col="red", main="Original data", bty="l"))
with(pc, plot(scores[,1], scores[,2], col="blue", main="Scores from principal components(\n(rotated)", bty="l"))
</code>


Inequality involving Alternating Sequence

Question: Suppose a > $\frac{1}{2}$. I would like to show that:
\begin{equation}
\sum_{r=0}^m (-1)^{m-r} {m \choose r} \frac{1}{q-r} \left(a^{q-r} -\frac{1}{2^{q-r}}\right) \geq 0.
\end{equation}
Splitting my head on this. Would appreciate any help on this.
Answer: Let $$f(x)=\sum_{r=0}^m (-1)^{m-r} {m \choose r} \frac{1}{q-r} x^{q-r}$$
We need to show that $f(a)\geq f(\frac 1 2)$.
Then $$f^\prime(x)=\sum_{r=0}^m (-1)^{m-r} {m \choose r} x^{q-r-1}=x^{q-1}\left(\frac 1 x - 1\right)^m=x^{q-m-1}\left(1-x\right)^m$$
Thus $f^\prime(x)\geq0$ for $0\leq x \leq 1$. Consequently $f$ is non-decreasing and $f(a)\geq f(\frac 1 2)$ if $a\leq 1$.
Comment: Thanks. Should that be (1-x)^m?
Comment: Absolutely, thanks for catching this.
Comment: @StefanLafon More likely, $x^{q-m-1}(x-1)^m$. With $(1-x)^m$ the derivative is not always positive either.