Tensor basis change

Question: I have a question regarding tensors and basis changes, however upon searching the web I've found an infinity of definitions for tensors so I'll have to give the one I know first:
Given a vector space $E$ over a (commutative) field $F$, we call, for $p\ge 1$ a $p$-covariant tensor a map of the type $$ f:E\times\overset{\text{(p)}}{\dotsb}\times E\to F $$
where $f$ is $p$-linear (linear in each of the $p$ components). We call the set of $p$-covariant tensors (over $E$) $ T_p(E)$, which is the set of $p$-linear maps from $E$ to $F$, in other words, $T_p(E) = \mathcal L_p(E,F)$.
Next we define for $f \in T_p(E),\  g \in T_q(E)$ the tensor product of $f$ and $g$, as $f \otimes g \in T_{p+q}(E)$, where: $${f\otimes g : E\times\overset{\text{(p)}}{\dotsb}\times E\times\overset{\text{(q)}}{\dotsb}\times E \to F} \atop {(u_1,\dots,u_p,v_1\dots,v_q) \mapsto f(u_1,\dots,u_p)\cdot g(v_1\dots,v_q)} $$
For example, for $p=1, \  T_1(E) = E^*$. For arbitrary $p$, it can be shown that $T_p(E)$ is a vector space over $F$, and if $e_1,\dots,e_n$ is a basis for $E$, with dual basis $e_1^*,\dots,e_n^*$ ($e_i^*(e_j) = \delta_{ij}$) then a basis for $T_p(E)$ is $\{e_{i_1}^*\otimes\dots\otimes e_{i_p}^*\}_{1\le i_1,\dots, i_p\le n}$
My question regards 2-covariant tensors. For simplicity, say we have $\varphi\in T_2(E)$, and $E$ is two-dimensional with basis $e_1,e_2$. Then $T_2(E)$ has the ordered basis $B_e = \{e_1^*\otimes e_1^*, \ e_1^*\otimes e_2^*, \ e_2^*\otimes e_1^*, \ e_2^*\otimes e_2^*\}$ and $\varphi = (a,b,c,d)$ in this basis.
What I want to know is, if $B_u$ is a similar basis of $T_2(E)$ relative to basis $u_1, u_2$ of $E$, how can I express $\varphi$ in basis $B_u$, using the fact that I know the basis change matrix that changes from $e_1,e_2$ to $u_1,u_2$ in  $E$? I know it has to do with a Kronecker product of matrices, but I don't quite understand how it works.
Answer: Let $B$ and $B'$ be two bases of $E$ and denote by $A$ the matrix of base change from $B$ to $B'$. First there are the induced dual bases on $E^\ast = T_1(E)$, denoted by $B^\ast$ and $B'^\ast$. The matrix of base change from $B^\ast$ to $B'^\ast$ is $A^\ast:= {}^t A^{-1}$ as you can easily check.
Now you have induced bases $\tilde{B}$ and $\widetilde{B'}$ on $E^\ast  \otimes E^\ast := T_2(E)$ with your notations. The matrix of base change from $\tilde{B}$ to $\widetilde{B'}$ is the Kronecker product of $A^\ast$ with itself.
Look at the Wikipedia page if you don't know about Kronecker products.
I think that the best way to understand this stuff is to learn tensor products of vector spaces and not only tensor products of maps.
Edit: In order to prove these things, you have to write carefully the matrix of basis changes. Write $B = (e_1,\dots,e_n)$ and $B' = (f_1,\dots,f_n)$. By definition of $A$, $f_i = \sum_{j=1}^n A_i^j e_j$ (you can also adopt the other convention). Now you want the matrix from $B^\ast$ to $B'^\ast$. This matrix $C$ should satisfy $f_i^\ast = \sum_{j=1}^n C_i^j e_j^\ast$. Evaluating at $f_k$ you find, $\delta_i^k = \sum_{j=1}^n C_i^j e_j^\ast(f_k)$. But $f_k$ is $\sum_{l=1}^n A_k^l e_l$. So $\delta_i^k = \sum_{j=1}^n C_i^j A^j_k$. These equations are satisfied for $C = {}^t A^{-1}$ which shows the first part.
For the tensor product, you have to understand how to write $f_{j_1}^\ast \otimes f_{j_2}^\ast$ with $e_{i_1}^\ast \otimes e_{i_2}^\ast$. We have $f_{j_1}^\ast \otimes f_{j_2}^\ast = (\sum_{i_1} C_{j_1}^{i_1} e_{i_1}^\ast) \otimes (\sum_{i_2} C_{j_2}^{i_2} e_{i_2}^\ast) = \sum_{i_1, i_2} C_{j_1}^{i_1} C_{j_2}^{i_2} e_{i_1}^\ast \otimes e_{i_2}^\ast$.
Compare these coefficients with the definition of the Kronecker product; you find the same thing (with a certain ordering of the bases in $T_2(E)$).
Comment: Thanks, is a proof to be found somewhere?

Tensor basis change


character tables for groups of order $pq^2$

Question: What is the character table for groups or order $pq^2$?  The classification of order $pq^2$ groups has already been discussed in relation to Sylow theory.
For the Abelian groups, $\mathbb{Z}_p \oplus \mathbb{Z}_{q^2}$ and $\mathbb{Z}_p \oplus \mathbb{Z}_q \oplus \mathbb{Z}_q$, all the irreducible representations are 1-dimensional.
According to some group theory lecture notes I found online (bottom of page 8), there is only one other group when $q \not\equiv 1 (\mod p)$ and two when $q \equiv 1 (\mod p)$.   I am asking for  the character table in any or all of these cases.
Comment: Try looking at the "method of little groups" as explained in Serre's book.  This gives a way of calculating all irreps of any group that has a large normal abelian subgroup as certain induced representations.
Comment: There are more groups of order pqq than you indicate.  For instance, there are 8 groups of order 5887 up to isomorphism, not just four.
Answer: Any group of order $pq^2$ is a semidirect product by an abelian group. Indeed, by Sylow theory either the Sylow $p$-subgroup or the Sylow $q$-subgroup is normal. The Schur-Zassenhaus theorem says that if a normal subgroup has order coprime to its index, then it has a complement.
To classify all irreducible character of semidirect products by abelian groups is a very nice exercise in character theory. See another answer of mine for details. This is from Serre's representation theory book Part II, Section 8.2.


Overwriting content from one table to existing table

Question: I have two different tables with two colums that have the same name, datatype and size.
My issue:
When I try to copy the content from one column to the other,
update Table1
set Column4 = (select Column1 from Table2);

I get an error. (subquery returns more than one row)
My question:
Is there a way for me to copy the content from Table2 to Table1 in a similar fashion as the code shows above?
Answer: Use Insert ... Select
Insert INTO Table1 (Column4)
SELECT Column1 FROM Table2

Comment: I get the error message: Duplicate entry '0' for key 'PRIMARY'.
Table1 contains a key and a couple more columns than Table2. Which could be related to the issue, but I'm not sure how.
Comment: @user5553 you will need to extend my query as per your actual table structure, to include rest of the columns


How can I tell my C# project where to look for DLLs?

Question: I'm currently trying to use custom functions with JUST.Net.
I've created this function in a project called Foo.JUST.CustomFunctions:
using Newtonsoft.Json.Linq;

namespace CustomFunctions;

public class Normalizer
{
    public static object TryUnquote(object value) =>
        value is string quotedValue
            ? JToken.Parse(quotedValue)
            : value;
}

I am trying to register it with:
// FIXME: Use Dependency Injection!
JUSTContext context = new();

context.RegisterCustomFunction("Enpal.JUST.CustomFunctions", "CustomFunctions.Normalizer", "TryUnquote", "tryunquote");

But the system throws this exception:

System.IO.FileNotFoundException: 'Could not load file or assembly
'C:\projects\SalesforceEventListenerService\Salesforce.EventListener\Foo.JUST.CustomFunctions.dll'.
The system cannot find the file specified.'

Which makes perfect sense because Visual Studio is not putting it there when it builds the project but rather it can be found in "C:\projects\SalesforceEventListenerService\Salesforce.EventListener\bin\Debug\net6.0-windows8.0"
How can I make sure the system looks in the right place?
And what, if anything, more will I need to do to make sure this also works when it hits the Azure DevOps CI/CD pipeline?
Comment: Handling AssemblyResolve is explained here: https://learn.microsoft.com/en-us/dotnet/standard/assembly/resolve-loads    Basically when .NET can't figure out the file path, you have the chance to find the DLL yourself, load it, and return it to .NET which will go on without raising FileNotFoundException.
Comment: If you want to fix the symptom, you can handle the `AppDomain.AssemblyResolve` event.  But probably better to find the root cause.
Comment: @BenVoigt, Cheers for the response.  Care to elaborate how I might either do the handling or search for the root cause?
Comment: @BenVoigt, Cheers.... Looks promising for local development, but I'm not sure what I'd need to do with the solution so it would continue to work when it hits the pipeline and eventually gets deployed to an Azure App Service...
Answer: I was able to get this working like so:
_ = Assembly.GetAssembly(typeof(Normalizer));

JUSTContext context = new();
context.RegisterCustomFunction("Enpal.JUST.CustomFunctions", "CustomFunctions.Normalizer", "TryUnquote", "tryunquote");

Comment: Nice solution, force .NET to go find it while your code is active, before the other library gets a chance to reconfigure search paths.


Calling union member in struct with c

Question: Below is piece of code which I am working on..
struct ArgusRecord {
   struct ArgusRecordHeader hdr;
   union {
      struct ArgusMarStruct     mar;
      struct ArgusMarSupStruct  sup;
      struct ArgusFarStruct     far;
      struct ArgusEventStruct event;
#if defined ARGUS_PLURIBUS
      struct ArgusVflowStruct vflow;
#endif
   } ar_un;
};

I have defined my variable as
struct ArgusRecord MyRecord;

I can call the first member MyRecord.hdr If same way I call the union members such as mar, sup .. etc I am getting the error message ..... has no member named 'mar'
Please some one tell me how to call the union members.
Comment: access union members as `MyRecord.ar_un.`
Answer: You have to call using the union name ar_un
MyRecord.ar_un.mar

Answer: Members of unions are accessed with dot notation.
In other words, mar must be accessed like this:
struct ArgusRecord record;
record.ar_un.mar (...)

Calling union member in struct with c


Can I loop inside an PHP array like in JavaScript?

Question: Is possible to loop trough an array in php like we do it in JavaScript for example without using the for ( $X  as $Y){}
For example we in JavaScript we can use this code :
var names=['john','tom','jane'];

for (i=0;i<names.length;i++){
        names[i];
 }

Now in the case of using the same method for this loop it would be this one  and it gives us an error :
$names=['john','tom','jane'];
    for ($i=0;$i<$names.length;$i++){
        $names[$i];
    }

So is there a way around this?
Comment: `foreach` may also be a good option for you; it eliminates having to dereference the array.
Comment: [`sizeof()`](https://secure.php.net/manual/en/function.sizeof.php)
Comment: @GregSchmidt  Yes i was only was not sure if this type of method would work on PHP like i does in javascript
Comment: Did you Google `PHP foreach`?
Answer: You can use count() for the length of the array.
$names = ['john', 'tom', 'jane'];

for ($i=0; $i < count($names); $i++){
  echo $names[$i];
}

Answer: First of all the code gives you errors because you have written lenght wrong. It should be sizeof() or count().Secondly there is also another option for looping through array. That's foreach. As I'm not on the computer you could check out the php manual for foreach and how to use it. I hope I was useful !
Comment: You don't get the size of an array by writing `length` in PHP. `count()` or `sizeof()` are the methods for that.
Comment: Oops my bad, yes you are correct ! I updated my answer !


Expected number of trials before first success

Question: I have a question which I hope statistics experts on this forum can help me with.
Given a time series data D(t) with mean m and median M what is the expected time (number of trials) before value y is encountered for the first time after value x is encountered.
For example, if given numbers 2,5,2,6,3,7,6,3 (with discrete time starting at 1 with time step 1) and x=2 and y=6 the answer to this question with this data would be 2.66 ((3+1+4)/3 = 2.66).
I am looking for a statistical solution as opposed to an algorithm to calculate this.
Apologies in advance if something is not fully defined.
Comment: In the example, why do you count distance 4 since in 26376, the last 6 is not "encountered for the first time after value 2 is encountered"?
Comment: I don't think I understand your example. Can you explain how you get $3$, $1$ and $4$? (Why don't you have $6$ if you have $4$?)
Comment: Did/Tunococ - agree with you both distance 4 is not relevant. I get 3 as distance between the first 2 and 6 and 1 as distance between second 2 and first 6.
Comment: Is the distribution of the time series known?
Answer: Let $T_n$ denote the time when the $n$th time value $x$ is observed, and $T_n+D_n$ the first time after $T_n$ when the value $y\ne x$ is observed. For every $N\geqslant1$, let $\nu_N=\sup\{n\geqslant1\mid T_n+D_n\leqslant N\}$. The question seems to ask for the limit when $N\to\infty$ of
$$
E[\Delta_N\mid\nu_N\geqslant1],\qquad\text{where}\ \Delta_N=\frac1{\nu_N}\sum\limits_{n=1}^{\nu_N}D_n.
$$
Assuming that the letters produced are i.i.d. and uniform on an alphabet of size $a$, each random variable $D_n$ is geometrically distributed, with $P[D_n\geqslant k]=\left(\frac{a-1}a\right)^{k-1}$ for every $k\geqslant1$, but the random variables $(D_n)$ might not be independent--hence one would like some confirmation from the OP that this is the model considered, or not, before going any further.
Comment: Did - this is indeed the model being considered with one exception - the the values produced are not i.i.d nor uniform. The value generating function is dependent on the last value produced with probability of it being the same highest and further away - lowest, i.e. if the last value was 6 the next one is more likely to be 6 again rather than a 10. Any simple function that describes this relationship will do for the purposes of this question.


Recalculation of Balance Factor in AVL Tree

Question: After performing a rotation to balance an AVL tree, immediately after an insertion, how can I change the balance factor of all the parent nodes (appropriately, by -1 or 1)?
Each node of the AVL tree has the following structure:
<code>typedef struct _avlTree
{
 nutbolt part;
 int balanceFactor;
 struct _avlTree *left,*right;
} *avlTree;
</code>
I have set the balance factor as per the definition given on Wikipedia.
Do I need to have a pointer to the parent node in each node?
Comment: Are you implementing the AVL code, or are you using somebody else AVL code?
Comment: Trying to implement own code.
Comment: well someone seems to have stolen your data structure declaration then.
Answer: You either need a parent pointer for each node, which will need modification too whenever you change the tree structure. Or you need to keep track of all visited nodes beginning from the root, either automatically by the recursion or manually in an array if you have an iterative approach.
You shouldn't miss this for an in-depth study of the topic:
http://www.stanford.edu/~blp/avl/
Answer: Maybe have a look at AVL C Library for inspiration?


function for reversing an array in C (K&R 2nd ed.)

Question: Trying to do Exercise 1-19 of K&R 2nd ed., e.g. writing a function to reverse a string. I thought I managed, but the print output looks strange :-) If I use STRINGSIZE 5 the output is
Original String: hello
Reversed String: ollehhello. If I use STRINGSIZE 6 to keep in mind the '\0' string end character and modify the while-loop to while ((outputString[STRINGSIZE - (i + 2)] = inputString[i]) != '\0'), then I get Original String: hello
Reversed String: olleh?hello, I guess the ? is some random character coming from a '\0' added to the reversed string in the while-loop at position 5; but hello is again added. Could anyone explain how come hello gets added to the end of olleh and how can I get rid of it so that I only get the proper reversed string ?
Here is the code:
#include <stdio.h>
#define STRINGSIZE 5

void reverseString (char inputString[], char outputString[]);

int main(void) {
    char stringToReverse[] = "hello";
    char reversedString[STRINGSIZE];
    reverseString(stringToReverse, reversedString);
    printf("Original String: %s\nReversed String: %s\n", stringToReverse, reversedString);
}

void reverseString (char inputString[], char outputString[]) {
    int i;
    i = 0;
    while ((outputString[STRINGSIZE - (i + 1)] = inputString[i]) != '\0')
        ++i;
}

Comment: You didn't null-terminate the reversed string. Using `printf` on a character array which isn't null-terminated leads to undefined behavior.
Comment: There isn't even room in `reversedString[]` to hold `"hello"`, forwards or reversed.
Comment: @JohnColeman Thank you, John, I think I implemented the 0-termination with `if (i == (STRINGSIZE)) {
            outputString[STRINGSIZE] = '\0';
            break;
        } ` after the ++i in the while-loop, but the issue was obviously the declaration of the target string size as pointed out by @4386427
Answer: First, the character array reversedString[] does not have enough space to store the null terminator of the string "hello". One option is to use a variable length array here:
char reversedString[strlen(stringToReverse) + 1];

VLAs were introduced in C99, and made optional in C11. As I remember it, K&R does not include coverage of variable length arrays, since even the 2nd edition was published before this.
Another option that would be compatible with C89 is to use the sizeof operator:
char stringToReverse[] = "hello";
char reversedString[sizeof stringToReverse];

Here, the result from the sizeof operator is known at compile time, and can be used in the declaration of a fixed size array. This size includes space for the null terminator, in contrast to the result from strlen("hello"). Note that this would not work with char *stringToReverse = "hello";, since then the sizeof operator would give the size of a pointer. This also would not work if stringToReverse had been passed into a function first, since then the array name would have decayed to a pointer to the first element of stringToReverse.
In the reverseString() function, the length of inputString needs to be determined (since STRINGSIZE is no longer being used); this can be done with strlen(), or in a loop. Then, critically, the function must be certain to add a null terminator (\0) to outputString[] before returning. Also note that a return statement has been added to the end of main() to make this truly C89 compatible:
#include <stdio.h>

void reverseString (char inputString[], char outputString[]);

int main(void) {
    char stringToReverse[] = "hello";
    char reversedString[sizeof stringToReverse];

    reverseString(stringToReverse, reversedString);
    printf("Original String: %s\nReversed String: %s\n",
           stringToReverse, reversedString);

    return 0;
}

void reverseString(char inputString[], char outputString[])
{
    int length = 0;
    int i = 0;

    /* Get inputString length; or use strlen() */
    while (inputString[length] != '\0') {
        ++length;
    }

    /* Copy to outputString[] in reverse */
    while (i < length) {
        outputString[i] = inputString[(length - i) - 1];
        ++i;
    }

    /* Add null terminator */
    outputString[i] = '\0';
}

Answer: First I'll suggest that you change this line:
    char reversedString[STRINGSIZE];

to
char reversedString[strlen(stringToReverse) + 1];  // + 1 to make room for the string termination

Then I would do something like:
void reverseString (char inputString[], char outputString[]) {
    int i;
    int len = strlen(inputString);
    for(i=0; i<len; ++i)
    {
        outputString[len-i-1] = inputString[i];
    }
    outputString[len] = '\0';  // Terminate the string
}

Comment: Note that this solution depends upon variable length arrays, which weren't in the Standard when K&R was published (hence, not covered in K&R).
Comment: As noted, using `strlen()` to determine the size of `reversedString[]` would not be kosher for the language of K&R2 (it was published in 1989 or thereabouts, just about the time the original version of the standard was finalized; variable length arrays were added to C99, ten years later), there's an easy alternative that would work: `char reversedString[sizeof(stringToReverse)];`.  Note that `sizeof` includes the terminal null too; no need to add 1.
Comment: Thank you, 4386427, for the answer, the generalization of the function with `strlen(inputString)` instead of `STRINGSIZE ` was also helpful :-)


How do I allow users to add additional data to a mySQL users database table after they have already joined?

Question: I am fairly new to PHP but am in the process of hacking together a web app focused around gardening. I followed a tutorial and built a registration and login system. I want the user in the app to be able to input additional data at a later date including fields like Postcode/Zip code and the ability for them to select 'Plants' to add to their account. I know how I create the form but I want to know how to add this data to the database so that it corresponds with their account details such as username which are already in the database.
Comment: you can ask these kind of question on here reddit.com/r/php or reddit.com/r/wedev you won't get answer to this question on this website. you need to provide some codes
Comment: You take the data and update the specific row in the database that you identify via the username/userID.
Comment: Please complete some tutorials and learn at least the basics. If you have specific questions later, please come back and ask.
Answer: Hopefully you have a column in the users table called 'id' or something similar which auto increments and is unique, this gives you a point of reference for each user.
When the user logs in, using his username and password, you can retrieve this id, and then use it throughout your app when working with the table or other tables that are related (using the id).
So if you were to add/update information in the table you'd use the user's id eg:
<code> UPDATE users SET postcode = 'sg12988' WHERE id = '8374'
</code>
You can read more about SQL commands here or here .


Get Request id's per app

Question: From documentation:

If a user clicks 'Accept' on a request, they will be sent to the canvas URL of the application that sent the request. This URL will contain an additional parameter, request_ids, which is a comma delimited list of Request IDs that a user is trying to act upon:
  http://apps.facebook.com/[app_name]/?request_ids=[request_ids]

How to get all request id's for the current app without knowing their id's and getting them from url?
Answer: You could use a FQL query:
<code>SELECT recipient_uid, request_id, app_id
FROM apprequest
WHERE recipient_uid = me() AND app_id = 182197005148613
</code>
Comment: great answer ... but have you mentioned that it returns only 1 request in the array (latest one) ... facebook bug I guess
Comment: it should return more if there are more.

Get Request id's per app


Finitely generated group unlikely to be generated by randomly chosen elements.

Question: A well known interesting fact is that if two integers are picked "at random" (in an appropriate asymptotic sense), the chances they generate the integers is $6/\pi^2$. So, the integers can be generated by two randomly selected elements with non-vanishing probability.
I am wondering if there exists a (finitely generated) group that is almost certainly not generated by any finite number of "randomly chosen" elements. That is, is there a group $G$ with generators $\{g_1, ... , g_n\}$ such that for every $k$, our if we pick $k$ elements of $G$ at random, there is a vanishingly small probability that the selected elements generate $G$.
To clarify, select elements randomly from balls of a given radius in the group, using the word metric with given generators, and see if the probability $k$ elements chosen from the ball generate $G$ tends to $0$ as the radius of the balls grows. This definition is compatible with the above result about the integers.
Comment: One problem with a general finitely generated group is that the property for a subset $L$ that $|L\cap B_n|/|B_n|$ for $B_n$ balls, is sensitive to the choice of generating subset. There's no reason at all that balls are the right way to measure things. For instance, in many amenable groups, the balls are not Følner.
Answer: All non-abelian free groups have this property, although it really depends how we flesh out the phrase "randomly chosen".
The most obvious way of addressing this problem is to do as suggested in the question. That is, consider balls of increasing radius and go as follows:

fix a basis $X$ of your free group $F$,
find a function $f: \mathbb{N}\rightarrow\mathbb{R}$ such that
$$
\frac{\#\{\text{non-generating sets of size $n$ consisting of words of length $\leq k$}\}}
{\#\{\text{sets of size $n$ consisting of words of length $\leq k$}\}}\geq f(k)
$$
Prove that $\lim_{k\rightarrow\infty}f(k)=1$.

You can prove that such a function exists*, and is in fact of the form $1-ae^{bk}$ (so the number of generating sets decreases exponentially with $k$). Therefore, all non-abelian free groups have this "random non-generation" property.
In fact, if you are comfortable with presentations, instead of taking the ball $\{\text{non-generating sets of size $n$ consisting of words of length $\leq k$}\}$ we could have taken the ball $$\{\text{sets of size $n$ consisting of words of length $\leq k$ and with $\langle X\mid S\rangle$ non-trivial}\}.$$ Refining this ball further gives us the notion of a "random group"; this is called the "few relator" or "$0$-density" model of random groups, and such groups are known to be infinite (indeed metric small cancellation and so hyperbolic), as well as lots of other things. What is interesting is that the theory has been developed to be much more general than the "growing balls" idea, and there is a theorem which says that a "random group of density $>\frac12$ is either trivial or cyclic of order $2$". Therefore, changing the model changes the result (I do not know though how this impacts on the question at hand, about generation). For more details on random groups and their various models see the book Yann Ollivier, A January 2005 invitationto random groups which you can find on Ollivier's webpage here (Section I.3.c gives further properties of the random groups I describe above).
*standard arguments use small cancellation theory though, and so are non-trivial but prove much more.
Comment: Great answer (and it's satisfying to know my conjecture in my answer was in fact correct).
Answer: I think that a free group (not free abelian) on two generators $a$ and $b$ has this property --- the odds of two longish words "cancelling" so that their product is one of the four generators $a$, $a^{-1}$, $b$, $b^{-1}$ is pretty small. (OK, other generators are possible, too, but...) There's probably a nice topological proof of this having to do with the universal cover of the figure-8 curve, but I don't see it offhand.
Comment: Fair enough...but I'm still betting that's the case. On the good side, free groups are the only ones you have to study, in the sense that if you get a result here, it can be"pushed forward" to other groups that are quotients of free groups (i.e., all other groups).
Comment: I imagine two random generators wouldn't be able to do it, but at least to me it's not obvious that three or more wouldn't be able to.


Where are all the post-event olympic interviews?

Question: I'm used to seeing athletes who win their event in the Olympics interviewed straight after but this Olympics I've seen basically no interviews at all. Where are they all? I'm in Australia and our network only seems to get interviews with Australian athletes. If I VPN to France and watch on France TV I only see interviews with French athletes.
All winning athletes seem to give interviews to a microphone which just has the Olympic rings on it so I thought it was the Olympic channel but that just seems to play documentaries all day. Where can I see or hear these interviews?
Comment: I think there's a case to be made for editing the title of this: something like, "Why is there no one site with all Olympic athletes' post-event interviews?"
Answer: When athletes finish their competition, they go through a section known as "the mixed zone" (because that's where the athletes "mix" with the media). The Olympic mixed zone at the track (which is the one I'm most familiar with) is usually broken down in three sections; first there are rows of television broadcasters arranged such that the cameras show the athlete with the track in the background. Next come the radio broadcasters (a shrinking crew) and finally, out of sight of the track and into the bowels of the stadium, the print media (including websites, these days).
The television broadcasters are all "rights holders", which is to say, the networks who have paid for the right to broadcast the Olympics in their territory. (In the USA, that's NBC.) This means the athletes will be passing by crews from NBC, Eurosport, BBC, CBC, CCTV, etc. etc., any and all of which may choose to buttonhole the athlete for a quick interview or let them move on by. Because the broadcasters have their own audiences in mind, they're most likely to talk to the athletes of their country, although athletes like Usain Bolt could take most of an hour to work through the mixed zone since every single broadcaster would want a minute from him.
To your question, though, if there is an Olympic crew in place, they're unlikely to put their footage online quickly because they're limited by terms of the agreements with the right-holders. Those agreements might prevent the IOC (or the LOC) from posting video that would compete with that of the rights-holders, which would result in the post-race interviews being fragmented by broadcaster in the way you describe.
There is one central interview which is run by the LOC, but it's not video: it's what's known as the "flash quotes" team. They sit between the broadcasters and the print media and get a very brief interview (three or four sentences) with every heat winner or medalist. That interview is transmitted to the entire press corps, something like a pool reporter, so if a media outlet does not have the staff to have a reporter on hand in the mixed zone, they can still run a story with a quote from the athlete. This is why you'll often find several stories in different publications with the same quotes from an athlete. Flash quotes are a specialized skill; they prioritize speed and being able to speak to many athletes, so being multi-lingual and/or a fast typist is more important than, say, punctuation, or even solid English grammar. (One of my jobs at an event once was copyediting flash quotes in the hours after a session ended; they can be a mess.) But there is no video equivalent of flash quotes that I'm aware of.


How many samples do I need for OCR problems?

Question: I am thinking about collecting samples of hand written digits (0 to 9) from people. I'll try to test different algorithms for optimal character recognition- some form of neural network and random forest may be! I have planned to collect 20 entries from each person (the same digit being asked to write twice) so that I can make a training set and a test set.
Is my idea correct? How should I statistically decide how many samples will suffice?
Answer: Overall suggestion:
There are many open data sources for digit OCR available, have you checked about MNIST? Also, there are works done for algorithm comparison as you described in the same line I provided. Please check it first.
If you want to do the same thing, why? Is there anything the MNIST doesn't offer? If there are some, I am sure you can find other open data online. Such as this one.
Collecting data by yourself is very costly and it is better to have a good reason to do it.

To your question:
It is hard to say how many data are needed. It depends on your model and the complexity of the "task". Finally the quality of the data.

For example, if you want to use a complex model (neural network), it is better to have hundreds of thousands data points. On the other hand, it is a simpler model (say, logistic regression), less data is required.
For example, if you want to build a classifier to classify 0 vs 1, then it is a relative simple task (comparing to classify 0 and 6), and less data will be needed.
In addition, if the quality of data is low, say all the digits are blur or have low resolution, then, more data are needed.


Amplifier has no aux in, what alternatives can I use?

Question: As stated my amplifier has no Aux in jack. It's hindering me from practicing with an otherwise (imo) great amp (a Vox Pathfinder 15r).
Been  thinking of using this to interface between the music player and my amplifier since the pathfinder 15r has a mono lineout: Tascam CD GT1 mk2
or maybe this? USB Guitar Link
thoughts?
Comment: What do you want to connect to your amp, other than a guitar?
Comment: I have an effects chain where in I connect my guitar into, that goes directly into the amplifier
Answer: The USB guitar link is for recording your guitar into a computer. Useful, but not relevant to your needs here.
To play something like a CD player through a guitar amp, it is sometimes enough to connect the headphone output of the CD player, to the instrument input of the amp. You will need to turn the headphone volume right down, and turn down the gain/distortion on the amp - because the amp will distort a strong signal. Remember a guitar amp is designed to colour and distort the sound.
However, if what you want to do is practice alongside recorded backing music, you would probably be better off letting your guitar amp do what it's good at -- amplifying a guitar -- and have the backing music come from a separate amp and speaker. A cheap boombox or a set of PC speakers would be fine.  This way you can adjust the tone of your guitar, without affecting the backing music.

If you plug your guitar into the guitar amp, connect the amplifier's line-out to the Tascam's line-in, and listen to the output of your Tascam through headphones (or some other amp/speaker setup -- one designed not to distort or colour) -- then you are effectively using your guitar amp as a bulky effects pedal.
That's fine, but note that some of the tonal qualities provided by the guitar amp come from the physical build of the speaker and cabinet, and of course if you're not using those, you don't get the benefit from them.
Comment: I think it should be stressed that the music player will sound horrible coming out of the amp, especially with the gain/distortion dialed up.
Comment: I see. So my option of using the tascam as an interface between the guitar amplifier, and then the music player will just color my tone more and in the end won't help me at all won't it? Also, if I were to plug the USB guitar link to a wallsocket wouldn't it serve as some sort of splitter that accepts the signal from the guitar and from the mp3 player?
Comment: @galley: The USB link into an wall socket would combine the signals from the guitar and MP3 player, and send them into the wall... The output is the USB plug with purpose to record on a computer using some recording software.
Comment: looks like it didn't even notice that there wasn't any aux in for that device lol.
Answer: Your simplest option would be to replace the amp with one that has an aux in.That way, the impedences for gtr. and mp3 or whatever are better balanced, and individually controllable for volume, tone etc.Provided you eq. your own amp, the sound will not be as awful as suggested - guitar amps WILL produce clean sounds when the gain is not excessive.Or, find another practice amp just for the backing tracks - 10 / 15 watts will be ample.Or, buy a small mixer - Behringer do great ones, and feed gtr in one channel and sounds through another.Problem with that is - if you want distortion on gtr., you'll have it on the other sound source as well.Good luck.
Comment: ahhh, this seems close to my plan of using a tascam cd gt1 to sit between the amplifier and the music player then right? worried though that it will just color my tone since the tascam cd gt1 is also an amplifier
Answer: Different answer. I used  to use a Tascam,and the chain was gtr - Tascam - amp., which is probably the path you mean. Yes, it'll work.The CD player in the Tascam will obviously let you play CDs,and you can plug the output from mp3 etc. into 'line in' on the Tascam. Be aware that the balance between inputs  may be possible but you'll need to change the gain via the output source.  All this will work, and the effects will only colour the guitar sound, so no real need to add an effects unit into the chain.  If you did, it'd be gtr - effects - Tascam - amp.If all fails, read the instructions,which are fiddly to follow, but help tremendously.
Comment: It just means you shouldn't connect the speaker output from an amp - because it'll be too loud a signal. Line-out into line-in is fine. The Tascam doesn't know what device the line out came from!
Comment: oh okay, that's nice. how about guitar-effects-amplifier-tascam? then the music source would be plugged into the tascam as well, all mixed into one line out for headphones?
Comment: how about mixing everything into a ABY box? would that be to the same effect without tone coloration?
Comment: I think it says don't plug amps into Tascam, but it'll be on the instructions.If you need to use cans, cut out the amp.
Comment: Ahh, didn't know about that part! thanks for the heads up. Looks like using the tascam is a no go then, unless I do your suggestion of putting the tascam before the amplifier, problem I think though is the music would mix into the amp and would be getting the same eq settings and what not from the amplifier.
Comment: just read the manual and indeed I can't connect an amplifier to it. whew good thing I havent purchased the unit yet.
Comment: ahh so that's how it works, and so I learn. the pathfinder 15r has a mono line out on the back of it. which should go into the 3.5mm line in. also after reading the manual it says that the line in accepts a pre amp, which means it can also accept an amplifier also?
Comment: The manual is just giving you examples of things that the line level signal might come from. Line level is line level. The input doesn't care what's on the other end of the wire. It only cares that the peak voltages are within line level range.
Comment: ahh so I can assume that an amplifier would work with it then. I was looking into small mixers and found this [behringer 302](http://www.behringer.com/EN/Products/302USB.aspx) also this [one](http://www.behringer.com/EN/Products/UFO202.aspx) looks like this would answer my needs?
Comment: That, or any mixer, from Behringer, will be fine, in my opinion.Used them for years with no problems.The Tascam is more of a pre-amp. than an amp, so it's not going to cause you problems.


Detect if an incoming value in streaming data is an outlier

Question: I am reading a sensor that gives data. Sometimes some data is false. I can store some samples before and I would like to detect a glitch on the fly.
Process :

Values are integers (distances in centimeters)
I get distances from a sensor (~ 200Hz)
The distance read is not always correct, and have outliers
There can be up to 10% outliers
Typical values are [100;2000]
The standard deviation is about 2
The process is dynamic up to 150/s
The measurements follow a gaussian curve (if static)
Typical outliers are [0;20] U [950;1200]

I need to filter the measurements on the fly to be sure to get at least 100Hz.
I first thought of a Kalman filter, it would be working well if I didnt have the outliers. Indeed, there is no correlation between those and the true value (Communication problems/or bug). The outliers do not carry data at all.
I would like to filter outliers before passing data into the Kalman filter and get more precise values.
Is there a simple way to implement it on a microcontroller? I do not need the solution done in C, I can implement it. What I need is inspiration! :D
Comment: I understand you would like to get rid of the outliers then apply a kalman filter.
Your question is specific, however you are not specifying your final goal (bigger picture).  Sometimes things can be worked around depending on the task.
Comment: The task is to acquire data as precise as possible to locate a flying multicopter based on on-board lasers
Comment: Possibly worth looking at [tag:outliers], or [tag:time-series], or [tag:control-chart] but you'll need to explain in more detail for this question to be answered.
Comment: "Is there a simple way to implement it on a microcontroller?": are you really looking for a *statistical* answer, or a electronics implementation?
Comment: I can implement it myself, I am sure the algorithms exists but I do not know where to look. The aim is to implement it anyway.
Comment: Please edit your post so that people can give you an answer.
Answer: I believe this article is quite similar to what you are trying to accomplish. They are able to reconstruct the signal without removing the outliers before it is transmitted. You might not have to follow the entire approach.
Here's one idea: Think compression. What doesn't compress well is a possible outlier candidate (although not necessarily). There are many compression algorithms out there. I would look into compressed sensing and random projections, these methods are fast. If the 'buffer' doesn't compress well that means it contains an outlier. For "Doesn't compress well" you require a measurement relative to a near optimal compression. For this you need to compute some stats over large amounts of data.
Random projections should be easy to implement, although don't solve your problem entirely, you still have to find the outliers. Plenty of methods, one of the most popular one is LOF. I believe it is possible to implent it as an online method as well. This one is specifically designed for streaming data.
Comment: Thanks for thoses methods, I will implement it later since I finally did a simple prediction on the value, then compare the incoming value with the predicted one.
Answer:
An outlier is a statistical term for any data value that seems to be out of place with respect to the rest of the data. Formally, given user-defined parameters p and D, and a distance function F, an object O in a dataset T is said to be a distance-based outlier if at least fraction p of the objects in T lie greater than distance D from O.

I would recommend that you check out the following paper by Bay and Schwabacher: http://stephenbay.net/papers/outliers.kdd03.pdf
Moreover, here is a nice compiled list of some additional papers that might be of interest to you: http://www.cs.ubc.ca/nest/dbsl/outliers.html


How can cofactor matrix help find eigenvectors?

Question: Browsing around for math literature related to eigenvalues and eigenvectors I did not read yet, I came across the following algorithm. It seems to be functional for all 3x3 matrix I tried (symmetric, diagonal, triangular, etc. for a grand total of a few 10000 matrices), but I do not fully get the math logic behind...
Let $M$ be an arbitrary $3 \times 3$ matrix.
Let $\lambda_1$, $\lambda_2$, and $\lambda_3$ be the eigenvalues of $M$ (i.e.: the roots of its polynomial obtained by solving $det(M - \lambda I) = 0$).
Now, let
$
P = (M - \lambda_{i} I) = \begin{bmatrix}
a & b & c \\
d & e & f \\
g & h & i \\
\end{bmatrix}
$
The algorithm then creates three vectors $v_{ij}$ made of the determinant of the sub matrices $M[i,j;]$ as follow:
$
v_{01} = \begin{bmatrix}
   bf - ce  \\
 -(af - cd) \\
   ae - bd  \\
\end{bmatrix}
$
$
v_{02} = \begin{bmatrix}
   bi - ch  \\
 -(ai - cg) \\
   ah - bg  \\
\end{bmatrix}
$
$
v_{12} = \begin{bmatrix}
   ei - fh  \\
 -(di - fg) \\
   dh - eg  \\
\end{bmatrix}
$
From there, we find that the eigenvector associated to the current $\lambda_i$ is the $ \max \left ( |v_{01}|, |v_{021}|, |v_{12}| \right )$ dividing its corresponding vector to produce a normed eigenvector.
Q1: Could you explain and provide a bit more details about the math behind this algorithm?
I find some similarities with what I have done by substitution to express one unknown as a function of the others to inject it in a third equation and then solve the system by fixing a free unknown. The above algorithm looks, to me, like a great shortcut to obtain the eigenvectors. Furthermore, when I made my regular calculus there were some "corner cases" to check for in order to avoid, for instance, division by zero.. which seems not to be a problem here!
Q2: Although I doubt it, can this adapted to $2 \times 2$?
Q3: Can this be extended to higher matrix dimensions?
EDIT:
Staring at it long enough I realized that the vectors $v_{ij}$ form the rows of the cofactor matrix. I also found out that the odd lines of the cofactor matrix $P$ are timed by -1 (but this does not seem to change the final result).
Now I realize that this can be generalized to higher dimensions matrix (I went up to 5x5).
However, I still don't get the relation so Q1 is still a question..
Q4: why don't we always use this method to compute the eigenvectors? I mean, apart from the higher number of multiplications (which heavily impacts the performance though), this seems to be working for any types of matrix ..
NOTE: I renamed the title of the post accordingly.
Comment: The basic math behind it is the following relation: $ M \text{adj}(M) = \det(M) I $
Comment: So in the case of this problem $P \ \text{adj}(P) = 0 $ where the right-hand side is the $3 \times 3$ zero matrix.
Answer: Q1. As we know, the eigenvector $\boldsymbol{v}$ must solve
$$
P\boldsymbol{v}=(M-\lambda I)\boldsymbol{v}=\begin{bmatrix}
a & b & c \\
d & e & f \\
g & h & i \\
\end{bmatrix}\boldsymbol{v}=\boldsymbol{0}\,.
$$
In other words, it must be orthogonal to all three vectors
$$
\boldsymbol{x}=\begin{bmatrix}
a  \\
b \\
c  \\
\end{bmatrix}\,,\quad
\boldsymbol{y}=\begin{bmatrix}
d  \\
e \\
f  \\
\end{bmatrix}\,,\quad
\boldsymbol{z}=\begin{bmatrix}
g  \\
h \\
i  \\
\end{bmatrix}\,.
$$
The existence of a non zero eigenvector is, as we know, equivalent to the matrix $P$ having rank at most two.
If we set $\boldsymbol{v}=\boldsymbol{x}\times\boldsymbol{y}$ (which is exactly what your algorithm is doing) then there are to possibilities:

$\boldsymbol{x}$ and $\boldsymbol{y}$ are linearly independent. Then $\boldsymbol{v}$ is orthogonal to both, $\boldsymbol{x}$ and $\boldsymbol{y}$. Since $P$ has rank at most two this means that $\boldsymbol{z}$ must be a linear combination of $\boldsymbol{x}$ and $\boldsymbol{y}$. Then $\boldsymbol{v}$ is orthogonal to all three vectors and therefore an eigenvector. $\quad\Box$

$\boldsymbol{x}$ and $\boldsymbol{y}$ are not linearly independent.
Then $\boldsymbol{v}=\boldsymbol{0}$ which is not an eigenvector that we are seeking.

We see that this algorithm does not always produce eigenvectors. The most simple case where it doesn't is $M=\operatorname{diag}(\lambda,\lambda,\lambda)$ in which case $P=0$ and $\boldsymbol{x}=\boldsymbol{y}=\boldsymbol{z}=\boldsymbol{0}\,.$
Q2. Q3. Don't think so. The algorithm relies heavily on the properties of the cross product in $\mathbb R^3$.
Q4. It should be obvious by now why we don't always use this method.
Comment: Thank you very much for your clear and detailed answer. It is now clear as water! One more thing would help: do you mean I got some bad luck when checking against higher dimensions in $R^{n \times n}$? Of course I understand that both diagonal and zero matrices require special handling case, but all other matrices were ok (upper/lower triangular and regular ones)..
Comment: In $\mathbb R^{n\times n}$ with $n\not=3$ there is no cross product $\boldsymbol{x}\times\boldsymbol{y}$ that generates a vector. If you have a specific higher dimensional example please post it. We can remove the python code to save some space.
Comment: I just edited the question to add an example of such $4 \ times 4$ matrice
Comment: How did you produce these $4\times 4$ results with a python code that was hardcoded to $3\times 3$ ?   In the meantime I picked up @HosamHajjir 's hint and looked at [Adjugate Matrix](https://en.wikipedia.org/wiki/Adjugate_matrix). The answer to Q3 could then be: It works when you know what determinants you should be calculating.
Comment: I made a generalization based on cofactor for $n \times n$ matrices. Great, so it answers my last question! Thank you very much to the two of you for taking time to answer this post
Comment: I think I concluded too quickly that the algorithm cannot be generalized to $n>3$. Hosam's hint is the way to go. Since you are well versed at programming leave that aside for now. Instead I recommend that you  work out the maths of, say, the $4\times 4$ case just as you described the $3\times 3$ case in the original post.


Finding the points common to a hyperbola and straight line

Question: I'm trying to find points common to hyperbola and straight line. One method is to directly substitute for variables and solve, however it may get tedious, so I'm using parametric form of hyperbola. I've worked my approach but something is wrong as I'm getting 2 possible answers.But in my answer key only one answer is mentioned. Here's my solution.
https://i.stack.imgur.com/WOxrV.jpg
I want to know why extra answer is generated. I'm a newbie to coordinate geometry and sorry, I don't know Latex (so i have to attach a picture)
Comment: Welcome to MSE. Please type your questions (using [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)) instead of posting links to pictures.
Comment: When you square an equation, you run the risk of introducing extraneous solutions.
Comment: See https://math.stackexchange.com/questions/757497/how-to-solve-4-sin-theta-3-cos-theta-5
Answer: You obtain $25+40\sin\phi+16\sin^2\phi=9\cos^2\phi$ from $5+4\sin\phi=3\cos\phi$. But $5+4\sin\phi=-3\cos\phi$ also implies $25+40\sin\phi+16\sin^2\phi=9\cos^2\phi$.
The extra answer is for $5+4\sin\phi=-3\cos\phi$.
Comment: Understood it ! Thanks....


How to change the key of an object to match the parameter passed into the function?

Question: When the following function runs the parameter 'state' will be an abbreviation for one of the US 50 states. I want the state key in the return block to not be read as 'state', but instead, one of the 50 us state variables passed into the function. What can I do?
  config = (state) => {
      return {
        state: {
          fill: 'gray'
        }
      }
    }

Answer: Use square parens to use the value of a variable as a key name:
config = (state) => {
  return {
    [state]: {
      fill: 'gray'
    }
  }
}

Comment: This answered my question, so thank you, but it did not solve the problem I'm having on my website.
Comment: @SalvatoreDePalma you should still accept an answer, though.   We can't answer a question about a problem that you never asked about.
Comment: @SalvatoreDePalma You should accept the answer if it solves the question you asked
Answer: config = state => ({
   [state]: {
      fill: 'gray',
   }
})

Javascript allows you to do this with dynamic key name.
How to be clean with ES6:
you can also omit the return keyword if you're not doing anything else in the function other than returning an object.
You can also omit the parens around the params if state is the only param you need.
This solution is as clean as it gets
Comment: some coders prefer to use the parens even for single parameter functions.
Comment: @Alnitak True, it's all preference


Grafana plugin node project won't sync with node_module in dev mode

Question: I'm having an issue trying to link a grafana plugin I'm working on.
This plugin use a node module that I'm also modifying (I have to modify both of them), but everytime I add the plugin to grafana I see the the node_module is not in sync and keeps loading the original version. The plugin change on the other hand are all being updated acordingly, but not the other modeule under node_module.
If someone have an idea I would really appreciate it, I have a feeling is simple. I just can't figure it out.
Thanks in advance,
Answer: The problem seems to be because I was running grafana in docker and linking my plugin to the grafana container with a volume, so the dependencies were never found and they were downloaded.
Installing grafana locally and adding the the other module via
npm install --save <my_dev_module> resolved it.


Trouble simplifying a tough equation

Question: I'm having trouble simplifying the following equation.  I've tried grouping terms in different ways, but it's not looking any more joyful.  Can someone please help with its resolution?  Hopefully by midnight??
$$
\omega - \ln Y=\ln\left(H p^2 a + \exp(ra)\right) - \ln N
$$
Comment: What do you want to do with the equation ?
Comment: OH. Now I see (after looking at the answers)!
Answer: $$
\omega - \ln Y=\ln\left(H p^2 a + \exp(ra)\right) - \ln N
$$
$$
\omega =\ln\left(H p^2 a + \exp(ra)\right)+ \ln Y - \ln N
$$
$$
\omega =\ln\left(H p^2 a + \exp(ra)\right)+ \ln (Y/N )
$$
$$
\omega =\ln\left({YH p^2 a + Y\exp(ra)\over N}\right)
$$
$$
\omega =\ln\left({Ha p^2Y + Ye^{ar})\over N}\right)
$$
$$e^{\omega}=\frac{Ha p^2Y + Ye^{ar}}{N}$$
$$0=Ha ppY-Ne^{\omega} + Ye^{ar}$$
Comment: Or just $HappY = Ne^{\omega} - Ye^{ar}$ :).
Comment: O.K. THats sounds better
Answer: Assuming everything there are numbers (or at least, everything commutes), may be you are wishing the community "$HappY Ne^\omega Ye^{ar}$".
Comment: $1=HappY(Ne^\omega)^{-1}Ye^{ar}$ to be more accurate.
Answer: Here, I solved for $a$ for you:
$$ a = \frac{N r e^\omega-H p^2 Y \cdot \mathrm{W}\left(\frac{e^{\frac{e^\omega N r}{H p^2 Y}} r}{H p^2}\right)}{H p^2 r Y} $$
Where $\mathrm{W}(x)$ is the Lambert-W function.
Comment: Technically correct.

Trouble simplifying a tough equation


Instalar o pacote six no projeto python3.7

Question: Estou tentando instalar esse projeto no meu computador, mas não estou conseguindo
Já instalei o python3.7 e  quando executo comando sudo python3.7 setup.py install, eu tenho no final o seguinte resultado
error: six 1.11.0 is installed but six~=1.12 is required by {'astroid'}
Já tentei usar isso
sudo python3 -m pip install six
e assim
pip install six
Ele diz que a versão que eu tenho instalada é a 1.15.0
Eu estava tentando esse tutorial aqui, mas não sai do primeiro vídeo
pip install six
Answer: Tente usar o
pip install six==1.12.0
pip install -r requirements.txt

se não funcionar(somente se não funcionar) tente isso
pip install -U six
pip install astroid

Comment: Mas ele nao vai direto pra versão python2.7?
Comment: tente mesmo assim
Comment: ai depois vc tenta instalar normalmente
Comment: Blz. Obrigado!!


groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method com.predic8.schema.Element#setType.?

Question: I need to parse the WSDL file dynamically.
My code are Here:
package com.wsdl.migration;
import com.predic8.schema.Schema;
import com.predic8.wsdl.Definitions;
import com.predic8.wsdl.Fault;
import com.predic8.wsdl.Message;
import com.predic8.wsdl.Operation;
import com.predic8.wsdl.Part;
import com.predic8.wsdl.PortType;
import com.predic8.wsdl.WSDLParser;

import groovy.lang.GrabResolver;
import groovy.lang.MetaMethod;
import javax.xml.namespace.*;

public class FullWSDLParser {

    public static void main(String[] args) {
        WSDLParser parser = new WSDLParser();

        //https://community.workday.com/custom/developer/API/Time_Tracking/v23.0/Time_Tracking.wsdl
       Definitions defs = parser.parse("http://www.thomas-bayer.com/axis2/services/BLZService?wsdl");

        out("-------------- WSDL Details --------------");
        System.err.println("TargenNamespace: \t ---- > " + defs.getTargetNamespace());
        if (defs.getDocumentation() != null) {
            out("Documentation: \t\t" + defs.getDocumentation());
        }
        out("\n");
        //defs.getQName().getQualifiedName()
        // For detailed schema information see the FullSchemaParser.java sample.
        out("Schemas: ");
        for (Schema schema : defs.getSchemas()) {
            out("  TargetNamespace: \t" + schema.getTargetNamespace());
        }
        out("\n");

        out("Messages: ");
        for (Message msg : defs.getMessages()) {
            System.out.println("  Message Name: " + msg.getName());
            System.out.println("  Message Parts: ");
            for (Part part : msg.getParts()) {
                out("    Part Name: " + part.getName());
                out("    Part Element: " + ((part.getElement() != null) ? part.getElement() : "not available!"));
                out("    Part Type: " + ((part.getType() != null) ? part.getType() : "not available!" ));
                out("");
            }
        }
        out("");

        out("PortTypes: ");
        for (PortType pt : defs.getPortTypes()) {
            System.err.println("  PortType Name: " + pt.getName());
            System.out.println("  PortType Operations: ");
            for (Operation op : pt.getOperations()) {
                System.err.println("    Operation Name: " + op.getName());
                System.out.println("------------QNAME - > "+op.getQName());
                System.err.println("    Operation Input Name: "
                    + ((op.getInput().getName() != null) ? op.getInput().getName() : "not available!"));
                System.out.println("    Operation Input Message: "
                    + op.getInput().getMessage().getQname());
                System.out.println("    Operation Output Name: "
                    + ((op.getOutput().getName() != null) ? op.getOutput().getName() : "not available!"));
                System.out.println("    Operation Output Message: "
                    + op.getOutput().getMessage().getQname());
                System.out.println("    Operation Faults: ");
                if (op.getFaults().size() > 0) {
                    for (Fault fault : op.getFaults()) {
                        System.out.println("      Fault Name: " + fault.getName());
                        System.out.println("      Fault Message: " + fault.getMessage().getQname());
                    }
                } else out("      There are no faults available!");

            }
            out("");
        }
        out("");

        out("Bindings: ");
        for (Binding bnd : defs.getBindings()) {
            out("  Binding Name: " + bnd.getName());
            out("  Binding Type: " + bnd.getPortType().getName());
            out("  Binding Protocol: " + bnd.getBinding().getProtocol());
            if(bnd.getBinding() instanceof AbstractSOAPBinding) out("  Style: " + (((AbstractSOAPBinding)bnd.getBinding()).getStyle()));
            out("  Binding Operations: ");
            for (BindingOperation bop : bnd.getOperations()) {
                out("    Operation Name: " + bop.getName());
                if(bnd.getBinding() instanceof AbstractSOAPBinding) {
                    out("    Operation SoapAction: " + bop.getOperation().getSoapAction());
                    out("    SOAP Body Use: " + bop.getInput().getBindingElements().get(0).getUse());
                }
            }
            out("");
        }
        out("");

        out("Services: ");
        for (Service service : defs.getServices()) {
            out("  Service Name: " + service.getName());
            out("  Service Potrs: ");
            for (Port port : service.getPorts()) {
                out("    Port Name: " + port.getName());
                out("    Port Binding: " + port.getBinding().getName());
                out("    Port Address Location: " + port.getAddress().getLocation()
                    + "\n");
            }
        }
        out("");
    }

    private static void out(String str) {
        System.out.println(str);
    }
}

And My Gradle file for Dependency is here :
buildscript {
    ext {
        springBootVersion = '1.5.2.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}
dependencies {
 compile 'org.springframework:spring-support:2.0.8'
  compile 'org.springframework:spring-aop:4.1.2.RELEASE'
  compile 'org.springframework:spring-beans:4.1.2.RELEASE'
  compile 'org.springframework:spring-context:4.1.2.RELEASE'
  compile 'org.springframework:spring-core:4.1.2.RELEASE'
  compile 'com.squareup.okio:okio:1.11.0'
  compile 'com.squareup.okhttp3:okhttp:3.6.0'
  compile 'org.json:json:20160810'
  compile 'mysql:mysql-connector-java:5.1.38'
  compile 'org.apache.commons:commons-dbcp2:2.0.1'
  compile group: 'org.hibernate.javax.persistence', name: 'hibernate-jpa-2.0-api', version: '1.0.1.Final'
  compile group: 'log4j', name: 'log4j', version: '1.2.17'
  compile('org.springframework.boot:spring-boot-starter-jdbc')
 // https://mvnrepository.com/artifact/com.predic8/soa-model-core
    compile group: 'com.predic8', name: 'soa-model-core', version: '1.5.4'
    // https://mvnrepository.com/artifact/org.reflections/reflections
compile group: 'org.reflections', name: 'reflections', version: '0.9.5-RC2'
}

My error Log  :
Exception in thread "main" groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method com.predic8.schema.Element#setType.
Cannot resolve which method to invoke for [null] due to overlapping prototypes between:
    [class javax.xml.namespace.QName]
    [class groovy.xml.QName]
    at groovy.lang.MetaClassImpl.chooseMostSpecificParams(MetaClassImpl.java:3268)
    at groovy.lang.MetaClassImpl.chooseMethodInternal(MetaClassImpl.java:3221)
    at groovy.lang.MetaClassImpl.chooseMethod(MetaClassImpl.java:3164)
    at groovy.lang.MetaClassImpl.getNormalMethodWithCaching(MetaClassImpl.java:1380)
    at groovy.lang.MetaClassImpl.getMethodWithCaching(MetaClassImpl.java:1295)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1065)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1027)
    at org.codehaus.groovy.runtime.metaclass.MultipleSetterProperty.setProperty(MultipleSetterProperty.java:54)
    at groovy.lang.MetaClassImpl.setProperty(MetaClassImpl.java:2694)
    at groovy.lang.MetaClassImpl.setProperty(MetaClassImpl.java:3775)
    at com.predic8.soamodel.XMLElement.setProperty(XMLElement.groovy)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.setGroovyObjectProperty(ScriptBytecodeAdapter.java:532)
    at com.predic8.schema.Element.parseAttributes(Element.groovy:50)
    at sun.reflect.GeneratedMethodAccessor16.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:64)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:174)
    at com.predic8.soamodel.XMLElement.parse(XMLElement.groovy:41)
    at com.predic8.soamodel.XMLElement$parse.call(Unknown Source)
    at com.predic8.schema.ModelGroup.parseChildren(ModelGroup.groovy:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:64)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:182)
    at com.predic8.soamodel.XMLElement.parse(XMLElement.groovy:46)
    at com.predic8.soamodel.XMLElement$parse.call(Unknown Source)
    at com.predic8.schema.ComplexType.parseChildren(ComplexType.groovy:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:64)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:182)
    at com.predic8.soamodel.XMLElement.parse(XMLElement.groovy:46)
    at com.predic8.soamodel.XMLElement$parse.call(Unknown Source)
    at com.predic8.schema.Schema.parseChildren(Schema.groovy:99)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:64)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:182)
    at com.predic8.soamodel.XMLElement.parse(XMLElement.groovy:46)
    at com.predic8.soamodel.XMLElement$parse.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
    at com.predic8.wsdl.Types.parseChildren(Types.groovy:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:64)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:182)
    at com.predic8.soamodel.XMLElement.parse(XMLElement.groovy:46)
    at com.predic8.soamodel.XMLElement$parse.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
    at com.predic8.wsdl.Definitions.parseChildren(Definitions.groovy:251)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:182)
    at com.predic8.soamodel.XMLElement.parse(XMLElement.groovy:46)
    at com.predic8.soamodel.XMLElement$parse.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
    at com.predic8.wsdl.WSDLParser.parseLocal(WSDLParser.groovy:44)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:174)
    at com.predic8.soamodel.AbstractParser.parse(AbstractParser.groovy:35)
    at com.predic8.wsdl.WSDLParser.super$2$parse(WSDLParser.groovy)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1218)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:132)
    at com.predic8.wsdl.WSDLParser.parse(WSDLParser.groovy:24)
    at com.wsdl.migration.FullWSDLParser.main(FullWSDLParser.java:39)

I get this code from net.But i can get the output only use thier WSDL url, when i chage with other wsdl file URL,i throws me error,says some thing related with QName.I am newbee for wsdl and xml also. i can not find the acctual problem .So please help me . Thanks in advance.
Comment: I too have faced this problem.. Dont know the solution, but the thing I suspect is,
The class QName is defined in two different jars.
1. class javax.xml.namespace.QName
2. class groovy.xml.QName
i.e., from xml library of java and groovy. Groovy during runtime finds both and thus the ambiguity.
Answer: I too faced this issue and the is problem with groovy version,
Please try to downgrade groovy version.


System.UnauthorizedAccessException: Access to the path C

Question: I am trying to build a automatic backup and restore system.
My logfile:
2012-08-02 22:34:06 - Init: Folder main created for server Teamdeathmatch
2012-08-02 22:34:06 - Backup: Couldn't copy files: System.UnauthorizedAccessException: Access to the path 'C:/temp/backups/Teamdeathmatch/server/main' is denied.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite)
   at System.IO.File.Copy(String sourceFileName, String destFileName, Boolean overwrite)
   at BackupRollback.Backup.getServerFiles() in C:\Users\jordi\Desktop\ConsoleApplication1 - kopie\Backup.cs:line 51

The target and the file exist.
I hope that anyone can help me. Also some feedback about my programming of c# since c-sharp is new for me.
Thank you
class Backup
{

    public static void getServerFiles()
    {

        Log.Info("Get servers");
        string[] fileEntries = Directory.GetDirectories("c:/Gameservers");

        Log.Info("Servers found: " + fileEntries.Count());

        string _directoryPath = @"C:\temp\backups";

        // check folder exists
        if (!Directory.Exists(_directoryPath))
        {
            Log.Data("Temp backup folder not found");
            Directory.CreateDirectory(_directoryPath);
            Log.Data("Temp backup folder created successfully");

        }
        else
        {
            Log.Data("Temp backup folder found");
        }

        // move files to directory
        foreach (string fileName in fileEntries)
        {
            try
            {
                string servername = Path.GetFileNameWithoutExtension(fileName);

                Directory.CreateDirectory("C:/temp/backups/" + servername + "/server");
                Log.Data("Folder server created for server " + servername);

                Directory.CreateDirectory("C:/temp/backups/" + servername + "/server/main");
                Log.Data("Folder main created for server " + servername);

                File.Copy("C:/temp/backups/" + servername + "/server/main", "C:/Gameservers/" + servername + "/server/main/server.cfg");
                Log.Data("File server.cfg copied for server " + servername);

                Directory.CreateDirectory("C:/temp/backups/" + servername + "/b3 server/conf");
                Log.Data("Folder conf [b3] created for server " + servername);

                File.Copy("C:/temp/backups/" + servername + "/server/main", "C:/Gameservers/" + servername + "/b3 server/conf/b3.xml");
                Log.Data("File b3.xml copied for server " + servername);

                Directory.CreateDirectory("C:/temp/backups/" + servername + "/server/mods");
                Log.Data("Folder mods created for server " + servername);

                DirectoryCopy("C:/temp/backups/" + servername + "/server/", "C:/Gameservers/mods/" + servername + "/server/mods/");
                Log.Data("Folder mods copied for server " + servername);
            }

            catch (Exception ex)
            {
                Log.Data("Couldn't copy files: " + ex.ToString());
            }
        }

    }

    private static void DirectoryCopy(string sourceDirName, string destDirName)
     {
      DirectoryInfo dir = new DirectoryInfo(sourceDirName);
      DirectoryInfo[] dirs = dir.GetDirectories();

        FileInfo[] files = dir.GetFiles();

           foreach (FileInfo file in files)
          {
             string temppath = Path.Combine(destDirName, file.Name);

             file.CopyTo(temppath, false);
         }

         foreach (DirectoryInfo subdir in dirs)
        {
            string temppath = Path.Combine(destDirName, subdir.Name);

            DirectoryCopy(subdir.FullName, temppath);
        }
    }

}
Comment: are you running this line of code
string[] fileEntries = Directory.GetDirectories("c:/Gameservers");
on your local machine or the remoter server machine..??
Comment: For the sake of getting the obvious out of the way, do you have proper rights to write to that directory? Try rather than writing to C:\temp\backups writing to somewhere else, like My Documents. Does that work?
Comment: the c:/Gameservers is on my remote machine.
Answer: File.Copy(source, destination)
You have your parameters reversed.  Try this instead.
File.Copy"C:/Gameservers/" + servername + "/server/main/server.cfg",
         "C:/temp/backups/" + servername + "/server/main");
Log.Data("File server.cfg copied for server " + servername);


Prove that $\sin A - \sin B + \sin C = 4\sin A/2 \cos B/2 \sin C/2$

Question: Prove that $\sin A - \sin B + \sin C = 4\sin A/2 \cos B/2 \sin C/2$ occurs in an $ABC$ triangle.
I don't know how to solve the RHS... Can anyone help me please?
Answer: Hint: Use the Half Angle identities to simplify the right side into terms of A, B, and C. After that, it should be much easier.
Comment: Did trying this help at all? Or do you still need more of a hint? Where did you get stuck if it didn't help?


Subquery do SQL Server está sempre retornando nulo. Como consertar.

Question: Eu tenho uma procedure e uma COMMON TABLE EXPRESSION(subquery).
Essa minha CTE faz uma busca e oferece para a minha query o resultado, a minha query então utiliza os resultados da mesma.
Na minha tabela Endereço eu possuo um campo "Complemento" que permite valores nulos.
No entanto quando a minha CTE faz a consulta e compara com o @complemento se o complemento tiver vazio, o resultado da CTE não retorna nada, mesmo o valor NULL existindo na tabela_endereco, já o contrário, se for procurar um registro cujo complemento está preenchido a pesquisa encontra.
Vou mostrar para vocês o código e o erro.

Observação 1: O erro acontece pois a FK não aceita valores nulos e como a subquery retorna valor nulo, esse erro acontece.
Observação 2: A outra procedure após o EXEC faz apenas cadastro de endereços.
Answer: Quando a coluna complemento da tabela, tem o valor NULL numa linha, para que esta seja devolvida pela query não basta fazer:
[...] where complemento = @complemento [...]

Os valores NULL não podem ser comparados com o operador =.
Para que as linhas a NULL sejam devolvidas,  pode ser feito assim:
[...] where complemento = @complemento or (complemento is null and @complemento is null) [...]

Ou então assim:
[...] where isnull(complemento,'') = isnull(@complemento,'') [...]

Answer: Use IDENTITY_SCOPE pra pegar a chave primária do último registro inserido e adicionar na outra tabela. Dependendo de como suas tabelas foram criadas, se você colocou restrição de chave estrangeira, use cascateamneto para fazer o CRUD completo.
Answer: O erro apresentado no print, é porque a consulta "(SELECT ID_Endereco FROM CTE_ENDERECO)" não trouxe nenhum resultado ou seja NULL e você tentou atribuir este resultado ao campo "FK_Endereco" da tabela "Tabela_Representante" (que não permite nulo).
O erro do print poderia ser resolvido da seguinte maneira:
DECLARE @FK_Endereco AS VARCHAR(10)
SET @FK_Endereco = (SELECT ID_Endereco FROM CTE_ENDERECO);

Troque na sua consulta, na linha do insert:
O valor:
(SELECT ID_Endereco FROM CTE_ENDERECO)

Pelo valor:
(CASE WHEN @FK_Endereco IS NULL OR @FK_Endereco = '' THEN 'Sem Endereço' ELSE @FK_Endereco END)

Não entendi a relação do erro citado com a comparação do valor da coluna "complemento" com a variável "@complemento". Esta comparação que você disse não aparece nos prints de tela.
Se o problema for ao dar o select no campo "complemento" da tabela "CTE_ENDERECO" basta usar:
SELECT (CASE WHEN complemento IS NULL THEN '' ELSE complemento END) AS complemtento FROM CTE_ENDERECO

Ao invés de dar um simples SELECT no campo que pode ser nulo (como você deve estar fazendo):
SELECT complemento FROM CTE_ENDERECO


Multi-variable calculus involving $\ln$

Question: I am having difficulty with differentiating this equation with respect to $y$:
$$
W= x^{y \ln(z)}.
$$
Differentiating calculators are giving me the answer
$$\ln(x) \ln(z).x^{y \ln(z)}$$
But I can't understand why the $\ln(x)$ appears in the answer
Any help would be greatly appreciated.
Answer: Start by taking the natural logarithm to both sides
$$ \ln W(x,y,z) = y\ln(z)\ln(x), $$
then differentiate w.r.t. $y$
$$ \frac{W_y}{W} = \ln(z)\ln(x) $$
which gives
$$ W_y = W \ln(z)\ln(x) \longrightarrow (1)$$
Now substitute $W = x^{y\ln(z)}$ in $(1)$ yields the desired result
$$ W_y = x^{y\ln(z)} \ln(z)\ln(x)  $$

Multi-variable calculus involving $\ln$


$X$, $Y$, and $Z$ are continuous IID, $\text{P}(X<Y<Z)$?

Question: So we have 3 continuous IID random variables $X$, $Y$ and $Z$. I want to find $p = \text{P}(X<Y<Z)$.
The easy way to do it is to use symmetry and thus we have $3!$ equally likely orderings and thus $p = 1/3!$
I was thinking about doing it the hard way and go for the integral of the joint pdf over a specific region. This is where I'm stuck. I'm not sure about the limits of the integral for each one. Any help or guidance is appreciated.
Comment: $$p=\int_{-\infty}^{+\infty}\int_{-\infty}^z\int_{-\infty}^yf(x)f(y)f(z)dxdydz$$
Answer: Let $F$ be the common distribution function. Then
\begin{align*}
P(X < Y < Z) &= E\big( E\left(\mathbb{I}_{X < Y} \mathbb{I}_{Y < Z}\mid Y, Z\right)\big)\\
&= E\big(F(Y)\mathbb{I}_{Y < Z} \big)\\
&=E\Big(E\big(F(Y) \mathbb{I}_{Y < Z} \big) \mid Y\Big)\\
&=E\left(F(Y)-F(Y)^2\right)\\
&=\int_{-\infty}^{\infty}F(y)dF(y) - \int_{-\infty}^{\infty}F(y)^2dF(y)\\
&=\frac{1}{6}.
\end{align*}
Answer: Here is a brutal way. Let $F$ be the CDF of the common distribution of $X$, $Y$ and $Z$. Then starting @Did's expression for $p$ and using the relation $F' = f$ triple times,
\begin{align*}
p
&=\int_{-\infty}^{\infty} f(z) \bigg( \int_{-\infty}^z f(y) \bigg( \int_{-\infty}^y f(x) \, \mathrm{d}x \bigg) \mathrm{d}y \bigg) \mathrm{d}z \\
&=\int_{-\infty}^{\infty} f(z) \bigg( \int_{-\infty}^z f(y)F(y) \, \mathrm{d}y \bigg) \mathrm{d}z \\
&=\int_{-\infty}^{\infty} f(z) \left[ \frac{1}{2}F(y)^2 \right]_{y=-\infty}^{y=z} \, \mathrm{d}z \\
&=\int_{-\infty}^{\infty} \frac{1}{2} f(z) F(z)^2 \, \mathrm{d}z \\
&=\left[ \frac{1}{6}F(z)^3 \right]_{z=-\infty}^{z=\infty} \\
&=\frac{1}{6}.
\end{align*}
Answer: If you want to consider the joint integral, maybe you could start out by reducing the problem a little. Due to continuity with $F$ denoting the distribution function,
$P(X<Y<Z)=P(F(X) < F(Y) < F(Z))=P(U_1<U_2<U_3)$,
where the $U_i$ are iid $\text{Unif}(0,1)$-distributed, $i=1,2,3$.
Then (just calculate):
$P(U_1<U_2<U_3)
=
\int_{u_1<u_2<u_3} 1_{(0,1)^3}(u_1,u_2,u_3) \, \mathrm{d}(u_1,u_2,u_3)
=
\int_0^1 \int_0^{u_3} \int_0^{u_2} \mathrm{d}u_1 \mathrm{d}u_2 \mathrm{d}u_3
=
\int_0^1 \int_0^{u_3} u_2 \, \mathrm{d}u_2 \mathrm{d}u_3
=
\int_0^1 \frac{u_3^2}{2} \, \mathrm{d}u_3
=
\frac{1}{6}.
$
The idea to transform such problems into the uniform case is very typical.
Answer: Comment. Your intuitive method seems sound.
Here are simulations with standard uniform (on $(0,1)$),
standard normal (on the real line), and standard
exponential (on the positive half line). With a million
simulated realizations of each random variable, you
should expect about two-place accuracy.
<code># std unif
m = 10^6; x = runif(m); y = runif(m);  z = runif(m)
cond = (x < y) & (y < z)
mean(cond)
## 0.166949

# std norm
m = 10^6; x = rnorm(m); y = rnorm(m);  z = rnorm(m)
cond = (x < y) & (y < z)
mean(cond)
## 0.167202

# std exponential
m = 10^6; x = rexp(m); y = rexp(m);  z = rexp(m)
cond = (x < y) & (y < z)
mean(cond)
## 0.166133
</code>
As a start towards a demonstration using integrals, I suggest you
do it first in 2-D with just random variables $X$ and $Y$. Make sure the density function
is defined using an indicator function to restrict it to the support
of its distribution. Then use symmetry.
In the plot below (for standard uniform random variables and 100,000 iterations),
49,988 points with $X < Y$ are plotted. And 16,833 of the points with $X < Y < Z$ are
plotted in red. Maybe the figure will help you set limits for the
appropriate region in 2-D space (subsequently in 3-D).

<code>m = 10^5; x = runif(m); y = runif(m);  z = runif(m)
cond = (x < y) & (y < z)
plot(x[x < y], y[x < y], pch=".", col="blue")
points(x[cond], y[cond], pch=".", col="red")
</code>
Comment: Sorry but this seems offtopic for the question as it is phrased.
Answer: Assuming they have pdfs,
$$\int_{-\infty}^{\infty}\int_{-\infty}^{z}\int_{-\infty}^{y} f_{X,Y,Z}(x,t_y,t_z)dxdt_ydt_z$$
$$ = \int_{-\infty}^{\infty}\int_{-\infty}^{z}\int_{-\infty}^{y} f_X(x)f_Y(t_y)f_Z(t_z)dxdt_ydt_z$$
$$ = \int_{-\infty}^{\infty}f_Z(t_z)\int_{-\infty}^{z}f_Y(t_y)\int_{-\infty}^{y} f_X(x)dxdt_ydt_z$$
To begin let
$$u=\int_{-\infty}^{z}f_Y(t_y)\int_{-\infty}^{y} f_X(x)dxdt_y$$
$$dv = f_Z(t_z)dt_z$$
Can you take it from here?
Otherwise, what you said.
Comment: "Can you take it from here?" Can you take it from here yourself?
Comment: Apparently not. Then what should we think of the act of posting such a misleading "answer"?


Views 3 List Style CSS

Question: Usually, when I make a views block list, and I want it horizontal, I would just add CSS styles to the block itself.
#block-views-something li
{
  display: inline;
  list-style-type: none;
  padding-right: 20px;
}

Having to do this for each block is a pain. I know Views 3 lets me add a class to the view to style the list, but I have never been able to do it. I have tried HTML List, and adding classes to Page: Style options Row class, and Wrapper class or even List class. I have tried it with a dot like .mystyle and without the dot 'mystyle'.
In fact, I just get myself into a right old mess. Could anyone advise me the simplest route to take to add the class to whatever box I should add it to?
Answer: The only good way is to use the 'add a class'-option in views. That allows for maximum flexibility and should not break if something in the view changes. (block-view-id-something can break when numbers or names change).
One you have added a css class to the field, something like horizontal. Then you can define it in your theme file css with .horizontal {...}.
But since themes can update their css, overwriting your changes, you are even better off using an extra stylesheet in your themes folder. Give it any name you want, add the .horizontal {...} lines. Then open the *.info file in your theme and add stylesheets[all][] =

Views 3 List Style CSS


How to add html tag in a form element?

Question: How to add html tag in a form element drupal 8?
$form['buttons']['submit'] = [
  '#type' => 'submit',
  '#value' => T('Send'),
  '#prefix' => '
',
  '#suffix' => '<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">' . $this->t('Close') . '</button>
',
  '#attributes' => [
    'class' => ['btn-success'],
  ]
];

I try to add allowed_tags:
$form['buttons']['submit'] = [
  '#type' => 'submit',
  '#value' => T('Send'),
  '#prefix' => '
',
  '#suffix' => '<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">' . $this->t('Close') . '</button>
',
  '#allowed_tags' => ['button'],
  '#attributes' => [
    'class' => ['btn-success'],
  ]
];

OR
$form['buttons']['#allowed_tags'] = ['button'];
$form['#allowed_tags'] = ['button'];

Not working...
Help me please!
Answer: I can't tell which element is giving you trouble.
For the div, instead of prefix/suffix you can create a container element:
$form['submit_container'] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => ['modal-footer'],
  )
);

And then you can put a submit input inside of that:
$form['submit_container']['submit'] = array(
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#attributes' => array(
    'class' => ['btn', 'btn-sm', 'btn-default'],
    'data-dismiss' => 'modal',
  )
);

If you need a button type='button' just to fire Javascript and not submit the form, that is somewhat problematic, it seems. One method is to override the button template.
Type inline_template may be the best bet:
$form['submit_container']['button'] = array(
  '#type' => 'inline_template',
  '#template' => '<button type="button" class="btn btn-sm btn-default" data-dismiss="modal" onclick="closeButton()">Close</button>',
);

Change a normal submit 'input' type to 'button' type with button tag
Answer: If you are looking to add a custom HTML tag use the new type in the form api html_tag, here's an example from the form API documentation :
$build['hello'] = [
  '#type' => 'html_tag',
  '#tag' => 'p',
  '#value' => $this->t('Hello World'),
];

How to add html tag in a form element?


Como não sobrepor rotulos(annotations) no google charts?

Question: Estou desenvolvendo um gráfico de linhas, onde os rótulos(annotations) são fixos, porem alguns pontos ficam muito perto uns dos outros, assim sobrepondo um rótulo no outro.
Gostaria de saber se tem alguma forma de mudar a posição dos rótulos de maneira dinâmica ou estática(posicionando em locais diferentes)?
Lembrando que gostaria de deixá-los sempre fixos, ou seja, sempre aparecendo, sem a necessidade de colocar o mouse em cima dos pontos para que apareça as informações.
Segue um exemplo de como está:
Answer: Nas options, dentro de annotations, do seu gráfico acrescente alwaysOutside: true. Deixará as anotações do lado de fora.
annotations: {
     textStyle: {
         color: 'black',
         fontSize: 11,
     },
     alwaysOutside: true
}

Nessa parte da Documentação, fala sobre annotations.
Comment: Obrigado pela resposta, porém não é isso que eu quero. Posso ter me expressado mal. Quero que uma annotation não sobreponha a outra. Isso que você indicou é para q a annotation fique fora das colunas. Olhe o que a documentação fala: annotations.alwaysOutside

In Bar and Column charts, if set to true, draws all annotations outside of the Bar/Column.

Type: boolean

Default: false
Comment: @AmarildoMartins, acho que não tem como resolver esse bug com as funções do google charts. Você vai ter que sobrescrever o SVG ou fazer com CSS.
Answer: usa o stem... eu estava com a mesma dificuldade... defina o item 1 positivo e o item 2 negativo, desta forma o annotation 1 ficará a cima do eixo, e o 2 abaixo...
series: {
              0: { annotations: { stem: { color: "transparent", length: 5}, alwaysOutside: true, textStyle: { color:'red',  bold: true, fontSize: 30 } } },
              1: { annotations: { stem: { color: "transparent", length: -40},  alwaysOutside: true, textStyle: { color:'yellow', bold: true, fontSize: 30 } } },
            }
        };


meta description quotes escape

Question: html code meta tag description,
it is generated dynamically and we have quotes in the description part and  search engines didn't read everything.
it shows until the quotes begins in the search results
how to deal with it ?
thanks
Answer: You need to escape the quotes using HTML character references:
<meta name="description" content=""quoted content"">

The description here is "quoted content".
Answer: In PHP use strip_tages + str_replace('"',"&quot") to archiv
<meta name="description" content=""quoted content"">

meta description quotes escape


Como não perder o "this" do objeto atual

Question: Eu já havia feito uma pergunta parecida, contudo desta vez estou com um problema um pouco mais complexo :

ObjectTest1 = (function(){

  var init = function(){
      this.callback = null;
  }

  init.prototype = {
    setCallback : function(callback){
      this.callback = callback; // O CALLBACK DEFINIDO AQUI É init.prototype.methodTest2 PERTENCENTE AO ObjectTest2
    },
    applyCallback : function(){
      if(typeof this.callback == 'function'){
        this.callback();  // CHAMADA NORMAL DE init.prototype.methodTest2 DO OBJETO ObjectTest2
      }
    }
  }

  return init;
}());

ObjectTest2 = (function(){

  var init = function(){}

  init.prototype = {
    methodTest1 : function(){
      console.log('methodTest1');
    },
    methodTest2 : function(){
      console.log('methodTest2');
      var self = this; // AQUI this PASSA A SER ObjectTest1 MESMO EU NÃO TENDO USADO .call OU .apply
      if(typeof self.methodTest1 != 'undefined'){ // ESTE METODO NÃO EXISTE NO ObjectTest1 POIS ELE É DO ObjectTest2
        self.methodTest1();
      }else{
        console.log('ERROR');
      }
    }
  }
  var newInit = new init;
  return newInit;
}());

var o = new ObjectTest1();
o.setCallback(ObjectTest2.methodTest2);
o.applyCallback();

Duvida

Porque o this foi alterado se eu fiz uma chamada normal do método?
Como eu posso fazer para não perder a referencia this do objeto que estou atualmente?

Resumo
Eu instancie o ObjectTest1 e setei como callback um método do ObjectTest2 que por sua vez ao ser executado deveria chamar um outro método de si próprio.
Answer: Não há nada de inesperado no seu código. this está apontando, corretamente, para o contexto do objeto que invocou o método onde this foi utilizado.
O seu stack é o seguinte:
new ObjectTest1()         <- contexto
.applyCallback()          <- função
[ObjectTest2.methodTest2] <- função
var self = this;          <- this: referência do contexto ObjectTest1()

ECMAScript 5 introduziu a palavra-chave bind(), que você pode utilizar quando chamando uma função para que escopo e corpo sejam preservados.
No seu caso, para preservar o contexto, preserve-o com uma referência (o motivo de várias implementações JS possuírem uma linha var self = this;.)
Fontes e mais informações:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
Answer: Regra: uma função corre no mesmo contexto de quem a chamou.
Há ferramentas para modificar isso. O new, como tu usaste, mas também .call(contexto), .bind(contexto) e .apply(contexto).
Contudo neste caso o que falha é que tens var self = this; dentro da função. É tarde demais, pois aí o contexto já é defenido por quem chamou, ou seja o Objeto1.
Neste caso parece-me que a solução mais simples é passar o self = this para dentro do init, forçando assim o contexto desejado no momento em que crias uma nova instância:
ObjectTest2 = (function() {
    var self;
    var init = function() {
        self = this;
    }

jsFiddle: https://jsfiddle.net/0o5wqgpz/
Comment: Realmente é um resposta valida e revolve meu problema perfeitamente, contudo creio ser mais aplicável a resposta do @wallace, pois caso eu queira alterar para `return init;` cada instancia teria que ter seu próprio escopo de `self`.
Answer: Pode não ser muito prático, mas o this está sempre associado a uma chamada, não a uma declaração de função (tentaram melhorar um pouco isso com as funções com flecha =>, que seguem outras regras)
No seu código
var o = new ObjectTest1();
o.setCallback(ObjectTest2.methodTest2); // Aqui você perdeu o this
o.applyCallback(); // Aqui você chamou (indiretamente) usando "o" como this

Na segunda linha você jogou fora o this, já que a função não conhece o seu this, ele é setado apenas na chamada.
Na terceira linha você usou o objeto "o" como this, ainda que indiretamente.
As possibilidades para o this são:

method() → não tem this (estou simplificando...)
obj.method() → this é obj
new Method() → cria um novo this.
.call() e .apply() → permitem escolher o this dinamicamente
.bind() → permite fixar um this a uma função para que ela não "esqueça" a quem pertence.

Então, qual é a solução? O jeito mais simples na minha opinião é criar uma nova função que não precise de this:
o.setCallback(function () {
    return ObjectTest2.methodTest2();
});

Mas usar o bind (ver as outras respostas, o uso deve ser algo como: ObjectTest2.methodTest2.bind(ObjectTest2)) tem o mesmo efeito. Eu me acostumei a fazer sem bind porque há um tempo atrás nem todos os navegadores suportavam.
Comment: interessante ver que nesse escopo também funcione. +1.
Answer: Bem, eu não sei ainda o porquê de no Javascript funcionar assim, mas eu já tive muitos problemas com isso, quando tento, por exemplo, simplesmente passar a referência da função como callback.
Vou mostrar abaixo um dos casos onde tive esse problema.
Veja:

var els = ['#id', '#id2'].map(document.querySelector);

O erro retornado é:

Uncaught TypeError: Illegal invocation(…)

Parece ser um erro relacionado ao contexto em que o querySelector foi aplicado. Ou seja, não foi invocado com o contexto de document, e sim de Array.
Uso do Bind
A solução foi usar o método bind, que definirá um escopo para o callback passado. Mesmo que esse callback entre em outro escopo, ele será executado no contexto em que foi passado em bind.
No caso do exemplo, o problema aciam foi resolvido assim:

 var els = ['#id', '#id2'].map(document.querySelector.bind(document))

O seu caso
No seu caso, eu utilizei o bind quando passo o callback para a função ObjectTest1.setCallback.
Veja:

ObjectTest1 = (function(){

  var init = function(){
      this.callback = null;
  }

  init.prototype = {
    setCallback : function(callback){
      this.callback = callback; // O CALLBACK DEFINIDO AQUI É init.prototype.methodTest2 PERTENCENTE AO ObjectTest2
    },
    applyCallback : function(){
      if(typeof this.callback == 'function'){
        this.callback();  // CHAMADA NORMAL DE init.prototype.methodTest2 DO OBJETO ObjectTest2
      }
    }
  }

  return init;
}());

ObjectTest2 = (function(){

  var init = function(){}

  init.prototype = {
    methodTest1 : function(){
      console.log('methodTest1');
    },
    methodTest2 : function(){
      console.log('methodTest2');
      var self = this; // AQUI this PASSA A SER ObjectTest1 MESMO EU NÃO TENDO USADO .call OU .apply
      if(typeof self.methodTest1 != 'undefined'){ // ESTE METODO NÃO EXISTE NO ObjectTest1 POIS ELE É DO ObjectTest2
        self.methodTest1();
      }else{
        console.log('ERROR');
      }
    }
  }
  var newInit = new init;
  return newInit;
}());

var o = new ObjectTest1();
o.setCallback(ObjectTest2.methodTest2.bind(ObjectTest2));
o.applyCallback();

Solução em jQuery
Apenas a nível de informação adicional, no jQuery é possível resolver esse problema usando $.proxy.
Leitura recomendada:

Why are certain function calls termed "illegal invocations" in JavaScript?