Find least value of $9\tan\phi+4\cot\phi+3$ without derivatives

Question: The problem is as follows:

In a pharmaceutical lab in Daegu, a group of scientists need to find
the power of a visible blue light lamp to get through a sucrose
crystal in order to measure its purity for a certain medication.
The power for such light is given by:
$$J=\frac{1}{H}$$
Assuming that $H$ has to be the minimum value of the equation from
below:
$$H=9\tan\phi+4\cot\phi+3$$
$\theta$ is an acute angle which lies in the first quadrant.
What would be the value of $J$ so that the scientists could set up
their lamp?

The alternatives given in my book are:
$\begin{array}{ll}
1.&\frac{1}{5}\\
2.&\textrm{1}\\
3.&\textrm{15}\\
4.&\frac{1}{15}\\
\end{array}$
This problem is making me feel confused. Should derivatives be used here?
I've attempted to do so and derivate the equation, by doing so this yields:
$H'=9\sec^2\phi-4\csc^2\phi$
But equating this to zero doesn't seem to be the intended approach.
Then I came up with the idea of adding the intervals from where $\phi$ in the first quadrant lies.
$0\leq \cot \phi < +\infty$
Tangent is also in the same interval:
$0\leq \tan \phi < +\infty$
Then multiplying by $9$ and by $4$ and adding $3$ to the second equation.
This results into:
$3\leq 9\tan\phi+4\cot\phi+3 < +\infty$
But without any further constrain there isn't any way to tell, which would be the least value?
If it would had been the integer value, wouldn't had been $4$?
Running out of idead, what it came to my mind was to equate both functions:
$\tan\phi=\cot\phi$
This corresponds to $\phi=\frac{\pi}{4}$
Assuming this: I'm guessing that the result would be
$9\tan\phi=1$
$4\cot\phi=1$
then $1+1+3=5$
But this is more like guessing and not a serious way to justify the answer. I cannot be sure if that's the answer. Can someone help me here and explain me why derivatives doesn't seem to work?
How to solve this without derivative?. Help me please, I'm confused.
Comment: If $\tan\theta=x$, then $\cot\theta=\frac1x$.  As you do not need to solve for $\theta$, you could simply use the substitution and find the minimum using quadratics.
Answer: Note
\begin{align}
9\tan\phi+4\cot\phi+3&=( 9\tan\phi+4\cot\phi-12)+15\\
&=(3\sqrt{\tan \phi}- 2\sqrt{\cot \phi})^2+15\ge 15
\end{align}
Comment: That's an interesting approach. But I'm assuming that the intended strategy was to use $b^2 \geq 0$. What's the justification of the method you have used?. Other user has hinted that what's used here is Cauchy-Schwarz inequality, but upong reading such entry on wikipedia it expresses it in terms of vectors, and I don't see any vectors here. **What property or identity have you used, does it has a name?**. I attempted to do you method but you used $\left(3\sqrt{\tan\phi}-2\sqrt{\cot\phi}\right)^2$ intead of $\left(3\sqrt{\tan\phi}+2\sqrt{\cot\phi}\right)^2$. Why the later doesn't work?.
Comment: @ChrisSteinbeckBell - you could do the latter. Then, you have to show its least value is 24 instead of 0, which is less convenient
Comment: Can you please add this second method in your answer?. I'm trying to do it on my own but I can't get the same as you. Please?. Can you please attend my earlier doubt?. Does your method has a name?. **Why its least value has to be $24$ intead of $0$ this part I don't understand?** Please explain this to me. I'm stuck.
Answer: Using drivatives works fine.
$H' = 9\sec^2\phi - 4\csc^2\phi =0\\
9\sin^2\phi = 4\cos^2\phi\\
\tan^2\phi = \frac {4}{9}\\
\phi = \arctan {\frac 23}$
Plugging this into the original equation gives:
$9(\frac 23) + 4(\frac 32) + 3 = 15$
Answer: If $x^2 = \tan \phi$
$$ 0 \leq \left(3x - \frac{2}{x} \right)^2 = 9 x^2 - 12 + \frac{4}{x^2}  $$
$$ 12 \leq   9 x^2  + \frac{4}{x^2}  $$
$$ 12 \leq   9 \tan \phi + 4 \cot \phi $$
https://en.wikipedia.org/wiki/Cauchy%E2%80%93Schwarz_inequality
Comment: Howdy!. Interesting approach. I tried to understand the wikipedia entry you had just written. But it seems too complex for me. But from what I do understand in your method you seem to use $b^2\geq 0$. While the inequality you mention indicates the use of vectors. The article also mentions the dot is the inner product. What it confuses me the most is **how does this inequality explains your method?** You used a greater and equal than zero not less and equal as the inequality. Can you please explain this part? I'm assuming that the final part in your answer is to add $3$ to both sides.
Answer: A bit late this answer but I think worth mentioning it.
It is just AM-GM - the inequality between arithmetic and geometric mean:
For $\theta \in \left(0,\frac{\pi}2\right)$ you have $\tan \theta >0$ and AM-GM gives
$$9\tan \theta + 4\frac 1{\tan \theta}+3 \stackrel{AM-GM}{\geq} 2\sqrt{9\tan \theta \cdot 4\frac 1{\tan \theta}}+3 = 12+3 = 15$$
The minimum is reached for
$$9\tan \theta = 4\frac 1{\tan \theta} \stackrel{\theta \in \left(0,\frac{\pi}2\right)}{\Leftrightarrow} \theta = \arctan \frac 23$$
Answer: Set $\tan\phi=z$
$f(z)=9 z + \frac{4}{z} + 3$ is minimum when $f'(z)=0$ and $f''(z)>0$
$f'(z)=9 -\frac{4}{z^2}=0\to z=\pm\frac{2}{3}$.
$f''(z)=\frac{8}{z^3}$
as $f''\left(\frac{2}{3}\right)>0$ we have that $f\left(\frac{2}{3}\right)=15$ is the minimum.


Como conseguir os arquivos de um repo do GitHub?

Question: Estou fazendo um projeto que irá fazer  download de um Git do GitHub, porém, quero que o download seja automatizado ao usuário. Para isso, preciso conseguir o nome dos arquivos e das pastas que estão no diretório. Há algum arquivo em um repo que contenha os diretórios e os arquivos existentes em cada Git?
Comment: Serve o link com o zip? `https://github.com/contaUtilizador/nomeProjeto/archive/master.zip`
Comment: Eu sei que localmente isto fica na pasta `.git` e dentro do arquivo `index`.
Comment: @Sergio perfeito. Vou encontrar uma maneira de transformar o zip em pastas. Pode colocar o comentario como resposta!
Comment: Quer fazer isso do lado do servidor ou cliente?
Comment: @Sergio sempre, cliente. É uma aplicação de desktop em C++ com WinAPI.
Answer: Pode usar-se o link que o github tem com o zip do projeto.
O formato é:

https://github.com/contaUtilizador/nomeProjeto/archive/master.zip
Answer: Baixando dinamicamente o zip para seu para o seu projeto através da url mencionada acima
<code>https://github.com/contaUtilizador/nomeProjeto/archive/master.zip
</code>
Você pode extrair o zip e navegar livremente pelos diretórios, que já estarão no seu ambiente.
Comment: Essa resposta é a exata acima.


O que significa uma variável de dupla precisão?

Question: Gostaria de entender o significado de uma variável de dupla precisão.
Answer: Normalmente chamada de double, é a variável que armazena um número de ponto flutuante com espaço para indicar números maiores, seja na parte inteira, seja na parte decimal. Ele é o "irmão" do tipo float que é o tipo de simples precisão. Geralmente o float ocupa 4 bytes e o double ocupa 8 bytes. Algumas implementações ocupam 10 bytes e até 16 bytes, embora nesse caso costume ser chamado de quadrupla precisão.
Na verdade variável é apenas um nome para um local de armazenamento. Valores possuem tipos. Em linguagens de tipagem estática as variáveis aceitam valores de apenas um tipo conforme declaração em código.
Tipos de ponto flutuante costumam ser implementados por representação binária para que os cálculos sejam feitos rapidamente pelos processadores. Se a representação fosse decimal o cálculo não seria natural para o processador e levaria bem mais tempo. Há uma desvantagem nessa escolha. Não há exatidão, então nem todos os números podem ser representados dessa forma. Sempre dá para representar um número muito próximo, que é quase o mesmo, mas não exatamente o mesmo. Não é um problema para cálculos científicos, mas para representar dinheiro ele não serve. Dinheiro precisa do valor exato. Nunca use float e double para dinheiro ou outros valores que precisam exatidão.
Então entenda que exatidão e precisão são coisas diferentes. Precisão tem mais a ver com a capacidade de expressar números mais extensos, mais casas à direita ou esquerda. Precisão é o grau de variação de resultados de uma medição. Exatidão, que se refere à conformidade com o valor real.
Números com ponto flutuante são armazenados com um valor significante multiplicado por uma base fixa elevada a um expoente, além do sinal.
Precisão simples:

Precisão dupla:

Quanto mais bits disponíveis mais o número pode ser preciso.
Coloquei no GitHub para referência futura.


Practical limitations of the 4 mallet technique for idiophones from a compositional point of view

Question: Pretty much as the title puts it. I haven't found any literature (so far) that covers it well, and I don't have any percussionists among my current acquaintances (more's the pity). Essentially, what sort of "hand spans" can I expect? What intervals are hard to manage in one hand? Are there any "gotchas" I should keep an eye out for when writing for them? I'd prefer to work with ranges that I can safely expect from a well-trained professional, not the exceptional cases.
I've got a sketch hanging fire involving vibes, more or less jazz (which is outside of my usual comfort zone), that I was given to collaborate on by a jazz composer of my acquaintance. Unfortunately he's a bassist - not his particular expertise either.
Comment: I'm curious about this, but don't know enough to answer. @jjmusicnotes you answered a four mallet question elsewhere, maybe you can answer this?
Answer: Hmm. On vibes I think you can safely and easily expect each hand to be able to reach an octave span; it depends some on the player and what part of the instrument you're in generally (e.g., on marimba you can probably get a noticeably wider range - maybe out to a 10th - at the upper end of the instrument, where the bars are closer together). On vibes that extension is probably not going to be as noticeable, though I think you could still ask for a 10th at the upper end.
Range between each hand, in my experience, depends a lot on the length of the arms of the player. I wouldn't get too crazy -- maybe an octave to 12th or so between the inner mallets -- especially since you may begin to lose agility and accuracy as the hands get too far apart. Think about it - the pianist can touch the keys without playing them and know where they are, but the percussionist needs to look at the keys all the time. If they have to turn their head back and forth to see both hands, you're likely going to start getting flubbed notes.
The biggest "gotcha" I've encountered actually relates to voicing. Given the distance and placement of the accidental bars, if you have a 4-note chord with two black keys and two white keys, it is easiest for the percussionist to play the two black keys in the middle. That way, their hands are splayed outward (hold some sticks and try it, you'll see).
It is also pretty easy to play both black keys in one hand, or black key on the bottom/left of both hands (though in the latter case note that the percussionist may need to move their body to the left or the right of the instrument, making fast jumpy passages trickier). It gets difficult when you start voicing the two black keys on outsides of the hands; the player will have to turn their arms in in order to hit all four notes at once. This also sharply limits the distance available between the hands.
Furthermore, in fast passages you probably don't want to jump around between different "configurations" of the voicing so that the player has to keep switching which mallet on which hand is playing on the black vs. the white keys.
Also, small intervals on the same keyboard (white keys vs. black keys) within one hand, if I recall correctly, can be awkward too. Think about trying to get the two mallets that close together with the standard grip. The player might turn their hand so that the two mallets are playing at different parts of the bars.
The physicality of percussion in general is one of the most important oft-overlooked things I see in writing for it. They're moving around so much, and it will really help your work to try - as best you can - to replicate the basic physical actions necessary to play the part you're writing.
There's plenty of other things to keep in mind, but I think this hits most of the highlights.
Disclaimer: I'm not a percussionist by any means, just a composer who has at some point made every mistake single described above :)
Comment: Thanks, that's fairly comprehensive. I hear you regarding making all the mistakes, and I feel your pain. Been there, done that, got the teeshirt, wore it out and went back for seconds... :D
Comment: You'd also want to take into consideration whether you're letting the notes ring or not when using mixed black & white key chords.  You can cheat a little when the pedal is down and play on the ends of the bar, like on a marimba.  Doing that while the pedal is up won't sound very good.
Answer: To add my $0.02 -
There is actually a really wonderful text for percussion writing called How to write for percussion by Samuel Z. Soloman, which is fairly comprehensive (and has some really handy beater charts!)
Remember to think of physical distance - a simple 4 octave jump that would be easy on a piano might mean a marimbist having to move 6-8 feet!
For four mallet technique, most percussionists can handle an octave to a tenth in distance per hand.  It is hard on their hands and is tiring though, so use intervals larger than an octave sparingly.  The exact opposite also holds true: intervals that are close together are sometimes just as obnoxious as large intervals.
The most comfortable intervals fall between 3rds-6ths.
I want to also support remembering your voicings.  Percussionists sometimes have to put their arms in really awkward / funny positions in order to achieve certain voicings.  It takes time, is awkward, and is most of the time not worth it.  If you can, try visualize how a percussionist might play each voicing.  If you can't, get some mallets, go to a school, and try playing yourself.  Seeing how the notes fit on the instrument can be a humbling experience.

Since we are discussing intervals, I also just want to mention that it's important for you to remember the context of your piece.  If the tempo is slow and you give the percussionist lots of time to prepare the large intervals, then great, use them!  But if it is fast / loud, they will become tired much more quickly.
Comment: Thank you! I wasn't aware of that book - I shall have to look it up. So far, actually, it looks like what I've written is not too bad - fast single note scalar passages, separated by rests from alternating dyads of a 3rd to a 6th spaced at the crochet in fairly close harmony, with the inner mallets doing most of the movement.
Answer: The pro-style 4 mallet grip allows for a very wide selection of intervals and easy switching between them.  It gets kind of fidgety at the extremes, but a good player should really have no trouble reaching anything that the mallets can physically reach.  For context, I am by no means a great percussionist and I honestly have little problem playing any intervals that are physically possible.
I agree with the others about voicing.  One particularly nasty thing that I once watched someone else (a very good percussionist) practice was a switch between a chord that was black-white white-black (so both hands turned inwards) to one that was white-black black-white (so both hands turned outwards).  Even though the notes didn't move much, it was a very extreme motion and was giving him a lot of trouble.
Comment: I'm trying to imagine this (the voicing problem). Does the grip constrain wrist motion? I can see it as a real problem if the motion must be done with forearms and elbows.
Comment: Evidently it does - was just watching Jean St-Jacques (ex-UZEB) on a malletKAT. It's a more compact layout than vibes, but I imagine the stick technique doesn't change much, and his elbows were going in and out...
Comment: @Patrx2 Percussionist employ several types of grips depending on their playing style and application.  Some grips offer wider range while other grips offer more versatility / dexterity.  Just write the music, let the percs worry about the grips.


Floating point hash table

Question: I want to construct lookup table using a floating point value as the key.  When I query the table with a given floating point key, I want it to return the value whose key is closest to the query key.
However I don't know beforehand if the floating point keys are evenly distributed or not.
For example, my table might be:
<code>key     value
1.0     "red"
1.25    "blue"
2.0     "green"
</code>
If I query 1.5, I want to get back "blue".
Is there a way to construct the table so that it has O(n) memory and O(1) lookup?  (That is, a hash table).  There's obviously a O(log(n)) algorithm if I store the key/value pairs sorted, but I'm curious if that bound can be improved.
Comment: Do you know anything about (1) the range of the floating point values, (2) the number of significant digits involved or (3) the minimum allowed distance between two values / any restrictions on number count per range?
Comment: If we're talking about IEEE floats, then they're represented in sign-magnitude order, and you can adapt algorithms for 32-bit (64 for doubles) integers.
Comment: I don't think it's generally possible without very specific constraints. I'd just use a binary search.
Comment: @Apriori Subnormals behave fine with respect to sign-magnitude ordering.
Comment: Did you mean "if I query 1.24, I want to get back 'blue'"? You can't do O(1) nearest neighbor searches.
Comment: A hash table does not support nearest neighbor queries, so the reference to O(n) space/O(1) time is not so relevant.
Comment: @Dukeling - I know the range, yes.  I don't need to change the table often relative to the number of times I need to query against it, so even though I don't know the minimum allowed distance between two keys a priori, I don't mind calculating it when I build the table.  It sounds like you're thinking about some sort of discretization of the domain?
Comment: @DavidEisenstat - Sounds interesting.  Care to elaborate?
Comment: @JayLemmon "I know the range" - What's the range? "Some sort of discretization of the domain" - Yes, something like that. It's not so much about calculating the distance, but rather about having some guarantees about the distance to allow for this approach to work without excessive memory usage or running time in 'unlucky' cases (when too many values are too close together).
Comment: @Dukeling - Well any finite domain can be mapped to any other in O(1) without changing the relative ordering of IEEE floating point numbers, so without loss of generality let's say the domain is [0,1].
Comment: What I mean is that you can write an (e.g.) Java method `static int intKey(float f) { int i = Float.floatToRawIntBits(f); return i ^ ((i >> 30) >>> 1); }` that converts floats to ints efficiently in an order-preserving manner. Then you can use tries and related structures like van Emde Boas trees. There's no one good data structure for successor queries, so you'll have to experiment a bit if you want the best performance.
Comment: (If the keys are nonnegative, then you can do away with the bit hacks converting sign-magnitude to one's complement and just return `i`.)
Comment: If you ever decide to implement van Emde Boas trees and use it for this, please come back and edit the question to report your results. I'd be incredibly interested in whether they are actually useful for any real-life scenario
Comment: Why a hash table? Why not e.g. a binary tree?
Comment: That's a good point about signed-magnitude representation of a float. With that, you could do this: Interpret the bits of the float as a signed magnitude int, then convert it to a twos complement int. Ascending numbers from the two's complement int will correspond to monotonically increasing floats. It's important to note this may break if the float is a denormal (when they get very close to zero). You can think of these ints as strings of ones and zeroes in lexigraphic order. From here, you can use a data structure called a Trie.
Comment: For English strings a Trie might be a tree of degree 26, but for binary strings it's just a binary tree.  The existence of each node (or not) records the existence of a bit string so-far. This tree can be stored in an array of bits (1 bit for the 1st level, 2 for the 2nd, 4 for the 3rd, ect.), each bit being the existence of that node or not. Then, if you are traversing the tree for a given floating point value and run out of child nodes (no exact match), then if you wanted to visit a 1 but had to visit a 0, then visit a 1 whenever it's available thereafter until you hit a leaf node;
Comment: and similarly if you wanted a 0 but there was only a 1 take 0s if possible thereafter. For a 32-bit float this structure is going to take up 512 MB (a 64-bit double would be more space than you'll ever have on your hard drive). However, if you know things about the range of your exponent, sign bit, and mantissa you can shave down your integer representation of the number to be say 12 bits, then your Trie will only occupy 512 cache-friendly bytes. I'm not sure how practical this all is, but it is one way you could use the signed-magnitude ordering.
Comment: @David Eisenstat, thank you, that is good to know.
Answer: You can ignore the fact that your key is a floating-point number as it really doesn't effect the answer. The answer would be the same if your input was a 32-bit (equivalent to float) or 64-bit (equivalent to double) integer. And, I believe the answer is 'no'.
In order to find the nearest neighbor you need the keys to be sorted. When you have a 32-bit or 64-bit key (it could be helpful to clarify which) that means that you really have no choice but to have a sorted data structure (tree? heap? sorted array?) which you do an O(log(n)) search in.
It's easy to get constant-time access to a specific entry, but getting constant-time access to the nearest neighbor to a specific entry either requires a lookup table with 4 billion entries (for floats) or magic.

Floating point hash table


General question on notations when dealing multiplicative and additive modulo

Question: One of the property for the requirement for a set to be a group is associativity.
Under ordinary multiplication:
$\large{a(bc)=(ab)c}$
Under ordinary addition:
$\large{a+(b+c)=(a+b)+c}$
What about under multiplicative modulo and additive modulo?
Do we write it, respectively as:
$\large{a(bc) \pmod n =(ab)c \pmod n}$
and
$\large{a+(b+c) \pmod n=(a+b)+c\pmod n}$
Comment: Why do you tag your questions with set theory tags? This is not the first time it happens, and this is rarely the right tag.
Answer: If you want to be precise, you must specify what your $a,b,c$ are.
$\def\nn{\mathbb{N}}$
$\def\zz{\mathbb{Z}}$
Given $n \in \nn^+$ and $a,b,c \in \zz/n\zz$, we have the exact equality $(a+b)+c = a+(b+c)$ and $(ab)c = a(bc)$.
Given $n \in \nn^+$ and $a,b,c \in \zz$, we have an equivalence relation which we can denote by "$\equiv_{\pmod{n}}$" which lets us write "$(a+b)+c \equiv_{\pmod{n}} a+(b+c)$" and "$(ab)c \equiv_{\pmod{n}} a(bc)$". Often people choose to write "$(a+b)+c \equiv a+(b+c) \pmod{n}$" and "$(ab)c \equiv a(bc) \pmod{n}$" instead.
Comment: People, please stop editing my answers unless it's an obvious mistake and you know what you are doing. If it is not made clear that it is really an equivalence relation, it is not good!


Two different x axis labels on line chart, chart.js react

Question: I'm trying to create a chart component for weather in React using chart.js. I want two different x axis with the temp above the chart, and the times below the chart. The data is correct in how I wan't it, I just want to use two different labels along the top and the bottom of the x axis.
How would I do this?
import React from "react";
import { Line } from 'react-chartjs-2';

class WeatherOverview extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            chartData: {
                labels: ['15:00', '18:00', '21:00', '00:00', '03:00', '06:00', '09:00', '12:00'], //time
                datasets: [{
                    data: [18, 19, 18, 16, 15, 15, 16, 17, 18] //temp
                }],
            }
        }
    }
    render(){
        return (

                <Line
                    data={this.state.chartData}
                    options={{
                        scales: {
                            yAxes: [{
                                gridLines: {
                                    drawOnChartArea: false
                                },
                                ticks: {
                                    suggestedMin: 13, // lowest from data minus 2/3
                                    display: false
                                }
                            }],
                            xAxes: [
                                {
                                    gridLines: {
                                        drawOnChartArea: false
                                    },
                                },
                                { position: 'top' },
                            ]
                        }
                    }}
                />

        )
    }
}

export default WeatherOverview;

Comment: That looks like it should work @DavidPeer. Thank you!
Comment: look at that:
https://stackoverflow.com/questions/42934608/how-to-create-two-x-axes-label-using-chart-js this is what you are looking for?
Answer: look at this ref her:
How to create two x-axes label using chart.js
it looks like what you are asking about.
enjoy!


Leased Line bandwidth distribution among users

Question: Say that i purchase a 4 Mb leased line (Radio wave), and also i have around 50-75 users using the connection.
What will the speed will each user get ? Will the 4MB be divided among all 75 users or will all users receive the same speed throughout the day ?
Answer: This would be entirely dependent on what everyone was doing at any given moment. The minimum bandwidth everyone could get would be 1/75th of the 4Mb (everyone streaming videos for example). The maximum could be 4Mb, with only one person using the line.
Answer:
Will the 4MB be divided among all 75 users or will all users receive
  the same speed throughout the day

You buy one pizza. YOu have 4 guests. Will every guest get a complete pizza?
Com on, that is common sense. NATURALLY the limited resource (4Mbit bandwidth) will be distributed among the users that actually use it (which is less than 50-75 - not everyone will have the same demands at exactly the same moment).
Answer: Well, actually it depends on the queue management on each end. If it is a FIFO queue, in case you have eg a big FTP transfer between the two sites, it will consume the whole bandwidth while connections to Internet will suffer and telnet will seem unresponsive.
Normally you would put a router on each end, shape the output interface of the router (which probably is ethernet) to 4Mbps, configure a QoS policy and apply fair-queueing, random-detect. You could also prioritize or reserve bandwidth for some applications.


How to make my GPT bot answer questions using the data from a database?

Question: I am researching on how to create a chatbot that provides information to the user from the APIs or databases, and not some document.
I watched a couple of videos on Youtube over langchain and GPT bots.
Here is what I gathered:
GPT bots need prompts. They need a dataset from where they can answer questions.
What I need:

My GPT bot should be domain specific, i.e., refuse to answer any other kinds of questions.
Extract the intent, the data provided in the user input.
Make an API call (I will provide the API endpoints, user, password) to the respective URL with the data in the query parameters
Once it gets the data from the API, it should respond with the data it retrieved.

In a nutshell, I don't need the bot to train on some document, I just need the GPT API to understand the intent from the user input, and carry on a conversation. I just need it to fetch the data dynamically from the database/APIs.
------EXAMPLE------
INPUT - Tell me which orders did I receive yesterday?
Intent - fetch orders
Data - from yesterday
Webservice call - www.example.com/orders?dateStart=${YESTERDAY}&dateToday=${TODAY}
ANSWER - Here are the list of orders:-

ABCD - qty 1
EFGH - qty 10

--------EXAMPLE---------
Earlier I thought I could leverage langchain for this, but I'm not sure. And also confused on how to search the internet for my requirement. I really need guidance.
It could be possible that I am looking at the wrong technology for this. If not this, then what?
Many thanks!
Comment: Ask ChatGPT... Use of ChatGPT or AI is not on topic here.
Comment: Sorry, I didn't get you. So this is not the right place to ask this question?
Comment: I actually want to use the Open AI API to create a chatbot.
Answer: tl;dr;
https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models
OR
https://platform.openai.com/docs/assistants/how-it-works
Some time ago you needed to play with prompt to make ChatGPT identify and send you back function calls (example later). Right now it's embedded in the API. You still need to send 2 calls (once to identify functions and another with the additional information) but it's much more formal, stable and easier.
There are 2 approaches - tools list where you define ChatGPT which "tools" (former "function_calls") you have and it will respond with list of tools it needs to call and how. And Assistants which can be pre-created and configured with available functions so that you don't need to repeat it on each future request. So best is follow examples and documentation of OpenAI itself.
Here's how function calls were done before the "tools" API parameter. You first send request with prompt similar to this:
Here is a list of available functions:
get_price(symbol) - receives stock symbol returns last price as number
get_title(symbol) - receives stock symbol returns title as string
get_num_shares(symbol) - receives stock symbol number of shares as number

List function calls that will help answering my question in JSON array. Answer with JSON only, without explanations. Example:
[ {"function": "get_price"}, {"arguments": ["XOM"]} ]

Question:
What is the latest price and title of MSFT?

Parse results, call functions, send another prompt:
You have the following information:
price of MSFT is $377.43
title of MSFT is  "Microsoft Corporation Common Stock"

Please answer the question while using the above information to fill the gap in knowledge:
What is the latest price and title of MSFT?

You can paste this in ChatGPT and see the answers. Play with question and examples, sometimes it can glitch.
However, as of recently Assistant API supposed to replace all that, so go to
https://platform.openai.com/docs/assistants/how-it-works
and learn how to use it.


Windows 2008 IIS Fast CGI PHP or Windows 2008 with ubuntu guest w/LAMP stack?

Question: I have a server that I have co-located in a datacenter. It is a Quad Xeon (5130) with 8GB of RAM.  I have a few usb and serial port devices (peripherals) attached to it which require Windows to run.
I would like to add web hosting a (production) website onto this server's workload.  The website is runs on a LAMP stack.  After much reading, it seems that hypervisors and VM installs don't seem to work with peripherals (physical serial ports etc). Please correct me if I'm wrong.
So I was thinking about running Windows 2008 server x64bit and installing Vbox 4.0 (Ubuntu guest )on it to handle the production LAMP stack.  I was also thinking about running the LAMP stack on IIS 7.0 w/FASTCGI.  Which option do you think is better?  Are there other options that I'm not considering?
Syirrus
Answer: If you are stuck in a lamp stack you are probably better off using a virtualization solution. Performancewise the fastcgi solution would be faster but more dificult to administer. I would however encourage you to migrate the site to an IIS solution since you already have a windows system, if performance is a concern.
Comment: I think I will investigate running IIS for my web server. Performance and realiablty being of great importance whether its MS or Linux.  Thank you very much for your suggestions.  Is there anyone else that has anything to add?


libavcodec, how to transcode video with different frame rates?

Question: I'm grabbing video frames from the camera via v4l, and i need to transcode them in mpeg4 format to successively stream them via RTP.
Everything actually "works" but there's something I don't while re-encoding: the input stream produces 15fps, while the output is at 25fps, and every input frame is converted in one single video object sequence (i verified this with a simple check on the output bitstream). I guess that the receiver is correctly parsing the mpeg4 bitstream but the RTP packetization is somehow wrong. How am I supposed to split the encoded bitstream in one or more AVPacket ? Maybe I'm missing the obvious and I just need to look for B/P frame markers, but I think I'm not using the encode API correctly.
Here is an excerpt of my code, that is based on the available ffmpeg samples:
<code>// input frame
AVFrame *picture;
// input frame color-space converted
AVFrame *planar;
// input format context, video4linux2
AVFormatContext *iFmtCtx;
// output codec context, mpeg4
AVCodecContext *oCtx;
// [ init everything ]
// ...
oCtx->time_base.num = 1;
oCtx->time_base.den = 25;
oCtx->gop_size = 10;
oCtx->max_b_frames = 1;
oCtx->bit_rate = 384000;
oCtx->pix_fmt = PIX_FMT_YUV420P;

for(;;)
{
  // read frame
  rdRes = av_read_frame( iFmtCtx, &pkt );
  if ( rdRes >= 0 && pkt.size > 0 )
  {
    // decode it
    iCdcCtx->reordered_opaque = pkt.pts;
    int decodeRes = avcodec_decode_video2( iCdcCtx, picture, &gotPicture, &pkt );
    if ( decodeRes >= 0 && gotPicture )
    {
      // scale / convert color space
      avpicture_fill((AVPicture *)planar, planarBuf.get(), oCtx->pix_fmt, oCtx->width, oCtx->height);
      sws_scale(sws, picture->data, picture->linesize, 0, iCdcCtx->height, planar->data, planar->linesize);
      // encode
      ByteArray encBuf( 65536 );
      int encSize = avcodec_encode_video( oCtx, encBuf.get(), encBuf.size(), planar );
      // this happens every GOP end
      while( encSize == 0 )
        encSize = avcodec_encode_video( oCtx, encBuf.get(), encBuf.size(), 0 );
      // send the transcoded bitstream with the result PTS
      if ( encSize > 0 )
        enqueueFrame( oCtx->coded_frame->pts, encBuf.get(), encSize );
    }
  }
}
</code>
Answer: Most simple solution would be to use two threads. First thread would do all the things outlined in your question (decoding, scaling / color-space conversion, coding). Partially transcoded frames would be written to intermediate queue shared with second thread. Maximum length of this queue would be in this particular case (converting from lower to higher bitrate) 1 frame. Second thread would be reading in loop frames from input queue like this:
<code>void FpsConverter::ThreadProc()
{

timeBeginPeriod(1);
DWORD start_time = timeGetTime();
int frame_counter = 0;
while(!shouldFinish()) {
    Frame *frame = NULL;
    DWORD time_begin = timeGetTime();
    ReadInputFrame(frame);
    WriteToOutputQueue(frame);
    DWORD time_end = timeGetTime();
    DWORD next_frame_time = start_time + ++frame_counter * frame_time;
    DWORD time_to_sleep = next_frame_time - time_end;
    if (time_to_sleep > 0) {
        Sleep(time_to_sleep);
    }
}
timeEndPeriod(1);
}
</code>
When CPU power is sufficient and higher fidelity and smoothness is required you could compute output frame not just from one frame but more frames by some sort of interpolation (similar to techniques used in mpeg codecs). The closer output frame time stamp to input frame time stamp, the more weight you should assign to this particular input frame.


Smooth function on $\mathbb R$ whose small increments are not controlled by the first derivative at infinity

Question: I need some help in finding a (as simple as possible) smooth function $f:\mathbb R \rightarrow \mathbb R$ which does NOT satisfy the following:
There exist a constant $C>0$, a compact $K\subset\mathbb R$ and $h_0>0$ such that for every $|h| \leq h_0$ and every $x\in\mathbb R\setminus K$
$|h|^{-1}|f(x+h) - f (x)|  \leq C |f'(x)|$
EDIT: and there exists a $\tilde C>0$ such that $|f'(x)|>\tilde C$ for $x\in\mathbb R\setminus K$.
EDIT 2: my intuition is that such an $f$ may look like this: the first derivative stays always positive and oscillates (around g(x)=|x| for example), the oscillations becoming both faster and larger in amplitude when $x$C goes to infinity.
Many thanks.
Comment: It can't be oscillating if $f'$ is not allowed to have zeros. Also, do you want the "sufficiently small" uniformly in $x$? Maybe try to rephrase the whole question to make it a little clearer.
Comment: How did ${\mathbb R}^n$ get in there?
Comment: @LukasGeyer and Robert Israel. Thanks for your comments, I edited, hope it is clear now (yes the "sufficiently small" should be uniform in $x$). With oscillating I meant not the function itself, but higher derivatives. Anyway I cancelled the comment on the oscillations, maybe it is only confusing.
Answer: Take $$
\begin{eqnarray*}
  f(x) &=& x + e^x + sin(e^x) \\
  f'(x) &=& 1 + e^x + e^xcos(e^x)
\end{eqnarray*}
$$
Then $f'(x) \geq 1 + e^x - e^x \geq 1$
You have $f'(\log(\pi + 2\pi n)) = 1$ and $f'(\log(2\pi n)) = 1 + 2e^x$, i.e. arbitrarily close points with arbitrarily large differences of $f'$. This looks promising. Take now, for example, the differential quotient at $$
\begin{eqnarray}
  x &=& \log(\pi + 2\pi n) \\
  h &=& \log(2\pi (n+1)) - \log(\pi + 2\pi n)
\end{eqnarray}
$$
which is $$
\begin{eqnarray}
&&  \frac{h + e^{x+h} - e^{x} + sin(e^{x+h}) - sin(e^{x})}{h} \\
&=& \frac{h}{h} + \frac{2\pi(n+1) - (\pi + 2\pi n)}{h} + \frac{0 - 0}{h} \\
&=& 1+ \frac{\pi}{h}
\end{eqnarray}
$$
Now, since $h \to 0$ as $n \to \infty$, and since $f'(x) = 1$, the differential quotient at $x$ isn't bound by $f'$ globally.
Comment: Tanks, this is what I was looking for!
Answer: Try e.g. $f(x) = \cos(x)$.  All you need is that $f$ is not constant on any interval and $f'$ has arbitrarily large zeros.
EDIT: With the new condition, take $$f(x) = \int_0^x (1 + t^2 \cos^2(t^2))\ dt = x+\frac{x \sin \left( 2\,{x}^{2} \right)}{8}-\frac{\sqrt {\pi }}{16}{\rm
FresnelS} \left( 2\,{\frac {x}{\sqrt {\pi }}} \right) +\frac{{x}^{3}}{6}
$$
Note that for $x > 0$
$$\eqalign{\frac{f(x+h) -f(x)}{h} &= \frac{1}{h} \int_x^{x+h} (1 + t^2 \cos^2(t^2))\ dt\cr
&> \frac{x^2}{h} \int_x^{x+h} \cos^2(t^2)\ dt \cr
&= \frac{x^2}{h} \left(\frac{h}{2} + \frac{\sqrt{\pi}}{4} \left({\rm FresnelC}\left(
\frac{2(x+h)}{\sqrt{\pi}}\right) - {\rm FresnelC}\left(
\frac{2x}{\sqrt{\pi}}\right) \right)\right)
\cr
&=  \frac{x^2}{2} + o(x^2)}$$
as $x \to \infty$ for any fixed $h$ (since ${\rm FresnelC}(t) \to 1/2$ as $t \to \infty$), while $f'(\sqrt{(n+1/2)\pi})=1$ for positive integers $n$.
Comment: ops, I forgot to write that I want also the first derivative bounded away from zero..see edit. sorry.
Comment: I accept the other answer because it is bit simpler, but this is interesting anyway, thanks!


Guardar valor geojson

Question: Como é que ao fazer um geojson eu conseguiria gravar números em vez de string.
Exemplo:
$geojson = array(
    'type'      => 'FeatureCollection',
    'features'  => array()
);

while( ($registo = mysqli_fetch_assoc($resultado)) !=null)
{
    $feature = array(
        'type' => 'Feature',
        'geometry' => array(
            'type' => 'Point',
            'coordinates' => array($registo['x'], $registo['y'])
        ),
        'properties' => array(
            'id_publicidade' => $registo['id_publicidade'],
            'id_utilizador' => $registo['id_utilizador'],
            'nome' => $registo['nome'],
            'categoria' => $registo['categoria'],
        )
    );
array_push($geojson['features'], $feature);
};
echo json_encode($geojson);

A minha questão está na parte: 'coordinates' => array($registo['x'], $registo['y'])
Ao fazer o echo do json o resultado é:
"coordinates":["-8.847618468261716","41.693271914384525"]
Eu quero que não me apreçam as aspas, quero que o json fique sem àspas, porque ao continuar o meu código as áspas conseguem de alguma forma interferir com as coordenadas.
Comment: Já testaste usando o `floatval()`? Assim: `'coordinates' => array(floatval($registo['x']), floatval($registo['y']))`
Answer: Podes usar o floatval() que converte uma string em valor com parte fracional:
'coordinates' => array(floatval($registo['x']), floatval($registo['y']))
                          ^                        ^

Comment: Perfeito amigo, desconhecia totalmente isso.
Muito obrigado!

Guardar valor geojson


Check if DateString is valid from List of formats using Java8

Question: I am new to Java8
I am trying to check whether a DateString is valid by checking it against a list of acceptable date formats in my application.
I am currently using SimpleDateFormat.
Is it possible to do this using DateTimeFormatter since I am using Java8?
<code>public static boolean isDateValid(String dateValue)
    {
        boolean returnVal = false;
        String[] permissFormats = new String[]{"yyyy-MM-dd", "ddMMMyy"};
        SimpleDateFormat sdfObj = new SimpleDateFormat();
        sdfObj.setLenient(false); //strict validation
        ParsePosition position = new ParsePosition(0);
        for (int i = 0; i < permissFormats.length; i++) {
            sdfObj.applyPattern(permissFormats[i]);
            position.setIndex(0);
            position.setErrorIndex(-1);
            sdfObj.parse(dateValue, position);
            if (position.getErrorIndex() == -1) {
                returnVal = true;
                break;
            }
        }
        return returnVal;
    }
</code>
Answer: Here is one way which is just replacing with java 8 equivalent.
<code>    public static boolean isDateValid(String dateValue)
    {
        boolean returnVal = false;
        String[] permissFormats = new String[]{"yyyy-MM-dd", "ddMMMyy"};
         for (int i = 0; i < permissFormats.length; i++) {
            DateTimeFormatter sdfObj = new DateTimeFormatterBuilder()
                    .parseStrict().parseCaseInsensitive().appendPattern(permissFormats[i]).toFormatter();
            ParsePosition position = new ParsePosition(0);
            position.setIndex(0);
            position.setErrorIndex(-1);
            sdfObj.parse(dateValue, position);
            if (position.getErrorIndex() == -1) {
                returnVal = true;
                break;
            }
        }
        return returnVal;
    }
</code>
Comment: Hi, I tested with 19JAN17 but the method returned false. I see the exception java.time.format.DateTimeParseException: Text '19JAN17' could not be parsed at index 0
java.time.format.DateTimeParseException: Text '19JAN17' could not be parsed at index 2
Comment: DateTimeFormatter is more strict than SimpleDateFormat. Added the case insensitive option to the builder. Try now.
Comment: I see that the 1st pattern yyyy-MM-dd is working but ddMMMyy is not working
Comment: MM for number & MMM for text. So the first one works and second one needed case insensitive option to work in all cases.
Comment: If I put ddMMMyy is placed in first place then it works but yyyy-MM-dd fails. Whichever is the 1st pattern is working correctly. the second pattern is not working


Prove that $2AB$ is square

Question: Let $$A= 1! \cdot 2! \cdot 3! \cdots 1002!$$
$$B= 1004!\cdot 1005! \cdots 2006!$$
Prove that $2AB$ is square. Help guys, I tried, I really did but I couldn't.
Comment: $$\begin{align}
1! \times 2! &= 2 \times (1!)^2 \times 1,\\
3! \times 4! &=  2 \times (3!)^2 \times 2,\\
&\;\;\vdots\\
1004! &= 2 \times (1003)! \times 502\\
1005! \times 1006! &= 2 \times (1005!)^2 \times 503\\
&\;\;\vdots\\
2005! \times 2006! &= 2 \times (2005!)^2 \times 1003
\end{align}
$$
Comment: What did you try?
Answer: With help from above comment we have:
\begin{align}
2AB &= 2(1!×2!×...×1002!)(1004!×1005!×...×2006!) \\
&= 2(2^{501}×1×2×...×501)(2^{500}×502×503×...×1003)((1!)^2(2!)^2 ...(1003!)×(1005!)^2 ...(2005!)^2 \\
&= 2^{1002}(1!)^2 ...(1003!)(1003!)(1005!)^2 (1006)^2 ...(2005)^2 \\
&=  2^{1002} ...
\end{align}
square.

Prove that $2AB$ is square


Is it common to use pinky (little finger) on black keys?

Question:
So I'm reading this book called piano and keyboard all in one for dummies and in the very last measure of this image you can see a 5 (pinky/little finger) is suggested for the B flat since this is key of F.
I think I read that you're not supposed to use thumb or pinky on black notes? Why does author suggest it here?
Comment: All comment have been purged here. In general, we have a wide audience  that use different sets of terminology (ground/earth,  crochet/quater note, ect.)  and we do not expect localization edits for every single term.
Answer: As a piano player of over 30 years, I can assure you that the pinky finger plays plenty of black keys. Either hand.

Is it common ...?

I want to say yes, but let's have some specific examples.

it's less common to use pinky fingers to play major scales which originate on black keys (Bb, Eb, Ab)
no pinky finger is used when playing the chromatic scale
pinky fingers are less commonly used for trills (and most other ornaments)

All that aside, I have never considered the pinky to be uncommon or under-used. I use both of mine all the time when playing, and certainly on many black keys. As do most other players I should hope.
Comment: Another point: How else are you supposed to play octaves if not with the fifth finger?
Comment: @Ian Goldby - Apparently, some people's hands are big enough that they can use their thumb and ring finger to play octaves.
Comment: Just to reinforce this answer, when playing Mendelssohn Songs Without Words and other similar music, almost the entire melody is played with the fourth and fifth fingers of the right hand, the other right hand fingers being kept fully occupied with the accompaniment. Plenty of black notes there.
Comment: I can think of at least one Beethoven piece (last movement of the Waldstein) where the 4th and 5th fingers are used for an extended trill (mainly because the other fingers are busy doing the melody below them).  I think it occurs in several Chopin pieces as well, I'd have to check if black keys are involved...
Comment: @Dekkadeci I can play a 10th with my left hand and a wide 9th on my right, so I can pretty easily do octaves using my thumb and ring finger.
Comment: @DarrelHoffman "Less commonly used" does not mean *never.* Check if you want, but don't waste your time ...
Comment: Pianists advanced enough to play most of the Beethoven sonatas and Chopin etudes *very* commonly play white note octaves with 5th finger, black with 4th.  Play a chromatic octave run to see how well it fits the hand.
Answer:
I think I read that you're not supposed to use thumb or pinky on black notes?

Then you read incorrectly.  It may be helpful for absolute beginners when they are first learning, but by the time a beginner can play more than "Twinkle twinkle little star" with one finger, they should have gone past that rule.
For a very obvious counter-example, look at the first movement of Beethoven's Moonlight Sonata, which should be within a player's ability around Grade 3.

The very first notes played on the left hand are C#'s an octave apart.  In bar 5 we add octave G#'s in the right hand.  The entire piece makes substantial use of notes an octave apart in both hands, and there is no practical way to play this except with thumb and little (pinky) finger.
Comment: "no practical way"?  1st and 4th finger...
Comment: @ApollyssupportsMonica You've got longer fingers than me then, especially if you can do the octave-plus-one stretch in bar 8 like that! As an interesting aside, my mum is a piano teacher, and one of her little fingers is shorter than normal, due to a childhood accident.  She's a brilliant musician, but she has trouble playing octaves with that hand, and she really can't reach that stretch - she has to "arpeggiate" it.  Which of course she can make sound good, because she's so much better. :)
Comment: @ApollyssupportsMonica Oh, and practicality does also depend on what else you need those fingers to do.  Technically you can play the arpeggios and the top "melody" notes with the first four fingers, I guess, but it wouldn't be my choice of fingering.
Answer: When there's a choice! It makes a lot of sense to use a longer finger on the further-away-from-you black keys. Easier to reach, surely? Same reason there's a 'rule' about not using thumbs on black keys.
One always has to use a modicum of common sense when sorting fingering on piano. And sometimes, the 'rule' has to be broken for want of compromise. If it's easier, better, more effective to use pinky (or thumb) on a black key, then so be it. If it's easier (etc.) not to, then don't!
Comment: I agree. This is exactly what I was taught on organ. It definitely has it's uses, but should not be the first option to consider when deciding on a fingering. It greatly depends on the notes missing in the image. When followed by G+Bb for example it makes sense to use the pinky.
Answer: When the aim is to play a scale perfectly evenly, the 'long fingers on black keys, short fingers on white' rule makes sense.
In playing pieces, understand the purpose of that rule, but be prepared to break it!   Especially when the bit in question ISN'T a fast scalic passage.
Answer: I think you want to distinguish fingerings for scale from chords. And chords can be groups into different spacings like less than an octave, full octave, exceeding an octave. The fingerings for those things have different requirements and so one general rule won't really apply to all of them.
While finger 5 on black is avoided for scales that isn't the case for playing chords. Same goes for finger 1 - the thumb. The obvious case is a full octave chord starting and ending on black keys, ex. E flat minor. A normal fingering for that would be fingers 1 and 5 on the E flats. I suppose a large hand could use 1 and 4, but let's not generalize from extreme cases.
About the finger 5 on B flat in the bass from the example: other options like reaching with finger 4 as - 4 2 1 2 - or some kind of cross over like 4 1 2 1 seem less than ideal. Too much effort to reach or cross. For the suggested fingering - 5 2 1 2 - I would consider these two points: 5 on B flat and 1 on G  fits with the concept of keeping the short reach fingers (the thumb in this case) on white and by comparison finger 5 can reach farther than the thumb to the black key. Also, if you keep your fingers arched and move in a little toward the fallboard so your fingers are positioned in the middle of the key length (yellow zone in the picture below) it will mitigate the finger reach issues.
Comment: This is the answer.  Other answers do not note that the rule cited in the question makes perfect sense for scales, but does not apply in the example in question because it's not a scale.
Answer: There are no rules about which fingers to use on which keys. Fingering notation is a suggestion (unless indicated otherwise), possibly from the composer himself, so it might be extremely valuable. It may also be awkward depending on your comfort level and relative finger strength.
You'll have a very hard time playing more difficult pieces if you could never use your thumb or pinky on a black note! You may even be indicated to use your forearm or foot on the keys if you look into 20th century avant garde composition...
Comment: As a rather novice musician I'm a bit shocked that the little/pinky finger is used on black keys at all. I have short pinkies and can't reach the white keys with them (at least with any strength), let alone the black (probably why a strong factor it not progressing beyond being a novice). I Don't even use them to type on a keyboard. It makes me curious what the breakdown is by gender and handspan is for the difficulty of various compositions (and how this affects how people adapt or not).
Answer: If you are a beginner (which I guess from the fact that you are reading a "for dummies" book), don't forget that the position of your fingers on the white keys should be up close to the end of the black keys, not right at the end of the keys.
So playing B flat or E flat with your left hand pinky should be easy, since there are no other keys that get in the way. The same is true for F sharp and C sharp with your right pinky.
As others have said, you often need to play any black key with the pinky, and also with the thumb.
Answer: I know the rule for playing scales  using the thumb on the white keys - and not running from a white key played e.g. by the middle finger under leading the thumb to a black key - let's say you play the B major scale then it is clear that the thumb is on B and E and not (1,2,3,1,2,3,4) and not the ring finger (4) on E and the thumb on F# (1,2,3,4,1,2,3)
So, of  the rules you are talking about I only use the one for the thumb and only for scales, but not necessarily for chords, triads and arpeggios. (how would you play a F#major arpeggio F#,A#,C#,F#->A#,C#,F#,A# -> C#,F#,A#,C# ->F#,A#,C#,F#???)
About the rule not using the pinky finger for black keys I have never heard, but it makes sense to play in front of the keys and so it makes sens to use the longer finger to play the black keys as they are further behind.
It also make sense to use the pinky finger that it doesn't get spoiled and lazy to stay in form and strong ;)
Edit:
I've just seen in your example:
It seems to be a Boogie or Blues like pattern in the left hand:
For beginners it might be an advantage to use the same fingering  for the F and Bb chords.
Answer: When it comes to fingering, it's all down to context. You cannot decide which finger to use for a note without considering the notes before, the simultaneous notes, and the notes after. You may have some preferences, like not using short fingers for black keys, or not using the weak ring and pinkys for fast trills. But, every singe such rule must yield to the context consideration.
In this case, the left hand plays the Bb followed by f and g. The first interval is a fifth, and the fact that a g follows, discourages the use of the thumb for the f. So, playing the Bb with the ring finger and the f with the index finger would force you to spread your fingers quite significantly. Using the pinky allows your hand to remain in a much more relaxed posture. The fact that there is an f and a g following the Bb determines that the pinky is the best choice for the Bb. If there were a c and a d following the Bb, you'd likely use your middle finger instead.


Outlier detection using k-means in a binary classification problem

Question: I'm using k-means in every class of a binary classification problem and remove samples that have high distance from center of my features (21 features so 21 dimensions problem) before inserting data set to a neural network. After designing neural network model, now i want use this model for a new data set (out sample).
As you know we must use outlier detection parameters in per-process stage for out sample data (like normalization x-min(x)/max(x)-min(x) that will use max(x) and min(x) for normalization of out sample). what parameters of k-means algorithm should i use for out sample and how can I do that in MATLAB ?
Thanks.
Answer: You have to calculate the distance of your test samples (out sample) from the previously defined centroids (second output in Matlab kmeans function) using the same metric (see pdist) and then apply the same cutoff values on the distances obtained.
Comment: Thank you for your fast answer. So there isn't any pre-defined function for that in `MATLAB` and we should manually do that. Can you add a brief code in your answer for more description?
Comment: I think we should use `pdist2`. Is that true? `pdist2(out_sample_observations,centers_from_training_set_kmeans_output)`
Comment: + We are using `kmeans` on every class (class 1 and class 2) in training_sample but in out sample data we only have one database without any labeling. So I have two center sets for every class in training sample and now i have only one data set (without labels) as out samples. How can I do outlier detection in this problem?
Comment: + I remove highest 5% distances after sorting distances in training sample. Is that true?. If yes now I should remove highest 5% distances in out sample (5%-after sorting) ?
Comment: pdist2 is indeed more handy here, about your 5% I'm not sure to follow you, once you have the distance you can  remove anything above the threshold (the maximal distance allowed to a centroid) you defined on your training


Moving parts of data inside a single cudaArray with cudaMemcpy3D possible?

Question: I want to implement a shift operation for a volume texture in CUDA. I thought of an implementation that does several iterations of a memcpy-operation that moves data inside a cudaArray from one position to another.
What am I doing wrong, because I always get the invalid argument error? Here is a sketch of what I am doing:
<code>/* My volume texture */
cudaArray* g_pVolumeTexture // its size is 256^3 voxels of type uchar2

...

cudaMemcpy3DParms prms;
prms.srcArray = g_pVolumeTexture;
prms.dstArray = g_pVolumeTexture; // src = dst, because I wanna rather shift than
                                  // copy

prms.extent = make_cudaExtent(24, 256, 256);
prms.srcPos = make_cudaPos(0, 0, 0);
prms.dstPos = make_cudaPos(48, 0, 0); // this will mean a move of 48 voxels in
                                      // x-direction; the piece of data moved
                                      // measures 24 voxels in x-direction

cudaMemcpy3D(&prms);

// Here cudaGetLastError always returns 'invalid argument error'
</code>
Comment: try `cudaMemcpy3DParms prms=0` - you probably have uninitialised arguments with random values in them. This is explicitly noted in the API documentation.
Answer: The answer is yes: It is possible to use the Memcpy3D command with same srcArray as dstArray. The problem I faced appeared due to the nonexistance of an initial reset of the cudaMemcpy3DParms with:
<code>cudaMemcpy3DParms p = {0};
</code>


Using the latent representation from an autoencoder as input to layers of LSTMs

Question: When people talk about using an autoencoder for feature extraction before some network, in this case a deep network of LSTMs, are they referring to first training the autoencoder, and then passing the latent representation to the next network, or are they talking about passing the reconstruction? What are the pros and cons? Would passing the latent representation of the autoencoder to a deep LSTM aid in time series analysis?
Answer:
I would train the AE, and use the resulting Encoder to extract a reduced dimension form of the input to pass to the LSTM. There is research that suggests the use of an AE has resulted in improved performance for prediction. Note that this is just dimensionality reduction, a non-linear form, as opposed to PCA, a linear form. There is research that suggests PCA helps to address multicollinearity, which constrains the predictive accuracy. I would think the Encoder would have similar positive effects.
The reconstruction is used for training the AE. Use the reconstruction and the original input to compute a loss, compute gradients, and then apply backpropagation. Most frameworks will handle this for you out of the box. I don't think the reconstruction should be passed to the LSTM.


Scorekeeping a fielder on a Sacrifice Fly

Question: Currently I know that in a baseball game (Major League Baseball), a sacrifice fly is scored to the batter acting in an attempt to forfeit their attempt at a score (aka get on base) to allow someone else a chance to score (when there are less than two outs).
The question is does the fielder who catches the sac fly still get credit with a putout? I would like to say YES but the scorebook I'm using is showing empty box. I know that the batter is not credited as having an official at bat.
Answer: Yes, the fielder gets credited with a putout.  Per the MLB rulebook, 9.09(a):

(a) The official scorer shall credit a putout to each fielder who

(1) catches a ball that is in flight, whether fair or foul;
(2) catches a batted or thrown ball and tags a base to put out
    a batter or runner; or

Rule 9.09(a)(2) Comment: The official scorer shall credit a
      fielder with a putout if such fielder catches a thrown ball and
      tags a base to record an out on an appeal play.

(3) tags a runner when the runner is off the base to which the
    runner is entitled.

No exception is made for sacrifices of any sort.


Existe algum erro nestas linhas de comando?

Question: Estou fazendo comparações entre documentos pelas linhas de comando de Bash e usando um comando de loop. Porém, ocorre um erro com os resultados:

<code>./anibatch.sh: line 38: ./ANIcalculator: No such file or directory
./anibatch.sh: line 39: ./ANIcalculator: No such file or directory
./anibatch.sh: line 40: ./ANIcalculator: No such file or directory
./anibatch.sh: line 41: ./ANIcalculator: No such file or directory
./anibatch.sh: line 3: ./ANIcalculator: No such file or directory
./anibatch.sh: line 4: ./ANIcalculator: No such file or directory
./anibatch.sh: line 5: ./ANIcalculator: No such file or directory
./anibatch.sh: line 6: ./ANIcalculator: No such file or directory
./anibatch.sh: line 7: ./ANIcalculator: No such file or directory
./anibatch.sh: line 8: ./ANIcalculator: No such file or directory
./anibatch.sh: line 9: ./ANIcalculator: No such file or directory
./anibatch.sh: line 10: ./ANIcalculator: No such file or directory
</code>

com tal informação, eu quero saber se o bash em questão está errado:
<code>#!/bin/bash
for file in *fna; do
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_alginolyticus_DSM_5050_NBRC_15375.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_algorifonticola.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_alvei_DSM_29.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_antarcticus.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_borealis.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_chitinolyticus_NBRC_15660.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_curdlanolyticus_YK9.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_daejeonensis_DSM_15491.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_darwinianus.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_dauci.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_durus_ATCC_35681.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_durus.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_forsythiae_T98.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_glacialis.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_glucanolyticus.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_graminis.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_graminis_RSA19.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_harenae_DSM_16969.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_jilunlii.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_macquariensis_subsp._defensor.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_macquariensis_subsp._macquariensis.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_massiliensis_2301065_DSM_16942.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_odorifer.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_pabuli_NBRC_13638.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_pinihumi_DSM_23905_JCM_16419.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_pini_JCM_16418.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_polymyxa_ATCC_842.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_popilliae_ATCC_14706.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_riograndensis_SBR5.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_sabinae_T27.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_sanguinis_2301083_DSM_16941.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_senegalensis_JC66.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_sonchi_X19-5.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_sp._A9.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_stellifer.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_swuensis.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_taiwanensis_DSM_18679.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_wulumuqiensis.fna -outfile genoma_comparacao
./ANIcalculator -genome1fna $file -genome2fna Paenibacillus_zanthoxyli_JH29.fna -outfile genoma_comparacao
done
</code>
Comment: Simplemente não existe nenhum ANIcalculator no diretório corrente. Provavelmente está rodando o script no diretório errado.
Answer: O erro ocorre porque os arquivos não estão no diretório onde você está executando o script. Uma das alternativas é dentro do seu script você entrar na pasta onde se encontra os arquivos ou o arquivo:
<code>    #!/bin/bash

    cd <caminho_do_arquivo>
    #restante do script
</code>
Answer: Pode ser que o problema esteja nos locais dos arquivos como o amigo de cima falou. Um exemplo simples que você pode fazer é com esse script de teste. Crie alguns arquivos com a extensão ".tst" de exemplo e veja se ele exibe eles da forma que você precisa.
Como meu exemplo.
<code>#!/bin/bash

folders="*.tst"

for i in $folders;do

        ls $i

done
</code>


What are these dots above a note?

Question: I was going through some jazz music and I encountered these four dots above a note leading into an improv solo:

What do they mean? Is it a doit, or does it signify going up in the following solo? Here are the following measures:
Comment: I think the composer made it up & only he knows what he was thinking
Comment: probably trailing sound since it's the end of the piece. That's my guess.
Comment: Is that the end of the piece (a final barline), or just the end of a section (a *double* barline)? If it's just a double barline, it may be a dotted slur leading into the next system.
Comment: it looks like multiple dotting https://en.wikipedia.org/wiki/Dotted_note
Answer: It's an optional slur. That's why it's dotted. There's a solo section after that note right? It's just saying you can hold that A into the solo if you want. Optional
Answer: It can ben an optional slur like Kidd671 said but it can also be anything you can imagine. Here, the composer let you deceide what you feel this dotted line is : continue, go up, whatever improvise your solo starts here.
The second page you showed us is just the form and suggested notes to use for your solo, just for inspiration. You do not have to follow theses notes all the time, of course, and you do not need to use all of them! Just go on and play.
In resume we could say : from the start of that "A", you are absolutely free to do whatever you feel for

What are these dots above a note?


List all Nodes a user ever edited

Question: I want to do display a list with Views, which shows all Nodes the current user have ever edited.
The workbench Module includes a list like I need, 'workbench_edited', this view uses the Filter
<code>(revision user) User: Current (Yes)
</code>

But the problem is that this View only checks if the user is the editor of the CURRENT REVISION, it does not check all revions of a node, just the current one.
Is there a way to list all Nodes a User ever edited? So that Views checks all revisions of a node?
Answer: The "content revision : content" relationship in that view needs to be based on the nid rather than the vid. Remove that existing relationship and add back the one that has the same name but uses the nid.
Then you'll need to fix the relationships that have been broken since a number of the fields, filters, and sort options relied on that relationship.  You can just step through each of the fields and filters, open their settings, then click "apply" to re-save them to fix the relationships.
In the settings for the title field you need to switch it to link to the revision rather than the node, in order to avoid an error.
And I also noticed that, for some reason, the exposed "published" filter got switched to having a default value of "no" after doing these steps.  I have no idea why that happened, but switch it back to "any".
Here's an export of the View you should end up with: http://pastebin.com/a9tXXCqP
Comment: yes there are two: The revision NID of the content revision. and The Version-ID, wich belongs to the version of the content. But if I choose the first one and remove the second I get too few nodes.
Comment: You need to remove the revision ID relationship then add the NID option...the one labeled "The revision NID of the content revision.".  After doing that you'll need to step through each and every field, filter, and sort option.  Click the link to open the settings, then without changing anything, click "apply" at the bottom.  This is because there are a bunch of broken relationships that need to be fixed.  Once you've done that it should work.
Comment: This does not work, if I change the relationship i get no results.
Comment: When I tested it randomly set the published filter's default value to "no", so make sure that's not tripping you up.
Answer: I was able to get a list of pages the user has edited (has made a revision on) by using the following setup:

List all Nodes a user ever edited


What's the proper way of working locally with freshly created features?

Question: I have recently started to using Features, it was due time.
Once thing I started to wonder, is, once you created your feature locally, what's the best way to work with it. I first thought that creating the feature was enough and once it was there you could use it as such, but disabling the newly created feature doesn't remove everything the features exports, so it doesn't behave the same way as if you installed the same feature on a plain site.
Is that on purpose? If so why? What are the details I should consider for working with Features on the initial site.
Answer: How features store settings
Features that are created locally have all there setting and content in the database as they where there before you export them to the feature, as an example if you created a view it will reside in the database even if you exported it to a feature.
as for features enabled on another site it will store every thing in the database when enabled except for ctools exports, which in this case even if you disable or uninstalled the feature those sittings will persist in the new site database, an example a strongarm (variable) will still be set even after you uninstall the feature.
as for settings using ctools exports they will not be added to the database unless you have override them, as an example if you had a view exported through features it will disappear if you have disabled the feature since it only exist in code.
Conclusion
Features do not delete any thing in your database if uninstalled, except for true exportables that can only reside in code without the need to be in the daatabse to work.
Suggested features workflow
When creating a feature on you local development machine it is a good thing to enable it to see if the settings in your database and the settings in the feature does match and be aware if they do change.
As for removing things added by the feature you can add a hook_uninstall manually to your feature .install file and remove or delete what ever you like just like a proper module will do when uninstalled.
More info about this issue:

https://www.drupal.org/node/1732766#comment-6382244
https://www.drupal.org/project/configuration


Monte Carlo Simulation...?

Question: I just have 2 questions:
(1) If we can obtain samples from the posterior distribution, is there any need to try to compute posterior expectations and intervals analytically...?
(2) Also, I know that Monte Carlo methods will, in general, produce different results every time they are run, but how might I convince someone that my results obtained using MC are reliable?
Any help would be appreciated.
Answer: 1) Your question suggests you have the analytical posterior distribution available. If this is the case, it is always of value to have the analytic expectations and such like if it is non intractable to derive (as someone famous said, a good Monte Carlo is a dead Monte Carlo). For one thing, it may not be easy (algorithmically, or programmatically) to sample from the posterior distribution even if you know it analytically. However, if you don't know the analytical posterior expression i.e. you can't easily compute the integral denominator, then your only choice is to sample - that's why we have Monte Carlo in the first place.
2) If you produce multiple MC runs - you can compare results. If your MC sample can guarantee independent samples, then a simple variance estimator ($\frac{\widehat{\sigma}^2}{n}$ type) can give you some idea of how good your expectation estimate is. If your MC sample is from a MCMC algorithm, say, Metropolis Hastings, some more careful thought and good diagnostics are required - typically looking at the trace plots and autocorrelation plots. I'm sure someone else can contribute much more to this discussion...
Comment: +1 Although there is more that can be said, as you intimate, this is a nice start. (I don't want to leave you hanging with that cryptic remark, so I will be more explicit. One direction this conversation could go in would be to point out that any randomized sampling procedure is typically subject to greater uncertainties ("unreliability") than the output of a well-done MC calculation. This has a bearing on question (2).)
Comment: I guess the main thing is that the question is quite vague and open-ended. Perhaps Dan could consider being more specific?
Answer: For your second question, someone will be convinced if your MC results are converged within some error bar. Since multiple MC runs produce different results, the conception of converging result comes in. How to tell your results are converged or not is given in @queenbee answer.
By the way, for other people to fully reproduce your MC results, setting your random number seed at the beginning is important.

Monte Carlo Simulation...?


Setup WAMP to be able to access from a mobile phone

Question: I am making a WordPress theme that should be served to mobile users. So far I have been testing it in Chrome using User agent spoofing. Now I would like to try and access it from a real mobile device.
On my PC I access the site using a virtual host that aims a folder on my computer. How do I do this from my phone, where I can't edit hosts file?
I found this tutorial.
Regarding my httpd.conf file, I changed
Listen 80

to
Listen 192.168.xxx.xxx:8081

I also added to <Directory "cgi-bin">
Allow from all

The third thing I did was to open up port 8081.
Now, what I don't know is how to access my WordPress site from my phone, because when I type 192.168.xxx.xxx:8081 into the browser, I get Forbidden.
Comment: Check http://wordpress.stackexchange.com/a/98419/12615
Answer: You can leave Listen 80 as is.  Just find out the IP of your machine and type that into your phone. http://192.168.xxx.xxx
Make sure your local machine's firewalls are configured properly to accept these connections.
If you have multiple virtual hosts, you can either make sure the site you are looking to test is listed first, or you may also be able to set DNS entries into your router / gateway if you are lucky.


Secure App Service Behind Azure WAF

Question: we are deploying some app services into Azure behind an Azure web application firewall, we already have some applications running on servers behind them, these are secured end to end using SSL. But what I can't get my head around is what security or protection we are to implement on the app services and how, I'm thinking it must be Azure AD OAuth or something similar, am I on the right track? Or is there a way I've missed, or can we use certificates?
Comment: Your question is really confusing, what are you trying to achieve? Are you looking for user authentication for your apps, or protection of the connection between your WAF and app service? If the later, what Azure Service are you using to host the WAF?
Comment: @SamCogan hi, we are using an azure app gateway, and my question is how you route traffic from the front end listener on http to back end site on https, sorry I was a bit rushed when I put the question together. I would be interested in how the ad authentication works, but the question is around securing access through the waf
Answer: If all you are looking to do is enable end to end encryption of traffic between App Gateway and your app then you can do this. This doc details how to enable e2e encryption with App Gateway.
If you want to authenticate the connection between App Gateway and your backend then that is more tricky. Currently App Gateway does not support mutual TLS authentication, or any sort of token based auth.

Secure App Service Behind Azure WAF


What's the ColdFusion 9 script syntax for cfsetting?

Question: I'm trying to convert an Application.cfc to script. The original had this:
<cfcomponent displayname="Application" output="false">
     <cfset this.name               = "testing">
     <cfset this.applicationTimeout = createTimeSpan(0,1,0,0)>
     <cfset this.sessionManagement  = true>
     <cfset this.sessionTimeout     = createTimeSpan(0,0,30,0)>

     <cfsetting requesttimeout="20">
     ...

I can't figure out how to convert the cfsetting tag to script. The following attempts don't work:
setting requesttimeout="20"; // throws a "function keyword is missing in FUNCTION declaration." error.
setting( requesttimeout="20" ); // throws a "Variable SETTING is undefined." error.

It looks like Railo may be supporting it (link), but I can't find an equivalent for the cfsetting tag in ColdFusion's documents
Comment: It doesn't help you in CF9, but CF10 added native cfsetting to script.
Answer: There isn't one. Normally I'd suggest filing an ER for this, but there already is. What I'd recommend is putting into a CFM file and using include to bring it in.
Comment: Does voting for the error report help, or is it already accepted and going to be fixed for next version?
Comment: The bug has been closed as "fixed".  CF10 appears to have a `setting` tag-equivalent.
Answer: Give this a try
<cfscript>
createObject( "java", "coldfusion.tagext.lang.SettingTag" ).setRequestTimeout( javaCast( "double", 20 ) );
</cfscript>

or this
<cfscript>
createObject( "java", "coldfusion.runtime.RequestMonitor" ).overrideRequestTimeout( javaCast( "long", 20 ) );
</cfscript>

where 20 is your cfsetting requesttimeout value
Answer: In CF11 (and I think CF10), per the docs you can do:
setting enablecfoutputonly="true" requesttimeout="180" showdebugoutput="no";

Comment: The question is about CF9, but since this is a top result in Google regardless of version I thought it would be useful to include here and to include the actual code sample.
Answer: These cfml scripts:
<cfsetting enablecfoutputonly="true" />
<cfsetting requesttimeout="60" />
<cfsetting showdebugoutput="false" />

should work in cfscript as these:
createObject( "java", "coldfusion.tagext.lang.SettingTag" ).setEnablecfoutputonly(true);
createObject( "java", "coldfusion.tagext.lang.SettingTag" ).setRequestTimeout(javaCast( "double", 60 ));
createObject( "java", "coldfusion.tagext.lang.SettingTag" ).setShowdebugoutput(false);

Comment: Poor documentation is no excuse for not using features built in to the software. The only difference is you are just responsible for ensuring they are still present in future editions. There has been plenty of documented features that have broken in newer versions anyway. So, long story short, make sure you use a testing framework and trust your tests more than incomplete/inaccurate documentation.
Comment: As this is not documented, I would not recommend using this in production code.
Answer: setting.requesttimeout="3000";

This should work


Proving that $\int_{-\infty}^{\infty} \frac{\cos \pi x}{z^2-2z+5}\mathrm{d}x = -\frac{\pi }{2}e^{-2\pi}$

Question: I want to show that (for $x \in \mathbb{R}$ and $z \in \mathbb{C}$)
$$ \int_{-\infty}^{\infty} {\dfrac{\cos \pi x}{z^2-2z+5}}\mathrm{d}x = -\frac{\pi }{2}e^{-2\pi}$$
However, I am a little confused on how to proceed given that the denominator of the integrand is complex.
If the integral was in the form $ \int_{-\infty}^{\infty} {\dfrac{\cos \pi x}{\color{blue}{x^2-2x+5}}}\mathrm{d}x$, then I could treat it as a Fourier integral, and use the fact that $$ \int_{-\infty}^{\infty} {\dfrac{\cos \pi x}{x^2-2x+5}}\mathrm{d}x = -2\pi \sum {\operatorname{Im} \operatorname{Res} \left[ \dfrac{e^{i\pi z}}{z^2-2z+5} \right] }$$
But given that the numerator of the integrand is a complex number, I am missing a key insight on how to proceed towards a solution.
Thanks in advance!
Answer: Let $\Gamma_{R}$ be the semicircular contour in the upper-half plane of radius $R$. Then calculate
$$\int_{-\infty}^{\infty} \frac{\cos(\pi x)}{x^2-2x+5}\, dx = \Re \left \{\int_{-\infty}^{\infty} \frac{e^{i \pi x}}{x^2-2x+5}\, dx \right \} \\
= \Re \left \{\int_{\Gamma_R} \frac{e^{i \pi z}}{z^2-2z+5} \right \} \\
= \Re \{2\pi i \mathrm{Res}_{z=1+2i} \left (e^{i \pi z}/(z^2-2z+5) \right ) \} \\
= \Re \{2\pi i e^{i \pi - 2\pi}/(4i) \} = -\frac{\pi}{2}e^{-2\pi}.$$
On the question of whether it is a $z$ or an $x$: it is a typo. Just substitute $z=0$ and $z=1$ to belie a contradiction by linearity to do a dummy check.


How to make a selector for direct child of the root node?

Question: Consider that you are given a node node and you must provide all direct children given by selector Direct. Selector for direct child is:
childParent > directChild

However, the following fails with an error in console:
document.body.querySelectorAll(">div")
SyntaxError: '>div' is not a valid selector

I have a function that needs to do something on select direct child nodes, but I'm not sure how to handle this. Except of course using the for loop and analyse the children with my own code, abandoning selectors completely.
The following code does not work. Can it be changed so that it does what is intended?
function doWithDirectChildren(parentNode) {
    // does not work, the selector is invalid
    const children = parentNode.querySelector(">.shouldBeAffected");
    for(const direct of children) {
        // do something with the direct child
    }
}

I'm asking for a solution, not a workaround.
Comment: If it's always `body` you can do `document.querySelectorAll('body > div')`
Comment: What is the root node? body?
Comment: jQuery solves this problem https://api.jquery.com/children/
Comment: https://jsfiddle.net/xs7eb81h/
Comment: Without including jQuery, I'd say @JeffreyWesterkamp 's comment is the way to go.
Comment: If it was always body, I wouldn't contrive example that involves arbitrary element passed as an argument.
Comment: That's why I also posted an answer :)
Answer: The proper way to do this is with the :scope psuedo class.
According to the documentation at MDN:

When used from a DOM API such as querySelector(), querySelectorAll(), matches(), or Element.closest(), :scope matches the element on which the method was called.

For example:

let parent = document.querySelector('#parent');
let scoped = parent.querySelectorAll(':scope > span');

Array.from(scoped).forEach(s => {
  s.classList.add('selected');
});
.selected {
  background: yellow;
}

   Select Me

   Me Too

 Not Selected
Comment: @Simon, for `:scope + *` use [Element.nextElementSibling](https://developer.mozilla.org/en-US/docs/Web/API/Element/nextElementSibling), for `:scope ~ *` do `[...element.parentElement.children].filter((el,i,a) => i>a.indexOf(element));`
Comment: Caution, the `:scope` selector is not compatible with the sibling selectors. Example: `:scope + *` or `:scope ~ *` do not work. Question open here: https://stackoverflow.com/questions/65595914/css-pseudo-selector-to-select-the-current-element-within-queryselector-usable-fo
Answer: The child combinator operator > is a binary operator so using it with nothing on the left side is invalid.

The child combinator (>) is placed between two CSS selectors. It
  matches only those elements matched by the second selector that are
  the direct children of elements matched by the first.

If you can provide individual parent and child selectors you can do something simple like this
let directChildren = (parent, child) => document.querySelectorAll(`${parent} > ${child}`);
directChildren('body','div');//...

If your parent argument is a node or collection you would have to use a method of converting it back to a selector, like this one
Answer: jQuery solves this problem in 2 ways. Consider this code:

$('div.root').find('> .p2').addClass('highlighted');
$('div.root').children('.p2').addClass('red');
.highlighted {
  background: yellow
}

.red {
  color: red
}

div 1

paragraph 2

paragraph 3

paragraph 2 2

using .find('> selector) finds only direct children matching the selector, and using .children('selector') also does the same.
Comment: The question is not tagged `jquery`, IMHO it would be overkill to add JQuery only for this problem. (Furthermore, I think it would be overkill to add it for any problem in 2020. But that's just my opinion)
Comment: Most of my projects use React and so have no need for any dom-selecting logic. But there's no doubt in my mind that if you need complicated dom manipulation, jQuery still offers the best api, much much better than the tools provided by browsers by default (even with es6 features)


Confidence interval given sample size?

Question: Let's say I have a normal distribution of N ~ (1,0.01)
I pick 10 observations from that normal distribution. Is the confidence interval the same for 10 observations as it is for 100 observations? Or is there a difference?
Answer: If you really know the mean and the distribution of your data, no matter how much data you have, the mean distribution can be taken as if you had n as number of observations to infinity. Nevertheless, if you do not know the mean but you have only n data (As shown in the image below which is extracted from dummies.com), when the population standard deviation is known, <code>"the formula for a confidence interval (CI) for a population mean is"</code>

Therefore, if you were to depend only on data, then the larger your n for an equal standard deviation, the smaller the confidence interval.
Cheers !

Confidence interval given sample size?


change field value in a view using preprocess_views_view_fields

Question: I'm trying to change the value of a field in a view programatically but i find some problems.

first is  that even though I created a Global: custom text field which field id is 'nothing', It's value remain unchanged and the value is applied to a new field created at the end of the view.
Second is that this function creates some errors and drupal send lots of notices:

Notice: Undefined property: stdClass::$wrapper_prefix in include()
  (line 32 of
  /my/path/sites/all/modules/views/theme/views-view-fields.tpl.php).
Notice: Undefined property: stdClass::$label_html in include() (line
  33 of
  /my/path/sites/all/modules/views/theme/views-view-fields.tpl.php).
Notice: Undefined property: stdClass::$wrapper_suffix in include()
  (line 35 of
  /my/path/sites/all/modules/views/theme/views-view-fields.tpl.php).

My code is:
function real_estast_sub_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];

  foreach ($view->field as $id => $field) {

    // change the global custom text content depend on result (node id)
    if ($vars['row']->nid == 1625){
      $vars['fields']['nothing']->content = '666€';
    }else{
      $vars['fields']['nothing']->content = $vars['row']->field_data_field_price_field_price_value."€/noche ";
    }
  }
}

What's the problem here? I tried to follow all the steps explained in:
How to insert values into Global custom text field of views programmatically?

Edit:   I soolved the notices form drupal by adding:
  $vars['fields']['nothing']->wrapper_prefix = '';
  $vars['fields']['nothing']->wrapper_suffix  = '';
  $vars['fields']['nothing']->label_html = '';

But it's like I'm defining a totally new field instead of assigning a
  value to the existing one
Answer: You are probably not accessing the fields array correctly, and creating your own additional renderable array within $vars.
Install the Devel module if you haven't already and put
dpm($vars);

at the top of your function.  That will allow you to view the structure of the object on the screen (make sure you're logged in as user 1).
Comment: The problem was that the field was inside a field group so it couldn't be accessed directly. I had to put it outside and It solved the problem.


How to find a object of a list in a text

Question: The goal is finding any object of a list in a users input. In context, I am trying to find any letter in a string of numbers. My "solution" is to have a list of every letter of the alphabet then searching through a text finding any object of the list.
Problem being, I am extremely unknowledgeable and don't know how to do it. I suppose using "find()" would work, though am unable to make this work either.
def Main():
  text = input("Enter Algorithym \n")
  count = 0
  for x in alphabet:
    found = text.find(alphabet.count)
    if found != "-1":
      print(count)
      count += 1

  Main()  ## Main Loop

Answer: You could import re to find the letters in the string as follows:
import re

# Define a string of numbers
string_of_numbers = '1234abc5678def'

# Use regular expressions to find letters in the string
letters_found = re.findall('[a-zA-Z]', string_of_numbers)

# Print the letters found in the string
print(letters_found)

Alternatively, if you wanted to loop through you can use isalpha:
# Define a string of numbers
string_of_numbers = '1234abc5678def'

# Loop through each character in the string and check if it is a letter using isalpha()
letters_found = [char for char in string_of_numbers if char.isalpha()]

# Print the letters found in the string
print(letters_found)


How can I deduce (3.6) from (3.5)?

Question:
My attempt:-

I could verify the above formula for $f\in A_2(V) $ and $g\in A_1(V)$
  and vise versa. I know the fact that number of even permutation in
  $S_{k+l}$ is $\frac{(k+l)!}{2}$. So, sgn($\sigma$)=$1$ for
  $\frac{(k+l)!}{2}$ terms and sgn($\sigma$)=$-1$ for
  $\frac{(k+l)!}{2}$. I couldn't able to deduce for general case.
Comment: What is the paragrapf before Example 3.18?
Comment: How it is going to help me?@JaroslawMatlak
Comment: "By the paragraph before Example 3.18 one may rewrite (3.5) as ..."
Comment: okay. Let me try again :). Thank you very much
Answer: From @Jaroslaw Matlak 's Comment I typed my understanding of the section in the textbook.
Consider any $\sigma \in S_{k+l}$ and $\tau \in S_k$.$$(sgn\sigma \tau)f(v_{\sigma \tau(1)}, v_{\sigma \tau(2)},..., v_{\sigma \tau(k)})=(sgn\sigma \tau)(sgn\tau)f(v_{\sigma ((1))}, v_{\sigma ((2))},..., v_{\sigma ((k))})=(sgn\sigma)f(v_{\sigma ((1))}, v_{\sigma ((2))},..., v_{\sigma ((k))}).$$  There exists one $\tau'\in S_k$ such that $\sigma \tau'(1)<\sigma \tau'(2)<...<\sigma \tau'(k). $ We have $\sigma \tau \in S_{k+l},$ fixes the argument of $g$. T
herefore $k!$ number of equal quantities exists in the ($3.5$).
Consider any $\sigma \in S_{k+l}$ and $\rho \in S_l$.$$(sgn\sigma \rho)g(v_{\sigma \rho(k+1)}, v_{\sigma \rho(k+2)},..., v_{\sigma \rho(k+l)})=(sgn\sigma \rho)(sgn\rho)f(v_{\sigma ((k+1))}, v_{\sigma ((k+2))},..., v_{\sigma ((k+l))})=(sgn\sigma)g(v_{\sigma ((k+1))}, v_{\sigma ((k+2))},..., v_{\sigma ((k+l))}).$$  There exists one $\rho'\in S_l$ such that $\sigma \rho'(k+1)<\sigma \rho'(k+2)<...<\sigma \rho'(k+l). $ We have $\sigma \rho \in S_{k+l},$ fixes the argument of $f$.  Applying in ($3.5$) We get ($3.6$).

How can I deduce (3.6) from (3.5)?


Evaluating the integral $\int \frac{x-1}{(x+1) \sqrt{x^3+x^2+x}}dx$

Question: The integral to be evaluated is  $$\int \frac{(x-1)}{(x+1) \sqrt{x^3+x^2+x}}dx$$
I split the integral to obtain
$$\int \frac{\sqrt x}{(x+1) \sqrt{x^2+x+1}}dx - \int \frac{1}{(x+1)\sqrt{x^3+x^2+x}}dx$$
But I could not proceed any further, as I am not able to find any substitution, nor could I find any further simplification.
I tried by multiplying the numerator and denominator with $\sqrt {x-1}$ so as to obtain $ x^3-1$ inside the radical, but that didn't help either.
How should I proceed to evaluate this integral?
Comment: look like WA is not that smart. $2\tan^{-1}\sqrt{x+1+x^{-1}}$
Comment: [Wolfram|Alpha](http://www.wolframalpha.com/input/?i=integrate+(x-1)%2F((x%2B1)*sqrt(x%5E3%2Bx%5E2%2Bx))) suggests that the indefinite integral can be expressed in terms of [elliptic integrals](https://en.wikipedia.org/wiki/Elliptic_integral) of the first and third kind.
Answer: Notice
$$\begin{align}
  \int \frac{x-1}{(x+1)\sqrt{x^3+x^2+x}}dx
= &\int \frac{x-1}{(x+1)\sqrt{x+1+x^{-1}}}\frac{dx}{x}\\
= &\int \frac{x-1}{(x+1)\sqrt{x+1+x^{-1}}}\frac{d(x+1+x^{-1})}{x-x^{-1}}\\
= &\int \frac{d(x+1+x^{-1})}{(x+2+x^{-1})\sqrt{x+1+x^{-1}}}
\end{align}
$$
Let $u = \sqrt{x + 1 +x^{-1}}$, the indefinite integral evaluates to
$$\int \frac{du^2}{(1+u^2)u} = 2\int \frac{du}{1+u^2}
= 2\tan^{-1}(u) + \text{ const.}
= 2\tan^{-1}\sqrt{x+1+x^{-1}} + \text{ const.}$$