Is there a functor $F$ preserving finite direct sums but not split exact sequences, for which $F\mathbb{Z}$ is free and finitely generated?

Question: Is there a functor $F$ from the category of abelian groups to itself, such that

$F$ preserves finite direct sums (as well as the empty direct sum) up to (arbitrary) isomorphism
$F$ doesn't in general preserve split exact sequences
$F\mathbb{Z}$ is free and finitely generated.

By 2., I mean that there should exist abelian groups $A$ and $B$ such that the sequence
$$
0\to FA\overset{Fi}{\to}F(A\oplus B)\overset{Fp}{\to}FB\to 0
$$
isn't exact, where $i:A\to A\oplus B$ is the canonical injection and $p:A\oplus B\to B$ is the canonical surjection.
In this question, I asked whether there is a functor $F$ from the category of abelian groups to itself satisfying 1. and 2., and after some time I found such a functor, the construction of which I posted also in the original question. The basic idea is to first quotient out the torsion, i.e. sending $A$ to $GA:=A/\operatorname{Tor}(A)$, and then sending $GA$ to the free abelian group $FA:=\mathbb{Z}^{\oplus GA}/\mathbb{Z}\cdot\delta_0$, where $\delta_0$ is the element in $\mathbb{Z}^{\oplus GA}$ which has a coefficient of $1$ at $0=0_A$, but is $0$ everywhere else. One can check that then $F(A\oplus B)$ and $F(A)\oplus F(B)$ are free abelian of equal rank, for all $A,B$.
However, in this construction $F(\mathbb{Z})$ is infinitely generated, and furthermore the construction heavily relies on sending abelian groups to infinitely generated ones, in order to exploit that on infinite cardinals, multiplication and addition are equal. In the context where this question came up, it would be interesting to know whether there is such a functor, but I think it is also interesting of itself.
Answer: Fix an uncountable set $X$.  For any set $S$, let $G(S)$ denote the set of injective functions $X\to S$.  Define $F(A)$ to be the free abelian group on $G(A)$.  We can make this $F$ into a functor: a homomorphism $f:A\to B$ induces a partial function $G(A)\to G(B)$ by composition (partial because some injections $X\to A$ may no longer be injective after composition with $f$), and then we can get a homomorphism $F(f):F(A)\to F(B)$ by mapping the generators on which $G(A)\to G(B)$ is undefined to $0$.
This functor has $F(\mathbb{Z})=0$ which is free and finitely generated.  The fact that $F$ preserves finite direct sums up to isomorphism follows easily from the fact that $F(A)$ is trivial unless $|A|\geq |X|$, in which case $F(A)$ is free of rank $|A|^{|X|}$ (and these cardinals are infinite).  Finally, $F$ does not preserve split exact sequences since you can have in injection $X\to A\oplus B$ which is not injective when projected to $B$ but does not have its image contained in $A$, and this will give an element of the kernel of $F(A\oplus B)\to F(B)$ which is not in the image of $F(A)\to F(A\oplus B)$.
Comment: Ingenious! How did you come up with that, if not just by a spontaneous idea? :)
Comment: Well, the idea was to look for some functor that does some horribly non-additive infinitary stuff on big abelian groups (with the infinitary nature making it still preserve direct sums up to isomorphism), but not on $\mathbb{Z}$.  So, I was looking for some operation that is nontrivial on uncountable groups but trivial on countable groups, and $G$ is a simple example of that.


Algebraic word problem

Question: A woman walked five hours (total), first along a level road, then up a
hill, then she turned around and walked back to her starting point along
the same route. She walks 4 miles per hour on the level, 3 uphill, and 6
downhill. (i) Find the total distance she walked. (ii) Can this problem
always be solved regardless of the speeds she walks, or were the numbers
4, 3, 6 a "lucky choice"?
Im m not sure how to go about starting this problem. Can anyone help me start it and explain the reasoning behind it? Any help would be appreciated! Thank you!
Comment: Level distance plus non-level distance equals 10 miles so, since she walked the two legs one direction and then back the opposite direction, she walked 20 miles.
Comment: (i) Level distance plus non-level distance equals 10 miles so, since she walked the two legs one direction and then back the opposite direction, she walked 20 miles. On the level ground she takes x/4 hours twice and on the non-level ground, she takes y/3 hours up and y/6 hours down. Add those four and they equal 5 hours. The resulting equation is x + y = 10 miles. 10 miles one way and 10 miles back equals 20 miles. (ii) Given values are immaterial. For speeds a, b, c, one gets 2bcx + aby + acy = 5abc. After substituting whatever speeds one wants one has mx + ny = 5k, equivalent to the above.
Answer: This one is interesting. We have four speeds to worry about.
First level: 4 mph
Uphill: 3 mph
Downhill: 6 mph
Second level: 4 mph.
The average speed on the levels is 4mph. If you don't believe this, you can use the table method below with both levels. To find the average speed on the hills, let's make a table.

Notice that the uphill and downhill distances are the same, so we can set $3t_1 = 6t_2$. Solving for $t_1$ gives us $t_1 = 2t_2$.
Now, the average rate of the uphill and downhill speeds will be:
\begin{align}
r & = \frac{d}{t} \\
 & = \frac{\mbox{sum of hill distances}}{\mbox{sum of hill times}} \\
 & = \frac{3t_1 + 6t_2}{t_1 + t_2} \\
 & = \frac{3(2t_2) + 6t_2}{2t_2 + t_2} \\
 & = \frac{12t^2}{3t^2} \\
 & = 4
\end{align}
It turns out the the total average hill speed will be 4 mph. This means the average speed of the entire trip will be 4 mph. So... if this woman walks for 5 hours, how many miles will she travel?
For the second part, notice that it was pretty nice to end up with an average hill rate that was the same as the level rate. This allowed us to find an average rate for the entire trip and calculate the distance. What would happen if the average hill rate gave us something other than 4 mph? Try picking another pair of rates for uphill and downhill, say 2 uphill and 7 downhill. Find the average hill rate using the table method we did above. Would you be able to calculate the total distance?
Comment: Hi @Alti. If you found this answer useful, I would really appreciate a "check" next to it. If not, is there more explanation or information you need? Thanks!

Algebraic word problem


How to set content type to html on Google Calendar api?

Question: So reading the google calendar api (php) documentation it states:
"...content, set using setContent, provides additional information about the event which appears when the event details are requested from within Google Calendar. Optionally,   the description's mime-type is set using  setType to specify HTML instead of plain text. "
I've been trying to figure this out for a really long time but i have no idea how to go about setting the content to html instead of plan text. I tried using the setType method, on Zend_Gdata_Calendar object, but it said the method doesn't exist. Any ideas?
Answer: In the API there is a section that talks about "Creating web content events."  That shows an example of setting the type, which is just a MIME type.  For HTML, you can set the type as "text/html" and then provide the link to the HTML.
Data API Developer's Guide: PHP
From reading it, I believe this will create an iFrame that shows your content.  I've been playing around with this a lot in .NET and it seems to work.  I hope this helps you.


What exactly is a "successor" in the Extended Gale-Shapley algorithm?

Question: Background
In the main Gale-Shapley algorithm, a Stable Matching (if one exists) within the conventional Stable Marriage Problem is achieved as follows:
INITIALIZE M to be an empty matching
WHILE (some man m is free)
    w <- first woman on m's list to whom m has not yet proposed
IF (w is unmatched)
    Add m-w to matching M
ELSE IF (w prefers m to current partner m')
    Replace m' - w with m - w in matching M
ELSE //w is already matched

In the Extended Gale-Shapley algorithm, a weakly stable matching  from the Stable Marriage Problem with Indifference is achieved as follows:
INITIALIZE M to be an empty matching
WHILE (some man m is free)
    w <- first woman on m's list
    Add m-w to matching M
    IF(some man m' is engaged to w)
        Remove m'- w from M
    FOR EACH successor m'' of m on w's list
        Remove m'' - w from M
end

The first difference I notice is that adding a pair to Matching M is automatic, and removal happens after that fact, rather then an active check to see if w is matched in the original algorithm.  However, I have trouble understanding what a "successor" is in this context.  What exactly is a successor in the case of ties, and how does the algorithm know how many w's or m's are part of a tie?  This confusion is what lead me to ask:
Question
What exactly is a "successor" in the context of the Extended Gale Shapley algorithm?
Answer: As we learn from reading the paper, Wikipedia doesn't really know what's going on here.
The actual way to find weakly stable matchings is this:

Break all ties arbitrarily.
Use the Gale-Shapley algorithm.

The result is a matching that's stable with respect to the tiebroken preferences; this means that it must be weakly stable even without the tiebreaks. (A counterexample to weak stability is a man $m$ and woman $w$ that strictly prefer each other to their partners, and this strict preference is unaffected by breaking ties.)

The extended Gale-Shapley algorithm in the Wikipedia article is quoted directly from Irving's paper. It is still meant for solving the stable matching problem in the case with no ties, so $m'$ is a successor of $m$ on $w$'s list if $w$ prefers $m$ to $m'$, with no discussion of what happens if preferences are tied.
In fact, in all cases, Gale-Shapley and extended Gale-Shapley output exactly the same result; extended Gale-Shapley just does different book-keeping to get there. It deletes edges where Gale-Shapley just keeps track of which women a man has already proposed to, but ordinary Gale-Shapley would never want to use those edges. This may save a few checks down the line, but both algorithms are $O(n^2)$ in any case, so it doesn't save too many.
The extended Gale-Shapley algorithm exists to simplify the exposition in Irving's paper. Irving's other algorithms (the ones quoted in the rest of the Wikipedia article) are refinements of it: they also proceed by deleting edges. Those algorithms are meant to deal with ties, and are careful to only talk about "strict successors". If there are in fact no ties, those algorithms will end up taking the same actions as extended Gale-Shapley (and deleting the same edges).


Comparing and eliminating elements of vectors in R

Question: Let's say I have two vectors
x <- c(1, 2, 3, NA, 5, 6, NA, NA, 10, 11, 12, NA, NA, 13)

y <- c(14, 15, 16, 17, 18 ,19, 20, 21, 22, 23, 24, 25, 26 ,27)

They have both length of 14. I want remove NAs from x and the value that corresponds to it in y. And obtain x and y as equal lengths.
for (i in 1:length(x)) {
 for (j in 1:length(y)) {
   if(is.na(x[, i]==y[, j))
   x <- x[-which(x %n% y)]
 }
}

But it doesn't give what I want. Can you please help me ?
Answer: I read the comments above, do you want to plot x and y without NAs?
If so,you can just plot it,R will not give any warnings or error indication.
x <- c(1, 2, 3, NA, 5, 6, NA, NA, 10, 11, 12, NA, NA, 13)
y <- c(14, 15, 16, 17, 18 ,19, 20, 21, 22, 23, 24, 25, 26 ,27)
plot(x,y)

If you need to remove NAs from x and remove the corresponding values in y,you can combine x and y into a data.frame,then use na.omit() to deal with the new dataframe,finally,you can plot it.Ths codes as followed:
df2 <- na.omit(data.frame(x,y))
plot(y~x,df2)

OR:you can use the index to sovle it.
is.na is a function help you detect which is NA.
Finding the NA position in vector x us is.na(),
then remove the corresponding values in y
last,change the value in x.The code as follows:
y <- y[!is.na(x)]
x <- x[!is.na(x)]

Notice:the order cannot be changed.
Comment: I'm not sure this is what the question is asking: this would replace the NA values in `x` with the corresponding values in `y`.
Comment: @MichaelVeale Yes,previously,I think Emily565 want to get this results.
Answer: x <- x[!is.na(x)]
y <- y[!is.na(x)]

Comment: selectInput("mat",  ....., choices = c( a, y, b), .. )   and ı have x as a vector.  when the user make choice let's say y, it should remove NA values from x and the value that corresponds to it in y. so the elements of both x and y are decreased from 79.   plot(input$y,  x,   .......)
Comment: in which variable is the value stored which the user has selected? (either a, y or b)
Comment: Thanks for your answer. I'm using R markdown and asked this question to plot my actual data but it gives error incorrect number of dimensions still. Am I doing anything else wrong?
Comment: That would be difficult to predict based on the given data. This would just remove `NA` values from `x` and corresponding values from `y`
Comment: In my actual data, x and y has length of 79. x is a vector with NAs and y is a matrix with 3 columns. I have a selectInput for the column choice.
Comment: so `y` is 79 X 3 matrix ? Can you share the actual `x` and `y` data ?
Comment: yes, I have a 79 X 3 matrix. According to the user's column choice( y ), it should plot x and y. x has length of 79 with NAs
Comment: `y <- mat$y[!is.na(x)]` is this what you want? where `mat` is your matrix.
Comment: If you're trying to remove rows that have NAs in (if you could also combine your data into a single matrix or data frame), are you aware of the `complete.cases` function?
Comment: a, y, b all have NA values in different rows. the one the user selects is the variable that will be eliminated and plotted with x
Comment: Try assigning this value to `y` `y <- input[!is.na(input[mat]), mat]` and then `plot(x, y)`
Comment: how can ı rewrite it with not specifying any column like y, like any of them could it be because it is an input from the user. shouldn't ı write it in a for loop ?
Comment: how do you come to know what the user has selected ? (a, b or y) There must be some variable where the value gets stored after the user selects his option. Which is that variable?
Comment: okey, thanks a lot


Finding a Smooth Function With Given Proprieties

Question: I need to find a function $f:\mathbb{R} \to \mathbb{R}$ such that
$\bullet$ $f$ is smooth ($C^\infty)$
$\bullet$ $|f'(x)| < 1$
$\bullet$ $f(x) \neq x \quad \forall x \in R$
What I've done so far:
I was able to find a function that seems to work (at least looking at the plot). I will show the function bellow:
$$f(x)=
\begin{cases}
e^\frac{-2}{x-2}  & \text{for $x>2$} \\
(x-2)e^{\frac{2}{x-2}} & \text{for $x<2$}\\
0 & \text{for $x=2$}
\end{cases}$$
Here is the Plot
But I have 2 problems:
1)I would like to know if there is a simpler function since I would prefer not to define things conditionally
2)I'm not sure I know how to show the function satisfies what I want in a rigorous way.
Comment: Is "$f(x) \neq x$" intended to mean "The function $x \mapsto f(x) - x$ has no zero in $\mathbb{R}$" or "there is an $x\in \mathbb{R}$ with $f(x) \neq x$"?
Comment: Anyway, write $f(x) = x + g(x)$. Then $g$ must be smooth, and $-2 < g'(x) < 0$ for all $x$. A fortiori $g$ is not identically $0$, so if $f(x) \neq x$ has the second interpretation that condition is always satisfied. For the first interpretation, you need $g$ to have no zeros at all. Such $g$ aren't too hard to find using well-known functions.
Comment: The function x↦f(x)−x has no zero in R
Comment: As expected. So you need a decreasing $g$ that doesn't ever decrease too fast and that is strictly positive or strictly negative. Have you any ideas for such $g$?
Comment: Maybe if $g(x)=-tg^{-1}(x) -2$?
Comment: Yes, that's one such function. More generally, $g(x) = c - \arctan x$ for $\lvert c\rvert \geqslant \frac{\pi}{2}$. Or $g(x) = c + \frac{1}{1 + e^x}$, $c\notin (-1,0)$.
Comment: Thank you very much :)
Answer: I'm not sure if it is possible, check https://en.wikipedia.org/wiki/Fixed_point_(mathematics)


R adds unexpected variable to interaction model

Question: Not sure if this is more of a programming question (in which case please move to stack overflow) or a statistical model question (in which case, please read on!)
I'm exploring a data set and doing cox proportional hazards regression.
One of my variables did not satisfy the proportional hazards assumption so I decided to stratify by that variable.
Stratifying by the variable will assume that the effect of all covariates is the same in each stratum but each stratum has different baseline hazards.
To check this I test for an interaction between the stratifying variable and each covariate.  When I run any model with interactions R does something that is unexpected to me:
Call:
coxph(formula = Surv(NRM_time, NRM_status) ~ strata(chemosens) +
    remission + chemosens * (high.LDH + working) + eversmoke +
    etoh.current + married - chemosens, data = data)

                        coef exp(coef) se(coef)      z       p
remission1           -0.6206     0.538    0.192 -3.225 1.3e-03
high.LDH1             0.8181     2.266    0.177  4.635 3.6e-06
working1             -0.4329     0.649    0.204 -2.121 3.4e-02
eversmoke1            0.1698     1.185    0.125  1.358 1.7e-01
etoh.current1        -0.1633     0.849    0.124 -1.322 1.9e-01
married1             -0.0607     0.941    0.133 -0.455 6.5e-01
high.LDH0:chemosens1  0.8353     2.305    0.255  3.270 1.1e-03
high.LDH1:chemosens1      NA        NA    0.000     NA      NA
working1:chemosens1   0.7644     2.148    0.299  2.553 1.1e-02

Likelihood ratio test=40  on 8 df, p=3.19e-06  n= 738, number of events= 267
   (38 observations deleted due to missingness)

As you can see, all my covariates are dichotomous. When I fit the model with interaction between chemosens and both high.LDH and working why does R have an interaction term for chemosens with high.LDH0 AND high.LDH1 (as opposed to just high.LDH1 like it did for working).
Comment: Yes, it seems to be because I take out the main effect of `chemosens` (since the data is stratified by `chemosens`).
Comment: Than you have your answer.
Comment: Indeed, that wasn't too complicated. You can write a quick blurb as an answer and I can select it if you want.
Answer: My guess is that the chemosens * (high.LDH + working) part of the formula got translated into: working1:chemosens1, high.LDH0:chemosens1, and high.LDH1:chemosens1, while working0:chemosens1 seems to be baseline for the comparison. So you got what you asked for: interaction of chemosens with two variables. This kind of things happen if you remove intercept from the model.


Qual a melhor tag para criar uma barra de menu

Question: Boa noite pessoal, sou iniciante e tals, venho pedir ajuda para criar uma barra de menu
Estou montando um site e tenho 2 barras horizontais, a primeira eu quero colocar uma barra, com um botão de pesquisa e outro de login/cadastro
Já em baixo são os menus de navegação.
Geralmente crio uma tag e coloco um bg color nelas para fazer uma barra, e tenho extrema dificuldade para posicionar da forma que desejo
Alguém saberia me indicar o que fazer para posicionar perfeitamente está barra, além de uma tags adequada para cria-la?
Valeu pessoal!
Comment: Dê uma lida nisso: [MDN: nav](https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/nav). Sobre o resto, sugiro [edit] a pergunta e adicionar um [EMCV](https://pt.meta.stackoverflow.com/questions/1186/como-criar-um-exemplo-m%C3%ADnimo-completo-e-verific%C3%A1vel).
Answer: você pode usar a tag nav ele representa uma seleção de links
ex:

test

não entendi muito bem sua pergunta, você quer uma tag pra posicionar melhor seu menu?
Answer: você pode fazer seu menu desta forma na horizontal

  *{margin: 0; padding: 0;}
  body{font-family: 'Roboto', sans-serif;}
  .menu{height: 60px; width: 100%; background-color: #f74343; display: table;}
  .menu ul{list-style: none;}
  .menu ul li{float: left;}
  .menu ul li a{text-decoration: none; color: #fff; padding: 20.8px; float: left; font-weight: lighter;}
  .menu ul li a:hover{background-color: #f77d7d; transition: 0.5s;}
<!DOCTYPE html>

 <title></title>
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

Página Inicial

Loja

Suporte


error of permutation feature importance

Question: Feature importance can be calculated by permuting features. But it seems to suffer from instability. To be more accurate about the feature importance, chap 5.5.1 in interpretable machine learning suggests repeating the permutation many times to get the permutation error. Also, the author's  R package iml makes the error plot using the percentile of the permutations.
My question is when I permute the features, should I sample with replacement or without replacement?
If I sample with replacement, it would be more like bootstrap rather than permutation, then is it safe to use bootstrap's approach to calculate the confidence interval?
If I sample without replacement, how do I interpret the percentile of permutations? It somehow has a connection to the confidence interval but I could not find a reference to support this connection.
Answer: In the following answer I assume that we compute the feature importance for one feature $x_j$ and compute the importance as the difference in model error after permutation (the alternative would be the ratio).
In the paper about model-agnostic feature importance by [1], the authors suggest splitting the dataset into two random halves and swap the values of feature $x_j$. This is the equivalent to sampling without replacement.
Sampling Without Replacement
Sampling is random and will yield different results when repeated. That's why I would recommend repeating the feature importance estimate multiple times and see how large the variance is.
We compute the feature importance $FI_j$ of feature $x_j$ as the difference in model error increase when feature j is permuted:
$FI_j = \sum_{i=1}^n L(y^{(i)}, f(x^{(i)})) - \sum_{i=1}^n L(y^{(i)}, f(x^{(i)}_{perm:j}))$
where $L$ is a loss function, e.g. squared difference: $(y - f(x))^2$ and $x^{(i)}_{perm:j}$ is the i-th instance from the data with the j-th feature replaced by a randomly drawn value from another data instance.
There is a connection with confidence intervals and hypothesis tests. By resampling without replacement, we perform a permutation test, with the Null-hypothesis that the feature importance of feature $x_j$ is zero:
$$H_0: FI_j = 0$$
By resampling $x_j$ without replacement, we generate samples under this Null-hypothesis.
When the feature is really not important, we should observe values for $FI_j$ that vary around 0.
Permutation tests are a framework to generate confidence intervals and p-values from resampling.
Imagine you would repeat the $FI_j$-estimate 100 times, i.e. we get 100 $FI_j$ estimates.
Then we order the importances by increasing value.
The 90%-confidence interval would range from the 5-th to the 95-th value of the (ordered) feature importances.
Sampling with Replacement
I asssume you mean that you would sample for each instance the feature $x_j$ from the training data with replacement, i.e. you allow the $x_j$ of an instance to be drawn repeatedly (or not at all).
I think that should work as well, but I would recommend sampling without replacement since than we can rely on the framework of permutation tests.
[1] Fisher, Aaron, Cynthia Rudin, and Francesca Dominici. "Model Class Reliance: Variable Importance Measures for any Machine Learning Model Class, from the" Rashomon" Perspective." arXiv preprint arXiv:1801.01489 (2018).
Comment: +1. Welcome to the website. I like your IML book!

error of permutation feature importance


how to validate file size in drupal file upload

Question: in here file validate extensions are working,but the file size validate is not working,i just need file size only, resolution doesn't matter,i want to restrict max file size to 1MB
<code> $form['photo']['file'] = array(
'#title' => t('Photo (Max size 2 MB)'),
'#type' => 'managed_file',
'#description' => t('xvxcds'),
'#default_value' => variable_get('photo', ''),
'#upload_location' => 'public://photo_images/',
 '#upload_validators' => array(
'file_validate_size' => array(1024*1280*800),
'file_validate_extensions' => array('gif jpg jpeg'),
// Pass the maximum file size in bytes
), );
</code>
Answer: You're currently setting the limit to 1024*1280*800 bytes, which is the equivalent of about 1Gb.
Remember, 1kb = 1024b, 1mb = 1024kb, so for a 1mb limit:
<code>'file_validate_size' => array(1024 * 1024),
</code>
Comment: How i set drupal error message for validation?
Answer: You can use managed_file: Like this ....

<code>      $form['files'] = array(
        '#type' => "managed_file",
        '#title' => 'CV',
        '#required' => 'required',
        '#upload_location' => 'public://job',
        '#upload_validators' => [
          'file_validate_extensions' => ['pdf doc txt'],
          'file_validate_size' => [1024 * 1024], // stores files into Byte
        ],
      );*
</code>


How to Encrypt and Decrypt Text message in react native and backend Node js?

Question: i have Messaging app in react native and messages coming from nodejs back end which is encrypted but when i try to decrypt in my react native app using react-native-crypto-js it is not working.
so i want to use a library that works on both nodejs backend and React native app .
any solutions?
Comment: What is the encryption that you use on your back end?
Comment: cryptography.js
Comment: You mean CryptoJS: https://github.com/brix/crypto-js ?
Answer: You must be looking for something like Hybrid Crypto
Comment: thanx a lot . i will use it and check it .
Comment: can i use this library of there is angular.js backend ?
Comment: Also if you find the solution useful you can accept and answer and upvote it. Thanks. Happy Coding :P
Answer: You can also try using JSEncrypt https://github.com/travist/jsencrypt


Question about a robocode method containing sinus and cosinus

Question: I recently started coding courses while my math is really lagging behind beceuse of my past. I'm currently working on the Robocode program but I don't understand the Sine and Cosine example in one of the examples.
Can someone explain me what this lines of code really do?
This is what the master robot does:
// Calculate enemy bearing
    double enemyBearing = this.getHeading() + e.getBearing();
    // Calculate enemy's position
    double enemyX = getX() + e.getDistance() * Math.sin(Math.toRadians(enemyBearing));
    double enemyY = getY() + e.getDistance() * Math.cos(Math.toRadians(enemyBearing));

        // Send enemy position to teammates
        broadcastMessage(new Point(enemyX, enemyY));

This is what the droidrobots will recieve:
Point p = (Point) e.getMessage();
            // Calculate x and y to target
            double dx = p.getX() - this.getX();
            double dy = p.getY() - this.getY();
            // Calculate angle to target
            double theta = Math.toDegrees(Math.atan2(dx, dy));

            // Turn gun to target
            turnGunRight(normalRelativeAngleDegrees(theta - getGunHeading()));

Sorry for my probably simple question. I can't figure it out.
Full code here: https://github.com/robo-code/robocode/tree/master/robocode.samples/src/main/java/sampleteam
Answer: It would be much easier for you if you would make a sketch. Let's use three points on a 2D grid (marked with North, South, East, and West). The first point, say $(x_1,y_1)$ is your ship. The enemy is at $(x_2,y_2)$, and your droid is at $(x_3,y_3)$. Your ship is oriented at an angle with respect to the North direction. This is given by this.getHeading(). In the coordinate system of your ship, the position of the enemy is at distance e.getDistance(), in the direction e.getBearing() with respect to your forward direction. That's equivalent of saying that the enemy ship is at distance e.getDistance(), at an angle enemyBearing with respect to the North direction. Then the position of the enemy ship in Cartesian coordinates with respect to your ship are $$e_x=e_d\sin e_B\\e_y=e_d\cos e_B$$
Here $e_d$ is the distance to the enemy ship, and $e_B$ is the true direction with respect to North. To find out the absolute position, you need to add the position of your ship.
The second part is doing the same steps in reverse.


free/open source proxy server in java with support for IPv6/https/user management

Question: I am looking for a easy-to-configure Proxy server in Java, that is either free or opensource, and has the following features--

Support for IPv6.
Support for HTTPS
Addition/editing/deletion of users permitted to access the proxy server- through command line is a must, and if this can also be done through web forms that would be great.

Also, in connection with my query, I found one script named Muffin(http://muffin.doit.org/), but it is quite old...Will it take a lot of time to add IPv6 support to it?(I dont know what exactly has to be done to enable Muffin to support IPv6)- the last release date of Muffin is sometime in 2000!
Answer: Jetty is one solution.  They have a proxy servlet and should support IPv6 and SSL.

Addition/editing/deletion of users permitted to access the proxy server- through command line is a must, and if this can also be done through web forms that would be great.

This you would have to program yourself.  Here's some docs about username/password stuff for Jetty.  Jetty has a password class which generates the auth lines for the realm file yourself.  You could easily write a script for it.
Comment: The Jetty proxy servlet page has moved, now is [here](http://www.eclipse.org/jetty/documentation/current/proxy-servlet.html)
Comment: Is any project like https://hide.me/en/proxy in java ?


Twilio WhatsApp - Already bought phone number and creating messages

Question: To send an SMS we can do:
await twilio.messages.create({
  to: "07888888888",
  from: twilioMessagingServiceSid,
  body: "Body of message",
});

When using Whatsapp is it possible to do the same in the from parameter as in passing the twilio messaging service sid?
I would like to be able to support both SMS and WhatsApp for our customers using the same phone number that is already in use for SMS messaging.
Answer: Twilio developer evangelist here.
You can enable your Twilio number to send WhatsApp messages as well as SMS messages. There are a few steps to go through, at a high level they look like this:

Request access to enable your Twilio numbers for WhatsApp
Submit a WhatsApp Sender request in the Twilio console
Approve Twilio to message on your behalf in the Facebook Business Manager console
Submit your Facebook Business Manager account for Business Verification
(Twilio completes your WhatsApp Sender registration)

The full instructions to connect your Twilio number to your WhatsApp Business Profile are available in the documentation here.
Once you have done that, you can add your WhatsApp enabled number to the messaging service. Then, when you send a message to a WhatsApp number you can use the messaging service as the from and a WhatsApp number as the to.


What is a `##` means in bash variable substitution `${}`?

Question: I am learning the bash script materials on http://www.tldp.org/LDP/abs/html/index.html
and stuck in the Example 7-7:
http://tldp.org/LDP/abs/html/comparison-ops.html#EX14
There is an ${filename##*.} != "gz", this probably means
that the $filename does not end with .gz, but I do not
know the meaning of ## here. Could anyone help me?
Thanks!
Comment: From your shell, you can also run `man bash`, then hit the forward slash to start a search, type `##` and hit Enter. Magic!  :-D  (And that entire section, "Parameter Expansion" is worth a close look.)
Comment: That is holy great! @ghoti
Answer: Used in a variable expansion, ${string##sub} removes the longest matching substring sub from string (# removes the shortest matching substring by contrast).
In your case, yes - this will return the string after the first . from the filename, giving the file extension.
If you search for ## in this documentation, you'll find an explanation (along with other similar commands).
Comment: Thanks. WIth your help, I found the guide of expansion on http://tldp.org/LDP/abs/html/refcards.html#AEN22728 .
Comment: @cmal I hadn't seen the refcards page before - that's actually really, really useful, bookmarking that. Thanks for showing me something new!
Answer: In the context of filenames, is trying to find the extension in the variable filename
filename="*.log"
echo ${filename##*.}
log

We are attaining the part of the string filename after "*."
Answer: ## is a used for to remove a substring from a variable. For more info check this page.
For eg. if filename=/home/user.name/folder.1/test.gz, then ${filename##*.} will give you output as gz.


PHP Prevent Direct Access

Question: Is there any possible way to make direct browser access to
http://www.example.com/test.php

Not available when viewing url directly but still allowing
JQuery $.get('http://www.example.com/test.php') function

To read the file? I know this might not be possible because I believe going in my browser and typing http://www.example.com/test.php is basically the same thing on client side as using the $.get() function.. But I didn't know if there was any work arounds for this.
Answer: Kinda, have php check for the x-requested-with header. If it is not present, redirect somewhere else.
It doesn't stop someone from sending their own request with said header though.
Comment: It has cookie's inside said test.php so I don't believe it's an issue because that would knock it out.. Plus even if they did all that and somehow got past that it wouldn't be the biggest deal in the world it's merely profile information.. But people get snoopy sometimes and like to go to source files if you know what I mean.
Comment: How would I check if those are set and redirect if you don't mind asking?
Comment: Here's a blog post that explains it pretty well: http://davidwalsh.name/detect-ajax The first result in a google search. Imagine that!
Answer: You are right, using a browser or $.get are basically the same. The only difference is that an AJAX call sets the X-Requested-With header to XMLHttpRequest. This can be added with browser extensions, though, so it is not fool-proof.
Comment: How would I check if those are set and redirect if you don't mind asking?
Comment: The snippet before was just to see if the request came via AJAX. You will just use a condition like `if (!isAjax()) { header("Location: somewhere-else.php"); }`

PHP Prevent Direct Access


Change webserver with minimal downtime

Question: I have a webserver in production.  Its IP is 126.96.36.199 and it is referred to as ServerA.  In addition to storing script files, the server also stores user uploaded files and has a database.  The application uses wildcard subdomains where foo.example.com, bar.example.com, etc go to a common virtual host, and the server code responds as appropriate given the subdomain name.    I have my domain registrar pointing to IP 184.108.40.206 and also set up to support wildcards.
I will need to change webservers to a new server with IP 126.96.36.199 which it is referred to as ServerB.
What steps should be taken to migrate the servers with minimum downtime?
Below is my  initial thoughts.  Please comment if incorrect or if I am missing steps.

Post notice on ServerA that the system will be down for maintenance.
Setup Apache on ServerB similar to the setup on ServerA and also add another virtual host on ServerB with ServerName 22.214.171.124, (more on this later).
Set up Apache on ServerA to display a down for maintenance page instead of accessing the application script.
Copy script files, uploaded user files, and the database from ServerA to ServerB.
Change domain registrar to point to IP 184.108.40.206.
Setup Apache on ServerA to redirect all requests to IP 184.108.40.206.  How will this work with the subdomain requirements?
Wait for domain name changes to propagate.  Will I be down during this time?
After ServerB is fully tested, cancel service plan for ServerA.
Answer: How about a zero downtime migration?
This is my general plan for such migrations:

Set up an ad hoc VPN between the old server and the new server (e.g. with OpenVPN).
Copy the entire application from the old server to the new server.
Set up database replication between the old server and the new server, with the old server as master and the new server as slave, via the VPN.
Wait for all databases to be replicated. This may take a while.
Once replication is complete, connect directly to the new server (use the /etc/hosts trick) and verify that the application seems to work, that the web server is configured correctly, etc.
Break the master/slave relationship and configure the application on the old server to talk to the database on the new server via the VPN.
Change the DNS records. While waiting for the TTL to expire, some users will hit the old server and some will hit the new server, but both will use the database on the new server.
When the TTL expires and the old server is no longer receiving traffic, decommission it. Take down the temporary VPN.
Comment: Zero downtime is good!  I've never done database replication.  Is this available with MySQL community edition (EDIT.  Looks like it is: http://dev.mysql.com/doc/refman/5.0/en/replication.html)?  Could you give me some key words to google regarding the /etc/hosts trick?  Thank you
Comment: Yes, you can do replication with MySQL; it's all in their documentation. And modifying /etc/hosts is just putting the IP address of a site in the hosts file to override where your computer tries to load it from. Pretty common development trick.
Comment: Thanks Michael,  After asking about replication, I did a little research and found it.  Very nice answer!

Change webserver with minimal downtime


What is the best way/tool to analyze raw data(network stats) from Simulation?

Question: After running a simulation(using a simulator(QualNet)) of a simulated network I end up with ip stats stored in a database, I then extract the data to a csv file
So now I have 750mb of raw network stats(time stamp, packet id, source ip, source port, protocol, etc).
What are the common ways of analyzing large amounts of data like above, if you want to know things like packet loss, throughput, delay, congestion, etc.
Comment: I've had great success using something called an "IT bitch" for similar tasks.  If you use a smart IT bitch, it will usually employ a number of useful tools to complete the task, which you can then reuse in future work.
Comment: This sounds like a joke, please provide the link for the tool
Comment: I don't have a link for our current IT bitch because it doesn't have a LinkedIn or Facebook account, or whatever.  Plus, I don't share my bitches.  If you want to find an IT bitch to call your own, advertise the job openign.  I think the HR-friendly synonym for "IT bitch" is "IT intern," if that's helpful.
Comment: @user90500 It is a joke. What you need is a [PFY](http://en.wikipedia.org/wiki/Bastard_Operator_From_Hell), or maybe an intern.
Answer: Without knowing just what data you are interested in we can only give very broad and general replies.
Others will no doubt have their own preferred methods but what I do with that much data is to create Perl scripts to read the data directly from the database, using queries designed to read only those parts I am interested in for a particular report. The script would then produce output in a suitable form, most often as spreadsheets or charts.
The hardest part is not filtering the data and producing the reports. The hardest part is determining just what parts you do want to see. With that much data you have to filter it down if you want to make any kind of sense out of it.
Comment: Thanks for the suggestion John, I am not too familiar in scripting with Perl, what is your suggestion on how to get started with writing Perl scripts that can filter database stats? How do you ultimately plot the info?
Comment: It doesn't have to be Perl, that's just what I prefer to use. Nevertheless, it's the best language for such jobs. There are numerous tutorial sites on the Internet. As for plotting, I generally create Excel charts, mainly because Excel is already on all the machines that may be used to view the charts. This is surprisingly easy to do with the "Excel::Writer::XLSX" module.
Comment: Thanks again John, can you please guide me to the most helpful tutorial that will help me start learning about making use of Perl scripts with databases
Comment: Which tutorial might be best for you will depend a bit on your previous experience with programming and scripting languages, so it's hard to recommend one but if you Google for "perl tutorial" and flick through the results you should be able to find one that is aimed at your level.


javascript: console log use parent scope

Question: Is it possible using some javascript trickery to tell console.log which line number it should output?
Suppose, we the following simple example:
function Logger () {
    this.debug = function(msg) {
        // do some stuff with msg
        console.log(msg);
    };
}

var log = new Logger();
log.debug("Hello");

If you open the page, Chrome shows up this:

This indicates that the message was logged at main.js:4 but what I really want is that it shows main.js:9. Because line 9 is where the logger was called.
For this simple case it doesn't make much difference, but when the Logger is in a separate file, it always shows logger.js instead of the class which called the logger.
The Logger class should do some additional stuff with the logged message (e.g. sending it to the server), thus I can't just use this.debug = console.log.
EDIT:
There are already some similar questions, but all of them just add an additional line to the output, which isn't clickable to jump to the corresponding line:

Extending console.log without affecting log line
console.log wrapper that keeps line numbers and supports most methods?
Get console wrapper to log message on correct line
Getting Chrome's console.log to display the line that called a function
Custom console.log that keeps line number
Intercept console.log but keep stack
https://stackoverflow.com/questions/28457477/javascript-console-log-change-line-number-to-somewhere-higher-in-the-stack?rq=1
Answer: The first thing that comes to my mind is creating a new Error object to get the stack trace and then find the line that called your method, like this:
function Logger () {
    this.debug = function(msg) {
        // do some stuff with msg

        //TODO: document this line
        var callerLine = new Error().stack.split('\n')[2];
        console.log(msg, callerLine);
    };
}

var log = new Logger();
log.debug("Hello");

Basically I'm splitting the error's stack in each newline and ignoring the first and second lines (The error message and your own method in the stack, respectively).
Comment: This is a solution which is not yet perfect.
The output is now: `Hello     at http://localhost/main.js:12:5       main.js:7`
It would be nicer to have just the relative path.
Comment: Unforunately the Error.prototype.stack property is non standard conform, so this isn't a valid solution. See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Error/stack
Comment: This code is not even meant to work in production because your JS should be minified, fitting everything in as few lines as possible. This is not meant to be a cross-browser thing, just a way to simplify logging, so I don't see how not being a standard makes this a "invalid solution"
Comment: Well the problem is that I'm using Typescript which complains at this line that `TS2339: Property 'stack' does not exist on type 'Error'.`


Definition of a geometric sequence

Question: Is the sequence $0, 0, 0, 0 ...$ geometric? If so how would you define it? In order to define a geometric sequence you need the first term, and the ratio of terms. In this case you could have:
$a = 0$
$r = k$ for some $k \in \mathbb{R}$
Is this still geometric, even though a single unique definition doesn't exist (a non variable $r$)?
EDIT: This is an interesting debate. But you could also say that $0, 0, 0, 0 ...$ is an arithmetic sequence. So to all who are saying that it is geometric, can a sequence be both geometric and arithmetic?
Comment: $1,1,1,1,1,...$ is a sequence geometric, arithmetic and harmonic. :)
Comment: @talfred Yes. Consider  $U_{k} = 1^{k} $
 $V_{k} =0k+1$
Comment: The problem is You can not have $\frac{a_{i+1}}{a_{i}}=r\neq \frac{0}{0}$ , where $i$ is any $ith $ term.
Comment: In response to the edit. Well since a sequence defined with an exponent $x$ will always change (increase or decrease depending on whether the $x$>1) at a faster rate than a sequence defined linearly, it appears that the only hope of having the sequences remain equal at all terms would be to have the sequence be defined in such a way that it is constant at all terms. Which explains why 0 is unique in this respect.
Comment: @J.Gudal So you can have a sequence which is both geometric and arithmetic?
Answer: Ultimately it will depend on what you consider the definition of a geometric series, as you can see by the other answers here. If the definition relies on calculating a common ratio $r = a_{k+1}/a_k$, then you will run into division by $0$.
You can avoid that problem by saying that a geometric sequence is one whose terms obey the property $a_ka_{k+2} = a_{k+1}^2$. Another way is to define the sequence as $a_k = cr^k$.
Personally, I would say that the sequence $0,0,0,\ldots$ is a geometric sequence in the same way that a point is a circle of radius $0$.
Comment: Here's another metaphor similar to my last sentence: as a vector, $\langle 0,0 \rangle$ has no clearly defined direction. Do we still allow it as a vector?
Comment: A very nice reference on your last sentence. :)
Comment: @talfred The use of different definitions between different authors doesn't mean that there's lack of rigour. If the same author used two different definitions in the same work, then there would be a problem. It's more a question of which definition is most useful or appropriate, and this can change over time. The zero sequence is certainly not geometric according to Euclid, but we've moved on from there.
Comment: @mattbiesecker Ha! Next thing you know, we'd be replacing $\pi$ in the literature with $\tau /2$ ...
Comment: I like your last point! So you say it is geometric, but then I say given the sequence $0, 0, 0, 0...$ and given that it is geometric, what is $r$ for this sequence?
Comment: @Théophile You are the master of metaphors tonight. Could I hear your take on the edit in the original post?
Comment: @talfred Sure: I think the sequence $0,0,0, \ldots$ can be many things: geometric, arithmetic, exponential, and so on. It's not a particularly interesting sequence, but that doesn't mean we should shun it. :) The way I see it, it's much better to include the trivial sequence in the definition than to exclude it. Otherwise, we'd end up with such cumbersome statements as: "Any sequence of the form $a_k = cr^k$ is either a geometric sequence or the zero sequence." Similarly, "The solution to the ODE $y' = y$ is an exponential function or the zero function." It's exhausting even typing that out.
Comment: @Theophile.   Any interest in heading the International Committee for Standardizing Mathematical Definitions and Notation.  :)
Comment: $r$ can be anything, since $c=0$?
Comment: @Atvin but does this uniquely define the sequence? Seeing as you could take $r \in \mathbb{R}$ there exists infinitely many definitions for this sequence. So does a geometric sequence need a single unique definition, or can it be defined in more than one way?
Comment: I thought a point was a non-empty interval of length 0 :P
Comment: @Théophile It looks like we need a rigorous definition of a geometric sequence! I believe a similar issue to the one we are having would occur for prime numbers, if "greater than 1" was not included in the definition. This debate about geometric sequences troubles me, as it is "wishy-washy" and Maths should be rigorous and definite.
Answer: Just to play devil's advocate, here are some theorems we lose if we allow a sequence that ends in zeroes to be geometric:

A geometric sequence converges if and only if the common factor is in $(-1,1]$. (Counterexample: $0\cdot 2^{n-1}$ does converge).
A geometric sequence has a sum if and only if the common factor is numerically less than $1$. (Counterexample: $0\cdot 2^{n-1}$ does have a sum).
If $(a_n)$ and $(b_n)$ are geometric sequences and for some $i$ we have both $a_i=b_i$ and $a_{i+1}=b_{i+1}$, then $a_i=b_i$ for all $i$. (Counterexample: $0,0,0,\ldots$ versus $1,0,0,\ldots$).

Pragmatically it is probably most useful to exclude these sequences from being "geometric" such that the statements of the general properties can be kept simple. If we need to apply the theorems in a situation where the sequence might be degenerate, it is usually very simple to handle degenerate cases by ad-hoc methods.
Comment: @talfred: It is true that the particular definition of "prime" _that most mathematicians have chosen to use_ leads to $1$ not being prime. That doesn't negate the fact that using this definition was a _choice_, rather than a necessary truth that is amenable to proof or disproof.
Comment: @talfred: It is not a matter of proof! Which definition to use is a _choice_ we make.
Comment: Thank you for your contribution! I personally think that it is not geometric, as you can construct a counter-argument for it not being geometric, hence it is not rigorously accepted as being geometric. You could say the reverse: but it's more ideal in my eyes to not consider it geometric, until it has been rigorously proved (geometric or not) beyond all doubt.
Comment: So depending on the definition you choose, you end up with a different outcome! It should either be geometric, or it is not. Just like $1$ is not a prime number, because it is included in the definition of a prime number.
Comment: @talfred: Once you decide what you want the word "geometric sequence" to mean, the sequence is either geometric, or it is not. Just like once you decide what you want the word "prime" to mean, the meaning you decide on will either apply to $1$ or it won't.
Comment: But $1$ is mathematically accepted as not being prime. Anyone saying that it is prime would be considered wrong.
Comment: @talfred: And I don't know why you bring up primes, but if you just take a look at http://en.wikipedia.org/wiki/Prime_number you will see that the definition of prime is different for different people in different contexts. Anyway the basic point which Henning has been trying to get across is that **a definition is a choice of what is to be given what name**, and **a proof is a sequence of deductions from axioms that are allowed by inference rules**. Definitions simply go into the list of axioms to fix the interpretation of certain predicate symbols or function symbols.
Comment: Your last point is invalid as stated. $1,1,1,1,\ldots$ and $1,-1,1,-1,\ldots$ are _bona fide_ distinct geometric sequences that coincide in more than one position. This could be repaired by requiring coincidence in two successive positions. But personally I think this is a rather unimportant property, and cannot imagine any real use being made of it.
Comment: @Marc: Fixed. (And it might be that the devil has a poor case here, but I work with what I have to work with).
Answer: It depends on the exact definition, using @Atvin definition, it is not geometric.  Using an alternate definition, e.g. "a geometric sequence has the form $a_n = c r^{n-1},$ where $c,r$ are constants."  Taking $c=0$ generates your sequence.
Comment: @J.Gudal: $0/0$ is usually actually undefined. You may be thinking of $0^0$ which is an indeterminate form, but also defined as $1$.
Comment: Interesting take on that definition. Kind of interesting, that with the one I used, we got a non-existant thing, and with this, it seems ok.
Comment: $0/0$ is not non-existent. Its indeterminate. There is a distinction. Indeterminate means that there exists a value, we just don't know what it is.
Comment: @Makholm http://mathworld.wolfram.com/Indeterminate.html
Comment: @J.Gudal: $0/0$ happens to be _both_ an indeterminate form _and_ undefined.
Comment: @Makholm But there is a subtle distinction.between the two. $0/0$ has no value that we can ascertain. But suppose if we decided that $2 \times 0=0 \rightarrow 2= \frac{0}{0} $ then we have defined $0/0=2$ right? But starting from $0/0$ we cannot determine what this value would be. I may be deeply mistaken though, so I'm happy to be corrected.
Answer: Using the definition: $\frac{ a_{n+1}}{a_n} = q$
It can't be a geometric series, since by definition it comes, that $\frac{ a_{n+1}}{a_n} = q$(for every $n \in \mathbb{N}$), where $q$ quotient is fixed, but in that case, you have $\frac00$, which leads to divising with $0$, and you can't do that. :)
Comment: @talfred: Mathematics can be rigorous _once we have decided which definitions and/or axioms to work from_. However, the choice of which definitions it is worthwhile to use is a more pragmatic and fuzzy question. Ultimately it comes down to opinion about which definitions are so _useful_ that they should get the short words.
Comment: This is my opinion. However you could still "generate" the series by taking $r = 1$ and $a = 0$, which would generate $0, 0, 0, 0 ...$. Because I've just generated a sequence using the two defining features $a$ and $r$ is this not geometric?
Comment: What is $a$ and what is $r$? :)
Comment: Well @talfred , it depends on definition. You can use various definition to formulate a geometric progression. But one definition of common-ratio is the one stated in this answer. So you can't have that as $\frac{0}{0}$. However you can avoid this problem by defining your geometric series without the help of $r$.
Comment: @Mann This is my issue! There doesn't appear to be a strict mathematical argument as to whether it is geometric or not. I don't like this, maths should be rigorous.
Comment: Now that it seems, maybe it indeed can be considered as one. When properly defined. For e.g., the nice analogies by theophile :) @talfred
Answer: We could also define a geometric sequence as any sequence such that each term ,after the first term, is the geometric mean of its successor and predecessor.
In which case, the sequence given would satisfy this definition.
I suppose it comes down to which definition we are using.
Answer: As others have noted, it all depends on how precisely one defines the term geometric sequence. One can define anything one likes; for instance Wikipedia gives the definition that the general term at position $n$ (starting from $0$) should be of the form $ar^n$ with the rather ridiculous condition that $r\neq0$ though $a$ is unconstrained; that would make $0,0,\ldots$ into a geometric series of undetermined ratio $r\neq0$ (taking $a=0$), but $1,0,0,\ldots$ would not be a geometric series (here the ratio would clearly have to be $0$, but that was forbidden).
Part of the problem here is that one tries to define the unqualified notion "geometric progression" (or sequence), while in practice one most often deals with geometric progressions of specified ratio $r$ (in which case the general term is simply $ar^n$ where $a$ is the initial term); this shifts the focus from generating a geometric progression (which really never poses any problem) to recognising a given sequence as being geometric (this leads to considering ratios of successive terms, which is problematic if they are $0$; it still does not explain why one should forbid $r$ to be $0$, but not $a$).
To take some distance from the rather uninspiring "I found a source that says this" approach, let me view geometric sequences as an instance of anther notion, that of eigenvector. In the vector space of infinite sequences, the geometric sequences with ratio $r$ are precisely the eigenvectors of the "guillotine operator", which removes the initial term of a sequence and shifts the other terms to fill its place, for the eigenvalue$~r$. From this perspective, one sees why the zero sequence should have a special status; normally the zero vector is explicitly forbidden as eigenvector (because it would be so for any value of$~\lambda$, whether or not it is an eigenvalue), although it is included
in any eigenspace. For the exact same reason allowing the zero sequence as a geometric sequence is somewhat problematic (no unique ratio can be determined for it) but it is OK (in fact necessary) to include the zero sequence in the subspace of geometric sequences with given ratio$~r$.
Note that viewing geometric sequences as eigenvectors is quite natural; they are used in this role when solving linear recurrence relations with constant coefficients.

Definition of a geometric sequence


Can Ansible git-module install the latest tag from a repo?

Question: I want to install recent, but not the HEAD. Instead, I'd like to install the most-recent tag of a remote repository -- on the assumption, that this is, what the maintainers consider a "release". Can the git-module do that?
The methods of figuring out the most recent tag are provided here, but they all require for a clone to have happened first.
Is there a way to have the module do "the needful" for me automatically, or must I do it the hard way:

Clone with the git-module.
Find the latest tag with the command-module.
Use another git-task to switch to the tag?
Answer: No. Ansible git module requires one commit-ish as the version parameter. One tag, a branch, a commit hash, or HEAD.
How would you sort the tags, committerdate, refname? Actually could be non trivial. The authors could maintain multiple  branches in one repo. A previous version backport might commit later. Also, version "number" strings are   annoying to sort correctly, git tag --sort=refname might order things in an undesirable way:
v2.8.2
v2.8.20
v2.8.20rc1
v2.8.3

Forget git for a moment, it is not the best deployment tool. Install releases with a package manager that has version numbers and dependency resolution. If a package does not exist, write one yourself, perhaps following the guidelines for your OS distro of choice.
To continue with git anyway, provide the git module a commit-ish that will resolve to the latest stable that you want. Such as a maintenance branch. Create such a branch if it does not exist, on the tag you want. Keep updating this branch as new versions are released.
Comment: The repositories are _many_, but none of them are _mine_. I cannot change them. But I can query each for the most-recently created tag. Ordered by time. The link in my question explains, how this can be done. But, I guess, Ansible's `git`-module cannot do that :(
Comment: Consider making your own clones of  the upstream repos that has maintenance branches you advance as desired. Deploy from your git repo. Not the only way to do it, you could write a shell script to sort tags.  However, my answer is idempotent modules, so `git` or `package` or `pip`


What's is the equation of sinusoidal function on cylinder perimeter

Question: How can I determine the equation of a sinusoidal function that instead of proceeding on a horizontal line, proceeds along the perimeter of a cylinder while its sinus also lies on the surface area of the cylinder, like radially squeezing the cylinder?
Answer: Just use cylindrical coordinates
$$
z = h\sin \left( {\lambda \theta  + \alpha } \right)
$$
where:
 - $h$ is the amplitude of the sinusoid;
 - $r$ is the radius of the circular cylinder around the $z$ axis;
 - $\lambda$ is the angular speed  of the sinusoid (n. of repetitions along one turn around the cylinder);
 - $\alpha$ is the phase (in rad) of the sinusoid;
 - $\theta$ is the parameter, which is the angle (in rad) of the generatrix of the cylinder.
You can then convert to a parametric equation in Euclidean coordinates as
$$
\left\{ \matrix{
  x = r\cos \theta  \hfill \cr
  y = r\sin \theta  \hfill \cr
  z = h\sin \left( {\lambda \theta  + \alpha } \right) \hfill \cr}  \right.
$$
example:
Comment: @FabioSpaghetti: I recasted the answer with parametric equations you can use for plotting
Comment: @FabioSpaghetti:  I'm sorry I don't know the details of Python (not yet, I would like to learn). I obtained the above with my old (but still very good) Mupad as x:=t->r*cos(t):
y:=t->r*sin(t):
z:=t->h*sin(l*t+a):

r:=3: l:=5:  h:=1:  a:=0:

plot(
plot::Cylinder(r,[0,0,-2],[0,0,2],Color=RGB::Yellow),
plot::Curve3d([x(t),y(t),z(t)],t=0..2*PI)
);
Comment: @FabioSpaghetti: maybe you can follow [this other py.plot example](https://matplotlib.org/3.1.0/gallery/mplot3d/lines3d.html#sphx-glr-gallery-mplot3d-lines3d-py)
Comment: @FabioSpaghetti: well, the example is for a paraboloid spiral, not for a cylindrical sinusoid. So just replace r= const. (as $h$ and $\alpha$) and $x,y,z$ as in the answer
Comment: This is definitely a fantastic answer. only that I will have to plot it in Python , and based on the code here : https://matplotlib.org/3.1.0/gallery/mplot3d/surface3d_radial.html it needs to have the functions also in 3D, I wish someone could help me
Comment: @G Cab : YOU ARE SUPER GREAT !! more than what I expected ! thanks a lot
Comment: just one problem, this did not work for me, why ?
Comment: I can't post my code here , too long
Comment: only the definition :
Comment: h= 0.5;
landa= 1;
alfa = 0;
r = np.linspace(0, 1.25, 50)
p = np.linspace(0, 2*np.pi, 50)
R, P = np.meshgrid(r, p)

Z = (h* np.sin(landa*P+alfa))

# Express the mesh in the cartesian system.
X, Y = R*np.cos(P), R*np.sin(P)
Comment: Thank you very much, but why in that code, r is a function of Z, instead of Z function of theta, like your formula ?
Comment: This was the most beautiful answer I got on StackOverFlow.com ! Gold answer !! it worked beautifully ! thank you!!!!!!!!!!


which features does a network library wrap over the linux network syscalls

Question: Support we just consider on the Linux platform.
Since the syscalls can provide the epoll/select function, why do we need a C network library?
or in other words, which benefit does a network library offered better than using syscalls directly.
Comment: What network library?
Answer: First of all, it is the OS (on linux) that provides the "syscalls" feature, not the other way around.
Starting from that, to answer your question, libraries are useful for :

abstracting away low-level OS-bound or API-bound complexity
working on a higher level of abstraction
faster and easier development
easier comprehension of features
easier knowledge appropriation

and this by providing :

higher abstraction around concepts/features
error handling
error anticipation
memory management (not always)

A good reading to start with would be :
https://man7.org/linux/man-pages/man2/syscalls.2.html


A logic problem about set theory

Question: In a group of n people, subgroups with common interest are formed (football,tennis,snooker). The number of subgroups equals $2^{n-1}$. Any 3 subgroups have a common member. Prove that there is a person who is a member of all the subgroups.
proof by contradiction seems like a good fit here, but I can't seem to get the details right.
Comment: @Fargle Yes, I see that now. I think I understand the question.
Comment: I'm not quite sure what you mean here. I see that there are $n$ people, (say $X=\{1,\dots,n\}$) but I'm not sure how many subsets there are. I understand that there are $2^{n-1}$ proper non-empty subsets of $X$ but it seems you only consider some, say $Y_1,Y_2,\dots,Y_k\subset X$. Do you know what $k$ is in this case? It seems that given any distinct $a,b,c$ that you know $Y_a\cap Y_b\cap Y_c\ne\varnothing$ and want to prove that $Y_1\cap\cdots\cap Y_n\ne\varnothing$ but I'm not sure I understand the question. Could you try to clarify please?
Comment: @DanRobertson: I believe that there are $2^n - 2$ proper non-empty subsets. Thus only about half of all possible subsets end up forming.
Comment: @DanRobertson any idea how to prove this?
Comment: @prometheus21 Not really, Perhaps it would be possible to determine the largest collection of subsets where any three intersect but the total intersection is null and show that the size of this is $2^{n-1}-1$. It is certainly at least $2^{n-1}-1$, take subsets $X_i=\{1,\dots,n\}\backslash\{i\}$.
Comment: This looks a bit like a finite version of the delta system lemma. But I'm not sure if one could take some inspiration from there.
Comment: I'm pretty sure that the subgroups need to be distinct, otherwise there are obvious counterexamples
Comment: Is that American football?
Comment: Haha no, European football.
Comment: The statement is untrue for $n=2$.
Answer: Denote the set by $S,$ and let $X$ be the collection of subsets of $S$ as given in the problem. First note that $A\in X$ iff $A^{C}\notin X$ since we have exactly $1/2$ of the total number of subsets. From this we deduce that if $A, B\in X,$ then $A\cap B \in X,$ since $(A\cap B)^{C} \cap A\cap B = \emptyset.$ Now, if $\{x\} \in X$ for some singleton, then we're immediately done, so suppose this isn't true. Then every set of the form $S-\{x\}$ is in $X.$ Taking the intersection of two of these gives a set of the form $S-\{x, y\},$ and we clearly get all such sets. Continuing in this manner gives that every set is in $X,$ a contradiction, so we're done.
Alternatively you can just do this by induction on the intersection of $k$ sets, with the base case being $k=2$ proven above.
Answer: Given a finite set $N$ of size $n$, let $O_n$ be a family of subsets of $N$ such that any three elements of $O_n$ have non-empty intersection. Given that $|O_n| = 2^{n-1}$ you want to show that $\exists x \in N \forall o \in O_n : x \in o$.
When forming an $O_n$, the maximum number of subsets of $N$ that can be chosen of a specific size $k$ is exactly the number of choices from $N$ where one element is fixed; this is exactly $\binom{n-1}{k-1}$. Fixing one choice ensures that all the subsets of size $k$ obey the requirement at any three subsets share an element.
Notice that enumerating the maximum choices for each $k \le n$ forms a row in Pascal's Triangle, and the sum of all the maximum counts for each $k$ is equal to $2^{n-1}$. Therefore, in order to form an $O_n$ whose cardinality is exactly $2^{n-1}$, the maximum number of each size $k$ subset must be chosen. This includes one singleton subset (if no singletons are chosen, then one more set must be chosen to reach the appropriate size, but one more choice from any other size subset would violate the maximum for that size). Thus, in order for $O_n$ to satisfy the requirement that any three subsets share an element, the fixed choice in each size $k$ subset must be the element of $N$ in the singleton.
Therefore the singleton choice is the $x$ that satisfies $\exists x \in N \forall o \in O_n : x \in o$
Comment: Any comments about why the downvotes?
Comment: I didn't downvote, but I don't understand your argument either. It looks like you are counting the maximum number $m$ of sets that can have one common element. This is certainly necessary that $2^{n-1} \leq m$ for the proposition to be provable, but I don't see how $m = 2^{n-1}$ actually proves it. Also, you didn't use the other hypothesis, which looks a bit suspicious...
Comment: @A.P. I do use the other hypothesis. Since any three subsets must share one element, and the singleton set must be chosen, then any three subsets must include the singleton, which means that the one common element must be the singleton in every case.
Comment: Still, you didn't address the other issue. It looks like you measure the maximum size $m$ of a collection of subsets which satisfies the thesis (i.e. which have a common element). I understand how you could use it to *disprove* the proposition, but not how $m = 2^{n-1}$ gives you a proof that a singleton must be chosen.
Comment: @A.P. Perhaps I was too verbose. I've condensed the argument and made the use of the hypotheses  more obvious.
Comment: What you need to explain is "the maximum number of subsets of $N$ that can be chosen of a specific size $k$ is exactly the number of choices from N where one element is fixed", which isn't obvious at all. The rest can then be condensed in a couple of lines: since the fixed element for each size is arbitrary, you can just count all the sets that contain a single element, which is the same as measuring the cardinality of the power set of a set of size $n-1$. To see this, just substitute the singleton with the empty set.

A logic problem about set theory


Binomial representation

Question: We already know that we can represent this binomial as the following:
$$(a+b)^K=\sum _{n=0}^K \binom{K}{n} b^n a^{K-n};$$
where $\binom{K}{n} = \frac{K!}{n! (K-n)!}$
I want to know if this representation is correct for the reciprocal binomial expression:
$$\frac{1}{(a+b)^K}=\sum _{n=0}^K \frac{1}{\binom{K}{n} b^n a^{K-n}};$$
where $K$ is a positive integer larger than zero.
Answer: Absolutely not.  What you wrote is equivalent to claiming that $$\frac{1}{a+b} = \frac{1}{a} + \frac{1}{b}.$$
Answer: If $|a|>|b|$ then
$$
\begin{align}
& \frac{1}{(a+b)^K} \\[8pt]
= {} & (a+b)^{-K} = a^{-K} + (-K)a^{-K-1}b + \frac{-K(-K-1)}{2} a^{-K-1}b^2 \\[8pt]
& {} + \frac{-K(-K-1)(-K-2)}{6} a^{-K-3} b^3 + \cdots \\[8pt]
= {} & \sum_{n=0}^\infty \binom{-K}{n} a^{-K-n} b^n.
\end{align}
$$
http://en.wikipedia.org/wiki/Binomial_theorem#Newton.27s_generalised_binomial_theorem
Comment: @barznjy : If the exponent were $4$, so that the coefficients were $1,4,6,4,1$, then we could write $\dfrac{4\cdot3}{2!}$, $\dfrac{4\cdot3\cdot2}{3!}$, $\dfrac{4\cdot3\cdot2\cdot1}{4!}$, $\dfrac{4\cdot3\cdot2\cdot1\cdot0}{5!}$, $\dfrac{4\cdot3\cdot2\cdot1\cdot0\cdot(-1)}{6!}$, and so on, and we'd have an infinite sequence in which everything after the fifth term is zero.  But when the exponent is either negative or a non-integer, then we never get zero.  The condition $|a|>|b|$ assures us that the series converges.
Comment: Then you have $1,-4,\dfrac{(-4)(-5)}{2!},\dfrac{(-4)(-5)(-6)}{3!},\dfrac{(-4)(-5)(-6)(-7)}{4!},\ldots$.
Comment: could you please write the compact summation form represetation?
Comment: 1- If a and b are real numbers greater than zero, the above statement is the same, I mean can we omit the condition of $|a|>|b|$ because there is + sign between them?
2- Why the upper limit of the summation is $\infty$, (i.e. why it is not K), bearing in mind K is positive integer greater than zero ?
Comment: 1- Is it (1,-4,6,-4,1) or (1,4,6,4,1)?
2- So we can say that totally we have (K+1) terms, (and for our specific case when K is integer, we can say the upper limit of the summation is (K+1)); is that correct?
Comment: @barznjy : I was speaking of the coefficients when the exponent is $4$.  Those are $1,4,6,4,1$.  And one can view them as $1,4,6,4,1,0,0,0,\ldots$.
Comment: What about the the coefficients when the exponent is $-4$?
( i.e. $(a+b)^{-4}$ ).
Comment: Could you tell me a reference book that mentioned this equation:
$ (a+b)^{-K} = \sum_{n=0}^\infty \binom{-K}{n} a^{-K-n} b^n $

Binomial representation


Em qual ordem uma classe herda de suas superclasses em python?

Question: Seja o código abaixo:
class B(A):
    def __init__(self):
        self.c  = 16
    def y(self):
        print("B.y")
    def get_c(self):
        return self.c

class C(object):
    def __init__(self):
        self.c = 5
    def y(self):
        print("C.y")
    def get_c(self):
        return self.c

class D(C, B):
    def __init__(self):
        C.__init__(self)
        B.__init__(self)

var = D()

Ao chamar var.y() o resultado é C.y  pois D(C, B) herda seus métodos de suas superclasses seguindo uma ordem de esquerda para a direita. Porém, ao chamar var.get_c() o resultado é 16. Por que?
Answer: Conforme a documentação oficial acerca de classes em Python, vemos no item de heranças múltiplas a definição:

For most purposes, in the simplest cases, you can think of the search for attributes inherited from a parent class as depth-first, left-to-right, not searching twice in the same class where there is an overlap in the hierarchy.

Ou seja, utilizando seu exemplo, se um método/atributo não é encontrado na classe D, Python irá buscar por sua definição na classe C, primeira à esquerda. Se não encontrar, iria mais fundo, para as classes base de C. Como não possui, volta à classe B e, se não achar, vai para a classe A, se não achar, para as classes bases de A. Se ainda não achar a definição, dispara a exceção.
Portanto, quando executado var.y(), busca-se a definição de y em D, C, B, A, nesta ordem. Encontra em C, portanto retorna C.y. Quando executado var.get_c(), a mesma coisa, também é encontrado em C, retornando o valor de self.c, porém, o que acontece aqui é que no inicializador da classe D, você executa o inicializar da classe B após a da classe C e em ambos a propriedade self.c é definida. Ou seja, quando executado C.__init__(), o valor de self.c será 5, mas quando executado B.__init__(), o valor de self.c passa a ser 16, o que explica o fato de var.get_c() retornar o valor 16-


ii-V-I versus I-IV-V

Question: The I-IV-V progression is used in a lot of blues, rock, folk, country and pop music, while jazz music tends to favor the ii-V-I.
I am aware that the ii and IV chords are both subdominant and they both perform the same function, however I'm curious of the possible historical reasons why ii-V-I are favored in jazz and I-IV-V in the others.
Comment: Is your question "why does jazz favour the chords in one order and other genres, another order?", or "why does jazz favour ii and other genres favour IV?"?
Comment: these are good chord progressions in any genre.
Comment: @NeilMeyer ii and IV are very often interchangeable, the bass player can make the switch without asking anyone and the song is not spoiled at all, just slightly different.
Comment: could you illuminate us to what you exactly mean by ii and IV serving the same purpose?
Comment: @RosieF I don`t care for the order necessarily , just why does one genre uses the ii as subdominant while others the IV
Comment: @piiperi if anyone is playing the second scale degree then the bass player playing the fourth scale degree does not create a IV chord but a ii 6/5 chord.
Comment: @phoog I'm not sure if there's an actual meaningful difference outside laboratory conditions and theory classes. Even if you play all the scale degree notes as a cluster chord, the bass player's IV note can make it perform the job of a IV chord to some extent. Can you post an example where these substitutions don't work, and instead spoil the whole _jazz_ tune?
Comment: @piiperi no, they don't spoil any tune.  I'm just saying that (for example) in C major, the chord that a jazz musician would call Fadd6 is a ii 6/5 chord in roman numeral analysis.
Answer: First of all the I IV V is also very common in Classical music, not just rock and other modern pop genres. It is a very old progression that I see in pre-classical era music.  From a chord substitution perspective the ii is (relatively speaking) the relative minor of the IV, as the iii is to the V, and the vi to the I.  So in a very real sense ii-7 --> V7 --> I is really identical to IV6 --> V7 --> I.  But they really do sound and feel different.  It seems that your question aims at the cultural difference not the technical difference.  Why is the ii-->V7-->I more prevalent in Jazz than elsewhere.  And I agree that it does seem that way.
I think if you search for it, you will find jazz tunes or standards that have I IV V and likewise rock tunes that use a version of the ii V7 I, but they'd be the exception, not the rule.  It helps to understand another progression called the circle progression.  One can walk in circles in any key by the following set of changes
Imaj7 --> IVmaj7 --> vii-7(b5) --> iii-7 --> vi-7 --> ii-7 --> V7 --> Imaj7
This is really a beautiful device and so many tunes of every genre can be seen to be embedded in this.  The most well known harmony "ending" to a musical line is the V7 --> I, which contains the movement 7-->8 and 4-->3 within the chords.  In classical music it is emphasized while other changes are not.  One thing you will see in Jazz more so than any other style of music is the creation of this ending or cadence with every change.  This is accomplished with a cycle extension, i.e. treating the chord you want to go to as a temporary I and inserting its relative V7 in there.  This is easy to do in the circle progression since every chord is the V of the next chord in the circle (except the IVmaj7 --> vii-7(b5)).  All other extensions of the cycle are borrowed from the circle progression.
When I was younger I learned the iii --> vi --> ii --> V --> I, before the ii --> V --> I.  My teacher thought that progression was more important and that the ii --> V --> I was a truncated version of it.  You can see it is just a truncated circle.
Ultimately western harmony favors the V7 --> I.  Since the ii chord is the V of the V chord the movement is more conducive to creating a cadence to the V.  This is, in my opinion, a sound that is favored in Jazz and I have heard people colloquially refer to it as hyper-resolution.  Not sure that's a real music theory term or just street jargon.  But in comparison to classical music you have several lines of music that may move from I to IV to vi to somewhere else and then finally when the musical idea is over there is a V7 --> I (the period at the end of the sentence).  In some sense Jazz has periods in almost every measure.  This creates the feel of tension and release.  Starting anywhere in the cycle you can create this resolution by modifying the chord to a dom7 chord (except the IV) and generate a cadence with the 7-->8 and 4-->3 movement.  A complete modified circle progression would look like
Imaj7 --> I7 --> IVmaj7 --> IV#dim --> vii-7(b5) --> VII7 --> iii-7 --> III7 --> vi-7 --> VI7 --> ii-7 --> II7 --> V --> V7 --> Imaj7.
The only odd one out is the IVmaj7 --> IV#dim --> vii-7(b5) since the IV is not the V of the vii.
This type of movement contains a lot of close interval movement and a lot of chromatic lines.  In contrast the IV --> V change, while perfectly nice and allowed in classical harmony, does not immediately offer the opportunity to resolve to the V in the same way that the circle does.  Again, constant resolution is not a requirement in western music but that sound represents a type of "climax" and is often considered the most interesting part of a musical idea.  It is often described as a musical representation of releasing tension.  Melodic ideas are moved around and may "meander" (not to disparage classical ideas).  To me it seems that jazz evolved to be constant tension-->release.  There may be other takes on this.
Answer: Possibly misinterpreting the question here!
The first five categories are more mainstream, generally speaking, and tend to use the primary harmonies, which are easy to follow, easy to play, and easy on the ear.
Jazz doesn't merely use ii V I. That's a simplification. Patterns tend to be more complex ('sophisticated' if you like!) and use more chord changes. There is that tendency to use more V>I sort of changes, so simple ii V I - Dm G C may become a little more - Dm Dm7 G G7 Cmaj7. Or more complex - Em Am Dm G C, going through the circle of 4ths/5ths. Anywhere in there there's the 2-5-1 change pattern.
Comment: @Dekkadeci, I wouldn't call it abuse.  Have you studied the Coltrane cycle?
Comment: I've heard that Giant Steps jazz patterns abuse ii-V-I in various, somewhat distant keys in the same piece.
Comment: Or D-7 --> D7 --> G --> G7 --> C to create a cadence to the V.
Answer: Jazz uses more varied chords, substitute chords, altered chords, modulations, modal interchange and all sorts of harmonic tricks, just like it uses more varied rhythms and rhythmic tricks. It feels nicer if music isn't too obvious, and if it tickles deeper layers of understanding. Some people feel that it's intriguing when art isn't completely self-evident, and doesn't blurt out everything too directly and explicitly. Some people don't get subtle and complex hints, they need simpler forms of expression. Like JAMES BOND GOOD GUY. DANGER. SHOOT BAD GUY. BANG BANG. PRETTY GIRL. THE END. Big letters, short sentences, black and white. Not jazz.
ii-V-I is not particularly jazzy or complicated, but it adds a tiny bit of variety compared to just IV-V-I.
Answer: The I-IV-V progression is just in "twelve bar blues"; that doesn't represent all of blues. Blues cannot be separated from jazz.
The actual progression goes like this, among other possilities (each bar is 4 beats):
<code>I | I | I | I | IV | IV | I | I | V | IV | I | V
                                |<--      -->|  <- Blues turnaround
</code>
(Here we don't actually see a I-IV-V literally at all! We do hear that in some classic pop rock songs like for instance "Do You Love Me (Now That I Can Dance)" by The Contours.)
The dominant at the very end leaves the tension hanging, and resolves to another tonic: the start of the next twelve bars, or else the end of the tune.
In other words, there is a V-I resolution in there, just not preceded by II.
The II-V-I pattern can be substituted into the twelve bar blues. See the Basic jazz-blues progression which is an altered twelve bar blues. The last four bars are:
<code> Original:  | V   | IV | I        | V      |
 New:       | ii7 | V7 | iii7 VI7 | II7 V7 |
</code>
First there is a slow II-V, four beats each, which doesn't resolve to a tonic. It's a kind of deceptive foreshadowing of the end. Then the pace picks up and we get the iii7 VI7 at two beats each, and a quick II7-V7 (which will go to a I7 in the next round again).
From this you can see how the II-V has been snuck into the jazzed-up blues pattern; where it fits in. The final V is in the same spot, as is the ending I in the next round. However, the time of the V has been cut in half down to two beats, and the II was inserted into the space before it.
Comment: I thought that sequence was I vi IV V, very common on the 60s. It hasn't shown in the box!

ii-V-I versus I-IV-V


Comparing class in swift

Question: I would like to check in swift whether an object is a member of a specific class.
However the class is stored as property of an another object, in this case RKRequestDescriptor, a class of the RESTKit framework. RKRequestDescriptor has a property defined, which stores a class object in its objectClass property.
So in objective-c I have something like:
  for (RKRequestDescriptor *thisDescr in self.requestDescriptors) {
    if ([thisDescr objectClass] == [obj class]) {
        ...

where "obj" is some arbitrary object to test against and since this is a subclass of RESTKits RKObjectManager, there is an array with requestDescriptors.
Now I am having a hard time in swift to "translate" the above objective-c code. I tried:
     for var thisDescr:RKRequestDescriptor in self.requestDescriptors {
        if let newObj = obj as thisDescr.objectClass {

That doesn't work. Xcode throws errors. To begin with it doesn't "like" in-the loop ("expected condition in for statement). So it to:
    var thisDescr:RKRequestDescriptor?
    for index in 0..<countElements(self.requestDescriptors) {
        thisDescr = self.requestDescriptors[index] as? RKRequestDescriptor
        if let newObj:AnyObject = obj as? thisDescr.objectClass {

but still no luck. It is really harder than I thought to "translate" objective c to swift :-(
Comment: http://stackoverflow.com/questions/24101450/how-do-you-find-out-the-type-of-an-object-in-swift
Comment: thank you, but I had seen that SO question, but it didn't help me, as I want to compare to an arbitrary class, which is stored in a variable. Or am overlooking something?
Comment: It is not "hard" to translate Objective-C to Swift at all. In fact, a machine could do it. It is pure application of simple rules. But you do have to speak in Swift syntax; you can't just say any old nonsense you like.
Comment: Oh, that's good news. So such a machine will be 'round the corner soon, if that's feasible. You should think about coming up with one yourself then. Might even be a good business idea.
Comment: I have in fact suggested this to Apple. In a sense Apple is doing it in part (that is, after all, what the Swift headers are). They are much of the way there already! There's no money to be made with it, but it would make a useful utility, similar to the other Edit > Refactor functionality that Xcode already has.
Comment: It might help to get used to the syntax. But yes, probably no money to make with it, as it isn't really necessary technically, only helps for learning purposes.
Comment: I've translated thousands of lines of my own code from Objective-C to Swift, and believe me, I could tell that a machine could have done it! I was just a coding monkey. Worse than a monkey. A coding amoeba.
Comment: That gives me hope :-) I have just started the job of translating parts of my code, as I want to move forward and not stick to an "old" language and the clients also are starting to request swift code. ...but then again, I learned Latin as well, which qualifies as old language... ;-)
Comment: I know Latin and Ancient Greek, and believe me, translating Objective-C is easier! :)
Answer: Swift equivalent of [thisDescr objectClass] == [obj class] is:
thisDescr.objectClass === obj.dynamicType

Comment: thanks, that works like a champ. As for the other problem with the loop, I figured out, that it works, if I leave out the "var" keyword. It makes sense, as swift will implicitly treat it as a variable in a for..in loop.
Comment: @alexdafranca Yup, that's what I was referring to when I said "speak in Swift syntax".
Comment: @matt Yes, of course I need to get used to the syntax. Unfortunately at the moment that is much of time consuming "try and error", as things like these are not immediately "logical" to me. Until now all other places, where swift is implicit and tries to be smart in order to save us keystrokes (and typos or especially: errors!)
Comment: @alexdafranca Apple's documentation is _excellent_ and very complete, and states clearly and simply what the syntax for `for...in` is.
Comment: (...ups, that return key again, sorry) ...in those areas it usually is allowed to be explicit. So if the thing is meant to be a "var" I can omit it, but I am used to be able to write it nonetheless, for what reason ever (readability etc.). But in this case the compiler complains with an unhelpful error message ("Expected '{' in for statement").
Comment: File a bug with Apple about the unhelpful error message! (If you have time.) This is a major problem with Swift; the error messages are very opaque, and often cause you to look in the wrong place for the source of the issue.

Comparing class in swift


Volume form on $S^n$ is $SO(n+1)$ - invariant

Question: For $a=(a_1, \cdots, a_{n+1})\in S^n$, and $v_i=(v_{i,1}, \cdots, v_{i,n+1}) \in T_aS^n, \ 1 \leq i \leq n$. We define the volume form $\omega$ as $$\omega(a)(v_1,\cdots,v_n)=\det \begin{pmatrix}a_1&\dots & a_{n+1}\\v_{1,1}&\dots & v_{1,n+1} \\ \vdots &  & \vdots\\v_{n,1}&\dots & v_{n,n+1}\end{pmatrix}$$
How do I show that this volume from is $SO(n+1)$ - invariant?
Differential geometry isn't my forté, so if I could get some idea on what techniques to employ to arrive at an answer, I'll be obliged. Any small hints/nudges are much appreciated.
Comment: You're basically computing the Jacobian of the map $x \to gx$ for $g\in SO(n+1)$.
Comment: Use the fact that the derivative of a linear map $x \to gx$ is just $g$ itself.
Comment: I'm sorry, I don't follow. Would you elaborate a bit?
Comment: Though it's already given that $\omega$ is a volume form, I'm trying to prove it. Any hints on how I can proceed?
Answer: We have: $g^*\omega_a(V_1,...,V_n)=det(g(a),g(V_1),...,g(V_n))=det(g)det(a,V_1,...,V_n)$, use the fact that $det(g)=1$.


Fast ways to subset categorical data in R with multiple conditions

Question: I have a large dataset in R (say >40,000 rows and >20 categorical columns) that I repeatedly subset, so I would like to speed this up as much as possible. It needs to be a general function (each categorical column has a discrete number of possible values, say in string format).
Each time I subset, I need to identify the subset of rows that satisfy multiple logical set membership conditions (e.g. >10 conditions). I.e., I need to check several columns and check if values in that column match a certain set membership (hence the use of %in%).
# simple dataset example
library(dplyr)
num_col <- 15
num_row <- 100000
dat_list <- list()
for (i in 1:num_col) {
  dat_list[[i]] <- data_frame(sample(letters[1:10], size = num_row, r = T))
}
dat <- bind_cols(dat_list)
names(dat) <- paste0("col", seq(15))

I've looked around the internet and SO a lot, but haven't found the discussion of performance I'm looking for. I mostly code using dplyr, so apologies if there's a clear performance improvement here in data.table; I've tried some simple benchmarks between the two (but without using any data.table indexing or etc.) and it's not obvious if one is faster.
Example options I've considered (since I'm not great at data.table, I've excluded data.table options from here):
base_filter <- function(dat) {
  for (i in 1:7) {
    col_name <- paste0('col', i)
    dat <- dat[dat[[col_name]] %in% sample(letters[1:10], size = 4), ]
  }
  dat
}
dplyr_filter1 <- function(dat) {
  for (i in 1:7) {
    col_name <- paste0('col', i)
    dat <- filter_(dat,
                   .dots = interp(~ colname %in% vals,
                          colname = as.name(col_name),
                          vals = sample(letters[1:10], size = 4)))
  }
  dat
}
dplyr_filter2 <- function(dat) {
  dots_filter <- list()
  for (i in 1:7) {
    col_name <- paste0('col', i)
    dots_filter[[i]] <- interp(~ colname %in% vals,
                               colname = as.name(col_name),
                               vals = sample(letters[1:10], size = 4))
  }
  filter_(dat, .dots = dots_filter)
}

Note: In practice, on my real datasets, dplyr_filter2 actually works fastest. I've also tried dtplyr or converting my data to a data.table, but this seems slower than without.
Note: On the other hand, in practice, the base R function outperforms the dplyr examples when data has fewer rows and fewer columns (perhaps due to copying speed?).
Thus, I'd like to ask SO what the general, most efficient way(s) to subset a categorical dataframe under multiple (set membership) conditions is. And if possible, explain the mechanics for why? Does this answer differ for smaller datasets? Does it depend on copying time or search time?
Useful related links

fast lookup for one key
using hash tables in R for key-value pairs
Comment: Why are you using sample()? It seems like that is going to impact your benchmarking.
Answer: Understand that you prefer not to use data.table. Just providing some timings for reference below. With indexing, subsetting can be performed much faster and  inner join of the 2 tables can also be done easily in data.table.
# simple dataset example
library(dplyr)
library(lazyeval)
set.seed(0L)
num_col <- 15
num_row <- 100000
dat_list <- list()
for (i in 1:num_col) {
    dat_list[[i]] <- data_frame(sample(letters[1:10], size = num_row, r = T))
}
dat <- bind_cols(dat_list)
names(dat) <- paste0("col", seq(15))

selection <- lapply(1:7, function(n) sample(letters[1:10], size = 4))

base_filter <- function(df) {
    for (i in 1:7) {
        col_name <- paste0('col', i)
        df <- df[df[[col_name]] %in% selection[[i]], ]
    }
    df
}

dplyr_filter1 <- function(df) {
    for (i in 1:7) {
        col_name <- paste0('col', i)
        df <- filter_(df,
            .dots = interp(~ colname %in% vals,
                colname = as.name(col_name),
                vals = selection[[i]]))
    }
    df
}

dplyr_filter2 <- function(df) {
    dots_filter <- list()
    for (i in 1:7) {
        col_name <- paste0('col', i)
        dots_filter[[i]] <- interp(~ colname %in% vals,
            colname = as.name(col_name),
            vals = selection[[i]])
    }
    filter_(df, .dots = dots_filter)
}

library(data.table)

#convert data.frame into data.table
dt <- data.table(dat, key=names(dat)[1:7])

#create the sets of selection
dtSelection <- data.table(expand.grid(selection, stringsAsFactors=FALSE))

library(microbenchmark)
microbenchmark(
    base_filter(dat),
    dplyr_filter1(dat),
    dplyr_filter2(dat),
    dt[dtSelection, nomatch=0],   #perform inner join between dataset and selection
    times=5L)

#Unit: milliseconds
#                         expr       min        lq      mean    median        uq       max neval
#             base_filter(dat) 27.084801 27.870702 35.849261 32.045900 32.872601 59.372301     5
#           dplyr_filter1(dat) 23.130100 24.114301 26.922081 24.860701 29.804301 32.701002     5
#           dplyr_filter2(dat) 29.641101 30.686002 32.363681 31.103000 31.884701 38.503601     5
# dt[dtSelection, nomatch = 0]  3.626001  3.646201  3.829341  3.686601  3.687001  4.500901     5

Comment: With > 20 columns, wouldn't the "dtSelection" object be too large to fit in memory (`nrow(dtSelection) == prod(lengths(selection))`)?
Comment: @alexis_laz yes very possibly depending on usage
Answer: In addition to chinsoon12's alternatives, one thing to consider is to avoid subsetting the data.frame in each iteration. So, instead of
f0 = function(x, cond)
{
    for(j in seq_along(x)) x = x[x[[j]] %in% cond[[j]], ]
    return(x)
}

one alternative is to accumulate a logical vector of whether to include each row in the final subset:
f1 = function(x, cond)
{
    i = rep_len(TRUE, nrow(x))
    for(j in seq_along(x)) i = i & (x[[j]] %in% cond[[j]])
    return(x[i, ])
}

or, another alternative, is to iteratively reduce the amount of comparisons, but by reducing the row indices instead of the data.frame itself:
f2 = function(x, cond)
{
    i = 1:nrow(x)
    for(j in seq_along(x)) i = i[x[[j]][i] %in% cond[[j]]]
    return(x[i, ])
}

And a comparison with data:
set.seed(1821)
dat = as.data.frame(replicate(30, sample(c(letters, LETTERS), 5e5, TRUE), FALSE),
                    stringsAsFactors = FALSE)
conds = replicate(ncol(dat), sample(c(letters, LETTERS), 48), FALSE)

system.time({ ans0 = f0(dat, conds) })
#   user  system elapsed
#   3.44    0.28    3.86
system.time({ ans1 = f1(dat, conds) })
#   user  system elapsed
#   0.66    0.01    0.68
system.time({ ans2 = f2(dat, conds) })
#   user  system elapsed
#   0.34    0.01    0.39

identical(ans0, ans1)
#[1] TRUE
identical(ans1, ans2)
#[1] TRUE


How can I create an executable uber jar for spring boot with gradle?

Question: I'm aware that with the traditional "gradle build" command I can create what Spring boot calls an "executable jar".
This jar contains all the jar dependencies needed inside the jar's lib folder.
What I need is that, instead of copying the dependency jars inside the lib folder inside the executable jar, I want a full blown uber jar, that instead of having its dependencies as jars inside a lib folder, I need them extracted as packages/classes.
I already tried the shadow plugin to no avail, and I see nowhere how to create an uber jar, actually most Spring users and the documentation tend to mix in the uber jar term with the executable jar, so it's hard to get developers to understand that they are different packaging strategies even though the result tends to function the same way when running the java -jar command.
Comment: I am curious why you would want to do that?
Comment: There is some OSGi stuff I use with Spring, and as Spring deprecated OSGi support since DM was killed, the only way to use it is to explode the jars and limit its use to the declared bundle. Also, I know how to expand jars using Maven but I've never done this with Gradle, I can't get it to work, even if using the shadow plugin
Answer: See the shadow gradle plugin, it does what you want
Comment: Hi Lance, like I mentioned, I already tried to use the shadow plugin but doesn't work, maybe there's something special I need to add so it works correctly but I don't know what.
Currently the shadow plugin only expands the core spring boot jar, but leaves other jars in the lib folder and I don't know why.
Do you have any working example what could make it work?


Why am I getting a syntax error on the first line of this code?

Question: I cannot understand what the syntax error is.
application(environ,start_response):
    status = '200 OK'
    html = '\n' \
           '\n' \
           ' Hooray, mod_wsgi is working\n' \
           '\n' \
           '\n'
    response_header = [('Content-type','text/html')]
    start_response(status,response_header)
    return [html]

  File "test_wsgi_script.py", line 1    application(environ,start_response):
                                       ^
SyntaxError: invalid syntax
(scripts) root@django:/var/www/scripts#

Comment: ... What do you think the line of code should mean?
Comment: I didnt know, which is why I posted here.
Answer: Do need def in front of the function call?
def application(environ,start_response):

Comment: It appears that, not knowing the fundamentals of the language well enough to spot an error this simple, you copied and pasted code from a tutorial and expected it to work. I assume the tutorial writer's psychology was similar.
Comment: That solved it. I don't understand why people post tutorials without testing thrm.