How i can best deploy an application from git to forge that requires an entry in the .env file?

Question: I have a Laravel app that uses a socialite custom provider to connect an oAuth2.0 API.
I would like to use Forge to deploy this simply, on the regular.I cannot however, figure out how to do it, as there is a required entry in the .env file for the Socialite provider. If it is not there, it fails.
I have tried using the inbuilt environment editor, but you can only do it once it has been pushed to forge.
Now obviously I shouldn't commit my .env file, so what is the best way around this?
Answer: Ok after much deliberation, I tried without installing composer dependencies and forge just created the entries in the ENV file automatically....err I feel outsmarted, but in a nice way. Thanks forge! :)


Set default value for Enity Reference using View and Entity Reference View Widget Checkbox

Question: Basically i have a field (in line item(commerce custom product)) with Field type: Entity Reference and Widget:View. The view is a list of terms and has an aditional field type:Entity Reference View Widget Checkbox to provide a checkbox in so user could configure the product.
The whole chain works fine from user point of view but there is no option to set the default value (in UI) and the option to set the default value from hook_form_alter() is not giving the needed result.
This is hook_form_alter:
function test_form_commerce_cart_add_to_cart_form_3_alter(&$form, &$form_state, $form_id){

    $form['line_item_fields']['field_pesonal_data']['und'][0]['field_cover']['#default_value']=6;

}

Please provide a solution. Thx!
Answer: Did you try casting the value to a string?  I had to do that when I was setting default values for a user reference field type.  It wouldn't work otherwise. Something like
 $form['line_item_fields']['field_pesonal_data']['und'][0]['field_cover']['#default_value']=(string)6;

Also, I noticed that you had a spelling error.  You had 'field_pesonal_data' It should probably be 'field_personal_data'
Also, I was a little confused by your use of terminology.  You described that the user is configuring the entity reference field on the product.  Did you mean configuring the entity on the line item?  I just wanted to clarify, because if you are modifying the form that governs the adding of products (or product variations in Commerce Kickstart 2.0), you need to use a different form alter call because the product variation creation form uses the inline_entity_form module to manage the specific product variations.
That call is:
function hook_inline_entity_form_entity_form_alter(&$entity_form, &$form_state)

Look at the inline_entity_form.api in the contrib/inline_entity_form folder in Commerce Kickstart 2.0
for modifying a user reference on a product, I did the following:
function bh_vendor_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  global $user;
  if ($entity_form['#entity_type'] == 'commerce_product') {
    $entity_form['vendor_user_reference']['und']['#default_value'] = (string)$user->uid;
  }
}

My widget I used was a option list.
You have to have the ['und'] or it won't work either.
Comment: "field_pesonal_data" is fine, no mistake was made

The user is configuring the product by choosing some options, those options are supplied by line item type (are multiple options so using product variation would become a huge task).

Now I tested in hook_form_alter() to set the default value for a textfield and it works as any other form_alter so this concludes that the problem is Widget:View and Entity Reference View Widget Checkbox which seesm to have no support for such things.


Diferença entre './', '../' e '/'

Question: Em alguns códigos que trabalho, as vezes não existe uma variavel global que aponte para a raiz do projeto, tal como:
$RAIZ='PATH/EXAMPLE/';

Então frequentemente usam:
src='./somePath';
src='../somePath';
src='/somePath';

Qual a diferença?
O que acontece com arquivos de outros diretorios que foram incluidos (include) e precisam acessar recursos do diretorio local?
Exemplo:
|a.php -> inclui ('pasta/b.php')
|pasta/b.php -> acessa ('img.png')
|pasta/img.png

Comment: Uma dica off amigo, para evitar problemas com inclusões de diferentes locais, o melhor é colocar o caminho todo nos includes. Como por exemplo `define('FULL_PATH', dirname($_SERVER['SCRIPT_FILENAME']) . '/'); include FULL_PATH . 'pasta/meu-arquivo.php';`. Use este `define` apenas em um arquivo na pasta raiz do teu projeto, para acessar está "constante", inclua ela em uma arquivo global e inclua este arquivo em outros :)
Answer: Cada um desses muda a forma como um diretório é referenciado.
Suponhamos um arquivo teste.txt:

/teste.txt: significa que o arquivo teste.txt está na pasta raiz do sistema;
./teste.txt: significa que o arquivo teste.txt está na mesma pasta que o script está rodando;
../teste.txt: significa que o arquivo teste.txt está na pasta imediatamente acima da pasta em que o script PHP está rodando.

Em qualquer linguagem de programação, é sempre importante referenciar arquivos em relação ao diretório raiz da aplicação, e não em relação ao sistema, para evitar confusões. Com isso você garante portabilidade à aplicação, que pode rodar em qualquer sistema ou estrutura de diretórios, independente de seu sistema de arquivos.
Comment: Sua última frase define tudo, na aplicação sempre ter o caminho absoluto pode ajudar a evitar muitas dores de cabeça +1
Answer: Tendo a estrutura de pasta a baixo:

Levando em consideração que estou no arquivo conteúdo.html e quiser incluir o arquivo horas.html, como os dois estão no mesmo no mesmo nível de pastas então eu deverei usar:
include "./horas.html";

Para incluir o arquivo dicas.html que está na pasta recursos deverei usar:
include "./recursos/dicas.html";

Já que a pasta recursos está no mesmo nível que conteúdo.html
Agora para incluir o arquivo catálogo.html que está na pasta produtos deverei usar:
include "../produtos/catálogo.html";

Sendo assim eu irei subir um nível entre as pastas e a partir daí inserir o caminho do arquivo desejado.
Mas sabendo que a pasta produtos é uma pasta que está na pasta raiz eu posso usar:
include "/produtos/catálogo.html";

Sendo assim
Em src='./somePath'; o ./ significa que você está referenciando à pasta atual
Em src='../somePath'; o ../ significa que você está referenciando uma pasta anterior a atual. Você pode utilizar vários para buscar em pastas em níveis diferentes.
Exemplo:
src='../../../otherPath'; aqui estou buscando a pasta otherPath em uma pasta que está 3 níveis acima da pasta onde o script atual está rodando.
Em src='/somePath'; 0 / significa que você está se referenciando à pasta raiz do sistema
Answer: Uma maneira simples:
Considere a Pasta Raiz como DirZero...
No arquivo que está sendo trabalhado (independente do Diretório), e irá incluir o arquivoincluido.php que está dois níveis abaixo da raíz:
include ($_SERVER['DOCUMENT_ROOT'].'/DirNivel1/DirNivel2/arquivoincluir.php');

Diferença entre './', '../' e '/'


go time.Now() not giving proper time

Question: I am running this simple go program and expecting to get different time (a difference of 3-second period) for starting and shutdown logs as I have given sleep of 3 seconds, but I am getting same time.
package main

import (
    "fmt"
    "time"
)

const (
    logInfo = "INFO"
    logWarning = "WARNING"
    logError = "ERROR"
)

type logEntry struct {
    time time.Time
    severity string
    message string
}

var myLogChannel = make(chan logEntry, 50)

func main() {
    go logger()
    myLogChannel <- logEntry{ time.Now(), logInfo, "App is starting" }
    time.Sleep(3 * time.Second)
    fmt.Println("Time is :", time.Now().Format("2006-01-02 15:04:06"))
    myLogChannel <- logEntry{ time.Now(), logInfo, "App is shuting down" }
    time.Sleep(2 * time.Second)
}
func logger() {
    for entry := range myLogChannel {
        fmt.Printf("%v : [%v]: %v\n", entry.time.Format("2006-01-02 15:04:06"),entry.severity, entry.message)
    }
}

Output:
On my system (running under cygwin env):
2020-10-12 11:03:20 : [INFO]: App is starting
Time is : 2020-10-12 11:03:20
2020-10-12 11:03:20 : [INFO]: App is shuting down
On playground:
2009-11-10 23:00:09 : [INFO]: App is starting
Time is : 2009-11-10 23:00:09
2009-11-10 23:00:09 : [INFO]: App is shuting down
Comment: Note that the Playground has no real time.
Comment: A better way to check time difference will be  t:= time.Now(); and then check time elapsed as time.Since(t)
Comment: I changed the time.Now().Format as:
time.Now().Format("2006-01-02 T 15:04:05")
Now it's giving correct results. I am a toddler in go..so need to check more about this.
Answer: Your time format is wrong. 06 is the last two digits of the year, so it is printing 20 for 2020. Use the format: 2006-01-02 15:04:05

go time.Now() not giving proper time


Harp - "Half Pedal"

Question: I know from Kurt Stone's book Music Notation in Twentieth Century:

Hold pedal halfway between two notches to allow the string to vibrate against the tuning gear.

So, how exactly is half pedal executed on the harp? (if possible suggest a sound file or video demonstrating that)
Answer: From an executional standpoint, it helps to know how the harp's mechanism works.
The harp's pedals are laid into a zig-zag pathway, and have the same kind of spring tension in an upwards vertical direction as a piano pedal. However, the pedals can also be moved side-to-side to go through this pathway. When the pedal is all the way up, it can be pressed  vertically down and horizontally away from the center of the instrument to rest on the next notch in the zig-zag. From here, there is one more notch where the pedal can rest, again, by pressing down and away.
The harp's strings are anchored to a tuning peg at the top of the instrument, and can be altered up in pitch by half steps by small rotational mechanisms that grab the strings between two pegs. There are two of these mechanisms per string, allowing for a range of two half-steps of alteration.
Each pedal corresponds to a set of strings on the harp (all the same pitch in multiple octaves). When the pedal is all the way up, the alteration mechanisms are both open, so the full string is vibrating all the way to the tuning peg. Moving the pedal down to the first notch actuates the first mechanism, which rotates to grasp the string between two pegs at a half step. Essentially, it's like a fret, except instead of pressing the string over the fret, the fret is grabbing the string. The second notch on the pedal actuates the second mechanism, raising the pitch of those strings a second half step.
So then, the half pedal technique involves only rotating the peg mechanism (tuning gear) so that it comes in contact with the vibrating string, but doesn't shorten the vibrating length. It would be like striking a note on the guitar and then lightly brushing your fingernail on the string without dampening it fully. The harpist would execute this by moving the pedal vertically until the gear starts touching the string, but not so far that it can be rested on the next notch. Since this is going to be different for each harp, this definitely constitutes an "extended technique", and I concur with @jjmusicnotes that the sound of this will be very subtle. I'll suggest it might best be used in a solo harp setting.
Comment: Good explanation - just want to clarify that the pedal *automatically follows* the zig-zag pattern when depressed, so there is no option to move them side-ways. The movement corresponds with the three positions: pedal up = 1st position (flat) / pedal middle = 2nd position (natural) / pedal down = 3 position (sharp.) Each pedal affects **all** corresponding notes across the instrument - aka each "pitch class." Therefore, the standard (and most resonant) tuning for a concert harp is Cb major.
Comment: So, I assume this works best on *lower strings* since the decay time is longer which makes the effect more audible.
Answer: First off, the Kurt Stone is a great notational resource, so kudos for introducing that resource to this site.  I'd also suggest Gardner Reed's 20th Century Notation as well.
To get the best sense of this sound, I would highly suggest talking to a harpist and hearing the effect in real life.  The difference is akin to seeing a picture of a famous painting, and then actually seeing the painting in real life - there is subtlety and nuance that a photograph (or in this case, a recording) cannot capture.
Orchestrationally, I can tell you that this is a very subtle effect and will be most effective if the scoring is extraordinarily thin or if supported somehow - perhaps by a sizzle cymbal or perhaps paperclips being dropped on a suspended cymbal or tossed against a tam-tam. (Now I'm getting ideas!)
But all the same, talk to a harpist and get them to show you (and if you're really lucky, ask them to show you how to hold / play the harp. Harpists love it when composers at least attempt to write thoughtfully for their instrument!)
Comment: Very true! Good point - I assumed the OP was a composer since they referenced the Kurt Stone; typically only composers know about the Kurt Stone.
Comment: Nice answer. The OP never mentioned anything about being a composer, which you seem to assume that they are (as opposed to an interested Harp player). However, this "mistake" (forgive me if it was purposeful, just makes your answer more applicable to future viewers. Thank you!

Harp - “Half Pedal”


MLE for mean of symmetric but otherwise unknown distribution

Question: Given i.i.d. draws $x_1,...,x_n$ from $X$, where:

$X$ has a finite mean $E[X]=\mu < \infty$,
$X$ is symmetric about its mean, meaning $f_X(\mu+c)=f_X(\mu-c)$ for all $c$,
The probability density function $f_X$ is not otherwise known.

Is it possible to prove the following?
Proposition. The MLE for the mean of $X$ is the sample mean, $\hat \mu_{MLE}=\bar x = \sum_{i=1}^n x_i$.
A proof or a counterexample would be great. I am willing to additionally assume that $X$ has a finite variance $Var[X]=\sigma^2 < \infty$, or other common basic assumptions, if that becomes necessary for the proposition to hold, or if it greatly simplifies the proof.
I suspect that it may be possible to use the invariance of the MLE to transformations of the data to prove this, but it might follow from simpler facts about the sample mean.
Comment: A [question posted just a few hours ago](http://stats.stackexchange.com/questions/98971/mle-of-a-cauchy-distribution) provides a counterexample (well, it comes close enough: it concerns a distribution without a mean, but it's easily modified to give a counterexample with a mean).
Comment: The difficulty is that the sample itself will rarely be symmetric about *its* mean, so the underlying symmetry of $f_X$ is of little use. Writing $q$ for the derivative of $\log(f_X)$, your requirement implies (among other things) that $\sum_{i=1}^n q(x_i-\bar{x})=0$ for *all* possible samples $(x_i)$. That pretty much limits $q$ to be linear, which means $X$ has a Normal distribution.
Comment: Yes! I updated the question to reflect "sample mean". Thanks for the question from a few hours ago. The Cauchy distribution in that example has an undefined mean, does the counterexample translate to some distribution with a defined mean?
Comment: Your edits beat me to it. I'll take a look at how it can be modified, thanks! I'm still interested in knowing if there are some set of stronger assumptions for which this may hold: log-concave? Something else?
Answer: Consider the single-parameter Exponential Family of distributions, i.e. distributions whose probability density (or mass) function can be written as
$$f(x) = h(x)\cdot \exp{\big\{\eta(\theta)T(x)-A(\theta)\big\}}$$
The log-likelihood from an i.i.d sample of size $n$ is then
$$\tilde L = \sum_{i=1}^n\ln h(x_i) + \eta(\theta)\sum_{i=1}^nT(x_i) - nA(\theta)$$
and the derivative with respect to $\theta$ is
$$\frac {\partial \tilde L}{\partial \theta}=\eta'(\theta)\sum_{i=1}^nT(x_i)-nA'(\theta) = 0$$
$$\Rightarrow  \frac 1n \sum_{i=1}^nT(x_i) = \frac {A'(\hat \theta_{MLE})}{\eta'(\hat \theta_{MLE})}$$
it is obvious from the above that, to arrive at "the sample mean is the MLE for the mean", the involved functions must have suitable forms.
Examples where the result holds
1) For the Normal distribution (with known variance $\sigma^2$) : $T(x_i) = x_i/\sigma$, $A(\theta)=\mu^2 / 2\sigma^2 \Rightarrow A'(\theta) = \mu / \sigma^2$, $\eta(\theta) = \mu/\sigma\Rightarrow \eta'(\theta) = 1/\sigma$
2) For the Bernoulli(p) distribution,  $T(x_i) = x_i$, $A(\theta) -\ln (1-p)\Rightarrow  A'(\theta) = 1/(1-p) $, $\eta (\theta) = \ln(p/(1-p)\Rightarrow \eta'(\theta) = 1/p(1-p)$
In these cases, indeed the MLE for the mean is the sample mean.  It is perhaps easier to find counter-examples, as Whuber hinted.
Comment: You can also add the gamma distribution, parameterised by its mean and dispersion, i.e. $p(x_i)=\frac{1}{x_i\Gamma(\alpha)}\left(x_i\frac{\alpha}{\mu}\right)^{-\alpha} \exp\left(-\frac{\alpha x_i}{\mu}\right)$
Comment: Why are exponential families relevant to the answer of this question? It's not the case that all exponential families belong to the nonparametric model mentioned in the question (the class of all probability distributions with densities symmetric about their mean). Or are you saying: choose an exponential family for which the distributions have densities that are symmetric about their means. (I.e. an exponential family which is a parametric submodel of the nonparametric model from the question.) For one of them the sample mean will not be the maximum likelihood estimator of the mean?


what are the tensor rule for canceling indices in the same tensor variable?

Question: what are the tensor rule for canceling indices in the same tensor variable?
let's say I have a tensor:
$\Huge V^{rs}_{trs}$
textbook says this tensor is equal to:
$\Huge V^{rs}_{trs} = V_{t}$
Which I could believe because it looks like the same letters cancel each other out, but then again. i'm not really sure what's happening here...what's the general rule for canceling out indices on the same variable?  can the indices with the same index variables be in any position in the upper and lower, and if they match can you cancel them out, or do they need to be in specific slots to  cancelling the upper and lower indices of the same term to work?
I'm just going to hit this question with a brute force hammar:
true or false? $\huge V^{ij}_{i} = V^j$
true or false? $\huge V^{ji}_{i} = V^j$
true or false? $\huge V_{ji}^{i} = V_j$
true or false? $\huge V_{ij}^{i} = V_j$
true or false? $\huge V_{i}^{i} = V$
true or false? $\huge V_{ii}^j = V^j$
true or false? $\huge V^{ii}_j = V_j$
all you need to do is copy and paste this section and answer true or false.
Then I will understand the rule.  Thanks.
Comment: They aren't canceling the indices. They are actually summing them out. These are called "contractions" https://en.wikipedia.org/wiki/Tensor_contraction
Comment: Also, when someone writes $V_{ij}^i=V_j$. This is a definition. We are defining a new lower rank tensor by contracting out two indices from a higher rank tensor much in the same  way the trace of a matrix is not the matrix itself but instead is some summary information about it.
Comment: A pedestrian example of a contraction would be $A_i^i$ which is the trace of the matrix $A_i^j$.
Comment: can you contract any index slot with any other index slot in the same tensor variable regardless if its upper or lower index?
Comment: what about all the "non-pedestrian" examples listed... are they all true or are there some exceptions?
Comment: No, unless you have an inner product allowing you to identify your underlying vector space with its dual. Such an isomorphism (between vector space and dual - which is essentially the same thing as specifying an inner product) allows you to raise and lower indices.
Answer: The answer is true on all accounts.  But, there's a caveat... I'll illustrate one example without any deleted steps to show what's happening:
Let's assume this tensor is over $\mathbb{R}^3$:
$\Huge V^{ii}_j = V^{11}_j + V^{22}_j + V^{33}_j = \tilde{V}_j$
Here I'm using the tilde to indicate that $\huge \tilde{V}$ is a different tensor that is the sum of three terms.  However, at this point we drop the use of the tilde for this purpose, instead, we implicitly see that:
any tensor with different tensor ranks in the numerator and denominator is implicitly a different variable even enough though the base letter is the same. thus:
$\Huge V^{ii}_j = V_j$
it would be just as vaild to write the contraction this way as well:
$\Huge V^{ii}_j = W_j$
Both are equivalent, but reusing the same letter saves letters and keeps track of where a tensor variable came from.... its a type of "overloading" of variable names...

Here are the rules for contraction.
Contraction of (2,2) tensor
Suppose $\huge A^{i_1~ i_2}_{j_1~ j_2}$ is a tensor.
Assuming $\mathbb{R}^n$, The contraction of A with respect to $i_2$ and $j_1$, is given by setting $i_2 = j_i = u$ and evaluating:
$\huge A^{i_1~ u}_{u~ j_2}  = A^{i_1~ 1}_{1~ j_2} + A^{i_1~ 2}_{2~ j_2}  + A^{i_1~ 3}_{3~ j_2} =\tilde{A}^{i_1}_{j_2}$
in going from A to $\tilde{A}$ , contravariant rank is reduced by 1, and covariant rank reduced by 1. Thus:
contracting a (2,2) tensors results in a (1,1) tensor.
Contraction of (p, q) tensor
Suppose S is a (p, q) tensor such that $\huge S \equiv \bigg(S^{~i_1~ i_2~ \dots ~i_{\Large p}}_{~j_1~ j_2~ \dots~ j_{\Large q}}\bigg)$.  The contraction of S with respect to a contravariant index $i_f$ and a covariant index $j_g$ is given by setting $\huge i_f = j_g = u$ and evaluating:
$\huge S^{~i_1~\dots~u~\dots~i_{\Large p}}_{~j_1~\dots~u~\dots~j_{\Large q}} = \tilde{S}^{~i_1~\dots~i_{\Large p}}_{~j_1~\dots~j_{\Large q}}$
$\tilde{S}$ is now a (p-1, q-1) tensor.
contracting a (p,q) tensors results in a (p-1,q-1) tensor
Comment: if you beleive wikipedia, it says: " contraction on a pair of indices that are either both contravariant or both covariant is not possible in general. However, in the presence of an inner product (also known as a metric) g, such contractions are possible. One uses the metric to raise or lower one of the indices, as needed, and then one uses the usual operation of contraction. The combined operation is known as metric"... not sure i understand, because i just showed you can contract it... unless there's some reason why that's not valid...
Comment: You can contract that way, its just that the result is generally not a tensor when contracting a pair of covariant indexes, or a pair of contravariant indexes.   To remain a tensor 100% of the time you first need to use a metric tensor to juggle one of the contracting indexes to to be opposite of the other before performing contraction.  that's why they usually ignore this case when talking about contraction because the result is no longer a tensor...and that would be considered an invalid operation if you want stay in tensor land...


Use fundamental identities to write the first expression in terms of the second, for any acute angle θ. sec(θ); sin(θ)

Question: Can someone please help me with the question above? I don't understand what it's asking. A thorough explanation would be much appreciated.
Answer: Using the "fundamental" identity : $\sin^2 x + \cos^2 x = 1 $
$$ \sec^2 x  = \frac{1}{\cos^2 x} = \frac{1}{1 - \sin^2 x} $$
$$ \therefore \sec x = \frac{1}{ \sqrt{1 - \sin^2 x }} $$
Comment: It's worth mentioning that the choice $+ \sqrt{1 - \sin^2 x}$ is where we use that $\theta$ is actue.
Comment: What does it mean to write the first expression in terms of the second? and why did you start out with sec^2x? I understand the trig process that you used to simplify but I don't understand why you used that Pythagorean identity, and I don't understand how you know when you're finished?
Comment: I don't understand haha.


Find the equation of tangent.

Question: Original Question: Find the equation of the tangent at point P of parabola $x^2=4y$, which is at the minimum distance to center of a circle $x^2+y^2+6x+8=0$.
What i did:

Found coordinates of center of circle i.e. $(-3,0)$
Equation of tangent at point $P(h,k)$, $hx-2y-2k=0$.

Now how to proceed further?
Comment: It isn't clear to me at all. The title seems little more than a restatement of part of the problem. Please show your work.
Comment: The general formula for tangent at given point (h,k) for this parabola will be $xh = 2(y+k)= 2(y+\frac{h^2}4)$. Now,apply distance formula to get distance between this line & (-3,0) and minimize that distance to know the points of parabola
Comment: @AloknathFurr did you get the formula by taking derivative?
Comment: Your perception of question is wrong. It is asking for the minimum distance between tangent line & centre of circle. Not between point of parabola and centre of circle.
Comment: For a general line ax+by+c =0, distance between this line & some point $(x_0,y_0)$ is defined to be length of perpendicular from the point to the line and is given by $d = \frac{ax_0 + by_0 +c}{\sqrt{a^2+b^2}}$
Comment: Hint: minimum distance is zero.
Comment: @amd no it isn't. the parabola and circle never touch so the minimum distance is greater than 0.
Comment: Hint: The normal line to the parabola at a point must pass through the circle's center for the distance to be minimized.
Comment: Minimum distance can still be zero, as the tangent to parabola may still pass through centre of circle. In fact, it is coming out to be zero.
Comment: @ChristopherMarley The question is not clearly worded. You're reading it as requiring the point on the parabola to be at a minimal distance; I'm reading it as requiring the tangent line to be at a minimal distance.
Answer: You really don't need the distance formula to solve this problem. Just a clear and intuitive understanding of geometry. Remember that if you have a line in space, and a point not on that line, the shortest distance between point and line make a right angle. Because of this property, the shortest distance between the circle's center and the parabola should make a right angle. That is to say, the normal line of the parabola must pass through the circle's center.
So first, we must find the equation of the normal to the parabola $y=x^2/4$. Simple enough, we can use point-slope form: $y-y_0 = m(x-x_0)$ where we'll plug in our point $(a, a^2/4)$. The slope of a normal line is the inverse reciprocal of the tangent. $y' = \frac{x}2$ --> normal slope = $-\frac2x$.
Equation of normal line: $y-\frac{a^2}4 = -\frac2a(x-a)$.
This normal line at point $a$ must pass through the center of the circle, which you've found (correctly) to be $(-3,0)$. So... Plug and solve!
$$0-\frac{a^2}4=-\frac2a(-3-a)$$
Simplify
$$-\frac{a^2}4=\frac6a+2$$
I multiplied by 4a
$$-a^3=24+8a$$
$$a^3+8a+24=0$$
This has one solution, at $a=2$. At that point is the minimum distance between the parabola and the center of the circle. On the parabola, this would be the point $(2,1)$. Now we can find the tangent line at that point! Remember, slope of the tangent line is $\frac{x}2$.
$y-1=\frac22(x-2)$ ------> $y=x-1$
https://www.desmos.com/calculator/w3y243i0qm
Comment: Thanks it really helped
Comment: I changed my question before viewing your answer, Sorry for that.And i appriciate the time you spent for making graph
Comment: i am also in high school, are you on facbook or twitter ?so i can share my future math problems with you.
Comment: $a=-2$ , hence $x+y+1=0$, Anyways i just wanted the algorithm
Comment: Glad this helped @Aman, and for future math problems, always use Math SE. Great place to get help, and I might pop up again! You're welcome!

Find the equation of tangent.


iPhone Security for Businesses

Question: After much negotiation with AT&T Business (and tremendous pressure from dissatisfied BB users) we recently switched from BlackBerries to the ubiquitous iPhone. How best can we secure the data on the iPhones to help prevent a mis-placed phone from being a major problem?
I know there's the Mobile Me service that can remotely wipe the phones, but setting up and managing dozens of accounts (and PAYING for them) is time consuming, costly and not easily centrally managed.
Are there apps out there, or some other way, to help increase iPhone security when used in a business setting? Remote wipe, encryption, etc.
Thanks!!
Answer: I've found the iPhone implementation for business to be pretty good documented on the Apple site: http://www.apple.com/iphone/business/integration/
With the iPhone configuration utility, you can create profiles which help you standardize the installs.  I'd recommend you start documenting your installs/setups and find what the best configuration will be for your business.
For remote wipe, if you are an MS shop and use Exchange, then you're pretty much set as exchange gives you this ability if you have an account created on the phone.
Answer: If you have Exchange 2007 (or 2010 when released) you can remotely wipe any device that is still setup to talk directly to the Exchange server (iPhone, Windows Mobile, etc).
Comment: Does it work for Exchange 2003?
Comment: Yep: "With Exchange Server 2003, you can initiate a remote wipe using the Exchange ActiveSync Mobile Administration Web Tool"
Answer: we're a blackberry shop here at the moment, and l0c0b0x is right.
in regards to remote wiping, I believe even if you're using 2003 server, it works via the activesync service.
provisioning is a heck of a lot easier in my opinion, as you can set up your security profile, host it on a webserver (you need to add a MIME type), browse to it on the iphone and it applies whatever restrictions you set.
update as needed, send an email, people click link. insta-update.
we had a spare iphone that we used for testing from the CEO :)
beats all the annoying blackberry licences, 'bolt ons' and stuff you need to do.
I wouldn't use mobileme, your exchange server will do all that stuff.
data plan required, that's it. you can even turn off youtube if somebody gets tap happy with it via the security settings :)
only thing I'm not happy with is that (at least in my version of iphone config util, was in 2.0) you couldn't specify authorised applications.
it was all apps, or no apps.

iPhone Security for Businesses


Two identical Vista machines, only one processes Group Policy Registry Extension

Question: I have two Panasonic Toughbook CF-30 machines setup from the same installer CD.  Both machines were joined to the domain and moved into the same OU.  Both machines have no errors in the event logs on startup.  One machine gets the 'AutoLogon' group policy which contains the registry entries to get Vista to autologon, the other machines does NO registry processing from any policy that has registry settings.
The working machine logs Event ID 4016 from GroupPolicy which says 'Starting Group Policy Registry Extension Processing.  List of applicable policy objects: (No changes detected.) AutoLogon Policy'
The other machine does not have any events which mention registry processing.
Any pointers on where to dig / what to try next?
Comment: As a wild guess, have you compared the UAC settings on both machines?
Comment: I will double-check that first thing in the morning.
Comment: Sorry for the delay.  I tested both machines with UAC enabled, and both with it disabled.  Same result.
Answer: Stumbled across this article:
http://blog.mpecsinc.ca/2009/05/vista-service-pack-2-not-applying-group.html
Installed KB943729 and now the registry settings are being applied.
Software Update Services says this update is 'installed/not applicable' to the Vista machines, but manually installing it fixes the problem.
Answer: I would start by running gpresult on the Vista machine with the issue.  It will tell you what policys are applied with a lot of other useful troubleshooting information.  Also, have you tried gpupdate /force? Do you have multiple DCs? If you do, then it might be contacting another DC that might not have received the GP changes.
Comment: Thanks for replying Xeon.  Sorry, I should have added that info to the initial question.  Gpresult and the GPMC both show the policy being applied with no errors, and that they are contacting the Windows 2008 DC which is where I made the changes.  I have tried gpupdate /force and rebooting many times during the testing.  I have also made sure the toughbooks are plugged in to the LAN instead of attempting this wirelessly.


Python 3 KeyboardInterrupt Multithreading

Question: I am trying to have a main thread wait for its worker threads to finish using the following code, but when I try to interrupt it with Ctrl+C it doesn't stop
import threading
import sys
exit = threading.Event()

#pass it to the threads

try:
    exit.wait()
    print('Goodbye')
    sys.exit()
except KeyboardInterrupt:
    print('Interrupted')
    sys.exit()

UPDATE
Nothing prints. All background threads are daemons.
Comment: There was a formatting error. Fixed
Comment: What platform are you on? On Linux or macOS (unless you're using 3.0-3.1, which are basically broken), I believe all `wait`s on `threading` objects should be interruptible by signals, and, once it's interrupted, Python will immediately process the SIGINT as a `KeyboardInterrupt`. But on Windows… I'm not sure how that works, but you may need something more.
Comment: Also, I assume the main thread _is_ still blocked on that `exit.wait()`, and hasn't yet printed `Goodbye'`, right? (Because otherwise, it's already left the `try`/`except` block, so obviously the `try` can't capture the exception.)
Comment: Daemon thread or not? Does `Interrupted` print?
Comment: I am on Windows. The main thread is still blocked. All my background threads are currently daemons.
Answer: import threading
import sys
import time
exit = threading.Event()

#pass it to the threads

try:
    print("hi")
    time.sleep(20)
    print('Goodbye')
    sys.exit()
except KeyboardInterrupt:
    print('Interrupted')
    sys.exit()

Please try the above statement to test your code. i have tested it and its working fine for me.
As you are using exit.wait() without giving any timeouts, its running for infinite seconds. So please put some time as an agument.
Follow the below code:
exit = threading.Event()

#pass it to the threads

try:
    print("hi")
    exit.wait(5)
    print('Goodbye')
    sys.exit()
except KeyboardInterrupt:
    print('Interrupted')
    sys.exit()

Comment: Thats possible if you will use Loops for that. But using Wait() its impossible.
Comment: I am trying to have the main thread wait indefinitely unless interrupted, ideally without simply have a while loop running checking for a flag.
Comment: Is that possible??


Using an array inside a constructor using Javascript

Question: I've been trying to find a way to correctly define an array as one of the constructor values. Let's say we have a student and we need to have an array with his grades and then using the array we need to get an average from the student's grades. Sadly, I only found some threads addressing this in other programming languages.  This is what I thought would work:
function student(name, surname, number, grades) {
this.name = name;
this.surname = surname;
this.number = number;
this.grades = [];
this.average = function(grades) {
 var sum = 0;
 for(var i = 0; i < grades.length; i++) {
  sum + = grades[i];}
  var average = sum / grades.length;
  return average;
 }
}

And then
var student1 = new student("Peter","Cat",14444,[2,3,4]);
console.log(student1);

Unfortunately, it shows my grades array as blank and I can't see if my average function is working properly. Which part(s) should I change so that I would actually have some values in the grades array?
Thank you.
Comment: `this.grades = [];` Shouldn't that be `this.grades = grades`?
Answer: You have a couple things messed up. If you are going to pass the grades array in as an argument, then you need to set grades with this:
this.grades = grades;

Also in the average function you need to refer to grades with this.grades not just grades. This will allow you to add more grades later and still get the correct average. You could also consider making the grades optional by defining the constructor with something like:
function student(name, surname, number, grades =[])

Then if you don't pass in a value, an empty array will be waiting for you.
In the end you might have something like:

function student(name, surname, number, grades = []) {
  this.name = name;
  this.surname = surname;
  this.number = number;
  this.grades = grades;
  this.average = function() {
    return this.grades.reduce((a, c) => a + c, 0) / this.grades.length
  }
}

var student1 = new student("Peter", "Cat", 14444, [2, 3, 4]);
console.log("Average: ", student1.average())

// add another grade:
student1.grades.push(6)
console.log("New Average: ", student1.average() )
Answer: You can solve same problem by using ES6, in your code, you are initializing this.grade=[] with an empty array inside function so further processing of average will be done on empty array only. For good practice, function parameters should be assigned with a default value, so that if mistakenly we do not pass an array as an argument then the function parameter will use the default value. Attaching code snippet for easy understanding in ES6.
class std{
constructor(name, surname, number, grades = []) {
    this.name = name;
    this.surname = surname;
    this.number = number;
    this.grades = grades;
}

average() {
  if(this.grades.length !== 0){
    return this.grades.reduce((previous, current) => previous + current, 0) /
    this.grades.length
  } else { return "no grades mentioned"; }
 }
}

var student1 = new std("Peter", "Cat", 14444, [1, 3, 4]);
console.log("Average: ", student1.average());
//add new student
var student2 = new std("Prasanna", "Test", 14444);
console.log(student2);

//student2.grades.push(7)
//console.log("New Average: ", student2.average() )

Answer: You're already passing grades into the student() function, so you don't need to pass it in to the student.average function (as the inner function will already have access to the outer function parameter). Because of this, you also don't need to set this.grades = [].
Also, sum + = grades[i] should be sum += grades[i].
Simply fixing this error, then omitting passing grades into the inner function will correctly show the average, as can be seen in the following:

function student(name, surname, number, grades) {
  this.name = name;
  this.surname = surname;
  this.number = number;
  this.average = function() {
    var sum = 0;
    for (var i = 0; i < grades.length; i++) {
      sum += grades[i];
    }
    var average = sum / grades.length;
    return average;
  }
}

var student1 = new student("Peter", "Cat", 14444, [2, 3, 4]);
console.log(student1.average());
Answer: Your initialization of the variable is an empty array.
this.grades = [];

Should be
this.grades = grades;

However, I recommend that you study some javascript ES6 / ECMAScript 2015 and use classes.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
class Student {
  constructor(grades) {
    //... Other code
    this.grades = grades;
  }
}

Answer: you can use this line :

function student(name, surname, number, grades){ }

instead of this:

function student(name, surname, number, grades = [ ]){ }

function student(name, surname, number, grades) {
  this.name = name;
  this.surname = surname;
  this.number = number;
  this.grades = grades;
  this.average = function() {
    return this.grades.reduce((a, c) => a + c, 0) / this.grades.length
  }
}

var student1 = new student("Peter", "Cat", 14444, [2, 3, 4]);
console.log("Average: ", student1.average())

// add another grade:
student1.grades.push(6)
console.log("New Average: ", student1.average() )
Answer: We can use the Object Method to store the Average value:
function Student(name, surname, number, grades = [])
{
    this.name = name;
    this.surname = surname;
    this.number = number;
    this.grades = grades;

    //Method to calculate the Average
    this.average = function()
    {
        if(this.grades.length !==0)
        {
            //Return the Average Calculation
            return this.grades.reduce((previous, current) => previous + current, 0) / this.grades.length
        }
        else
        {
            //This will return if grades not provided
            return "No Grades Mentioned"
        }
    }

}

//With Grades
var student1 = new Student("Srinivasan", "Raja", 1635, [22,43,67,89,90]);
console.log(student1, "Average: "+ student1.average());

//Without Grades
var student1 = new Student("Denny", "Lawrence", 1635);
console.log(student1, "Average: "+ student1.average());


Can ping servers but cannot connect to them

Question: Sorry in advance if this question is a bit newbi-ish. I downloaded Microsoft Connection Manager and added multiple .rdg files for different servers I need to access. I can browse to only a few of them, but most of them I get the following errors:

Unable to decrypt password
Cannot establish a connection

I have checked the passwords and credentials and they appear to be correct (checked against a collegues' settings). I can ping the servers and I get get a reply from them but cannot connect to them through Connection Manager.
Also, for two of the servers I can navigate to them in the browser (but cannot connect to them in Connection Manager)
As I know very little about servers and networks, I would like to know how I can investigate this further and find out (and fix) why some of them are connecting and some aren't - especially as I can ping them but not connect to them? The main thing that puzzles me is why I can browse to them in the browser for some of the servers, or ping them when they cannot be connected to in Connection Manager.
I have seen a few solutions to similar problems on the net that recommend clearing the tcp ip stack; but I'm not sure if this applies to the above. Could this be related to permissions?
What things can I do to investigate/fix this problem?
Comment: what os's are you connecting to, more then likely its network level auth being required.
Answer: Just because you can ping a system or connect to it through a web-browser does not mean you can connect through other methods. Since you are a "newbie" as you put it, ill explain it in layman's terms. Computers use certain ports to communicate with other systems and to allow communication to their own system. Services run on certain ports to allow connections from other computers. For example, when you connect to Google.com, you use a web-browser which sends out a connection to Google.com (connecting to google) on port 80 (Http) or 443 (Https). I put TO GOOGLE there because your system doesn't use port 80 to send the outbound connection, it is connecting TO GOOGLE on port 80. There is a lot of other stuff that goes on in the background (DNS, NAT, etc.) but I'm trying to keep this as simple as possible.
Depending on the network configuration, perhaps port 80/443 (Http/Https) are allowed through (a firewall, VLAN trunk, etc.) but 3389 (RDP) is not. Maybe the server you are trying to RDP into doesn't even allow RDP connections (no port/service listening). Maybe it should but the exception wasn't added to that systems local firewall or perhaps the standard 3389 port has been changed.
There are a variety of factors but the first thing that comes to mind in MY environment at work is trunking. We have over 25 VLAN's on our Cisco Catalyst 6513 switch. One VLAN is for the commons area (students can use systems) and one is for management. Each VLAN is restricted from the other with certain conditions. Now from the commons, I can ping management systems, but if I wanted to connect through RDP, HTTP, SMTP, SSH, etc. I would not be able to because traffic on those certain ports is not allowed to be passed to those systems on the other VLAN. Trunking can also be directional, i.e. from the management VLAN, I can connect to whatever system on whatever port I want (in the commons) but from the commons, only certain kinds of traffic is allowed through (21,22,80,443,135,137,445, etc.)
First, ensure the system you are trying to RDP into has the Remote-Desktop service listening. After that, ensure that there is an exception in the firewall to allow connections to that service. Determine if you are on the same subnet or not. Can other people RDP into the machine you are trying to RDP into? Are you on the same subnet as the people who can connect to that system?
There are numerous other factors but without knowing your environment, there are various factors which could be the issue. Reseeting the TCP/IP, Winsock stack could help, but unlikely the issue. Could be as simple a ipconfig /release /renew /flushdns or could be as complicated as tunneling traffic.
Comment: yep there are a lot of possibilities and you may have just scared the (you know what) right out of him! Sounds like a typical asp.net user...
Comment: @Blake, thank you for the detailed reply. Yes, other people can access the machine(s) and they appear to have the same environment setup. I will check to see if I am on the same subnet as the other people who can connect to them, I hadn't considered that.
Comment: Doh, I think I might have over thought this issue. If you are receiving the "Unable to decrypt password" you can either retype the password in the properties and save, and/or select store password in clear text. Im sure this will fix your issue. (Ref: http://superuser.com/questions/344081/unable-to-decrypt-password-popup-in-remote-desktop-connection-manager)
Answer: The Problem here is that although you can ping and tracert between two machines [windows] neither machine will recognize the other as anything at all. This means to me that no software capable of handling the connected computers is running. OR, necessary ports are being blocked one way or another. The trick here is to aquire some kind of full duplex software which will run on both machines and be able to recognize the reason for non-connections or non recognition. I see no one making available, stand alone network troubleshooting programs, dedicated to ONLY LAN [NOT INTERNET]. It needs to have its own ETHERNET drivers independant of the operating system.
All I want to do is transfer files between two machines using the ETHERNET and can find no programs easy to use which will do this. CD/DVD/BRD/USB are all too slow. Ethernet is by far the best way I know to do this. I think the big boys make it hard to network locally on purpose.
Comment: That sounds more like a rant than a coherent answer.


Modelar banco de dados de um sistema de amigos

Question: Olá, estou desenvolvendo uma aplicação onde existirá uma opção para adicionar amigos,é bem simples, não é rede social, mas tem que adicionar amigo.
Tenho a tabela usuario.
Quais tabelas e quais relacionamentos tenho que criar para adicionar amigos?
Se alguém mandar um exemplo mais simples e que funcione,mostrar quais tabelas, e quais campos, e quais relacionamentos entre si precisam.
Obrigado
Eu achei um exemplo,acho que resolve minha situação:
1) João faz uma requisição de amizade para Maria
- requestorId = id do Joao
- targetId = id da Maria
- Criar registro na tabela REQUISICAO (requestorId, targetId)
2) Listar as requisições enviadas para a Maria na página dela
- Buscar todos os registros na tabela REQUISICAO quando o targetId for igual ao id da Maria
- Para cada registro montar uma mensagem do tipo (Joao quer ser seu amigo - Aceitar ou não)
3) Maria recusa
- Exclui o registro da tabela REQUISICAO.
4) Maria aceita
- Cria registro na tabela AMIZADE (idJoao, idMaria)
- Exclui o registro da tabela REQUISICAO.
Mas como ficariam os tipos de relacionamento, de qual para qual?
Answer: A meu ver é interessante armazenar o solicitante e o solicitado da seguinte forma
        Usuarios
----------------------------
id_usuario  |  Nome
    1       |  Joao
    2       |  Maria
    3       |  José

                                 Amigos
-------------------------------------------------------------------------
data_solicitadao | id_solicitante | id_solicitado | data_confirmacao
  01/11/2014     |      1         |     2         |     NULL
  01/11/2014     |      2         |     3         |     01/11/2014
  01/11/2014     |      1         |     3         |     02/11/2014
  02/11/2014     |      2         |     1         |     NULL

Eu ainda incluiria se houve recusa de amizade para controlar solicitações em série
Dessa forma, seria possível buscar todos os amigos de um determinado usuário
SELECT *
FROM amigos
WHERE
  id_solicitante = :id_usuario
  OR id_solicitado = :id_usuario
  AND data_confirmacao  IS NOT NULL

E todas as solicitações que um usuário tem pendente para aprovar
SELECT *
FROM amigos
WHERE
  id_solicitado = :id_usuario
  AND data_confirmacao IS NULL

Observaçao
Em termos de performance às vezes é melhor não utilizar o controle por data ou campo nulo e sim por um booleano indexado dependendo de qual engine for utilizar para acessar o MySql. Nesse caso seria bom ter um campo boolean confirmado  separado da data e indexar pelo mesmo
Ter uma flag de rejeição ou data de rejeição é uma alternativa simples e objetiva, além de otimizada de consultar pedidos rejeitados
-------------------------------------------------------------------------------------
data_solicitadao | id_solicitante|id_solicitado|data_confirmacao|aprovado|rejeitado
  01/11/2014     |      1        |    2        |    NULL        |  False |  False
  01/11/2014     |      2        |    3        |    01/11/2014  |  True  |  False
  01/11/2014     |      1        |    3        |    02/11/2014  |  True  |  False
  02/11/2014     |      2        |    1        |    NULL        |  False |  True

Nova proposta
Utilizar um único campo com a situação atual da solicitação (P Pendente, A aprovada R Rejeitada)
-------------------------------------------------------------------------------------
data_solicitadao | id_solicitante|id_solicitado|data_confirmacao| situacao
  01/11/2014     |      1        |    2        |    NULL        |    P
  01/11/2014     |      2        |    3        |    01/11/2014  |    A
  01/11/2014     |      1        |    3        |    02/11/2014  |    R
  02/11/2014     |      2        |    1        |    NULL        |    P

Comment: Obrigado , valeu
Comment: o primeiro bloco de sql é pra saber , a lista de amigos? saber todos os amigos de um determinado usuario.
Comment: No caso da rejeição o que teria q ser feito limpar algum valor?
Answer: Simples, vc teria uma tabela chamada amigos que conteria o id do usuário e o id do amigo, ela seria 1 - n e em cada registro vc colocaria o id do usuário e o id do amigo então se quiser buscar pelos amigos de um usuário faria a seguinte sql:
select * from amigos where id_usuario = X
| amigos    |
| id        |
| id_usuario|
| id_amigo  |
Comment: Ok, mas e a requsição de amizade? teria que ter uma terceira tabela com o nome requisição , como ficaria?
Comment: Eu editei minha pergunta, com um exemplo , agora queria saber como relacionalas


List of well known Claim Type

Question: I'm building a single sign-on service using ADFS. I can't find a complete list of claim types (Ex: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier).
There are some partial lists on Microsoft's website and the Oasis wiki pages. Does anyone know where I can find a comprehensive list?
Comment: [ClaimTypes Members](https://msdn.microsoft.com/en-us/library/microsoft.identitymodel.claims.claimtypes_members.aspx), which was located by internet search for "ADFS claim types"
Comment: Thanks for your help. As I previously mentioned, I found the same list on Microsoft's website and another on Oasis's website. I didn't know if a more comprehensive one exists or if that's it.
Comment: define comprehensive- you can add any claimtype you want with ADFS, more important is what claimtypes you want vs your ADFS will allow
Answer: The Information Card Foundation (ICF) was maintaining such a list at: http://wiki.informationcard.net/index.php?title=Claim_Catalog#Well_Known_Claims
Since informationcard slowly disappeared the site isn't available anymore, too.
Luckily you can still access it, thanks to archive.org: https://web.archive.org/web/20140823181452/http://wiki.informationcard.net:80/index.php?title=Claim_Catalog#Well_Known_Claims
You may also refer to the OASIS Identity Metasystem Interoperability Version 1.0:
http://docs.oasis-open.org/imi/identity/v1.0/os/identity-1.0-spec-os.html#_Toc229451870
(Although that's probably the OASIS source you already discovered)
Answer: Note that your ADFS instance exposes a URL with the well-known configuration.
While perhaps not an exhaustive list it would be the default set of ADFS claim types and a great place to start.
Answer: You can also have a look at my site, where I have collected those often used.

List of well known Claim Type


How do I enable directional lock for a UIScrollView?

Question: I have a UIScrollView with a UIView inside. I want to lock the x-axis so that the view is only scrolled vertically. How do I enable directional locking?
Answer: First, set the UIScrollView's contentSize to have a width that is equal to or less than the width of the UIScrollView's frame.
Next, set UIScrollView's alwaysBounceHorizontal to NO. This will prevent the scroll view from "rubber banding" even though you've told it there's no more horizontal content to display.
UIScrollView *scrollView;
CGSize size = scrollView.contentSize;
size.width = CGRectGetWidth(scrollView.frame);
scrollView.contentSize = size;
scrollView.alwaysBounceHorizontal = NO;

It doesn't matter what's actually inside the scroll view.
Swift 5.0
let scrollView = UIScrollView() // Or however you want to initialize it
var size = scrollView.contentSize
size.width = scrollView.frame.width
scrollView.contentSize = size
scrollView.alwaysBounceHorizontal = false

Comment: This helped me even in Xcode 7. I had to turn off bounce in the storyboard to get the direction lock to work (even though I had direction lock enabled turned on already).
Answer: You'll be subclassing UIScrollView and overriding the touchesBegan:withEvent: method, touchesMoved:withEvent: method, and the touchesEnded:withEvent: method.
You'll use those methods, along with the start and end points of a touch, to calculate what kind of touch event took place: was it a simple tap, or a horizontal or vertical swipe?
If it is a horizontal swipe, you cancel the touch event.
Take a look at the source code here to learn how you might get started.
Comment: Better to inform the scrollview of your intent I think rather than manually cancelling touches yourself. With your approach, if you begin dragging horizontally (even if by accident), you cannot then drag vertically and have it work.
Comment: I was afraid someone would say this...A sure-fire way to lock an axis i'm sure, but I think I'll keep searching for a lazier way to do this. Thanks for your response though. Nick Farina solved my issue by suggesting to:

 First, set the UIScrollView's "contentSize" to have a width that is equal to or less than the width of the UIScrollView's frame.

Next, set UIScrollView's "alwaysBounceHorizontal" to NO. This will prevent the scroll view from "rubber banding" even though you've told it there's no more horizontal content to display.
Answer: #import <UIKit/UIKit.h>

@interface DemoButtonViewController : UIViewController <UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *filterTypeScrollView;
@property (nonatomic, strong) UIBarButtonItem *lockButton;

- (void)lockFilterScroll:(id)sender;

@end

#import "DemoButtonViewController.h"

@implementation DemoButtonViewController

@synthesize filterTypeScrollView;
@synthesize lockButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self)
    {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor darkGrayColor];
    self.filterTypeScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 130, self.view.frame.size.width, 320)];
    filterTypeScrollView.contentSize = CGSizeMake(self.view.frame.size.width*4, 320);
    filterTypeScrollView.pagingEnabled = YES;
    filterTypeScrollView.delegate = self;
    [self.view addSubview:filterTypeScrollView];

    UIToolbar *lockbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 450, self.view.frame.size.width, 30)];
    lockbar.barStyle = UIBarStyleBlackTranslucent;
    self.lockButton = [[UIBarButtonItem alloc] initWithTitle:@"Lock Filter Scroll" style:UIBarButtonItemStylePlain target:self action:@selector(lockFilterScroll:)];
    [lockbar setItems:[NSArray arrayWithObjects:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],lockButton,nil]];
    [self.view addSubview:lockbar];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)lockFilterScroll:(id)sender
{
    filterTypeScrollView.scrollEnabled = !filterTypeScrollView.scrollEnabled;

    if (filterTypeScrollView.scrollEnabled)
    {
        [lockButton setTitle:@"Lock Filter Scroll"];
    }
    else {
        [lockButton setTitle:@"Unlock Filter Scroll"];
    }
}

@end


MySQL Repeatable Read isolation level and Lost Update phenomena

Question: In High Performance Java Persistence book's 220.127.116.11 section it's written that Lost Update phenomena is possible in MySQL Repeatable Read isolation level. This is the screenshot:

Assuming the following(isolation level is REPEATABLE READ):
              tx1                     |                tx2
-----------------------------------------------------------------------------------
START TRANSACTION;                    |
SELECT * FROM test WHERE id = 1;      |
( say, DB_TRX_ID = 7 at this moment)   |
                                      |
                                      |  START TRANSACTION;
                                      |  SELECT * FROM test WHERE id = 1;
                                      |  UPDATE test SET name="x" WHERE id = 1;
                                      |  COMMIT;(say, makes DB_TRX_ID = 10)
                                      |
UPDATE test SET name="y" WHERE id = 1;|
COMMIT;

Question:
Upon tx1 commit will MVCC detect that the row version(DB_TRX_ID) is not equal to 7 anymore(instead it's 10) and perform a rollback ? Or the commit will be succeeded causing a Lost Update ?
Comment: MVCC is by nature optimistic because queries advance in the implementation until a commit conflict occurs. But that doesn't mean optimistic locking is relevant. You keep asking questions about MySQL mentioning locking inappropriately & with other wrong expectations. Don't ask "shouldn't it"--to give an answer we would have to write yet another presentation--that is too broad, and when you don't understand it what do we do then? Instead: Explain exactly what things you think will happen with justifcation per a particular presentation. Then we can tell you where you first go wrong.
Comment: Please [use text, not images/links, for text (including code, tables & ERDs)](https://meta.stackoverflow.com/q/285551/3404097). Use a link/image only for convenience to supplement text and/or for what cannot be given in text. And never give a diagram without a legend/key. PS Here that means give the table as text. But you also need to give in your post anything that we need to know to answer the question. So either quote that relevant stuff (as text) or if it would not be legal to copy then paraphrase. So, what is that business about leaking & what else do we need to know from that link?
Comment: [The classic paper introducing ACID & describing SQL pheomena & other transaction 'anomalies' & relating them to SQL implementation.](https://arxiv.org/pdf/cs/0701157)
Comment: where did I mention locking inappropriately as you say ? tx1 selects a row, then tx2 updates and commits that row, then tx1 updates the same row and commits. So I'm asking whther MVCC upon tx1 commit does check that the row version has been updated since he has selected the row and does a rollback(called optimistic locking) or it the commit does succeed causing a Lost Update ? what is wrong ?
Comment: Please clarify via post edits, not comments. (Explain *all* the steps that you think are happening.) Re "where did I mention locking inappropriately": "shouldn't MySQL MVCC prevent Lost Update using database level Optimistic Locking".
Comment: Hi. Please act on my comments, don't just do bits & pieces. Transaction implementation involves updating the database & certain DBMS data structures according to an algorithm. You don't seem to understand that because you keep not describing everything relevant. Yet again: Say how the DBMS state (DB & MVCC control) changes on each transaction start & read & write & commit & *justify it by reference to a presentation of the MVCC algorithm* that *you have quoted/paraphrased in your post as text*. I repeat myself. Please reread my comments & act on all of them.
Answer: I'm the author of the book that's mentioned in the question.
According to the SQL standard, Repeatable Read should prevent:

dirty reads
non-repeatable reads

The standard says nothing about lost updates because the standard was designed when 2PL (Two-Phase Locking) was the facto Concurrency Control mechanism.
If you use 2PL, then the Repeatable Read isolation level will, indeed, prevent a Lost Update.
However, MVCC can provide Repeatable Reads via multiple versions of a tuple, but in order to prevent Lost Updates, they also need the transaction scheduler to track tuple modifications for the records read by a certain transaction. Apparently, InnoDB does not work like that.

shouldn't MySQL MVCC prevent Lost Update using database-level Pessimistic Locking resulting in transaction rollback

MVCC does not use any Pessimistic Locking in Repeatable Read. The only locks taken are the gap and next-key locks taken on the clustered index, but those don't prevent Lost Updates.
MySQL uses Pessimistic Locking for Serializable only, which provides a 2PL Concurrency Control model, even when using the MVCC-based InnoDB storage engine.
Comment: Sorry, I should have written "Optimistic Locking" instead of "Pessimistic Locking" in my question. When tx1 selects a row having an MVCC assigned version, say X, then tx2 commits its update, then when tx1 commits its own update, then I was thinking that MVCC should detect that the row version is not X anymore resulting into a rollback of tx1. So as I understand from your answer, Innodb MVCC doesn't track the version change during commit so there is no Optimistic Locking provided by Innodb MVCC, correct ? P.S.  I've updated my question.  Could you please update your answer as well ?
Comment: It's just an implementation detail. The only thing that was standardised is just those anomalies that need to be prevented. So, according to the standard, their implementation is fine. How does it really work behind the hood, it's hard to tell without studying the source code.
Comment: The row version does not need to be checked during update, but during commit for the previously loaded tuples.
Comment: @VladMihalcea IMHO, 2PL can prevent lost update regardless of isolation level. (Of course, even if 2PL may produce deadlock..)
Comment: @VladMihalcea Hmm, first, you NEVER mention `SQL server` on the paragraph you wrote. Second, IMHO, the reason why lost update occurs at Read Committed on SQL Server is because 2PL is not used at the level. If 2PL is used, I think lost update can NEVER occur.
Comment: @VladMihalcea I don't understand why you told me SQL:92, SQL:96 or MVCC which I know already what it is. What I pointed out is that 2PL itself can prevent lost update regardless of isolation level. Please let me know if there is some specific case where 2PL can't prevent lost update.
Answer: If I know correctly, MySQL use MVCC at repeatable read isolation level.
BTW, MVCC itself can't prevent lost update.
So, at repeatable read isolation level. of MySQL, we have to use select ... for update which use exclusive lock so that we can prevent lost update.

JFYI.
PostgreSQL also uses MVCC.
At repeatable read isolation level of postgreSQL, it uses first-updater-win strategy, so earlier transaction A which has updated X before later transaction B updates X will win if A successfully commits, then B must be rollbacked. If A failed and rolled backed, then B can commit successfully.
Both MySQL and postgreSQL use MVCC at read repeatable isolation level, but they have different strategies for how resolve lost update problem.


Why is the derivation maps an idenpotent element to $0$?

Question: Let $R$ be a commutative ring and $D:R\rightarrow R$ be a function such that $D(a+b)=D(a)+D(b)$ and $D(ab)=aD(b)+D(a)b$. Let $w\in R$ be an idempotent. Why in this case $D(w)=0$?
Thank you in advance.
Comment: Nice exercise! Compare $D\left(w\right) = D\left(w^2\right) = 2w D\left(w\right)$ with $D\left(w\right) = D\left(w^3\right) = 3w^2 D\left(w\right) = 3w D\left(w\right)$.
Comment: @m.idaya No not need to be
Comment: the ring R is it integral domain
Comment: if $R$ would be an integral domain, the question would be boring, since w could be only 0 or 1...
Answer: We do not need to invoke $D(w^3)$. After computing $D(w^2)$, we can argue like this:

Given any commutative ring $R$ and an idempotent $w$, we have that
  $x=2wx$ implies $x=0$.

To see that, multiply with $w$ to get $wx=2wx$, which is equivalent to $wx=0$, hence $x=2 \cdot 0=0$.


Exponential distribution question!

Question: Suppose that the time between calls from your best friend has an exponential
distribution with a mean time of $3$ days.
(a) If you just received a call from her, what is the probability that you will receive the next call within the next $2$ days?
(b) You realize that you have not received a call in at least $2$ days. What is the probability that she will not call you within the next $2$ days?
My attempt:
if $\mu=3$ then $m=1/\mu = {1/3}$ hence $X \sim \exp(1/3)$
(a) $P(X\leq2) = 1-e^{-1/3*2} = 0.4866$
(b) $P(X > 2) = 1-P(X\leq2) = 1-(1-e^{-1/3*2}) = e^{-2/3} = 0.5134$
I think my answers are incorrect. I also tried $X \sim \exp(3)$ but those answer make even less sense than the ones above.
Will anyone please point me in the correct direction if my approach is incorrect please?
Answer: Your answers are correct. Perhaps tell us why you thought they were incorrect, because it's important to improve on the intuition that led you to think this.
Comment: I feel like I'm ignoring the first part of each question, like if i receive a call or not receive a call then calculate each probability, is like something is missing. Does that make sense?
Comment: When waiting times are exponentially distributed, anything in the past is irrelevant. This is called the 'memorylessness' property and the exponential distribution is the only continuous distribution that has it. So, they put information about the past, probably to play games with your intuition. :) If you know a bit about conditional probabilities, e.g. that $f_{X|Y}(x|y) = f_{X,Y}(x,y)/f_{Y}(y)$ then you can prove that conditioning on the past doesn't change the result i.e. in (b) that $Pr[X>4|X>2] = Pr[X>2]$ where $X \sim \exp(1/3)$.

Exponential distribution question!


Setting number of CPU cores in VMware image

Question: I have a laptop with a core2duo CPU. When I am setting up my Ubuntu VM, should I set it to have 2 cores or 1? Do you always set it to the number of cores your host has?
Answer: tl;dr: It doesn't matter, so use one core.
Full version: If you're talking about the number of cores the virtual machine has, the number of cores the host has doesn't really matter, with some important caveats"

If you set up a huge number of cores (whether multiple cores on multiple VMs or multiple single-core VMs) then you'll end up oversubscribing the CPU of the host machine, and you'll see a performance drop.

Unless you have a reason to set the VM to multiple cores, set it to 1.


How do I prevent MySQL from filling up the disc with binary log files

Question: I have the following settings in my /etc/my.cnf
log-bin                 = /var/lib/mysql_bin_logs/mysql-bin.log
expire_logs_days        = 3
max_binlog_size         = 100M
relay-log               = /var/lib/mysql/slave-relay.log
relay-log-index         = /var/lib/mysql/slave-relay-log.index
log-slave-updates

and I can see that the /var/lib/mysql_bin_logs/ folder remains at a constant size.  However the disc is filling up and I think it is to do with the file descriptor's for these binary log file not being closed properly.  When I restart MySQL, disk usage drops by several Gigabytes, suggesting that act of restarting is freeing up the space.
How do I prevent the disk being filled up this way other than restarting MySQL on a cronjob?
Comment: Does a mysqladmin flush-logs free that space?
Answer: First I'd try lsof -u mysql while it's running to see what files MySQL has open.  You may also find it more helpful to do lsof -u mysql | grep deleted to see files that MySQL still has open but are deleted.  If it turns out to be the log files hanging around you could try issuing a FLUSH LOGS inside MySQL as a workaround and see if it closes them.


How to return the object with just a selected few embedded objects?

Question: My structure is as follows:
{
    day: x,
    events:
    [
        {
            year: y,
            info: z
        }
    ]
}

Up to now I created the following query, which I does not return an error but does show anything either (which is wrong).
db.days.aggregate([
{
    $match:
    {
        $and:
        [
            {
                'day': 'March_13'
            },
            {
                'events.year': '1870'
            },
            {
                'events.info': {$regex: "./French./"}
            }
        ]
    }
},
{
    $unwind: {path: "$events"},
},
{
    $match:
    {
        'info': { $regex: '.*French.*'}
    }
}])

From what I read I need to group by _id, but I do not know how to recreate the array with the objects that satisfied the second $match.
Could you please have a look and maybe tell me why the initial query does not work and advise me on a group block?
Some sample data is here:
{
    "day" : "March_13",
    "events" :
         [
             {
                 "year" : "1929",
                 "info" : "Peter Breck, American actor (d. 2012)"
             },
             {
                 "year" : "1929",
                 "info" : "Joseph Mascolo, American actor"
             },
             {
                 "year" : "1929",
                 "info" : "Zbigniew Messner, Polish economist and politician, 9th Prime Minister of the Republic of Poland (d. 2014)"
             },
             {
                 "year" : "1929",
                 "info" : "Bunny Yeager, American model and photographer (d. 2014)"
             }
         ]
}

And here is if I would succeed in querying by the word "American":
{
    "day" : "March_13",
    "events" :
         [
             {
                 "year" : "1929",
                 "info" : "Peter Breck, American actor (d. 2012)"
             },
             {
                 "year" : "1929",
                 "info" : "Joseph Mascolo, American actor"
             },
             {
                 "year" : "1929",
                 "info" : "Bunny Yeager, American model and photographer (d. 2014)"
             }
         ]
}

Basically I want to check if the field info contains the searched word, and if it does I keep it in the array.
Comment: Can you [edit] your post to include some sample documents and your expected result to show what you want achieved with the aggregation framewrok?
Comment: @chridam Please check the edit.
Answer: You'd want to try running the following aggregation pipeline for the above example to get the desired result:
db.days.aggregate([
    {
        "$match": {
            "day" : "March_13",
            "events.year": "1929",
            "events.info": /American/
        }
    },
    { "$unwind": "$events" },
    {
        "$match": {
            "day" : "March_13",
            "events.year": "1929",
            "events.info": /American/
        }
    },
    {
        "$group": {
            "_id": "$_id",
            "day": { "$first": "$day" },
            "events": { "$push": "$events" }
        }
    }

])

Sample Output
/* 0 */
{
    "result" : [
        {
            "_id" : ObjectId("5706b38dcc578484faab815f"),
            "day" : "March_13",
            "events" : [
                {
                    "year" : "1929",
                    "info" : "Peter Breck, American actor (d. 2012)"
                },
                {
                    "year" : "1929",
                    "info" : "Joseph Mascolo, American actor"
                },
                {
                    "year" : "1929",
                    "info" : "Bunny Yeager, American model and photographer (d. 2014)"
                }
            ]
        }
    ],
    "ok" : 1
}

Comment: It is wierd but the query does not return anything, but it does not return an error either.
Comment: @PetruDanielTudosiu Did you check how you are applying the regex pattern in the match pipeline?
Comment: @chirdam The regex is .*American.* to match anything that contains American. On the first try it was wrong but after I modified it still didn't return anything.
Comment: @chirdam
db.days.aggregate([
    {
        "$match": {
            "day" : "March_13",
            "events.year": "1929",
            "events.info": '.*American.*'
        }
    },
    { "$unwind": "$events" },
    {
        "$match": {
            "day" : "March_13",
            "events.year": "1929",
            "events.info": '.*American.*'
        }
    },
    {
        "$group": {
            "_id": "$_id",
            "day": { "$first": "$day" },
            "events": { "$push": "$events" }
        }
    }

])
Comment: @PetruDanielTudosiu You're doing it wrong, look at my example above and try the regex without the quotes i.e. try /American/
Comment: @chirdam I tried you code, it did not return anything :-?
Comment: @chirdam Sorry my bad. Forgot to change the db.
Comment: @PetruDanielTudosiu No worries, glad it worked out well for you.
Answer: This would be simple if we could use the $regex with the $cond operator or the $filter operator. That being said you have two options, the first one is to use the aggregation framework (as mention in this answer) and the native aggregation pipeline operators which will be faster as coded in C++ but in the pipeline you need to use the $unwind operator and if you are dealing with large array, the size of your documents after de-nomalization may exceed the 16MB in which case the aggregation query will fail. If that happen, you can do this using mapReduce
function map() {
    var events =  this.events.filter(function(element) {
        return (/American/i).test(element.info) && element.year === "1929";
        });
    emit(this.day, events);
}

db.collection.mapReduce(
    map,
    function(key, value) {},
    { out: { inline: 1 } },
    { query: { "day": "March_13" } }
)

Which returns:
{
    "results" : [
            {
                "_id" : "March_13",
                "value" : [
                    {
                        "year" : "1929",
                        "info" : "Peter Breck, American actor (d. 2012)"
                    },
                    {
                        "year" : "1929",
                        "info" : "Joseph Mascolo, American actor"
                    },
                    {
                        "year" : "1929",
                        "info" : "Bunny Yeager, American model and photographer (d. 2014)"
                    }
                ]
            }
    ],
    "timeMillis" : 27,
    "counts" : {
        "input" : 1,
        "emit" : 1,
        "reduce" : 0,
        "output" : 1
    },
    "ok" : 1
}


LilyPond: modifying woodwind diagrams

Question: Regarding woodwind diagram in LilyPond such as:
<code>\markup {
\center-column {
\override #'(size . 0.7) {
\woodwind-diagram #'flute  #'((cc . (oneF two three four five six))
                             (lh . ())
                             (rh . ())) }}}
</code>
... which results in:

Is it possible to change the diagram somehow to get something like:
Answer: You can create new patterns using Scheme:

Creating new diagrams is possible, although this will require Scheme ability and may not be accessible to all users. The patterns for the diagrams are in 'scm/define-woodwind-diagrams.scm' and 'scm/display-woodwind-diagrams.scm'.

Source: https://lilypond.org/doc/v2.18/Documentation/source/Documentation/notation/woodwind-diagrams.html
The simplest one might be to make a copy of the whistle scheme file and modify it to your needs.
Answer: My friend assist me to defined those Lilybin lines, in order to add additional grafical to wood-wind diagram:
<code>    \version "2.22.1"

% LilyBin
#(define-markup-command
  (woodwind-diagram-x layout props
    instrument user-draw-commands)
  (symbol? list?)
  #:properties ((upper-hole1 #f)
                (size 1)
                (thickness 0.1)
                (graphical #t))
  (let* ((ww-diagram
          (interpret-markup layout props
            (make-woodwind-diagram-markup
             instrument user-draw-commands)))
         (hole-circle
          (make-circle-stencil size thickness upper-hole1))
         (midline
          (make-line-stencil (* thickness 2) (* -0.80 size) 0 (* 0.80 size) 0))
         (upper-circle-and-midline
          (ly:stencil-combine-at-edge hole-circle Y DOWN midline (* 0.80 size))))
    (ly:stencil-combine-at-edge
     upper-circle-and-midline Y DOWN ww-diagram (* 0.80 size))
    ))

\markup {
  \center-column {
  \override #'(upper-hole1 . #f)
    \override #'(size . 0.7) {
      \woodwind-diagram-x #'flute
      #'((cc . (oneF two three four five six))
         (lh . ())
         (rh . ()))
    }
  }
}
</code>
That works.
Thanks a lot guys

LilyPond: modifying woodwind diagrams


I can see the posted data in the url but nothing happen

Question: its been 2 days that im stuck with this error i can see the data that i post but the next page do not load
when i submit i get  http://localhost:8000/android/www/login1.html?username=**********&password=****************&action=SignIn
thanks for ur help.

        <form id="form" >

                <input type="text" placeholder="Numéro Téléphone" id="username" name="username" />

                <input type="password" placeholder="Password..." id="password" name="password" />

                    Mot de passe oublié?

                    <button type="submit" id="action" name="action" value="SignIn">Sign In</button>

        </form>

<?php

header('Access-Control-Allow-Origin: *');
 include('conn.php');

 if(isset($_POST["username"])&& isset($_POST["password"])){
   $password = $_POST['password'];
    $username = $_POST['username'];

  echo"Veuillez remplir les champs";
}

 $sql7="select * from utilisateur WHERE username='$username'";
$result=mysqli_query($conn, $sql7);
while($result1 = mysqli_fetch_array($result)){
 $var=$result['password'];}

if($password!='$var'){
 $status="passworderrone";
echo json_encode(['status' => $status]);

 }

if($password=='$var'){

$vari='11';

function getRemoteIp(){
    if( !ini_get('register_globals') ) {
            return $_SERVER['REMOTE_ADDR'];
    } else {
        return @$REMOTE_ADDR;
    }

    return "";
}

$ip = getRemoteIp();
$sql2="select * from session WHERE username='$username'";
$usrname=mysqli_query($conn, $sql2);
while($result = mysqli_fetch_array($usrname)){
 $vari=$result['username'];

  }
if('$vari'==$username){
 $status= "dejainscris";
 echo json_encode(['status' => $status]);
 $sql3 = "INSERT INTO session (username, tps_connx, tcpip)
VALUES ('$username',NOW(),'$ip')";

$res3=mysqli_query($conn, $sql3);

}

else {$status="premiereinscription";
echo json_encode(['status' => $status]);
}
}

?>
Comment: Possible that the form is being submitted without the jQuery being run at all meaning ajax isn't being used? Simple debugging - add `console.log('Submit function called');` and see if that logs in the browser console. If it doesn't then try adding `event.preventDafault();` to your submit function, this will stop the forms default behaviour submitting.
Comment: thank u newtojs4 but  i got nothing when i did in the console
Comment: Then your form is being submitted before the jQuery can run. Well you have a few options. you can use `event.preventDefault();` in your function or `return false;` to stop the form being submitted.
Comment: i have already a return false; in my script!! and event.preventDefault(); doesn't work.
Comment: I have just noticed you are targeting the submit button. `$('button[type=submit]').submit(function () {` Try targeting the form since the form has the action of submitting...? `$('#form').submit(function () {`
Comment: that what i had but when i did that i dont get the data in the url
Comment: You don't want anything in the url! When you see those parameters in the URL it's because your page has just reloaded "trying to send that data" the point of ajax is to keep the client on the page with no reload while making a request. I suggest you start placing some `console.log();` in your source code, open the console and debug. Example: Check the ajax for the response? `success:function(json){
console.log(json);`
Comment: as u can see in the code php i return status so in javascript it deppend on the value of status i want to send the user to another interface i did that before and its working
Comment: Yes... and have you checked what the PHP is returning back to your ajax request?
Comment: when i run the php code with real values (password and username) it work
Comment: I mean have you checked it within ajax... Just like I have posted above. When using javacript/jQuery use your browser console, it's your best friend! Check it for any error reports and use `console.log('Some success message');` to check parts of your function are working, you can also use it to display values/data. Check the ajax response.
Comment: im sorry i did console.log(json);  but nothing  happened  :(
Comment: Do you have any errors in your console? place a `console.log()` at the start of your function. make sure the function is running first.
Comment: yes i did that nothing happen in the console!
Answer: There are two things you can do to fix this.

Remove type=submit from button and in JS instead of catching submit event, you should catch click event.
<button id="action" name="action" value="SignIn">Sign In</button>
and in JS you should look for click event.
$('button#action').click(function () {
The reason for this type=submit directly submit the form. So first that needs to be checked, then look for click event and do your thing.
Second way to do this is that instead of catching submit event on button, look for submit event on form because it is meant for forms.
so your JS should
$('#form').submit(function (e) {
     e.preventDefault();
     ...


A proof in Spivak on integration.

Question: The theorem states

If $f$ is bounded on $[a,b]$, then $f$ is integrable on $[a,b]$ $\iff$ for all $\epsilon > 0$ there is a partition $P$ of $[a,b]$ such that
$$U(f,P) - L(f,P) < \epsilon$$

The proof is on page 220. I believe I  have the 2nd ed of the book.
One of the steps really confused me in which he writes

"$\inf \{ U(f,P')\} - \sup\{ L(f,P')\} < \epsilon$, since this is true for all $\epsilon > 0$, it follows that $\inf \{ U(f,P')\} = \sup\{ L(f,P')\}$

I do not understand how this follows, how did this become an equality?
Comment: So he is saying that $\lim_{x \to a} f(x) - L = 0 \implies f(x) = L$?
Comment: Actually why is the LHS bounded below by 0?
Comment: No that's exactly what is in the book. Though the inf of a set is a number and so is the sup. So we are really subtracting numbers here
Answer: This is a cute strategy in analysis: to prove that $x = y$, you instead prove that $|x - y| < \epsilon$ for all $\epsilon > 0$.  Because if $x \neq y$, then taking $\epsilon = |x - y|$ would falsify the inequality.  In your case, $x = \inf U(f,P')$ and $y = \sup L(f,P')$.
In your question, the absolute values are omitted because $x > y$ already; this is because we always have $U(f,P') \geq L(f,P')$ for the same partition, which is the intuition behind the use of "upper" and "lower" in the names of these quantities.
Comment: Absolute values aren't needed because the difference in question is non-negative.  All the numbers $U(f,P)$ (as $P$ varies) are $\geq$ all the numbers $L(f,P)$, so the infimum of the former is at least as large as the supremum of the latter.
Comment: But he didn't use absolute values at all
Comment: @sizz: Suppose you know that $|x-y| \lt \epsilon$ for all $\epsilon > 0$. If $x \ne y$, you can take $\epsilon = |x-y|$ (because $x-y$ is not $0$), and you get $|x-y| < |x-y|$, a contradiction which came from assuming $x \ne y$.
Comment: Can expand on the $\epsilon = |x - y| $ part a bit? I am still have trouble seeing the conclusion
Comment: Oh I see, he omitted a lot of steps here...
Comment: It's better than what you wrote, Ryan. For any two partitions, $P$ and $Q$ you have that $U(f,P) \geq L(f,Q)$. Because there is some common refinement $R$ of both $P$ and $Q$ and hence we must have that $U(f,P) \geq U(f,R) \geq L(f,R) \geq L(f,Q)$.
Comment: More generally, if $a < b+ \epsilon$ for all $\epsilon > 0$, then $a \leq b$. This is used all the time in analysis.
Comment: So basically we have $0 < |x - y| < \epsilon $ for all $\epsilon$. Then we choose $\epsilon = |x - y|$ to get a contradiction to the fact that $x \neq y$? Now I actually don't understand the point of the theorem.
Comment: In the theorem, $x$ and $y$ depend on $\epsilon$ so it doesn't follow that $x = y$ (after getting $\epsilon$, you have to find an appropriate partition); the theorem is basically saying that the limit of Riemann sums exists.  However, in the step that you asked about, you've got some partition $P'$ already and the claim is that some quantities depending on its upper and lower sums are equal; this is proved by showing that their difference is less than every positive number, hence zero. (Since otherwise it would be positive, so not less than itself.)
Answer: This is called a Darboux integral and to show that $\inf \{ U(f,P')\} \geq \sup\{ L(f,P')\}$  you first have to show that for a refinement $P'$ of a partition $P$ you always have $$U(f,P) \geq U(f,P') \geq L(f,P') \geq L(f,P).$$ Then to show that all the upper integrals are bigger than all the lower integrals you can use the fact that for any two partitions $P_1$ and $P_2$ there is always a partition $P'$ that is a refinement of both of them, $P' = P_1 \cup P_2$ for example.
Now assume we have $0 \leq \inf \{ U(f,P')\} - \sup\{ L(f,P')\} < \epsilon$ for every $\epsilon > 0$ as assumed in the question. That doesn't leave room for the difference to be anything other than zero since $\epsilon$ can be chosen arbitrarily small.
Comment: How did you turn a strict inequality into an ordinary inequality?
Comment: @sizz Typo. Thanks for pointing it out, I've fixed it.

A proof in Spivak on integration.


File loop and logic in controller of view header?

Question: I have the following in the header.php file which is included in all of my views:
$dh = opendir(Vs.get_class($this).'/js') ;
while($script = readdir($dh)) {
    if(!is_dir($script))
    {
        echo '' ;
    }
}

$dh = opendir(Vs.get_class($this).'/css') ;
while($css = readdir($dh)) {
    if(!is_dir($css))
    {
        echo '<link type="text/css" href="css/'.$css.'" rel="stylesheet"/>' ;
    }
}

It's purpose is to autoload all the css and JS files for a particular view (which has the same name as the controller, hence get_class).
Should all this be a part of the associated controller or is how I have done it fine?
Comment: To the people commenting above me .. the purpose of SO is to learn, not to mock others!
Comment: AUW this code hurts my eyes
Comment: Wow :) Some of the worst PHP code I've seen in a long time - possibly ever! As long as things exist it looks OK-ish...
Answer: Dude just use Glob php function . And then include those.. it will work perfectly fine. Also you will need to pass the absolute path
foreach (glob("*.css") as $filename)
{
   echo '<link type="text/css" href="css/'.$filename.'" rel="stylesheet"/>' ;
}

Comment: For a good answer, place example code including 'Glob'. It'll help answer the OP's question, help others in the future, and you'll be more likely to get up-voted.
Comment: @kuldeep Thanks, looking into it now. Can you provide an example where I'd match css and js files?
Comment: foreach (glob("*.css") as $filename) {
    echo '' ;
}
Comment: @kuldeep Put this in your actual answer (edit it) and use backticks for `code` :)
Comment: @Jimbo I added it to the answer :)
Comment: @kuldeep Cool, now that'll be more likely to help people in the future that visit this post, and it's more likely that you'll get more upvotes :)
Answer: Scripts and stuff which are only and exclusively used in the View belong in the View. The controller has nothing to do with it.
Views don't need to be dumb. In fact, they shouldn't be. They need to care about everything that has to do with preparing and returning a response. That even includes setting HTTP headers and possible caching logic. Including necessary CSS and JS scripts is also part of its job.


Botão Voltar - Nível acima ou Página anterior

Question: Bom dia, sei que a pergunta parece estranha e meio óbvia, mas tenho tido essa dúvida a um tempo...
Digamos que tenha a seguinte estrutura:
<code>Home
Clientes
---Lista
------Editar
---Cadastro
</code>
Se o camarada estiver no "Editar", ao clicar no meu botão "voltar", por padrão ele ele vai para "Lista"... Mas se ele tiver entrado na página "Editar" diretamente pelo URL por exemplo? O "location back" não vai funcionar certo? Devo então definir meu botão "Voltar" já com o link do nível superior (Lista)?
Qual seria a forma correta?
Answer: Minha opinião: Caso você possua esse botão de voltar em sua página, isso realmente ficará a seu critério. O botão voltar do navegador já irá fazer a função de voltar, o que eu não te impede de ter a mesma função na sua página, por questão de design ou navegação. Mas no seu caso você pode sim fazer com o que o usuário "retorne" para a página desejada.
Estretanto isso pode criar um problema de lógica em alguns outros casos, por exemplo:

Supondo que a página A é encaminhada para página C.
Foi criado uma página B que também será encaminhada para página C.
No botão de voltar da tela C, teria que direcionar para página A ou página B de acordo de onde o usuário veio.

Mas se ele acessar a página C diretamente pela URL, o que fazer?
Entendeu, aí que teremos que pensar cuidadosamente, você pode deixar dois links paras duas páginas, ou deixar para uma página anterior as duas, em uma lógica hierárquica como a da sua pergunta. Isso será maleável de acordo com a estrutura geral de seu site, e como já disse ficará a seu critério.
Comment: Show, entendi. Vou ver essa questão da lógica aqui, pois acredito que definir a página diretamente será melhor. Fiz um teste aqui e se o usuário atualiza as informações de um cliente e clica no botão Voltar ele acaba voltando pra mesma tela de edição que estava e isso já vai gerar um desconforto e choradeira rs.
Answer: Pense no conceito de "voltar", que está relacionada à um histórico.
Se a página foi acessada de forma direta, a página anterior à ela seria o comportamento "correto", mas nada impede de você forçar sua aplicação à voltar para o nível acima, independente de onde o usuário veio.


Recuperar dados geográficos através de uma solicitação HTTP via URL do Google Maps

Question: Bom dia galera.
Estou querendo recuperar algumas informações geográficas tendo como parâmetros a latitude e longitude.
Para recuperar tais informações estou tentando fazer uma solicitação via URL através deste link: Google Maps Geolocation API.
Ele me retorna um XML onde eu poderei trabalhar em cima do mesmo.
Ao criar este serviço em meu web service, subi para o servidor Weblogic em desenvolvimento (Rodando em Sistema LINUX) e ele me retorna o seguinte erro ao executá-lo:
java.io.FileNotFoundException: Response: '502: Bad Gateway' for url: 'http://maps.google.com/maps/api/geocode/xml?latlng=-15.8040195453225%2C-47.8799401993617'

Já tentei de várias maneiras, mas continua dando o mesmo erro. Estou utilizando o código da própria Google para realizar o consumo das informações, segue abaixo:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;

public class GeocodeProcessor {

    private static final String GEOCODE_REQUEST_PREFIX = "http://maps.google.com/maps/api/geocode/xml";

    private static final int PROXY_PORT                 = 3128;
    private static final String PROXY_HOST              = "vampre.funasa.gov";
    private static final int TIMEOUT                    = 30000;

    public static void main() throws IOException,
            URISyntaxException, ParserConfigurationException, SAXException {

        String urlString = null;

        urlString = GEOCODE_REQUEST_PREFIX + "?latlng=" + URLEncoder.encode("-15.8040195453225,-47.8799401993617", "UTF-8");
        System.out.println(urlString);

        // Convert the string to a URL so we can parse it
        URL url = new URL(urlString);

        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
                PROXY_HOST, PROXY_PORT));

        HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
        conn.setConnectTimeout(TIMEOUT);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/xml");

        try {
            // open the connection and get results as InputSource.
            conn.connect();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),
                    "UTF-8"));

            String line = null;
            StringBuilder ab = new StringBuilder();
            while( ( line = reader.readLine() ) != null )  {
                ab.append(line);
            }
            reader.close();

            System.out.println(ab.toString());

        } finally {
            conn.disconnect();
        }
    }

}

Uma ajuda seria extremamente útil agora. Vlw galerinha.
Comment: Está OK, provavelmente seu proxy ou acesso do servidor em que está acessando à rede externa. Inclua o *stack trace* completo.
Comment: Por coincidência, estou trabalhando em um projeto que também vai precisar usar essa API. Se eu conseguir resolver, eu posto uma resposta.
Answer: O @Bruno está correto!
Dando um bypass no seu proxy, o código rodou normalmente!
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

Eu fiquei me perguntando, porém, se tinha algo de errado com o código do proxy - mas parece que não - instalei um servidor de proxy para testar - segue o log do programa:

Saída do seu programa:

O programa de proxy utilizado foi o WinGate.


How to merge specific column from another dataframe in Python Pandas?

Question: I have two dataframe df1 and df2, in df1 I have 'id', 'name', 'rol' and in df2 I have 'id', 'sal', 'add', 'deg'.
I have to merge only 'sal' and 'deg' column from df2 to df1.
I have successfully merged all columns from df2 to df1.
but now I just need to add two columns on the basis of common column "id"
I am using python 3.7 version.
df_right = pd.merge(df1,df2,how='right',on='id')

how can I merge only these two columns ('sal' and 'deg') from df2 on the basis of 'id'?
Answer: Just go slice before you merge like so.
pd.merge(left=df1, right=df2[['id', 'sal', 'deg']], how='right', on='id')

Comment: I have already tried this one. it gives me KeyError: 'id' can you please tell me why this error is coming.
Comment: well are you sure 'id' is a column or an index? cause "KeyError" means that it's not a column in one of the dataframes.
Comment: yes, I am 100% sure. as I removed [ ] with columns name mentioned within it. it is working fine fetching all the columns from df2. can you please suggest something.
Comment: solved now it is working fine. I was just missing 'id' into [ ].