Select sum case in SQL Server 2008 R2

Question: I have this problem: a query with iif (instead of CASE below) function works in MS Access doesn't work anymore in SQL Server 2008 R2:
SELECT
    t1.id, t1.quantity as q1,
    (SELECT sum(t2.quantity) where t2.id=t1.id FROM table2 as t2) as sumQuantity,
    (CASE sumQuantity IS NULL then 0 ELSE sumQuantity) as sumQuantityOk
FROM
    table1 as t1

The error is

invalid sumQuantity column name

Without CASE (or with iif in MS ACCESS) the query is ok.
Answer: Replace
CASE sumQuantity IS NULL then 0 ELSE sumQuantity

with
CASE when sumQuantity IS NULL then 0 ELSE sumQuantity end

or use coalesce instead
coalesce(sumQuantity, 0)

Comment: I actually wrote as you said but I get that error. I think there's something with the SUM that doesn't work with CASE the way I think. I also tried COALESCE but same error. Thank you anyway.
Comment: Ah my bad. Did not notice it. You can't use alias column names in the `select` clause or  `where` clause.
Comment: No, you're right, here I wrote from my memory but in the real code I wrote as you said. But I don't understand what do you mean by "you can't use alias column names...". I can use alias in the SELECT like this: "SELECT table.column as aliasColumn".
Comment: You make a subselect and name the result of that select `sumQuantity`. But now you can not use this name in the same `select` clause. Or in a `where` clause. You have to write that statement up again.
Comment: ah, ok. I thought the problem could be this. But how it works in MS Access ? Maybe because the database engine is different. Thanks again. I will sign the question as "Answered" hoping that it works with your answer.

Select sum case in SQL Server 2008 R2


Graph Automorphisms and Induced Subgraphs

Question: Let $G=(V,E)$ be a finite simple graph, $\Gamma=Aut(G)$ be the automorphism group of $G$, and $G_v=G-\{v\}$ be a vertex-deleted induced subgraph of $G$. We define the following equivalence relation on the vertices,
$u,v\in V: u\sim v \iff G_u\cong G_v$
(I will forego proving that this is an equivalence as it seems trivial. If someone would like further clarification please let me know.) This equivalence partitions $V$ such that,
$V=\displaystyle\bigcup_{i=1}^k V_i$
We know that $u\sim v$ is a necessary condition for $u$ and $v$ to lie in the same orbit under $Aut(G)$ (i.e. these equivalence classes are larger than the orbits of $V$ under $\Gamma$).

Can we recover some information about $\Gamma$ given the equivalence classes under $\sim$?

It is clear that a partition of $V$ into orbits under $\Gamma$ will be a refinement of the partition. Also, we have an obvious upper bound $\Gamma\le S_{|V|}$. It seems that the "easier case" is when there are many vertices with distinct equivalence classes (i.e. the graph is not very symmetric).
Comment: A first natural question in this direction is (analogous as for the orbits) whether almost all graphs have a trivial partition under $\sim$. If this is true (which I'd say it is) then there is not much you can say in general if you're given $\sim$
Comment: @Joseph Zambrano: What do you mean by "some information"? Dou you have something specific in mind? What is the context of your question?
Comment: @Jernej Your assertion is almost certainly true (at least to me) but that still leaves "a lot" of graphs.
Comment: @Moritz Maybe I should clarify - if the partition is in fact the partition given by orbits then what can be said of $\Gamma$? If not, then is there a particular obstruction to the existence of an automorphism between two points which are equivalent under the relation?
Answer: The multiset of isomorphisms types (equivalence classes in your question) induced by the removal of every single vertex is called the deck of $G$. Certainly, "some information" can be recovered from the deck. For example, in a number of special cases (classes of graphs), we know that $G$ can be reconstructed unambiguously from its deck. Thus, a fortiori, $\Gamma$ as well (from $G$). Whether this is true in general is not known and is referred to as the reconstruction conjecture [1].
In fact, the reconstruction conjecture is at least as strong as your question, since the reconstruction of $G$ yields that of $\Gamma$. Whether the converse holds is not clear to me (can we determine $G$ from $\Gamma$ and from the deck?). For sure, some information can be recovered from the deck that helps ruling out some automorphisms, e.g. the degree of every vertex and a few other such parameters are known to be determined unambiguously by the deck.
[1] https://en.wikipedia.org/wiki/Reconstruction_conjecture
Comment: This question is quite old, but I believe to motivation behind it was exactly what you noted in your answer - "the reconstruction conjecture is at least as strong as your question". At the time I was looking at algebraic analogs of the reconstruction conjecture.  Thanks for answering!


How to change slider widget price range text and "Go" label in KickStart Commerce?

Question: How to change slider widget price range text and "Go" label in KickStart Commerce?
Want to remove "range from...." and change "Go" on the button to Russian "Найти".
What Drupal display view or template, page or module to change? Thank you (see fig. attached, please).
Answer: Below is a work around. See if it works :

Create a file custom_string_overrides.inc  inside your custom module folder and add the below code:

$conf['locale_custom_strings_en'][''] = array(
  'Go' => 'Add replacement here',
  'range from' => 'Add replacement here',
);

Add the below code to settings.php

include DRUPAL_ROOT . '/path-to-module/custom_string_overrides.inc';
The above trick does the string replacement and texts will be replaced where ever they appear. As I mentioned, this is just a workaround.


ex (vim) adds an extra space character to empty lines

Question: I would like to do some processing with ex (vim in ex/silent mode). There is however a strange behaviour if a line is empty. An extra space character is added to that line - even in binary mode. Is it possible to eliminate that?
Check out:
$ printf "a\n1st\n\n3rd\n.\n%%p\n" | ex -b | hexdump -C
00000000  31 73 74 0a 20 0a 33 72  64 0a

Note the Ex rows in printf: a for appending text, three rows, . to close append mode, %p to print everything)
a
1st

3rd
.
%p

The expected result is
00000000  31 73 74 0a 0a 33 72 64  0a

Comment: It looks like you have a space on that supposedly empty line. Doing the same manually doesn't give me that extra space, though.
Comment: @romainl, Actually, no. You can see in `printf` that there is no space between the two `\n`. And if I simply save the output, this space does not appear, only if I use `:print` or `:list`. So this might be an internal issue of representation.
Answer: printf doesn't seem to be where that extra space comes:
$ printf 'a\n1st\n\n3rd\n.\n%%p\n' | hexdump -C
00000000  61 0a 31 73 74 0a 0a 33  72 64 0a 2e 0a 25 70 0a |a.1st..3rd...%p.|
00000010

ex doesn't seem to be involved either, at least used in a somewhat more "normal" way:
$ printf "a\n1st\n\n3rd\n.\nwzob\nq\n" | ex | hexdump -C zob
00000000  31 73 74 0a 0a 33 72 64  0a                       |1st..3rd.|
00000009

but you are not using ex that way. You are somehow making a kind of screen dump to stdout, which might explain the appearance of that space.
Without knowing what you are actually trying to do it is hard to provide a better solution. In any case, being a full screen document-oriented program, ex is generally not suited for use in a pipe so you might want to look for a different approach.
Comment: Thanks, actually my environment is rather complex and I would like to use internal commands to print parts of the text. I know that this is not an intended way how to use vim/ex.
And yes, it seems that those spaces are added by `print` and `list` commands or they are there in the internal representation for some reason and they are not removed by these commands (only when creating real output).


States on the reduced group $C^\ast$-algebra of $\mathbb{F}_2$

Question: Consider the reduced group $C^\ast$-algebra $C_{\text{r}}^\ast (\mathbb{F}_2)$ of the free group in two generators $a$ and $b$. Further, let $\phi$ be a state on $C_{\text{r}}^\ast (\mathbb{F}_2)$. Let $(g_i)_i \subseteq \mathbb{F}_2$ be a sequence of group elements for which the word length (with respect to the generators $a$ and $b$) of $g_i$ is equal to $i$. Is it then true that $\phi(\lambda_{g_i}) \rightarrow 0$ for $i\rightarrow \infty $? Here $\lambda$ denotes the left-regular representation of $\mathbb{F}_2$. The statement looks kind of obvious, but I don't see how to prove it.
Answer: The answer is no.
Let $A$ be the closed *-subalgebra of $C_{\text{red}}^*(\mathbb F_2)$ generated by $\lambda _a$.  It is easy to see that $A$
is isomorphic to $C(S^1)$, the continuous functions on the unit circle, via an isomorphism that maps $\lambda _a$ to the identity
function "$f(z)=z$".
Consider the state $\varphi $ (actually a character) of $A$ defined by
$$
  \varphi :g\in A\mapsto g(1)\in {\mathbb C}.
  $$
By a well known result, $\varphi $ extends to a state, say $\tilde\varphi $,  of $C_{\text{red}}^*(\mathbb F_2)$.
Setting $g_n = a^n$, one has that the word length of $g_n$ is $n$, but
$$
  \tilde \varphi (\lambda _{g_n}) = \varphi (\lambda _a^n) = z^n|_1 = 1,
  $$
which doesn't converge to zero.


How do I init every parent method before init?

Question: I have a custom bootstrap class and I'm extending it.
<code>class Bootstrap extends MyBootstrap
{

}
</code>
MyBootstrap.php class have some _init methods. I need it to load all MyBootstrap methods first. How to?
Answer: Try something like this inside the Bootstrap class:
<code>$methods = get_class_methods ('MyBootstrap');
foreach ($methods AS $method) {
    if (str_pos ($method, '_init') !== false) {
        call_user_func (array ($this, $method));
    }
}
</code>
get_class_methods - returns the class methods' names. Then look for methods like '_init' and run them.
Comment: Isn't there something more consistent?
Comment: Nothing I would be aware of. Only other way is to call each method manually but I guess this is not what you are looking for.


Suppressing/Catching the ValidationError error from Mongoose

Question: I have a static method setup that will verify if an object follows the schema of the model properly, and I've got the validation itself working just fine, but I can't get Mongoose to hide the ValidationError error that displays in the console.
The static method for the validation is:
fieldSchema.statics.testValidate = function( field ) {
    return new Promise( ( res, rej ) => {
        new this( field ).validate( err => {
            if ( err ) return rej( err )

            res( true )
        } )
    })
}

Then when I execute it:
Field.testValidate( fieldData )
    .then(data => {
        console.log('OK!', data)
    })
    .catch( err => {
        console.error('FAILED:',err)
    })
    .finally(() => Mongoose.connection.close())

And like I said, I can get it to validate the data, but it will always show this error:
Unhandled rejection ValidationError: Field validation failed
    at MongooseError.ValidationError ....

(Note: Im using Bluebird for my JS promises, incase it has anything to do with the then/catch somehow)
The script execution keeps going on with the code, so that means that it doesnt actually kill the script or anything, it just logs the error to the console. But since this function is meant to validate, its not really an "error", so is there a way to hide this from the console? (Just for this function, not for ALL Mongoose errors)
Thanks
Answer: validate already returns a promise so you don't need to wrap it in a new promise. The reason you see the error logged to the console is because of the fact that you're wrapping it in a new promise thus preventing the original promise from ever being caught i.e. Unhandled rejection.
fieldSchema.statics.testValidate = function(fieldData) {
    return new this(fieldData).validate()
}


Prove lemma: order of $x\ \mathrm{mod}\ N$ is even with probability $1/2$

Question: In the book Algorithms by Vazirani et al., a simple lemma is stated without proof:

Let $N$ be an odd composite, with at least two prime factors, and let $x$ be chosen uniformly at random between $0$ and $N-1$. If $\gcd(x,N)=1$, then with probability at least $1/2$, the order $r$ of $x \mod N$ is even.

Note: the order $r$ of $x$ modulo $N$ is the smallest positive integer $r$ such that $x^r \equiv 1\ \mathrm{mod}\ N$.
I've been trying to prove this, to no avail. The only hints I am given is that it may entail Fermat's Little Theorem or the Chinese Remainder Theorem.
A proof, a sketch of a proof, or even a reference to one would be appreciated.
Comment: Hint 1: Well, if the order of $a \mod p$ for prime $p$  is $n$ and the order of $a \mod q$ for prime $q$ is $m$ then the order of $a \mod pq$ is the least common factor of $n$ and $m$.  Hint 2: the non-zero equivalence classes modulo a  prime form a cyclic group under multiplication.
Comment: Just checking: do you mean "least common multiple"?
Comment: Yes I did mean multiple.
Answer: Let $1 \le x \le N - 1$ and $\gcd(x, N) = 1$. If $x$ has odd order $2m+1$, then $-x$ has even order $2(2m+1)$. So for every odd-order $x$, there's a unique corresponding $-x$ of even order. So the number of even-order elements is at least half.
Proof that $-x$ has order $2(2m+1)$. This is a special case of the fact that if $a$ and $b$ are elements of an abelian group with order $m$ and $n$ respectively and $\gcd(m,n)=1$, then $ab$ has order $mn$.
Here is the proof of the order of $-x$. Let $n$ be the order of $-x$.
Then $1 = (-x)^n = (-1)^nx^n$. Consider 2 cases: $n$ is odd or $n$ is even.
If $n$ is odd, then $x^n = -1$, $x^{2n} = 1$, which implies $2m+1$ divides $2n$, and hence $2m+1$ divides $n$. So $x^n = 1 = -x^n = -1$, which means $2 = 0 \mod N$. This is impossible since $N$ is odd.
If $n$ is even, then $1 = (-x)^n = x^n$, which implies that $2m+1$ divides $n$. Since $n$ is even, the smallest such $n$ is $2(2m+1)$. We verify that $(-x)^{2(2m+1)} = 1$.
Comment: @Myath The last paragraph can be omitted: $-x$ having odd order leads to a contradiction, so the order *must* be even.
Comment: Yes, let me edit my answer to include a proof of that for you.
Comment: @egreg You're right. I think it helps to see why the order is $2(2m+1)$ in addition to being even.
Comment: This is quite elegant. I'm just trying to figure out a rigorous argument for $-x$ having an even order. Do you have one?
Comment: @JyrkiLahtonen Thank you. I've replaced it with another claim that I think is correct this time.
Comment: The last three paragraphs are not needed: since $\gcd(2,2m+1)=1$ and $-1$ has order $2$ because $-1\not\equiv1\pmod{N}$, you have that $-x=(-1)x$ has order $2(2m+1)$.
Comment: Actually, I followed the last two paragraphs but didn't follow the group theory argument, so it works for me, thanks @Myath
Comment: @egreg You applied that result about the order of the product of 2 elements in an abelian group. But I don't know if that result is clear or has been proven to the OP. So I wanted to show a proof of the special case needed for this problem.


invalid token: [node:title] when Token module installed

Question: I'm on Drupal 7.80 and a Drupal newb so help with how to debug as well as things to try appreciated.
Taking over a Drupal install that might have some outstanding issues.
Problem: It looks like 'core' tokens are not available. E.g. [node:title], [current-page:pager], and [site:name] are all unavailable
Detail: When trying to save/preview a custom content type called 'Event' I get a lot of token errors. It looks like they're coming from the Meta tags module which is set by default to populate its fields using tokens. For example Page title in Meta tags is set to: [node:title] | [current-page:pager][site:name], and when saving an Event I get error messages that none of those tokens can be found. (I'm assuming Metatag is a use/required core module and I shouldn't attempt to disable it or just remove all these settings)
I have two token modules installed: 'Entity tokens' and 'Token' that both look like core Required modules. I don't know how to check if they're actually installed and working?
The Token Browser only shows 3 top level sections: 'Current Date', 'Current page' and 'Random'.
Is it possible an errant module is removing tokens? How should I debug this?
Thanks for any/all help
UPDATE
I found the Flush Cache > Metatag, did this and that has just removed the Metatag panel from all my Content Types, but it does not seem to have re-added 'core' tokens - Token Browser still shows the limited set of tokens as above.
I've also done a 'Flush all caches' now
Answer: Despite having flushed caches whilst logged in I clicked 'Flush all caches' whilst logged in as admin user and this seemed to do the trick where click this while logged in as non-admin did not before.
I'm about 90% sure it was this, I was also clicking around with things in the Configuration > Meta Data > Defaults page to see if re-saving settings there did anything but don't think it was this.


$\frac{1}{\sqrt{-1}}=\sqrt{-1}$?

Question: I have trouble to comprehend what my mistake is in the following calculation:
If we set $\sqrt{-1}$ to be the new number with the property that $(\sqrt{-1})^2 = -1$ then I can write $$\frac{1}{\sqrt{-1}}=\sqrt{\frac{1}{-1}}=\sqrt{-1}.$$
But we also have (and I know this is the correct result) $$ \frac{1}{\sqrt{-1}}\cdot\frac{\sqrt{-1}}{\sqrt{-1}}=\frac{\sqrt{-1}}{-1}=-\sqrt{-1}$$
What am I missing? Thanks.
Comment: The identity $\sqrt{a} \sqrt{b} = \sqrt{ab}$ is not true in general for complex numbers.
Comment: Every nonzero complex number has **two** square roots.
Comment: $\sqrt{a}\sqrt{b} = \sqrt{ab}$ is a little white lie we tell our selves when we assume we are only dealing with real numbers. Well one of two. In truth we only know that $|\sqrt{|ab|}|=|\sqrt{|a|}||\sqrt{|b|}|$. this is a white lie for reals as only positive numbers have square roots and we only consider that positive square root.
Comment: For real numbers only $x\ge 0$ have square roots.  So if we see $\sqrt{ab}$ we *assume* $ab\ge 0$ which means either $a\ge 0; b\ge 0$ or $a<0;b<0$ but in either case $ab = (-a)(-b) = |a||b|$ so we *assume* $a\ge 0;b\ge 0$.  And in that case $\sqrt{ab}=\sqrt{a}\sqrt{b}$ that assumes only real numbers $\sqrt{ab}=\sqrt{(-a)(-b)}\ne\sqrt{-a}\sqrt{-b}$ because negatives don't have square roots.  In reality we have $\sqrt{ab}=\sqrt{|a|}\sqrt{|b|}$ but *ONLY* with the assumption $ab \ge 0$.  Now if we assume that we can have square roots of negative numbers *LOTS* of things go out the window.....
Comment: To begin with if $x = a^2$ then $x=(-a)^2$ so ever number has two square roots. One is $\sqrt{x}$, the other is $-\sqrt{x}$.  That's true even if $x=a^2$ if $a$ isn't real or $x$ isn't positive. If $\sqrt{-1}=i$ exists then we can't say that $\sqrt{ab}=\sqrt{a}\sqrt{b};\sqrt{ab}=\sqrt{-a*-b}=\sqrt{-a}\sqrt{-b}=i\sqrt{a}i\sqrt{b}=i^2\sqrt{ab}=-\sqrt{ab}$.  It isn't true that $\sqrt{ab}=\sqrt{a}\sqrt{b}$.  Instead it's only $|\sqrt{ab}|=|\sqrt{a}||\sqrt{b}|$.
Comment: So the second way works.  But the first way doesn't.  It's interesting but.  $\frac 1{\sqrt{-1}} = -\sqrt{-1}$.
Comment: And it's interesting that $i^1 = i; i^2 = -1; i^3 = -i = \frac 1i$ and $i^4 = (i^2)^2 = i^3*i =1$.
Answer: The incorrect step is $$\frac{1}{\sqrt{-1}}=\sqrt{\frac{1}{-1}}$$
This kind of relations that you learned very soon in your life are so anchored in your thinking that you don't even think that they need to be re-checked whenever the settings are different. Complex numbers behave differently to positive real numbers in that respect.
Answer: The problem is due to the use of the same symbol $\sqrt{\cdot}$ with different meanings.
Let's separate the meanings by distinguishing:

$\sqrt[\text{real}]{\cdot}$ is an operator defined on non-negative real numbers, that associates to $x$ the unique non-negative real number $y$ such that $y \cdot y = x$;
$\sqrt[\text{new}]{-1}$ is a symbol used to indicate a new number, that satisfies the property $\sqrt[\text{new}]{-1}\cdot \sqrt[\text{new}]{-1} = -1$.

The first chain of equations you wrote translates to:
$$\displaystyle\frac{1}{\sqrt[\text{new}]{-1}}=\frac{\sqrt[\text{real}]{1}}{\sqrt[\text{new}]{-1}} \overset{!}{=} \frac{\sqrt[\text{real}]{1}}{\sqrt[\text{real}]{-1}} \overset{!}{=} \sqrt[\text{real}]{\frac{1}{-1}} \overset{!}{=} \sqrt[\text{real}]{-1},$$
but the steps marked with $\overset{!}{=}$ are not valid since $\sqrt[\text{real}]{-1}$ is not defined.
Comment: I have to point out that this misses the point. $\sqrt[\text{real}]{x}$ is *NOT* unique.  If $y*y=x$ then $(-y)(-y)=x$.  Nor is $\sqrt[\text{new}]{-1}$.
Comment: This would be almost perfect if you added the word *positive* when necessary. Also, the equations at the end make no sense, because $\sqrt[\text{real}]{-1}$ doesn't exist.
Comment: Thank you for suggestions. I tried to fix my answer.

$\frac{1}{\sqrt{-1}}=\sqrt{-1}$?


What is the 3d location of the tip of a triangular pyramid with faces identically angled from vertical but an arbitrarily tilted base face?

Question: How can I find the 3d location of the tip of a pyramid which has a 3 sided base arbitrarily angled relative to the xy plane and remaining three faces with identical anglation relative to the z-axis.

The known variables are:
The three xyz vertices for the base face
The angle relative to the z-axis for the other three faces
   (this would be acceptible if fixed at pi/4, but much better if it could be determined on a case-by-case basis)

Why?
I am automatically generating supports for printing of a 3d modelled structure.
In 3d printing, faces which "overhang" (ie are inverted and within approx 45 degrees of horizontal) often fail to print correctly without support.
The intention is to develop a more robust support structure for these faces which spreads force more evenly and thus requires less point adhesion to the printed object which therefore reduces surface damage when removed.
The option being currently tested is a series of inverted triangular pyramids.
The pyramid faces will have an identical angle relative to horizontal (typically 45 deg, but it would be ideal if this angle could be arbitrarily set between 0 and PI/2). To minimise waste and optomise quality this angle should be identical for each of the 3 non-base faces irrespective of the orientation of the base.
Although many models to have faces with more than 3 sides, for practical purposes any faces with more than 3 sides will have previously been split into multiple 3-sided "base" faces which are each processed individually.

I have coded the following with outputs as per linked graphics which is probably "good enough". However although I don't believe it is robust (as evidenced when recursively looped), I haven't managed to get closer to a better solution.
triangular pyramidal supports underneath hand
triangular pyramidal supports underneath icosohedron
<code>

def support_interface(faceVertices, maxAngle):
    vertices = []
    for vert in faceVertices:
        vertices.append((vert[X], vert[Y], vert[Z]))

    # find a point which is maxAngle (currently locked at 45 degrees) below and between each pair
    #   vertices loops anticlockwise around the face
    # then average this to get an approximate intersection point
    #potentially repeat the process to successively approximate the solution

    curV = 0                 # which vertex pair is currently being evaluated?
    nextApproxVert = []      # temp list holding the most recent full iteration around all the vertex pairs
    closeEnough = False      # not really needed - but set up for future successive approximation
    loopCnt = 1              # the maximum number of loops to iterate over
    #maxAngle = -3.14159/4   # locked at 45 degrees for testing
    PI_2 = -3.14159/2        # 90 degrees

    while not closeEnough:

        # load the next vertex pair in the loop around the edge of the face
        x0 = vertices[curV][0]
        y0 = vertices[curV][1]
        z0 = vertices[curV][2]

        if curV < vertexCnt -1:
            x1 = vertices[curV+1][0]
            y1 = vertices[curV+1][1]
            z1 = vertices[curV+1][2]
        else:
            x1 = vertices[0][0]
            y1 = vertices[0][1]
            z1 = vertices[0][2]

        # get the xyz axial distances of the triangle
        dx = x0 - x1
        dy = y0 - y1
        dz = z0 - z1

        #print("dxyz=",dx,dy,dz)

        # get the 2D distance on the z-plane between vertices
        xyLen = math.sqrt(dx*dx + dy*dy)
        #print("xyLen",xyLen)
        # get the 3D distance between vertices
        h0 = math.sqrt(dx*dx + dy*dy + dz*dz)
        #print("h0",h0)
        # get the angle of the hypotenuse relative to horizontal
        a0 = abs(math.asin(dz/h0))
        #print("a0",a0)
        #get the angle of the additional triangle needed to keep angle under max value
        a1 = PI_2 - a0 - maxAngle
        #print("a1",a1)
        #get the length of the opp and adj sides of the "safe" triangle
        opp = math.sin(a1) * h0   # the z drop from the lower vertex to the "safe" vertex
        adj = math.cos(a1) * h0
        #print("opAd",opp, adj)
        #now get the other side lengths for the triangle from the higher vertex to the safe vertex
        # at 90deg to horizontal
        zHigh = math.asin(PI_2 - maxAngle) * adj   # adj for the previous triangle is hyp of the new one
        zAdj = math.acos(PI_2 - maxAngle) * adj
        #print("zHigh/zAdj",zHigh,zAdj)

        xyProp = zAdj / xyLen
        #print("xyProp",xyProp)

        dx1 = dx * xyProp
        dy1 = dy * xyProp
        #print("dxy1",dx1,dy1)

        nextApproxVert.append((x0 - dx1, y0 - dy1, z0 + zHigh))

        curV +=1
        if curV >= vertexCnt:
            curV = 0
            loopCnt -= 1
            #print(nextApproxVert)
            vertices = nextApproxVert
            nextApproxVert = []
            if loopCnt <= 0:
                closeEnough = True

    # after it meets criteria for closeEnough then take the average of vertices
    (x,y,z)=(0,0,0)
    for v in vertices:
        x += v[0]
        y += v[1]
        z += v[2]
    x=x/vertexCnt
    y=y/vertexCnt
    z=z/vertexCnt

    return (x,y,z)
</code>
Answer: First, implement a function that computes a plane that passes through two given points and whose normal makes some given angle with the z-axis.
Here's how to do that: suppose the two given points are $P$ and $Q$, and we want the normal of our plane to make an angle $A$ with the z-axis. Let the plane normal be given by the unit vector $N = (u,v,w)$. The equation of the plane can be written as $(X-P)\cdot N = 0$. All we need to do is figure out $N$. Since the vector $Q-P$ lies in the plane, we have $(Q-P)\cdot N = 0$. The angle requirement tells us that $N \cdot(0,0,1)= \cos A$, so $w= \cos A$. Also, since $N$ is a unit vector, $u^2 + v^2 +w^2 = 1$. These three equations give us enough information to calculate $N$.
Use this function to get the three planar sides of your "pyramid" (the correct term is "tetrahedron", actually).
The point you want is the intersection of these three planes. So, you need to write a function that intersects three planes, if you don't already have one.
Comment: You're correct, I don't know how to establish the function of a plane passing through two points with a given angle to either the z-axis vector, or the xy plane, and in a couple of hours of searching I haven't found an answer - thus I got stuck at the first step. If I could do that stage then the intersection point should fall out fairly easily. Since this shape is highly unlikely to be a regular polyhedron I was assuming virtually no instances would be a strict "tetrahedron" (ie something with congruent equilateral triangles for each of its faces), thus my use of "triangular pyramid".
Comment: Incidentally the "most feasible" option I came up with was that it might be possible to reverse the formula for dihedral angle and substitute in the xy plane formula, but to get from that to the desired plane equation using either the known points or the vector they share in some sort of generalisable fashion is beyond me. Similarly so with your hint - so help for this stage would definitely be appreciated.
Comment: Any solid object with four triangular faces is called a tetrahedron. If the four triangles are congruent, it's a regular tetrahedron.
Comment: I added an outline of how to compute the plane through two points.
Comment: Thanks - I think your hint pointed me in the right direction. The dot product of the line defined by the two points with the z-axis allow me to calculate that intercept. From there I can calculate two potential intercept points (one above and one below the xy plane at the z-level of the intercept. Then I have four potential normals for the plane. Selecting the normal which is on the same side as one of the other face points and which has uv.z >0 (or it's negative) will identify the correct one. I'll post a more detailed answer when I've confirmed it works.
Comment: Incidentally I'm currently expecting that the intersection point of all three planes will be M = (d1*(N2×N3) + d2*(N3×N1) + d3*(N1×N2)) / (N1·(N2×N3)) where d1,d2,d3 are the plane constants, and N1,N2,N3 are the normal vectors.
Comment: Your formula for intersecting three planes looks correct.
Answer: The full code is here: https://github.com/dgm3333/3d-print-toolbox-modified/blob/master/supports.py
However the primary python routine which takes a list of face vertices and creates the support is as follows. Since it was a learning experience for me it's got lots of comments...
Because bubba's advice got me there I've marked that answer as correct.
<code># This creates a triangular pyramid with one face in contact with the original face
#   and the other faces angled to ensure they do not exceed a
#   predetermined maximum overhang angle
# It starts by calculating the length of a line perpendicular from an
#   edge from the face to the centroid.
# It then calculates the height the line would intercept a vertical axis
#   running through the centroid at maxAngle from vertical.
# The three vertices are then used to generate a plane from that edge
# This is repeated to generate three planes.
# The location at which all three intersect provides the 4th vertex to form the pyramid...
def support_interface(faceVerts, maxAngle):

    if len(faceVerts) != 3:
        return

    # will create with faces feeding under the centroid
    # This isn't the ideal point as angle from some vertices will be much shallower than required
    centroid =  Point((faceVerts[0].x + faceVerts[1].x + faceVerts[2].x)/3,
                 (faceVerts[0].y + faceVerts[1].y + faceVerts[2].y)/3,
                 (faceVerts[0].z + faceVerts[1].z + faceVerts[2].z)/3)

    # two points forming a z-axis directly though the centroid
    pZ1 = Point(centroid.x, centroid.y, centroid.z-1000)
    pZ2 = Point(centroid.x, centroid.y, centroid.z+1000)

    # loop through each edge
    #   identify the z intercept (using the centroid as the z-axis)
    #   generate the 3 points to define the plane
    #   add the plane generated to the list of planes
    planes = []
    for v in range(3):
        p1 = faceVerts[v]
        if v == 2:
            p2 = faceVerts[0]   # it's a loop so vertex[0] is the next in line from vertex[2]
        else:
            p2 = faceVerts[v+1]

        # identify the intersection of the lines
        # This is calculated as the dot product of the line defined by the two points with the centroid z-axis
        # Blender could also do this step:  mathutils.geometry.intersect_line_line(v1, v2, v3, v4)
        lli = LineLineIntersect3D(p1,p2,pZ1,pZ2)

        if (lli.uv.x == 0.0 and lli.uv.x == 0.0 and lli.uv.x == 0.0):
            #print("ERROR: unit vector has length zero. This means both lines are in contact.")
            #print("  This may be a zero-area face (but then it shouldn't be overhanging so seems odd), as it should never happen using the centroid z-axis (or the face wouldn't be a triangle)")
            #print("  aborting calculation on this face")
            return
            #print(" NB it would be a risk if using the true z-axis")
            #print("Thus the z-axis intercept cannot be used to provide the 3rd point of the plane")
            #print("And in this situation could try using (1,1,0)->(1,1,1) line instead)")
            #lli = LineLineIntersect3D(p1,p2,Point(1,1,0),Point(1,1,1))

        #print("Calculating plane from p1p2 edge with coordinates of:")
        #print(p1)
        #print(p2)
        #print("UV (unit vector):", lli.uv)

        # the point on p1p2 will be exactly maxAngle from the point the plane intersects the centroid z-axis
        #print("Nearest point on p1p2 to z-axis:",lli.Pmem1)
        # the hypotenuse of a horizontal xy triangle becomes the adjacent side for the triangle down to the intercept
        # thus the opposite side (the difference in z-axis height from the current point is Opp = Adj*tan(maxAngle)
        #formula if using the z-axis at x=0,y=0
        #xyHyp = sqrt(lli.Pmem1.x*lli.Pmem1.x + lli.Pmem1.y*lli.Pmem1.y)
        dx = lli.Pmem1.x - centroid.x
        dy = lli.Pmem1.y - centroid.y
        #dz = lli.Pmem1.z - centroid.z
        print("dx=",dx,"dy=",dy)
        xyHyp = sqrt(dx*dx + dy*dy)

        print("xy hypotenuse = xyz adjacent side:",xyHyp)
        opp = abs(xyHyp * math.tan(maxAngle))
        if opp==0.0:
            #print("ERROR: this function will not work for horizontal planes")
            #print("  This should never happen if using centroid and non-zero face size")
            #print("Function will ignore this face until script is updated to handle this")
            return

        # Because we are using the centroid for our z-axis, we know the correct point must be below the height calculated for the intersection
        # and the normal N.z needs to point up to be towards the centroid
        p3 = Point(centroid.x, centroid.y, lli.Pmem1.z-opp)
        planeC = Plane3D(p1, p2, p3)
        if planeC.N.z < 0:
            planeC.N = -planeC.N

        planes.append(planeC)
        print("Verts of plane", p1, p2, p3)

        '''
        # If using the true z-axis the check is a bit more fiddly we need to test which of the two points produces a plane in the correct orientation
        #print("z intercept should be +/-",opp)
        # now we have two potential intercepts (one above and one below the level of the intersection)
        p3a = Point(0,0,lli.Pmem1.z+opp)
        p3b = Point(0,0,lli.Pmem1.z-opp)

        #print("zIntercept candidates are:-")
        print(p3a)
        print(p3b)

        # Now there are four potential normals for the plane.

        # Selecting the normal which is on the same side as one of the other face points and which has uv.z >0 (or it's negative)
        #   will identify the correct one.
        # Use the face centron to identify whether the normal is on the same or opposide side of the plane as the face
        #   and whether the normal points up or down (it should point up towards the face or down away)
        #print ("Testing plane candidate generated using point p3a")
        planeC = Plane3D(p1, p2, p3a)
        correctPlane = False
        lieCheckA = planeC.lie_check(centroid)

        if lieCheckA == 0.0:
            #print("Warning: The face centroid lies on current plane.")
            #print("  The face  may be at exactly maxAngle (but if this is the case it shouldn't have been selected for support)")
        elif lieCheckA < 0.0:
            #print ("The centroid lies on OPPOSITE side of current plane as normal N.")
            if planeC.N.z < 0:
                #print ("The normal N.z points DOWN so this is the correct plane")
                correctPlane = True
                planeC.N = -planeC.N
        else:
            #print ("The centroid lies on SAME side of current plane as normal N.")
            if planeC.N.z > 0:
                #print ("The normal N.z points UP so this is the correct plane")
                correctPlane = True
                planeC.N = -planeC.N

        if not correctPlane:
            #print ("p3a plane didn't meet selection criteria")
            #print ("Testing plane candidate generated using  point p3b")
            planeC = Plane3D(p1, p2, p3b)
            correctPlane = False
            lieCheckA = planeC.lie_check(centroid)
            if lieCheckA == 0.0:
                #print ("ERROR: The face centroid lies on current plane - THIS SHOULDN'T HAPPEN IF THE PLANE IS CORRECT")
            elif lieCheckA < 0.0:
                #print ("The centroid lies on OPPOSITE side of current plane as normal N.")
                if planeC.N.z < 0:
                    #print ("The normal N.z points DOWN so this is the correct plane")
                    correctPlane = True
                    planeC.N = -planeC.N
            else:
                #print ("The centroid lies on SAME side of current plane as normal N.")
                if planeC.N.z > 0:
                    #print ("The normal N.z points UP so this is the correct plane")
                    correctPlane = True
                    planeC.N = -planeC.N

        if not correctPlane:
            #print ("ERROR: Neither plane matches - THIS SHOULDN'T HAPPEN IF THE PLANE IS CORRECT")
            return
        else:
            planes.append(planeC)
        '''

    # Now we should have three planes we just need to establish the intersect point
    if len(planes) == 3:
        #print("3 PLANES IDENTIFIED")
        pass
    else:
        #print("ERROR: Number of planes != 3")
        #print("  Not sure why as zero area faces should already have been filtered, but function will ignore this face")
        return

    # The intersection point of the three planes "M" is given by:
    # M = (d1*(N1 cross N2) + d2*(N2 cross N0) + d3*(N0 cross N1)) / (N0 dot (N1 cross N2))
    # 'cross' indicates the cross product and 'dot' indicates the dot product
    # blender could do this step with:
    # blender could do this with
    # mathutils.geometry.intersect_plane_plane(plane_a_co, plane_a_no, plane_b_co, plane_b_no)
    #print("Normals and D coefficients for the three planes are:-")
    N0 = planes[0].N
    N1 = planes[1].N
    N2 = planes[2].N
    D0 = planes[0].D
    D1 = planes[1].D
    D2 = planes[2].D
    #k0 = round(N0.dot(planes[0].p1), 6)
    #k1 = round(N1.dot(planes[1].p1), 6)
    #k2 = round(N2.dot(planes[2].p1), 6)
    #print(N0.x, N0.y, N0.z, "   ", D0)#, "   ", k0)
    #print(N1.x, N1.y, N1.z, "   ", D1)#, "   ", k1)
    #print(N2.x, N2.y, N2.z, "   ", D2)#, "   ", k2)

    N12 = N1.cross(N2)
    N20 = N2.cross(N0)
    N01 = N0.cross(N1)
    N0dN12 = round(N0.dot(N12), 6)

    #print("Original Face Vertices and Centroid are:-")
    #for vert in faceVerts:
        #print(vert.x, vert.y, vert.z)
    #print(centroid.x, centroid.y, centroid.z, "(=centroid)")

    #print("Intersection Point Is:-")
    # TODO: figure out why Point overloads aren't working
    # M = (D0*N12 + D1*N20 + D2*N01) / N0dN12
    # point overloads not working, so calculate individually first
    D0N12 = Point(N12.x*D0, N12.y*D0, N12.z*D0)
    D1N20 = Point(N20.x*D1, N20.y*D1, N20.z*D1)
    D2N01 = Point(N01.x*D2, N01.y*D2, N01.z*D2)

    CPs = D0N12 + D1N20 + D2N01

    pyramidTip = Point(CPs.x / N0dN12, CPs.y / N0dN12, CPs.z / N0dN12)   # = M
    #print(pyramidTip.x, pyramidTip.y, pyramidTip.z)

    # now create a list with the vertices from the original face + the new vertex
    verts = []
    for vert in faceVerts:
        verts.append(vert)
    faceVertCnt = len(verts)
    verts.append(pyramidTip)
    for v in verts:
        print(v)
    ##print("faceVertCnt=",faceVertCnt)

    faces = []
    faces.append((range(faceVertCnt)))
    faces.append((0,faceVertCnt-1,faceVertCnt))
    for i in range(0,faceVertCnt-1):
        faces.append((i+1,i,faceVertCnt))

    ##print("Verts=",verts1)
    ##print("Faces=",faces1)
    obj = createMesh('interface', (0,0,0), verts, [], faces)
#    bpy.ops.collection.objects_remove_all()
    bpy.data.collections['AutoSupports'].objects.link(obj)
    print()
    return pyramidTip
```
</code>


How do I memorize the jazz music as just a listener?

Question: I want to get into jazz but I have a small (?) problem: most of the jazz music sounds same to me. How do I learn to distinguish different songs? With salsa it was easier as songs had some lyrics there. But how do I remember and distinguish songs that have only sax and piano? I've read that one of the ways to memorize music is to play it. Unfortunately, I don't play any instruments nor I can sing along. I don't even know the notes. Is there any way for me how I could memorize jazz songs and learn to distinguish them?
For example, there is playing a jazz song and I am like: "oh, that's Pennies From Heaven by Count Basie". I hope you got what I mean.
Comment: If all jazz sounds the same to you, why would you want to "get into" it?
Comment: I'm voting to close this question because it is not about music practice or theory as outlined in the help center. Questions about listening to and enjoying music can be asked at the [Music Fans Stack Exchange](https://musicfans.stackexchange.com/questions) site.
Comment: What do you mean you can't sing along?
Comment: It's like everything else: practise
Comment: Give yourself time. Shop around the subgenres. May be start with jazz arrangements of classical, Beatles, whatnot? Plenty of such material in Youtube.
Comment: Are you entirely a listener or are you working to get into jazz so you can start performing, composing, or engineering jazz music?
Answer: First, a short, simple answer, then a longer, more helpful one.
Short/simple: It will get easier as you spend more time with the genre. There's a joke among many folk musicians, applicable to various instruments: "Q: How do you tell [banjo/fiddle/polka] tunes appart? A: By their titles." Really this joke is about cultural acclimation. It's similar to the phenomenon in which someone looks at people of an ethnicity that they have little experience with and says "all you people look the same to me." Any time there's a culture gap, that difference between the observer's own culture and the culture being observed obscures internal differences between cultural artifacts. In other words, if a Martian musicologist landed and started making a study of Earth's music, they'd have trouble perceiving the difference between rock, jazz, and classical because it's all so different from Martian music. So the longer you spend with jazz songs, the more you'll start to notice how they're different from each other.
The longer answer is simply steps that any non-musician can take to learn to recognize a melody. First, for jazz, make sure to distinguish the "core" tune; this will often be at the beginning, and in instrumental performances, might be followed by a long period of improvisation (perhaps ending with the main tune again). If the song has lyrics, there might be an introduction which is more or less disposable before the "main verse." It might help to get a "fake book," a big book of very basic sheet music for lots of popular numbers.
Once you've zeroed in on the main melody that you're trying to learn, listen for two variables: pitch and rhythm. In other words, the notes go up and down, and some notes might last longer than others. In a song with lyrics, try speaking the lyrics along with the singer. Try clapping your hands on each note, and notice the differing length of the claps. In your example, "Pennies from heaven," of those five syllables, you'll notice "-nies" is the shortest. Or for a more dramatic example, in the opening of "Summertime," notice the length of "-time," and how in "and the livin' is easy," there's a pattern of longer-shorter-longer-shorter.
Next listen for pitch. Even if you're not a trained singer, try singing along. Even if you don't know how to read music, look at a copy of the sheet music and notice how some dots are higher on the lines and some are lower. Now listen to the opening of "Summertime" and notice how, of those three notes, the middle one is lower, and the rest of the line goes down. (Btw, this idea of "up vs down" is an arbitrary idea, constructed by our human imagination, so don't feel bad if it takes some getting used to.) Try to notice the difference between small distances and bigger ones; for instance, in "Puttin' On the Ritz," in the lines "If you're blue and you don't know where...", hear the big drop in pitch between "blue" and "and," or between "know" and "where."
There are many other variables that one can hear in music, but many of the others can be changed from one performer to another and it can still be "the same song." One song can be performed at different speeds, with different moods or tones, in different vocal ranges, with different instrumentation. And in jazz, even the basic rhythm and pitch are open to small changes from one performer to another. But it's these patterns that you'll recognize among all the performances of a given number.
Answer: I'm not sure this is on-topic but I don't know where to shunt the question to, so here goes.
There's a lot of jazz, and it's went in a lot of directions. You will not like some of the things that are called jazz. Listen to a lot of it and find what you like.
If I was to say "jazz band", you would probably imagine one or more horn players, piano, upright bass and a drummer with a fairly small kit. Pat Metheny's Bright Size Life band looked like a rock power trio (electric guitar, electric bass, drums) but played jazz. Oregon had a tabla player and classical guitar but played jazz. 70s Miles Davis had electric piano, many electric guitars and trumpet through wah pedal and played jazz.
Structurally, you may want to think of jazz like parkour/free-runners on an obstacle course. The first chorus, they run it straight, like that is what is expected by the course. We call this the "head". Then each player gets to run through the course, showing off what they can do with it. This is improvisation. And then, to signal that things are coming to an end, they play the head again. As a listener, you listen to that first part and then recognize when the structure goes up or goes down, so that you know what to expect when the player improvises over that part, where they follow the course and where they go off wildly.
The most extreme version of the "obstacle course" take is "Giant Steps" by John Coltrane. Vox has a good explainer here, but shortly, in jazz, you play the chord changes, which means that there isn't an overriding key for the song, so you play chord notes, and jazz harmony gives you extended chords that give you a lot of choices. (Rock has a lot of "power chords", typically just roots, fifths and octaves, which allow for a different set of choices.) There is no overriding reason for jazz chords to be connected to each other, so you might find yourself playing a note that sounds good over this chord but is dissonant to the next. "Giant Steps" is about chords that are minimally connected, played fast, so playing melodically over them is a challenge. Tommy Flanagan was the pianist for the session, and practiced the piece at a much slower tempo, so you can hear him fall off.
Because you're often trying to show off your melodic playing over particular structures, it is common to play a new "head" over an existing set of chords. For example, "Ko-Ko" by Charlie Parker is adapted from Ray Noble's "Cherokee", and so many songs are based on "I've Got Rhythm" by George Gershwin that they're called the "rhythm changes" and are as common as the 12-bar structure for blues bands.
That's a lot about what's going on in these things, but you don't have to understand them to listen to jazz and like what you hear. You just have to listen and appreciate it. The swinging drums make me nod my head in time. The saxophone reminds me of a rainy city in a noir movie. Whatever. However you learn to love music is right. And if it all sounds the same to you, that's fine, if you like how it all sounds.
Answer: Can you tell songs apart, without vocals, when they AREN'T in jazz style and the melody is being clearly stated?  If not, there's probably no hope!
But otherwise, I know exactly what you mean and it's not your fault.  Jazz players sometimes forget that a song is not just a chord sequence for them to improvise over, there's also a melody.  OK, it's their prerogative to work this way, stating the melody just once (or even not at all!) and getting straight into the improvising.  But there's a dimension lacking when they reference only the chord structure, ignoring melodic features of the original tune.
But that's what they do.  And chord sequences aren't as distinctive as melodies.  It's often impossible to detect WHICH tune they're improvising on, even if you listen from the beginning!
Answer: It's generally accepted that the first verse states the actual melody for jazzers. So knowing how that goes will help, as you'll recognise it, without words. After that, the jazz starts, where the chord base continues, but the players 'play over the changes' - with an occasional nod back to the melody, note or timing wise.
But, as stated in the previous paragraph, the chord structure of a given song stays mainly the same. I say mainly, but there's often embellishments to those chords - 6ths, 9ths, 13♭9s etc, but it's still possible to recognise the 'geography' of a song through that. 12 bar tunes apart! So, even if you don't know what a chord sequence is, technically, its 'feel' will help. Pennies From Heaven' - main chord, then up a step, up another step, etc. Most songs will have their own trade mark chord sequence.
Comment: Eventually, we'll get screwed over by all those pieces that use the rhythm changes, all those versions of the 12-bar blues, and all those contrafacts.
Comment: @Dekkadeci - not sure what you allude to here?
Comment: I think @Dekkadeci might be suggesting that one thing that can make a lot of jazz sound the same is the fact that a lot of jazz **is** the same, at least in terms of the changes. It's mainly the melody of the head that we should listen to in order to recognize a tune, not the chords. I disagree that "most songs will have their own trade mark chord sequence". Two different jazz standards can easily have almost the same or even identical changes - and that's not even a copyright issue since chord progressions can't be copyrighted.
Comment: @ToddWilcox - fair point. There's an awful lot of ii>V>I found in jazz - but also in a lot of other music. It's sort of 'the way home'. So, if OP hears the head, most tunes should be recognisable from that. Have to admit - without that, I find it difficult to recognise some stuff - and I play jazz (apart from other music). However, there are many jazz standards which *do* have specific chord sequences, which is another way in which to follow a piece, and possibly even recognise it. But worse - looking at real/fake books, many 'standards' have alternate sequences, so for a non-muso...


How to stop buzz and radio interference on a mini amp

Question: I'm a beginner and recently bought my mini amp (borne strike g30) but it keeps picking up radio signals and making a really annoying buzz. When I change rooms sometimes the buzz will either go up or down. When I touch metal parts in my guitar it also gets a little better. I don't know if it's a grounding issue, but I hope not (cause I can't really do anything about technical stuff). Don't really know what to do, anyone got some advice? Thanks!
Comment: Try a better quality guitar lead?
Comment: Are you talking about buzz with the guitar plugged in or buzz without anything being plugged in?
Comment: both! but it gets louder when the guitar is plugged in
Answer: The things that cause buzz:

Poor ground or shielding on the guitar
Poor quality lead
Poor ground or shielding on your amp
Dodgy wiring in the house

We have a number of questions on each of these already that should have your answer, but for simplicity try the following:

use another guitar, if the problem remains it isn't the guitar
use another lead to rule it out
try a different amp if those two don't help.
Comment: A process of illumination - throwing light onto the problem...
Comment: Hehe, did the last bit of the answer go missing? "If those two don't help..." ... switch to acoustic? :)
Comment: Thanks Andy - my fault not checking when on mobile


How to implement custom ostringstream-like formatting states?

Question: PROBLEM
Suppose I have a class like this:
enum eOutputMode
{
  DECIMAL,
  BILLS_AND_COINS
};

class BankAccount
{
  ssize_t         m_dollars;
  unsigned short  m_pennies;

public:
  friend ostream& operator<<( ostream& os, BankAccount const& rhs )
  {
    // switch on eOutputMode : output in DECIMAL or in BILLS_AND_COINS
    return os;
  }
};

QUESTION
How can I modify the code above so that I can call it like this?
BankAccount  ba;
os << eOutputMode::DECIMAL << ba << "\n";
os << eOutputMode::BILLS_AND_COINS << ba << "\n";

In other words, how and where should I capture the output states?
Answer: You can write an output manipulator and capture the states in ios_base::iword (that page has an example of a custom stateful manipulator)


How do I automate deployment of Java non web based application

Question:
My Application: Java based server and client application.
Need: To automate the deployment process in UAT and PROD in both windows and unix environemnt.
Present State: Manual steps given to support team to follow and deploy.
Main steps involved in deployment on UNIX or WINDOWS : 1) download the artifact from hudson 2) stop the process 3) unzip the application 4) start the process

What I am looking for:
-Suggestions to automate the deployment. Tools or product.
-Details or links to documentation so that I can understand how that particular tool or product will solve my issue.
Comment: Client app, use JavaWebStart.
Comment: For the server side, have you considered using a deployment tool such as [kwatee](http://kwatee.net)
Answer:
Write batch/bash script and trigger it with parameters, from Jenkins.
The script will download the artifacts
Stop process
Unzip artifacts
Start process


【iOS】error in targetcontentoffset, which is inconsistent with the real stop position

Question: I am using textview, which has very large text. I need to get the exact location of the final stop before the user stops scrolling
I use the following code. When the user's sliding distance is very small, it can work (but there is also a small error). When the user's sliding distance is very large, such as sliding for 10 times continuously, its expected position is inaccurate
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
     CGPoint willEndPoint = *targetContentOffset;
     //Where it is expected to stop
     NSLog(@"expected to stop:%f",willEndPoint.y);
}
- (void)scrollViewDidEndScroll {
    NSLog(@"Actual stop position:%f",self.textView.contentOffset.y);
}

targetcontentoffset and self textView. contentOffset. There is an error between y. when the sliding distance is very small, their error is very small, between 1 and 5, but when my text has tens of thousands of lines, and users slide down madly, their gap will be very large. I have a need to get the exact final stop position before the scrolling stops. Obviously, the error of getting targetcontentoffset makes me unable to do this. I'm very confused. I guess it's because textview doesn't load all the content at once. In the process of scrolling, it loads new content, which leads to this error, so, Is there any way for me to get the exact final stop position before rolling stops
The following is a complete demo
#import "ViewController.h"
@interface ViewController ()<UITextViewDelegate>
@property (strong, nonatomic) UITextView *textView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.textView = [[UITextView alloc]init];
    self.textView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [self.view addSubview:self.textView];
    self.textView.font = [UIFont systemFontOfSize:50];
    NSString *str = @"";
    for(int i = 1; i < 10000;i++){
        str = [NSString stringWithFormat:@"%@%i\n",str,1];
    }
    self.textView.text = str;
    self.textView.delegate = self;
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
     CGPoint willEndPoint = *targetContentOffset;
     //Where it is expected to stop
     NSLog(@"expected to stop:%f",willEndPoint.y);
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    BOOL scrollToScrollStop = !scrollView.tracking && !scrollView.dragging && !scrollView.decelerating;
    if (scrollToScrollStop) {
        [self scrollViewDidEndScroll];
    }
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        BOOL dragToDragStop = scrollView.tracking && !scrollView.dragging && !scrollView.decelerating;
        if (dragToDragStop) {
            [self scrollViewDidEndScroll];
        }
    }
}
- (void)scrollViewDidEndScroll {
    NSLog(@"Actual stop position:%f",self.textView.contentOffset.y);
}

When the user slides continuously for 2-3 times:

When the user slides continuously for more than 10 times
Comment: No one? Is this an unsolvable problem
Answer: I think the second method you are using is the wrong one. That will be called when the user ends scrolling. But not when the scroll view stops updating.
If there is a velocity when the user ends scrolling then you will want to use the method didEndDecelerating instead…
https://developer.apple.com/documentation/uikit/uiscrollviewdelegate/1619417-scrollviewdidenddecelerating
Comment: Sorry, I didn't describe it clearly. I have modified my problem. Please have a look again


ABC is a triangle. BB$_1$ and CC$_1$ are angle bisectors of B and C respectively. E,F are feet of perpendiculars from A on BB$_1$ and CC$_1$…

Question: ABC is a triangle. BB$_1$ and CC$_1$ are angle bisectors of B and C respectively. E,F are feet of perpendiculars from A on BB$_1$ and CC$_1$ respectively. Suppose D is point at which incircle of ABC touches AB, Prove that AD = EF.
Use coordinate geometry only.
Answer: NOTE : This is not a complete answer. This is the answer for the case that $ABC$ is an isosceles triangle. You'll see how ugly it becomes. If you understand how it goes, you can generalize this answer.
Without loss of generality, we may suppose that $A(0,a),B(-1,0),C(1,0)$ where $a\gt0$. (Do you see why?)
Letting $\tan\theta=1/a$, which is the slope of the line $AB$, the slope of the line $BB_1$ is
$$\tan\frac{\theta}{2}=\sqrt{\frac{\sqrt{a^2+1}-1}{\sqrt{a^2+1}+1}}=a^\prime.$$
In the same way, you know that the slope of the line $CC_1$ is
$$-\sqrt{\frac{\sqrt{a^2+1}+1}{\sqrt{a^2+1}-1}}=a^{\prime\prime}.$$
Hence, the line $BB_1, CC_1$ can be represented as
$$BB_1 : y=a^\prime x+a^\prime, \ CC_1 : y=a^{\prime\prime}x-a^{\prime\prime}.$$
By the way, the lines $AF,AE$ can be represented as
$$AF : y=-\frac{1}{a^{\prime\prime}}x+a, \ AE : y=-\frac{1}{a^{\prime}}x+a.$$
Hence, we can get the coordinate of $F,E$ as
$$F \left(\frac{a^{\prime\prime}+a}{a^{\prime\prime}+(1/{a}^{\prime\prime})},\frac{aa^{\prime\prime}-1}{a^{\prime\prime}+(1/{a}^{\prime\prime})}\right), E \left(\frac{a-a^{\prime}}{a^{\prime}+(1/{a}^{\prime})},\frac{aa^{\prime}+1}{a^{\prime}+(1/{a}^{\prime})}\right).$$
By the way, since the incenter $I$ of the triangle is the intersection point of the lines $BB_1, CC_1$, we get
$$I \left(\frac{a^{\prime\prime}+a^{\prime}}{a^{\prime\prime}-a^{\prime}},\frac{2a^{\prime}a^{\prime\prime}}{a^{\prime\prime}-a^{\prime}}\right).$$
NOTE : $a^{\prime}\not=a^{\prime\prime}$ because $a^{\prime}\gt0, a^{\prime\prime}\lt0.$
Hence, we know the point $D$ is the intersection point of $AB : y=ax+a$ and the line which is perpendicular to $AB$ and passes through $I$. Then, the latter line can be represented as
$$y-\frac{2a^{\prime}a^{\prime\prime}}{a^{\prime\prime}-a^{\prime}}=-\frac 1ax\left(x-\frac{a^{\prime\prime}+a^{\prime}}{a^{\prime\prime}-a^{\prime}}\right).$$
Hence, we get
$$D \left(\frac{a(2a^{\prime}a^{\prime\prime}+aa^{\prime}-aa^{\prime\prime})}{(a^2+1)(a^{\prime\prime}-a^{\prime})},\frac{a(2aa^{\prime}a^{\prime\prime}-a^{\prime}+a^{\prime\prime})}{(a^2+1)(a^{\prime\prime}-a^{\prime})}\right).$$
Now, in order to prove $AD^2=EF^2$, all we need is to check if
$$\left(A_x-D_x\right)^2+\left(A_y-D_y\right)^2=\left(E_x-F_x\right)^2+\left(E_y-F_y\right)^2$$
holds for any $a\gt 0$. This is just a calculation, so I left it to you.
Comment: You have just solved it for isosceles triangle. It may turn out(!!We all know that it will not!!) that this relation does not hold for every triangle. Then what ?
Comment: I am only awarding this to you since you gave a coordinate solution ,even if not entirely generalized.
Answer:
Synthetic solution (out of habit, angles are measured in degrees):
Lemma: ADFIE are concyclic points.
Proof: $AE \perp EI$ and $AF \perp FI$, so $AEFI$ is a cyclic quadrilateral. $AD \perp DI$ and $AF \perp FI$, so $ADFI$ is a cyclic quadrilateral.

Lemma: $AE \parallel DF$.
Proof: First notice $\angle BAE = 90 - \frac{1}2 \angle ABC$.
Then $\angle FDA = \angle AIC$ by cyclicity of the quadrilateral $ADFI$, and $\angle AIC = 180 - \frac12 \angle BAC - \frac12 \angle CAB.$ Therefore the complementary angle $\angle BDF$ has measure $\frac{1}2 \left( \angle BAC + \angle CAB \right) = 90 - \frac12 \angle ABC = \angle BAE$. It follows $DF \parallel AE$.

Then, $AE$ and $DF$ are parallel lines cutting the circle formed by A,D,F,I, and E. Therefore the segments AD and FE have equal length.
Comment: Please solve it using coordinate geometry
Comment: I only posted this because you commented in your post that any solution would be acceptable; I challenge anyone to find a coordinate solution more elegant than this synthetic one! :)


Stuck with Angularjs

Question: Hello i'm new to angularjs and i'm creating an Angularjs application with visualstudio 2012 mvc4 and i need some help with a request.
this is my get method
<code>    // GET: /getCard/
    Logic l = new Logic();
    public List<Cards> Index()
    {
        var cards = ml.getSortedDeck();
        return cards;
    }
</code>
here is my js code
<code>  MemoryApp.factory('Cards', function($resource){
    return $resource('/getCard/', { method: 'GET', isArray: true });
 });

 var ColourCtrl = function ($scope, Cards, $routeParams, $resource) {
$scope.cards = [];

$scope.setcards = function () {
    Cards.query(function (data) {
        console.log(data);
        $scope.cards = $scope.cards.concat(data);
    });
}

$scope.setcards();
</code>
}
when i stepped through my backend code it worked fine, i got 16 hits back in the "cards" list which is the right amount. Though when i check my console.log on the website i have an array with 59 items that are unuseable to me.
When i check the response section in under the network tab i get this message
"System.Collections.Generic.List`1[Memory.Models.Cards]" and that seems right to me.
best regards /M
Comment: jumpingcode that didnt change anything, i still got the same result as before.
Answer: Return JSON.
<code>public JsonResult Index()
{
    var cards = ml.getSortedDeck();
    return Json(cards, JsonRequestBehavior.AllowGet);
}
</code>

Stuck with Angularjs


JPA entity: get the hours,minutes and sec from Oracle DATE column

Question: I have problems to get the full DATE info from my Oracle DB (dd/mm/yyyy hh/mm/ss).
In the db level, in the column that I want to receive I set test values:
update my_table
set my_date_column=(to_date('2011-06-15 15:43:12', 'yyyy-mm-dd hh24:mi:ss'));

but in my JPA entity I have:
@Column(name = "MY_DATE_COLUMN")
@Temporal(TemporalType.DATE)
private Date dateDetailed;

public Date getDateDetailed() {
    if (this.dateDetailed!= null) {
        return this.dateDetailed;
    }
    return null;
}

public void setDateDetailed(Date dateDetailed) {
    if (dateDetailed!= null) {
        this.dateDetailed= dateDetailed;
    } else {
        this.dateDetailed= null;
    }
}

Each time I acccess my object, It is giving me date without hours, min and seconds.
I tried to use TemporalType.TIMESTAMP, but in that case I would need to also change column type in db (which I want to avoid).
Any suggestions?
Answer: Its the TemporalType.DATE
You will need TIME or TIMESTAMP. DATE is only the date without time. TIMESTAMP is represented as a number.
Comment: Unfortunately, you will need to do that regardless.  If you create an Oracle column of type DATE, it will not store the time information along with the date, e.g., `create table foo (bar date);`.  If you create this table and then perform the insert you mentioned, you will notice that the time information was removed and the column only contains `15-JUN-2011` rather than the expected `15-JUN-11 03.43.12.000000000 PM` (as seen from sql dev output).  The DB column must be able to support the data in order for JPA to provide the needed functionality.
Comment: TemporalType.DATETIME is not valid javax.persistence.TemporalType type. Only valid ones are DATE, TIME and TIMESTAMP. If I use TIMESTAMP then I must change type of column in my db to be also TIMESTAMP instead of DATE, and I would like to avoid th at if it is possible.
Comment: @Kris In this case, can you explain me why, if in the DATE column I can only store date, my select is giving me real value including hours, minutes and seconds? And also why, with column type DATE, with EJB2 entity bean I can retrieve hours, minutes and seconds?
Comment: That is an interesting question. What is the exact column definition that is being used in the table?  I have tested this scenario as I described above in an Oracle 10g db and see the result as described.  If you are truly getting the results you describe, then simply converting the JPA annotation from `TemporalType.DATE' to `TemporatlType.TIMESTAMP` should work for your particular case without any database modification.
Comment: http://download.oracle.com/docs/cd/B19306_01/server.102/b14225/ch4datetime.htm its written taht in DATE type we can store date AND time. My sqls from the question post are able to set/receive time from this column. And just changing TemporalType.DATE' to TemporatlType.TIMESTAMP is giving me deployment exception : wrong column type. Maybe the problem is that in select my_column which is type DATE is by default just giving me date, and default select my_column which is type TIMESTAMP is giving me both DATE and TIME..
Comment: Ok I found solution... Problem was coming that default SELECT statement with column type DATE is just returning date, and default SELECT statement for column type TIMESTAMP is returning date and time... In my case just modifying TemporalType.DATE to TemporalType.TIMESTAMP causes deployment exception because in db column type is DATE and not TIMESTAMP.. So I needed to also change column type in DB to be TIMESTAMP... Now im getting both date and time :) THanks.
Answer: By using the TIMESTAMP temporal type, you will get the date and the time part of the java date datatype but Oracle will make a column with the TIMESTAMP datatype. To overcome this issue if you want a DATE datatype, you can use the columnDefinition parameter of the column annotation such as:
@Column(name = "MY_DATE_COLUMN", columnDefinition = "DATE")
@Temporal(TemporalType.TIMESTAMP)
private Date dateDetailed;


Is the matrix inequality $P > Q \geq 0$ implies $P^2 > Q^2$?

Question: Assume $P$ and $Q$ are positive definite and positive semi-definite, respectively, and both are symmetric. Then, is it true that
\begin{equation}
   P > Q \;\; \Longrightarrow \;\; P^2 > Q^2 \;\;?
\end{equation}
 (I know that both $P^2 > 0$ and $Q^2 \geq 0$ are obviously true).
 Can anyone provide a counter example if the statement is not true?
Answer: Not a satisfactory answer, but with $P=\begin{bmatrix}13 & -6 \\ -6 & 13 \end{bmatrix}, Q= \begin{bmatrix}10 & 0 \\ 0 & 0 \end{bmatrix}$ one finds that
$P>Q \ge 0$, but $P^2 \not> Q^2$.
$\lambda(P) = \{7, 19\}$, $\lambda(P-Q) = \{ 8 \pm \sqrt{61} \}$,$\lambda(P^2-Q^2) = \{ 155 \pm 2 \sqrt{6709}\} $. ($\sqrt{6709}> \sqrt{6561} = 81$, hence the smallest eigenvalue of $P^2-Q^2$ is negative).


Not call onRequestPermissionsResult from fragment

Question: In my android project, I use this code to check & request runtime permissions:
public class AgentsFragmentMapTab extends RootFragment implements  ActivityCompat.OnRequestPermissionsResultCallback
{
     //..
     private boolean checkAndRequestPermissions() {
            int internet = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.INTERNET);
            int loc = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION);
            int loc2 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
            List<String> listPermissionsNeeded = new ArrayList<>();
            if (internet != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.INTERNET);
            }
            if (loc != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            if (loc2 != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (BuildConfig.DEBUG)
                Log.d(TAG, "checkAndRequestPermissions_listPermissionsNeeded(" + listPermissionsNeeded.size() + ")");
            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions(getActivity(), listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), LOCATION_REQ_CODE);
                return false;
            }
            return true;
        }

        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

            if (requestCode == LOCATION_REQ_CODE) {

                } else {

                }
            }
        }

This code shows the permission dialog perfectly. But when I click on the Allow or Deny button, the method onRequestPermissionsResult() doesn't get invoked. Why isn't it getting invoked and how to achieve this?
Comment: override the onRequestPermissionsResult method in the parent activity, then push the result to this fragment.
Comment: But I need to handle click button Allow in fragment
Comment: I strongly suggest you to use dexter permissions library
Comment: `ActivityCompat.requestPermissions` only sends the result to the Activity as it doesn't know about your Fragment. Why aren't you using `requestPermissions` on `Fragment` itself?
Answer: As mentioned in comments Override onRequestPermissionsResult in the parent activity
Make sure to call super.onRequestPermissionsResult from this activity's onRequestPermissionsResult
it will then send to your fragments which override onRequestPermissionsResult
Edited :
Here is what i did
i called  requestPermissions(StringOfPermissions,YourRequestCode);
inside the fragment
And Here is the code i used to add the fragment inside the activity , pretty straight forward
getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.container, BlankFragment.newInstance("",""))
            .disallowAddToBackStack()
            .commit();

I overridden onRequestPermissionsResult():
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}

inside the activity and fragment
when i requested from the fragment it entered the activity and then it entered the fragment
Comment: Call only in activity, but not call in fragment
Comment: even after  `super.onRequestPermissionsResult(requestCode, permissions, grantResults);` in the activity ?
Comment: yes. In my activity:
    public void onRequestPermissionsResult(int requestCode, String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }. But not call in fragment
Comment: I've edited the answer after testing can you check it now ? @Alexei
Comment: Not help. Same result. Not call in fragment
Comment: did you change this `ActivityCompat.requestPermissions(getActivity(), listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), LOCATION_REQ_CODE);`
to `requestPermissions(StringOfPermissions,YourRequestCode);` ?

as the first one actually asks android to check the permission in the activity not in the fragment that's why you send the getActivity() @Alexei
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/196100/discussion-between-hossam-eldeen-onsy-and-alexei).
Answer: Change
 ActivityCompat.requestPermissions(getActivity(), listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), LOCATION_REQ_CODE);

to:
requestPermissions(listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_CODE);

And also ContextCompat to ActivityCompat and getActivity() to getContext() like:
int loc2 = ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION, LOCATION_REQ_CODE);

Answer: Firstly, do this in the parent activity.
...
Fragment theFragment =
     getSupportFragmentManager().findFragmentById(R.id.your_fragment_name);
...

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case LOCATION_REQ_CODE: {
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                if(theFragment instanceof AgentsFragmentMapTab)
                    ((AgentsFragmentMapTab)theFragment).passPermissionResult(true);

            } else {
                if(theFragment instanceof AgentsFragmentMapTab)
                    ((AgentsFragmentMapTab)theFragment).passPermissionResult(false);
            }
            return;
        }
    }
}

Then in your fragment, add a public method like so:
public void passPermissionResult(boolean allowed) {
    if(allowed) {
        // ALLOW clicked
    }
    else {
        // DENY clicked
    }
}

Comment: This isn't necessary. Calling `requestPermissions()` in the Fragment automatically sends the result to the Fragment for you.
Comment: Oh i see. Thanks for the correction! I learned something new today.


How to solve AJAX search in Laravel?

Question: I'm trying to make AJAX searching into my app, but I have a problem.
Please correct me if I'm doing anything wrong, I'm new to AJAX.
My Route:
Route::get('/retours/{id}/searchpart/{searchquery}', 'RetoursController@searchpart');

My Table and Search form, the vars are commented out, else I would always get an error and can't test.
{!! Form::open(['class' => 'form-horinzontal']) !!}
    {!! Form::text('search', null, array('required','class'=>'form-control','placeholder'=>'Zoeken in onderdelen','onkeyup' => 'search_data(this.value, "result")')) !!}
    {!! Form::submit('zoek', array('class'=>'btn btn-info form-control')) !!}
{!! Form::close() !!}

        Artikelcode
        Artikelcode verkoop
        Omschrijving
        Prijs
        Actie

    @if(isset($resultquery))
        @foreach($resultquery as $result)

                    id) }}">
                        {{ $result->artikelcode }}

                    {{--{{ $result->artikelcodeverkoop }}--}}

                    {{--{{ substr($result->omschrijving,0,50) }}--}}

                    {{--€ {{ $result->prijs }}--}}

                    {{--id . '/addpart/'. $result->id) }}" style="margin-right: 10px;" class="pull-right">--}}

                    Aan bon toevoegen

        @endforeach
    @else

    @endif

And my Controller of course:
public function searchpart(Request $request, $searchquery){

    $data = Parts::where('omschrijving','LIKE', '%' .$searchquery.'%')->get();

    return view('retour.updatefill')->with('resultquery',$data);

ajax ofcourse:
function search_data(search_value) {
        $.ajax({
            url:'searchpart/' + search_value,
            method: 'GET'
        }).done(function(response){
            $('#myTable').html(response);
        });
    }

Sometimes I get 500 internet server error
Sometimes I get 404 not found

I have the feeling I'm doing it terribly wrong.
errors requested by madalin:
Comment: where is your `ajax`?
Comment: sorry i added @ParthTrivedi
Comment: Please `console(search_value)` are you getting it all the time?
Comment: Use `'/retours/[id]/searchpart/' + search-value` as your `url` in the `$.ajax`.
Comment: this doesnt work @Duvdevan, i think it gets the right URL as seen in the uploaded image..  thx for the comment tho..
Comment: why not use a get variable like normal people and not a custom route?
Comment: What is the Laravel error that is shown under the "Voorbeeld" (= Example) tab in your browser console?
Comment: @piscator Internal server error
Comment: @madalinivascu what do you mean??
Comment: @JordyGroote see my answer below man
Answer: You should be return json response to ajax callback.
Try this:
public function searchpart(Request $request, $searchquery){

    $data = Parts::where('omschrijving','LIKE', '%' .$searchquery.'%')->get();

    return response()->json([
        'data' => $data
    ], 200);
}

Ajax
.done(function(response){
    //do something
    console.log(response.data);
});

Comment: why append a html json to the page?
Answer: Use a get variable not a custom route
Route::get('/retours/{id}/searchpart', 'RetoursController@searchpart');

public function searchpart(Request $request){
    $searchquery = $request->get('searchquery');
    $data = Parts::where('omschrijving','LIKE', '%' .$searchquery.'%')->get();

    return view('retour.updatefill')->with('resultquery',$data);

ajax:
function search_data(search_value) {
        $.ajax({
            url:'{{action("RetoursController@searchpart")}}' ,
            data:{searchquery:search_value}
            method: 'GET'
        }).done(function(response){
            $('#myTable').html(response);
        });
    }

Comment: and i don't even need the ID so i deleted that from the route
Comment: Hello thanks for this, the {{action}} needs parameters what shoud i give it ?
Comment: pass the id of the route `{id}` like `action('UserController@profile', ['id' => 1]);`
Comment: I still get internal server error... has this something to do with csrf token?
Comment: you need to return something if there is no data returned
Comment: $data = Parts::where('id','LIKE', '%' .$searchquery.'%')->get();
        if($data > 0) {

        } else {
            return "Nothing found";
        }
Comment: what do you mean by `if($data > 0)` are you returning a number ??
Comment: why not use count()?
Comment: that's indeed what i ment, i still get internal server errror tho.  this is killing me
Comment: what errors are in the ajaxed page can you paste them here?
Comment: will add to original post
Comment: the ajax gives no errors whatsoever, this is all i get. the internal server 500
Comment: added in post above ^^
Comment: i mean the error in the body of the xhr request not the response error
Comment: added the new picture
Comment: @JordyGroote  ok this is not woking with the picture and stuf so i want you to open the following url into your project and paste me the screenshot  from that  `/retours/searchpart?searchquery=test` is the url you are trying to ajax to
Comment: it return this,   Trying to get property of non-object (View: /Applications/MAMP/htdocs/site/resources/views/retour/show.blade.php)
Comment: damn hard, your view has a variable that is not returned by your database query
Comment: Any idea how i can fix this?
Comment: yes you go to the template and you check every variable if exists

How to solve AJAX search in Laravel?


Google play games services - launching the google+ sign in flow from an app in landscape mode

Question: Let me start with the relevant code from the GameHelper class found in BaseGameUtils, provided by the google team as a starting point:
<code> /**
 * Attempts to resolve a connection failure. This will usually involve
 * starting a UI flow that lets the user give the appropriate consents
 * necessary for sign-in to work.
 */
synchronized void resolveConnectionResult() {

    // Try to resolve the problem
    if (mConnectionResult.hasResolution()) {
        // This problem can be fixed. So let's try to fix it.
        try {
            // launch appropriate UI flow (which might, for example, be the
            // sign-in flow)
            mExpectingActivityResult = true;

 // >>> **I 'VE ADDED THE FOLLOWING LINE - IT RESOLVES MY ISSUE WITH SOME SIDE EFFECTS which are irrelevant with the problem here (they have to do with my app)** <<<
            mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

            mConnectionResult.startResolutionForResult(mActivity, RC_RESOLVE);
        } catch (SendIntentException e) {
            ...
        }
    } else {
           ....
    }
}
</code>
My application's manifest file forces the orientation of my app to landscape
<code>  android:configChanges="orientation"
  android:screenOrientation="landscape"
</code>
When my player requests a multi-player game for the first time, he is presented with the google+ sign-in button, drawn in an opengl canvas (everything in landscape). As soon as he taps it, the user initiated sign-in flow begins and the above method is executed.
If I comment out the line that I 've added half-way, strange things happen.
Sometimes I am presented with the dialogue to chose one of my google accounts, some other times the result of the intent indicates failure to connect and I return to my app.
For these times that I am able to choose an account, after I do so:

The orientation of the screen goes back and forth from landscape to portrait a couple of times
The activity that presents google's sign-in dialogue is launched many times on-top of itself.
I have to select my google+ app sharing preferences and press "OK" at least 3 times in at least 3 successive identical dialogues. Sometimes the "public" button is missing (there is white-space in its position)
Sometimes I successfully sign-in in after all the above happen, some other times I get a failure message. When I click sign-in again, it automatically signs in successfully without any user interaction.

I am trying to figure out whether I am doing something wrong, or if this is a known issue. Is anyone able to reproduce it? (note that this happens only on the first sign-in, i.e. if one wants to try and reproduce it he will first need to:

Clear the app data
Go to the google+ app settings, and disconnect the app from the google account

I am not sure whether this has to do with connecting to the GAMES_CLIENT, or if launching the google+ sign-in flow from a landscape app is problematic in general.
Thanks in advance,
Nikos
Comment: Thanks for reporting. I'll try to repro this and get back to this question once I figure it out.
Answer: I can't reproduce the problem. When I set up my test app exactly as you described and hold my phone in landscape orientation, no problem happens. When I hold the phone in portrait orientation, I can see the orientation changing as the sign-in dialogs appear, and then it changes back to landscape when the app regains focus, but everything seems to be working. The auth and consent dialog appear only once, and everything seems to work fine.
That said, my sample doesn't use an OpenGL canvas -- maybe that's where the problem is. Might be some weird interaction between the canvas and the sign-in flow. I would recommend hiding the OpenGL surface (and replace it with a static View that says "Signing in...") while you go through the sign-in flow, just to be sure.
Comment: your help is very much appreciated. :) Indeed hiding the opengl surface works - I 'll stick with that for now!


Prove that there is at least one real solution to the equation...

Question: $x^{17}+\frac{243}{1+x^4}=120$
Can anyone show me how to approach this problem..? Any help would be great, thanks.
Answer: The left side is less than $120$ at, for example, $x=-2$, and bigger than $120$ at $x=-1$, so by the Intermediate Value Theorem it is exactly $120$ somewhere in between $-2$ and $-1$.
We are using the fact that the function $x^{17}+\frac{243}{1+x^4}$ is continuous everywhere.
Comment: Could have used a lot of other things. It is obvious that the left side is very negative if $x$ is large negative, and is $243$ at $x=0$. So at first I used $-2$ and $0$, then switched to $-1$ because it gives near equality.
Comment: How did you know to use $x=-2$ and$ x=-1$..?
Answer: HINT Multiply both sides by $1+x^4$. Then your equation simplifies to a $21$-degree polynomial. Any polynomial of odd degree satisfies which property?
Answer: Because $17$ is odd, $x^{17}$ goes to $\infty$ as $x$ goes to $\infty$ , and $x^{17}$ goes to $-\infty$  as $x$ goes to $-\infty$.
On the other hand ${243 \over 1 + x^4}$ goes to zero as $x$ goes to $\infty$ and $-\infty$, so it stays bounded.
Hence $x^{17} + {243 \over 1 + x^4}$ goes to $\infty$ as $x$ goes to $\infty$, and goes to $-\infty$ as $x$ goes to $-\infty$.
Since $x^{17} + {243 \over 1 + x^4}$ is a continuous function, the last statement implies that $x^{17} + {243 \over 1 + x^4}$ will take every real value, including $120$. The intermediate value theorem can be used to make this rigorous.


Angular 2 http change value in response not affect the page

Question: I am quite new to angular 2. I am trying to change the value after getting response from http request of parameter that will be used in the page. I do not understand why it not affect at the page even though value have changed in the console log.
page.html
<ons-list>
  <ons-list-header>Settings {{testMsg?testMsg:''}}</ons-list-header>
  <ons-list-item>

      Enable VoLTE

      <ons-switch (change)="enabled()"></ons-switch>

  </ons-list-item>
</ons-list>

page.ts
testMsg = 'before request';
enabled() {
    let body = JSON.parse(this._settingService.load(this.pageName));
    let url = this._settingService.loadUrl(this.pageName);
    this._sesService.getCarsRestful().subscribe(
        function (response) {
            console.log("Success Response" + response);
            this.test2 = response;
            // this.showFrame = 'show';
            // console.log(this.showFrame);
            this.testMsg = 'after request';
            console.log(this.testMsg);
        },
        function (error) { console.log("Error happened" + error) },
        function () {
            console.log("the subscription is completed");
            // console.log(this.test2[0].name);
            // this.showFrame = 'show';
        }
    );

}

Answer: When you use function you will lose the current this of class. You should use Arrow function in success and error function of observable. function () {} should be () => {}
testMsg = 'before request';
enabled() {
    let body = JSON.parse(this._settingService.load(this.pageName));
    let url = this._settingService.loadUrl(this.pageName);
    this._sesService.getCarsRestful().subscribe(
        //changed to arrow function
        (response) => {
            console.log("Success Response" + response);
            this.test2 = response;
            // this.showFrame = 'show';
            // console.log(this.showFrame);
            this.testMsg = 'after request';
            console.log(this.testMsg);
        },
        //changed to arrow function
        (error) => { console.log("Error happened" + error) },
        //changed to arrow function
        () => {
            console.log("the subscription is completed");
            // console.log(this.test2[0].name);
            // this.showFrame = 'show';
        }
    );
}


Mostrar imagem enviada Phonegap + PHP

Question: Olá, eu estou utilizando o seguinte código para fazer upload da imagem de um app phonegap para um servidor :

    // Wait for PhoneGap to load
    document.addEventListener("deviceready", onDeviceReady, false);

    // PhoneGap is ready
    function onDeviceReady() {
    // Do cool things here...
    }

    function getImage() {
        // Retrieve image file location from specified source
        navigator.camera.getPicture(uploadPhoto, function(message) {
        alert('get picture failed');
    },{
        quality: 100,
        destinationType: navigator.camera.DestinationType.FILE_URI,allowEdit: true,
        sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
    }
        );

    }

    function uploadPhoto(imageURI) {
        var options = new FileUploadOptions();
        options.fileKey="file";
        options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
        options.mimeType="image/jpeg";

        var params = new Object();
        params.value1 = "test";
        params.value2 = "param";

        options.params = {
        email : localStorage.getItem('email')
        }
        options.chunkedMode = false;

        var ft = new FileTransfer();
        ft.upload(imageURI, "http://localhost/app/photo.php", win, fail, options);
    }

    function win() {

        location.href="settings.html";
    }

    function fail(error) {
        alert("Erro ao enviar foto!");
    }

    </script>

Aparentemente funciona sem problemas. Porém, eu estou usando o código php abaixo para verificar se o arquivo existe ou não, assim, se existir ele vai colocar a foto caso contrario ele coloca uma imagem padrão:
  $setphoto =     "http://localhost/app/_profile_photo/$userid.jpg";
  $photodefault = "http://localhost/app/_profile_photo/default-image.png";

if (file_exists($setphoto)){

   echo "";

}

else{

    echo "";
}

O problema é que a função file_exists() não está reconhecendo o arquivo enviado e sempre pega a foto padrão.
O que eu já testei:
1- Verifiquei se o $userid esta correto no caminho da foto.
2- Usei a funcão como !file_exists() e ele passa a mostrar a imagem certo.
3- Colocar direto no html a imagem src="http://localhost/app/_profile_photo/aquiOIdDoUsuario.jpg"> - Mostra a imagem.
Eu preciso saber como fazer para a função file_exists() verificar que o arquivo está la.
Obrigado.
Answer: Tente algo assim:
$filename= 'http://localhost/app/_profile_photo/$userid.jpg';
$file_headers = @get_headers($filename);

if($file_headers[0] == 'HTTP/1.0 404 Not Found'){
      echo "O file $filename não existe";
} else if ($file_headers[0] == 'HTTP/1.0 302 Found' && $file_headers[7] == 'HTTP/1.0 404 Not Found'){
      echo "O file $filename não existe, e redirecionou para uma custom 404 page..";
} else {
      echo "The file $filename exists";
}

Retirado daqui https://stackoverflow.com/questions/10444059/file-exists-returns-false-even-if-file-exist-remote-url
Comment: Olá Lucas, fiz as alterações conforme o código passado e neste caso ele aparece que o arquivo existe. Porém, eu deletei o arquivo e mesmo assim ele diz que existe.
Comment: Trocando o 'HTTP/1.0 404 Not Found' por 'HTTP/1.1 404 Not Found' funciona. Alguém saberia dizer porque e se é confiável no sentido de funcionar?

Mostrar imagem enviada Phonegap + PHP


Seek Time vs Transfer Rate

Question: Estava lendo um pouco a respeito da ferramenta Hadoop para big data e me deparei com os termos Seek Time e Transfer Rate. Encontrei definições do tipo Seek Time é o delay para encontrar um arquivo/dado especifico e Transfer Rate é a velocidade para encontrar o arquivo/dado porém não estou muito satisfeito com as respostas que achei e não estou certo de que elas estejam certas.
Então gostaria de saber se alguém possui definições mais detalhadas a respeito dos dois termos e conseguiria responder essas dúvidas.

O que é Seek Time e Transfer Rate?
Qual é a real diferença entre eles ?
E quando é melhor usar um e quando é melhor usar o outro ?
Comment: nesse caso o mais importante e o tranfer, onde o MapReduce se baseia na velocidade aos dados.
Answer: Seek Time é o delay (o tempo que leva) para que o sistema encontre o arquivo (posicione o head de read/write no arquivo).
Transfer Rate, no contexto de throughtput, é a velocidade de leitura ou escrita desse arquivo.
Ambos são úteis e medem coisas distintas.
RDBMS por ser baseado em B-Tree, é altamente dependente de operações de Seek e por isso é mais eficiente para atualizar pequenas porções em grandes conjuntos de dados.
Já o MapReduce utiliza operações de SORT e Merge para recriar dados, o que acaba sendo mais dependente de Transfer.
Como o Transfer é mais rápido que o Seek e tem evoluído devido ao surgimento de novas tecnologias, o MapReduce é mais indicado para uso em cenários de BigData.

Seek Time vs Transfer Rate


How to enable logs for Language server in Visual Studio Code

Question: In the Language Server Extension Guide it says:

'If you are using vscode-languageclient to implement the client, you
can specify a setting [langId].trace.server that instructs the Client
to log communications between Language Client / Server to a channel of
the Language Client's name.
For lsp-sample, you can set this setting:
"languageServerExample.trace.server": "verbose". Now head to the
channel "Language Server Example". You should see the logs:

Where and how exactly do I specify this setting in VS Code?
Answer: Found it!
You need to create a new Node.js Attach run configuration in your launch.json.

{
    "name": "Attach",
    "port": 6009,
    "request": "attach",
    "skipFiles": [
        "<node_internals>/**"
    ],
    "type": "pwa-node"
},

And change the port from default 9229 to 6009. You also need to pass this 6009 port in the ServerOptions when instantiating new LanguageClient():

After that, when you start your plugin with F5, you can now go to the Run view and run the newly created "Attach" configuration alongside your client process:

When both processes are running, you can switch between them in the Call Stack section to see either your client console.logs or your language server's:

Just after posting a bounty, of course, like always...
Answer: What I do for php language server is adding "log": true to launch.json file, Then the compiler will try to show logs when you press f5 to start debugging. But from what I understand from the documentation you have shared in your question, You can follow this instructions (I don't guarantee this will work, As I mentioned this is the instruction for what you have shared in your question):

Press Ctrl+comma.
Search for "trace server".
Now languages should be listed. If you are on the latest version of vscode, choose verbose in any language server you want.
If you are on an older version of vscode, then choose the pencil button next to the language you want, and select "verbose".
Comment: Thank you very much for your help.
Do you know how I can view the output of console.log() statements executed within the server? They do not seem to display in the output.
Answer: Change that in the workspace setting of the newly opened VS Code instance titled [Extension Development Host], not the original VS Code.
Comment: It would be great if you could extend your answer with more specific information like: change this in the file named "blah.txt" ... Otherwise your answer will just help a reduced number of people
Answer: You can also change the default value in your package.json:
"languageServerExample.trace.server": {
                    "scope": "window",
                    "type": "string",
                    "enum": ["off","messages","verbose"],
                    "default": "verbose",

Comment: Is that the package.json for the client folder only or package.json at the root folder (lsp-sample)


Suppose a box contains 4 balls numbered 1,2,3,4. From this box, 2 balls are randomly drawn without replacements...

Question: Suppose a box contains 4 balls numbered 1,2,3,4. From this box, 2 balls are randomly drawn without replacements. Let X denote the larger of the two numbers on the balls selected. Find the probablity distribution table of X and draw it's bar chart.

Distribution table of X:
$$\begin{array}{|c|c|c|c|c|}\hline X & 1 & 2 & 3 & 4 \\ \hline f(x) & 0  & 1/6 & 2/6 & 3/6 \\\hline\end{array}$$
And I'm thinking these are the only options for the selection we have:
$\{(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)\}$
I would appreciate any form of help. And if I messed something up please feel free to fix it or let me know!  I want to figure this out but with your help because I'm learning and I'm unsure.
Answer: You are correct that 1 must have probability 0.
The 6 possibilities you list are equally likely. There is only one with 2 as the maximum and so this has probability $\frac{1}{6}$. Over to you for the others!
Comment: Thank you, I think I got it, you can confirm if you'd like. :)
Comment: Spot on Taljana. For similar questions you may well find it helpful to use 2-D possibility tables.
Comment: Thanks! And sorry what is a 2-D possibility tables?
Comment: A table with the (i,j) cell of the table representing  i being the number of the first ball drawn (or whatever the question is about)  and j  being the number of the second ball drawn.
Answer: You are correct that $f(1)=0$. Whether or not you want to include it in the table is a matter of preference (and/or your teacher's preference). I suppose it cannot hurt to keep it there for clarity.
You have correctly listed the possible outcomes. Can you reason why they are equally likely? From here you can fill in the table by counting how many outcomes have larger ball being $x$, and divide by the total number of outcomes $6$. For example, there are two outcomes with $3$ as the larger ball, so $f(3) = 2/6$.
Comment: Alright with your help I was able to find the others. You check each possibility where the chosen value of x is the biggest. Can you confirm it is correct?
Answer: I would do something like this:
Comment: Yeah I'm not sure how to create that on here but I'll be writing/drawing it on a paper. Thank you!