calculate gradient

Question: I'm trying to understand differentiation. At 9:45 the kind sir is filling in numbers in this video.
My question is, where is he getting the gradient numbers from when hes filling in the table? I know it can be calculated by using nx^n-1, but I don't think hes using it over there because he only explains this at the time the video reaches 13:09.
Also can someone tell me when differentiating applies? Is it just in parabolic shapes? (I dont feel like its worth opening a new question for this)
Answer: Well, that method you've mentioned is probably how he's been able to write them down so quickly, but he just finished explaining how if you take $\frac{f(x_0+\Delta x)-f(x_0)}{\Delta x}$, and let $\Delta x=0.1,0.01,0.001,\ldots$, then you get a good idea of where things are headed.
Basically, a function (of one variable) is differentiable at a point if its graph has a tangent line at that point, which happens when the graph is 'smooth' there.
Speaking in precise terms, though, a function defined in a small interval centered at a point $x_0$ (and perhaps elsewhere, though that is of no consequence here) is said to be differentiable there if there exists $L\in\mathbb{R}$ such that for every converging sequence $x_n\to x_0$ it holds that $|\frac{f(x_n)-f(x_0)}{x_n-x_0}-L|\to 0$. We then have $y = f(x_0) + L(x-x_0)$ as the tangent to the function's graph at $(x_0,f(x_0))$.
Comment: Thanks for your answer. When hes filling in the table hes also filling in x=2 and x=1, but what I understand is that you need two points to calculate the tangent/slope. At 4:30 he shows an example of this. But like I asked in my question he just fills in the table with nx^n-1? That doesn't make sense to me, because I think hes filling in the tables to show where he got the gradient function nx^n-1 from, so why would he be using it first and then show where he gets it from?
Comment: I dont understand all the symbols yet, I think I'm going to have to get better before I can get to that. what is x with indice 0?
Comment: 1. Look from around 4:00. He estimates the slope from $3$ to $3.2$, then $3.1$, then $3.05$, and so on. With this process he's able to 'estimate' what the gradient ($L$, in our noation) is going to be. Later on he's 'prepared' the results for similar cases 'in advance', although what he's really doing is using the formula he later establishes, of course.

2. $x_0$ is just a fixed point (zero is a nice index for that purpose) in the domain of the function. The main thing to know here is this: are you familiar with the notion of sequences and their limits?
Comment: Since you need two points before u can calculate the slope, can you just use any random point that is on the parabolic? For example at 4:41 the sir keeps using point p(3,9) to calculate delta x and delta y. What point would he use for when x is 2 later in the video when he fills in the table?
Comment: what he did was use $(3,9),(3.2,10.24)$, then use $(3,9),(3.1,9.61)$, then $(3,9),(3.05,9.3025)$, and so on. The corresponding slopes would be $6.2,6.1,6.05,\ldots$
Comment: Again, thanks alot for your help! I'm still a bit confused. At around 5:00, he is calculating the slope of line PR, but what is he calculating when hes filling in the table at around 7:30?
Comment: He's doing the same thing he did before, but without showing us the process. I.e. approximating using pairs of points closer and closer together.
Comment: I finally get it now. For some reason I couldn't grasp my mind on it, maybe because its 3:30 am. Last question: So basically, once he filled the tables he can then derive the formula nx^n-1 from the patterns inside the table answers? Is that correct?

calculate gradient


How does this IF-Conditions in Python work?

Question: This is a Mergesort i found online and tried to implement. It worked but i am not sure how it works. Can someone please explain to me why/how this if-condition works? Where does the code continue when the first-if statement isnt true anymore. I know how if-condtions work in general but to the lack of indentions and/or 'else' confuses me here.
def mergeSort(alist):
   print("Splitting ",alist)
   if len(alist)>1:
       mid = len(alist)//2
       lefthalf = alist[:mid]
       righthalf = alist[mid:]
       #recursion
       mergeSort(lefthalf)
       mergeSort(righthalf)

       i=0
       j=0
       k=0

       while i < len(lefthalf) and j < len(righthalf):
           if lefthalf[i] < righthalf[j]:
               alist[k]=lefthalf[i]
               i=i+1
           else:
               alist[k]=righthalf[j]
               j=j+1
           k=k+1

       while i < len(lefthalf):
           alist[k]=lefthalf[i]
           i=i+1
           k=k+1

       while j < len(righthalf):
           alist[k]=righthalf[j]
           j=j+1
           k=k+1

alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)```

Comment: This is a recursive in-place sort.  When the first condition isn't true, nothing has to be done in the call (i.e. meaning only 1 element so no sorting).  [Quick video](https://www.youtube.com/watch?v=JSceec-wEyw) illustrating how mergesort works.
Comment: To expand on Darryl's comment, when the function `mergesort(alist)` is entered, first it prints the list, then asks "Is the list longer than `1` element?". If there is only `1` (or `0`) elements in the list, there's no need to do any sorting, because it is already in order, so it simply exits the function.
Answer: This relies on alist effectively acting like a global variable, which tends to be a bit frowned upon (especially since it's not declared global). There are also some while loops that could be replaced by list comprehensions.
If the if condition is not true, then alist has only one element, and so sorting it is trivial: a sorted list of one element is just that list. A list of only element can't be out of order. So the function simply terminates without doing anything, because nothing is needed.
If the if condition is true, then function reassigns entries in the list, using recursive calls to itself. Each recursion calls the function on a smaller list, so eventually a list of length one is reached, terminating the recursion. So when the if condition is false, the function just returns to the next higher level of recursion.
Because of the way mutable data types such as lists work in Python, when a recursion level changes what's in a particular location of the alist that it was passed, it also alters what's in that location in the alist of the higher recursion levels. This results in the original alist ending up sorted, even though the function doesn't have the return keyword and thus doesn't explicitly return anything. This is known as a function operating on the input "in place".
Answer: In this code there is no else used - to find the matching else always look for else that starts at the same position(with same indentation) as if.  Since there is no such code, it will exit the function when if condition is not satisfied.


Chage View title with taxonomy term

Question: I have a Taxonomy Vocabulary as People. In it there are two terms Board and Staff.
I've created a view with two displays, to display the people content with respect to taxonomy terms. The view title is Board Members.

When I access the  board page http://example.com/people/board the title is Board Members.
When I access the  Staff page http://example.com/people/staff the title is Board Members too.

I want to change the staff display title to be like Staff Members? How to change it?
I've filtered by using Contextual filters.
Comment: Do you use 2 page displays for this view?
Comment: Yes two pages with single view
Answer:
In the contextual filters click on override title and set it to %1
Specify validation criteria to taxonomy term and select the vocabulary
Leave the views title empty.

This will set the present's term's title as the view's title.
If need you can add "text" %1 to display the text appended to the term's name.
Comment: Don't forget to make sure he will overwrte defaults, not update them. If he will update them, he will end up with both displays titled "Staff Members"
Comment: @dinesh : "Yes two pages with single view", the pages are called as displays in views.
Comment: Did you try the one here http://drupal.stackexchange.com/questions/11760/dynamic-views-title
Comment: Thnaks @Gladiator
I did little more work to got the result.
1.I left the view display name as blank.
2.In contextual filter, under When the filter value IS in the URL or a default is provided, checked override title, and placed %1.
this gives me the terms as titles as board and staff. So i changed the term names (Board Members and Staff Members) add changed the alias and done!
Comment: Hello again, guys :) Could you please edit what you figured in comments, @Dhinesh to a question and Gladiator to an answer, respectively? You know, for future readers.
Comment: Click on the board's display , where is the display :(
Comment: then i have only one display and i filtered using contextual filters
Specify validation criteria: Taxonomy Term
Filter value type: Term Name converted to term ID
Comment: @Mołot : sure will do now.
Answer: Another method add this code in the template.php
<code>    function template_preprocess_page(&$variables) {
      $current_path = drupal_get_path_alias();
       if($current_path == 'people/staff') {
       drupal_set_title('Staff Members');
      }
    }
</code>

Chage View title with taxonomy term


Kendo TreeView: How to set Intermediate state Programmatically

Question: I am trying to use Kendo TreeView with other controls. Each of the leaf node on tree opens a detail pane. When I select all the elements from detail pane, I set the state of that node as Checked
myTree.dataItem(node).set("checked", true);

and when all the items are un-selected, I set the state of node as unchecked.
myTree.dataItem(node).set("checked", false);

but if some of the items are selected, I want to show the state of node as Intermediate
how can I do that. I cant find anything in the documentation that can help me. The closest thing I found is
myTree.updateIndeterminate()

however, it is not doing the job. Apparently, it sets the state based on the state of child nodes. but in my case, there are no child nodes. I am dealing with leaf nodes here. Can I set the state of a leaf node as Intermediate ? if yes, how?
Answer: Couldn't find any help on this.
Ended up using the following approach
I am now finding the checkbox associated with that particular node and setting it's indeterminate value using jQuery.
function SetTreeNodeIndeterminate(nodeId, set) {
  var uid = $("#" + nodeId).parents('li').attr('data-uid');
  var node = myTree.findByUid(uid);
  if (node.length == 0) return;
  var checkBox = $("#_" + uid);
  if (checkBox.length == 0) return;
  checkBox.prop('indeterminate', set);
  updateParentNodeState(node);
}

the following line makes sure that all the parents of a node are also marked as indeterminate
function updateParentNodeState(node) {
  myTree.updateIndeterminate(node);
  let parentNode = myTree.parent(node);
  if (parentNode.length > 0)
    updateParentNodeState(parentNode);
}


Conta de desenvolvedor

Question: Estou tentando abrir uma conta, e tenho as seguintes duvidas:

Posso pagar a taxa de desenvolvedor com cartão de credito internacional pre-pago (o travel card da master card)?
Sou desenvolvedora autonoma, (logo trabalho em casa), e a conta pede para fornecer um endereço para ser exibido ao usuario para poder vender apps!!! Como assim??? Sacanagem pô! Não posso e nem quero meu endereço divulgado pra qualquer um! O campo não é de preenchimento obrigatorio, porem fala que se não por o app e/ou a conta pode ser suspensos... Como vcs resolveram isso? Pq não vejo endereço nenhum no google play.
Como vcs fazem para receber o dinheiro da venda dos apps? A google deposita na conta de vcs? Se sim, tem q ser algum tipo de conta especifica, ou conta corrente mesmo? E onde vcs informam essa conta? pq não vi nenhum campo para por a conta bancaria para deposito...

Por favor, estou precisando urgente abrir essa conta, mas não sei por onde começar, já li a documentação, mas muita coisa não é dita lá, como esses detalhes acima, só quem ja criou a conta para saber mesmo, então se alguem puder me responder eu agradeceria muito.
Comment: Claro que aparece o endereço, veja esse da google, clique em "leia mais" e verá Mountain View(sede da google) https://play.google.com/store/apps/details?id=com.google.android.googlequicksearchbox&hl=pt_BR
Comment: A senhorita entende de inglês? tenta perguntar aqui. https://www.reddit.com/r/androiddev/
Answer: Senhorita,
Quanto ao endereço isso faz parte nos termos para desenvolvedores https://play.google.com/about/developer-distribution-agreement.html , quanto ao pagamento quando paguei a taxa exigida utilizei um cartão pré-pago internacional e ocorreu tudo bem, caso não ocorra com tu, melhor é contactar a administradora do cartão.
Comment: Oi Hugo, obrigada. Como vc faz com a questão do endereço? Vc tb é autonomo como eu? O @diegofm comentou q tem sim o endereço, fui ver e nos pagos tem mesmo, porem nem todos são completos(ex:[https://play.google.com/store/apps/details?id=com.sikebo.antimo.material.icons] ou [https://play.google.com/store/apps/details?id=com.armaker.essappx&hl=pt_BR]), alguns tem só cidade e pais, isso basta? Obrigada.
Comment: Inicialmente utilizei um endereço de um escritório virtual na época que criei a minha conta, não é necessário tu informar o seu endereço completo como número da residência por exemplo.
Melhores cumprimentos para sí.

Conta de desenvolvedor


How do i arrange chords after mixing pentatonic modes?

Question:
The Ionian mode which is the Major scale - is the second mode of the minor pentatonic scale (the Major pentatonic scale) plus a Perfect 4th and a Major 7th notes. It is also a combination of, for instance, the 5th mode of the minor pentatonic scale and the 4th pentatonic mode a half-step down.

The Dorian mode is the minor pentatonic scale plus a Major 2nd and a Major 6th. It is also a combination of the 1st and 5th modes of the minor pentatonic scale.

The Phrygian mode is the minor pentatonic scale plus a minor 9th and a minor 6th. It is also a combination of the minor pentatonic scale and the major pentatonic scale a half step up.

The Lydian mode is the Major pentatonic scale plus a sharp 4th and a Major 7th, and it is a combination of the major pentatonic scale and the minor pentatonic scale a half-step down.

The Mixolydian mode is the Major pentatonic scale plus a Perfect 4th and a minor 7th and is a combination of the Major pentatonic scale and the 3rd mode of the minor pentatonic scale.

The Aeolian mode is the minor pentatonic scale plus a Major 2nd and a minor 6th. It can be seen as, among other things, a combination of the 3rd and 4th modes of the minor pentatonic scale.

The Locrian mode is the 4th mode of the minor pentatonic scale plus a minor 2nd and a flat 5th. It is also the combination of the 4th mode of the minor pentatonic scale plus the 5th mode a half step up.

where the first minor pentatonic mode is 1 b3 4 5 b7
How would yall go about connecting the dots in terms of forming modal sounds and chords mixing pentatonic modes like this ?
Comment: I'm not clear on what you're trying to do. Modulate between two pentatonic scales? Compose using diatonic modes? Why is it important to your question that diatonic modes can be broken down into combinations of pentatonics?
Comment: @Aaron heyy, so i was mixing major and minor pentatonics on guitar for the blues licks and all, then i found out about this nugget a couple of mins ago and I m trying to connect dots and see the colors of the modes thru pentatonics
Comment: Are you using the same root note for each mode, or the same diatonic notes from one parent key?
Comment: @Tim I don't think that affects the answer. Any diatonic collection breaks down into the same two pentatonic scales, adjusted for rotation.
Comment: @Aaron - OP mentions Aeolian and Locrian. Notes from A Aeolian are not the same as those from A Locrian, I think.
Comment: @Tim That's not quite what I mean. Given a particular base scale, there are only two unique pentatonic scales that generate it. For parallel modes, each will have its own pentatonic pair; for relative modes there will be just one pair. Either way, the core relationships are the same up to transposition.
Comment: @Aaron i just put the combo of all the major modes with pentatonic modes, now i suppose its clearer,
Comment: @MikeHawke At the end of my post is a short section about locrian. Please let me know if it demonstrates a correct understanding of your approach.
Comment: @Aaron you mixed 1 and 2 but you have to mix 4 and 5 to get it tho, i think someone mentioned in a comment too eg: A locrian :A Bb C D Eb F G, pentatonic modes making it 4th mode : A C D F G and 5th mode: Bb C Eb F G
Comment: @MikeHawke that's equivalent to my formulation. You're using two minor pentatonics that are a major second away from each other: D min pent. and C min pent. Any diatonic mode with exactly two flats can be derived from those two pentatonics.
Comment: @Aaron Heyy, I wanna work towards something which coincides with both our pentatonic mixing , i mean its the same interval shapes rearranged, Can we get out of the perspective dilemma and see how it works with chords i mean chords are just smaller scales but still recognisable i guess
Comment: @MikeHawke That's what I'm still not clear on. How would thinking about diatonic modes as pentatonics impact how chords operate in that mode?
Answer: TL;DR
There are four combinations of major and minor pentatonics which create the entire diatonic collection.

Two minor pentatonics a whole step apart
Two major pentatonics a whole step apart
One minor and one major pentatonic a half step apart
One minor and one major pentatonic a perfect fourth apart

However, any one of these formulations will suffice, as they all have identical pitch content.

Deconstructing diatonic modes into pentatonics
Let's restart from the inverse question: how can diatonic modes be deconstructed into two pentatonic scales?
Since all diatonic modes are rotations of each other, it's sufficient to consider a single mode, so let's use ionian (major).
Here is a map of the ionian mode on C along with the diatonic scales that can be derived from it. The numbers indicate the starting points of the nth mode, where ionian and major pentatonic are, respectively, mode 1.

  1 2 3 4 5 6 7 1 2 3 4 5 6 7 1
  C D E F G A B C D E F G A B C
1 * * *   * *   * * *   * *   *
2   *   * * *   * *   * * *   *
3     *   * * *   * *   * * *
4       * * *   * *   * * *   *
5         * * *   * *   * * *
6           *   * * *   * *   *

What this table shows is ionian can be composed from:

min pent on ionian deg 2 + min pent on ionian deg 3 (2-4-5-6-1 + 3-5-6-7-2)
min pent on ionian deg 2 + maj pent on ionian deg 5 (2-4-5-6-1 + 5-6-7-2-3)
min pent on ionian deg 3 + maj pent on ionian deg 4 (3-5-6-7-2 + 4-5-6-1-2)
maj pent on ionian deg 5 + maj pent on ionian deg 4 (5-6-7-2-3 + 4-5-6-1-2)

But consider that the pentatonics built on ionian degrees 1/6, 2/4, and 3/5 contain identical pitch content, respectively. Further the pitches missing from 1/6 form a tritone, which is not contained in any maj/min pentatonic scale. This means there is really only one way to build the entire ionian (and by extension, diatonic) collection:

minor pentatonic on X + minor pentatonic on (X + M2)

Constructing diatonic modes from pentatonics
Now let's consider the minor pentatonic scale and look at how to construct the diatonic collection. The X axis is the diatonic collection, the Y axis is modes of the minor pentatonic. (Note that this is equivalent to considering the major pentatonic, with appropriate rotation.)

                       V____________________V
  1  2  b3 4  5  b6 b7 1  2  b3 4  5  b6 b7 1
  A  B  C  D  E  F  G  A  B  C  D  E  F  G  A
1 *     *  *  *     *  *     *  *  *     *  *
2                *  *  *     *  *     *  *  *
3 *  *     *  *     *  *  *     *  *     *  *
4             *     *  *     *  *  *     *  *
5       *  *     *  *  *     *  *     *  *  *

As can be seen, the only minor pentatonic mode that can be mapped to diatonic degree 2 is mode 3, and only modes 2 and 5 can be mapped to diatonic degree b6. But the pitch content of modes 2 and 5 is identical; thus, we have

diatonic collection = minor pentatonic mode 2 + minor pentatonic mode 3,

which is identical to the formulation in the previous section.

Incorrect formulation
The Aeolian formulation is correct, but Locrian can not be decomposed into a minor pentatonic and a minor pentatonic a half-step up, regardless of the modes used.

Minor pentatonic = 1 b3 4 5 b7
Minor pentatonic + m2 = b2 3 b5 b6 7

Sum = 1 b2 b3 3 4 b5 5 b6 b7 7 (Too many pitches)
Comment: @piiperiReinstateMonica I'm not aware of any practical use of this, nor is it clear to me how OP intends to use it. Also D and E are not a half-step apart. I interpret OP as meaning that the roots of the two scales are a half step apart, though I see how you got your interpretation. It seems clarification is needed on both points.
Comment: @piiperiReinstateMonica I understand your construction but wasn't clear myself. By "root", I meant "of the major or minor pentatonic from which the mode is taken." So I would have said you're using D and E minor pentatonics, which, obviously are not a half step apart. I've asked OP for clarification.
Comment: Can you give a concrete musical example where this has been applied? Like something that could actually be played on an instrument. :) Is it like, if I play the notes of D minor pentatonic and E minor pentatonic, then I have played all 7 notes at least once, and thus explicated all notes of C major and its modes? The same with chords Dm7add11 and Em7add11. Or scales E minor pentatonic and F major pentatonic. And the musical application would be, how to use pairs of pentatonic scale shapes to explicate diatonic modes.
Comment: "Locrian can not be decomposed into a minor pentatonic and a minor pentatonic a half-step up, regardless of the modes used" - if you're allowed to use _modes_ of pentatonic scales, and if that means shifted rotations, then it can be done. 4th mode of E min pent B-D-E-G-A, and 5th mode of D min pent, C-D-F-G-A, you get all 7 notes of B Locrian. In theory. But in practice, I suspect it will take a lot of skill and a strong B bass pedal tone to make it sound like B Locrian.
Comment: Yes, B and C, which would be the roots of those "pentatonic modes", are a half-step apart. I actually tried out this system, and it's a bit strange, because in order  to make the proper modal sound you want to be able to use the characteristic tones, but maybe they're not available at the same time in either one of the pair of pentatonic scales chosen. Like in my example, if you want to use B, you can't use C and F at the same time. So you'll have to switch between the two scales relatively fast. It's certainly a way to make _some_ kinds of colors.
Answer: I don't really do this kind of music, but I've been watching videos about techniques like triad pairs and constructing scale patterns with seemingly arbitrary rules, so the system described here seemed somewhat interesting. Triad pairs... scale pairs?
I tried to produce a modal sound using a system where a pair of pentatonic scales is selected so that when their notes are combined, all seven notes of a diatonic scale are covered. As a target mode, I selected B Locrian, and as the two pentatonic scales, (1) the 4th mode of E minor pentatonic, i.e. root on B, and (2) the 5th mode of D minor pentatonic, root on C. Then I tried to construct licks with these two scales.
Here's a one-octave box of scale 1:

And scale 2, close to the same position:

First, a lick using the B-rooted scale, the 4th mode of E minor pentatonic scale.

Then a lick using the C something scale, which is also the 4th mode of F major pentatonic, and the 5th mode of D minor pentatonic scale.

(In Guitar Pro, the C something scale seems to be called "C Mixolydian Pentatonic". But in what sense is that C Mixolydian anything, if there's no Bb or E in it? It makes no sense to me.)
But does this combination work? In my opinion, in order to sound like B Locrian, at least B, C, D and F should be felt to exist in the harmonic context, maybe A as well. With our first pentatonic scale, we can reach B, D and A, but no C or F. But with the second scale, we get C, D, F and A. So if we could rely on someone else playing a low B, or if B has been imprinted in the listener's harmonic context as a root note very deeply some other way, we could be quite Locrian by simply using the C something pentatonic scale.
When writing the licks, I tried to emphasize the relevant notes of the selected "pentatonic modes", so that e.g. the C something lick wouldn't sound like it's in E minor, when played alone. The C something scale doesn't have a third in it, so it's hard to hear it as a mode as in "Church modes".
Anyway, if we play the two licks together and end the whole thing on a B note, the final note sounds like a home-note resolution.

All in all, I think it's a plausible way of constructing lines, looking at a pair of pentatonic scales like a pair of chords that, when put together, form a modal scale.


Ler dados de uma coluna através do C#

Question: Tenho um código postal e dividio em 2 variáveis: a primeira, onde aparecem os primeiros 4 números e a segunda onde aparecem os 3 últimos.
Ex.:

4300-234 - primeira = 4300; segunda = 234.

Tenho uma tabela na base de dados que tem 3 colunas referentes a códigos postais. A PC4, onde aparecem os primeiros 4 números, a PC3 onde aparecem os últimos 3 e a Desc, onde aparece o descritivo correspondente, ou seja, de onde são esses códigos postais.
O que eu preciso é de comparar a minha primeira variável com a coluna PC4, comparar a segunda variável com a coluna PC3 e depois quando as minhas variáveis forem iguais ás colunas PC4 e PC3, quero receber os dados correspondentes da coluna DESC.
Comment: Ok, tudo bem que você não saiba, mas pelo menos se esforce um pouco para nos explicar **como quer fazer** isso.
Comment: @Dc poste o código, leia isto e reformule a pergunta https://pt.stackoverflow.com/help/mcve, veja que é uma recomendação do Help oficial do site e não minha. Assim você evita da sua pergunta ser fechada
Comment: Mas em que momento você quer fazer isso? Numa _query_ direto no banco? Executar uma _query_ pelo seu código C# usando algum ORM ou a `SqlCommand`? Por favor, seja mais específico.
Comment: Quero fazer isto no código c#
Comment: É algo que nunca fiz, já pesquisei e não consigo perceber como fazer
Comment: Eu tentei explicar o melhor que consegui. Tenho 2 variaveis, variavel1 tem os 4 primeiros numeros do codigo postal, a variavel2 tem os ultimos 3. Preciso de comparar a variavel1 com a coluna PC4 e a variavel2 com a PC3, quando a variavel1 = PC4 e variavel2 = PC3, quero receber o valor da coluna Desc (que é a cidade onde pertence o codigo postal)
Comment: Vamos tentar de novo. Você sabe fazer conexão com o banco de dados? O seu projeto já faz conexão com o banco?
Comment: Sim, ja tenho tudo conectado, ja inseri valores na base de dados atraves do c# e tudo.
Comment: Ok, chegamos na parte que eu queria. Como é que você insere (e lê) dados do banco?
Comment: através de INSERT e SELECT
Comment: Ok, ok, vamos tentar de novo. Que você faz select e insert eu sei, afinal não tem outra forma natural de se fazer isso. Agora, o que eu quero saber é: **qual é o código que você usa para fazer um select no banco de dados**?
Comment: @jbueno o problema é esse ! nao sei como formular o meu codigo para fazer um select !
Comment: @DC Você já consulta algum dado no banco. Não consulta?
Comment: @jbueno A unica coisa que fiz neste projeto foi inserir dados na base de dados
Comment: E qual é o código que você usa para "inserir dados na base de dados"?
Comment: conn.Open();
comm.CommandText = "INSERT INTO Tabela(coluna1, coluna2, ...) VALUES (value1, value2, ...)";
comm.ExecuteNonQuery();
conn.Close();
Answer: Essa é uma ideia de como você pode fazer, existem n formas de se fazer, acredito que você consigo retornar alguns dados para ir testando.
Dentro do select você pode implementar uma cláusula WHERE onde você retornará somente os registros que satisfizerem aquela condição. O retorno da comparação adicionei em uma variável, você pode adicionar em uma lista ou fazer alguma operação caso seja necessário.
Na parte da comparação passei um tipo Int32 sem saber qual é o seu valor de fato, ai você precisa adequar o código para sua necessidade.
public void SelectDescricao()
{
    try
    {
        using(SqlConnection conn = new SqlConnection("Sua string de conexão"))
        {
             using (SqlCommand cmd = new SqlCommand("SELECT coluna1, coluna2, coluna3_Descricao FROM Tabela", conn))
             {
                cmd.CommandType = CommandType.CommandText;

                using (SqlDataReader rd = cmd.ExecuteReader())
                {
                    if (rd.HasRows)
                    {
                        while (rd.Read())
                        {
                            if( variavel1 == Convert.ToInt32(rd["coluna1"].ToString()) && variavel2  == Convert.ToInt32(rd["coluna2"].ToString()))
                            {
                                varDescricao = Convert.ToInt32(rd["coluna3_Descricao"].ToString());
                            }
                        }
                    }
                }
            }
        }
    }
    catch (SqlException ex)
    {
        // tratamento da exceção
    }
}

Comment: Era exatamente isto que eu precisava ! Já ajustei o código à maneira que eu precisava, muito obrigado !
Comment: @DC, que bom que ajudou. Abraço
Comment: Ajudou bastante ! Abraço
Comment: já agora, tenho outra duvida, talvez me possa ajudar
Comment: @DC, diz ai. Qual sua dúvida ?
Comment: consegue ver as minhas outras perguntas ? eu fiz uma pergunta nova. Está lá a minha duvida

Ler dados de uma coluna através do C#


Freely homotopic but not homotopic

Question: I want to find a example of closed paths freely homotopic but not homotopic (I do not have many tools, like fundamental group, then has to be the simplest way possible).
I thought at the following:
$U=\mathbb{R}^2\smallsetminus\{(-1,0),(1,0)\}$;
$\lambda:[0,2\pi]\longrightarrow U, \lambda(t)=(1-cos(t),sin(t))$;
$\mu:[0,2\pi]\longrightarrow U, \mu(t)=(cos(t)-1,sin(t))$.
Clearly they are not homotopic. For free homotopy I thought of exchanging the two paths, but I couldn't write it.
Anyone have any idea?
Thanks.

A free homotopy between two closed paths $\lambda, \mu:[a,b]\longrightarrow X\subset \mathbb{R}^n$ is a continuos function $H:[a,b]\times[0,1]\longrightarrow X$, such that $H(s,0)=\lambda(s)$, $H(s,1)=\mu(s)$ and $H(a,t)=H(b,t), \forall s\in[a,b], \forall t \in[0,1]$.
Comment: What do you mean by '*freely homotopic*' here? You mean, the endpoints are not necessarily fixed?
Comment: See my edits, please.
Answer: Hint. It is not difficult to show that free homotopy classes of closed paths correspond to conjugacy classes in the fundamental group (assume the space is path connected for this)
Therefore you should look for an example with nonabelian fundamental group.
Comment: Indeed, if you show the claim I made in my first paragraph, to get an example you need only find two curves whose classes are conjugated but not equal in the fundamental group.

Freely homotopic but not homotopic


How to tell that a converse of a statement is correct?

Question: This is a problem from "Mathematical Logic for the Humanities" fro mhttp://jiblm.org/guides/index.php?category=jiblmjournal:

Suppose that a homework problem asks you to write the converse of the conditional "If I cash in my chips, then I got a royal flush."
Suppose that a particular student's response is "If I get a royal flush, then
I will cash in my chips." This student's response is not correct. Briefly ex-
plain why, by identifying the error and offering a correction. [Hint: the
truth values of any of the statements involved aren't what matters.]

My answer is that the error lies in the student changing the "got" in the original conclusion into a "get" in the hypothesis of the converse, thereby changing the meaning of the statement altogether. The correct converse should say, "If I got a royal flush, then I cashed in my chips."
Is this correct? Is there a simple test I can run the converse against to verify that it's the correct converse of a statement?
Comment: Well, in a similar spirit, I'd have said "If I got a royal flush, then I will cash in my chips."
Comment: I don't really see a difference between "got" and "get" here
Comment: @IraeVid I believe this exemplifies my confusion at what is the correct way to think about negating a statement when time is a factor.
Answer: The unmistakably correct answer that is obtained by "simply swapping the hypothesis and conclusion" (see text after Definition 50) is "If I got a royal flush, then I cash in [sic] my chips".
Since the phrase is in a natural language and is open to interpretation, Problem 53 is the kind of hair-splitting that drives students away from the course, regardless of their abilities. Deducting points from the student's answer for it being incorrect would be hypocritical, as when proving theorems in mathematics we rather freely interchange equivalent statements with each other — this helps shorten the texts. The pair of statements in question might or might not be equivalent, depending on context; and in a situation that immediately comes to mind, they are equivalent. However their mathematical content depends on formalization, which is swept under the rug here (it would be even more tiresome for the students).
In a Mathematical Logic course one surely needs to pay attention to the content of the statements, and the student's supposed answer warrants a comment that their $\tilde Q\to \tilde P$ may not be really equivalent to $Q \to P$. Though I don't see a good way for the lecturer to deliver a convincing explanation if they are asked to elaborate on this problem, and in any case it would have to detract from mathematics.

On the same page, instead of adding a single word ("Write a different statement..."), the author decides to hide the crux of the whole Problem 57 in brackets — as if the student should have invented it by themselves via double-think. A statement is always equivalent to itself — this is not a "too simple to be simple" situation. Sorry for the vent...
Answer: Actually, the problem deals more with negating a (simple) implication properly than wording it correctly.
Let's rename the two statements "Cashing in the chips" and "Having a royal flush" as $p$ and $q$ respectively, so that the first proposition is written as $p \rightarrow q$. Then, its contraposition is given by $p \rightarrow q \equiv \lnot q \rightarrow \lnot p$, which can be worded as "If I haven't got any royal flush, then (it means that) I didn't cash in my chips".
The statements of this problem have been a bit poorly chosen, in that $p$ and $q$ are not really simultaneous and our brains feel unnatural to conceive this causal relation in a chronologically reversed and negated order. confusion may come from the fact that the You can replace $p$ by "It's rainy" and $q$ by "It's cloudy" in order to convince yourself.
Comment: You have an equality between the negation of a conditional and its contrapositive, which is not correct. Typo? I think you don't want the negation before the brackets, i.e. the conditional is equivalent (use tribar or biconditional) to its contrapositive.
Comment: @MariuszPopieluch  Thank you for spotting the typos, my bad. It is now corrected.
Comment: @Abezhiko This is not about contraposition. The manual (p16, Def50) states: "Let $P$ and $Q$ be statements. The conditional $Q \to P$ is called the *converse* of the conditional $P \to Q$." OP's problem is number 53.


Bootstrap Grid System does not work inside mat-expansion-panel

Question: When using the Boostrap 4 grid system inside the Angular/Material mat-expansion-panel, the grid elements do not fit into the grid. All elements in a row do not fit and the last element carries over to a new line.
Answer: The Bootstrap grid system expects all elements to have the box-sizing set to border-box. To fix this just add the following css to your page.
.mat-expansion-panel{
    box-sizing: border-box;
}

Answer: for all elements in a row, obviously have col-* class, add this style:
col-* {  box-sizing: border-box;}


include file in .htaccess

Question: Is it possible to include a .htaccess in another .htaccess file.  The purpose would be to have a single location of all .htaccess.
Thanks
Jean
Answer: It seems it's not possible.
But you could use any htaccess rules in httpd conf VirtualHost or Directory conext, where includes are possible.
E.g.:
<code><Directory /var/www/site1/>
   <...>
   Include /etc/apache/conf.d/site1-htaccess.inc
</Directory>
</code>
See also: http://httpd.apache.org/docs/2.0/mod/core.html#include
Comment: But would not that require an apache restart
Comment: No, it would require reload (graceful restart - no connections aborted). If you need grant reload rights to non-privileged users, you could use sudo.
Comment: Which is exactly I dont want to do.  If I do require, I have to restart apache via a php page.
Answer: If I understand correctly, Apache will check for an .htaccess file in every directory above the current one where AllowOverride is set to something other than None.
This means if your DocumentRoot for a site is /var/www/hello/, and it's serving a request for /path/name/filename, it will check for:
/.htaccess
/var/.htaccess
/var/www/.htaccess
/var/www/hello/.htaccess
/var/www/hello/path/.htaccess
/var/www/hello/path/name/.htaccess
So if you like, you can use a single .htaccess file in your server's DocumentRoot, or even above that to affect multiple sites, as long as AllowOverride allows it for that directory.
Comment: And it will combine all that match?
Comment: @nafg Yes, any directives found in a later .htaccess file should take precedence over what's in the earlier ones, provided the server's AllowOverride for that directory permits it.

include file in .htaccess


Is FOL equivalent to Turing Machines?

Question: Does every FOL (axiom set expressible in First Order Logic) have a corresponding Turing machine?
The proved FOL statements would be strings the Turing machine accepts.
Does every Turing machine have a FOL?
The strings the Turing machine accepts are proved by a finite set of FOL axioms.
Someone said this:

Meanwhile, FOL (unlike propositional logic) is Turing-complete in an appropriate sense

(See comments on https://math.stackexchange.com/a/3635100/187128)
Answer: Yes.
Turing himself showed that you can describe the behavior of any Turing-machine using FOL statements, and with that you can indeed show that any FOL statements a Turing-machine accepts would indeed be provable from a finite set of FOL axioms.
Going the other way around, for every finite set of FOL Axioms, you can construct a Turing machines that accepts all and only those statements provable from it.  This is closely related to Godel's Completeness Theorem: it turns out there is an algorithm that cranks out all and only valid FOL statements, and thus also a Turing-machine that can do that.

Is FOL equivalent to Turing Machines?


python console closes before it starts

Question: I am learning Python and came across this problem. I know that i can put "input()" at the bottom of the program, but the problem is that it IS there, but console terminates nevertheless. It seems like the programm never starts at all. I am using the 3.5 version of Python.
Comment: What are you trying to run and how are you running it? Is this on Windows/mac/linux?
Answer: Open a terminal, navigate to the directory of your file, and type python myfile.py. If you just double click the file in your system explorer it will run and close when it finishes, which is often too fast to see what's going on.
Answer: I think you are starting the programme  by clicking on it don't do that to run your programme follow following steps
1.open command prompt
2. go to the path where you have your python programme
3. use command for python for eg: python programme.py in linux
4. if it says python command not recognised probably because the path to python executable is not present in system path add it to environment variable and that should work fine

python console closes before it starts


CFA with R - small sample size - also different outcomes at different times

Question: I have the following problem:
We have a model of 3 latent variables with 8 observed variables each.
Our sample size is 19, which can't be upped because it is a special subgroup of the population and this is a pretest to see if the factor structure is roughly as expected, so we can use the scale in an even smaller sample.
The syntax is as follows:
model <- "
    L = ~ LM_S + LM_W + LM_S + LM_Au + LM_Fae + LM_Fah + LM_E + LM_An
    A = ~ AM_Fr + AM_P + AM_T + AM_B + AM_G + AM_Fa + AM_PZ + AM_PU
    M = ~ MM_G + MM_R + MM_Fah + MM_Fae + MM_Vo + MM_E + MM_H + MM_Ve
    "

    fit <- cfa (model, data=trp_int_pretest)
    summary (fit, fit.measures=TRUE, standardized=TRUE)

When I first ran the script yesterday evening, it gave me an error message, but calculated the model, leaving out "M". When I calculated it this morning, it calculated the model just with "L" and now it doesn't calculate it a all.
This is the error message the first 2 times:
Error in lav_samplestats_icov(COV = cov[[g]], ridge = ridge.eps, x.idx = x.idx[[g]],  :
lavaan ERROR: sample covariance matrix is not positive-definite
In addition: Warning message:
In lav_data_full(data = data, group = group, cluster = cluster,  :
lavaan WARNING: small number of observations (nobs < nvar)
nobs = 19 nvar = 24

Now I get the additional message:
Error in h(simpleError(msg, call)) :
Fehler bei der Auswertung des Argumentes 'object' bei der Methodenauswahl für Funktion 'summary':
object 'fit' not found

(Also, this is a German error message. I am German but never saw a German error message before.)
So questions are as follows:

How can the program react so differently over time? What might be going on?
Why does it not find the object "fit"? It seems it does not compute it anymore - is this right? (See 1)
Is there anything we can do to test the structure? I ran a factor analysis for every latent factor, but this is of course no solution. (Model-fit was not good)

(Tried fixing covariances of the latent factors, but no different outcome)
Answer:
I'm going to guess that the first time you ran it you ran the CFA command only. That gives the first error message (which comes from Lavaan). The second time you ran it, you ran the summary command, which said "I can't find 'fit', so I don't know what to do". This message came from base R so it is in German. If I try to run the second command only, I get the same error:

    summary (fit, fit.measures=TRUE, standardized=TRUE)
    Error in h(simpleError(msg, call)) :
      error in evaluating the argument 'object' in selecting a method for function 'summary': object 'fit' not found

Your sample is too small. You need to have more rows than columns in your data frame. The program can't estimate the CFA, so 'fit' does not exist.

Your sample is too small. Even if fit could be calculated, 19 is not a large enough sample to run any sort of CFA, regardless of the number of variables. Your results will not be meaningful or useful.

Yes. It doesn't find 'fit' because there was an error when it tried to generate fit so fit does not exist.

No. Your sample is too small. Sorry to be the bearer of bad news.
Comment: Thanks a lot for the thorough explanation. Yeah, hope was small, but never the less... Will wait one more day and then mark your answer as a solution.


Hierarchical select ajax conflict in custom bootstrap theme

Question: I have created a custom theme from scratch using twitter Bootstrap. In my content type there is Taxonomy term Hierarchical Select (HS) list.
Problem: When authenticated user try to select any term from first level, HS keeps on loading...for ever.
Note: Hierarchical select is working fine for admin with core Seven theme enabled and with jQuery update version 7.
Please help.
Answer: It was Colorbox which was conflicting with HS. I disabled the colorbox module and it worked perfectly. I don't know why this happens, but this should be raised as an issue since both are contrib modules.
Comment: I got the same problem and resolved by the suggested solution!! Thanks~ save my day
Comment: I don't have colorbox module enabled, but still have issue with Bootstrap sub-theme.


EntityQuery not returning content based on language

Question: I'm trying to get a list of all of a specific content type, but my entityQuery is only returning the original language of the site (English). Here's my code:
<code>  public function fetchDocumentReferenceOptions() {
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$query = \Drupal::entityQuery('node')
  ->condition('status', 1)
  ->condition('type', 'document')
  ->condition('langcode', $language)
  ->sort('title', 'ASC');

$nids = $query->execute();

$nodes = node_load_multiple($nids);

$options = [];

foreach($nodes as $node)
{
  // check if the document (content type) has an uploaded file
  if ($node->field_document->entity) {
      $options[$node->id()] = $node->getTitle();
  }
}

return $options;
</code>
}
This is how I call the function:
<code>'#options' => $DocumentReferenceCore->fetchDocumentReferenceOptions(),
</code>
What I am expecting, based on condition for langcode would be that, if, for example, I am editing a Chinese language node (translated from the original English node), I should see Chinese nodes, and the content being returned, but instead I am still seeing the original English content.
What am I doing wrong here?
Comment: Your code should work, i have tested it i works perfectly, but i just call the function  directly not in some form `#options' => ...` , try to dump the `$language` and se if it's the right language !   the condition is right.
Answer: Content entities have an active language concept. When loaded, they by default return values for the default translation.
With your query, you know it has that translation, so you can use this code.
<code>$node = $node->getTranslation($language);
</code>
If you're not sure it exists, you can use this code.
<code>$custom_tag = \Drupal::service('entity.repository')->getTranslationFromContext($node, $desired_langcode);
</code>
That will return the node matching the language, if it exists, or the best alternative. You can also leave out the language code; in that case it will use the current content language.
Comment: I'm having translation issues. I have a custom block in which I EntityQuery multiple nodes and deliver them to a twig template. The nodes are always in the default site language. Your $custom_tag suggestion fixes the issue @Berdir, but I would like to understand why they do not return the translated values by default, as you suggest in your first statement.
Comment: OK, I just understood what you meant in the opening sentence: by default, all content entity queries return the default site language. I guess the 'active language concept' means I have to 'actively' translate them to the language I need? Thanks @Berdir, as usual ;)


Remove Done bar on IQKeyboardManagerSwift

Question: Im new to this lIbrary and to swift and im looking to remove this "Done" grey bar. How can I go about doing this? And other input would be of great help.

import UIKit
import Firebase
import IQKeyboardManagerSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        //Configures all of Firebase
        FIRApp.configure()

        //Configure Key Board manager from Library (IQKEYboardManagerSwift)
        IQKeyboardManager.sharedManager().enable = true

        //Tab Bar Appearnece
        UITabBar.appearance().barTintColor = UIColor.black
        UITabBar.appearance().tintColor = UIColor.white

        return true
    }

Answer: In your AppDelegate you can add:
IQKeyboardManager.sharedManager().enableAutoToolbar = false

to disable the toolbar.
Also under MARK: IQToolbar handling you'll find properties which might help you customize the toolbar the way you want.
Don't forget to explore the IQKeyboardManager.swift class a bit ;]
Comment: Thank you. You are much appreciated.
Answer: In Latest swift:
IQKeyboardManager.shared.enableAutoToolbar = false

Answer: Swift 4.2
import IQKeyboardManagerSwift

then
IQKeyboardManager.shared.enableAutoToolbar = false

Answer: Also, if you want to disable it for a specific textfield you can use
Swift 4.2+:
   self.textfield.inputAccessoryView = UIView()

Objective-C:
   self.textField.inputAccessoryView = [[UIView alloc] init];

More on that here


Size of the set of locally $1/2$ Hölder continuous times for the Brownian motion

Question: I read in these notes, in the remark to corollary 4.3., that with probability one, the set of locally $1/2$ Hölder continuous times is of measure zero in $[0,1]$. I would like to use this fact for a problem I'm working on, but I do not know how to prove it. Does anyone have any references or ideas? I'm tried a proof by contradiction, but I'm not sure wherein the contradiction would lie. Obviously the Brownian motion can't be Hölder continuous of order $1/2$ on any interval, but all I've been able to get by supposing a contradiction is the existence of a closed, positive measure set on which it's Hölder continuous of order $1/2$. Is this impossible?
Thanks!
Comment: If you'd like a reference on top of saz's great answer, the textbook as standard as Karatzas and Shreve seems to have a discussion; see pp. 113-114 and p. 127.
Comment: The monograph by Mörters & Peres also discusses some results, see in particular Section 10.3.
Answer: Consider the mapping
$$(t,\omega) \mapsto L(t,\omega) := \sup_{h \in (0,1)} \left| \frac{B(t+h,\omega)-B(t,\omega)}{\sqrt{h}} \right|.$$
Since the Brownian motion has continuous sample paths, we have
$$L(t,\omega) = \sup_{h \in (0,1) \cap \mathbb{Q}} \left|  \frac{B(t+h,\omega)-B(t,\omega)}{\sqrt{h}} \right|,$$
and using that the mapping $(t,\omega) \mapsto B(t,\omega)$ is measurable, it follows that $(t,\omega) \mapsto L(t,\omega)$ is measurable. In particular,
$$(t,\omega) \mapsto 1_{\{|L_t(\omega)|<\infty\}}$$
is measurable. The law of the iterated logarithm shows that $\mathbb{P}(|L_t|<\infty)=0$ for each $t>0$, and therefore
$$\int_0^1 \mathbb{P}(L_t<\infty) \, dt = 0.$$
An application of Tonelli's theorem shows that
$$0=\int_0^1 \mathbb{P}(L_t<\infty) \, dt = \mathbb{E} \left( \int_0^1 1_{\{|L_t|<\infty\}} \, dt \right) = \mathbb{E}(\lambda(\{t \in [0,1]; |L(t,\cdot)|<\infty\})).$$
Hence,
$$\lambda(\{t \in [0,1]; |L(t,\cdot)|<\infty\})=0 \quad \text{almost surely}$$
Remark: The points $t$ for which $|L(t,\omega)|$ is finite are called slow points. They have been studied quite intensively in the 80s, e.g. by Kahane, Perkins et al. ; they obtained quite interesting results on the Hausdorff dimensions of slow points as well as possible values for the Hölder constant. You can find references to some of the papers e.g. in the monographs by Karatzas & Shreve and Mörters & Peres.
Comment: I tried this technique but I didn't see how to show $\mathbb{P}(|L_t|<\infty)=0$. I'm afraid I still don't. Could you please expand on that a bit further?
Comment: @DavidBowman For each fixed $t$, the process $W_h := B_{t+h}-B_t$, $h \geq 0$, defines a Brownian motion, and therefore the LIL gives $$\mathbb{P} \left( \limsup_{h \downarrow 0} \frac{W_h}{\sqrt{2h \log \log(h^{-1})}} = 1 \right)=1$$ which entails $$\mathbb{P} \left( \limsup_{h \downarrow 0} \frac{|W_h|}{\sqrt{h}} = \infty \right)=1,$$ i.e. $$\mathbb{P} \left( \limsup_{h \downarrow 0} \frac{|B_{t+h}-B_t|}{\sqrt{h}}=\infty \right)=1.$$
Comment: Of course. Thank you!
Comment: @DavidBowman You are welcome.
Comment: Why does the second step in your comment follow from the LIL or rather why is the limsup  almost surely equal to infinity?


Add calculated value to DatagridView from getting value from another datagridview in vb.net

Question: I have an vb.net windows application that has some values which i entered through textbox.
And two datagridviews, in that in first datagridview ,when i enter values in all columns, i have a formula which takes value from Textboxes and DatagridView1 column values. These calculated value should display in second datagridview columns.
For this i tried two ways but both showing problem.
    First try:
//First Datagridview -LogCalcEnter , Second Datagrid - LogCalValue

    Private Sub LogCalcEnter_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles LogCalcEnter.CellValueChanged

    LogCalValue.Rows(intRow).Cells(0).Value = LogCalcEnter.Rows(iRow).Cells(0).Value * fPorCutoff.Text

    LogCalValue.Rows(intRow).Cells(1).Value = LogCalcEnter.Rows(iRow).Cells(1).Value * fSWCutoff.Text

        End Sub

When executing the application,before showing the form below  error occurs at
Me.MainForm = Global.LogCalculation.Form1 in     OnCreateMainForm().

Additional information: An error occurred creating the form. See
  Exception.InnerException for details.  The error is: Index was out of
  range. Must be non-negative and less than the size of the collection.
  Parameter name: index

So i tried another option i have button in form, when i press button,then depends on number of rows in first grid view i will set the values for second datagrid.
But it works if i have one row in Datagridview1. If more than one row, it shows error at second row.
 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim oLog As New Log
        oLog.sWellName = tWellname.Text
        oLog.fPoroCutoff = fPorCutoff.Text
        oLog.fSWCutOff = fSWCutoff.Text
        oLog.fN = fN.Text
        oLog.fM = fM.Text
        oLog.fA = fA.Text
        oLog.fRW = fRW.Text
        For iRow = 0 To LogCalcEnter.Rows.Count - 1
            If (Trim(LogCalcEnter.Rows(iRow).Cells(0).Value) <> "" And Trim(LogCalcEnter.Rows(iRow).Cells(1).Value) <> "" And Trim(LogCalcEnter.Rows(iRow).Cells(2).Value) <> "") Then

                LogCalValue.Rows(iRow).Cells(0).Value = LogCalcEnter.Rows(iRow).Cells(0).Value * oLog.fPoroCutoff
                LogCalValue.Rows(iRow).Cells(1).Value = LogCalcEnter.Rows(iRow).Cells(1).Value * oLog.fSWCutOff
                LogCalValue.Rows(iRow).Cells(2).Value = LogCalcEnter.Rows(iRow).Cells(2).Value * oLog.fN

            End If
        Next iRow
    End Sub

Actually i want the first option only. But here these two cases get failed.
Answer: In the first event, your intRow & iRow may not be defined.
Try this instead,
LogCalValue.Item(0, e.RowIndex).Value = LogCalcEnter.Item(0, e.RowIndex).Value * fPorCutoff.Text

LogCalValue.Item(1, e.RowIndex).Value = LogCalcEnter.Item(1, e.RowIndex).Value * fSWCutoff.Text

Comment: Check this [link](http://stackoverflow.com/questions/11887232/error-inside-of-application-designer-vb-inside-of-oncreatemainform-sub), it could be related to your issue.


Pandas expand rows from list data available in row

Question: I have a data frame like this in pandas

The output shows ... which i highlighted here and it shows first 5 rows and last 5 rows. But i want to get first 25 rows as my results and download that output as a txt file.
Answer: You should use
pandas.set_option to achieve your goal
You could run below command:
import pandas
pandas.set_option('display.max_rows', None)  # list all rows

or
pandas.set_option('display.max_rows', 25)  # list max to max 25 rows

Comment: ('display.max_rows', None) shows all the rows but ('display.max_rows', 25) is not working.
Answer: file = data.iloc[0:25]
file.to_csv('data.txt')


Android using float[] as vertices causes OpenGL error 0x502

Question: I am trying to use an array of floats for my verticies in OpenGLES 2.0 on Android instead of a FloatBuffer but When I do I glDrawArrays gives the error 0x502 or GL_INVALID_OPERATION.
I do not get this error and everything works fine when I use FloatBuffers.
I have read that this error is normally caused by a program not being set. I only use one shader program and I set it when everything initialized.
Here is my code
public class LineEngine {
    private static final float[] IDENTIY = new float[16];
    private float[] mLinePoints;
    private float[] mLineColors;
    private int mCount;

    public LineEngine(int maxLines) {
        Matrix.setIdentityM(IDENTIY, 0);

        mLinePoints = new float[maxLines * 2 * 4];
        mLineColors = new float[maxLines * 2 * 4];

        reset();
    }

    public void addLine(float[] position, float[] color) {
        int offset = mCount * 2 * 4;
        System.arraycopy(position, 0, mLinePoints, offset, 8);
        System.arraycopy(color, 0, mLineColors, offset, 4);
        System.arraycopy(color, 0, mLineColors, offset + 4, 4);

        mCount++;
    }

    public void reset() {
        mCount = 0;
    }

    public void draw() {
        if (mCount > 0) {
            GraphicsEngine.setMMatrix(IDENTIY);
            GraphicsEngine.setColors(mLineColors);
            GraphicsEngine.setVertices4d(mLinePoints);
            GraphicsEngine.disableTexture();
            GLES20.glDrawArrays(GLES20.GL_LINES, 0, mCount * 2);

            int error = GLES20.glGetError();
            if (error != 0)
                Log.e("OpenGL", "Draw " + error); // Prints error 1282

            GraphicsEngine.disableColors();
            reset();
        }
    }
}

This code works fine with no errors
public class LineEngine {
    private static final float[] IDENTIY = new float[16];
    private FloatBuffer mLinePoints;
    private FloatBuffer mLineColors;
    private int mCount;

    public LineEngine(int maxLines) {
        Matrix.setIdentityM(IDENTIY, 0);

        ByteBuffer byteBuf = ByteBuffer.allocateDirect(maxLines * 2 * 4 * 4);
        byteBuf.order(ByteOrder.nativeOrder());
        mLinePoints = byteBuf.asFloatBuffer();

        byteBuf = ByteBuffer.allocateDirect(maxLines * 2 * 4 * 4);
        byteBuf.order(ByteOrder.nativeOrder());
        mLineColors = byteBuf.asFloatBuffer();

        reset();
    }

    public void addLine(float[] position, float[] color) {
        mLinePoints.put(position, 0, 8);
        mLineColors.put(color, 0, 4);
        mLineColors.put(color, 0, 4);
        mCount++;
    }

    public void reset() {
        mLinePoints.position(0);
        mLineColors.position(0);
        mCount = 0;
    }

    public void draw() {
        if (mCount > 0) {
            mLinePoints.position(0);
            mLineColors.position(0);
            GraphicsEngine.setMMatrix(IDENTIY);
            GraphicsEngine.setColors(mLineColors);
            GraphicsEngine.setVertices4d(mLinePoints);
            GraphicsEngine.disableTexture();
            GLES20.glDrawArrays(GLES20.GL_LINES, 0, mCount * 2);

            int error = GLES20.glGetError();
            if (error != 0)
                Log.e("OpenGL", "Draw " + error); // no errors

            GraphicsEngine.disableColors();
            reset();
        }
    }
}

The related GraphicsEngine code is here
public static void setVertices4d(FloatBuffer vertices) {
    GLES20.glVertexAttribPointer(aVertexHandle, 4, GLES20.GL_FLOAT, false,
            16, vertices);
    GLES20.glEnableVertexAttribArray(aVertexHandle);
    mState.shape = -1;
}

public static void setVertices4d(float[] vertices) {
    GLES20.glVertexAttrib4fv(aVertexHandle, vertices, 0);
    GLES20.glEnableVertexAttribArray(aVertexHandle);
    mState.shape = -1;
}

public static void setColors(FloatBuffer colors){
    GLES20.glVertexAttribPointer(aColor, 4, GLES20.GL_FLOAT, false,
            16, colors);
    GLES20.glEnableVertexAttribArray(aColor);
    GLES20.glUniform1i(GraphicsEngine.uEnableColors, 1);
}

public static void setColors(float[] colors){
    GLES20.glVertexAttrib4fv(aColor, colors, 0);
    GLES20.glEnableVertexAttribArray(aColor);
    GLES20.glUniform1i(GraphicsEngine.uEnableColors, 1);
}

I don't want to use FloatBuffers because they are slower to change than an array of floats.
Answer: You don't have a choice but to use FloatBuffers for this code.
Your setVertices4d method which takes a float[] is broken, you cannot use glVertexAttrib4fv in that way. glVertexAttrib4 only specifies a single vertex, and using the v version just passes the values of an attribute as an array to that single vertex, it doesn't set up a vertex array similar to the pointer functions.
Comment: Uniforms and Attributes are totally different. Uniforms are just a single value that's always constant. When you're specifying attributes, you're creating a big list of attributes such that you have one per vertex. glVertexAttrib specifies attributes for a single vertex at a time. If you want to define an array of vertices, then you must use glVertexAttribPointer with the FloatBuffers.
Comment: Do you know where I can find any documentation on all of this?
Comment: Just the sdk/docs which you've found is the only source I know, you'll learn this stuff the more time you spend with it. I can see where you're coming from that you would think that you can specify an array of vertices with that, but it just doesn't work that way. I think you would use the vector form of that function for example if you were doing multitexturing, and you wanted to pass an array of multiple texcoords to each vertex.
Comment: `glVertexAttribX` can only set the attribute values for a single vertex **and** a single attribute. So this multitexturing idea won't work that way, too. Any array larger than 4 elements won't make any sense to this function, which is just there if you have your vertex attribute as, say, a vector of 4 values. But of course the overall answer is correct and you (OP) are using this function in the wrong way. Since you (OP) enable the attribute arrays anyway, the values set with `glVertexAttrib` are not used anyway, as they only grip when the respective array is disabled.
Comment: Oh yes my bad, for some reason I thought that **4v** meant 4 * number of vectors, not just a pointer to 4 floats. Don't use it very often, my mistake!
Comment: You can use glUniform4fv to pass in a float[] with a length more than 1 for uniforms though right? I'm doing that in another section of my code and it's working. Is it something unique about vertex attributes that makes it so you can't?

Looking at http://www.khronos.org/opengles/sdk/docs/man/xhtml/glVertexAttrib.xml it says _Specifies a pointer to an array of values to be used for the generic vertex attribute._ That makes it sound like you can pass in more than one value.


Unable to retrieve value from json result MVC 4

Question: I'm unable to get the desired result from JSON controller Action. I have searched the internet but no suggested solutions could solve my problem.
My Controller Action:
public JsonResult AutoComplete(string term)
        {
            var result = (from c in db.CategoryContents
                          where c.Title.ToLower().Contains(term.ToLower())
                          select new { c.Title, c.ImageURL, Description = c.Category.Name + " Review" }).Distinct();
                            return Json(result, JsonRequestBehavior.AllowGet);
        }

This is my jQuery ajax file:
$(document).ready(function () {

            var displayLimit = 7;

    // jqueryui autocomplete configuration
    $("#term").autocomplete({
                    source: function (req, resp) { // get JSON object from SearchController
            $.ajax({
                url: "/Search/AutoComplete", // SearchController JsonResult
                type: "POST",
                dataType: "json",
                data: { term: req.term },
                success: function (data) {
                    resp($.map(data, function (item) {

                        return { label: item.Name, value: item.Name, imageURL: item.ImageURL, id: item.ID };
                    }

                    ));
                }
            });
        },

        select: function (event, ui) { // keyword selected; parse values and forward off to ProductController's ViewProduct View
            var selected = ui.item;
            var mdlNum, mdlName;

            if (selected.value !== null) {
                var array = selected.value.split(' ');
                mdlNum = array[0].toLowerCase();
                //   mdlName = selected.value.replace(array[0], '').trim().toLowerCase().replace(/[^a-z0-9]+/g, ' ');
                // window.location.replace('http://' + location.host + '/Search/Refine?ref=' + mdlNum + '' + mdlName);
                window.location.replace('http://' + location.host + '/Category/Details/' + ui.id);

            }

        },

        open: function () { $('ul.ui-autocomplete').addClass('opened') },
        close: function () { $('ul.ui-autocomplete').removeClass('opened').css('display', 'block'); }

    })

.data("ui-autocomplete")._renderItem = function (ul, item) {

            //var inner_html = '

' + item.label + '

' + item.description + '

';

            var newText = String(item.value).replace(
                   new RegExp(this.term, "gi"),
                   "$&"
                 //  "$&"
                   );

            var inner_html = '

' + newText + '

' + item.id + '

';

            return $("

")
                .data("item.autocomplete", item).append(inner_html)
                .appendTo(ul);

        };

It is not returning productId, I have got error on this line:
window.location.replace('http://' + location.host + '/Category/Details/' + ui.id);

It is saying /Category/Details/undefined but I want id here instead of undefined. Please help.
Answer: You need to return your ID from your autocomplete, it is missing from your projection.
Change it to the following instead:
var result = (from c in db.CategoryContents
                          where c.Title.ToLower().Contains(term.ToLower())
                          select new { c.Title, c.ImageURL, Description = c.Category.Name + " Review", ID = c.ID }).Distinct();
                            return Json(result, JsonRequestBehavior.AllowGet);

The above assumes that your ID in the db is uppercase.
Comment: thanks it solved my problem but when I applied your code my renderItem method giving error, I have edited my jquery code now u can see.
Comment: http://stackoverflow.com/questions/22097793/unable-to-render-html-in-jquery-autocomplete-mvc4 this is the link sir, please help me
Answer: jQuery UI Autocomplete needs a datasource with just label and value properties. Even though you're passing it extra properties: imageURL and id, those won't be available in your select callback.
Change this:
resp($.map(data, function (item) {
    return { label: item.Name, value: item.ID, imageURL: item.ImageURL, id: item.ID };
}

And this:
window.location.replace('http://' + location.host + '/Category/Details/' + ui.item.value);

I've changed it so the value for each suggestion item is set as the item.ID from your web service. This is then available through ui.item.value in the callback.


What do you think is wrong with following reasoning of 'students'?

Question:
Albert announces to his class that he plans to surprise them with a
  quiz sometime next week.
His students first wonder if the quiz could be on Friday of next next.
  They reason that it can't: if Albert didn't give the quiz before
  Friday, then by midnight Thursday, they would know the quiz had to be
  on Friday, and so the quiz wouldn't be a surprise any more.
Next the students wonder whether Albert could give the surprise quiz
  Thursday. They observe that if the quiz wasn't given before Thursday,
  it would have to be given on the Thursday, since they already know it
  can't be given on Friday. But having figured that out, it wouldn't be
  a surprise if the quiz was on Thursday either. Similarly, the students
  reason that the quiz can't be on Wednesday, Tuesday, or Monday.
  Namely, it's impossible for Albert to give a surprise quiz next week.
  All the students now relax, having concluded that Albert must have
  been bluffing.
And since no one expects the quiz, that's why, when Albert gives it on
  Tuesday next week, it really is a surprise!
Comment: This is a variant of [Unexpected hanging paradox](https://en.wikipedia.org/wiki/Unexpected_hanging_paradox)
Answer: The question is not if a quiz is a surprise, but when a quiz is a surprise. The students' argument only demonstrates that one will always have foreknowledge of the quiz as some point beforehand, but up until the day before you don't know.
Answer: There is a large literature on this sort of puzzle. For a helpful introduction, start here.


Como ligar tabelas que estão em bases de dados diferentes?

Question: Gostaria de saber como posso ligar duas tabelas que estão em bases de dados diferentes por forma a achar dados que são semelhantes nas duas tabelas.
Por exemplo, podemos ter a tabela Lista de compras por fazer e tabela Lista de compras feitas, para no fim auto criar uma tabela dos itens que constam na mesma tabela deixando de lado os itens que não foram comprados.
Comment: Utilize o `JOIN` do MySQL para mesclar dados de tabelas diferentes.
Answer: Unindo tabelas com UNION e JOIN:
Você usa UNION na "Vertical", para relacionar conforme a pergunta, em linhas separadas:

Search em várias tabelas

Qual é a diferença entre UNION e UNION ALL?

Buscar em tabelas diferentes sabendo de qual veio o resultado

Você usa JOIN na "Horizontal", para relacionar duas tabelas na mesma linha:

Selecionar dados de duas tabelas

Qual é a diferença entre INNER JOIN e OUTER JOIN?

Aplicando a bases de dados diferentes:
Como você falou que se tratam de bases de dados diferentes, você deve prefixar o nome das tabelas com suas respectivas bases (aplicável tanto a UNION quanto JOIN):
SELECT tabelaA.campo1, tabelaB.campo2 FROM baseA.tabelaB JOIN baseC.tabelaD ON <condicao>
                                           -----              -----

 E se por acaso as tabelas possuirem o mesmo nome nos DBs diferentes?
Aí você usa um alias em cada uma:
SELECT aliasX.campo1, aliasY.campo2
FROM baseA.tabela AS aliasX
JOIN baseC.tabela AS aliasY ON <condicao>

 E se as bases de dados estiverem em servidores separados?
Uma das soluções seria resolver o problema na linguagem cliente (PHP no caso), simplesmente executando duas queries e mostrando os resultados em seguida (ou filtrando e mostrando com operações de array por exemplo).
Dependendo da aplicação, pode usar FEDERATED TABLES, mas precisa tomar cuidado com a eficiência da aplicação:
create table t1 (
a int,
b varchar(32))
ENGINE=FEDERATED CONNECTION='mysql://user@hostname/test/t1'
                 -- aqui vão os dados do outro servidor --

Mais detalhes aqui:

Como faço para usar MySQL Federated?

The FEDERATED storage engine

Wikipedia - MySQL Federated
Comment: ficou muito bom. Só uma observação para ele: A depender da situação, ele teria que testar resolvendo o problema no back-end (como foi citado na resposta) ou plataformas como `ElasticSearch`, `Memcached` etc. Talvez ele vá perder [performance](https://dev.mysql.com/doc/refman/5.6/en/federated-usagenotes.html) com tabelas federadas.


Using PreparedStatement template issue

Question: Here's my static utility:
<code> //String sqlQuery = "select count(name) as num from tbname where name = ?"
    //String name = "testString";

    private static int correct(Connection connection, String sqlQuery, String name) {
        int result = 0;
        PreparedStatement statatement = null;
        ResultSet rs = null;
        try {
            statatement = connection.prepareStatement(sqlQuery);
            statatement.setString(1, name);
            rs = statatement.executeQuery();
            while (rs.next()) {
                result = rs.getInt("num");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                statatement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e.getMessage());
            }
            return result;
        }
    }
</code>
The method above returns 0 (incorrect result), but the following one returns '1' (it works OK, it the same sql query):
<code>//String sqlQuery = "select count(name) as num from tbname where name = 'testString'"

    private static int correct(Connection connection, String sqlQuery, String name) {
        int result = 0;
        PreparedStatement statatement = null;
        ResultSet rs = null;
        try {
            statatement = connection.prepareStatement(sqlQuery);
            rs = statatement.executeQuery();
            while (rs.next()) {
                result = rs.getInt("num");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                statatement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e.getMessage());
            }
            return result;
        }
    }
</code>
Could you please give me any advise, so I could resolve the problem.
PS: I'm not sure if it does matter, but the actual streetName - has a name in windows-1251 encoding (Russian) text.
PPS: The database is Oracle 10.
Comment: You've stated some facts but not told us what the problem is yet...
Comment: When I ran sql query via setting sql template (statement.setString(1, name) it does not work correctly. When I ran the same sql query as dynamic it does work.
Comment: What does show SQL editor with this query? (try SQL Developer or similar tool).
Comment: Is there any `SQLException` dumped to the error output? (The code does have issues with error handling and resource management.)
Answer: It seems the encoding conflict with the one which you set in your DB encoding charset and the the String you are passing..
You can do these 2 tries

Set the DB encoding to UTF-8 and then give a try. If this does not work you may go with following 2nd option

Set DB encoding charset to UTF-8 and also set the String by using this String constructor <code>String(byte[] bytes, String charsetName) </code>
Answer: It might be a character set issue. According to the Oracle JDBC Drivers release 10.1.0.2.0 (10g) README:

The following is a list of known
  problems/limitations:

If the database character set is AL32UTF8, you may see errors under the
  following circumstances:

accessing LONG and VARCHAR2 datatypes.
binding data with setString() and setCharacterStream().

So if your database character set is AL32UTF8, you might have to get it changed to something else.
Also, what is the datatype of your column? VARCHAR2?

Using PreparedStatement template issue


Perfect square as sum of two perfect squares

Question: I refer to this question.
Given a perfect square, can you prove that it is a sum of two perfect squares?
I recently saw this:

Let $p,q$ be primes. $p_i \equiv 1 \pmod 4$ and $q_i \equiv 3 \pmod 4$.
$N=p_1^{a_1}p_2^{a_2}\cdots q_1^{b_1}q_2^{b_2}\cdots$
$N$ can be written as sum of 2 squares iff all $b$ are even.

I used an identity that can multiply two numbers that can be written as sum of two perfect squares into a number that can be written as two perfect squares. And I have proved that the $p$ part can be written as two squares. Hence it is left to prove that the $q$ part can be written as sum of two squares.
Any help is appreciated. Thanks.
Comment: A good book - Proofs from THE BOOK by Aigner, Martin, Ziegler, Günter M. (P.17)
Comment: In case you allow $0^2$, then $a^2=a^2+0^2$. Otherwise, $9=3^2$ is a counterexample.
Comment: $0$ should be allowed.
Comment: How would you write $9$ as the sum of two squares
Comment: @PrasunBiswas Oh thank you! I didn't think of 0... Should I delete the question or what?
Answer: This is the outline of the proof found in the book "Proofs from THE BOOK" (P.17-22) by Aigner, Martin, Ziegler, Günter M. It is too long to put in a comment so I put it here. Please do not vote for it.
Lemma 1. For primes $p=4m+1$ the equation $s^2\equiv -1$ (mod $p$) has two solutions $s\in\{1,2,\dots,p-1\}$, for $p=2$ there is one such solution, while for primes of the form $4m+3$ there is no solution
Lemma 2. No number $n=4m+3$ is a sum of two squares.
Proposition. Every prime of the form $p=4m+1$ is a sum of two squares, that is, it can be written as $p=x^2+y^2$ for some natural numbers $x,y\in\mathbb{N}$
Theorem. A natural number $n$ can be represented as a sum of two squares if and only if every prime factor of the form $p=4m+3$ appears with an even exponent in the prime decomposition of $n$.
Comment: Rather than asking others not to vote your answer, you can make this answer a community wiki if you don't want the free rep.
Answer: The proof is not very hard when using the decomposition of prime numbers in the  Gaussian ring $\mathbf Z [i]$ : $2$ is ramified, the odd primes $p\equiv -1$ mod $4 $ remain prime ("inert"), and the primes  $p\equiv 1$ mod $4 $ are "decomposed" as $p=u\pi \bar \pi$, where $u=\pm 1, \pm i$ and $\pi , \bar \pi$ are two conjugate primes of $\mathbf Z [i]$ . Taking norms immediately yields Fermat's classical theorem that $2$ and the $p\equiv 1$ mod $4 $ are sums of two squares.  It follows readily that an integer $m=\prod {p_i} ^{a_i}$ is a sum of two squares iff $a_i$ is even whenever  $p_i \equiv -1$ mod $4$  : just decompose $m$ in $\mathbf Z [i]$ (which is a principal domain) and take the norm map (which is multiplicative).


Probability of neither person drawing a pair of gloves

Question: A question from my probability textbook:

A box contains $10$ pairs of gloves. A draws out a single glove, then B draws one, then A draws a second, then B draws a second. Show that the chance of neither drawing a pair is ${{290}\over{323}}$.

Here's what I did. The possible sequences that work here are RLRL, LLLL, RRRR, LRLR, and the probability of getting them is$${{2(10)(10)(9)(8) + 2(10)(9)(8)(7)}\over{20(19)(18)(17)}} = {{73}\over{323}},$$which does not equal the probability given in the book. So what did I do wrong? Is the book correct? Is there an alternative meaning of "neither drawing a pair" (that's the exact phrasing from the book) that I'm not aware of?
Comment: What about RLLL and so on?
Comment: As in the answer below, it depends on whether the pairs are identical or different.
Comment: As an aside, the flavor about $A$ drawing only a single glove *and then $B$ drawing a single glove before going back to $A$ again*... it can help to recognize that the order in which they draw is irrelevant and it may as well have been $A$ drawing two gloves followed by $B$ drawing two gloves.  This can help simplify calculations
Answer: I think the question means that each pair of gloves is different. So you draw a pair when you draw $R$ and $L$ of the same pair and not any $R$ and $L$.
First $A$ draws any glove. Then $B$ draws a single glove -
i) $B$ draws from the same pair that $A$ drew.
Probability is $\frac{1}{19}$ and that ensures none of them draw a pair.
ii) $B$ does not draw from the same pair.
Probability is $\frac{18}{19}$. Probability that now $A$ draws -
a) From the same pair as $B$ is $\frac{1}{18}$ and that ensures neither of them draw a pair.
b) Draws neither of own pair or of $B$ is $\frac{16}{18}$. Lastly $B$ does not draw a pair with probability $\frac{16}{17}$.
Hence the desired probability is,
$\frac{1}{19} + \frac{18}{19} \left[\frac{1}{18} + \frac{16}{18} \cdot \frac{16}{17}\right] = \frac{290}{323}$
Answer: Inclusion/exclusion seems to work well here.  I am assuming the pairs are different.
Let's say the event that $A$ draws a pair is $pair_A$ and the event that $B$ draws a pair is $pair_B$.
Then
$$P(pair_A) = P(pair_B) = \frac{10}{\binom{20}{2}} = \frac{1}{19}$$
and
$$P(pair_A \cap pair_B) = \frac{\binom{10}{2}\cdot 2!}{\binom{20}{2} \binom{18}{2}} = \frac{1}{323}$$
By inclusion/exclusion, the probability that neither $A$ nor $B$ draws a pair is
$$1 - P(pair_A) - P(pair_B) + P(pair_A \cap pair_B) = \frac{290}{323}$$
Answer: Another way to look at it.
We can as well let each draw her full quota in one swoop.
Suppose the first draws $\boxed{A|B}$ in $\binom{10}2\cdot2^2 = 180 $ ways
The next can draw $\boxed{A|B},\, \left[\boxed{A|X}\, \boxed{X|B}\right] \,or\; \boxed{X|Y}$
in $1 + \binom81 2^2 +\binom82 2^2= 145$ ways
Thus $Pr = \dfrac{180*145}{\binom{20}2\binom{18}2} = \dfrac{290}{323}$


PHP search form not getting results

Question: I have a database with the name Harry Butler in it under the columns first_name and last_name with this code :
<?PHP

//Create the connection…
//("where the database is", 'Database login' , 'database password' , "Database name")
$con=mysqli_connect("", 'root', 'root', "Social");

//Check our connection…
if (mysqli_connect_errno($con))
{
    echo " Sorry Mate";
}
$fname = $_POST[fname];
$lname = $_POST[lname];

$result = mysqli_query($con, "SELECT * FROM `User_info` WHERE first_name = '$fname' AND last_name = '$lname'");
while($row = mysqli_fetch_array($result))
{
echo $row['first_name'];
}

?>

Which gets the form data from the previous page :
<form action="searching.php" method="post">
<input id="fname" align="center" placeholder="First Name" name="fname"></input>
<input id="lname" align="center" placeholder="Last Name" name="lname"></input>
    <select id="gender">
        <option value="Male">Male</option>
    <option value="Female">Female</option>
    <option value="Other">Other</option>
    <option value="God">God</option>
    </select>

</form>

Yet when the results are submitted i get nothing any ideas?
Comment: `echo $result;` run it in phpmyadmin or the command line
Comment: what's the value of $fname and $lname in searching.php?
Comment: Add mysqli_error() to the query and check any errors are throwing.
Answer: change
$fname = $_POST[fname];
$lname = $_POST[lname];

to this:
$fname = $_POST['fname'];
$lname = $_POST['lname'];

$_POST is associative array,so i hope it helped
Comment: while they should be quoted, they don't have to be.
Comment: still best practice to do it: http://de.php.net/manual/en/language.types.array.php#language.types.array.foo-bar

PHP search form not getting results


Quartiles of a exponentially distributed function

Question: I am doing an exercise where I'm supposed to calculate the quartiles of the exponentially distributed function $f_\mathbb{X}(x)=\lambda e^{-\lambda x}$. So, first I calculate the distribution function, $F_\mathbb{X}(x)$, to be
$F_\mathbb{X}(x) = 1 - e^{-\lambda x}$
I know this is correct. Then, to calculate the first quartile $x_{0.25}$, I set
$F_\mathbb{X}(x_{0.25}) = 1-0.25$
I then perform the following calculations:
$F_\mathbb{X}(x_{0.25}) = 1-e^{-\lambda x} = 1-0.25$
$-e^{-\lambda x} = -0.25$
$e^{-\lambda x} = 0.25$
$-\lambda x = ln(0.25)$
$x = -{ln(0.25)\over\lambda}$
The same calculations are made for the other two quartiles, resulting in the following three quartiles:
$F_\mathbb{X}(x_{0.25}) = 1-0.25 => x = -{ln(0.25)\over\lambda}$
$F_\mathbb{X}(x_{0.5}) = 1-0.5 => x_{0.5} = -{ln(0.5)\over\lambda}$
$F_\mathbb{X}(x_{0.75}) = 1-0.75 => x_{0.75} = -{ln(0.75)\over\lambda}$
which, to me, seems pretty reasonable. The book, however, provides these answers:
$x_{0.25} = -{ln(0.75)\over\lambda}$
$x_{0.5} = -{ln(0.75)\over\lambda}$
$x_{0.75} = -{ln(0.25)\over\lambda}$
These answers does, on the other hand, not seem reasonable at all. Is the book wrong? And, if it's not, where am I wrong?
Comment: The book is right.
Comment: Ok. Could you please explain where I went wrong?
Comment: To put it briefly, for first quartile you want to set $F_X$ equal to $0.25$.
Answer: The usual definition of the first quartile is the place $q_1$ such that $\Pr(X\le q_1)=0.25$.
In our case, $F_X(x)=1-e^{-\lambda x}$ and therefore we want $1-e^{-\lambda q_1}=0.25$.
This manipulates to $e^{-\lambda q_1}=1-0.25=0.75$. Taking logarihms, we get the book's answer of $-\frac{\ln (0.75)}{\lambda}$.
For the second quartile, $\ln(0.75)$ is replaced by $\ln(0.5)$, and for the third by $\ln(0.25)$.
Remark: Note that $-\ln(0.75)\lt -\ln(0.5)\lt -\ln(0.25)$. This feels as if it is going the wrong way. It isn't. For the logarithms are all negative.
I think the book's answer is (though correct) not presented in a good way. Better would be the equivalent $q_1=\ln(1/0.75)\cdot \frac{1}{\lambda}$. Then everything is positive. Shouldn't we all  be positive?
Comment: I see what you mean, and that all makes sense. I'd just like to add that my book says that "The number $x_p$ that is a solution to $F_\mathbb{X}(x_p)=1-p$ is called the $p^{th} quantile$". Is this faulty then, for this gives that $Pr(X\le q_1) = 1-0.25 = 0.75$, or is this misinterpreted?
Comment: There are some inconsistencies in usage, unfortunately. I was using the most standard definition, see for example [this Wikipedia definition.](http://en.wikipedia.org/wiki/Quantile)
Comment: I see. I'll take a look at this! Thanks a lot!


Clustering historical data into meaningful "chunks"

Question: I have a binary dependent variable that I am interested in predicting with historical data. I have 19.000 observations from 1900 and onwards, and I would like to study the relationship between year/decade and the DV. Normally, in my field, what people do is that they code for the decade (1900, 1910, 1920, etc.) without taking into consideration variation within the decades. Also, coding by decade seems a bit arbitrary to me, since it is just a construction of time which has no validity in reality.
Taking that into account, I would like to find another way of grouping historical data than "decade". More specifically, I would like to identify meaningful clusters where the data points group dependending on the value of the DV. In that way, I would theoretically be able to find groups like "1900-1933; 1934-1978; 1979-2019", etc. These different clusters would then constitute a new predictor that I could enter into a GLM as a categorical factor. So the assigned group for each observations needs to be saved as a new variable in the frame.
Another option would of course be to introduce "year" as a numerical factor. However, I am interested in exploring the above explained option.
Does anyone know what type of cluster analysis would be required to be conducted?
Thank you in advance. I am using R for this.
Answer: Define"meaningful".
The are methods to detect abrupt change in mean. You could use these to chunk your data.

Basseville, Michèle, and Igor V. Nikiforov. Detection of abrupt changes: theory and application. Vol. 104. Englewood Cliffs: Prentice Hall, 1993.
Comment: I think you would like to add this as a comment.
Comment: Thank you for your comment. Sure, I understand your point. However, what I mean is that "decade" doesn't really mean anything in relation to your data - you could for example have significant heterogeneity within a decade, and then that grouping no longer makes sense - right? I would like some way of finding a data-based grouping rather than a priori.
Comment: Then a change in mean segmentation probably is what you want, as indicated in the answer. If you consider a "change in mean" to be meaningful. :-)
Comment: Great, thank you for your diligence in answering! :-)
Comment: The recommendation to use the usual and we'll known abrupt-change-in-mean methods is more than just a comment.
Comment: "meaningful" in a sense that the groupings are based on actual observations rather than a priori groupings, like "decade". The different chunks would (I'm guessing) be clustered according to degree of homogeneity. Would it make sense to measure mean when the DV is categorical?
Comment: Well, a standard quantile approach would also be data based... Usually, I would consider a decade a "meaningful" grouping (as it has a defined meaning), whereas a data-based grouping could be quite arbitrary (1923-1942).


Arquivos css no laravel 4

Question: Estou iniciando com o Laravel e não estou sabendo onde colocar os arquivos css, já que não existe a pasta assets, como existe no Laravel 5. Preciso trabalhar com a versão 4, pois a versão do PHP no servidor é antiga e não tenho como mudar. Não encontrei nada no Google que me ajudasse.
Answer: Coloque o seu css na pasta project/public/css/.
Para chamar no seu arquivo de template blade pode ser assim:
<link href="{{ asset('css/app.css') }}" rel="stylesheet">

ou
{{ HTML::style( asset('css/app.css') ) }}

Comment: @AmandaLima, daí você poderia utilizar a estrutura de layout do laravel para isso. Você cria um layout com tudo que vai utilizar e estende ele com a view.
Comment: você pode colocar em um arquivo chamado template e nas outras páginas herdar ele usando o extends, na documentação tem todo o passo a passo de como fazer:http://laravel.com/docs/4.2/templates
Comment: E precisa chamar o css em todas as páginas?? Eu costumo usar umas 4 css diferentes, terei que chamar todas em todas as páginas ou existe alguma maneira de chamar apenas uma vez para o projeto todo?
Comment: Muito obrigada!!
Answer: Amanda, você só precisa colocá-los na pasta public da aplicação.
Você pode criar uma pasta para cada tipo de documento/script que você vai utilizar.
Exemplo:
public/css
public/js

Eu não costumo a utilizar a função asset, pois o caminho gerado ficaria literamente como se a aplicação estivesse em public.
Para um arquivo javascript por exemplo que estaria em public/js poderiamos fazer sim.
public/js/jquery.js

Poderia ser inserido no código simplesmente assim:
{{ HTML::script('js/jquery.js') }}

Comment: Eu também faço assim. Sem a função `asset`.
Comment: @DeeSouza, eu chamaria isso de processamento adicional desnecessário

Arquivos css no laravel 4


Recompiling a SP in live environment

Question: I have a Stored Procedure which I want to recompile. is it safe to do that in a Live environment ? Because there's continuous flow of data which is being processed by the Stored Procedure and the SQL Server 2008.
Answer: Depending upon the method used (i.e. do not drop and recreate the procedure using the WITH RECOMPILE option), this is perfectly safe to execute on the Live environment.
If using sp_recompile, the stored procedure will simply be flagged to cause a new query plan to be calculated the very next time it is executed.  This may cause a very small delay whilst the new query plan is compiled but it will be negligible:
exec sp_recompile N'<your procedure>'

Comment: @RamMehta It will be safe to use this.  As I say, it simply flags the procedure to be recompiled the very next time it is executed (which will happen automatically).
Comment: So It would be safe to go with the command exec sp_recompile right ?

Recompiling a SP in live environment


Can .XML file set a value from variable in a .txt or .py?

Question: I have multiple xml files (Actually .wxs for Wix Toolset) that all need to get a programs version that updates regularly. I want all the files to automatically get the latest version number.  The program has a file formed like this:
Version.py
version='0.4.22'

Is it possible to get the variable version from Version.py into my .xml file?
Maybe something looking like this:
<VARIABLE app_version FILE="\\version.py" SELECT="version" />

<Product Name="MyApp" Version=&app_version; />

Comment: You mean you want to read Version value ? or you want to set the version value coming from some other files? both are possible.
Comment: Yes I want to read the value  of Version from version.py and how to assign that value to an Element attribute.
Answer: What I understand from your question, is that you want the version variable's value to be placed inside the .XML file's version attribute inside the Product tag.
You could just open the XML file in the script and automate it to write the updated version number from the Versions.py file to the XML file.
So, every time you run your script, it will update the XML file
Comment: Ah, did not really understand your answer first and I realize my question does not explain everything but Yes this does help. I'm building from a .bat file and from there i can set my variables and should be able to get value from an other file. Thank you
Answer: you just want read the version setting value from a .py file and used the setting value in the .wxml file.
In .wxs just read the .py file as a text file and get the version setting value, and then assign the setting value to the .wxml view.
Comment: Well yes but I cant' figure out how to read a text file and read a specific value.