finding roots of polynomial equation with Taylor series

Question: I have the following equation which is obtained by the characteristic equation of a matrix:
$$
(-1-\lambda)^N +  c \sum_{i=1}^N (-1)^{i+1} (-1-\lambda)^{N-i} \beta_i = 0
$$
$N$ is the size of the matrix. And $\beta_i$ comes from an exponential kernel which I can choose another type of kernel if I want. let's simplify the equation by changing the variable $(-1-\lambda = x)$.
$$
x^N + c \sum_{i=1}^N (-1)^{i+1} x^{N-i} \beta_i.
$$
I know this equation is very complicated and most probably I should use numerical methods to find the roots which are my eigenvalues.
But out of curiosity, say we can choose a kernel $\beta_i$ such that we can create some sort of coefficients that lead to an expanded Taylor series of a know function. Then is the problem approachable? I wonder what you think of this and if you have seen something similar?
Or an equivalent question is whether there's a way to write the above equation in the form of:
$$
x^N + c\sum_{i=1}^N (-i)^{i+1} \frac{x^{N-i}}{\beta_i^\prime !} =0
$$
update:
I solved this equation numerically and surprisingly found out that for an exponential kernel, the roots lie on a circle of radius 1 in the complex domain. The result is invariant to the change of N and $\tau$. There's one negative eigenvalue close to -3 which is changing if I change the coefficient $\eta$ in the exponential kernel formula:
$$
\beta = \eta e^{-t/\tau}
$$
Figure right is an exponential kernel but bouncing between $-\beta$ and $\beta$ because of the $(-1)^{i+1}$ term in my equations. and on the left is the roots of the second equation.
Comment: Depends on how much control you have over $\beta_i$ I guess. If they can be anything, then sure. If not, you might be out of luck
Comment: "*the roots lie on a circle of radius 1*" $\,$ That is a strong relation, but it's hard to guess why without knowing what the $\,\beta_i\,$ actually are.
Comment: In this case, I know what are the $\beta$s. I'm getting each $\beta_i$ from an exponential function. but then changing the even one's sign because of the formulation.
$$
\sum_{i=1}^N a_i x^{N-i}, \\
a_i = (-1)^{i+1} \beta_i, \\
\beta_i = \eta e^{-i/\tau}
$$
where $\eta$ and $\tau$ are two constants.
Comment: You're right. I added a figure to this question that shows the roots of the equation for a particular exponential kernel. I think it might give you some insights.
Answer: With $\,\beta_i = \eta e^{−i/\tau}\,$ per OP's comment, let $\,n = N\,$, $\,\mu = c \eta\,$, $\,\alpha = -e^{-1/\tau}\,$, $\,z = \dfrac{x}{\alpha}\,$, then $\,\beta_i = (-1)^i \eta \alpha^i\,$ and the equation can be rewritten as:
$$
\begin{align}
x^N + c \sum_{i=1}^N (-1)^{i+1} x^{N-i} \beta_i &= x^n + c \sum_{i=1}^n (-1)^{i+1} x^{n-i} \cdot  (-1)^i\eta \alpha^i
\\ &= x^n - c \eta \sum_{i=1}^n x^{n-i} \alpha^i
\\ &= x^n - \mu \alpha \sum_{i=0}^{n-1} x^{n-i-1} \alpha^i
\end{align}
$$
If $\,x = \alpha\,$ the latter reduces to:
$$
\alpha^n - \mu \alpha \sum_{i=0}^{n-1} \alpha^{n-i-1} \alpha^i = \left(1 - n \mu\right)\alpha^n
$$
Therefore $\,x = \alpha\,$ is not a solution unless $\,n \mu = 1\,$, otherwise if $\,x \ne \alpha\,$:
$$
\begin{align}
x^n - \mu \alpha \sum_{i=0}^{n-1} x^{n-i-1} \alpha^i &= x^n - \mu\alpha \,\frac{x^n - \alpha^n}{x - \alpha}
\\ &= \frac{x^{n+1} - \alpha x^n -\mu\alpha x^n + \mu \alpha^{n+1}}{x - \alpha}
\\ &= \frac{x^{n+1} - \alpha(\mu + 1) x^n + \mu \alpha^{n+1}}{x - \alpha}
\\ &= \alpha^{n}\,\frac{z^{n+1} - (\mu + 1) z^n + \mu}{z - 1}
\end{align}
$$
It follows that the roots of the original equation are $\,x = \alpha z\,$ where $\,z \ne 1\,$ and:
$$
z^{n+1} - (\mu + 1) z^n + \mu = 0
$$

The "geometry" of the roots is dictated by the polynomial in $\,z\,$ i.e. by $\,\mu=c\eta\,$ alone. The "scale" of the roots is dictated by the $\,\alpha\,$ factor in $\,x = \alpha z\,$.

When $\,n\,$ is large and $\,|z| \gt 1\,$ the non-constant terms dominate, so it is expected that a root exists near $\,z^{n+1} - (\mu + 1) z^n \simeq 0\,$ $\,\iff z \simeq \mu+1\,$ $\,\iff x \simeq -(c \eta+1)e^{-1/\tau}\,$.

When $\,\mu\,$ is large the last two terms dominate, so it is expected that roots exist near $\,-(\mu + 1) z^n + \mu \simeq 0\,$ i.e. near the $\,n^{th}\,$ roots $\,z \simeq \left(\dfrac{\mu}{\mu+1}\right)^{1/n}\,$. In this case, the roots in $\,x\,$ will lie near the circle $\,|x| \simeq |\alpha|\left(\dfrac{\mu}{\mu+1}\right)^{1/n} = e^{-1/\tau} \left(\dfrac{c \eta}{c \eta + 1}\right)^{1/n}\,$.

The equation can be solved numerically, but there is no closed form solution for $\,n \ge 5\,$.

Incidentally, the same equation was discussed in Annual interest rate in amortized loan, though the focus there was on the real roots.
Comment: @NosratMohammadi Your RHS is not right, but other than that it's the [difference of powers](https://artofproblemsolving.com/wiki/index.php?title=Sum_and_difference_of_powers) identity:
$$
a^n - b^n = (a-b)(a^{n-1}+a^{n-2}b+a^{n-3}b^2 + \dots + ab^{n-2}+b^{n-1})
$$
$$
\iff\quad a^{n-1}+a^{n-2}b+a^{n-3}b^2 + \dots + ab^{n-2}+b^{n-1} = \frac{a^n-b^n}{a-b}
$$

With $\,a=1\,$ this can also be written as the sum of a geometric progression:
$$
1+b+b^2+\dots+b^{n-1} = \frac{1-b^n}{1-b}
$$
Comment: Oh right. This is very beautiful!
Thank you so much @dxiv.
Comment: Thank you @dxiv for the nice answer. I still couldn't figure out how you solved this part:
$$
\sum_{i=0}^{n-1} x^{n-i-1} \alpha^i = x^n - \mu\alpha \frac{x^n - \alpha^n}{x - \alpha}
$$
Can you guide me to a reference? Is it just a geometric series?


Best way for random (cluster) chord notation

Question: I'm working on a piano part where the player needs to slam their fingers on the keyboard in semi-specific regions to create random cluster-like chords. What do you think would be the best way to notate it? Should I write the exact chords played in the MIDI recording I'm transcribing (maybe with X noteheads)? Or should it be like the standard cluster notation (MuseScore's notation is bad and hardly implemented, this is only a mockup):
Comment: I think this is important: Do you want the players to slam black keys, white keys, or both?
Comment: This does make me wonder if anyone ever tried to score the opening of David Bowies's Let's Spend the Night Together ;)
Comment: @Dekkadeci I want the player to slam both keys, but to do this using their fingers and not forearms/hands. The player isn't supposed to hit every key in the region, but rather play a random 10-12 note "chord".
Answer: The top and bottom notes - which define the extent of the cluster - are usually shown more distinctly than in your mock-up. Black-note clusters are shown by a sharp or flat-sign; white-note ones by a natural-sign.
You mention 'semi-specific regions'. You could simply show the approximate register and approximate extent of each cluster and write "A piacere" or "libero".
But whether the notes are black or white makes a huge difference and should surely be indicated. You wouldn't want the performer banging away on just black notes: it would sound like a child playing.
Mixtures of black and white are simple: one hand or arm plays the white notes and the other the black notes.
Have you looked at Henry Cowell's music? This page has some useful stuff about his cluster-notation.
If it's for live performance remember to wear long sleeves. Some pianists wear gloves. For larger clusters you may need lengths of wood, which should be wrapped with something soft to protect the keys.
Comment: This (Henry Cowell's) notation is recommended by Elaine Gould in *Behind Bars*, page 326.
Comment: Thank you for your answer! I don't intend for the player to play every single note in the specified region, just wherever their fingers land naturally. The sound is supposed to be cacophonic, but not too dirty. Thanks for the link, I now understand the proper notation and "a piacere" & "libero" is something I definitely had in mind, but couldn't remember exactly.
Comment: @Aaron: Wow. If it has examples from all the composers she's worked with that book must be fascinating.
Comment: @GreatCorn: _My_ fingers wouldn't naturally land pointing up and down the keyboard, but you might get lucky! :-) I suppose you could just indicate the approximate _middle_ of each cluster and get the player to slap at that.
Comment: I like the idea of marking the middle. I would write them as ghost notes with a small description at the beginning to describe what they mean
Comment: Could be the way to go. You'd need to say something in your description about black and white notes though. Like, "Each cluster should contain a mixture of black and white notes".


How to include higher-level grouping into lmer model?

Question: I have a panel dataset and my dependent variable is the logit-transformed share of farm workers on long-term contracts. I am particularly interested in the effect of pastoral focus in agriculture, represented by variable pastoral. The difficulty is two-fold. First,  the impact of this variable changes over time. Second, the data for this variable is only available at a higher level of grouping, called RC. To deal with the first issue, I use a mixed model:
model <- lmer(logitshare ~ pastoral + other variables + (pastoral | year),
               data = mydata)

How can I deal with the second issue, i.e. include in the model the fact that pastoral is only available for RC?
Comment: What do you mean by a higher level of grouping? It would be important to determine how exactly the hierarchical structure works in this data before advising on a proper model.
Comment: Most of my data, including the dependent variable, is available for a small geographic area, a parish. However, I know the value of pastoral only for a much larger unit, a county. There are ~ 200 parishes per county.
Comment: Im also curious about what you mean by your DV being logit transformed. What is the reason for this transformation?
Comment: Originally it was a share of workers on long-term contracts. It is bounded between 0 and 1, and I transformed it to deal with this.
Comment: More clarification would be helpful. Is it the case that for each parish you have multiple years of data? And then you have an identifier for which RC the parish belonged to? How many RCs are in your data?
Comment: Yes, that's exactly the case. I have data for 8000 parishes, grouped into 40 registration counties (RC), for 5 years. The issue is that one important variable, pastoral, is only available at a county level, and I have to use the county value for all parishes in it. Could you help?
Comment: Why not use logistic regression instead of logit transforming the response? The logistic regression is a model for logit(EY) while you have E(logit(Y)) so perhaps that's the motivation? If you can the number of workers (long-term & short-term) there are other modeling options too.
Comment: I have two reasons. First, I do not want to move to a more sophisticated approach, which means more assumptions, when a simpler model can work. Second, logistic regression is designed for binary variables, whilst my variable is continuous.
Comment: @Mikhail could you add some of the information from the comments into the question. Based on the body text I had the impression that your problem was that pastoral is a nested variable which is only 'available' for some measurements but not all.
Comment: What does it mean to you when a model 'works'? Do you just want to make a fit (which works easily), or do you also want to estimate the accuracy of the fit (which requires a sophisticated approach if you want it to work *and* also be realistic)?
Comment: @SextusEmpiricus Sorry if my description was not clear. Imagine a map, in which the country is divided into 40 counties, and each county is in turn divided into 200 parishes. My response variable and most predictors are for 8,000 parishes, over 5 years. The exception is 'pastoral', defined as a ratio of pastoral land to all cultivated land. It varied by parish but was only measured by county, so that I have to assume the same value for all parishes inside.
Comment: @Mikhail could you add that in the question. In the comments it might remain unnoticed by some readers.
Comment: @SextusEmpiricus. My question is whether 'pastoral' had an impact. Now I can see that the coefficient is statistically significant, so the answer is 'yes'. However, I am concerned that this approach underestimates the variability of 'pastoral' which may effect this conclusion.
Comment: It's also relevant to know if pastoral varies over the five years for a given county. Does it?
Comment: Yes, it does. There are general trends that effect all counties, but these are subject to local variations too.
Comment: And as to the dependent, do you know the exact counts like 80 long-term out of a total of 200?  Or only the shares or percentages?
Comment: Yes, I have the counts.
Comment: That is better. I would then rather use a model for data binomial data instead of shares or percentages, for which you need the assumption that they normally distributed. Although with "large" counts the results could be very similar.
Comment: @BenP thank you for then I have two questions. First, what would be the dependent variable? Second, how will this resolve my issue with 'pastoral'?
Comment: @BenP just because it is counts doesn't mean that it needs to be binomial distributed. The assumption behind that is that the contract of every worker, whether it is long term or short term, depends on an independent Bernoulli variable. It creates a strict assumption about the relationship between variance and mean. It is questionable whether that is right.
Comment: @Sextus Empiricus Agree, binomial came up first because there is a given total number n from which k are drawn. A choice for extra binomial variance could be considered e.g. random parish effect.
Comment: @Mikhail the pastoral variable can influence the dependant but that can only be estimated on the county level. Sextus Empiricus clearly explained that this is problematic.
Comment: @mikhail the dependent can consist of two variables, nr. of long and nr. of short term contracts for each parish and year.
Answer: Normally, you should have time (year) at both levels like pastorale and the variable RC at the second level (clusters). Looking only on the question , something like the following code should yield the desired results.
model <- lmer(logitshare ~ pastoral + year + other variables +
                           (pastoral + year | RC), data = mydata)

This model assumes that pastoral and year have random slopes and intercepts.
Regarding the comments, random intercept and slopes will account for differential effects across RCi.
You can test this by sequentially testing models.
# No random effects
mod0 <- lm(logitshare ~ pastoral + year + other variables,
           data = mydata)

# Add random slopes
mod1 <- lmer(logitshare ~ pastoral + year + other variables +
                           (1 | RC), data = mydata)

# Add random slopes for year
mod2 <- lmer(logitshare ~ pastoral + year + other variables +
                           (1 + year | RC), data = mydata)

# Add random slopes for pastoral
mod3 <- lmer(logitshare ~ pastoral + year + other variables +
                           (1 + pastoral + year | RC), data = mydata)

which you can test with
anova(mod0, mod1, mod2, mod3)

to see which one fits your data the best.
Comment: Thank you very much! What is the intuition behind this formula, how could adding a random slope at the RC level help?
Comment: How do you know that this is the desired result? There hasn't been any explanation about the underlying principles of the model. Why aren't the parishes added as random effect? Can we assume that the different years within the same parish are all independent? How is the application of ANOVA working put well without being sure about underlying assumptions?
Answer: For the counts a few models might be compared. I assume that parishes are numbered from 1 to 8000 across all the counties.
1 Random county and parish effects.
model1 <- glmer(cbind(longt, shortt) ~ pastoral + year + (1|RC) + (1|parish), family=binomial, data=mydata)

2 Random year effects added. Maybe first only across counties, next also across parishes.
model2 <- glmer(cbind(longt, shortt) ~ pastoral + year + (1+year|RC) + (1+year|parish), family=binomial, data=mydata)

3 Random pastoral effect across counties. Only possible if pastoral changes over the years, given a county.
model3 <- glmer(cbind(longt, shortt) ~ pastoral + year + (1+year+pastoral|RC) + (1+year|parish), family=binomial, data=mydata)

These models assume that for a given parish/year observation, e.g. 80 longterm and 120 shortterm, all 200 workers have the same probability to be longterm. The models might improve by adding a random parish/year effect. E.g. for model1 you add:
  + (1|parish:year)

The exp() function of the fixed effects of pastoral and year are oddsratio's as usual for a logistic regression.
Comment: I typed on my mobile phone and this works terrible.
Comment: @mikhail I just realised that at the beginning of your question you said that the influence of pastoral varies over years. That could be modelled by adding the interaction of pastoral:year to the model. Forgot that.


Add a custom style to victory chart bar

Question: I want to create a custom bar chart with Victory like this:

How can I add a horizontal line in the graph every 10%?
This is my sample code:
const data = [
  { day: 1, data: 0 },
  { day: 2, data: 1 },
  { day: 3, data: 2 },
  { day: 4, data: 2 },
  { day: 5, data: 0 },
];

const BarChart = () => {
  return (
    <VictoryChart domainPadding={20} theme={VictoryTheme.material}>
      <VictoryAxis
        tickFormat={(x) => `${x.toFixed(0)}`}
        style={{
          grid: { stroke: "none" },
          ticks: { size: 0 },
        }}
      />
      <VictoryAxis
        dependentAxis
        tickFormat={(x) => `${x}`}
        style={{
          grid: { stroke: "none" },
          ticks: { size: 0 },
        }}
      />
      <VictoryStack>
        <VictoryBar data={data} style={{ data: { fill: '#379F4B' } }} x="day" y="data" />
      </VictoryStack>
    </VictoryChart>
  );
};

Answer: Have you tried to use tickValues? Example:
<VictoryAxis dependentAxis
  tickValues={[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]}
  ...other stuff...
/>

Comment: the problem is not the tick but line in the bar...please see edited image.

Add a custom style to victory chart bar


UdpClient Receive does not return until 2nd broadcast

Question: I think this is really weird. Tried to use UdpClient to synchronously receive broadcast msg, but it does not return although the broadcast has completed. Only on subsequent broadcast did I get the message. I think there's a bug somewhere within the framework?
clientListener.BeginReceive(new AsyncCallback(RxBcastCallback), clientListener);
//this is passed as AsyncCall.AsyncState in the callback

.....
UdpClient udpListener = (UdpClient)AsyncCall.AsyncState;

IPEndPoint remoteEndPt = new IPEndPoint(IPAddress.Any, 0);

byte[] inBuffer = udpListener.Receive(ref remoteEndPt);
//does not return until subsequent broadcast

thanks,
Kenny
Comment: Where does AsyncCall.AsyncState value come from?
Comment: It's from the same UdpClient object. clientListener.BeginReceive(new AsyncCallback(RxBcastCallback), clientListener);//this is passed as AsyncCall.AsyncState in the callback
Comment: Well, there's your answer. Your callback is receiving the first message asynchronously, and then your sync Receive call is receiving the second - in all likelyhood.
Answer: Your callback endpoint should probably be:
UdpClient udpListener = (UdpClient)AsyncCall.AsyncState;
IPEndPoint e = (IPEndPoint)((UdpState)(AsyncCall.AsyncState)).e;
byte[] inBuffer= udpListener.EndReceive(AsyncCall, ref e);

Comment: Yes Robin, you're right. Rather than calling Receive synchronously, I should call EndReceive. The API is really baffling (and it's easy to fall into a hole) Thanks - seems to work now.


How to find a files which names start with a certain amount of digits?

Question: I am trying to locate files by name, ones that start with at least three digits for example.
find . -type f -name [0-3]* will find files starting with numbers up to 3, but not with a string of three digits at the start of the name.
Anyone can shed some insight?
Answer: If you want 3 digits, you have to specify you want 3 characters between 0-9
find . -type f -name "[0-9][0-9][0-9]*"

Comment: Thank you very much! This worked beautifully exactly as needed!


Min/Max of $f_{n}(x)=\lim_{n\to\infty}\frac{(n^{x+1}+1^{x})(n^{x+1}+2^{x})\cdots(n^{x+1}+n^{x})}{(n^{x+1}-1^{x})(n^{x+1}-2^{x})\cdots(n^{x+1}-n^{x})}$

Question: Let's consider the function $f_{n}(x)$ with $x>0$ defined as:
$$f_{n}(x)=\lim_{n\to\infty}\frac{(n^{x+1}+1^{x})(n^{x+1}+2^{x})\cdots(n^{x+1}+n^{x})}{(n^{x+1}-1^{x})(n^{x+1}-2^{x})\cdots(n^{x+1}-n^{x})}$$
I'd like to know what is the way to follow such that I may find out for what values of $x$ the function reaches its minimum and maximum , and then to compute these  values. It's a
problem that came to my mind after studying another limit. However, I have more questions regarding this function, but for the moment it's enough if I find an answer for the part with minimum/maximum. Thanks.
Answer: First write
\begin{align*}
\log f_n(x) &= \sum_{j=1}^n \log(n^{x+1}+j^x) - \sum_{j=1}^n \log(n^{x+1}-j^x) \\
&= \sum_{j=1}^n \log\bigg( 1+\frac{j^x}{n^{x+1}} \bigg) + \sum_{j=1}^n \log\bigg( 1- \frac{j^x}{n^{x+1}} \bigg)^{-1}.
\end{align*}
The following inequalities are valid for all $0<y<\frac12$:
\begin{align*}
y-y^2 &< \log(1+y) < y \\
y &< \log(1-y)^{-1} < y+y^2
\end{align*}
Therefore when $n\ge2$,
\begin{align*}
\log f_n(x) &> \sum_{j=1}^n \bigg( \frac{j^x}{n^{x+1}} - \bigg( \frac{j^x}{n^{x+1}} \bigg)^2  \bigg) + \sum_{j=1}^n \frac{j^x}{n^{x+1}} \\
&> 2\sum_{j=1}^n \frac1n \bigg( \frac jn \bigg)^x - \sum_{j=1}^n \frac1{n^2} \\
&= 2\sum_{j=1}^n \frac1n \bigg( \frac jn \bigg)^x - \frac1n
\end{align*}
and
\begin{align*}
\log f_n(x) &< \sum_{j=1}^n \frac{j^x}{n^{x+1}} + \sum_{j=1}^n \bigg( \frac{j^x}{n^{x+1}} + \bigg( \frac{j^x}{n^{x+1}} \bigg)^2 \bigg) \\
&< 2\sum_{j=1}^n \frac1n \bigg( \frac jn \bigg)^x + \sum_{j=1}^n \frac1{n^2} \\
&= 2\sum_{j=1}^n \frac1n \bigg( \frac jn \bigg)^x + \frac1n.
\end{align*}
By the squeeze theorem,
$$
\lim_{n\to\infty} \log f_n(x) = 2 \lim_{n\to\infty} \sum_{j=1}^n \frac1n \bigg( \frac jn \bigg)^x = 2 \int_0^1 u^x\, du = \frac2{x+1},
$$
because the sum is a Riemann sum for the integral. In other words,
$\lim_{n\to\infty} f_n(x) = e^{2/(x+1)}$
for all $x>0$ (since exponentiation is continuous).
Comment: awesome. Thank you! (+1)


Display a link to create new content when content missing (via Contextual Filters)?

Question: I'd like to give users the option to create new content when a certain contextual filter is missing on a panel.
e.g. I have my reviews on a panel. When a review is missing I'd like it to display a block/link to submit a new review.
However my only options are to hide the view, give a summary etc.
How do I do this?
I've found the option for 'No Results Behaviour', but I can't hook into the contextual filter (and then use a relationship to grab a term name). I've also found this work around:
https://www.drupal.org/node/1895724
But I'm struggling to re-write the code to pull the term name out of the term id in the contextual filter.
Answer: Here I suppose you have added an argument in panel path. You can assign any context to your argument, eg Node: Id. It can be Term as well.

Assign any context to argument like :

Add a visibility rule if Context exists to your view and not exists to custom pane.
Comment: Sumit I don't really follow. I'm looking at this from the point of view of the ... View. Yes I have an argument from the panel, but I don't follow you after that. Did you read the [question](http://drupal.stackexchange.com/q/137984/39377) I linked?
Comment: So you're saying, "If the argument doesn't exist, skip calling the view", right? That _can_ work in some cases, but say you're checking, "has something been tagged with this term", then the term argument always exists, so this won't help. Do I understand that right?
Comment: Well thats correct @Letharion.. In the case you said `Views No Result` Behaviour will work. :)
Comment: @SumitMadan I may have been confusing this with another question I was looking at recently. Reading the question again it looks like this would be a good solution.
Comment: I don't think this works as I don't have a node id in that scope. I'm passing it as a value on a link from one view to the next. Does this still work?
Comment: @Pureferret Is the pointed to link also controlled by Panels? If so, it should work just fine.
Comment: So when I look on my context tab of the panel, I don't have any arguments set up there.Here's my config: http://imgur.com/a/hqw4q
Comment: Well It looks like you didn't setup argument in panel. Otherwise it should look between Basic and Access link under Settings.
Answer: I managed to work it out, I turned on the PHP Filtering module, and inserted this as a Global text area, with Text format = PHP Code
<?php
    $view = views_get_current_view(); //get the current view
    $term =  taxonomy_term_load( $view->args[0] ); // the term id
    $term_name = taxonomy_term_title($term); //get the term id e.g. turn 123 = term_name
?>

No comments exist for <?php print $term_name; ?>.
//print out the name

<a class="button" href="localhost/drupal/node/add/technology-comments?edit[field_technology][und][textfield]=<?php print $term_name; ?>">Add new comment
 //link to the add new page, pre-populating with term_name

Comment: Well if Its just about the Term Name in pane, I suggest you should create a ctool plugin rather than adding php code inside database.
Comment: Thanks, @SumitMadan I'll look into it. [This](http://drupal.stackexchange.com/q/33336/39377) looks like a good place to start?


How to get all running PODs on Kubernetes cluster

Question: This simple Node.js program works fine on local because it pulls the kubernetes config from my local /root/.kube/config file
const Client = require('kubernetes-client').Client;
const Config = require('kubernetes-client/backends/request').config;

const client = new K8sClient({ config: Config.fromKubeconfig(), version: '1.13' });

const pods = await client.api.v1.namespaces('xxxxx').pods.get({ qs: { labelSelector: 'application=test' } });
console.log('Pods: ', JSON.stringify(pods));

Now I want to run it as a Docker container on cluster and get all current cluster's running PODs (for same/current namespace). Now of course it fails:
Error:  { Error: ENOENT: no such file or directory, open '/root/.kube/config'

So how make it work when deployed as a Docker container to cluster?
This little service needs to scan all running PODs... Assume it doesn't need pull config data since it's already deployed.. So it needs to access PODs on current cluster
Answer: Couple of concepts to grab your head around first:

Service account
Role
Role binding

To perform you end goal (which if i understand correct): Containerize Node js application
Step 1: Put application in a container
Step 2: Create a deployment/statefulset/daemonset as per you requirement using the container created above in step 1
Explanation:
In step 2 above {by default} if you do not (explicitly) mention a serviceaccount (custom) then it will be the default account the credentials of which are mounted inside the container (by default) here
volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-xxxx
      readOnly: true

which can be verified by this command after (successful) pod creation
kubectl get pod -n {yournamespace(by default is default)} POD_NAME -o yaml
Now (Gotchas!!) if you cannot access the cluster with those credentials then depending on which service account you are using and the rights of that serviceaccount needs to be accessed. For example if you are using abc serviceaccount which does not have rolebinding to it then you will not be able to view the cluster. In that case you need to create (first) a role (to read pods) and a rolebinding (for that role) to the serviceaccount.

UPDATE:The problem got resolved by changing Config.fromKubeconfig() to Config.getInCluster() Ref
Clarification: fromKubeconfig() function is good if you are running your application on a node which is a part of kubernetes cluster and has cluster accessing token saved here: /$USER/.kube/config but if you want to run the nodeJS appilcation in a container in a pod then you need this Config.getInCluster() to load the token.
if you are nosy enough then check the comments of this answer! :P
Note: here the nodejs library in discussion is this
Comment: Do you mean no code change needed then? (See app code in my question)
Comment: Can you tell me which client library you are using? is it any one of them from this list ?
1. github.com/tenxcloud/node-kubernetes-client
2. github.com/godaddy/kubernetes-client
3. github.com/ajpauwels/easy-k8s
Comment: It is kubernetes-client as you can see in my code above.. Here is the repo:
https://github.com/godaddy/kubernetes-client.. So I want to deploy my Node app which will scan all running pods on that cluster/namespace then e.g. access static files http:///public/read.me
Comment: @JohnGlabb after some digging in https://github.com/godaddy/kubernetes-client/blob/master/backends/request/config.js#L33 i think you will have to change one line of code Config.fromKubeconfig() to Config.getInCluster()


When checking out, redirected to front page and not payment page

Question: I am creating a new order, and line item (without a product, since this is just a fee we're collecting from the customer).  The order is created, with line item, but when I go to /checkout/[order_id], I'm just redirected to the front page.
My code for the order creation is:
<code>function mymod_form_submit($form, &$form_state) {
        global $user;
        $order = commerce_order_new($user->uid, 'checkout_checkout');
        commerce_order_save($order);
ddl($order);

        $line_item = commerce_line_item_new('app_fee_type', $order->order_id);
        $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);

        $line_item_wrapper->line_item_label = t('Application Fee');
        $line_item_wrapper->quantity = 1;
        $line_item_wrapper->commerce_unit_price->amount = 3500;
        $line_item_wrapper->commerce_unit_price->currency_code = 'USD';
        $line_item_wrapper->commerce_total->amount = 0;
        $line_item_wrapper->commerce_unit_price->data = commerce_price_component_add(
                $line_item_wrapper->commerce_unit_price->value(),
                'base_price',
                $line_item_wrapper->commerce_unit_price->value(),
                TRUE,
                FALSE
        );
        commerce_line_item_save($line_item);

ddl($line_item);

        $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
        $order_wrapper->commerce_line_items[] = $line_item;
        commerce_order_save($order);
ddl($order);
        commerce_order_status_update($order, 'checkout_payment');
        drupal_goto('checkout/' . $order->order_id);
}
</code>
The customer should just be taken to the checkout screen.  What am I missing?
Answer: It looks like the order ID isn't being saved for the session.  Add this:
<code>$_SESSION['commerce_cart_orders'][] = $order->order_id;
</code>
Just make sure you do this before you save the final version of your order.


What is the best way to prevent visitors from accessing website in development?

Question: What is the best way to prevent visitors from accessing a website in development stage? Something in the lines of a 'whitelist'.
In my particular case I am using WordPress as the platform for creating this website. I searched for plugins but didn't find anything specific for it. I have a local server to develop the website however, there are a few functionalities that I need it to be on the live server.
Answer: Since you are using WordPress, the plugin Restricted Site Access should be adequate.

Once installed go to Settings -> Reading
Near the bottom of the page there is an option called "Site Visibility" change the option to: " Restrict site access to visitors who are logged in or allowed by IP address"
There are now two new options called "Handle restricted visitors" and "Unrestricted IP addresses"
The first option will allow you to :

Send them to the WordPress login screen
Redirect them to a specified web address
Show them a simple message
Show them a specific WordPress page I've created (this is a good option for a splash page!)

The second option will allow you choose which IP address(es) to whitelist to view the website without needing to login or be redirect to the page/website you specified in the first option.
Comment: All answers are a good solution, but I will vote for this one because I am using WordPress and the plugin suggested works perfectly! Thank you all for your solutions. Great work!
Comment: @umagrama No problem, feel free to make the answer as correct so others will know which solution you used and it might help them as well
Answer: Using  basic authentication with htpasswd (assuming you are in an Apache server).
Do it in 2 minutes:

Generate a .htpasswd file
Uplaod the file to the root of your WordPress installation
Comment: yes, of course, duh. Thanks for pointing me in the right direction. ;)
Answer: "Best way" is going to be dictated by the logic of what you're doing. Is the secret the functionality, the content, or related to your brand or service? Probably, it's related to the brand (most obvious reason). You don't want a public mess associated with the brand, but the fact a mess exists somewhere on the internet isn't of particular concern.
Here is what I do: Register another domain and work live there. You could even use a random string of letters like "serverasdfxyz123.com". If you don't put up searchable content, I don't see how anyone who wasn't super dedicated could find it. This also forces you to have the discipline to make your code portable to another domain. Do it twice. Go from staging server 1, to staging server 2, then to your deploy.
Answer: White List for Additional WordPress Site Pages for plugin Restricted Site Access
It seems like I can allow users to get to the registration page as my default redirect, and they could register or login.
The trouble is when the registration sends them an email with a validation link, the WordPress Activation email provides a link to the "Activate" page.
e.g.
http://www.rosemansolutions.com/wordpress/activate/4WWEDW2oxhRvW69INJi2DSgQFockI49R/
Any way I can add additional WordPress pages to the "White" list, as we can do for IP Addresses? I'm willing to pay for it :-)


Calling Module function from jQuery and Ajax

Question: With every drupal site I make, I usually create a custom module that I use to hold different php functions and other things custom to the site I am working on. It usually only consists of a module_name.module and module_name.info. Additionally, I always have .js file in the theme to do any javascripts I might need. Pretty standard right? But I have now run into a situation where I need the two to talk to one another.
I know you can call a .php file and pass it data using .ajax in jquery. How would I envoke a function written in my custom module from the js file in my theme?
Answer: Hopefully this will help -- got this code from a Lullabot module development training.
It all revolves around a hook_menu callback.  The value in 'page callback' is the function that will be called, in this case it is: "menu_magic_page"
So Drupal looks for the menu_magic_page() function.
Your jQuery / AJAX call would then reference the value what's in $items['X'] where X is "magic" here.  So hitting http://example.com/magic would run the module function "menu_magic_page"
FWIW: the type/MENU_CALLBACK ensures it doesn't get added to menu's etc.  It just ensures Drupal is ready to process it.
Hope this helps.
<code>/**
 * Implements hook_menu().
 */
function menu_magic_menu() {
  $items = array();

  /**
   * This is a simple callback.
   *
   * This will create a path at http://example.com/magic. When visited, that
   * URL will trigger the "menu_magic_page" function.
   */

  $items['magic'] = array(
    'title' => 'Menu Magic!',
    'page callback' => 'menu_magic_page',
    'type' => MENU_CALLBACK,
  );

/**
 * Page callback for 'magic'. This is the function that will get called
 * everytime a user visits http://example.com/magic.
 */
function menu_magic_page() {
  global $user;
  return t('Hello, @username!', array('@username' => $user->name));
}
</code>
Comment: I am using this in ajax             $.ajax({
                url: 'magic',
                type: "GET",
                success: function (data) {
                    //Do something here with the "data"
                    alert(data);
                }
            }); which is actuly returning me the HTML in alert rather the user name being return by this functions. What am I doing wrong?
Comment: Rather I see RETURN is not working in 'menu_magic_page' but print.


Change a number from database through php

Question: I am trying to communicate with database MySQL and change a number from a certain cell-box. I have created some check boxes, and i want each time i check one of those to change the specific number in database.
I don't mind helping me in other, but i am not so good that's why.
I believe i want something like that but i haven't understand quite well his post.
Comment: This is WAY too broad. We're not going to whip up an entire js/ajax + php + sql system for you.
Comment: Perhaps you could be more specific about what your problem is. You don't know how to write the query? You don't know how to retrieve values from the form? How to plug values into the query? You think you know how but you're getting error messages that you don't understand? If you don't know how to do any of this, then I think this is really the wrong place to be asking. You need to get a book or find a web site on "how to write php/mysql programs". I don't mean to be rude, but a forum like this is not a good place to get a complete class in how to write programs.
Comment: If you want people to help you, you have to give them something to work with.  Paste in what you are trying and any errors that you are getting so folks can help you troubleshoot.
Comment: I can't understand how to say to my database to change something in particular with code, not just connect that's where i am stuck
Comment: I am not asking that, sorry for the misunderstanding, simply a 2 line code on how to refer to a specific row and line to my database
Comment: please include the two lines you have so far in your question and we can take a look.
Comment: Yeah you are right, and i think expressing your beliefs about something or someone despite being good or bad, if they are bound to help him you should do so, what i am saying is thank you for your time   writing that post and i was definitely not asking the right thing in that question. Anyway Quixrick helped me and i figured what i wanted out so sorry for the spam :P
Answer: Basically, you just connect to the database.  Write a query to do the work and then execute that query.
In this example, you have a variable named $checkbox_count which has the number you want to update the table with.  If it's not a number, put single quotes around it.
<?php

$link = mysqli_connect('DATABASE HOST', 'USERNAME', 'PASSWORD', 'DATABASE');

$query = "UPDATE table SET Checkbox_Count = $checkbox_count WHERE Id = 1";
mysqli_query($link, $query) or die('MySQL Error');


Flash Builder Output is Blank

Question: I am a Flash Builder 4 noobie here, and I began working on a simple application, to try out FB 4. However, I am having a problem.
When a compile and run the application, the output is entirely blank. The HTML wrapper page does contain the flash application, but the content is blank, even though I have a simple label component on the stage.
Also I noticed that when I right-click on the flash object, the default context menu appears, displaying the "Zoom In", "Zoom Out", "Show All", etc... options which are removed from the application by default.
If you are interested, here is my code, as easy as it gets. :)
<code><?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
           xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">

  <fx:Declarations>
    <!-- Place non-visual elements (e.g., services, value objects) here -->
  </fx:Declarations>

  <s:Label x="100" y="100" text="Hello World" fontWeight="bold" fontSize="18"/>
</s:Application>
</code>
I am running Flash Player 10.2. Can anyone help work out this issue?
Thank you for your time,
spryno724
Comment: erm, some code would be nice? are you sure it's building properly?  Do you have your 'build automatically' flag on?
Comment: No, I choose "Run" -> "Run __" option each time.
Answer: Although it would be difficult to be exact, I think I understand the issue.
I assume you are loading your swf file from local machine.(File: protocol). By default this behavior is considered a security violation and hence for development you need to use -use-network=false compiler setting. This will allow you to load your swf file from file system. You might want to remove this. once you are porting it to production.
Comment: more details on this stackoverflow thread,http://stackoverflow.com/questions/2198857/why-use-network-false
Comment: In anticipation of future data-centric applications I will build, I placed this experimental folder under the "htdocs" folder of my PHP server. Once I accessed via the server, it fired right up! Thanks for your time, doc_180!
Comment: btw, thanks for the follow-up link I could use read-up on this.

Flash Builder Output is Blank


How to implement whitelist firewall (every URL is blocked by default) using Squid?

Question: I'm struggling to implement whitelist firewall using Squid. Every URL (not SNI) should be blocked unless it is explicitly added to the whitelist (acl url_regex).
Squid is working in the intercept mode (traffic is redirected from VPN using iptables rules).
https_port 3129 intercept ssl-bump \
    cert=/usr/local/squid/ssl_cert/myCA.pem \
    generate-host-certificates=on dynamic_cert_mem_cache_size=4MB

I can block all requests using http_access directive:
http_access deny all

but If I try to allow certain URLs, it does not work (every request is blocked). From my understanding, it happens because I'm blocking all "fake" CONNECT (CONNECT ENDPOINT_IP:443) requests.
Please advise if it is possible to achieve what I want using the default Squid build or I have to use ICAP or something?
Answer: When I posted the question, I realized what my problem was. I needed to allow the CONNECT requests.
acl localnet src 10.0.0.0/8

acl CONNECT method CONNECT
http_access allow CONNECT localnet

solved the issue. The config is not meant to be perfect. I'm posting it just to demonstrate the idea.


MDX: Calculated Dimensions?

Question: I don't know if this is possible or not, or if my limited knowledge of MDX is pushing me in the wrong direction...
The cube I'm dealing with has two different dimensions for dates, [Statement Dates] and [Premium Dates].  Further in the hierarchy of each looks like this:
[Statement Dates].[Statement Year].[2008]
[Payment Dates].[Payment Year].[2008]

For the business logic I'm implementing I need to do something like:
select
  ({ [Measures].[Commission] }) on columns,
  ({[Products].[Product Category]}) on rows
from [Cube]
where
(
  IIF( [Products].[Product Category].CurrentMember.Name = "Some Category",
       [Statement Dates].[Statement Year].[2008],
       [Payment Dates].[Payment Year].[2008] )
)

So I need it to discriminate what dimension to use for filtering the year based on what product category is being used.
This parses ok and the query runs, but the numbers seem to suggest that the IIF statement is always returning false.
Answer: Because the WHERE clause gets evaluated first the .CurrentMember function in the IIF will only be seeing "All Product Cateogories". In which case the [Products].[Product Category].CurrentMember.Name will never be equal to "Some Category" as the only product category in context is "All Product Cateogories".
One possible work around would be to do a calculation like the following:
WITH MEMBER Measures.Commission2 as
SUM(
{[Products].[Product Category].[Product Category].Members}
, IIF( [Products].[Product Category].CurrentMember.Name = "Some Category"
   , ([Statement Dates].[Statement Year].[2008],[Measures].[Commission])
   , ([Payment Dates].[Payment Year].[2008].[Measures].[Commission]) )
)
select
   ({ [Measures].[Commission2] }) on columns
,  ({[Products].[Product Category]}) on rows
from [Cube]

You could also do a scoped assignement in the calculation script in your cube to do this sort of thing.

MDX: Calculated Dimensions?


Treatment vs control extrapolation of results

Question: Apologies in advance for any vagueness in the question. Please let me know if clarification is needed.
If a control group has a 33% payback rate on a loan, and an experiment finds that a treatment group had an 8% increase in probability to pay back a loan, can I simply do .33*.08 to extrapolate what the payback rate of a loan would potentially be in a treatment group?
Results were gathered using a probit regression. The study in question can be found here.
Answer: Table 3 reports probit index function coefficients, which are not particularly useful on their own. But it is easy enough to work out how they got the marginal effects and the predicated rates of repayment. Focusing on the first specification, it means that in this simple model,
$$\Pr(Repayment) = \Phi(-0.760)=0.22362729$$
if someone has the control experience.
If treated with the cash back, then this rises to $$\Pr(Repayment) = \Phi(-0.760 + 0.262)=0.30924202.$$
For the other two treatments, you would replace the second coefficient with the one corresponding to that treatment.
This means that about 3 out 10 repay with this treatment, versus about 2 out 10 in the baseline. The 0.085 is the difference between these two probabilities, which has the units of percentage points:
$$\Phi(-0.760 + 0.262) - \Phi(-0.760)=0.08561473.$$
It is not multiplicative, but an additive change in probability of repayment. Here $\Phi(.)$ is the standard normal CDF function.
Comment: Simple to understand and effective at explaining. Many thanks!
Comment: Would you know how to calculate the CDF function in R by chance?
Comment: @JonathanRauscher Try `pnorm()`.


Can you really pay attention to every single slur, trill, ornament, etc.?

Question: Debussy's Étude pour les agréments focuses on all those small symbols in a score that indicate some intent from the composer: accentuation marks, hairpins (crescendi, decrescendi), pizzicati, appoggiaturas, rest commas, etc.
Do you usually read all of them and memorize them along with the notes without skimming a single one?
Comment: Your choice of Debussy for starting this discussion strikes me as ironic. 1) Debussy had great respect for Bach, Couperin and Rameau who made liberal use of ornament signs, and this piece is among other things a tribute to them. 2) Debussy was also the kind of composer who carefully proofreads the copies of its published music (he edited himself several ancient composer works for his french publisher, Durand), and he added a lot of dynamic and agogic indications in his own piano music.
Comment: @ogerard : you misinterpret. I do not say nor suggest that ornaments are useless. I say that their quantity can sometimes be seen as a huge load and that the interpreter should maybe get the spirit of those ornaments rather than taking each one literally.
Comment: sorry, there is some risk to misinterpret naked text. Two composers for which I would take ornaments very literally would be Beethoven and Liszt. The trouble is that many of them in their works are placed in the middle of fast notes or with fingers already busy on hold notes. They require careful fingering and practice.
Comment: @ogerard: Probably you want to also include Schubert then.
Answer: Concerning ornaments (dynamic, expressive and tempo indications are a different case) I think you should try to look at them and train yourself to play them as they are written and by this I mean that you should train to

see them as very useful abbreviations, as composers do to write down their music faster
elements of style, that can be interpreted differently depending on the period, the instrument, your playing abilities
mnemonics that you can add or suppress at will at sight reading
elements of a language meant in certain case as tools for the virtuoso
know that their translation in term of precise music played by your fingers depends on the context. The speed of a turn or an ascent, and its proportion and position, especially for a long note is not always simple to decide. The decision to take into accounts preceding accidentals, check if some aspects of ornaments have been chosen by the editors.

So, you should be able to mentally say and execute: "I play this note with a turn, with a mordant, with a grupetto, ..." also look at a baroque piece with few or no ornaments and add some of them. In Bach French Suites and some of the editions of the Inventions, you can find ornamented and non-ornamented versions of some of the pieces. It is very profitable to look at them.
And if you plan to know really a piece, I would advise not to schedule their study to after you have already learnt the parts.
For staccato, and other toucher indications, this is something that I usually first study when I play the hands together. When I first try to play a piece, I use the most legato possible way as a first approach to fingering.
For tempo, volume and this kind of indication, I prefer not to memorize them first. I usually make a little sketch on paper or a mental map of where they are placed and I try to apply them in a second phase, marking places where I tend not to follow them, etc.  This is a phase where I usually need to have people listen to my playing (teacher, family, myself by recording, etc.)
Answer: As a general rule of thumb, you should be including these. I can think of two things you should always keep in mind with ornaments:
They often were not written by the composer:
They are many cases where they were not written by the composer, but rather by the editor. If this is the case, it probably means (assuming a good editor) that these ornaments were normal for the time. If that is the case, it is generally okay not to play some and maybe add some (Generally good to be conservative with this in auditions though). The way you can find this out is to look at an original manuscript reproduction (many music libraries in universities have these for major composers).
When you play them, don't let them effect your rhythm:
Ornaments when played well flow naturally and do not effect the underlying rhythm. So basically, when you play something through without ornaments, the fundamental rhythms should be the same when you then add them.
Answer: These are perhaps more important that the notes, in conveying what the composer wanted.
So definitely memorise them!
Comment: @Benoit I don't think anyone would explicitly memorize them to that level, but rather just get in the habit of playing it that way.  Playing without them would take *more* effort after a while.
Comment: Thank you for this answer. Does that mean that in your daily practice, you will know by heart the position of all these ornaments on a complete score?
Answer: Yes you can! That is as much part of the piece and everything else.
If something says pizzicato you should not use your bow to play it. You should memorize those specifications if and as much as you memorize the pitch and duration of each note.
A proper interpretation of a piece will try to take into account each and every information the composer included in the score. From pitch, rhythm, dynamics(volume, crescendo, decrescendo, forte, piano, etc.) to timbre (pizzicato and others) and sometimes there's even a metronome marking.
If the music you are performing is for your own enjoyment you are free to perform the music however you see fit and only to level you can reach technically, but keep in mind your audience. If you are auditioning for an orchestra for example, the jury will most likely expect the piece to be played as written.
Just keep in mind that while some of the markings are very specific like pitch (and even that depends on the tuning), a metronome marking (and even that one a conductor might decide to ignore if he feels the piece will sound better in a different way), others are more open to interpretation and are more relative like a forte or decrescendo.
Answer: As my father kept reminding me over and over: "There are no accidental pen strokes.  Beethoven put that there for a reason."  As you mention, those "small symbols...indicate some intent from the composer."  IMHO, you should respect that intent.
Comment: This is not really what I am asking. It is not about the should or shouldn't, it is about how you manage them, whether people here all usually read all of them carefully.


Estimating the dimension of a data set

Question: A colleague in applied statistics sent me this:

"I was wondering if you know any way
  to find out  the true dimension of the
  domain of a function.  For example, a
  circle is a one dimensional function
  in a two dimensional space. If I do
  not know how to draw,  is there a
  statistic that I can compute that
  tells me that  it is a one dimensional
  object in a two dimensional space?  I
  have to do this in high dimensional
  situations so cannot  draw pictures.
  Any help will be greatly appreciated."

The notion of dimension here is obviously ill-defined. I mean,
I could run a curve through any finite collection of points in
high dimensional space, and say that my data is one-dimensional.
But, depending on the configuration, there may be an easier or
more efficient way to describe the data as a higher dimensional set.
Such issues must have been considered in the statistics literature,
but I'm not familiar with it. Any pointers or suggestions? Thanks!
Answer: Principal Components Analysis of local data is a good point of departure.  We have to take some care, though, to distinguish local (intrinsic) from global (extrinsic) dimension.  In the example of points on a circle, the local dimension is 1, but overall the points within the circle lie in a 2D space.  To apply PCA to this, the trick is to localize: select one data point and extract only those that are close to it.  Apply PCA to this subset.  The number of large eigenvalues will suggest the intrinsic dimension.  Repeating this at other data points will indicate whether the data exhibit a constant intrinsic dimension throughout.  If so, each of the PCA results provides a partial atlas of the manifold.
Answer: See
Levina, E. and Bickel, P. (2004) "Maximum Likelihood Estimation of Intrinsic Dimension." Advances in Neural Information Processing Systems 17
http://books.nips.cc/papers/files/nips17/NIPS2004_0094.pdf
Their idea is that if the data are sampled from a smooth density in $R^m$ embedded in $R^p$ with $m < p$, then locally the number of data points in a small ball of radius $t$ behaves roughly like a poisson process.  The rate of the process is related to the volume of the ball which in turn is related to the intrinsic dimension.
Comment: +1 Nice find!  The paper also has a brief discussion of the PCA approach (as well as some other methods).
Comment: Thanks very much, I think that this is the closest to what my colleague was looking for.
Answer: I'm not sure about the 'domain of a function' part, but Hausdorff Dimension seems to answer this question. It has the odd property of agreeing with simple examples (e.g. the circle has Hausdorff Dimension 1), but of giving non-integral results for some sets ('fractals').
Comment: I'd even say [box-counting dimension](http://en.wikipedia.org/wiki/Box-counting_dimension) for a more practical statistic.
Answer: I highly recommend to read this survey:
Camastra, F. (2003). Data dimensionality estimation methods: a survey. Pattern recognition, 36(12), 2945-2954.
For performing this estimation, I found very good toolbox in matlab Matlab Toolbox for Dimensionality Reduction. In addition to the techniques for dimensionality reduction, the toolbox contains implementations of 6 techniques for intrinsic dimensionality estimation

Estimating the dimension of a data set


Calculating expected value when I don't know the function

Question:
You're given a randomizing function in which $x = 1$ with probability $0.1$,
  $x = 2$ with probability $0.3$ and $x = 3$ with $P=0.6$. Calculate the
  expected value.

So I know how to calculate the expected value of a function by using a definite integral over a given interval of $xf(x)$ Here, though, I don't have the information of what $f(x)$ even is (the formula, I mean). How to calculate it here, then?
Answer: No integrals required here since your randomizing function (or just random variable) is discrete. The expected value of a discrete random variable $X$ with probability function $p$, $p(x)=P(X=x)$, is simply given by
$$
{\rm E}[X]=\sum_{x: \,p(x)>0}xp(x).
$$
So to calculate the expected value just find $p(x)$ and insert in the formula above.


How to Retrieve array key values in Tcl

Question: Given Data
array set color {a red b green c blue}
set keylist [array names $color]
pointlist  {{1 2 3 4} {5 6 7 8} {9 10 11 12} {13 14 15 16}}

I get a new list after running a procedure.
 newlist  {b b b b}     # Note: length of newlist is same as length of pointlist

Question is : when i run a loop these values of b should be substituted, for example in this green.
for {set i 0} { $i < [llength $pointlist]} {incr i } {
    lassign [lindex $pointlist $i] x1 y1 x2 y2
    APICommand -points "$x1,$y1,$x2,$y2" -color $color($keylist)
}

Now this $color($keylist) is not getting me correct result and errors out saying :
can't read "color(red blue green)": no such element in array
Instead I want the first set of 4 points to get the green color which is the value of b. Similarly next set of 4 points from pointlist should also get green as its value is also b.
 #So, after substitution it should look like APIcommand -points 1,2,3,4 -color green ..... so on and so forth

Note this will not always be b , it just happens to be in this case.
Need solution asap. Thanks in advance.
Answer: Sounds like you need $color([lindex $newlist $i])
Comment: I was trying to use a foreach loop inside the for loop and then use      -color [lindex $color($newlist) $i] and that is why it was giving me error. but using the array name first and then the index of keylist solved my problem. Thanks again !! (It's exactly what I was looking for )
Answer: When iterating across a list, the foreach command is useful. It can also be used to iterate over multiple corresponding lists. Assuming newlist holds the colors that correspond to the points, I might try something like (usual warnings about untested code):
foreach point $pointlist new $newlist {
    APICommand -points [join $point ,] -color $color($new)
}

Comment: We dont have to calculate foreach point, we have to do this for group of 4 points. means 4 points corresponds to one color

How to Retrieve array key values in Tcl


Rotating around a point, object consistently getting further

Question: I'm making a game in Unity, and need an enemy to rotate around a point. I'm using atan2 to get the direction to the point, adding 90 degrees and then using cos and sin to change the position. After finding the object does rotate, but get further from the point, I decided to try this out in p5js. However I get the same issue.
Here is the code:

let x = 100;
let y = 100;
let speed = 5

function setup() {
  createCanvas(400, 400);
  angleMode(DEGREES)
}

function draw() {
  background(220);
  let dir = atan2(y - height / 2, x - width / 2);
  x += cos(dir + 90) * speed;
  y += sin(dir + 90) * speed;
  rect(x, y, 20, 20);
  console.log(dir)
}

Comment: So which is it, javascript or C#
Comment: There's no question in the post. Did you mean to ask how to rotate one position around another position in unity? The logic doesn't work because you're moving `speed` units in the direction of a tangent on the circle, but that doesn't describe circular motion. Basically the same problem addressed in [this answer](https://stackoverflow.com/a/56403553/1092820). You would need to take a different approach.
Comment: It's both. I initially made this in unity then went to see if i get the same result with js, but I see that the problem is in my method. How would i go about doing this, would it be better to get current coordinates, convert to polar and adjust the theta then convert back to cartesian?
Answer:
[...] but get further from the point [...]

Of course. You don't move on a circle. You move along the tangent of the circle. Each step on the tangent increases the distance from the center of the circle. Hence the distance to the center increase in each frame.
You can easily check this by scaling the distance vector with the ratio of the original distance and the current distance:

let x = 100;
let y = 100;
let speed = 5
let dist;

function setup() {
    createCanvas(400, 400);
    angleMode(DEGREES)
    dist = sqrt(pow(y - height/2, 2) + pow(x - width/2, 2));
}

function draw() {
    background(220);
    let dir = atan2(y - height / 2, x - width / 2);
    x += cos(dir + 90) * speed;
    y += sin(dir + 90) * speed;

    let newDist = sqrt(pow(y - height/2, 2) + pow(x - width/2, 2));
    x = (x - width/2) * dist/newDist + width/2
    y = (y - height/2) * dist/newDist + height/2

    rect(x, y, 20, 20);
    console.log(dir)
}

Comment: @matidfk This is an option. Actually, I did not present a solution, I just pointed out the issue.
Comment: Which one do you think would be better in terms of performace, since your bit of code works, but uses a lot of squares/square roots, whereas mine uses sin and cos instead.


Why are 1-morphisms functors?

Question: I'm learning Higher Category Theory but there's one thing I can't wrap my head around $n$-morphisms.
If a $0$-morphism is an object, why is a $1$-morphism a functor and not just a regular morphism?
From what I've been reading, a $1$-category is a category with $0$-morphisms and $1$-morphisms, yet other sources imply that morphisms are not the same as functors in general.
So, what is the difference between a morphism and a functor? Are they both $1$-morphisms? If so, how does that work?
My intuition tells me that morphisms could be defined as such:
$f = 1_Cf$ where $1_C$ is the identity functor in the cagetory $C$. It follows then that functors are a generalization of morphisms, so a morphism is a functor, but a functor is not a morphism. However I got no clue.
Comment: [Wikipedia](https://en.wikipedia.org/wiki/Higher_category_theory) seems to agree with you that 1-morphisms are just the morphisms of standard category theory.
Comment: The $1$-morphisms are functors if you are working in the $2$-category of categories. The objects of this $2$-category are categories, and a morphism between categories is precisely a functor.
Comment: But in a 2-category there would be 2-morphisms (natural transformations) and 1-morphisms (functors / morphisms), so, in that context a 2-morphism would be a functor, wouldn't it?
Comment: A (1-)morphism between categories is a functor per definition.
Answer: Take small categories $\mathcal{C}$ and $\mathcal{D}$, which are objects of $\mathbf{Cat}$, then the functors $\mathcal{C}\rightarrow\mathcal{D}$ are the morphisms of $\mathbf{Cat}$. The class $\operatorname{Fct}(\mathcal{C},\mathcal{D})$ or $\operatorname{Cat}(\mathcal{C},\mathcal{D})$ of functors $\mathcal{C}\rightarrow\mathcal{D}$ can itself be made into a category again, denoted by $\underline{\operatorname{Fct}}(\mathcal{C},\mathcal{D})$ or $\underline{\operatorname{Cat}}(\mathcal{C},\mathcal{D})$, by now considering the functors as the objects and the natural transformations between them as the morphisms. Therefore functors can be objects as well as morphisms depending on what category you consider and caution is necessary! In literature, according to my experience so far, the term "morphism" is more preferably used as it is more general, but "functor" is, when you need to be precise like here.
Combining both of these categorical structures together makes $\mathbf{Cat}$ into a $2$-category and choosing the notation of $n$-morphism avoids any confusion: Small categories are the $0$-morphisms, the functors between them are the $1$-morphisms and the natural transformations between them are the $2$-morphisms.
If you are going into the direction of $\infty$-categories, for which there are many models, the most common being certain simplicial sets, then the best way to imagine an $n$-morphism is by taking the partially ordered sets $[n]=\{0,\ldots,n\}$, which induce categories. You can now notice:

An object (more concretely a $0$-morphism) is equivalently a functor $[0]\rightarrow\mathcal{C}$ and therefore $\operatorname{Ob}\mathcal{C}=\operatorname{Cat}([0],\mathcal{C})$.
A morphism (more concretely a $1$-morphism) is equivalently a functor $[1]\rightarrow\mathcal{C}$ and therefore $\operatorname{Ar}\mathcal{C}=\operatorname{Cat}([1],\mathcal{C})$. Be cautious that the morphism is not the functor, but you have basically only rewritten your data, so considering it as such is basically identical.
Taking the face maps $d_0^1\colon[0]\rightarrow[1],0\mapsto 1$ and $d_1^1\colon[0]\rightarrow[1],0\mapsto 0$, you can use it to express the domain $\operatorname{dom}(f)=\mathrm{d}_1^1\circ f$ and codomain $\operatorname{cod}(f)=\mathrm{d}_1^1\circ f$ of any $1$-morphism $f$.

We can now extend this: Letting $n$-morphisms be the functors $[n]\rightarrow\mathcal{C}$ or $\operatorname{Cat}([n],\mathcal{C})$, which for example makes $2$-morphisms the commutating triangles of the category in particular, is called the nerve construction, which is a functor $N\colon\mathbf{Cat}\rightarrow\mathbf{sSet}$. It is fully faithful (Proposition 3.11.), which corresponds to the fact, that you keep the $0$- and $1$-morphisms the way they are and add informations only depending on them and their composition. You can also use general face maps $d_i^n\colon[n-1]\rightarrow[n]$ (order-preserving and leaving out $i$) as well as general degeneracy maps $s_i^n\colon[n+1]\rightarrow[n]$ (order-preserving and hitting $i$ twice) for generalisations of the domain and codomain. This makes an $n$-morphism basically connect $n+1$ $(n-1)$-morphisms.
By the way: Helpful literature about higher category theory is Higher Categories and Homotopical Algebra by Denis-Charles Cisinski (found here) or Kerodon by Jacob Lurie (found here as interactive website or here as a script).
Comment: Thank you! Props for giving literature about it as well, it's kinda hard to find good material for this.

Why are 1-morphisms functors?


Firestore Rules, allow update only certain fields

Question: I have the following database collection '/player_profiles/{userId}'.  I want to use the rule that only the request.auth.uid == userId unless they are only updating the field matches which is an array.  I tried this, but it denied permissions
match /player_profiles/{userId}{
        allow write: if userId == request.auth.uid;
      allow update: if (request.resource.data.keys().hasOnly(["matches"]) && request.auth != null);
    }

And here is the Flutter code that runs the update to add in the item to the matches array:
await DatabaseProvider()
        .db
        .collection(PLAYER_COLLECTION)
        .document(widget.userProfile.userId)
        .updateData({
      'matches': FieldValue.arrayUnion([profile.userId])
    });

Im new to firestore rules but i thought this would work
Was able to get the behavior I wanted with this:
match /player_profiles/{userId}{
        allow write: if request.auth.uid == userId || (request.auth != null && request.resource.data.diff(resource.data).affectedKeys().hasOnly(["matches"]));
    }

Looking at @Doug Stevenson's answer though I can add in making sure they only are allowed to put in their own userId into other peoples profiles.
Answer: request.resource.data.keys() always contains every field in the document being written, regardless of whether or not it's being updated.  You should use the new MapDiff API instead to compare what's being written with what currently exists.
I think you will want to do something like this:
if
  (request.resource.data.diff(request.resource.data).affectedKeys().hasOnly(["matches"]) &&
  (request.resource.data.matches.toSet().difference(resource.data.matches) == [userId].toSet()) ||
  request.auth == null;

I have not tested, but I think you get the idea.  You will need to make liberal use of the linked API documentation for security rules to work with maps, sets, and lists effectively.


Including MSSQL Server Analysis in WebDev Setup Disk

Question: Hi All and thanks in advance.
I have an application developed in WebDev 22, and I was able to successfully upload it to my own personal Home Web server, The Application works fine however it cannot read the data because it does not have the analysis.
This application Analysis uses an MSSQL Server Database via the Analysis utilizing MSQL Server Machine ODBC (Means that I am not using the PCSoft Native MS SQL Drivers).
How can place the analysis when creating the Deployment Setup Install File, and how to configure it so that when I am installing the Application in the Site it will talk to the same database I have installed on the Windows Web Server at Home?
Does anyone knows, can this be possible?
Thanks
Regards,
Carlos
Answer: I got my own situation resolved.
It turns out that when a Setup Disk is created in PC Soft WebDev, it will automatically include the Database analysis inside the package, in my case I used the option of creating a Media Setup disk to run it in the Web Server, and install the application there. I thought that a very special configuration was needed to be done to connect the Analysis to the MS SQL Data Server in the Web Server, and is none of that.
Let me explain how I got it solved and I would like to explain that everything
was done in the Analysis connection to make possible this connection.

Open the Analysis and Click Connections.
These are the Parameter:
Name: Your Connection Name.
Caption: Your Connection Name here if you want.
Connection By: SQL Server (Microsoft OLE DB Provider for SQL Server).
Data Source: Your MSSQL Database Server Name.
Database: Your Database Name.
User Name: User you created to connect to this database.
Password: The User Password for the User.
Click on Test, if the Connection is successful you are good to Go.
MAKE SURE YOU HAVE VISUAL ON THE SERVER YOU ARE TRYING TO CONNECT
Save the Analysis and Synchronize.
Create the Setup disk and install on the Web Server.
That is it.!!
Why?

Because of when the WebDev application starts, it will Automatically open the Analysis.
The Analysis will then automatically look at the settings you have provided in the Analysis Connection Settings, and it makes the connection.
That is it, I hope this has help.
Best regards,
Carlos


Checking proof for Omega Notation

Question: I am checking if the below statement is true. However, it is true where n is assumed to be 1 but not when it is greater than 1. In this case, I do not need to think about if c is not 0. Would I consider this statement to then be valid?
2^n/n^1000 ∈ Ω(n^1000000)
Answer: Let's look at the definition of $\Omega(f)$:
$$ \Omega(f) = \{ g \mid \exists c \text{ such that } c\cdot g(n) \leq f(n) \textbf{ almost everywhere} \} $$
That "almost everywhere" means "from some value of $n$ on". Sometimes you may have seen this written as $\exists c, n_0$ such that $c\cdot g(n) \leq f(n)$ for $n \geq n_0$.
So what you have to do is a limit, and notice that, for all real $c$:
$$ \dfrac{2^n \cdot c}{ n^{1000} \cdot n^{1000000}} \to_\infty \infty \cdot c = \infty $$
That is, $2^n$, even divided by a polynomial, still "grows faster" than any polynomial.
So there is no $c$ such that $\dfrac{2^n \cdot c}{n^{1000}} \leq n^{1000000}$ almost everywhere.

Checking proof for Omega Notation


grails/hibernate: how to disable auto-increment on ID column?

Question: By default, when you create a domain object in grails, it adds the "id" column and sets it to auto-increment in the DB.
I want to supply the id parameter when I create/save an object, not use any kind of generate (its for a small number of static pieces of data which I want the ID to be fixed to the values I give).
There are other benefits I want, e.g. to be able to create an object in memory with the correct ID, without having to read it from the DB then make this object a "contains" type relationship with another object, if that makes sense.
Grails has documenation for the id column, but doesnt say how to disable auto-increment and allow an ID to be passed into the domain object constructor:
http://grails.org/doc/2.1.0/ref/Database%20Mapping/id.html
Answer: Look at the mappings for the column. According to the documentation you can use assigned like this:
static mapping = {
    id generator: 'assigned'
}

According to the hibernate documentation assigned behaves as such:

lets the application assign an identifier to the object before save()
  is called. This is the default strategy if no  element is
  specified.
Comment: Sadly, this does not seem to work.  If I try it, and pass in a id to the constructor, and save it, I get: IdentifierGenerationException: ids for this class must be manually assigned before calling save()
Comment: @JohnLittle so why dont you assign it manually before calling save?
Comment: I was hoping to pass in the id in the constructor, e.g. new Status(id:1, name: "active").save().  I see that I could do this: s=new Status(name:"active"); s.id = 1, s.save(), which is more painful as I have a lot of static items to set in the bootstrap.  I looked at overriding the Status constructor, and passing in _id and assigning it, and all the other fields manually, but this is also significant overhead.
Comment: By default the `id` property is not "bindable", i.e. it's ignored with using the map constructor, and when setting properties in bulk (e.g. `foo.properties = params`). Either set it explicitly after the constructor call, or make the `id` property bindable with the [bindable constraint](http://grails.org/doc/latest/ref/Constraints/bindable.html). Note that making the property bindable this is somewhat unsafe; `id` and `version` are auto-excluded by Grails (in addition to the default `class` and `metaClass` exclusions that Groovy adds) because only Hibernate should set or update those values.


Scala nested map filter

Question: I'm having a nested map which contains both map as well as a combination of List and None value like this
Map(
  test -> 113123,
  "cat" -> None,
  crm -> List(age, gender, code),
  myList -> Map(
    test2 -> 321323,
    test3 -> 11122,
  )
)

But I wanted to filter out non-map values from an above-nested map
expected output:
Map(
  myList -> Map(
    test2 -> 321323,
    test3 -> 11122,
  )
)

Comment: Please note that I'm reading above value from JSON and parsing it using JSON parser
Answer: collect is your friend whenever you want to do something involving filtering a collection in a way that involves restricting to a certain type:
val map : Map[Any, Any] = Map(...)

map.collect {
  case (key, map: Map[_, _]) => (key, map)
}.toMap

Comment: I wanted output like this Map( myList -> Map(test2 -> 321323, test3 -> 11122)) but above code returning List (Key,map(key->value), please help me on this since im very new to scala
Comment: I mean it's returning List(myList , Map(test2 -> 321323, test3 -> 11122)) but i wanted Map(myList -> Map(test2 -> 321323, test3 -> 11122))
Comment: Ah, whoops - you need to explicitly call `.toMap` afterwards to get it back to a `Map` object. I've just edited my answer to add that.
Comment: I'm getting compile time exception for this val finalMappingValues= parsedJson.collect {
      case (key, map: Map[_, _]) => (key, map)
    }.toMap
Comment: I wanted to filter out based on key name like - List(age, gender, code) please any on help me on this

Scala nested map filter


Consumir WebService passando objeto como parametro

Question: Tenho o WebService e envio o objeto Cliente como paramentro, gostaria de saber como posso fazer isso funcionar, e ele criar um WSDL adequando quando executo o Server, para que eu posso fazer a chamada em um WebService Cliente.
@WebService
public interface UCClienteWS {
    @WebMethod public Cliente cadastrarCliente(Cliente cli);
    @WebMethod public Cliente obterTelefonesDoCliente(Cliente cli);
    @WebMethod public Cliente obterClientePorID(Cliente cli);
    @WebMethod public Cliente obterClientePorNome(Cliente cli);
    @WebMethod public boolean excluirClientePorID(Cliente cli);
    @WebMethod public ArrayList<Cliente> obterTodosClientes();
}

.
@WebService(endpointInterface = "webservice.cliente.UCClienteWS")
public class UCClienteImpl implements UCClienteWS{

    @Override
    public Cliente cadastrarCliente(Cliente cli) {
        UCCliente ucCliente = new UCCliente();
        return ucCliente.cadastrarCliente(cli);
    }

    @Override
    public Cliente obterTelefonesDoCliente(Cliente cli) {
        UCCliente ucCliente = new UCCliente();
        return ucCliente.obterTelefonesDoCliente(cli);
    }

    @Override
    public Cliente obterClientePorID(Cliente cli) {
        UCCliente ucCliente = new UCCliente();
        return ucCliente.obterClientePorID(cli);
    }

    @Override
    public Cliente obterClientePorNome(Cliente cli) {
        UCCliente ucCliente = new UCCliente();
        return ucCliente.obterClientePorNome(cli);
    }

    @Override
    public boolean excluirClientePorID(Cliente cli) {
        UCCliente ucCliente = new UCCliente();
        return ucCliente.excluirClientePorID(cli);
    }

    @Override
    public ArrayList<Cliente> obterTodosClientes() {
        UCCliente ucCliente = new UCCliente();
        return ucCliente.obterTodosClientes();
    }

}

Answer: Bom, vou compartilhar com vc como que eu uso um WS a partir de uma aplicação cliente.
Bom, vamos começar a missa. :-D
Existe uma ferramenta que já vem dentro do JDK que é simples, facil e de graça para vc gerar as classes cliente (consumidora) do seu Web service. É a ferramenta wsimport via linha de comando DOS(Windos) ou no terminal(Linux). Verifique se  o JAVA_HOME esta configurado em suas variaveis de sistema, se não estiver, vc terá que add JAVA_HOME em suas variaveis de ambiente.
Bom vamos ao que interessa. :-D
Vou considerar que seu Web service já esta desenvolvido e pronto para ser consumido e que já esta publicado.
1- acesso o seu serviço pelo browser como por exemplo http://ingo.com/myapp/UCClienteWS?wsdl
2- salvo essa URL com extensão .wsdl como UCClienteWS.wsdl (salve de preferencia dentro de sua aplicação cliente, pois se estiver usando SVN ou outra coisa, ja fica versionado.)
3- acesso o cmd ou terminal (de acordo com seu ambiente) e vai até onde seu arquivo wsdl esta salvado.
4- digite wsimport -keep -verbose UCClienteWS.wsdl isso vai criar uma estrutura de pastas para vc com as classes cliente dentro.
5- copie e cole essa pasta (package) para dentro de sua aplicação cliente.
6- chamando os metodos e passando seu objeto:
6.1- Dentro dessa estrutura foi criado uma Classe Cliente que é o objeto que o serviço aceita. Nessa classe tem umas anotações dizendo que ela vai virar um objeto XML quando enviada para o serviço.
6.2- chamando o serviço
Cliente cli = new Cliente();
cli.setNome("Zé");
cli.setRenda("1.000.000,00");

UCClienteWSService service = new UCClienteWSService();
UCClienteWS ucCliente= UCClienteWSService .getUCClienteWSPort();

ucCliente.cadastrarCliente(cli);

É por ai o caminho.
Qualquer busque no google algo sobre wsimport. è susse. Espero que tenha ajudado.
Abraço..


Confusion about critical points of a function

Question:
I'm a bit confused about why x=+/-1 are critical points but y=+/-1 aren't critical points. Can someone help clarify it for me?
Answer: The partial $\partial f/\partial y=0$ iff $y=0$, since the other factors are strictly positive (the exponential and $x^2+y^2+1$), so $y=\pm 1$ is impossible. Note the the partial derivatives are not symmetric, the minus sign is different.
Comment: Oh my... I think I was looking at the formulas wrong....It all makes sense now hahaha. Thanks for clarifying it for me!


Show that if $H$ is a subgroup of $S_n$, then either every member of $H$ is even or half of them are even

Question: Show that if $H$ is a subgroup of $S_n$ the symmetric group of order $n$, then either every member of $H$
is an even permutation or exactly half of the members are even.
I can see that if $a,b$ are arbitrary even elements in $H$, then their product and any combination of their products will be even, which implies $H$ is full of even permutations, but I'm not sure how to show the half-even half-odd part.
Comment: Say $o$ is an odd element of $H$. Think about the map $h\mapsto oh$.
Comment: Define a map $f:H\to H$ by $f(h)=oh$.
Comment: Makes sense to me.
Comment: I'm unfamiliar with that mapping notation, could you explain what that arrow means?
Comment: It seems it would be a bijective map from even functions to odd functions, which would imply the same cardinality.  Does that make sense?
Comment: What exactly do you mean by "$H$ is full of even permutations"?
Answer: Let $H$ be a subgroup of $S_n$. If $H$ contains no odd permutations, then $H$ contains only even permutations, and we're done.
Otherwise, let $o\in H$ be an odd permutation and consider the function $f:H\rightarrow H$ that multiplies each element by $o$.  Note that this function is bijective: it's injective, with an inverse function that multiplies each element by $o^{-1}$, and it's surjective, because for every element $h\in H$, we can find an element $h\cdot o^{-1}$ that $f$ maps into it.
Note that multiplying by an odd permutation changes odd permutations into even permutations and vice versa. It follows that $f$ is a bijection that perfectly pairs up the odd permutations in $H$ with the even permutations. Hence there are exactly as many odd permutations as even permutations in $H$.
Answer: Consider the homomorphism:
$\text{sgn}: S_n \to \{-1,1\}$ (with kernel $A_n$).
When restricted to $H$, this gives a homomorphism $H \to \{-1,1\}$.
We have two possibilities:
1.) $\text{sgn}(H) = \{1\}$, (that is $H \subseteq A_n$), or:
2.) $\text{sgn}(H) = \{-1,1\}$. Use the first isomorphism theorem, here.
Answer: Cosets are equal in size. If there exist odd elements in $H$, then the set of odd elements $H_{\mathrm{odd}}$ is a coset of the subgroup of even elements $H_{\mathrm{even}}$. Prove this! Can you proceed from there?
Answer: Let $H$ be a subgroup of $S_n$
If every member of $H$ is even permutation, then $H\subseteq A_n$, the subgroup of $S_n$ consisting of all even permutations.
Suppose not, i.e. there is at least one element namely $\sigma_1$ which is an odd permutation. Let $m_e,m_o$ denote number of even, odd permutations in $H$. If $\sigma_1,\sigma_2,\ldots,\sigma_{m_o\ }$ are odd cycles, then $\sigma_1^2,\sigma_1\sigma_2,\ldots,\sigma_1\ \sigma_{m_o}$ are all distinct even permutations, so there are at least that many even permutations as many there are odd ones, which implies $m_e\geq m_o$.
On the other hand, if $\alpha_1,\ldots,\alpha_{m_e\ }$ are even permutations, then $\sigma_1\ \alpha_1,\ldots,\sigma_1\ \alpha_{m_e\ }$ are all odd permutations, so there are at least that many odd permutations as many there are even ones, which gives $m_o\geq m_e$.
Thus, $m_e=m_o=|H|/2$
The result we have proved is: If $H$ is a subgroup of $S_n$, then either $H\subseteq A_n$ or $|H\cap A_n|=|H|/2$


Get the product of two values from two different tables

Question: If anyone can help me figure out where I am going wrong with this SQL that would be great. Please see my attempt to answer it below. I have answer how I think it should be answered but I am very confused by the exam advice below, which says I should use a SUM function? I have googled this and I do not see how a SUM function can help here when I need get the product of two values in this case. Or am I missing something major?
Question: TotalValue is a column in Order relation that contains derived data representing total value (amount) of each order. Write a SQL SELECT statement that computes a value for this column.
My answer:
SELECT Product.ProductPrice * OrderLine.QuantityOrdered AS Total_Value
FROM Product,
     OrderLine
GROUP BY Product;

Advice from exam paper:
 This is a straightforward question. Tip: you need to use the SUM function. Also, note that you can take the sum of various records set using the GROUP BY clause.
Comment: Hi Effie, contrary to what you may heard/expect, Stack Overflow is not a free code writing service.  Typically, only questions showing effort involving active problems get any assistance here.  That being said, have you tried something yet?
Comment: @Tim Biegeleisen She included an answer.
Comment: @Eggsalad No, that's a link to some table data, there is no sign a query anywhere.  Incidentally, I enjoy eating egg salad, and in fact had that for lunch a few days ago :-)
Comment: The general GROUP BY rule says: "If a GROUP BY clause is specified, each column reference in the SELECT list must either identify a grouping column or be the argument of a set function."
Comment: Add sample table data and the expected result - as well formatted text.
Comment: Tip of today: Switch to modern, explicit `JOIN` syntax. Easier to write (without errors), easier to read and maintain, and easier to convert to outer join if needed.
Comment: Another tip: Create the tables, add data. Try JOIN. Try GROUP BY etc! That's how you learn SQL!
Comment: @Tim Biegeleisen Haha! You are clearly highly intelligent.
Comment: @TimBiegeleisen My answer attempt was written in my question. Comes after "My answer:" and then there is a SQL query.
Comment: I am going to edit my answer to be more clear about what exactly my confusion with the question is.
Comment: @jarlh Thanks a lot for the feedback. That was from an exam paper from a few years ago - maybe it is out of date. The reason I am so confused by this is the Exam Advice tells me that I should use the SUM function... whereas I interpret that TotalValue is a product of Product.ProductPrice and OrderLine.QuantityOrdered. Cannot see how a SUM function would be useful. I am very happy to try using JOIN for this. I was just confused by the exam advice given. Thought I was missing something major.
Answer: Ok your question became a lot clearer once I clicked on the the hyperlink (blue text).
Each order is going to be made up of a quantity of 1 or more products.
So there could be 3 Product A and 5 Product B etc.
So you have to get the total for each product which is your Price * Quantity, but then you need to add them all together which is where the SUM comes in.
Example:
3 * ProductA Price (e.g. €5) = 15
5 * ProductB Price (e.g. €4) = 20

Total Value = 35
So you need to use the Product, Order and OrderLine tables.
Something like (I haven't tested it):
SELECT SUM(Product.ProductPrice * OrderLine.QuantityOrdered) FROM Product, Order, OrderLine
WHERE Order.OrderID = OrderLine.OrderID
AND Product.ProductID = OrerLine.ProductID
GROUP BY Order.OrderID

This should return rows containing the totalValue for each order - the GROUP BY clause causes the SUM to SUM over each group - not the entire rows.
For a single order you would need add (before the GROUP BY) "AND Order.OrderID = XXXXX" where XXXXX is the actual orders OrderId.
Comment: By the way, it's a good idea to avoid having a table called Order as it can lead to confusion with the ORDER BY clause.(Notice Order got turned blue above because ORDER is a reserved word in SQL)


MST, Cut in Graph, Some Claims?

Question: I ready for taking a P.hD Entrance Exam. one of old-solution problem of Data Structure is as follows:
Which of the following Claims is True about MST of Simple, Undirected, Weighted and Connected Graph G? (edge weights is not necessarily different.)
1) if lightest edge between any cut in G, be unique, then MST is unique.
2)If all edges weights be different, MST is unique.
3) if the weights of e=(u, v) be equal to maximum lightest edge in all paths between u and v then e be in the MST.
Answer: one of them is Correct.
Who can explain more, which is true? why? there is any proof or we must take an example or provide counterexample?
Comment: https://stackoverflow.com/q/35409184/781723
Answer: To see that 2 is true, consider two different MSTs $T_1$ and $T_2$; we will show that either $T_1=T_2$ (i.e. they are not different) or one of them is not actually minimal.  Since they are both minimum, the sum of each's edge weight is the same.  Say the edges of $T_1$ are $e_1 < e_2 < ... < e_n$ and the edges of $T_2$ are $f_1 < f_2 < ... < f_n$.
Since the trees are different (by hypothesis) there is (at least) one edge that is different: say $e_i\in T_1$ and $e_i\notin T_2$... choose $e_i$ as the smallest edge with this property i.e. $e_1=f_1, e_2=f_2, ..., e_{i-1}=f_{i-1}$ and $e_{i} < f_{i}$.
Then, add $e_{i}$ to $T_{2}$. You created a cycle, so now we delete an edge to make it a tree.  Delete the edge of maximum weight on the cycle, $f_{j}$.  Provided that the edge we deleted ($f_j$) isn't $e_{i}$ then the new Tree $T_{2}+e_{i}-f_{j}$ has lower weight than $T_{2}$ and hence $T_{2}$ wasn't a MST (contradiction).  Now, we just have to show that $e_{i}$ is not $f_{j}$.
If $e_{i}$ is $f_{j}$ that means that the edge we added was the heaviest edge on the cycle (had largest weight).  If this is the case, then every edge on the cycle is lighter and therefore comes earlier in the ordering (i.e. all the edges on the cycle have subscripts smaller than $i$).  But, then all these edges are also in $T_1$ and $e_i$ is in $T_1$, but $T_1$ is a tree and contains no cycle.  Therefore, there is an edge on the cycle that is not in $T_{1}$ and hence has more weight than $e_{i}$.  Thus, $e_{i}$ is not $f_{j}$.
Comment: @DaviedZuhraph, It may be that 1 is also true... but I did not immediately see a proof.
Comment: Please complete it to approve
Comment: @user4249446, I would write more except I feel that the person asking the question ought to provide more effort than the respondent (me).  If he/she explains what he/she has done in greater detail, then I am happy to provide more information.
Comment: @DaviedZuhraph, explain what you've done and where you're stuck, then I'll help.  You also need to clarify your question.  I assume for 1 you mean "every cut C contains a unique lightest edge" and I assume you mean that a cut is a set of edges that, if removed, result in a disconnected graph.

MST, Cut in Graph, Some Claims?