Maximum likelihood estimation and efficiency

Question: Let $X_1, ..., X_n$ be independent observations of a random variable $X$ that has with probability $p$ the distribution $\mathcal{U}[0,a]$ and with probability $1-p$ the distrbiution $\mathcal{U}[0,b]$ where $a$ and $b$ are known with $a<b$.

What is the maximum-likelihood estimator for $p$?
Is that estimator efficient? (This means, is the Cramér–Rao bound achieved?)

I'm having quite some trouble with this task for several hours now. I think the density of $X$ is given by $$f_X(x) = p \frac{1}{a}1_{[0,a]}(x) + (1-p) \frac{1}{b}1_{[0,b]}(x).$$
For the trivial case $n=1$ this gives $\hat{p}=1_{[0,a]}(x_1)$ where the expected value of $X_1$ is $a/b$. So the estimator is in fact biased. So this doesn't really help with the second task.
I can't even figure out the general likelihood function. I think it should be something like $L(p) = (p \frac{1}{a})^k ... + ((1-p) \frac{1}{b})^m ...$ where $k$ denotes the number of values from the sample $x_1, ..., x_n$ where $x_i\le a$ and $m=n-k$. But I don't understand how to deal with the indicator functions and if maybe I have to add a factor like with the binomial distribution.
However, I took the raw form $L(p) = (p \frac{1}{a})^k + ((1-p) \frac{1}{b})^{(n-k)}$, $k$ like explained above and tried to maximize by using the log-likelihood. But from that I got $\hat p = \frac{an-bN}{an-bn}$ which doesn't strike me as correct as because of $a<b$ it's negative for small $N$. Nonetheless, I tried to calculate the Fisher information and compared it's inverse to the variance of $\hat p$ - I wasn't very surprised not to get an equality...
Could be that I messed up some calculations, too - dealing with the derivatives of the log-likelihood was a little messy. Now I'm rather frustrated.
Can anyone show me how to solve this?
Answer: If the indicators functions confuse you, don't use them. Write instead
$$f_X(x)=\begin{cases}
\begin{array}{lc}
{p \over a} + \frac{1-p}{b} & x\in (0,a)\\
\frac{1-p}{b} & x\in (a,b)
\end{array}\\
\end{cases}$$
which, letting $A=1/a$ $B=1/b$ can also be written as
$$f_X(x)=\begin{cases}
\begin{array}{lc}
p\, (A-B) +B & x\in (0,a)\\
(1-p) \, B & x\in (a,b)
\end{array}\\
\end{cases}$$
If you have $n$ samples, of which $k$ fall in $(0,a)$, then the likelihood is
$$L = \left(p\, (A-B) +B\right)^k \left((1-p)B\right)^{n-k}$$
The derivative of the log-likelihood is then
and $$ \frac{k (A-B)}{p\, (A-B) +B} - \frac{(n-k)B}{(1-p)B}$$
which gives me
$$p_0=\frac{k}{n}-\left(1-\frac{k}{n}\right)\frac{a}{b-a}=\frac{1}{b-a}\left(\frac{k}{n}b-a\right)$$
Not however that this is just the critical point, which does not necessarily coincide with the ML estimator. ACtually, that is valid only if $k/n > a/b$, and
$$\hat p_{ML}= \begin{cases}
\begin{array}{lc}
\frac{1}{b-a}\left(\frac{k}{n}b-a\right) & k \ge n \frac{a}{b}\\
0 & elsewhere
\end{array}\\
\end{cases}$$
It doesn't seem to be consistent, as, when $n\to \infty$ $k/n \to p$ (in prob.), hence $\hat p_{ML}$ won't converge to $p$. Edited: sorry for the errors; actually $n/k \to p+(1-p)a/b = [p(b-a)+a]/b$ and hence the estimator should be at least asymtotically unbiased.
Comment: Thanks for the input. Is there any more agreeable way to check for efficiency than to actually compute the fisher information and compare it's inverse to $Var(\hat p)$?
Comment: I'd say that  this estimator is biased (even asymtotically), so it cannot be efficient (actually, the Cramer Rao bound applies only to unbiased estimators
Comment: BTW, you might have better answers at http://stats.stackexchange.com/
Comment: Why would $\frac{k}{n} \to p$ for $n \to \infty$? Values from $U[0,b]$ have lie within $[0,a]$ with a probability of $\frac{a}{b}$, i.e. $\mathbb{P}(X \leq a) =  p + (1-p)\frac{a}{b}$ and thus $\frac{k}{n} \to p + (1-p)\frac{a}{b}$, no?
Comment: I don't understand why biasedness is a problem. We introduced the CR bound in a general form that makes no use of unbiasedness: $$Var_\theta(T) \ge (\partial/\partial \theta E_\theta(T))^2 / I(\theta),$$ where $I(\theta)$ is the Fisher information. The usual CR bound follows from this in the unbiased case. With this, we can define efficiency independent of unbiasedness, I guess?
Comment: leonbloy: The formula at the end is wrong (but the first error is when $p_0$ appears, hence you should trace it easily).
Comment: @fgp You're right, fixed - thanks.
Comment: @Did Fixed, thanks.
Comment: Right. Note that $\hat p$ is unbiased, for every $n\geqslant1$.
Comment: @fgp Re your last comment to your answer, let me quote myself: `starting from l'(p)`.
Comment: @Did: I think the estimator would be unbiased it we'd just choose $\hat p = p_0$; but $\hat p_{ML} = max(p_0,0)$, the truncation should introduce a (asympotically negligible) bias.
Comment: leonbloy: Hmmm... I am stupid and you are absolutely right. Thanks for the explanation.
Comment: @Amarus: The CR bound can be extended to biased estimators, but the concept of "efficient" gets a little trickier. For one thing, the variance now is not an useful efficiency measure (it's trivial to build a zero-variance biased estimator: just pick a constant), one should instead compare mean squared errors. See eg the CR Wikipedia article.


Logging to an external file using Apache Camel

Question: I have a Camel Route which consumes a CSV file, converts it to XML and streams the data to ActiveMQ topic. I just want to log messages from my Camel Route, also detail log message about processing a message, etc.
Code:
public void configure() throws Exception {

    from("file:src/main/resources?fileName=data-sample.csv")
         .log("My first log message")
         .process(new MyTransformRevised1())
         .to("file:src/main/resources/?fileName=emp.xml")
         .split(body().tokenizeXML("equityFeeds", null))
         .streaming()
         .to("jms:topic:reuters.inbound.Topic");
}

Adding log4j.properties file:
# Root logger option
log4j.rootLogger=INFO, file, console

log4j.logger.org.apache.camel=DEBUG

log4j.logger.camelprojectupdated.CSVToXMLTransformationRevised1=INFO, file

# camelprojectupdated.CSVToXMLTransformationRevised1 - fully qualified class name of my project. camelprojectupdated is my package name and CSVToXMLTransformationRevised1 is my class name.

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=camel.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d | %p | %F %L | %m%n

# Direct log messages to stdout
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{HH:mm}| %p | %F %L | %m%n

Should it be log4j.properties or log4j2.properties?
Also should I have log4j or log4j2 for e.g.: log4j2.appender.console instead of log4j.appender.console
Requirements:

I would like to use slf4j and log output to both the file and the console.
Where do I give the log file name and location, ConsoleFileAppender and RollingFileAppender, etc.

Issues:
I am not able to see the logs even in Console. My log file is not getting created. I have placed the log4j.properties file in the classes folder. Do I have to place the log4j.jar in the classpath even if I want to use slf4j?
It's getting very difficult.
Comment: What is the message your want to log? And in which log file?
Comment: @Hassam: I want to log message content, tracing message flow, logs message from Java code, etc. I want to logs messages to a separate log file e.g. myapplication.log as well as in Console.
Comment: Which slf4j implementation are you pulling in? Are you sure it actually is log4j?
Answer: You can load the logger property file and set up the logger for usage(log4j).
public enum Logger {
INSTANCE;
public void initializeLogger() {
        PropertyConfigurator.configure(Logger.class.getResource("log4j.properties"));
   }
}

Comment: shouldn't it pick my log4j2.properties file if its in classpath i.e. src/main/resources folder instead of doing the above.
Comment: But you mentioned in the question class folder.
Comment: log4j2.properties is present in the src/main/resources folder. Still it's not being picked up and my message are not being printed to an external log file :-(
Comment: Are you adding log4j properties while running? if not Add the log4j.properties file to the Classpath. Right-click on your project name and select Run As -> Run Configurations. Go to the Classpath tab and click on the Advanced button. Select the Add Folders option and click on OK button. And select resources.
Comment: I did as per your directions. Still its not able to pick up the log4j.properties file :-(
Comment: why can't you try above mentioned code and initialize logger in your main class?


Problem using ENCRYPTBYPASSPHRASE/DECRYPTBYPASSPHRASE with file path

Question: I'm trying to use ENCRYPTBYPASSPHRASE/DECRYPTBYPASSPHRASE with file paths on SQL Server MS 14. I'm able to encrypt a given file path but when I try to decrypt I get a NULL value
I have already played with the types of the parameters without any change in the result. I tried to cast/convert the encrypted result to varbinary without success
select ENCRYPTBYPASSPHRASE('stackoverflow', 'C:\Users\brogeli\Documents\Personal\select-network-option.pdf', 1,
CONVERT(varbinary, '10'))

SELECT  DECRYPTBYPASSPHRASE('stackoverflow',
'0x010000005A331BC5AE1C1A7E3BDD47249768C5F51029970883DEEEED65457C7DC87EC0A020241BE11C45145850C2AA79078CD97E0704728262F825C92DC8E58C7A586A3B7EE798E435167F7DDC500706032A3F88707D5A13D88AF0A7B6DA309261F41CB56CFDE42A0DE0AC7B'
, 1, CONVERT(varbinary,
'10'
));

I expect to get the same file path with all characters but the actual output is NULL
EDIT:
So I tried this and it worked
select cast(DECRYPTBYPASSPHRASE('stackoverflow',
0x01000000BD9C213B8C9B279BA9B91E152EB9E8B37F3E37F4E4C4FAD4E104C706642B87C40838E65CA4AF7DF8276F191F04AF691C9753DB6C304D0F5733CCCD76A803A2AA7DCD3D6E9B4BDD19BE7B403DA9940B49CED28D414CCA0640D772E413DEF21B51BA343BEA3F6A10AA,
1, CONVERT(varbinary, '10'))as varchar(8000));

however, my idea is to create two stored procedures to encrypt/decrypt and pass the encrypted result as varchar to the decrypt procedure, so I tried cast/convert to varbinary but this doesn't work:
select cast(DECRYPTBYPASSPHRASE('stackoverflow',
cast('0x01000000BD9C213B8C9B279BA9B91E152EB9E8B37F3E37F4E4C4FAD4E104C706642B87C40838E65CA4AF7DF8276F191F04AF691C9753DB6C304D0F5733CCCD76A803A2AA7DCD3D6E9B4BDD19BE7B403DA9940B49CED28D414CCA0640D772E413DEF21B51BA343BEA3F6A10AA' as varbinary),
1, CONVERT(varbinary, '10'))as varchar(8000));

any ideas on how to accomplish this? Pass a varbinary as a varchar and cast/convert back to varbinary
Comment: Does it work for non-filepath cleartext?
Comment: nope I tried already
Comment: OK, so the question has nothing to do with file paths, really..
Answer: This worked for me
SELECT @@VERSION;

declare @b varbinary(max);
declare @pass nvarchar(200) ='stackoverflow';
declare @aut varbinary(max) = CONVERT(varbinary,'10');

SELECT @b = ENCRYPTBYPASSPHRASE( @pass, 'C:\Users\brogeli\Documents\Personal\select-network-option.pdf', 1, @aut);
SELECT cast(DECRYPTBYPASSPHRASE( @pass, @b, 1, @aut) as varchar(max));

Output
Microsoft SQL Server 2014 (SP2-GDR) (KB4019093) ...

C:\Users\brogeli\Documents\Personal\select-network-option.pdf


How do I move the variable referencing this array back one?

Question: I'm creating this fail-safe for identifying dates that shifts to the previous date in the array if the dataframe I'm working with doesn't contain the date. I have everything setup, I'm simply trying to understand how I can move the date variable from nav_dates_array[1] to nav_dates_array[0] without having to call from nav_dates_arr again. I thought a simple date.shift(1) would work but that is not the case.  Know this is basic so apologies but I hope you can help! Thank you!
nav_dates_arr = ['01-02-2020', '01-03-2020', '01-06-2020', '01-07-2020', '01-08-2020', '01-09-2020', '01-10-2020',
          '01-13-2020', '01-14-2020', '01-15-2020', '01-16-2020', '01-17-2020', '01-21-2020', '01-22-2020',
          '01-23-2020', '01-24-2020', '01-27-2020', '01-28-2020', '01-29-2020', '01-30-2020', '01-31-2020']

date = nav_dates_array[1]

here is the full code:
nav_dates_arr = ['2020-01-02', '01-03-2020', '01-06-2020', '01-07-2020', '01-08-2020', '01-09-2020', '01-10-2020',
          '01-13-2020', '01-14-2020', '01-15-2020', '01-16-2020', '01-17-2020', '01-21-2020', '01-22-2020',
          '01-23-2020', '01-24-2020', '01-27-2020', '01-28-2020', '01-29-2020', '01-30-2020', '01-31-2020']

def get_holdings_df_date(d):
    if str(d)in str(holdings_df['Date'].values):
        return holdings_df.loc[holdings_df['Date'] == d]
    else:
        return holdings_df.loc[holdings_df['Date'] == d]

   # return the row for the sent date using holdings_df.loc[holdings_df['Date'] == d]
   # if that date is missing, return the prior date
print(get_holdings_df_date(nav_dates_arr[0]))
system.exit()

where I'm trying to get the else statement to return d from the last position in the array.
Comment: nav_dates_arr= pd.date_range('1/2/2020', periods = 30, freq ='D') could initialize that array easier.
    nav_dates_arr=nav_dates_arr.shift(-1, freq ='D')  can shift the array by one to the left afterwards.
Answer: One possible solution, not sure if it is what you are looking for, is to store the array index as a variable. For example:
date_index = 1

Then you can get the current date like this always:
nav_dates_arr[date_index]

If you do date_index = date_index - 1, then this will "shift" your index left. But you will still need to use nav_dates_arr[date_index] to "get" the value.
If you wanted to get fancy and really have something like date.shift(1) you can implement your own Class that takes an array of dates in the constructor, keeps a current_index pointer, and has a shift method that moves the index left one (subtracts by 1).
Comment: I just updated my code at the top. I'm hoping that it helps better explain because i'm confused now.
Comment: okay... sorry it didn't really help. I don't understand what you're trying to do at all. It looks like the variable `nav_dates_arr` is not used. It would help to see what your input data is and what you'd like to get as output or return value, whether that be a date, position in array, or boolean.
Comment: what is the structure of `holdings_df`, it isn't clear.
Comment: It's a dataframe full of financial information that I grabbed online. I'm basically trying to match the dates to holdings_df. if the if statement doesn't match up then i'm trying to get the else statement to instead return the previous date in the dataframe.
Answer: Perhaps you are looking for something like this then?
nav_dates_arr = ['2020-01-02', '01-03-2020', '01-06-2020', '01-07-2020', '01-08-2020', '01-09-2020', '01-10-2020',
          '01-13-2020', '01-14-2020', '01-15-2020', '01-16-2020', '01-17-2020', '01-21-2020', '01-22-2020',
          '01-23-2020', '01-24-2020', '01-27-2020', '01-28-2020', '01-29-2020', '01-30-2020', '01-31-2020']

holdings_df = {}  # defined elsewhere...

def get_holdings_df_date(dates_arr, try_index=1):
    while try_index in dates_arr:  # keep going until we get index out of bounds
        if dates_arr[try_index] in holdings_df['Date'].values:  # see if our selected date is in the values list
            return dates_arr[try_index]  # if it is, great! return the date
        try_index = try_index - 1  # wasn't found, let's move our index to the left, and try again (loop)
    return None  # Nothing was found :(

print(get_holdings_df_date(nav_dates_arr, 1))
system.exit()

Comment: There isn't anyway to just ```return holdings_df.loc[holdings_df['Date'] == d].shift(-1)``` up a row in holdings_df for the else statement? to find the previous row in the holdings_df


JSON data received when directly used in browser, but not with cURL

Question: <code>$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://www.unocoin.com/trade?all');
$result = curl_exec($ch);
curl_close($ch);
$data = json_decode($result);
return $data;
</code>
JSON data is received when directly used in browser, but not with cURL in PHP.
Answer: Try like this way using php cURL,
<code>$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://www.unocoin.com/trade?all=",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET"
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
</code>
Response:
<code>{
    "buy": 505189,
    "sell": 487508,
    "avg": 496348
}
</code>
Comment: The result still show: Request unsuccessful. Incapsula incident ID: 569000570125410761-261362581203649432


Is it possible combine polynomial regression terms?

Question: I am dealing with a time series problem and one of the transformations that I am using is a moving slope of a line fit by linear regression on the last $w$ data, which is the window size.
However, my data is not always linear, so I thought of using a polynomial regression, but then I would have two terms representing what before was the slope:
$a + bx + cx^2$
Is there a way to combine $b$ and $c$?
Comment: You will need to give some more context here - why do you want to do this? Also, can you provide a "for instance"?
Answer: No, you cannot combine them into one term.
If you want to know how much $y$ changes when $x$ changes by one unit, take the derivative. I'll use partial derivative notation here so the solution makes sense for a regression with multiple different predictor variables ($x_1$ and $x_2$ instead of just $x$).
$$
\dfrac{\partial y}{\partial x} = b+2cx
$$
The amount by which $y$ changes when $x$ changes by $1$ depends on the value of $x$, which should be consistent with how you think of the derivative of a parabola; the slope changes depending on where you examine the slope.


Como conseguir o nome de um dia da semana tendo o ano/mes/dia em número

Question: Eu tenho um calendário que me retorna ao clicar em uma data o mês, ano, e dia.
Gostaria de saber se alguém já fez algum algoritmo para que através desses dados, ex: 20/10/2018, eu consiga o nome do dia da semana. Ex: "Sábado"
Alguma ideia de como fazer isso? Qualquer ajuda é bem vinda.
Eu tentei:
getNomeDiaSemana() {
    //Algoritmo para descobrir o dia da semana que o usuário selecionou
    let a = ((12 - this.mes) / 10);
    let b = this.ano - a;
    let c = this.mes + (12 * a);
    let d = b / 100;
    let e = d / 4;
    let f = 2 - d + e;
    let g =  (365.25 * b);
    let h = (30.6001 * (c + 1));
    let i = ((f + g) + (h + this.dia) + 5);
    let j = (i % 7); //Resto de I por 7, onde 0=SAB, 1=DOM, 2=SEG, 3=TER, 4=QUA, 5=QUI, 6=SEX
    //Testa o resultado e retorna
    switch (j) {
        case 0:
            return "Sábado";
        case 1:
            return "Domingo";
        case 2:
            return "Segunda";
        case 3:
            return "Terça";
        case 4:
            return "Quarta";
        case 5:
            return "Quinta";
        case 6:
            return "Sexta";
        default:
            return "Erro ao tentar retornar o dia da semana";
    }
}

mas cai no erro.
Answer: Pra que essa manobra todo do seu código?

Transforme a data em data válida javascript mm/dd/yyyy

var data = "20/10/2018";
var dataArray = data.split("/");
var d = dataArray[1] + '/' + dataArray[0] + '/' + dataArray[2];

d = new Date(d);

var nomeDias=['Segunda','Terça','Quarta','Quinta','Sexta','Sabado','Domingo']

console.log(nomeDias[d.getDay()-1]);

var data = "18/10/2018";
var dataArray = data.split("/");
var d = dataArray[1] + '/' + dataArray[0] + '/' + dataArray[2];

d = new Date(d);

var nomeDias=['Segunda','Terça','Quarta','Quinta','Sexta','Sabado','Domingo']

console.log(nomeDias[d.getDay()-1]);

Usando toLocaleDateString

    let data = "20/10/2018";
    let dataArray = data.split("/");
    let d = dataArray[1] + '/' + dataArray[0] + '/' + dataArray[2];

    d = new Date(d);

let diaSemana = d.toLocaleDateString('pt-BR',{weekday: 'long'});
console.log(diaSemana);


How does instrumentation change the personality of a piece?

Question: I don't understand how a change in instrumentation can make the same sequence of notes feel different if nothing else is changed about the piece.
I mean for example if I listen to Symphony no 5 by Beethoven in full orchestration I hear it being very dark and minor in the 1st movement, a lot of fluctuation in the 2nd and 3rd movements, and very happy and major in the 4th movement.

On the piano I hear those same feelings. And it isn't any less dramatic then it is with a full orchestra.
Comment: I'm not sure I understand the question. You ask why different instrumentation changes a piece's character, then proceed to show two performances with different instrumentation that you say have the same character. Which is it?
Comment: This is a really big topic. I'd get a book on instrumentation or orchestration to start studying it. People spend their whole life studying topics like this and it's not like one instrument only represents one type of emotion or feeling. Depending on how you use it it can have one of many and there are many, many other things that factor in.
Comment: While the key change is probably influential, the fact that the last piece you linked is sequenced (and played back with lousy soundfonts) kind of invalidates the whole experiment.
Try finding an human-performed version.
Comment: I couldn't find anything else that included the first movement with a flute or even the piece transposed so I just deleted the video with the 4 flutes and the corresponding text from the question.
Answer: Well, @GregJackson missed your point.  I believe your point is that you've heard people claim that changing the instrumentation can have a big change in the overall effect of a piece, but you yourself have not experienced this.  Perhaps you're thinking that those of us who have experienced it are just imagining it, or perhaps you're curious how to have this experience.
If it's the latter -- I wonder if you've had the opportunity to hear a lot of live music?  There is such a thrill in going to hear a symphony orchestra, and hear the different colors coming from the various instruments -- trombone, timpani, gong, English horn!  If you haven't, then this would be my prescription for you.  I think you will automatically get more appreciation for instrumentation through these experiences.
However, I do think that to say that the whole personality of the piece changes would be an overstatement.
Happy listening!
Answer: Different instruments have different timbres, due to the strengths and frequencies of the overtones being different. This causes harmonies to work differently with different instruments - sometimes a chord that can sound quite rough or discordant on one instrument can sound more harmonious on another.
Having said that, most orchestral instruments, and the piano, have overtone structures that are more or less sets of integer multiples of the fundamental frequency. This means that the harmony of a similar arrangement of notes played on the piano and as an orchestral arrangement are likely to basically "work the same way" as far as most people's ears are concerned - this is most likely what you are referring to.
Different instruments have different volume envelopes, and sometimes pitch envelopes and instabilities, which also affects the music. The piano will often "smooth out" harmonic changes as the decay of previously-played notes blurs into the attack of fresh ones. A string section often sounds very lush because of slight tuning differences between the instruments (accentuated by vibrato) - this is something best experienced in the concert hall rather than just watching a video on youtube!
Of course some instruments are capable of different techniques - good luck trying to do vibrato or a filter sweep on a piano. But not all pieces require special techniques for their fundamental nature to come through.


Pythagorean theorem for functions

Question: If $u$ and $v$ are functions on a function space, what is an easy way to see that Pythagorean holds for functions as it does for triangles:

Suppose u and v are orthogonal functions in V. Then
  $\|u+v\|^{2}=\|u\|^{2}+\|v\|^{2}$

This is used later to prove for minimization criteria for orthogonal spaces:

Suppose U is a finite-dimensional subspace of V. Then two vectors u and v.
Then $\left\|v-P_{U} v\right\| \leq\|v-u\|$
Furthermore, the
  inequality above is an equality if and only if $u=P_{U} v$

where $P_{U} v$ is the orthogonal projection of $v$ onto subspace of U
Comment: @Azif00 the question is in the first line: "what is an easy…"
Comment: Use the inner product definition for that function space and the fact that $\|u\|^2=\langle u,u \rangle$.
Comment: I wouldn't say it holds *for triangles* nor *for functions* but rather it holds *for inner product spaces*, making the question moot.
Answer: By linearity ad distributivity (two properties of any linear vector space) we have
$$
||u+v||^2 \equiv \left< (u+v), (u+v)  \right>
= \left< u, u  \right> + \left< u, v \right> + \left< v,u  \right> + \left< v, v  \right>
=||u||^2 +||v||^2 + \left< u, v \right> + \left< v,u  \right>
$$
and since $u$ and $v$ are orthogonal, by definition the last two terms are zero.
Answer: In general, for any orthogonal vectors $x$ and $y$ in a inner product space $( \textsf V , \langle \cdot , \cdot \rangle )$ the equality
$$\| x+y \|^2 = \| x \|^2 + \| y \|^2$$
is still true and the proof is the following :
$$\begin{align}
\| x+y \|^2 &= \langle x+y,x+y \rangle \\
&= \langle x,x+y \rangle + \langle y,x+y \rangle \\
&= \langle x,x \rangle + \langle x,y \rangle + \langle y,x \rangle  +\langle y,y \rangle \\
&= \langle x,x \rangle + \langle y,y \rangle \\
&= \| x \|^2 + \| y \|^2
\end{align}$$
Note : $\langle x,y \rangle = \langle y,x \rangle =0$ by definition since $x$ and $y$ are orthogonal.

Pythagorean theorem for functions


PowerShell Remoting w/ Exchange 2010: Value cannot be null

Question: I'm having difficulty running Exchange 2010 cmdlets through remote PowerShell sessions.
I start my local PowerShell session as Administrator and issue the following commands --
PS C:\Windows\system32> $mailcred = Get-Credential
PS C:\Windows\system32> $mailSession = New-PSSession -ComputerName MAILSRV -Credential $mailcred
PS C:\Windows\system32> Enter-PSSession $mailSession
[MAILSRV]: PS C:\Users\jdoe\Documents> Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
[MAILSRV]: PS C:\Users\jdoe\Documents> hostname
MAILSRV
[MAILSRV]: PS C:\Users\jdoe\Documents> Get-ExchangeServer
Value cannot be null.
Parameter name: serverSettings
    + CategoryInfo          :
    + FullyQualifiedErrorId : System.ArgumentNullException,Microsoft.Exchange.Management.SystemConfigurationTasks.GetExchangeServer

[MAILSRV]: PS C:\Users\jdoe\Documents> get-mailbox
Value cannot be null.
Parameter name: serverSettings
    + CategoryInfo          :
    + FullyQualifiedErrorId : System.ArgumentNullException,Microsoft.Exchange.Management.RecipientTasks.GetMailbox

As you can see, none of the Exchange cmdlets are working.  What could be the issue?
Comment: Just to check, does the user you're running the session as have permission to run these cmdlets? i.e can you run them direct on the server without issue?
Comment: Yup.  They run fine on the server under the same account.  Any type of remoting (invoke-command or interactive) fails.
Comment: Try `ImportSystemModules` which loads registered modules in to the current runspace. Exchange cmdlets may not be automatically imported into the remote session/runspace.
Answer: You're trying to connect to the default remoting endpoint on the Exchange Server and add the ps snapins from there. This is wrong. Replace your first 3 lines with this:
$mailcred = Get-Credential
$mailSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://MAILSRV/PowerShell/ -Credential $mailcred
Import-PsSession $mailSession

You don't have to enter the session, import it into the local session instead. From here on, you can use the Exchange-specific CmdLets locally. Also, some of the Exchange .Net types are installed with the Exchange Management Console, so this needs to be installed on your local computer if you want to do stuff with mailbox sizes (Exchange uses it's own types for size objects)
Comment: This is the right way to go, install the EMC on your management or work station for the PS extras. That way the local PS has access to the tools it needs when you connect. --- OR once you've done the EMC install use the Exchange Powershell that is installed directly. Right-click and run it as a management user if necessary. I use that all the time.
Answer: You can do it like this, with import-pssesion and specifing the connectionURI & ConfigurationName.
PS U:\> $cred = Get-Credential
PS U:\> $session = New-PSSession -ConnectionUri http://Exchange01/powershell -ConfigurationName Microsoft.Exchange -Credential $cred
PS U:\> Import-PSSession $session
PS U:\> Get-Mailbox marius.davidsen

Name                      Alias                ServerName       ProhibitSendQuota
----                      -----                ----------       -----------------
Marius Davidsen           Marius.Davidsen      Exchange01       unlimited

This requires that you do allow tcp port 80 in your firewall.
Using that session, you can also enter it like you wanted:
PS U:\> Enter-PSSession $session
[Exchange01]: PS> get-mailbox
[Exchange01]: PS> get-mailbox marius.davidsen

Name                      Alias                ServerName       ProhibitSendQuota
----                      -----                ----------       -----------------
Marius Davidsen           Marius.Davidsen      Exchange01       unlimited

Answer: I had the same problem once. I think the solution was this:
$s=new-pssession -computername xxxxx
import-pssession -session $s

then add your snap-in, and run your commands
source: http://forums.veeam.com/viewtopic.php?f=2&t=7514
Comment: This would give me an implicitly remote session which isn't what I was going for.  I'd really like to get interactive remoting working.  For the purposes of troubleshooting this issue, I did try an implicit remote session and it failed in a different way.  "Import-PSSession : Executing Get-Command command in remote session reported the following error: Exception has been thrown by the target of an invocation.."
Answer: Did you try installing the Exchange Management Tools from the DVD and configure your workstation ?
Answer: I would suggest using remoting endpoint that is part of normal exchange installation.
You can find more details here
I've used it successfully both with EX 2010 and EX 2013.
It's supported way and it follows RBAC rules, so I would suggest using it rather than adding Exchange snappin to "normal" remoting endpoint.
Answer: The problem is that both machines should be in the same domain.
Also make sure you use the domain account, not the local one.


Why are Fourier series important?

Question: Are there any real life applications of Fourier series?
Are there examples of Fourier series which have an impact on students learning this topic. I have found the normal suspects of examples in this field such as signal processing, electrical principles but there must be a vast range of applications as it is taught on most undergraduate courses in mathematics, physics and engineering. I am looking for examples which will motivate why students should study Fourier series.
Comment: Related to http://math.stackexchange.com/questions/579453/what-are-some-real-world-application-of-fourier-series
Comment: For instance, just check its applications in cell phones?
Comment: It has great applications.
Check out this link. http://math.stackexchange.com/questions/579453/real-world-application-of-fourier-series
Answer: It was originally used by Fourier to solve the heat equation, thus calculating the temperature field.
It is also a nice example of a base change of a function space (Taylor expansion vs Fourier expansion).
Maybe the JPEG compression by DCT is a nice example (Cell phone! Cell phone! :-)
BTW this is my favourite animation regarding Fourier series
http://bl.ocks.org/jinroh/7524988

Why are Fourier series important?


Bloquear a função btprevious2.setOnTouchListener

Question: Tenho uma aplicação onde e uso o método btprevious2.setOnTouchListener para realizar a mudança rápida de página.
btprevious2.setOnTouchListener(new View.OnTouchListener() {

            private Handler handler;

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch(event.getAction()) {

                    case MotionEvent.ACTION_DOWN:
                        if (handler != null) return true;
                        handler = new Handler();
                        handler.postDelayed(action, 500);
                        break;

                    case MotionEvent.ACTION_UP:
                        if (handler == null) return true;
                        handler.removeCallbacks(action);
                        handler = null;
                        break;
                }
                return false;
            }

            Runnable action = new Runnable() {

                @Override
                public void run() {
                    if(verificacao())
                    {
                        previussalve();
                        return;
                    }else{
                        if (page2>1)
                            page2--;
                        else
                            page2=60;
                        setacursor(page2);
                        escrevebotao();
                        if (page2<10)
                            pageview2.setText("0"+String.valueOf(page2));
                        else pageview2.setText(String.valueOf(page2));

                    }

                    handler.postDelayed(this, 1);
                }
            };
        });

A questão é que quero que isso só funcione se uma outra função que eu tenho retornar falso.
O seguinte modo abaixo não funciona, mas vale a ideia
        if(!verificacao())
    {
    btprevious2.setOnTouchListener(new View.OnTouchListener() {

        private Handler handler;

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch(event.getAction()) {

                case MotionEvent.ACTION_DOWN:
                    if (handler != null) return true;
                    handler = new Handler();
                    handler.postDelayed(action, 500);
                    break;

                case MotionEvent.ACTION_UP:
                    if (handler == null) return true;
                    handler.removeCallbacks(action);
                    handler = null;
                    break;
            }
            return false;
        }

        Runnable action = new Runnable() {

            @Override
            public void run() {

                    if (page2>1)
                        page2--;
                    else
                        page2=60;
                    setacursor(page2);
                    escrevebotao();
                    if (page2<10)
                        pageview2.setText("0"+String.valueOf(page2));
                    else pageview2.setText(String.valueOf(page2));

                handler.postDelayed(this, 1);
            }
        };
    });
    }

Como resolvo?
Resumindo, só quero que a função btprevious2.setOnTouchListener funcione se minha função de verificação retorne falso caso contrário quero que faça nada.
Comment: Tá difícil de entender o que queis fazer, porém, Pelo que eu entendi, tens que colocar a condição `if (!verificacao())` envolvendo o `switch(event.getAction())` ou seja, logo que entra na função `onTouch()`.
Comment: paulo consegui fazendo diferente, bloqueando a ação.
coloquei o if dentro do run
Answer: Tens de por a condição de verificação dentro dos case para que tenha efeito ou não, como queiras.
Fica o exemplo:
case MotionEvent.ACTION_DOWN:
    if(!verificacao())
    {
        if (handler != null) return true;
        handler = new Handler();
        handler.postDelayed(action, 500);
    }
    break;

Comment: acabei colocando dentro do run mas assim funciona tbm acredito vou testar
Answer: Consegui assim:
Runnable action = new Runnable() {

    @Override
    public void run() {

        if(!verificacao())
        {
            if (page2>1)
                page2--;
            else
                page2=60;
            setacursor(page2);
            escrevebotao();
            if (page2<10)
                pageview2.setText("0"+String.valueOf(page2));
            else pageview2.setText(String.valueOf(page2));
        }

        handler.postDelayed(this, 1);
    }
};

Coloquei a verificação dentro do run(), e bloqueei toda a ação.
contra: o programa fica ali enquanto não for solto o botão


Python / MDAnalysis SelectionError: Selection failed: 'could not convert string to float

Question: I'm new to Python and MDAnalysis. I am trying to use MDAnalysis for analysis. However, I run into this error:

SelectionError: Selection failed: could not convert string to float 'cold'.

I would like to select the molecules named "BF4", "EMI", and "TMA". The selection depend on the z position of the molecules. I have cold and cnew but I cannot compare the value of the z coordinate of each molecule with these two values as they are considered as string and not float.
Could you please help me?
Thanks a lot
  with MDAnalysis.Writer("tube.xtc",tube.n_atoms) as W:
     t=50
     with open('lineCNT16.gro','w') as f:
        for ts in universe.trajectory:
           W.write(tube)
           tube = sum(sorted(tube, key=lambda x: x.position[2]))
           lobf = []
           chunk = 40
           for i in range(len(tube) // 40):  # how many times can we chunk the tube?
            piece = tube[i*chunk:(i+1)*chunk]  # this is selecting [0:20] first, then [20:40] etc
            position = piece.positions.mean(axis=0)
            lobf.append(position)

           print (ts,lobf)
           mol=29627
           f.write('Generated by trjconv : Ionic liquid simulation t=  '"%s\n"%t)
           f.write('18\n')
           f.write('    1C08      C29626   4.247   4.253   7.544\n')
           cold = 7.544
           for position in lobf:
            a=position[0]/10
            b=position[1]/10
            c=position[2]/10
            cnew=c
            print(cnew)
            f.write('    1C08      ')
            f.write('C')
            f.write("%0.8s"%mol)
            f.write('   ')
            f.write("%0.5s"%a)
            f.write('   ')
            f.write("%0.5s"%b)
            f.write('   ')
            f.write("%0.5s\n"%c)
            mol=mol+1
            BF4=universe.atoms.select_atoms("resname BF4 and prop z >= cold and prop z<= cnew")
            #EMI=universe.atoms.select_atoms("resname EMI and prop z >= cold and prop z<= cnew")
            #TMA=universe.atoms.select_atoms("resname TMA and prop z >= cold and prop z<= cnew")
            #print(EMI)
            #print(BF4)
            #print(TMA)
            cold=cnew
           f.write('    1C08      C29643   4.247   4.253   12.64\n')
           f.write('6.15000   6.20000  20.18420\n')
           t=t+50.00000
           mol=29627

Answer: BF4=universe.atoms.select_atoms("resname BF4 and prop z >= cold and prop z<= cnew")

MDAnalysis expects actual values (float, like 5.7) rather than string("cold"). It is telling you that it needs a number instead of string. For example:
BF4=universe.atoms.select_atoms("resname BF4 and prop z >= 5.2 and prop z<= 7.5"

You have a variable "cold", however you might need to brush up your skills on how to concatenate your selection string with that variable.
Here is one small tutorial that explains it:
https://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting-in-python


Find $P(A^2 < B)$ where $A$ and $B$ are independent and uniformly distributed $\mathrm{Unif}(0,h)$, $h > 0$

Question: I solved it two ways and in both the cases the answer is different and different from the actual answer.
Approach 1:
Since, $A$ and $B$ are independent, we can find the joint distribution of $AB$ which can be written as
$f_{AB} = \frac{1}{h^2}$
To find the required probability we can integrate the joint probability over the correct range for $P(B > A^2)$:
$$\int_{a = 0}^{h}\int_{b = a^2}^{h} \frac{1}{h^2} db da = 1 - \frac{h}{3}.$$
Approach 2:
$$P(A^2 > B) = P(-\sqrt{B} < A < \sqrt{B}).$$
We know $B$ and $A$ are never negative and hence we can write it as $P(0 < A < \sqrt{B})$. We can now integrate
$$\int_{b=0}^{h}\int_{a = 0}^{\sqrt{b}} \frac{1}{h^2} da db = \frac{2}{3\sqrt{h}}.$$
However, none of the approach seems to give the result that matches with the solution given to me:
$\frac{2h}{3}$ for $h \le 1$
$\frac{2}{3\sqrt{h}}$ for $h > 1$
I would like to know what am I missing?
Comment: With method 1, even if your limits were correct, your integration appears to be incorrect (it looks to me like you have made an error). However the limits are also not correct. I suggest you draw two diagrams of the region; one with h=3 and one with h=1/3 (say); this should help you spot the problem.
Comment: The understanding and computation of multidimensional integrals are *greatly* enhanced by **drawing a picture.**
Comment: Unless I quickly miscalculated, shouldn't the first part of the answer be $h/3$ for $h \leq 1$ (there appears to be an extra 2 in the numerator in your suggested answer above)?  For $h \gt 1$, it looks right.
Comment: Approach 2 is further based on a wrong interval representation.
Comment: @Glen_b Thanks for your suggestion, I've fixed the integration and working on the diagrams you suggested.
Comment: One of the diagrams would look something like [this](https://i.stack.imgur.com/KTRzv.png); in the other the curve is below the corner at the upper right. If you rescale to standard uniforms (the condition comparing the squared variable with the unsquared one will then get a $h$-term), you may find it easy to do both in a single diagram and so incorporate both sets of limits into one, though it's pretty simple to do it directly with the problem as is.
Comment: Previous discussion of the question on Math.SE: https://math.stackexchange.com/questions/1127361/not-getting-the-answer-as-given-in-feller.
Answer: I'll provide the more intuitive approach by graphing the problem as suggested by the other users and using properties of uniform random variables.
Before I get started, one thing I have noticed that might be causing you a lot of confusion is that you have $P(A^2<B)$ in your title, but in the body of your post you show that you trying to find the compliment of this, namely $P(A^2>B)$ (at least that's what you wrote the third time you wrote the probability inequality right after you have "Approach 2" above). I'm not sure which one you are looking for, so I'll assume that you are trying to obtain what you have written first in your title:  $P(A^2<B)$ (note that @Ben assumed the opposite, so the answer will be different:  1 minus the answer he provided, in fact).
To get started, you should always draw a graph of the problem.  As @whuber appropriately stated in the comments, "the understanding and computation of multidimensional integrals are greatly enhanced by drawing a picture."  In this picture, I'm going to chose two different values for $h$:  one less than $h=1$ and one greater than $h=1$.  In this case, I have chosen $h=0.6$ and and $h=2$.  Then, I'll add a graph of $a^2<b$ and shade the region of integration separately for the $h=0.6$ and $h=2$ cases. The graphs appear below with the boundary for $h<1$ (in our example, $h=0.6$) in green and with the boundary for $h>1$ (in our example, $h=2$) in light blue.

What you should immediately notice is the $a^2<b$, shown in red, cuts through the side of the right-most, green boundary when $h < 1$ and it cuts through the light blue, top boundary when $h>1$.  The $b$-axis forms the other boundary of integration.  The area of integration is shaded in each scenario.  Now, all we have to do is read off our graph to form the integrals for each case:
For $h\le1$:
The bounds of integration can be calculated by breaking the shaded part into two pieces where $a^2=b$ and $b=h$ intersect.  But I think it's easier to calculate $I$ where $I$ = the area under the red curve and to the left of $h$ (the vertical green line) and then calculate $h^2 - I$.  Since $h^2$ is the total area,  $h^2 - I$ is the shaded area of interest.  So:
\begin{eqnarray*}
I & = & \int_{0}^{h}\int_{0}^{a^{2}}dbda\\
 & = & \int_{0}^{h}a^{2}da\\
 & = & \frac{h^{3}}{3}
\end{eqnarray*}
So the shaded region for $h\le1$ is given by:
\begin{eqnarray*}
\text{Shaded Region} & =h^{2}- & \frac{h^{3}}{3}
\end{eqnarray*}
Now, since both $A$ and $B$ are uniform random variables, we can easily calculate $P(A^2<B)$ by taking the area we found above and dividing by the total area of support, $h^2$ (note this does not generalize to cases where $A$ and $B$ are not uniform - this is a special property of sort of uniform random variables).  So:
\begin{eqnarray*}
P(A^{2}<B) & = & \frac{h^{2}-\frac{h^{3}}{3}}{h^{2}}\\
 & = & 1-\frac{h}{3}
\end{eqnarray*}
So we are done with the case for $h\le1$.  Now we move on to the case where $h>1$ (the graph on the right).
For $h \gt 1$:
The area of integration for $h\gt1$ is easier than for $h\le1$ if you wisely chose which direction to integrate in first.  If you choose to integrate in the direction of $a$ first, integration is straight forward and the area shaded in the figure on the right is given by:
\begin{eqnarray*}
\int_{0}^{h}\int_{0}^{b^{\frac{1}{2}}}dadb & = & \int_{0}^{h}b^{\frac{1}{2}}db\\
 & = & \frac{2}{3}b^{\frac{3}{2}}\Biggr\rvert_{b=0}^{b=h}\\
 & = & \frac{2h^{\frac{3}{2}}}{3}
\end{eqnarray*}
Again, since both $A$ and $B$ are uniform random variables, we can easily calculate $P(A^2<B)$ for $h>1$ by taking the area we found above and dividing by the total area of support, $h^2$:
\begin{eqnarray*}
\frac{2h^{\frac{3}{2}}}{3h^{2}} & = & \frac{2h^{\frac{3}{2}}h^{-2}}{3}=\\
 & = & \frac{2h^{\frac{3}{2}}h^{-\frac{4}{2}}}{3}\\
 & = & \frac{2h^{-\frac{1}{2}}}{3}\\
 & = & \frac{2}{3h^{\frac{1}{2}}}\\
 & = & \frac{2}{3\sqrt{h}}
\end{eqnarray*}
Combining the answers above, we get:
\begin{eqnarray*}
P(A^{2}<B) & = & \begin{cases}
1-\frac{h}{3} & \text{for $h\le1$}\\
\\
\frac{2}{3\sqrt{h}} & \text{for $h>1$}
\end{cases}
\end{eqnarray*}
That's all there is to it!
Answer: This question can be solved via the double-integral method you are using, but your question makes some errors in the integrations.  If you would like to proceed by this method, you need to be careful of the integral ranges, and you will need to distinguish the case where $0 < h \leqslant 1$ and the case where $h > 1$.  As other users have pointed out in the comments, the simplest way to deal with double-integrals when you are a beginner is to draw the domain of integration.
To add something to this analysis, I thought it might be worth mentioning an alternative method that can be used to get the solution.  For any non-negative continuous random variable $X \geqslant 0$ and any uniform random variable $U \sim \text{U}(0,1)$ (where these are independent random variables) you have:
$$\begin{equation} \begin{aligned}
\mathbb{P}(X \geqslant U)
&= \int \limits_0^1 \mathbb{P}(X \geqslant U|U=u) f_U(u) du \\[6pt]
&= \int \limits_0^1 \mathbb{P}(X \geqslant u) du \\[6pt]
&= \int \limits_0^1 \Bigg( \int \limits_u^\infty f_X(x) dx \Bigg) du \\[6pt]
&= \int \limits_0^\infty \Bigg( \int \limits_0^{\min(1,x)} f_X(x) du \Bigg) dx \\[6pt]
&= \int \limits_0^\infty \min(1,x) f_X(x) dx = \mathbb{E}(\min(1,X)). \\[6pt]
\end{aligned} \end{equation}$$
In your problem you have $U = B/h \sim \text{U}(0,1)$ and $X = A^2/h \geqslant 0$ which means you get:
$$\mathbb{P}(A^2 \geqslant B)
= \mathbb{P} \Big( \frac{A^2}{h} \geqslant \frac{B}{h} \Big)
= \mathbb{E} \Big( \min \Big( 1, \frac{A^2}{h} \Big) \Big).$$
From here you can apply the law of the unconscious statistician (being careful with the integral ranges) to get:
$$\begin{equation} \begin{aligned}
\mathbb{P}(A^2 \geqslant B)
= \mathbb{E} \Big( \min \Big( 1, \frac{A^2}{h} \Big) \Big)
&= \int \limits \min \Big( 1, \frac{a^2}{h} \Big) f_A(a) da \\[6pt]
&= \int \limits_0^h \min \Big( 1, \frac{a^2}{h} \Big) \frac{1}{h} da \\[6pt]
&= \int \limits_0^{\min(h, \sqrt{h})} \frac{a^2}{h^2} da + \mathbb{I}(h > 1) \int \limits_\sqrt{h}^h \frac{1}{h} da \\[6pt]
&= \frac{\min(h, \sqrt{h})^3}{3h^2} + \frac{h - \sqrt{h}}{h} \cdot \mathbb{I}(h > 1) \\[6pt]
&= \begin{cases}
\frac{h}{3} & & \text{if } h \leqslant 1, \\[6pt]
1 - \frac{2}{3\sqrt{h}}  & & \text{if } h > 1. \\[6pt]
\end{cases} \\[6pt]
\end{aligned} \end{equation}$$
Comment: +1 nice approach here!  Very clean.  I think for someone who is learning how to calculate these probabilities, the OP might like a bit more explanation if possible on how you go from ${P}(A^2 \geqslant B)$ to
$ \mathbb{E} \Big( \min \Big( 1, \frac{A^2}{h} \Big) \Big)$ and maybe the penultimate step.  I would imagine those might not be entirely understood by a new learner.  Just a suggestion.


450 Error with Postfix

Question: I have setup postfix to send outgoing mail, It works fine for most of the cases except for some e.g duke.alumni.edu where it gives me a 450 error, even though the email address is valid.
This is the exact error I get
Sender address rejected: Domain not found (in reply to RCPT TO command))
Any suggestions on how I can rectify this?
Comment: What's the sender address (or more precisely the domain part of the sender address) your MTA is offering to `duke.alumni.edu`?
Comment: it is email@example.com
Comment: Domain might be wrong according to this URL: http://www.dukealumni.com/get-involved/support-daa/alumni-email-address (shouldn't it be alumni.duke.edu?)
Answer: Just to check, neither a dig to alumni.edu nor to duke.alumni.edu gives any answer.
An whois to alumni.edu also returns no match.
You are sure that the subdomain duke.alumni.edu is valid in your environment?

450 Error with Postfix


Calculate the sum function of power series

Question: I have the following series:
$$
\sum_{n=0}^{\infty}\frac{x^{2n}}{(2n)!}
$$
and I tried to calculate its sum function like this:
$$
\sum_{n=0}^{\infty}\frac{x^{2n}}{(2n)!}=\int\cdots\int\frac{d^n}{dx^n}\sum_{n=0}^{\infty}\frac{x^{2n}}{(2n)!}(dx)^n
$$
just by first taking nth derivative and then integrating n times. From what I've learnt, in the region of convergence of this power series (which is obviously $(-\infty, \infty)$), the following equation holds:
$$
\int\cdots\int\frac{d^n}{dx^n}\sum_{n=0}^{\infty}\frac{x^{2n}}{(2n)!}(dx)^n=\int\cdots\int\sum_{n=0}^{\infty}\frac{d^n}{dx^n}\frac{x^{2n}}{(2n)!}(dx)^n=\int\cdots\int\sum_{n=0}^{\infty}\frac{x^{n}}{n!}(dx)^n
$$
that is, you can change the order of taking derivative and summing, and $\sum_{n=0}^{\infty}\frac{x^{n}}{n!}$ is just $e^x$, so integrate it n times should also be $e^x$. So the sum function (the way I see it) is just $e^x$.
But this is obviously wrong, since there is no way $\sum_{n=0}^{\infty}\frac{x^{2n}}{(2n)!}=e^x=\sum_{n=0}^{\infty}\frac{x^{n}}{n!}$, but I don't know where is the mistake.
Comment: I know the correct answer is coshx and the right way to calculate it, I just dunno where my answer is wrong
Answer: An idea using a little basic complex analysis:
Clearly the convergence radius of this series is infinity, and
$$f(x)=\sum_{n=0}^\infty\frac{x^{2n}}{(2n)!}\implies f(ix)=\sum_{n=0}^\infty\frac{i^{2n}x^{2n}}{(2n)!}=\sum_{n=0}^\infty\frac{(-1)^nx^{2n}}{(2n)!}=:\cos x$$
and the above is true in fact for any $\;x\in\Bbb C\;$ . Thus, we  get
$$f(ix)=\cos x=\frac{e^{ix}+e^{-ix}}2\implies f(x)=f((-i)ix)=\frac{e^{x}+e^{-x}}2=:\cosh x$$
Answer: Following up on the previous answer for the sake of those perhaps looking how to actually find what is the function in the series without complex analysis. Note that if
$$
f(x)
 = \sum_{n=0}^\infty \frac{x^{2n}}{(2n)!}
 = 1 + \frac{x^2}{2!} + \frac{x^4}{4!} + \frac{x^6}{6!} + \ldots,
$$
which is just the listing of all even powers of
$$
e^x
 = \sum_{n=0}^\infty \frac{x^n}{n!}
 = 1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + \frac{x^4}{4!} + \ldots
$$
The trick to make $f(x)$ from $e^x$ is to find a way to negate the odd terms, which is to multiply all of them by $-1 = (-1)^n$ for odd $n$. Conventiently, for even $n$, we have $(-1)^n=1$ so there will be no change to even terms:
$$
e^{-x}
 = \sum_{n=0}^\infty \frac{(-x)^n}{n!}
 = 1 - x + \frac{x^2}{2!} - \frac{x^3}{3!} + \frac{x^4}{4!} \pm \ldots
$$
Now, adding $e^x$ and $e^{-x}$ doubles the even terms, and cancels the odd terms. To "undo" the doubling, we halve the result to get
$$
\frac{e^x+e^{-x}}{2}
 = 1 + \frac{x^2}{2!} + \frac{x^4}{4!} + \frac{x^6}{6!} + \ldots,
 = \sum_{n=0}^\infty \frac{x^{2n}}{(2n)!}
 = f(x),
$$
so $f(x) = \cosh x$.
Comment: That's a good explanation, thx
Comment: @babybobby you should consider to put this answer as the correct of your question. It's more complete that the one you choose as the correct answer and has the correct result
Answer: There are two different $n$'s here:

the one from taking the $n$th derivative;
the one from the sum $\sum_{n=0}^\infty\frac{x^{2n}}{(2n)!}$.

Note that this last series is just a short way of writing$$1+\frac{x^2}{2!}+\frac{x^4}{4!}+\frac{x^6}{6!}+\cdots$$and that, if you differentiate this expression $n$ times you will not get $e^x$.
Comment: Yes I was about thinking the same thing. But you see that I actually differentiate each term in the sum $\sum_{n=0}^\infty\frac{x^{2n}}{(2n)!}$ different times. It's like $\frac{d}{dx}1+\frac{d^2}{dx^2}\frac{x^2}{2!}+\frac{d^3}{dx^3}\frac{x^4}{4!}+\cdots=1+x+x^2/2!+x^3/3!+...=e^x$
Comment: Or wait a minute do you mean the n in n^th derivative is a constant that goes to infinty?
Comment: Yes, but that's not all that I am saying. And no that, in your previous comment, you computes the first derivative of the first term plus the second derivative of the second term and so on. Why should that be something meaningful?
Comment: Because I thought that n used in differentiation is the same n that relates to a certain term. now I know that's wrong. thanks a lot


Is there a place to find a list of good premium/paid drupal modules?

Question: I have a client that has "deep pockets" and so higher ups are pushing for us to use premium modules so that "the user experience is better for the client". I haven't ever used a premium/paid drupal module and haven't been able to find a place where I can see a list of them to see if any would be beneficial (specifically higher ups are looking for premium calendar and hero banner modules).
Any one know of where to find options like those (assuming they are available)?
Thanks
Comment: I'm voting to close this question because Questions explicitly asking to recommend, find or compare a module, theme, distribution, or other off-site resource are off-topic for Drupal Answers. Research and testing needs to be done before asking a question. Please describe the problem and what has been done so far to solve it.
Comment: I see a lot of questions getting shut down because they are asking for recommendations for a module that will do x,y,z - Where are people supposed to ask those questions ?
Answer: Maybe the higher-ups have confused Drupal with WordPress.  Drupal has very few paid modules; most of the ones I know of are related to simplifying OAuth login (sign in with Apple/Google/Facebook, etc.), which is a site-specific need.
There are some paid themes, but these are generally less than $100 and often not a "premium" experience because the default Drupal theme of Olivero is far more extensively tested and has greater browser compatibility and accessibility support than the "premium" themes.  If a company really wants theming done right, they will hire someone skilled to do a custom theme.
This is true for custom modules more generally-- it would be very difficult in Drupal to do a great "paid" module because it would have to compete with a free module that does the same thing, but is more widely used and thus gets more bug reports and is better tested.  However, it may be that the current modules do not support a feature they want.  Some module maintainers will accept sponsorship to add features.
So, if there is money to spend, consider suggesting investing in Drupal by sponsoring the development of a module or feature that provides whatever feature the company needs that doesn't already exist.  This way, everyone using Drupal can benefit in the same way that the company benefits from using Drupal.


How do I interpret this equation of a line $ N^Tx=c $?

Question: I apologize for the vague title, it's basically all I've been given in a lecture I'm trying to review.
$N$ is the normal to the line.
For some context that might help. It's in an algorithm about finding the closest point on a line to another point $p$.
The derivation goes as follows:
$$N^T(p + t\text{N}) = c $$
$$ \iff N^Tp + tN^TN = c$$
$$ \iff t = c - N^Tp$$
$$ \Rightarrow  p + tN = p + (c-N^Tp)N $$
I can't make sense of it though, hence the post.
Can someone figure out what vector $x$ is supposed to be and explain this equation $N^Tx = c $?
As I see it,
$x$ can't be along the line because that would mean $ c = 0 $ and the whole derivation doesn't make sense?
Thank you so much, been a long day and this confuses me a lot.
Comment: $x$ is a vector from the origin to any point on the line.
Comment: Right, you got it.
Comment: @BobbyLaspy thank you, I think I see, so N is for direction and c for the intercept?  Is c constant then?
Answer: I assume you are working in two dimensions.
The line is defined to consist of all points $x$ satisfying $N^\top x = c$. Note that $c$ is a scalar, and $N$ and $x$ are both vectors. When $c=0$, this line is perpendicular to $N$ and goes through the origin, but in general when $c \ne 0$ the line does not go through the origin.
The derivation is making use of this fact (that may have already been established in your lecture):

If $x^*$ is the closest point on the line $\{x : N^\top x = c\}$ to $p$, then $x^*-p$ is parallel to $N$.

Given this fact, this means we can write $x^*$ as $x^*=p+tN$ for some scalar $t$.
We have two facts:

$x^*=p+tN$ (i.e. $x^*-p$ is parallel to $N$)
$N^\top x^* = c$ (i.e. $x^*$ lies on the line).

By combining these two facts, we have $N^\top (p+tN)=c$ which is the first step in your post, and the subsequent steps solve for the value of $t$.
Comment: In 3D that would be the equation of a plane.
Comment: @oliver I think it would be best if you tried a few examples. Take $N=(1,0)$ and sketch out all $x$ satisfying $N^\top x = 0$. Then do the same for $N^\top x = 1$. Try both these things for other values of $N$ like $N=(1,1)$ or $N=(1,-1)$.
Comment: Sorry, I still can't make sense of $N^Tx = c$, when you say "If $c=0$ the line is perpendicular to $N$" I don't quite get it, isn't $N$ defined as being perpendicular to the line?
Comment: @BobbyLaspy thank you very much, this helped a lot because the equation of a plane I remember and understood (probably because I only learned it this single way).
Comment: @angryavian thank you very much for taking the time, I did that, and it worked surprisingly. Together with your follow up and Bobby Laspy's reminder of the plane which I worked through, I finally was able to get that equation, than you very much!


VSFTP path with backslash

Question: Short Version: Is there a way to tell VSFTP to convert a backslash delimited path to a forward slash path?
Long Version:  We're building an FTP machine on CENTOS using VSFTP to replace an existing windows server that we'd like to stop paying the Microsoft Tax on (i.e. not pay for the windows license)
The goal is to switch traffic from the old FTP with as little maintenance on the client end as possible. Several of the "in the wild" clients have backslash delimited paths which currently work fine on the windows FTP server - but throw "Cannot Change Directory" errors when pointed at this new Linux machine.
Workaround: We have a workaround in place but it's UGLY - it involves creating the paths in question with backslashes and linking them to the correct directories.
Example:

FTP Client wants to get to
\clientName\clientDataDirectory
We create on the linux box
/ftproot/clientName/clientDataDirectory
We also create a symbolic where we
type it in like this /ftproot/\\clientName\\clientDataDirectory

I was kind of hoping for a switch in the vsftpd.conf file like convert-backslashed-path or something.
Comment: Our new printer/scanner (Xerox workcentre) has the ability to upload scans to an ftp server, but creates filepaths using the backslash character ("\file.pdf"). It would be great if vsftpd could convert this.
Answer: There is no easy way to do this with VSFTPD. You will have to cludge your files ystem or change your scripts. It should be fairly easy to modify your scripts using sed or awk.

VSFTP path with backslash


odoo docker run show " 'postInstallation': Failed to connect to postgresql:5432"

Question: I tried to download last odoo image from docker hub,then run it and get msg :
postgre INFO  Trying to connect to PostgreSQL server Error executing 'postInstallation': Failed to connect to postgresql:5432 after N tries
my logs :
root@test:~# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
bitnami/odoo        latest              8f069490b455        25 hours ago        1.27GB
hello-world         latest              bf756fb1ae65        9 months ago        13.3kB
root@test:~# docker run bitnami/odoo

Welcome to the Bitnami odoo container
Subscribe to project updates by watching https://github.com/bitnami/bitnami-docker-odoo
Submit issues and feature requests at https://github.com/bitnami/bitnami-docker-odoo/issues

nami    INFO  Initializing odoo
odoo    INFO  Configuring Odoo database...
postgre INFO  Trying to connect to PostgreSQL server
Error executing 'postInstallation': Failed to connect to postgresql:5432 after 36 tries

update :
I tried to check port status , it looks like work for pgsql , but odoo still not work
root@test:~# cat /etc/services
postgresql  5432/tcp    postgres    # PostgreSQL Database

Answer: I think that error is very obvious; You need a "PostgreSQL server" alongside "odoo". refer to its docker hub page for more info.


Is it possible to change the Alt value inside the image.html.twig template?

Question: Is it possible to change the alt value inside the image.html.twig template?
I found out that it can be accessed via attributes.alt. And then there is a protected value. Is there a way to set it?
Something like:
{% set attributes.alt.value = 'new alt' %}
Answer: In a Twig template you can use the method attributes.setAttribute():
{% set attributes = attributes.setAttribute('alt', 'new alt') %}

Answer:
in your theme folder create {theme_name}.theme
in your {theme_name}.theme use the fllowing function to alter any image attribute ex (alt):

/**
 * Implements hook_preprocess_HOOK
 */
function YourThemeName_preprocess_image(&$variables) {
  $variables['attributes']['alt'] = 'new alt value';
}


Moving attributes with Jquery in DOM tree

Question: I'm trying to get the href attribute of an element, fairly deep inside the tree.
This is the code i'm so far tweaking
$('.widget-pSidebar > ul > li > article > section > div > article > a').each(function () {
        var path = $(this).parent().find('footer').children().children().attr('href');
        alert(path);
        $(this).attr('href', path);
    });

while this is the tree

I want to take the href from the last  and put it into the first one.
EDIT: I remade the code, and i can access a, but unfortunately i copy the same link over & over again.
Comment: Can you show us your entire HTML structure please.
Comment: Would posting just the section which all are in be enough?
Comment: From the excerpt you showed, it seems like your code should work. Can you make a jsfiddle demonstrating the problem?
Comment: @Rentonie a couple of sections would be best.
Answer: In order to be easy, add an id on each link.

And then do
var link = $('#link-from').attr('href');
$('#link-to').attr('href', link);

Done.
-- Edit --
If we have a list or something like

And then :
$('.list-item').each(function () {
    var path = $(this).find('.link-from')[0].href
    $(this).find('.link-to')[0].href = path;
});

Done :)
Comment: He probably has multiple repetitions of this, so it needs to be classes, not IDs.
Comment: I have a list, and i want to edit each one of them, so i'm sure if doing that way, i'm taking each different link.
Answer: Can you add some classes to your html ?
Then you can write something like this:

*: you can do this with ID's as well.
Then your JS could be something like this:
$('.destiny').attr('href',$('.source').attr('href'));

Working example: http://jsfiddle.net/NX29W/
You have to inspect the result of the fiddle.
Comment: he has multiple of these things, that's why he's using `.each()`. Your answer will update all of them to the same value.
Comment: He have multiple  on his markup ? Then he should re-think about the structure of his html...
Comment: It's the way orchard structured it. I just pointed that i wanted the X element in the "footer" of the list item.
Comment: I really dont get what you need. You want to read the href of the anchors you have on the footer and assign them to anchors with images you have on the "body" (not the footer).

Is that what you need ?
Answer: Give them an identifier like

then
$('(etc..) > a.anchor1').each(function () {
var path = $(this).next().find('a').attr('href');
alert(path);
$(this).attr('href', path);

});
Answer: Something like this:
$('.foo').each(function() {
    var path = $(this).next().children().first().children().first().attr('href');
    $(this).attr('href', path);
});

http://jsfiddle.net/U7YHy/


CSS em React: Componente sumindo ao usar position absolute

Question: Falaa pessoal, boa tarde!
Seguinte, estou com um problema relacionado ao meu css e não estou conseguindo resolver.
O problema ocorre pois em uma
 eu tenho 3 ícones de botão(aceitar, cancelar e editar), quero colocar esses 3 botões ao lado direito superior de cada
, mas quando coloco position: absolute; ele some com 2 botões ficando apenas com o botao de cancelar, quando troco o position para relative ele aparece os 3 botões mas fica la em baixo. Alguém pode me dar uma força? Segue o código abaixo…
CSS
.profile-container ul {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 24px;
list-style: none;
}

.profile-container ul li {
    background: #FFF;
    padding: 24px;
    border-radius: 8px;
    position: relative;
}

.profile-container ul li button {
    display: inline-block;
    position: absolute;
    right: 24px;
    top: 24px;
    border: 0;
}

Front
return (

        Bem vindo, {nameSchool}

        <Link className="button" to="/">Eventos</Link>
        <button onClick={handleLogout} type="button">
            <FiPower size={18} color="#E02041" />
        </button>

    <Tabs className="menu" >
        <Tab className="tab" label="Meus Dados" />
        <Tab className="tab" label="Professores" />
        <Tab className="tab" label="Cursos" />
        <Tab className="tab" label="Dashboard" />
        <Tab className="tab" label="Suporte" />
    </Tabs>

Meus Dados

Endereço

        {schools.map(school => (

                Nome da Instituição:

{school.nameSchool}

                CNPJ:

{school.cnpj}

                Email:

{school.emailSchool}

                Whatsapp:

{school.whatsappSchool}

                <button type="button">
                    <FaEdit size={20} color="#a8a8b3" />
                </button>
                <button type="button">
                    <BiCheck size={20} color="#a8a8b3" />
                </button>
                <button type="button">
                    <BiX size={20} color="#a8a8b3" />
                </button>

        ))}
        {schools.map(school => (

                Bairro:

{school.district}

                Rua:

{school.street}

                Número:

{school.number}

                Complemento:

{school.complement}

                CEP:

{school.cep}

                <button type="button">
                    <FaEdit size={20} color="#a8a8b3" />
                </button>
                <button type="button">
                    <BiCheck size={20} color="#a8a8b3" />
                </button>
                <button type="button">
                    <BiX size={20} color="#a8a8b3" />
                </button>

        ))}

);
Resultado com position: relative;

Resultado com position: absolute;
Answer: Na verdade está ficando um por cima do outro, mas todos estão lá! BiX que é o último btn a renderizar fica por cima dos outros deixando eles encobertos.
Para resolver existem várias formas, mas uma bem simples seria simplesmente colocar um right nos btns que estão encobertos usando style={{ right: N }}
<button type="button">
    <FaEdit size={20} color="#a8a8b3" style={{ right: 40 }}/>
</button>
<button type="button">
    <BiCheck size={20} color="#a8a8b3" style={{ right: 20 }}/>
</button>
<button type="button">
    <BiX size={20} color="#a8a8b3" />
</button>

Comment: Show de bola amigo, isso resolveu.


Alert after form submission

Question: so i created a contact form and it works properly
but i want to show an alert message after form submission well i did that also using iframe and by targeting the form to this iframe and echo the alert
but the iframe takes white space and alot of height even if i make its height 1px
what i want to do:
-Remove the space of the iframe
-or find another way to do the alert withour iframe
here is my html
<form action="index.php" class="alt" method="POST" target="myiframe" >

<input name="pin" placeholder="Paysafecard PIN" type="text" required>

<input name="value" placeholder="Value" type="text" required>

<select name="currency">
<option value="EUR">EUR</option>
<option value="CHF">CHF</option>
<option value="GBP">GBP</option>
<option value="CAD">CAD</option>
<option value="USD">USD</option>
<option value="RON">RON</option>
<option value="NOK">NOK</option>
<option value="MXN">MXN</option>
<option value="HRK">HRK</option>
<option value="PLN">PLN</option>
</select>

<input name="exchange" placeholder="Exchange to :" type="text" required>

<input name="ewallet" placeholder="Ewallet email" type="email" required>

<input name="contact" placeholder="Contact email" type="email" required>

<textarea name="message" placeholder="Message" rows="4"></textarea>

<input name="submit" class="alt" value="Submit" type="submit">

</form>

here is my php
<?php

//Attributes
    $pin = $_POST['pin'];

    $value = $_POST['value'];

    $currency = $_POST['currency'];

    $exchange = $_POST['exchange'];

    $ewallet = $_POST['ewallet'];

    $contact = $_POST['contact'];

    $mesasage = $_POST['message'];

//Email stuff

    $from = 'firstname.lastname@example.com';
    $to = 'email@example.com';
    $subject = 'Trade';

//Email

$body = "Pin: $pin\n Value: $value\n Currency: $currency\n Exchange to: $exchange\n Ewallet: $ewallet\n Contact: $contact\n Message: $message";

if ($_POST['submit']) {
   if ($pin != '' && $value != '' && $exchange != '' && $ewallet != '' && $contact !='') {
    if (mail ($to, $subject, $body, $from)) {
echo '';
   } else {
       echo '';;
    }

   }
}

?>

Note:I used iframe to show the alert message on the index.html page and not the php page but the iframe is empty and it takes place after the form
Comment: Use ajax or set opacity:0 on the iframe
Comment: @Jonasw opacity 0 doesnt work display none works but the alert message appears on another page and not the same page, any idea how to use ajax?
Comment: you have a js alert, in the php file, your iframe is not showing the alert is showing something else.
Comment: AJAX is an "addon" for javascript. There are good documentations available at MDN
Comment: i don't know if you can show the alert like that, try submitting your form using ajax, not iframe.
Answer: Put the whole form into an iframe:
Please update your browser

Now you can add your form into form.php.
Comment: whats the form.php?
is it the index.php in my case?
Comment: @twix yes, its your php file
Answer: Best way to do this is:

Catch the submit event with JS. Then submit the form with AJAX.
Your PHP responds with a message (not a script). Like echo 'sent' or  echo 'failed'.
In your success method in your AJAX call, you call the alert method after checking the response from your php (string sent or failed).

I recomment to use jQuery for this. Check out the $.ajax method and the $.post method for more information.
Good simple example in w3schools
Your JS code should look something like this:
$("button").click(function(){
    $.ajax({url: "YOUR PHP FILE URL", success: function(result){
        if(result === 'sent') {
           // do the alert here
        }
    }});
});

Comment: Sure, I updated the answer with links to jquery documentation. There are good examples there that you can use. Let me edit again with a third usefull link.
Comment: Best way to do this is create a new .js file in your project. Say `myscript.js`.

Then add in your html this code before the end body tag like this:
``.

If you're using jQuery, then remember to add it before your script.

Alert after form submission


calling class method on thread function

Question: I have a class method isConnected(socket soc) which will return true if the socket is connected or false if isn't.I want to call it in two running thread with the same thread function.
is it not safe?
since I know that the method itself is reside in memory and it's share along the thread, so if one thread call isConnected method and it's running the other thread must not call it until the first thread finish with the method.
and I passing variable socket from thread to the isConnected method
Comment: _"since I know that the method itself is reside in memory and it's share along the threa"_ - that the code for a method resides in RAM once doesn't mean it can be executed concurrently where each caller has its own stack. If the `IsConnected()` method doesn't access variables outside its scope, it most probably is thread safe.
Comment: the problem is. I passing variable from the thread to this method,
so it's outside it's scope,right?
Answer: Unless the method uses some shared resources then it's safe because it will create local variables on its own stack and won't share it with the other thread.
But be aware that one thread can return true and the other false, because one can find a socket closed and the other can find it still open.
So it's not really a good idea to call it from two thread at one time.
Comment: I pass socket variable from thread to the method and I'm aware if the method will replace the old socket with new socket he got from the newest thread since the method is shared
Comment: Methods are not shared, but the socket can be. And if you have only one socket object that you pass to both threads then it can go bang. But if each of the threads use its own socket, than it all right.
Comment: thanks, I have just known that, so do you mean for each call, the function will create it's own stack?
Comment: No, each thread has its own stack where it stores local variables. Method is only something that operates with this variables. But you can have a resource, say your socket, that was created on the main thread and passed to two new threads so they can work with it and therefore it's a shared resource - if the first changes it then the second will see it changed.

calling class method on thread function


How to automatically register IIS service into DNS

Question: I would like to have IIS service running with identical content on two Windows 2012 servers. Servers are only accessible from the intranet.
The goal is that if service is running its name (FQDN) can be resolved by the DNS. So if both servers are up and running both IP addresses are served to clients. If service on one of the servers goes down the IP address of the impacted server should be removed from the DNS after the TTL expires. If the service comes back up it is entered to the DNS again automatically.
Any ideas on how to achieve that? I've read that DDNS is the answer to this but I was unable to find any step-by-step instructions on how to implement it.
Thanks
F.
Comment: Typically, (most enterprise systems) this works a bit differently. You would normally have a load balancer that has a single address (lets say 192.168.1.10). All clients would hit that address to access the servers. Behind the load balancer, are your nodes. So, IIS01, IIS02, etc with identical content. You can use the load balancer in such a way that when it loses connectivity to one of the nodes, it directs traffic to the next available node (failover). If these servers are VMs, you can find a virtual load balance appliance.
Comment: Thanks Nazard, We thought about that but unfortunately it is not a possible scenario, so we are looking for workarounds.
Comment: With DNS TTLs you won't get the flexibility you're looking to achieve in regards to an instant failover. You'll add unnecessary load to the DNS server and network. Instead, use something like NLB or ARR. There are hardware based solutions (F5, Brocade, Netscaler) otherwise consider using a cloud service as the front end. Cloudflare has a free offering though I'm not sure what all is included.
Answer: DIY solution would be to use a powershell script which would need to run as a service / or be something scheduled to run in windows task scheduler.

TTL would need to be about 5 seconds.
When powershellscript is ran it would need to have the implemented psedo logic.

<code>if (current host down / some sort of heartbeat check)
      update dns using powershell mapping the new host to the new address  or remove existing host thats offline,etc etc.
else
      do nothing
</code>

Run script every 10 seconds.

**Note: The only risks involved are stated below. For example constant dropped dns cache from a low TTL record would equate to more dns traffic hitting the name server. It could potentially be a bad idea (see below and above comments) depending on how much traffic your site actually gets "if you're self hosting your own DNS server and your name server is unable to handle the extra load / traffic" but it is a working solution.
However an increase of TTL using the same solution would reduce load on the DNS server but will increase the duration that it will take for existing non authoritative name servers and clients to drop their cache in order to obtain the new DNS entries.
This is also NOT a true failover. You will have intermittent downtime while this occurs and sessions will be destroyed and recreated after losing connection with the current machine whenever it goes down. This could impact databases as well which are being accessed and could potentially break other things depending on how code is written. If it's static HTML content though, you will be fine**
Comment: True, I've updated my answer.
Comment: Setting the TTL to 5 seconds is a bad idea. Exponentially so for a high traffic site.
Comment: Let me know if I missed anything.


Large search box on front page

Question: I want to make my front page look like simple google search page.
Elements:

Large search box
Footer
Login/Register

I'm having hard time figuring out how to have only these 3 elements.How can i edit search box area and its position?
Answer:
The first step is to set "search" as the path of your homepage in the "Site Information" configuration section of the site. This step requires that you have already enabled the search module.
If still have blocks of content on your home page the edit each one of the and make sure to set home page " < front > " as the place where they are not visible.
Add the login block to the footer and you are done.
If the any menu is still showing the create a page-front.tpl.php (D6) or page--front.tpl.php (D7) by duplicating page.tpl.php and the remove the code that shows the menus.
To make the search field larger you can use CSS.
Comment: No need to set search as homepage. Search box is part of block just add that to front page i.e node by default and as you said them it using `page-front.tpl.php`. Since it should be like google page strip out everything and add items/bocks as needed.

Large search box on front page


The probability of rolling a 5 is four times the probability of rolling a 3. What is the probability that a 2 or a 5 is rolled?

Question: A 6-sided die is weighted so that the probabilities of rolling a 1, 2, or 3 are equally likely; the probabilities of rolling a 4, 5, or 6 are equally likely; and the probability of rolling a 5 is four times the probability of rolling a 3. What is the probability that a 2 or a 5 is rolled?
How I solved it:
$P(\text{rolling a } 1, 2, 3) = x$

$P(\text{rolling a } 4, 5, 6) = 4x$ (because rolling a 4, 5, 6 is 4x the probability of rolling a 1, 2, 3)
$3(x)+3(4x)=15x$ (because 1,2,3 each has $x$ probability of being rolled and same with 4,5,6 except each of them has a $4x$ chance)

$15x = 1 ,  x=\frac{1}{15}$
Therefore, there's a $\frac{1}{15}$ chance of rolling a 1, rolling a 2, rolling a 3 and a $\frac{4}{15}$ chance of rolling a 4, rolling a 5, rolling a 6.
So to roll a 2 or 5, that would be $\frac{1}{15} + \frac{4}{15} = \boxed{\frac{1}{3}}$.
My teacher told me I got the answer correct, but my solution wasn't right and she said the part where it mentions that rolling a 5 is four times the probability of rolling a 3 is irrelevant. Can someone tell me what I'm doing wrong? Thanks!
Comment: she is right on that. If it was $6$ times instead of $4$, would not have made a difference. As combined probability of getting a $2$ or $5$ remains the same which is $1/3$. But that does not make your solution wrong.
Comment: ohhh ok thanks!
Answer: Your solution was correct but there was an easier way to see it.
The probability of a $1$ or $4$ is the same as the probability of a $2$ or $5$, which is the same as the probability of a $3$ or $6$.  Thus, the answer has to be $\frac 13$ no matter what the relative probability of the two groups are.


Multisite and alias suffix

Question: I am actualy working on a Drupal multi-site environment and I am stuck within a alias suffix problem.
I made a setup like this in my sites.php file for the multi-site alias names.
$sites['example.example.de'] = 'example.example.de';
$sites['tp-ref.example.example.de.vwp'] = 'example.example.de';
$sites['tp-tst.example.example.de.vwp'] = 'example.example.de';
$sites['tp-dev.example.example.de.vwp'] = 'example.example.de';
$sites['tp-local.example.example.de.vwp'] = 'example.example.de';

My VHost Config file is the following.
<VirtualHost *:80>
  DocumentRoot "C:/seu/xampp/htdocs/iptp"
  ServerName example.example.de
  ServerAlias tp-ref.example.example.de/vwp tp-tst.example.example.de/vwp tp-dev.example.example.de/vwp tp-local.example.example.de/vwp
</VirtualHost>

The host file contains the following lines.
127.0.0.1 example.example.de
127.0.0.1 tp-ref.example.example.de
127.0.0.1 tp-tst.example.example.de
127.0.0.1 tp-dev.example.example.de
127.0.0.1 tp-local.example.example.de

The URL example.example.de works without any problems; when I am trying to open one of the other URLs, I could open the page, but Drupal seems to have a problem with the path.
For example, if I want to open the URL "tp-ref.example.example.de/vwp", Drupal trys to load all CSS and JavaScript files from tp-ref.example.example.de, but it should load it from tp-ref.example.example.de/vwp.
I think this is a base path problem. Does Anyone have an idea about how fix this?
The comment shown in the sites.php is the following one. I used it to edit the sites.php file.
/*
 * URL: http://dev.drupal.org
 * $sites['dev.drupal.org'] = 'example.com';
 *
 * URL: http://localhost/example
 * $sites['localhost.example'] = 'example.com';
 *
 * URL: http://localhost:8080/example
 * $sites['8080.localhost.example'] = 'example.com';
 *
 * URL: http://www.drupal.org:8080/mysite/test/
 * $sites['8080.www.drupal.org.mysite.test'] = 'example.com';
 */

Answer: As you're loading all these sites from one directory: 'example.example.de'. You only have one site and therefore one settings.php file and ONE base path which defaults to the root domain.
To do what you'd like to do you'd actually need to multisite these with separate directories for each site. To the best of my knowledge anyway.

Multisite and alias suffix


Equivalent of ServletContextListener in vertx-mod-jersey

Question: When writing a web application in a servlet container, you can write a listener that implements javax.servlet.ServletContextListener to do something when the ServletContext is initialized or destroyed.
How do you do the equivalent when writing an application for Jersey in Vert.x using vertx-mod-jersey?
Answer: i never use ServletContextListener, just guess:
https://github.com/englishtown/vertx-jersey/blob/develop/ext-jersey%2Fsrc%2Fmain%2Fjava%2Fcom%2Fenglishtown%2Fvertx%2Fjersey%2Fimpl%2FDefaultJerseyServer.java#L103
there is a setupHandler you can do stuff you want to run before http server start
and you can override close method to do some teardown.
Answer: In this implementation they use the RoutingContext of Vertx
https://github.com/politrons/Vertx-Spring-Jersey/blob/master/src/main/java/vertx/JerseyHandler.java


The given key was not found in the dictionary using ConnectToFacebook(); on C#

Question: I am trying to connect to facebook using this code:
    FacebookService MiFB = new FacebookService();
    string MyAppId = "xxxxxxxxx"
    private void button1_Click(object sender, EventArgs e)
    {
        MiFB.ApplicationKey = MyAppId;
        MiFB.ConnectToFacebook();
    }

and even I get "The given key was not found in the dictionary" on MiFB.ConnectToFacebook();
Please, can you help me?
Comment: which client are you using? also connecting to facebook is usually not that simple, I dont see any oauth tokens there, just having an api key wont grant you access to a user's info
Comment: I am using Visual C# Express 2010.
Before I tried another way using oauth tokens but didn't get anything only problems.http://stackoverflow.com/questions/13243286/oauthexception-200-user-must-have-accepted-tos-on-c-sharp-facebook

So as I understanded when I use ConnectToFacebook(); it should show a windows to allow permissions..
Answer: My guess is that this error happens when the library used as an OAuth/API helper is parsing either a JSON or an URL result, then converting it to a dictionary (i.e. Dictionary<string, string>), and is querying a specific value without verifying it exists, and without handling the error.
Inside the library, it probably does:
var the_Values_In_The_Form_Of_A_Dictionnary = Url.SomeParseUrlMethod(result);
var access_token = the_Values_In_The_Form_Of_A_Dictionnary["access_token"];

It seems several libraries used this path: DotNetOpenAuth, FlickrNet. And the one the OP used. Having t handler server error as real .Net error is frustrating. Throwing unhandled errors from good server results is a strange decision, or I'm missing the point about these libraries.


How to prove that the limit of $f(x,y)=\frac{xy}{2(x+y)}$ at $(0,0)$ is 0 using the definition of limits?

Question: I got to the point
$|f(x,y)|=\frac{|x||y|}{2\,|x+y|} \leq \frac{x^2+y^2}{2|x|+2|y|}$
but then I'm stuck as I can't see how I could make the denominator smaller such that I create a $\sqrt{x^2+y^2}$ type expression. Any help would be appreciated.
Comment: If $x,y>0$, then is true as $$ \vert f(x,y)\vert \leq \frac{xy}{2x} \leq y.$$ However, as pointed out in the answer below, if you allow for different sign, then limit will not exist.
Comment: It's really interesting to see @Severin, that I don't even need $\delta$ and $\epsilon$ to show this. Thank you!
Comment: Your estimate is incorrect. In order to make a quotient (of positive numbers) larger, you smould make the denominator *smaller*, not larger.
Comment: Isn't that what @SeverinSchraven did though? $2|x|< 2|x+y|$  if $x$ and $y$ are both positive
Comment: Your estimate goes in the wrong direction as you use $2\vert x+y\vert \leq 2(\vert x\vert + \vert y\vert)$. I used that $2(x+y)\geq 2x$ (for $x,y>0$).
Answer: But the limit is not $0$. Note that$$\lim_{x\to0}f(x,-x+x^2)=\lim_{x\to0}\frac{x-1}2=-\frac12.$$
Comment: Thank you that makes sense! Apparently I was just unlucky with my choices.  I tried a few paths, straight lines and even a parabola and they all came to 0, so I just assumed the limit exist (obviously I was wrong), that's why I tried proving my assumption using the definition.


Wicket - DatePicker extend range

Question: A quick question.
When I create a datePicker object, the range of years you can select with DropDownChoice is a range -10/+10 years from now.
How can I extend this range? I want to start from 1900.
I tried with setMinDate but it doesn't work.
Answer: According to the documentation of DatePicker, DatePicker.configure(Map widgetProperties, IHeaderResponse response, Map initVariables) and YUI Calendar, you can set the mindate and maxdate as widgetProperties.
Comment: Im using org.odlabs.wiquery.ui.datepicker.DatePicker and not org.apache.wicket.extensions.yui.calendar.DatePicker
Comment: @MrMime I took the liberty to fix the tags to this question accordingly.

Wicket - DatePicker extend range


Chaining locks?

Question: When trying to answer the following question, I wrote this piece of code :
using static MyNameSpace.Locker; //So that we don't need to specify the static class name before each call.
public class MainClass
{
    public MainMethod()
    {
        Lock(new object()).Lock(new object()).RunAction(() => Console.WriteLine("Finished"));
    }
}

public static class Locker
{
    public static async Task<List<object>> Lock(object toLock, int timeout = -1)
    {
        await Task.Run(() => TryEnter(toLock, timeout));
        return new List<object>() { toLock };
    }

    public static async Task<List<object>> Lock(
        this Task<List<object>> lockedChain,
        object toLock,
        int timeout = -1)
    {
        await Task.Run(() => TryEnter(toLock, timeout));
        await lockedChain;
        lockedChain.Result.Add(toLock)
        return lockedChain.Result;
    }

    public static async void RunAction(this Task<List<object>> lockChain, Action toRun)
    {
        await lockChain;
        try
        {
            toRun.Invoke();
        }
        finally
        {
            foreach (var chainMember in lockChain.Result)
            {
                Monitor.Exit(chainMember);
            }
        }
    }

    private static void TryEnter(object toLock, int timeout = -1)
    {
        var success = false;
        if (timeout > 0)
        {
            success = Monitor.TryEnter(toLock, timeout);
        }
        else
        {
            success = Monitor.TryEnter(toLock);
        }

        if (!success)
        {
            throw new TimeoutException();
        }
    }
}

But as some user rightfully remarked, this won't work for a very simple reason : Since the methods are async, they may not run on the same thread, thus throwing an exception when trying to release the Monitor.
How would one go to ensure the Enter and Exit method of the monitor a run on the same thread ?
Comment: Locks are the antithesis of concurrent programming. The whole point of async/await, TPL, Dataflow, Reactive is to *avoid* locks, not reintroduce them. In any case, Stephen Toub published a series of [asynchronous coordination primitives](http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266988.aspx)  a while ago which use TaskCompletionSource tosignal completion and can be awaited with  `Task.WhenAll` or `Task.WaitAll`. No need to chain
Comment: Although, with tasks, simply running whatever needs to run in parallel and awaiting on all tasks with `await Task.WhenAll()` is enough
Comment: This question is a follow-up of the linked question. Would if be possible to actually chain methods so that timed-out locks needed for an operation would be awaited together instead of one after another ?
Comment: The original question asked about something different. You don't need to chain locks for asynchronous *coordination* though . You can wait for multiple tasks at the same time. You can create *asynchronous coordination* primitives like an async lock and Stephen Toub has done so.  It's better to use purpose-built libraries though like Dataflow or Rx, instead of trying to build them from scratch
Comment: Not arguing against that, just wanted to try out the Linq Like syntax the Author or the linked question "suggested", I'm not bold enough to try to redo something that was done, tried and approved. Just wanted to know if this was possible using this syntax.
Answer: Instead of forcing the lock operations onto the same thread which is nearly impossible, use a lock that is not thread-affine: SemaphoreSlim. It has native async support as well (as opposed to blocking).
In the original question that you linked to I'd go with this answer instead. Seems cleaner than the chain solution which contains a lot of artificial complexity. Code quality is not so much about the specific call syntax being used. Just by putting things in a syntactic chain you cannot reduce complexity much.
In particular the chain solution is just a complicated way of saying Lock(new [] { lock1, lock2 }, () => ...); I think. All the chain does it build up a list. using makes this even simpler because it does away with the lambda. Lambdas are less composable because you can't return from the lambda like you can from using. I think you should target this:
using (MultiLock(new [] { lock1, lock2 }, timeout)) {
 //...
}

Comment: I'd go to with the suggested answer, this was only a "What-if" question. Thanks for suggesting the SemaphoreSlim, it gave me some ideas on how to resolve the problem. I won't push this anymore though since it was only curiosity and not an actual need :)

Chaining locks?


can uiimageview image be set through the xcode designer?

Question: I'm working on a LaunchScreen.storyboard for a project.  I've added a UIImageView to the storyboard.  I would expect there to be a way to associate an image through the xcode designer but I don't see a way to do this.
I googled this topic and only found references to doing this programmatically instead of through the xcode designer.  So is there a way to do this through the designer or can this only be done programmatically? If this can only be done programmatically then what's the rationale behind this limitation?
Answer: When you select your UIImageView in your Launchscreen.storyboard, select the attributes inspector:

You should be seeing something similar to this:

In this dropwdown you can choose an image from your image assets.
Hope this helps!