x264: Optimal settings to have i-frames coincide with shot boundaries?

Question: I would like to encode a video using x264 in such a way, that the keyframes (a.k.a. i-frames) are coinciding with shot boundaries (a.k.a. cuts).
for testing, I used the following encoder settings (reference: http://www.chaneru.com/Roku/HLS/X264_Settings.htm):
keyint=500:min-keyint=10:scenecut:40

but from the looks of it scene changes are ignored entirely, and keyframes simply inserted every 500 frames.

scenecut:40 being the default value, is my result expected behavior? or is it an indication, that something is not quite right?
thanks a lot in advance

edit:
the complete encoder settings look like this (in handbrake):

TL;DR:
it was a typo :|
Answer: From your settings screenshot it looks like it result in disabling of scenecut (scenecut=0 in x264 Unparse) because you used : as separtor of parameter name and value for scenecut instead of =.
So either change your additional params to:
keyint=500:min-keyint=10:scenecut=40

or remove scenecut from it at all i.e.:
keyint=500:min-keyint=10


Pattern matching in compound if statements and switches with fall-through

Question: If I have an if statement like if (currentShape is ITable table || currentShape is AutoShape autoShape) I cannot use table or autoShape in the body because I get a CS0165 compiler error.
The same is true for a switch statement with fall-through:
void Foo(object o)
{
    switch (o)
    {
        case int i:
        case string s:
        case Guid g:
            string bar = i?.ToString() ?? s?.ToString() ?? g.ToString(); // cannot use i, s, or g.
            break;
    }
}

I understand why, but I'm left wondering, is this a limitation of pattern matching, i.e. you cannot use it in compound if statements, or is there a correct way to construct the statement so I can use either variable (e.g. by initializing them to null so I can then at least do a null check)?
Comment: maybe this is related https://stackoverflow.com/questions/46255003/fall-through-in-pattern-matching. You can use discards if you don't like to make garbage local variables in current region. then you can use switched variable directly
Answer: Since C# 9 you can do the followings
with switch statement
switch (o)
{
    case object probe when probe is int or string or Guid:
        string bar = probe.ToString();
        break;
}

and with switch expression
var bar = o switch
{
    int or string or Guid => o.ToString()
};

Answer: If truly there are two separate things to achieve, don't combine the pattern expressions.  Two separate if statements will work better.
if (currentShape is ITable table)
{
    // do something with tables
}

if (currentShape is AutoShape autoShape)
{
    // do something with autoshapes
}

However, your other example illustrates that perhaps there is some common functionality between the conditions.  ToString() is probably a bad example, as you could just do:
string? bar = o.ToString(); // doesn't matter the type of object

But let's say that perhaps you want a different format applied depending on the type.  In that case, a switch expression could be useful.  For example:
string? bar =
    o switch
    {
        int i => i.ToString("D3"), // three digits
        Guid g => g.ToString("N"), // no hyphens
        string s => s,    // no need to call ToString on a string
        _ => o.ToString() // all other types
    };

You also asked about whether the variables could be initialized with nulls so you could do a null check.  That wouldn't work for non-nullable types like int.  For nullable types, it would cause an extraneous compare operations (first to test the type and assign null, second to test for null).  Keeping the expressions separate ensures the minimal number of operations.


Mobile Edge browser swallows first few pixels of webpage height

Question: I've noticed a behavior where the mobile Edge browser on Android is eating the first few pixels of height of a webpage, instead covering it with its address bar in a way that you just can't see the content.
This is happening on a project I'm working on, but here is a minimal repro. It's a red box of height 1px, attached to the very top of the page (at least it should be!).

In reality, though, when I open this page in the mobile Edge browser on Android, the line is nowhere to be found. I've put up the above code at my github pages account.
If I inspect the page while connected to my PC and I change the box's margin-top in the inspector, I need to add about 9px of top margin to have it display on the page so it's not covered by the address bar.
That gives? Is this a known bug? Am I doing something stupid?
One may say "just scroll a bit to make the bar go away". Sure, but that doesn't work for websites that are fully stretched out vertically such as to make the address bar and other menu bar remain fixed without coming and going.
Thanks!
Comment: I make a test with your sample code. It works well in Edge Android mobile. You can check the screenshot: https://i.stack.imgur.com/BHqmv.png. I can see the red line on the top left of the browser. Which version of Edge browser are you using? My Edge browser version on Android is 46.06.4.5160.
Comment: @YuZhou I'm running 93.0.961.53 . Are you sure you've updated your version recently...?
Comment: I updated my Edge and now I can reproduce the issue. I suggest that you can provide feedback about this issue by clicking **three-dot icon on the bottom-> Send feedback** in Edge mobile. Edge team will check the feedbacks and improve the product continuously.
Comment: @YuZhou yeah, thanks, I did that and linked them to this page. Thanks for taking the time to repro!
Answer: It is because 1px is so small that you cant see the box in mobile
Try adding more CSS.
Margin and Padding just defines how much spacing between elements out side box and inside box.
try this :
your modified code with bigger pixels and navigation-bar(or) addressbar :

Navigation bar

Comment: It's not the box size. If I give it a margin-top of 20px, I can see it, for example.


Do I need 3 RGB channels for a spectrogram CNN?

Question: I am computing a linear spectrogram of an audio signal.
https://en.wikipedia.org/wiki/Spectrogram
The spectrogram is a 2-D matrix with time on the x-axis and frequency on the y-axis.  The traditional approach is to apply a color mapping to convert the spectrogram (with values from -80 to 0) to an image with three color channels.  This effectively makes it a 3-D tensor. Then we feed that into the convolutional neural net.

Does this color mapping step really need to be done?  The color mapping will have different nonzero ranges on different channels, but what are we gaining?  The color map is just derived from the 2-D matrix so I don't see how there is any information increase, but certainly it adds to the computational complexity.  And it seems like it might really depend on which color map is used, adding another layer of complexity.
Do I really need three channels since all of the information is in the 2-D matrix?  How does this affect the ability of the CNN to detect certain audio markers?
Comment: The colors come from a choice of how to map the greyscale values to a more pleasing/visible image, right? I can't see how the color is adding any additional information, because it's just a different way to display the greyscale data.
Comment: @Sycorax, The spectrogram that people view are for pleasing visualizations, but when fed into the CNN it's just data.  Different color maps map different intensities to different colors, so it seems like changing the colormap would impact the different channel values and maybe the effectiveness of the CNN.
Comment: That sounds like another reason to prefer the greyscale: you care about the underlying data, not the aesthetic choices that went into choosing a particular color scheme.
Answer: No, the color is just an aesthetic aspect of the spectrograms. A grayscale spectrogram contains all of the relevant information in its pixel intensities. You can tell because in most application you can select the colormap yourself (i.e. if you want the intensities to take shades of red, greed, blue, purple, etc.).
I can personally confirm this as I've successfully trained CNNs on grayscale spectrograms!
Comment: Ahh, relevant experience.  Thanks for confirming this!
Comment: You're welcome! :)
Answer: You are mapping intensity as function of time and frequency. That is: you have a map like $\mathbb{R}_+^2 \to \mathbb{R}_+ $.
This is much like many other types of mappings from 2d coordinates to some 1d level. E.g. height maps, temperature maps, etc.
Technically, you would indeed not need colours or 3 RGB channels, to express the (1 dimensional) result.
However, beyond the aesthetic purpose of the use of colours, you may wonder about certain functional/practical purposes of the colours. (for example: easier recognition of specific features, easier recognition of the scale including when people are colour blind, etcetera).
For instance, in topographic maps you find colours: blue (below sea level), green (moderate hight, ie where grass and plants grow), grey or brown for mountains.

These colours in the height map could be left out from a technical point of view and the graph could just as well be created in greyscale.

The use of colours becomes a neccesity when you wish to plot multiple one dimensional features in a single plot (like plotting each feature by a different colour or other aspect of the spectrum). That is, when you wish to plot more than a one-dimensional result.
Such complex colourful maps are not easy to read. And as a consequence not many are made and there are not many examples.


splitting file into multiple files within a while loop

Question: I have a file like this (InFile.txt):
TOM1 LE1 1
TOM1 LE2 1
TOM1 LE1 2
TOM3 LE2 2
TOM1 LE3 3

The output would be three new files labeled 1.txt, 2.txt, and 3.txt, which are generated from the original file based on having the value in column 3 in common.
1.txt
TOM1 LE1 1
TOM1 LE2 1

2.txt
TOM1 LE1 2
TOM3 LE2 2

3.txt
TOM1 LE3 3

I have been trying to do this as follows but struggling with my syntax
awk '{ i = 1; {while (i < 100); if($3 == i) print $1 " " $2 " " $3; InFile.txt > $i.txt} i++}' InFile.txt

Answer: You can use this awk,
awk '{ filename=$3 ".txt"; print $0 >> filename}' yourfile

Explanation:

$3 ".txt" - Forming filename using $3 value.
print $0 >> filename - Appending the current line($0) to corresponding
filename.
Comment: thank you for the explanation. a lot more straight forward to how I was approaching it.


Can a paired t-test be applied when there is no strict pairing but data come from same individual?

Question: The question is if it is possible to apply a paired t-test in the following situation:
Let's say we have conducted an experiment to measure how long does it take to perform a task under two different conditions. We have only one individual taking part in the experiment and we perform several measures in both conditions (let's say 300 measures under condition1 and 500 measures under condition2).
We want to figure out if we have enough evidence to state that there is a difference in the mean delay before response, more specifically that condition1 requires more time to complete the task.
To make it clearer a possible experiment may be:
we have one guy, running 100 meters 30 times and we measure the performances. 20 times this is done under sunlight and 10 times without sunlight. Can we use a paired t-test to provide evidence for the alternative hypothesis?
Comment: It depends on how you interpret your experimental objective.  *This* experiment can only assess how long it takes for *this individual* to perform the task.  It provides no legitimate basis to generalize to other individuals.
Comment: I perfectly agree with that point but what t-test should be used? Paired or unpaired? Because it is the same individual, but there is no natural correlation between the various measures (there are even more measure for one condition than the other)
Comment: What is the population parameter you want to make inference on?
Comment: I don't see any pairing, either.  Doesn't the lack of any pairing make your question moot?
Comment: The experiment is meant to check if we have enough evidence to state that (for example) under sunlight this person on average runs faster.
I know there is no pairing, but there still is a relation between the "two groups" since it is always the same subject.
Comment: Is there a strict ordering of equivalent tests under each condition? If each run under each condition was recorded with the same sequencing (enough pre experiment rest to ensure equivalent baseline, matched sleep, diet, time of day, day of week...) then for each run you give fixed rest and recovery protocols... In the end you can only use data points that can be directly compared (so must be same number in each). This gives different insight composted to unpaired and the question becomes will be what is that insight? That depends on the details.
Comment: The key here is that you need to be sure you have controlled for all possible biases otherwise what you end up measuring with a paired T test is the extent of bias in your experiment.
Answer: There is no pairing in this situation, so I cannot see how a paired t-test could be applied. But you could use the non-paired t test for comparing two groups, or maybe better a permutation test.  More details/context would be needed to say much more.


About View format its css setting.

Question: I am not good at CSS. Here I want to divid every grid evenly. The is my page. My view I use grid instead of table or unformatted list, which are only text on each row not suit my want.
https://www.jeffhost.idv.tw/services
The other question is on this. I found the picture too small, while making the window smaller. How to adjust a proper setting on View?
https://www.jeffhost.idv.tw/online-buying
Thanks.
Comment: Hi jeff, I just updated my answer. Let me know if it helps!
Answer: Okay, the answers to your questions are both rather simple.

Your columns are uneven because you did not apply a width to the columns. To solve this I simply applied a percentage width to the td element as follows:

.view-view-services .view-content td{
   width: 33.33%;
}

When you make your browser's viewport smaller, your images become smaller. This is due to the auto properties applied to the img tag's height and width. To solve the issue I overrode the max-width property as follows:

.view-uc-products .views-field-uc-product-img img{
   max-width: none;
{
Let me know if you have any questions!
Comment: Thanks. I get known more about CSS via some books and then I try this modification.
Comment: Hi,
I wonder a style to be on the phone. May I adjust each column width individually? I want to distribute the first column width 25%-33. The second width, title is at least 25-33.33%. Both of the two occupy 50%. The third one, price occupy 20% and the rest of place for adding to the cart. Is there any way to be more customized to adjust the size? Otherwise, I want the picture is set on its block aligning to the center. Wish your advices. Thanks.
Comment: @jefferyear I'll get back to you on this. You can specify the width of each individual column using child selectors. If you want to design your columns responsively (for a phone or tablet), you'll have to learn how to use media queries. Using media queries, you'll be able to adjust the column width based of the size of the screen. For example, you might have 3 columns at 33.33% on desktop, 2 columns at 50% on tablet, and 1 column at 100% on mobile.

About View format its css setting.


Need "carat" for currently active Superfish menu item

Question: I have a Drupal 7 Superfish menu (from the Superfish module) that I would like to add a "carat" to for the currently active menu item.
Here is my current menu:

But I would like a menu where the currently active menu item has a "carat" instead.
Here is what I would like: (altered in photoshop to give carat)

I'm looking for the easiest way to do this in Drupal 7.
Any ideas?
Answer: Your best bet would be to just use CSS.  You can create that effect using absolutely positioned pseudo elements with some border tricks.  For example:
<code>.sf-menu li {
  position: relative;
}

.sf-hover:after,
.active-trail:after {
  content: "";
  display: block;
  position: absolute;
  width: 100%;
  height: 20px;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #369;
}
</code>


Conditional distribution from order statistics

Question: I have the following data generating process:

I have two Uniform RVs $X$ and $Y$
I sample $n$ times from $X$ and $m$ times from $Y$, and then pick the max. Call this $Z$.
I'm trying to find the conditional distribution of $Z$ for each class $X$ and $Y$ separately. That is, the distribution of $Z$, given $Z$ came from $X$, and from $Y$.

$$X\sim \textit{Unif}[0,1]$$ $$Y\sim \textit{Unif}[0,b], \space  b>1$$
$$Z \sim Max\{X_1,X_2...X_n,Y_1,Y_2...Y_m\}$$
This is what I have so far.

I have the overall distribution of $Z$.

$Z$ can be written as $Z\sim Max(Max(X), Max(Y))$. Then,
\begin{align}
F_Z(z) &= Pr(Z \leq z) &\\
&=Pr(Max(X) \leq z)P(Max(Y) \leq z) \\
&=F_{Max(X)}(z)F_{Max(Y)}(z)
\end{align}
$F_{Max(X)}(x) = x^{n}$ and $F_{Max(Y)}(y) = (y/b)^{m}$
This gives
$$F_Z(z) = \begin{cases}
      (z/b)^m & z \geq 1 \\
      (z/b)^m z^n  & otherwise
   \end{cases}
$$
Note that $z$ is bounded by $[0,b]$. I checked this with simulation, and I got the same plots.

I also have $Pr(Max(X)>Max(Y))$, i.e probability that X is picked.
\begin{align}
Pr(Max(X)>Max(Y)) &= Pr(Max(Y)=x)Pr(Max(X)>x) \\
&= \int{f_{Max(X)}(1-F_{Max(Y)})dx} \\
&= \frac{b^{-m}n}{n+m}
\end{align}

I also checked this with simulation, and it looks right.
With this information, I'm trying to find the conditional distribution of Z given that it's from class $X$ and class$Y$ separately.
Here are the empirical pdfs of Z, where the different colors are $X$ and $Y$. This is what I'm trying to find analytically.

Thanks in advance for the help!
Answer: Turns out, I was overcomplicating this. All I had to figure out was
$$f(Max(X)|Max(X)>Max(Y)$$ and
$$f(Max(Y)|Max(Y)>Max(X)$$
$$f_{X\mid X>Y}(x)=\frac{f_X(x)F_Y(x)}{P(X>Y)}$$
see Conditional expectation of X given X is greater than Y


Comando javascript não funciona dentro do Buttom

Question: Bom dia!
Estou com um problema e não estou conseguindo resolver a questão.
Preciso que um buttom apareça ou não de acordo com a condição PHP.
Fazer o buttom aparecer estou conseguindo, a questão é que dentro dele tem uma chamada javascript que não funciona dentro do PHP. Não sei o que estou fazendo de errado.
Seguem os códigos:

<?php
    if (get('data_do_descredenciamento')!= ''){
        echo '<button type="button" class="btn" href="#" onclick="javascript: exibe('conteudo');">SUBSTITUTO</button>';
    }
?>

Está dando erro no conteúdo: onclick="javascript: exibe('conteudo')
Alguém poderia me ajudar, por favor?
Comment: O que é esse `conteudo`? é uma string? Tens de escapar essas aspas simples... assim: `exibe(\'conteudo\');`
Answer: Seu problema é por causa das aspas.
Segue algumas alternativas para resolver seu problema:
1° Concatenar aspas.
echo "<button type='button' class='btn' onclick="."exibe('conteudo');".">SUBSTITUTO</button>";

2º Escapar aspas simples
echo '<button type="button" class="btn" href="#" onclick="javascript: exibe(\'conteudo\');">SUBSTITUTO</button>';

3º Variável com o onclick
$button_onclick = "onclick="."exibe('conteudo');"."";
echo "<button type='button' class='btn' href='#' $button_onclick>SUBSTITUTO</button>";

Espero ter ajudado.
Answer: Substitua isso:
onclick="javascript: exibe('conteudo');"

Por isso:
onclick="javascript: exibe(\'conteudo\');"


Regression when both the predictor and outcome variables are proportions

Question: I am using
$X$ The estimated pre-game win probability of a sporting team playing on its Home field (estimated according to a certain model)
to predict
$Y$ Actual proportion of points scored by the Home team in the game (i.e. number of points scored by Home team divided by all points scored in the game).
Graphed, the data look like this.

Data viewable here.
I did a simple linear regression and it produced the parameters $b_{0} = 0.3554$ and $b_{1} = 0.2930$. Thus even at the maximum possible value of $x$ it doesn't predict the home team will score more than 100% of the points.
However, some reading of other questions here indicates that linear regression is generally considered inappropriate for situations in which the outcome variable is a proportion.
The question is highly similar to this one, in which a the poster was seeking to predict a team's winning percentage. There it was suggested that the poster should convert the proportion of wins to the number of wins. However, in my question it would not be the same thing for me to use the number of points scored by the team.

How inappropriate it is for me to use linear regression here?
What analysis should I use, keeping in mind that unlike in the linked question I can't just use the raw number of points scored by the team (since I really am interested in the proportion of points they will score). gung's answer here seems to indicate beta regression if the predictor is a continuous proportion, and logistic regression if it's a count proportion. However, I'm not sure which of those two my predictor is.
Does it make any difference that my predictor is also measured as a proportion?
Comment: 1). It's not great because your DV is bounded, 2). Beta regression would be the first choice, since it allows you to model your data as is (without needing to change it), 3). Yes, you could also use a logit transform $$\text{log}\Big(\cfrac{p}{1-p}\Big)$$ to transform your DV and do regular linear regression.
Answer: A glm with a binomial distribution and a logit link should work fine. If there are no probabilities of $0$ or $1$, beta regression is another possibility. In this case, they yield almost indistinguishable results (not shown).
The relationship between the logit of the actual and the logit of the estimated probabilities looks quite linear (see picture below), which would lead me to use the logit of the estimated probabilities as predictor. The R code using to generate the plots is at the bottom of this answer.

Let's visualize the model on the original scale (the points are partial residuals):

Possible extensions include:

Using robust standard errors (see R code below). Stata's fracreg command uses them by default.
Using a quasi-likelihood (by using quasibinomial as family in glm)

R code:
library(betareg)
library(visreg)
library(lmtest)
library(sandwich)

# Convert probabilities to log-odds
est_p_logit <- log(est_prob/(1 - est_prob))
act_p_logit <- log(act_prob/(1 - act_prob))

# Check linearity
scatter.smooth(act_p_logit~est_p_logit, las = 1)

# GLM with binomial distribution and logit-link
mod <- glm(act_prob~est_p_logit, family = binomial)

summary(mod)

# Robust standard errors
coeftest(mod, vcov = vcovHC, type = "HC3")

# Visualize GLM model
res_glm <- visreg(mod, scale = "response", ylim = c(0, 1), partial = TRUE, rug = 2)

# Beta regression
mod_beta <- betareg(act_prob~est_p_logit)

# Compare GLM results with beta regression
res_beta <- visreg(mod_beta, scale = "response", ylim = c(0, 1))
lines(res_beta$fit$visregFit~res_beta$fit$est_p_logit, type = "l", col = "red")

Answer: Differently from the other answer here which I think is a good answer, I think a linear regression suffices in your exact situation. As a matter of principle, it might be wrong because of the hard bounds on the outcome but a plot of your data suggests why it is a good enough approximation. At both extremes, the mean of your data is far enough from the extremes of the outcome, hence, there is no bending or curving of the relationship to respect the bounds on the original outcome. In short, your predictions appear to be linearly related to the outcome, the major requirement for linear regression.
If the above is true, the advantages of the linear model are then:

ease of interpretation, the coefficients you posted make sense on arrival
one can obtain a relatively simple measure of variability around the fitted line from the regression standard deviation if one cares.

I began by exploring the data:
dat <- read.csv("Estimated probability of winning vs Actual proportion of score - Sheet1.csv")
names(dat) <- c("x", "y")
ggplot(dat, aes(x, y)) + geom_point(shape = 1) + theme_bw() +
  geom_smooth() + geom_smooth(method = "lm", se = FALSE, col = "red")

The blue line is a generalized additive model smoother. The red line is the linear fit. One can observe some curvature at the ends but outwards, not inwards. So your predictions are not exactly linearly related to the outcome. Since you have enough data points, this is probably not arbitrary.
A logit transformation of $y$ is unlikely to help here, rather, a logit transformation of $x$ since it bends outwards. We can shrink the middle $x$ values somewhat and expand the larger $x$ values:
ggplot(dat, aes(log(x / (1 - x)), y)) + geom_point(shape = 1) + theme_bw() +
  geom_smooth() + geom_smooth(method = "lm", se = FALSE, col = "red")

And this time, the linear fit approximates the smoothed fit quite well, not so well at the tails, but good enough for most applications. And homoskedasticity is a plausible assumption.
So the regression model of choice is then:
coef(summary(fit.lm <- lm(y ~ log(x / (1 - x)), dat)))

                 Estimate  Std. Error   t value      Pr(>|t|)
(Intercept)    0.50116288 0.002897402 172.96973  0.000000e+00
log(x/(1 - x)) 0.05446613 0.002045560  26.62652 6.846189e-124

When the predicted log-odds are zero, we expect the win probability to be about 50%. A log-odd higher, and expectation is 5% higher. As seen in the second plot above, the log-odds don't go any further than 5 in either direction. So all the predicted values of $y$ are bound between about 25% and 75%. The regression effect is clear enough and at a large enough sample size that I trust that the inference is not misleading overall. There are always alternatives for better precision.
We can also get a sense of the error about the fitted line.
sigma(fit.lm)
[1] 0.09958555

Given a prediction, about 95% of values should be within about $\pm20\%$. The interval when added to the minimum and maximum predicted $y$ also lies within bounds.
The justification for the linear approach is its simplicity and its adequacy in this particular application.
Comment: In addition, $0.500$ is within the $95\%$ confidence interval of the estimate for the intercept.
Comment: @user1205901 if you had more data, you could empirically test to see how bad it would be if you made this approximation. If you can live with it, then why not?
Comment: This is certainly an intuitive and attractive approach. If I apply the model, do you think it's legitimate for me to manually change the intercept parameter from 0.50116288 to 0.5 exactly. Because it seems desirable that a team with a .5 chance of winning should be expected to score 50% of the points.
Comment: It wouldn't matter much here, but you could also then run a no-intercept model with .5 subtracted off from the outcome: `lm(I(y - .5) ~ 0 + log(x / (1 - x)), dat)`. Any predictions from this model would then have to be adjusted up by .5. Or alternatively using an offset: `lm(y ~ 0 + log(x / (1 - x)), dat, offset = rep(.5, nrow(dat)))`


How do I lower the action on my Floyd Rose guitar bridge?

Question: I have a Floyd Rose bridge on my guitar that I bought (used) last year and I have never been able to lower the bridge.
I've tried twisting the pivot screws but there's no difference. I use the guitar a lot but I can't shred or anything considering the strings are way too high from the neck.
Not sure if this is relevant, but it's currently in C tuning and I'd like to keep it that way.
Here's what it looks like:
Answer: I can see from your photographs that your guitar is so far out of its proper adjustment that the easiest way to fix it would be to take it to a professional guitar repair person and pay them for a setup. That way you know that the job will be done right.
The biggest problem is the bridge. But beyond that, the repair person will also adjust the tension on the truss rod in the neck (to compensate for the tension of the strings according to the gauges you are using and your alternate tuning), and possibly raise or lower the nut (at the headstock). These can affect string height and "action" as well.
Be sure to buy a brand-new set of strings in the the set of gauges you prefer and to give them to the repair technician. They will put the new set of strings on the guitar as part of the set-up procedure. Technicians are never willing to keep the same old set of strings on the guitar during a setup.
Now, about the bridge:
Can you remove the cover on the rear of the guitar and photograph the springs on the back and post it here?
You may need to add more springs to the assembly. The springs provide a counterweight to the tension on the guitar strings, pulling the bridge down and enabling the bridge to sit in the right position (after which the position of the components can be calibrated to provide the kind of behavior you want, such as making the bridge sit flat or "float")
With heavy-gauge strings, tremolo systems like the Fender need to have 5 springs in place.

With extremely light-gauge strings, you can use only 2 or 3 springs.

Here is a YouTube video where a guitar technician explains the relationship between string gauge and string tension and the number of springs on the back and how to adjust them.

The number of springs isn't the only deciding factor: it's also the adjustment of the plate you can see in the photograph above whose position is determined by the two long screws.
Here is another point in the same video where this is explained:

But again, as your guitar's bridge is so very far out of its proper alignment, I think it would be worth it for you to pay a professional guitar technician to calibrate everything correctly.
Comment: Take the back off as @ecline6 says, but also check to see how many springs you have from the hooked plate to he bridge. Normally 3 are used, but there are often 5 slots. Depending on the tension you need, you may need to add springs - the angle of your bridge is extremely high!
Answer: Tremolo bridges are a bit more work to get setup just right compared to fixed bridges.
From your photos, it looks like the there is too much tension from the strings, or not enough tension from the springs (in the back of the guitar).  I say this because the tremolo is being pulled too far forward.  Typically, the tremolo should look parallel to the body of the guitar if things are setup properly.
Either your string gauge is too large, your tuning is too high for string gauge, or the springs on the back of the tremolo are too loose.
Once you get your tremolo parallel to the rest of the guitar, if further adjustment is needed, you can lower the two pole pieces that the knife edge of the tremolo touches with an Allen wrench.
EDIT: since you said your guitar is in C tuning, I would make the assumption that there is not enough tension from the springs in the back of the guitar.
Answer: Loosen the strings and take off the cover on the back of the guitar.  There will be two screws that secure the plate that the bridge springs attach to.  Tightening them will pull the bridge down.  You may need to trial and error a bit to get it where you want it.
Different tunings will affect the floating bridge height due to different amounts of tension, so the C tuning may be the reason that it's so high right now.
Answer: As per the other answers, it looks like a setup issue.  The are plenty of good guides online which explain how to setup a floyd rose type bridge correctly.  Here are a couple I found with a quick search on google, although there are plenty of others:
http://www.soundunlimited.co.uk/articles/how_to_setup_a_floyd_rose_trem
http://www.glowingtubes.com/p/FloydTuning.htm
Warning, it does take time and patience!  If you don't feel confident setting up, a good guitar tech will be able to sort it out for you.
Answer: DO NOT tighten or loosen the screws holding the spring claw in place on the back of the guitar. Those screws should never be tightened or loosened. They're not meant for making adjustments. Instead, you make adjustments to bridge tension by adding or removing springs....from the looks of it...in your case i'd say youre missing them.
Comment: Those two long screws that hold the plate that the springs are attached to are there for that exact purpose.They work in the same way on Strat vibs. Floyd Rose instuctions call them adjustment screws ! Ecline6 will agree. Yes, adjustment is made coarsely with the number of springs, but fine adjustment is made using the claw screws. That's why they're there !!  In my opinion this edit is incorrect, as is the information contained in it.
Comment: To whoever is insistently trying to edit this post: on Stackexchange, we do not "correct" an answer by editing it. We comment on it, and downvote the answer if needed. If you think the answer is incorrect, simply add your own answer instead.


Serialized/Deserialize object created from dynamicly loaded dll

Question: I dynamicaly load a dll, create a new object and serialize this object into byte array. It works fine. However I cannot deserialize this object because it throws an exception SerializationException: Unable to find assembly 'TicTacToe, Version=184.108.40.206, Culture=neutral, PublicKeyToken=null'.
Here is short code expamle
<code>        var loadedGame = Assembly.LoadFrom(pathdll);

        var instances = from t in loadedGame.GetTypes()
                        where t.GetInterfaces().Contains(typeof(IMove))
                        select Activator.CreateInstance(t, 15) as IMove;

        IMove move = instances.First();

        var formatter = new BinaryFormatter();

        using (MemoryStream stream = new MemoryStream())
        {
            formatter.Serialize(stream, move);
            stream.Position = 0;
            formatter.Deserialize(stream); // exception is thrown here

        }
</code>
Do you have any idea how to deserialized object?
UPDATE:
Solution: How to serialize/deserialize an object loaded from another assembly?
Thanks you weston!
Comment: Is this of use? http://stackoverflow.com/questions/8183787/how-to-serialize-deserialize-an-object-loaded-from-another-assembly
Comment: Just try with [Json.Net](http://json.codeplex.com/) (`JsonConvert.SerializeObject`, `JsonConvert.PopulateObject`) It should work.
Answer: Solution: How to serialize/deserialize an object loaded from another assembly?


What changes need to make after changing deployment target in iOS app

Question: I am working on an iOS project. This project has been implemented in Swift with some pods (Frameworks) included in the project.
Recently a requirement has come to change Deployment Target from iOS 8.0 to 9.0, I changed it and built the app. The app works fine without any error. But this project has Podfile with below line,
<code>platform :ios, '8.0'
</code>
I am confused whether to change this as well or not.
Other than this please mention any other changes required in the project after changing deployment target?
Comment: yes you need to change that platform so new pod with delopment target will be downloaded
Answer: Yes, you should change the podfile as well, so that the code in the library also gets compiled with iOS 9 as its deployment target.
Comment: ok, nice, But other than this do I need to bother about anything else even on deployment time. Any configuration updates on my Apple developer account at the time of releasing next version?
Comment: No. Deployment targets are per app, not per developer.


How can I quickly clear GPT partition data from a disk?

Question: I want to do a quick "wipe" of some disks so they look like they're ready to be newly partitioned.  Currently there is a GPT partition type on disk, which seems to write some data both at the beginning and end of the disk.  In this case, it doesn't matter if the data on the disk is wiped, so no need to wait for the whole disk to dd from /dev/zero. So what's a simple way to clear just the beginning and end GPT headers?
In this case, I'm using Linux (CentOS 7) with standard SATA disks (/dev/sda, etc.)
Answer: gdisk has an option for it. Open extended options, choose 'zap':
gdisk /dev/sda
> x
> z
> w (maybe?)

Comment: TIL, the gdisk Zap option!  This will be my preferred method when only doing one or two disks.
Comment: This looks a simpler option than what I posted, assuming you have gdisk available.
Answer: This should do it pretty efficiently, based on the information about GPT on this site.
Clear the first block (two 512-byte sectors for MBR and header, and 16KiB for partition entries):
dd if=/dev/zero of=/dev/sdwhatever bs=512 count=34

The last part is trickier.  I'm borrowing from this question to assist, although if you have ddrescue handy, it can go in reverse.
dd if=/dev/zero of=/dev/sdwhatever bs=512 count=34 seek=$((`blockdev --getsz /dev/sda` - 34))

Comment: The reason this is so helpful is that all the commands (`dd`, `blockdev` ... uh that's it) are available in RHEL's `initrd.img` which means they're guaranteed to be available in the Anaconda/kickstart `%pre` environment. Thank you!
Answer: FreeBSD utility gpart can do it in this pretty straightforward way:
gpart destroy -F /dev/sdX

Comment: Should this be `gparted` instead of `gpart`?  I didn't find a `gpart` command installed by default, and there's no RPM in the regular CentOS repos.
Comment: Sorry, `gpart` is a FreeBSD tool for managing GPT. I was sure linux have it too.


ExtJS background file upload

Question: I have an ExtJS FormPanel with different form items (textfields, numeric etc) in some cases I need an addtional file upload in this form.
(In my opinion) The best solution would be a extJs filefield in the FormPanel, which starts the upload as soon as a file is selected by the user. After uploading the file successfully (getting {success: true, fileid: 17} from the server) the filefield should disappear and a text message ("File upload was successful") should be shown instead. Additionally to the text message a (new) hidden input with the fileid has to be added to the FormPanel:

User selects file with ExtJs filefield.
Upload is started immediately (onChange).
Server answers with success: true and fileId
Text "File upload was successful" replaces the filefield
hidden form item with fileId is added to the form

Is there any way to achieve this (or a similar solution) with ExtJS 4?
Comment: Short answer - yes. But I don't really think that anybody would write all of the code for you. It would be better if you tried to achieve the task by yourself and then came here with the specific problem.
Comment: What i tried so far is following: http://jsfiddle.net/fdxtK/1/ (The jsfiddle example will not work in jsFiddle cause of the same origin policy)

But i don't know what to do next.
Answer: Easiest way is to wrap filefield in panel and replace content in handler. Example:
var formPanel = Ext.create('Ext.form.Panel', {
    renderTo: 'testdiv',
    title: 'Basic information',
    id: 'schnitzel',
    items: [
        {
            xtype: 'textfield',
            name: 'title',
            fieldLabel: 'Title'
        },
        {
            xtype: 'panel',
            layout: 'fit',
            border: false,
            items: [{
                xtype: 'filefield',
                buttonOnly: true,
                name: 'file',
                onChange: function(value) {
                    var panel = this.ownerCt;
                    formPanel.submit({
                        url: 'index4_submit.php',
                        waitMsg: 'Uploading the image ..',
                        clientValidation: false,
                        success: Ext.Function.bind(panel.onSuccess, panel)
                    });
                }
            }],
            onSuccess: function(form, action) {
                if (action.result.success !== true) {
                    return;
                }

                this.removeAll();
                this.add({
                    xtype: 'label',
                    text: 'File upload was successful'
                });
                this.add({
                    xtype: 'hidden',
                    name: 'file',
                    value: action.result.fileid
                });
            }
        }
    ]
});

ExtJS background file upload


proof that on a compact manifold a vector field is complete

Question: I would like to know if my proof of the following statement is correct

If $M$ is a compact manifold, then every vector field $X$ over $M$ is complete.

Proof:
I take $p\in M$ and $(\gamma_p,I_p)$ a maximal integral curve through $p$. $I_p$ is open and non empty so if $I_p$ is closed, it is equal to $\mathbb{R}$.
So take $s\in \text{Adh}(I_p)$. There exists $t_i\rightarrow s, t_i\in I_p$. Define $q$ as $\text{lim}(\gamma_p(t_i))$ and take a maximal integral curve passing by $q$ as $(\gamma_q,I_q)$. Then since the vector fields are $C^\infty$, $\gamma_q(I_q)\cap\gamma_p(I_p)$ is nonempty (intuitively, this is clear but don't really know how to show it).
On the intersection, $\gamma_p$ and $\gamma_q$ coincide. So we can extend the maximal curve $\gamma_p$ to include $\gamma_q$. This implies that $q\in\gamma_p(I_p)$ and is actually equal to $\gamma_p(s)$
I think the main idea is there even though it probably lacks a bit of rigour.
Comment: (1) Continuity at what point? If you knew $\gamma_p$ were continuous at $t$, then you could conclude $\gamma_p(t_i)\to \gamma_p(t)$ as $t_i\to t$. But you don't even know it's _defined_ at $t$ -- that's what you're trying to prove. (2) If two integral curves pass through the same point, then one is a reparametrization of the other, but they're not necessarily equal. What point do they both pass through?
Comment: A couple of questions about your proof: (1) How do you know that the sequence $\gamma_p(t_i)$ converges? (2) How do you show that the two integral curves coincide where both are defined?
Comment: (1) by continuity of $\gamma_p$? (2) In my course we have a result that says that if two integral curves pass by the same point, then they coincide in their intersections (by showing that it is non empty, open and closed)
Comment: Your title is not a correct reflection of the question. To say that a _manifold_ is complete means that it is endowed with a complete Riemannian metric. Your question is about showing that a _vector field_ is complete.
Comment: One can also find a proof in Milnor's book Morse Theory on page 10 and the following.
Answer: As Jack Lee is already addressing the flaws of your proof, I thought I would drop a complete proof of the statement, so it is at hand for everyone having a question on it.
First, let us work out a general statement:

Proposition. Let $M$ be a smooth manifold and $X$ be a vector field on $M$ with a local flow given by $(\phi_t)_t$. Assume that there exists $\varepsilon>0$ such that $\phi$ is defined on $]-2\varepsilon,2\varepsilon[\times M$, then $X$ is complete.

Proof. For all $t\in\mathbb{R}$, let $k(t)$ be the integer part of $t/\varepsilon$, then one has:
$$t-k(t)\varepsilon\in[-\varepsilon,0]\subseteq]-2\varepsilon,2\varepsilon[,$$
so that one can define the following diffeomorphism of $M$:
$$\psi_t:={\phi_{\varepsilon}}^{k(t)}\circ\phi_{t-k(t)\varepsilon}.$$
For all $x\in M$, since $k(0)=0$, one has:
$$\psi_0(x)=\phi_0(x)=x.$$
Furthermore, for all $s\in\mathbb{R}$, one has the following equality:
$$\begin{align}\frac{\mathrm{d}}{\mathrm{d}t}_{\big\vert t=s}\psi_t(x)&=\frac{\mathrm{d}}{\mathrm{d}t}_{\big\vert t=s}{\phi_{\varepsilon}}^{k(s)}\circ\phi_{t-k(s)\varepsilon}(x),\\&=\frac{\mathrm{d}}{\mathrm{d}t}_{\big\vert t=s-k(s)\varepsilon}{\phi_{\varepsilon}}^{k(s)}\circ\phi_t(x),\\&=T_{\phi_{s-k(s)\varepsilon}(x)}{\phi_{\varepsilon}}^{k(s)}\left(\frac{\mathrm{d}}{\mathrm{d}t}_{\big\vert t=s-k(s)\varepsilon}\phi_t(x)\right),\\&=T_{\phi_{s-k(s)\varepsilon}(x)}{\phi_{\varepsilon}}^{k(s)}(X(\phi_{s-k(s)\varepsilon}(x))),\\&=T_{\phi_{\varepsilon}(\phi_{s-k(s)\varepsilon}(x))}{\phi_{\varepsilon}}^{k(s)-1}(T_{\phi_{s-k(s)\varepsilon}(x)}\phi_{\varepsilon}(X(\phi_{s-k(s)\varepsilon}(x)))),\\&=T_{\phi_{\varepsilon}(\phi_{s-k(s)\varepsilon}(x))}{\phi_{\varepsilon}}^{k(s)-1}(X(\phi_{\varepsilon}(\phi_{s-k(s)\varepsilon}(x)))),\\&=T_{{\phi_{\varepsilon}}^{k(s)}(\phi_{s-k(s)\varepsilon}(x))}{\phi_{\varepsilon}}^0(X({\phi_{\varepsilon}}^{k(s)}(\phi_{s-k(s)\varepsilon}(x)))),&\\&=X(\psi_s(x)).\end{align}$$
Therefore, by the unicity part of Picard-Lindelöf theorem, $\phi=\psi$ and $\phi$ is in fact defined on $\mathbb{R}\times M$. Whence the result. $\Box$
Remark. The key point of these computations is that $\phi$ preserves $X$, for all $t$ such that $\phi_t$ exists and $x\in M$:
$$T_x\phi_t(X(x))=X(\phi_t(x)).$$
Which is almost tautological, since by the very definition of the flow, one has:
$$X(\phi_t(x))=\frac{\mathrm{d}}{\mathrm{d}t}_{\big\vert s=t}\phi_s(x)=\frac{\mathrm{d}}{\mathrm{d}t}_{\big\vert s=0}\phi_t\circ\phi_s(x)=T_{\phi_0(x)}\phi_t\left(\frac{\mathrm{d}}{\mathrm{d}t}_{\big\vert s=0}\phi_s(x)\right)=T_x\phi_t(X(x)).$$
Another thing to notice is that for all $t$ sufficiently close to $s$, $k(t)=k(s)$.
From there it is easy to derive the desired result.

Corollary. Let $M$ be a compact smooth manifold and $X$ be a vector field on $M$, then $X$ is complete.

Proof. Let $p\in M$, using the existence part of Picard-Lindelöf theorem, there exists $\varepsilon_p>0$ and $U_p$ an open neighborhood of $p$ in $M$ such that $\phi$ the flow of $X$ is defined on $]-\varepsilon_p,\varepsilon_p[\times U_p$. By construction, $\{U_p\}_{p\in M}$ is an open cover of $M$, which is compact, hence there exists $p_1,\ldots,p_k$ in $M$ such that $\{U_{p_i}\}_{1\leqslant i\leqslant k}$ is still a cover of $M$. Let then define the following existence time:
$$\varepsilon:=\min_{1\leqslant i\leqslant k}\varepsilon_{p_i}>0,$$
by construction, for all $i\in\{1,\ldots,k\}$, $\phi$ is defined on $]-\varepsilon,\varepsilon[\times U_i$, therefore on the whole $]-\varepsilon,\varepsilon[\times M$. Whence the result using the above proposition. $\Box$
Comment: @AguirreK The equality $\phi_t\circ\phi_s=\phi_{t+s}$ means nothing if $s,t$ and $s+t$ are not in the domain of definition of the flow! The aim of this discussion is to prove that $\phi$ is indeed a global flow and not only a local flow. The idea for defining $(\psi_t)_t$ comes from the well-known formula you mentioned.
Comment: Oh, I see. Last question: the functions $k(t)$ and $t-k(t)\epsilon$ are not smooth, so how do we gurantee $\psi_t$ is smooth?
Comment: I don't understand the definition $\psi_t:=\phi_\epsilon^{k(t)}\circ \phi_{t-k(t)\epsilon}$. By the property $\phi_t\circ \phi_s=\phi_{t+s}$, this definition just says $\psi_t=\phi_{k(t)\epsilon +t-k(t)\epsilon}=\phi_t$, right? What am I missing?
Comment: Obviously, $\psi_t(x)$ is differentiable in $x \in M$. Also, in $t$: If $k(t)$ jumps one integer, then, looking at the definition of $\psi_t=\phi_\varepsilon^{k(t)}\circ\phi_{t-k(t)\varepsilon}$, you find out that, exactly because of the property you mentioned, we get for $z \in \mathbb{Z}$, that $\text{lim}_{t \to \varepsilon z}\frac{\psi_{\varepsilon z} - \psi_t}{\varepsilon z-t}$ exists.


Comments - Allow deletion of comments on your content without Administer Comments permission?

Question: Is there a way to allow users to delete comments that are on their own content without giving access to Administer Comments?
Example:
Authenticated user makes a blog post (or some node content)
Another Authenticated user comments on it
Author does not like comment- wishes to delete.
The only option I have is edit/reply.
Answer: Should be doable with the User Comment module in Drupal 6, or the Comment Access module in Drupal 7. They both add permissions so that authors can approve, delete or administer comments on their own content.
Answer: Another way would be the use of the nodecomment module with Drupal 6. This way you have permission by contenttype like delete own MYCOMMENT content


pub build fails due to urlencoded version numbers

Question: Pub build  throws the following error
Resolving dependencies...
Error on line 1, column 1 of
https://pub.dartlang.org/api/packages/source_maps/versions/0.10.0%2B2:
Invalid version constraint: Could not parse version

It seems pub tries to update https://pub.dartlang.org/packages/source_maps version to 0.10.0+2. The url contains version number and its encoded from + sign to %2B.
pub version 1.6.0,
OS Fedora 19, Any ways to overcome this?
Comment: Sounds like a bug. Can you please report at http://dartbug.com ? I think I have seen something similar recently. I guess you are using Windows?
Comment: OS Fedora 19, Just tried Ubuntu 14.04 also, got the same error. No idea on Windows.
To reproduce in an existing project try removing pup-cache and also the pubspeck.lock file and build freshly.
Answer: Pub version 1.6.0 didn't yet support the + in version constraints.
You need to update to a newer version.
Comment: Yes the answer from dartbug.com to update 1.9.1
https://code.google.com/p/dart/issues/detail?id=23061


How to detect multivariate binomial distributions?

Question: I tried the hartigans dip test, and it works well for univariate distributions. However, when i tried taking each variable (dimension) and applied hartigans dip test (assuming that if along one dimension/variable its bimodal the whole distribution is bimodal) it did not work. As an example, this is how my bimodal distribution looks like.
Can you please help me with any other way in which i can detect multimodality in my data?
Answer: You could apply the hartigans dip test on the data projected onto the first principle components (PCA) explaining most of the variance. Especially for the bimodal scenario this allows to highlight the multimodality.
Comment: Thanks for the response. So do you mean, find the first principal component using PCA on the complete multivariate data, and then project each dimension onto the principal component and then apply hartigans to each? or apply hartigans test to the principal component itself?
Comment: I was a little confused, i multiplied the resulting coefficients (Rotational matrix) with the original data and obtained the desired data. Thanks for the help.
Comment: You are welcome, happy that I could answer your question. Would you mind to rate it +1? ;-)
Comment: Sorry, i am not reputed enough for my +1 to be displayed. But thanks for the help.


Minimum points to guarantee qualification where top two qualify

Question: Related to this question, what is the minimum points required to guarantee qualification for Euro 2016 in a five or six team group? In a four team group with home and away games and the top two qualify (as in the Champions League) you must have 13 points to guarantee qualification?
Answer: For six teams 25 points, for five teams, 19 points.
If you have six teams there are 30 games, so maximum 90 points to play for. Assuming every game is won by a team where; the bottom team wins none, the second bottom beats only the bottom team (6 points) and the third team beats on the two lower placed team (12 points). That leaves 72 points, to be split between the three top teams who all beat the lowest three teams and each other once.

24
24
24
12
6
0

In a five team league there are 20 games, so 60 points to play for, same sort of logic applies, working up from the bottom team.

18
18
18
6
0
Comment: @gbianchi That's still not the point - the question is what is the minimum number of points you need to guarantee qualification *even if every other result makes it as hard as possible for you*.
Comment: No. If all games are draws, for five teams, then only 8 points will be necessary.
Comment: @MFornari that's sort of miss the point, as it is conditional on other results going in the favour of a qualified team. To guarantee qualification you must consider the worst (not the best) possible set of results in all other games.
Comment: It feels to me that you should be able to generalise this to `n` teams fairly easily at this point.
Comment: Then in a five teams draw, you could qualify with 10 points, 7 draws and a win...  and all other matchs finished ties


ListViews within ScrollView overlaps my TextViews

Question: I've seen a lot of problem related to mine, however, none of those have worked. I am currently designing a view where I have four ListViews within a ScrollView, and I want to make the whole ScrollView scroll, while all items in the ListViews are showing. That is no problem; however, the listviews keep overlapping my headertexts for the different listviews.
I've tried with both margins and paddings; none of which whom work. I've also tried to remake the scrollLayout into a LinearLayout. I've also tried to put the texts within separate LinearLayouts, separated from the ListViews, but that does not work either.
Below is my src code. Does anyone know how to make the text to not overlap with the Top item in the listViews? Btw, the "Top Result", the one up above, works totally fine.

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/scrollView"
    android:layout_alignParentTop="true">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/scrollLayout">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:id="@+id/topResultLayout">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/topResultTitle"
                android:textSize="20sp"
                android:textIsSelectable="false"
                android:layout_alignParentStart="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:textColor="#000000" />

            <ListView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/topResultList"
                android:layout_below="@id/topResultTitle"/>

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:layout_centerHorizontal="true"
            android:id="@+id/streamResultLayout"
            android:layout_below="@id/topResultLayout">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/streamResultTitle"
                android:textSize="20sp"
                android:textIsSelectable="false"
                android:layout_alignParentStart="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:textColor="#000000" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/seeAllStreams"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:textColor="#000000"
                android:textSize="14sp"
                android:layout_above="@+id/streamResultList" />

            <ListView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/streamResultList"
                android:layout_below="@id/streamResultTitle"/>
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:layout_centerHorizontal="true"
            android:id="@+id/broadcasterResultLayout"
            android:layout_below="@id/streamResultLayout">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/broadcasterResultTitle"
                android:layout_alignParentStart="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:textSize="20sp"
                android:textIsSelectable="false"

                android:textColor="#000000" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/seeAllBroadcasters"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"

                android:textColor="#000000"
                android:textSize="14sp" />

            <ListView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/broadcasterResultList"
                android:layout_below="@id/broadcasterResultTitle"/>
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:layout_centerHorizontal="true"
            android:id="@+id/tagResultLayout"
            android:layout_below="@id/broadcasterResultLayout"
            android:layout_alignParentBottom="true">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/tagResultTitle"
                android:layout_alignParentStart="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:textSize="20sp"
                android:textIsSelectable="false"
                android:textColor="#000000" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/seeAllTags"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:textColor="#000000"
                android:textSize="14sp" />

            <ListView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/tagResultList"
                android:layout_below="@id/tagResultTitle"/>
        </RelativeLayout>
    </RelativeLayout>
</ScrollView>

Comment: Never use `ListView` inside `ScrollView` and vice-versa
Comment: listview itself a scroll kinda view
Comment: Well looks fine xml wise I think, what are you using to expand it? I use the code below.
Answer: public static void setListViewHeightBasedOnChildren(ListView listView, ListAdapter adapter)
    {
        ListAdapter listAdapter = adapter;

        if (listAdapter == null) {
            return;
        }

        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
        int totalHeight = 0;
        View view = null;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            view = listAdapter.getView(i, view, listView);
            if (i == 0) {
                view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, ViewGroup.LayoutParams.WRAP_CONTENT));
            }
            view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
            totalHeight += view.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight;
        listView.setLayoutParams(params);
        listView.requestLayout();
    }

Comment: Thank you, that does work like a charm. Still some problems however. It only shows one out of three items of the first ListView, the streamResultList. Do you perhaps know what causes that? Also, the last still did not work, so I added a padding top of 20dp, and the TextViews and the ListView within the tagResultLayout got separated. However, a small part of the last item in tagResultList vanished. Can I add some space within the ListView in your function? perhaps in the loop, something like if (i == listAdapter.getCount()) ?
Comment: I fixed the first problem now, so I see all the streams. However it still does not work to click on seeAll in the last section. The padding makes it impossible to click on it unfortunatley, even though the padding fixes the layout issue. Do you know how to fix that? Thank you very very much for your help btw!


Have I gone about this proof in a clear way?

Question: Prove that if $f$ is uniformly* continuous on a bounded set $S \in \mathbb{R}$, then $f$ is a bounded function on $S$.
Assume that $f$ is not continuous on a bounded set $S \in \mathbb{R}$. By the Bolzano-Weierstrass theorem, $f$ has a convergent subsequence because it is bounded. Since $f$ is bounded and has a convergent subsequence, it must be Cauchy. That is,
$$f(x_{n_k}) \to L \implies x_{n_k} \to L_0$$
Since $x_{n_k}$ is Cauchy, it must be continuous, which is a contradiction to our assumption.  $\square$
* corrected
Comment: Isn't $1/x$ on $(0,1]$ a counterexample?
Comment: Ah shoot. I see my mistake. It's meant to be uniformly continuous. Based on what I posted, yes, that would be a counterexample.
Answer: As far as I understood, you are trying to prove that $f$ is a bounded function on $\mathbb{R}$. Then why did you start with the statement $f$ is not continuous on a bounded set $S$?


Are all keys created equal?

Question: Often when I have been composing, I have noticed a peculiar phenomenon.  Sometimes I can't think of a new way to tweak my song and it helps to change the key. I get new ideas and can then switch back to my original key.  But it matters a lot which key I switch to. There is usually one or two other keys that have a similar feel to the current one I am in.
Are there any scientifically substantiated theories about the differences between keys? Why might only a few keys preserve the original feel of my song?
For example, I have found Ludivico Eindaudi's song Nuvole Bianche (originally in A flat major) sounds very similar in A major but sounds terrible in G major and acceptable in C major.
I also find that it is necessary to listen to several stanzas. If you listen to just a few bars, the keys all sound pretty similar and pleasant. It is only over the course of the song it becomes clear the song is in the wrong keys.

Discussion of the probe tone method:

The subsequent Krumhansl and Kessler (1982) study used this method with a variety of musical contexts at the beginning of the trials. They were chosen because they are clear indicators of the key. They included the scale, the tonic triad chord, and chord cadences in both major and minor keys. These were followed by all possible probe tones in the chromatic scale, which the listeners were instructed to judge in terms of how well they fit with the preceding context in a musical sense. Different major keys were used, as were different minor keys, but the results were similar when transposed to a common tonic. Also, the results were similar independent of which particular context was used. Consequently, the data were averaged over these factors. We call the resulting values the K-K profiles, which can be expressed as vectors. The vector for major keys is: K-K major = <6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88>. The vector for minor keys is: K-K minor = <6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17>.
We can generate K-K profiles for 12 major keys and 12 minor keys from these. If we adopt the convention that the first entry in the vector corresponds to the tone C, the second to C#/Db, the third to D, and so on, then the vector for C major is: <6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88>, the vector for C# major is: : <2.88, 6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29>, and so on. The vectors for the different keys result from shifting the entries to appropriate number of places to the tonic of the key.
Krumhansl and Kessler (1982) then used these data to study how the sense of key develops and changes over time. They used ten nine-chord sequences, some of which contained modulations between keys. Listeners did the probe tone task after the first chord, then after the first two chords, then after the first three chords, and continued until the full sequence was heard. This meant that 12 (probe tones) x 9 (chord positions) x 10 (sequences) = 1080 judgments were made by each listener. Each of the 90 probe tone ratings were compared with the ratings made for the unambiguous key-defining contexts. That is, each set of probe tone ratings was correlated with the K-K profiles for the 24 major and minor keys. For some of the sets of probe tone ratings (some probe positions in some of the chord sequences), a high correlation was found indicating a strong sense of key. For other sets of probe tone ratings, no key was highly correlated which was interpreted as an ambiguous sense of key.
Comment: @MatthewRead However, that doesn't mean I did a good job writing this question. If you have any suggestions for points I should clarify to make it better, I am more than happy to rewrite it.
Comment: possible duplicate: http://music.stackexchange.com/q/32438/28
Comment: After skimming through it, it seems none of the answers there provide any sources or evidence. The topic really isn't similar in that I am not trying to get information about emotion or color or anything of that sort. I am asking what objective properties people have found about switching keys. I also do not regard timbre as important in this regard as a reason for choosing a key necessarily. I have worked with synthesizers where range does not matter and found this phenomenon I mentioned holds.
Comment: In 12et, it shouldn't make a difference, but obviously it does. Are you actually playing the piano in different keys, or transposing using that magic button? That may make some difference. While reading the question, instruments came to mind: guitar can sound quite different when a key is changed, losing open strings, for example. One of my 'party pieces' is The Entertainer, C in one hand, C# in the other. Now that sounds different...
Comment: I have done both. I have played them on a real piano and also done it with synthesizers. It didn't really matter, I observed the same effect. However, I have not used any other instrument besides piano. Also, why should it be the same? Mathematically, yes all keys are equivalent, but neurologically/neuropsychologically, each key could be perceived differently to some extent by the perceptual system. What evidence do you have to support the brain treats all keys equally? I'd love to see it if it exists. That would be very interesting.
Comment: The only evidence I have is my own experience, which says any key sounds like any other, on piano at least. In isolation, a piece could be transposed by a few semitones, and I probably wouldn't notice. When depping, I have to play pieces in different keys (usually to accommodate vox), and I can't feel or hear any differences. But that's me, not you. If I heard classical stuff in a different key, apart from knowing, usually, that it's been transposed, it still sounds the same - to me.
Comment: I've begun to suspect most musicians, and maybe everyone, have at least a vague sense of absolute pitch or a touch of inaccurate perfect pitch. We're not sure why C major feels different from Eb major, but we often have a vague sense or feeling that they are different. Just one person's theory that would explain a lot about my musical experiences as well as those of many people I've talked to about music.
Comment: De gustibus non disputandum.    However, when you write for something other than piano,  the natural resonances of each kind of instrument will play into the choice of notes (and thus key signature).
Comment: I don't want to post this as an answer because it's just a link and might not be there for ever, but there was an excellent series on this very topic on BBC Radio 4 which is still available on their website.  There are 15 episodes in total each one about a different key and the way it has been used by composers. It's well worth a listen -> http://www.bbc.co.uk/programmes/b00tw55v/episodes/player
Answer: Some possible answers, although it's probably impossible to answer properly.

Depending on the tuning system of your instrument, there may be differences in relative pitches. Though on instruments with equal temparament tuning there should be none. On a synthesizer it's probably really really accurate.
Depending on your instrument the quality (overtones, loudness, how long they keep resonating, how they begin/end, etc.) of the tones will change depending on which one you choose, so different keys will sound different
You'll have some measure of absolute pitch hearing no matter what. If the difference is large enough that should make a difference
You know you changed the pitch, together with some randomness source in your head. This just sometimes helps to open a new door in your mind.

Are all keys created equal?


Android: Clicking on an image to switch to another image

Question: What's a good way, both layout- and codewise, to accomplish the following:

Display one or more clickable images on the screen.
By default, the images are default images (duh)
When clicking on them, they change to a specified image
When clicking again, the change back to the default image

I cannot set all the images in the xml layout file(s), since I must be able to programatically set and change the images when clicking, and keep a record of the images on display etc.
In case anyone wonders: Yes, this is supposed to be a simple "memory" game, where I show x images, and click on two of them to display them, and give a result if they're identical.
Answer: I would suggest you to use ImageSwitcher, as the view, and setOnClickListener on the ImageSwitcher, to apply image changes on click action.
Comment: I can't really find any good examples of using imageswitcher without gallery, which seems to be the primary use for it? To begin with, I just want to display ONE image on the screen, and decide programatically which image. Then I want to display another image in its place, set programatically, when the image is clicked.


How to call a function with structure (C++)

Question: My code is not working because I have a problem with the call of my two functions when I use a structure. I think I didn't call it correctly but I'm not sure if the problem is here or in the definition itself.
Here is my code:
#include <stdio.h>
#define NUM 3

    struct student{
        char name[20];
        int kor;
        int math;
        int eng;
        int sum;
        double avg;
        double avg2;
        double k, m, e;
};

void average(student* st)
{
    int i, sum = 0;
    for(i=0;i<NUM;i++) {
    st[i].sum= st[i].kor + st[i].math + st[i].eng;
    st[i].avg= st[i].sum / NUM;
    }
}

void average2(student* st)
{
    int i, sum = 0;
    double K, M, E;
    for(i=0;i<NUM;i++) {
        K+= st[i].kor;
        M+= st[i].math;
        E+= st[i].eng;
    }
}

int main(void)
{
    student stu[NUM]={{"Tom"},{"Jane"},{"Eddy"}} ;
    int i;
    int max;
    double K, M, E;
    printf("Input scores.\n");
    for(i=0;i<NUM;i++)
    {   printf("\n<%s>\n",stu[i].name);
        printf("Korean:");
        scanf("%d",&stu[i].kor);
        printf("Math:");
        scanf("%d",&stu[i].math);
        printf("English:");
        scanf("%d",&stu[i].eng);
    }
    printf("\nName\tKorean\tMath\tEnglish\tSum\tAverage\n");
    average(stu);
    for(i=0;i<NUM;i++)
        printf("%s\t%d\t%d\t%d\t%d\t%.2f\n",stu[i].name,stu[i].kor,stu[i].math,stu[i].eng,stu[i].sum,stu[i].avg);

    average2(stu);
    printf("Average %.2lf\t%.2lf%.2lf\n", k/3, m/3, e/3);
}

Thank you in advance for your answers, Coco
Comment: `for` needs a scoped block to enclose more than one statement
Comment: But you have even *worse* problems, because you don't initialize some of the local variables before using them you have [*undefined behavior*](http://en.wikipedia.org/wiki/Undefined_behavior). The value of uninitialized (non-static) local variable is indeterminate.
Comment: C++ is not Python, indentation is only to increase readability and has no syntactical or semantic purpose.
Comment: Please show what actually happened, and what you expected instead. Does it compile? Does it run but crash?
Comment: There is no need to do `typedef struct student student;` in C++, that is only needed in C.
Comment: Thank you for your aswers, as usual, you're a big help! I'll try to fix the rest myself
Answer: for loops should have { and } to enclose more than one line in c++.
for(i=0;i<NUM;i++)
{
    st[i].sum= st[i].kor + st[i].math + st[i].eng;
    st[i].avg= st[i].sum / NUM;
}

Also in your function average2 it is not clear what you are exactly doing.
You are declaring same variable in main and average2 double K, M, E; so the function will take local variable only.
For your second printf here is the logic.,
for(i=0;i<NUM;i++) {
    K+= st[i].kor;
    M+= st[i].math;
    E+= st[i].eng;
}
printf("Average %.2lf\t%.2lf%.2lf\n", K/3, M/3, E/3);

Comment: Thank you for your answer, I did change the for statement. I understand that I need to declare a different variable in main and average2, but I don't know how should I write it in the last printf section.
Comment: Yes, I just saw that, thank you so much for your help!


How to simplify units with different scales in SymPy

Question: In sympy.physics.units identical units automatically simplify when they are used in equations. However, when units are different scales of the same dimension, they are not automatically simplified. For example:
from sympy.physics.units import *

(5000 * gram) / (2 * gram)
# 2500

(5 * kilogram) / (2 * gram)
# (5 * kilogram) / (2 * gram)

5 * gram + 1 * kilogram
# 5*gram + kilogram

5 * gram + 1000 * gram
# 1005*gram

1000*liter/(5000*liter)
# 1/5

1000*liter/(5*meter**3)
# 200*liter/meter**3

Is there an easy way to force unit simplification, at least in cases where the units are different scales of the same dimension?
I am looking for the same effect as using .subs() on all the units, just automated to use the information already contained in the expression, equivalent to
((5 * kilogram) / (2 * gram)).subs({gram: gram, kilogram: 1000 * gram, ...})

Answer: The issue of scale can be solved by print_unit_base method of the unit system. For example,
from sympy.physics.units.systems import MKS
expr = (5 * kilogram) / (2 * gram)
new_expr = expr.xreplace({q: MKS.print_unit_base(q) for q in expr.atoms(Quantity)})

Now new_expr is 2500.
A simpler function to use is convert_to(expr, kilogram) (which also returns 2500) but this depends on knowing that units of mass are an issue. print_unit_base uniformizes all units of the given unit system.
With liter, since it's not really a prefixed-meter-cubed, we need convert_to:
expr2 = 1000*liter/(5*meter**3)
convert_to(expr2, meter)     #  1/5


Problem with integer field format in Drupal 7

Question: I just created an integer field for one of my content types. I'm using it to display a value for a year. However, when it is displayed, it is putting in a space between the 1000s column and the 100s column; so, for example, "1991" is displayed as "1 991".
I'm guessing this is something to do with the formatting of the field. Can anyone tell me how I can correct this or change the formatting?
Answer: Go to the "Manage display" tab and edit "Thousand marker".
Comment: Thank you kalabro, I didn't realise it was so obvious! I was busy look for a complicated solution! :)


How to groupby only the top n% rows of another column by group in pandas?

Question: I have a df like this:
df = pd.DataFrame({'Date': ['01','01','01','01','01','02','02','02','02','02','02','03','03','03'], 'ID': ['a','b','c','d','e','a','b','e','f','g','h','b','e','g'], 'RESULT': [5,6,7,4,8,2,2,4,7,13,2,6,7,7], 'SALES': [100,150,120,130,200,140,150,100,120,110,180,170,120,100]})

I want to groupby the average of results by date, but only for the IDs that have the top 20% sales. Then, the expected results should be:

My original df is much larger, about 4,5 million rows, so I would need an efficient code.
I found other similar answers, but none of them address my problem.
Thank you very much in advance.
Answer: Try this: not sure if it'll be fast enough but it should be
df.groupby('date').apply(lambda x : x[(x['SALES'] >= x['SALES'].quantile(0.8))]['RESULT'].mean())

Answer: Another way by rank():
df[df.groupby('Date')['SALES'].rank(pct=True).gt(0.8)].groupby('Date')['RESULT'].mean()

Date
01    8
02    2
03    6


How to write junit of init()?

Question: Hi I am a beginner in junit's and I got stumbled upon the junit of init() method which I defined in my servlet.
Here is my servlet.
  public class EmailSendingServlet extends HttpServlet{

        private static final long serialVersionUID = -7796409155466523414L;

        /**
         * Creates an Email Model Object
         */
        Email emailMessage = new Email();

        /**
         * Overrides the init constructor of servlet
         *
         */
        public void init() {
            ServletContext context = getServletContext();
            emailMessage.setHostName(context.getInitParameter("host"));
            emailMessage.setPortName(context.getInitParameter("port"));
        }
        /**
         * Overrides the Service method of Generic Servlet
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            emailMessage.setFrom(request.getParameter("from"));
            emailMessage.setRecipient(request.getParameterValues("recipients"));
            emailMessage.setSubject(request.getParameter("subject"));
            emailMessage.setBody(request.getParameter("body"));
            emailMessage.setFile(request.getParameterValues("file"));

            String resultMessage = "";

            try {
                EmailUtility.sendEmail(emailMessage);
                resultMessage = "The Email was sent successfully";
                request.setAttribute("message", resultMessage);
                response.setContentType("text/html");
                RequestDispatcher view = request.getRequestDispatcher("/Result.jsp");
                view.forward(request, response);

            } catch (Exception e) {

                e.printStackTrace();
            }
        }

and given below is the test case of my servlet class:
@RunWith(PowerMockRunner.class)

    public class EmailSendingServletTest extends Mockito
    {

        @Test
        public void TestEmailSendingServlet() {

            HttpServletRequest request = mock(HttpServletRequest.class);
            HttpServletResponse response = mock(HttpServletResponse.class);
            RequestDispatcher requestDispatcher = mock(RequestDispatcher.class);

            when(request.getParameter("from")).thenReturn("email@example.com");
            String[] recipients = new String [3];
            recipients[0] = "email@example.com";
            recipients[1] = "email@example.com";
            recipients[2] = "firstname.lastname@example.com";
            when(request.getParameterValues("recipients")).thenReturn(recipients);
            when(request.getParameter("subject")).thenReturn("Test Mail");
            when(request.getParameter("body")).thenReturn("This is Body");
            String[] files = new String[1];
            files[0] = "C:\\Users\\asara3\\Documents\\Architecture.jpg";
            when(request.getParameterValues("file")).thenReturn(files);
            when(request.getRequestDispatcher("/Result.jsp")).thenReturn(requestDispatcher);

            try {
                new EmailSendingServlet().doPost(request, response);
            } catch (ServletException e) {

                e.printStackTrace();
            } catch (IOException e) {

                e.printStackTrace();
            }

        }

I am bit confused to stub the context.getInitParameter("host") in my test case ? Any help guys ?
Comment: There shouldn't be any init() method. The emailMessage variable should be a local variable of doPost(). Remember that the same unique instance of your servlet handles all the requests to that servlet concurrently. You don't want two requests to write to the same EmailMessage object.
Comment: Note: don't catch the exception in your test case. This test will currently pass if an exception is thrown. Add `throws` to the test method signature.
Comment: @AndyTurner Thanks for the suggestion. Will take care of that .
Comment: @JBNizet . Thanks for the suggestion. I thought of this way that when the servlet is going to initialise, the container takes all the parameters in DD (irrespective of either it is in config or context) and gives to the init(). So, I included the init() method just to be sure that the correct smtp settings goes into this.
Answer: You could use the spy() method of Mockito to mock the behavior of the getServletContext() method.
For example add this in your setup() method or in the constructor of the unit test class :
public class EmailSendingServletTest {
  ...
  private EmailSendingServlet emailSendingServlet;
  private EmailSendingServlet emailSendingServletSpy;
  ...

  public EmailSendingServletTest(){
    emailSendingServlet =  new EmailSendingServlet();
    emailSendingServletSpy = Mockito.spy(emailSendingServlet);
  }
}

Then you may mock the getServletContext() method like that :
Mockito.doReturn(yourMockedServletContext).when(emailSendingServletSpy.getServletContext());

Generally I avoid spying (that mocks the object under test) but in the case of third-party dependency as servlet, it is an acceptable case as refactoring is not able or else it forces us to write no standard changes in the way the third-party dependency is used. Which is often undesirable too.
Comment: Hi david, Thanks for the suggestion . What exactly do I need to spy ? What is this mail service ? I am getting confused.
Comment: Hello, you are welcome. Sorry typo. I updated. You have to spy `emailSendingServlet`, the object under test as explained :)
Comment: So did I tried. It's not working. Throwing Unfinished stubbing exception when I am trying to mock getServletContext() :

private EmailSendingServlet servlet;

 @Test
 public void TestEmailSendingServlet() {

   servlet = new EmailSendingServlet();
   servlet = Mockito.spy(servlet);
   ServletContext context = mock(ServletContext.class);
   Mockito.doReturn(context).when(servlet.getServletContext());
   when(context.getInitParameter("host")).thenReturn("localhost");
   when(context.getInitParameter("port")).thenReturn("25");
Comment: Try by using another variable for the spy object. I updated. And why do you use PowerMock ? Do you really need it ??? It doesn't seem. If  you don't need it remove it as it may create side effect.

How to write junit of init()?


Missing the message status when saving Node

Question: Of the handful of content types on our site, some of them don't display the message status (ex. Article Test has been created) when the node is saved.
Where can I investigate the cause?
Answer: This message comes from node.pages.inc (never edit Drupal core) in a form submit function and I believe messages are stored in the $_SESSION['messages'] variable. I would try to get at these with a hook_form_alter() and custom validation and submit handlers to see where it might be dropping.
If you're running any custom code look specifically for interactions with the $_SESSION variable. Clobbering or unsetting it could prematurely remove these messages.
If you use the devel module you can simply use the following.
dd($_SESSION['messages']); //Logs to drupal logs
dpm($_SESSION['messages']); //Outputs debug information to screen

You can also create your own messages using drupal_set_message()
For example:
drupal_set_message(t('It worked!'), 'status');

You may also want to check that you don't have something like the Disable Messages module installed or misconfigured.
Comment: Also, I would check the theme is really printing those messages.
Answer: It may also be necessary to insert a drupal_get_messages() statement in hook_node_insert(), hook_node_submit() or if you are using tpl files for the nodes then place that in the tpl file or any form callbacks. Not sure why it would work for other content types but not others though.


Ray problem (geometry)

Question: Problem:

Two plane mirrors $OP$ and $OQ$ are inclined at an acute angle (diagram is not to scale). A ray of light $XY$ parallel to $QO$ strikes mirror $OP$ at $Y$. The ray is reflected and hits mirror $OQ$, is reflected again and hits mirror $OP$ and is reflected for a third time and strikes mirror Magic Square Association $OQ$ at right angles at R, as shown. The distance $OR$ is $5$cm. The ray XY is d cm from the  mirror $OQ$. What is the value of $d?$

My thoughts: the answer says its 5, but I am not sure how to specifically construct the triangles or angles and sides to be able to solve the question. I did write a bunch of angles but Im not sure how to proceed. Can anyone help me solve this problem?
Answer: In problems involving mirrors it often becomes much easier if you draw the reflected world behind the mirror, because then you can just ignore the mirror as the rays go straight through it into the mirror world.
In the picture below, Q is reflected in P to give Q', P is reflected in Q' to give P', and Q' is reflected in P' to give Q''. The light ray travels straight through these mirror worlds and meets Q'' at right angles. By the way, this shows that the angle between the mirrors must have been 90/4=22.5 degrees (though in the original drawing the angle is a bit off so the reflections in the picture below are a little wonky). It is now also obvious that OR=OR'=OR''=d.
Answer:
Let $\angle PYX= \theta$. Then $\angle AYC=90^\circ-2\theta \implies \angle YAC=2 \theta \implies 4\theta=90^\circ, \theta=22.5^\circ$
Next, $d=YA \sin 2\theta, YA=AB \cot \theta, AB=\frac{BR}{\sin 2\theta}, BR=5 \tan \theta \implies d=5$
Answer: Let the first, second and third reflection take place at the points $Y, S$ and $T$. respectively. Define point $V$ to be the foot of the perpendicular from $Y$ to $OQ$.
Observe, $$\theta=\angle TOR=\angle OYS=22.5^{\circ}~~\text{and} ~~\angle SYV=\angle YSV=\angle TSR=45^{\circ}$$
Hence,
$$TR=RS=5\tan \theta\implies \tan\theta=\frac{VY}{OV}=\frac{d}{5+5\tan\theta+d}$$
Answer: The total angle reflected ( $\gamma= 90 ^{\circ} $) is given. we could unfold a stack to obtain a "development" of the reflection scenario as given:
Let the number of mirrors be $m$. The number of points of incidence is also $m$. Draw a sector on a thin transparency sheet dividing total angle $\gamma$ by $m+1$ into so many sectors or vertical angles.
Denting each reflecting edge by a sharp steel edge or needle and alternatively folding along the green reflecting mirror edges makes a stack given in the question which can be unfolded to get back the "development."
Even a print on paper can be folded from this rough sketch as in Origami.

Ray problem (geometry)


Join database tables using foreign key laravel

Question: I have two tables that I need to join in order to access more data. My first table thought_journal_entries contains many id values from the second table emotions. The primary key in emotions is id and the foreign key in thought_journal_entries is em_id.
This is in the Emotions model
public function thoughtJournalEntry() {
    return $this->belongsTo(ThoughtJournalEntry::class, 'id');
}

This is in the ThoughtJournalEntry model
public function emotions() {
    return $this->hasMany(Emotions::class, 'id');
}

This is how far I've got, not sure if this is correct and how I would join these in the controller?
Answer: If you set em_id in thought_journal_entries table, that means that thoughtJournalEntry belongs to Emotions, and Emotions hasMany thoughtJournalEntry, so in this case relations must be declared this way
// Emotions class
public function thoughtJournalEntries() {
    return $this->hasMany(ThoughtJournalEntry::class, 'em_id');
}

// ThoughtJournalEntry class
public function emotion() {
    return $this->belongsTo(Emotions::class, 'em_id');
}

// access from controller
$emotion->thoughtJournalEntries;
$thoughtJournalEntry->emotion;

If this type of relations is not what you wanted, then probably you have to change your db tables


Conversion failed when converting date and/or time from character string - but no idea why

Question: I have  the following table:
USE [junglegymSQL]
GO

ALTER TABLE [dbo].[UserSession] DROP CONSTRAINT [FK_UserSession_UserID]
GO

ALTER TABLE [dbo].[UserSession] DROP CONSTRAINT [DF__UserSessi__Creat__5CA1C101]
GO

ALTER TABLE [dbo].[UserSession] DROP CONSTRAINT [DF__UserSessi__Creat__5BAD9CC8]
GO

/****** Object:  Table [dbo].[UserSession]    Script Date: 16/09/2013 3:44:55 PM ******/
DROP TABLE [dbo].[UserSession]
GO

/****** Object:  Table [dbo].[UserSession]    Script Date: 16/09/2013 3:44:55 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[UserSession](
    [UserId] [int] NOT NULL,
    [SessionId] [varchar](500) NOT NULL,
    [Created] [datetime] NOT NULL,
    [CreatedBy] [varchar](50) NOT NULL,
    [LastModifed] [datetime] NULL,
    [LastModifiedBy] [varchar](50) NULL,
 CONSTRAINT [PK_SessionID] PRIMARY KEY CLUSTERED
(
    [SessionId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[UserSession] ADD  DEFAULT (user_name()) FOR [Created]
GO

ALTER TABLE [dbo].[UserSession] ADD  DEFAULT (getdate()) FOR [CreatedBy]
GO

ALTER TABLE [dbo].[UserSession]  WITH CHECK ADD  CONSTRAINT [FK_UserSession_UserID] FOREIGN KEY([UserId])
REFERENCES [dbo].[User] ([UserId])
GO

ALTER TABLE [dbo].[UserSession] CHECK CONSTRAINT [FK_UserSession_UserID]
GO

Which I'm trying to write to using the following PHP:
$sessiontoken = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));

// Save our cookie 'qcore' with the users session id
setcookie("qcore", $sessiontoken);

$query = "
    INSERT INTO dbo.UserSession (
        UserId ,
        SessionId
    ) VALUES  (
        :userid ,
        :sessionid
    )
";

$query_params = array(
    ':userid' => intval($row['UserId']),
    ':sessionid' => $sessiontoken
);

try
{
    // Execute the query to create the user
    $stmt = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
    // Note: On a production website, you should not output $ex->getMessage().
    // It may provide an attacker with helpful information about your code.
    // die("Failed to run query: " . $ex->getMessage());
    die("Failed to run query: " . $ex->getMessage());
}

However each time I do this, I  receive the following error:

Failed to run query: SQLSTATE[22007]: [Microsoft][SQL Server Native
  Client 11.0][SQL Server]Conversion failed when converting date and/or
  time from character string.

I've checked, and the following line is returning an integer:
':userid' => intval($row['UserId']),

and given that my second column is a varchar, well, I'm confused. Why am I seeing this error when I'm not working with dates at all and I'm passing an integer value?
Answer: Your column Created is of type datetime and you are using a Varchar as default.
ALTER TABLE [dbo].[UserSession] ADD  DEFAULT (user_name()) FOR [Created]

looks like you reversed Created and CreatedBy.
Answer: Have you specified the date format ??
Select CONVERT(Date, '17-9-2013', 105)

105 stands for (dd-mm-yyyy).
Please refer http://msdn.microsoft.com/en-us/library/ms187928.aspx


Change NSTexfield focus by pressing Enter key

Question: In my OS X App, how can I change the NSTextField focus by pressing the Enter key instead of pressing the Tab key?
Comment: What u want to do? Tab key switch focus to the next control by default in OS X and Enter - end editing.
Comment: I want press ENTER key to end editing and switch focus to the next control simultaneously. Is it Possible?
Answer: You may use NSText - (void)textDidEndEditing:(NSNotification *)aNotification delegate method, where you should use NSWindow's makeFirstResponder: to change the current first responder. See the NSResponder class reference for details on this.
First set delegate of your firs textField to self. Then in same class:
- (void)textDidEndEditing:(NSNotification *)aNotification {
     NSLog(@"delegate method");
    [self.window makeFirstResponder:[[[aNotification object]window]nextResponder]];
}

I assume that you do this in AppDelegate class.
Comment: I tried to use this method:

- (IBAction)changeFocus:(id)sender
{
    NSResponder*resp=[sender nextResponder];
    [myWindow makeFirstResponder:resp];

}

and link this action to my Textfield press ENTER key, but it doesn't work -
??
Comment: Are u shure the method will invoke?
Comment: yes I'm sure, it seems that the [sender nextResponder] does not work
Comment: Try to NSLog your "resp" NSLog(@"next resp = %@",resp);
Comment: The response of NSLog is:  - how do I see which control is?
Comment: @user3313512 Add a user identifier to the control.
Comment: I realized that when invoke [sender nextResponder] -(sender is my NSTextfield)- the nextResponder is the NSView that contain all my textfield. At runtime instead when I press TAB key the focus change from one Textfield to another- suggestions? thx


Python Typing: Type[UnionType]

Question: I am having a function safe_cast which casts a value to a given type, but raises if the value fails to comply with the type at runtime:
from typing import TypeVar

T = TypeVar('T')

def safe_cast(t: type[T], value: Any) -> T:
    if isinstance(value, t):
        return cast(T, value)
    raise TypeError()

This works nicely with primitive types. But I run into problems if I want to safe_cast against a UnionType:
string = "string"
casted: str | int = safe_cast(str | int, string)

The instance check works with a union type. But my solution does not work, because mypy gives me
error: Argument 1 to "safe_cast" has incompatible type "UnionType"; expected "Type[<nothing>]"  [arg-type]

I figure that <nothing> refers to the unspecified type variable T here. I also figure that apparently mypy cannot resolve Union[str, int] to Type[T]. My question is: How can I solve this?
I looked into creating an overload for the UnionType. IIUC, in order to write the overload, I would need to create a Generic Union Type with a variadic number of arguments. I failed to get this done.
Is this the right direction? If yes, how do I get it done? If no, how can I solve my problem with safe_casting Union types?
Answer: typing.cast is likely to be special-cased in a type-checking implementation, because while this works in mypy,
import typing as t

if t.TYPE_CHECKING:
    reveal_type(t.cast(str | int, "string"))  # mypy: Revealed type is "Union[builtins.str, builtins.int]"

the type annotations for typing.cast don't actually do anything meaningful with union types:
@overload
def cast(typ: Type[_T], val: Any) -> _T: ...
@overload
def cast(typ: str, val: Any) -> Any: ...
@overload
def cast(typ: object, val: Any) -> Any: ...

What you'd actually want to do is to exploit the magic that your type-checker-implementation already offers. This is very easily done by making typing.cast your typing API, while making your safe_cast the runtime implementation.
import typing as t

T = t.TypeVar("T")

if t.TYPE_CHECKING:
    from typing import cast as safe_cast
else:
    # Type annotations don't actually matter here, but
    # are nice to provide for readability purposes.
    def safe_cast(t: type[T], value: t.Any) -> T:
        if isinstance(value, t):
            return value
        raise TypeError

>>> reveal_type(safe_cast(int | str, "string"))  # mypy: Revealed type is "Union[builtins.int, builtins.str]"

Comment: That is not just a great answer to my question, but also an interesting pattern I will remember for the future.
Answer: i have the same problem, and apparently it is not possible to express this currently: https://github.com/python/mypy/issues/13498
but there is something in the works to allow this: https://github.com/python/mypy/issues/9773
for now i am doing the equivalent of this when passing in a type union:
casted: str | int = safe_cast(cast(type, str | int), string)

since i know using a type union will work with my code

Python Typing: Type[UnionType]