Definite integral $\int_0^{\frac{\pi}{2}}\! \frac{\sin x }{\sqrt{\sin 2x}}\,\mathrm{d} x$

Question: $$\int_0^{\frac{\pi}{2}}\! \frac{\sin x }{\sqrt{\sin 2x}}\,\mathrm{d} x$$
I'm pretty sure I can finish it after finding the anti derivative. I tried changing the denominator to $2\sin x \cos x$ and subbing $u$ as $\sin x$.
$$\int_0^{\frac{\pi}{2}}\! \frac{\sin x }{\sqrt{2\sin x\cos x}}\,\mathrm{d} x$$
Comment: $\sin(x)=(\sqrt{\sin(x)})^2$ and then ask [W|A](http://www.wolframalpha.com/input/?i=int_0^%28pi%2F2%29+sqrt%28tan%28x%29%29+dx)
Answer: This can be written as
$$\dfrac{1}{\sqrt{2}} \int_0^{\frac{\pi}{2}} \sqrt{\tan x}\, dx$$
Now substitute $t^2 = \tan x$ $-$ this is valid since $\tan x \ge 0$ for $0 \le x < \frac{\pi}{2}$.
Then $2t\, dt = (1+t^4)\, dx$, and so the integral is equal to
$$\dfrac{1}{\sqrt{2}} \int_0^{\infty} t \cdot \dfrac{2t}{1+t^4}\, dt$$
Try to take over from here; let me know if you have more problems.
You should end up with $\dfrac{\pi}{2}$, and it is possible to find a closed form for the antiderivative.
Comment: $\displaystyle{\large{ {t^2 \over 1 + t^4} = \Re\left({1 \over t^2 + {\rm i}}\right) }}$.
Answer: After a little algebra, we get
$$ \int_0^{ \frac{\pi}{2}}\! dx \: \frac{\sin x }{\sqrt{\sin 2x}} = \frac{1}{\sqrt{2}} \int_0^{\frac{\pi}{2}} dx \: \frac{\sin{x}}{\sqrt{\cos{x} \sqrt{1-\cos^2{x}}}}$$
Substitute $u=\cos{x}$:
$$\int_0^{ \frac{\pi}{2}}\! dx \: \frac{\sin x }{\sqrt{\sin 2x}} = \frac{1}{\sqrt{2}} \int_0^1 du \: u^{-1/2} (1-u^2)^{-1/4} $$
Now substitute $v = u^2$:
$$\begin{align} \int_0^{ \frac{\pi}{2}}\! dx \: \frac{\sin x }{\sqrt{\sin 2x}} &= \frac{1}{2 \sqrt{2}} \int_0^1 dv \: v^{-3/4} (1-v)^{-1/4} \\ &= \frac{1}{2 \sqrt{2}} \Gamma \left( \frac{1}{4} \right ) \Gamma \left( \frac{3}{4} \right ) \\ &= \frac{\pi}{2} \end{align} $$
That last step comes from the relation
$$\Gamma(z) \Gamma(1-z) = \frac{\pi}{\sin{\pi z}}$$


Math Subject GRE 1268 Question 55

Question: If $a$ and $b$ are positive numbers, what is the value of $\displaystyle \int_0^\infty \frac{e^{ax}-e^{bx}}{(1+e^{ax})(1+e^{bx})}dx$.
A: $0$
B: $1$
C: $a-b$
D: $(a-b)\log 2$
E: $\frac{a-b}{ab}\log 2$
I really don't see how to start this one, I'm not so great with integrals.
Comment: Note that $e^{ax} - e^{bx} = (1 + e^{ax}) - (1 + e^{bx})$.
Comment: Since interchanging $a$ and $b$ has the effect of multiplying the integral by $-1$ you can quickly rule out B.  The other answers can't be ruled out for that reason.
Comment: Leucippus, you have pretty much given him the solution step. After this, just expand the fraction.
Comment: @NoseKnowsAll I think it's new since I looked for tests a few months ago and found 4 publicly available tests (0568,8767, 9367, 9768), then I went on their website and looked at their practice test and it was a new one.  https://www.ets.org/s/gre/pdf/practice_book_math.pdf.  If you know of any others please let me know too.
Comment: Side note: I'm also studying for the Math GRE subject test and have not found the specific test you are referencing. Could you post a PDF of it (or private message/email it to me privately)? Always looking for more practice problems. Thanks.
Answer: One indirect approach:
Write
$$f(a,b) = \int_0^\infty \frac{e^{ax}-e^{bx}}{(1+e^{ax})(1+e^{bx})}dx$$
Then changing variables by $x = ku$, for some positive $k$,
$$f(a,b) = k \int_0^\infty \frac{e^{kau}-e^{kbu}}{(1+e^{kau})(1+e^{kbu})}du = k\, f(ka,kb) $$
The only$^*$ answer which obeys the relation $$f(a,b) = k \,f(ka,kb)$$ is Option E.

$^*$Footnote: As pointed out in the comments, Option A does follow this relation as well but is easy to rule out on other grounds.
To unpack my original thinking:

Option A is not possible as we can make the integrand positive: for $a > b$, $f(a,b) > 0$
Option B is not possible as $f(a,b)$ cannot be independent of $a$ and $b$, e.g., without explicitly calculating, it looks clear that $\partial_a f(a,b) \neq 0$.
Now we're down to Options C, D or E. Since this is a question from a timed test and mathematicians are ruthlessly efficient (aka lazy), I don't want to evaluate the integral. Instead, can I find quickly some sort of scaling argument to rule out Options C and D? My 'fear' is that $f(ka,kb) = k\,f(a,b)$ which will instead rule out Option E and then I'll be stuck having to calculate the integral in order to differentiate between C and D.
But no! Instead $f(a,b) = k\,f(ka,kb)$. Good!
Comment: THis is a very nice solution.
Comment: Why doesn't Option A obey that relation?
Comment: @Theophile A does but you can rule out A pretty easily by taking $a>b$, then the integrand is positive and this has nonzero integral.
Comment: I'm making [solution videos for this test](http://webpages.sou.edu/~stonelakb/math/testprep.html) and cited the clever solution that Simon S mentioned above as an alternative solutions. I gave you props in the video, but figured you'd never see that, so wanted to add a comment here.
Comment: @Brian Thanks Brian.
Comment: What theorem are you using in your argument to rule out option B?
Answer: The integral being considered is, and is evaluated as, the following.
\begin{align}
I &= \int_{0}^{\infty} \frac{e^{ax}-e^{bx}}{(1+e^{ax})(1+e^{bx})}dx \\
&= \int_{0}^{\infty} \frac{dx}{1 + e^{bx}} - \int_{0}^{\infty} \frac{dx}{1 + e^{ax}} \\
&= \left( \frac{1}{b} - \frac{1}{a} \right) \, \int_{1}^{\infty} \frac{dt}{t(1+t)} \mbox{ where $t = e^{bx}$ in the first and $t = e^{ax}$ in the second integral } \\
&= \left( \frac{1}{b} - \frac{1}{a}\right) \, \lim_{p \to \infty} \, \int_{1}^{p} \left( \frac{1}{t} - \frac{1}{1+t} \right) \, dt \\
&= \left( \frac{1}{b} - \frac{1}{a}\right) \, \lim_{p \to \infty} \, \left[ \ln(t) - \ln(1+t) \right]_{1}^{p} \\
&= \left( \frac{1}{b} - \frac{1}{a}\right) \, \lim_{p \to \infty} \left[ \ln\left( \frac{p}{1 + p}\right) + \ln 2 \right] \\
&= \left( \frac{1}{b} - \frac{1}{a}\right) \, \lim_{p \to \infty} \left[ \ln\left( \frac{1}{1 + \frac{1}{p}}\right) + \ln 2 \right] \\
&= \left( \frac{1}{b} - \frac{1}{a} \right) \, \ln 2
\end{align}
Note:  Originally the statement "This is valid if $a \neq b$" was given at the end of the solution. Upon reflection it is believed that the statement should have been "This is valid for $a,b \neq 0$".
Comment: Thanks. I can't believe I didn't see that... I have some kind of integral phobia... bad memories from calculus.
Comment: @user3281410 Do not take that "phobia" with you when taking the GRE.
Comment: @kobe Thanks for the corrections.
Comment: Actually, to answer this question, it is not necessary to do calculation. When you take the exam, you do not have enough time to do calculation.
Comment: @Leucippus I don't see why $a \not= b$ is necessary; the integral would be $0$ if $a=b$. We just need that $a,b > 0$.
Comment: @Cookie I made a note of correction based upon your remark.
Answer: Tale $a = 1$ and let $b\to 0^+.$ In the limit you get
$$\int_0^\infty\frac{e^x-1}{(1+e^x)2}\,dx.$$
That integral equals $\infty$ because the integrand has a positive limit at $\infty.$ The only answer that fits this phenomenon is E.
Comment: This was what I assumed I should do when I was trying the test, but I couldn't justify switching the limit and the integral so I moved on the next one and didn't have time to come back.
Answer: A slight variation of the accepted solution begins on line $3$:
\begin{align}
I &= \int_{0}^{\infty} \frac{e^{ax}-e^{bx}}{(1+e^{ax})(1+e^{bx})}dx \\
&= \int_{0}^{\infty} \frac{dx}{1 + e^{bx}} - \int_{0}^{\infty} \frac{dx}{1 + e^{ax}} \\
&= \int_{0}^{\infty} \frac{e^{-bx} dx}{(1 + e^{bx})e^{-bx}} - \int_{0}^{\infty} \frac{e^{-ax}dx}{(1 + e^{ax})e^{-ax}} \\
&=\int_{0}^{\infty} \frac{e^{-bx} dx}{(1 + e^{-bx})} - \int_{0}^{\infty} \frac{e^{-ax}dx}{(1 + e^{-ax})} \\
\end{align}
For the integral involving $b$, let $u=1+e^{-bx}$ so that $\frac{-1}{b}du=e^{-bx}dx$.  Then $x=0 \implies u=2$, and $x \to \infty \implies u \to 1^+$.  With a similar result for the integral involving $a$, and changing the order of integration, we end up with
\begin{align}
I &= \left( \frac{1}{b} - \frac{1}{a} \right) \lim _{\epsilon \to 0^+}\int_{1+\epsilon}^{2}\frac{1}{u}du = \left( \frac{1}{b} - \frac{1}{a} \right) \ln 2 \ .  \\
\end{align}
Answer: Another approach. $$\int_{0}^{\infty}\frac{e^{-bx}}{1+e^{-bx}}dx=\int_{0}^{\infty}\sum_{k\geq1}\left(-1\right)^{k+1}e^{-kbx}dx=\sum_{k\geq1}\left(-1\right)^{k+1}\int_{0}^{\infty}e^{-kbx}dx
 $$ $$=\frac{1}{b}\sum_{k\geq1}\frac{\left(-1\right)^{k+1}}{k}=\frac{1}{b}\log\left(2\right)
 $$ and in similar way we can calculate $\int_{0}^{\infty}\frac{e^{-ax}}{1+e^{-ax}}dx
 $. So

$$
\color{blue}{\int_{0}^{\infty}\frac{e^{bx}-e^{ax}}{\left(1+e^{bx}\right)\left(1+e^{ax}\right)}dx=\left(\frac{1}{b}-\frac{1}{a}\right)\log\left(2\right).}$$
Comment: You accidentally wrote the series and integral in the same order, twice. The first step should be the other way around.
Comment: @symplectomorphic Fixed, thank you.
Comment: This is a great method
Answer: Clearly (A) and (B) are wrong. Noting $$\lim_{a\to\infty} f(a,b) = \lim_{a\to\infty}\int_0^\infty \frac{e^{ax}-e^{bx}}{(1+e^{ax})(1+e^{bx})}dx=\int_0^\infty \frac{1}{1+e^{bx}}dx<\infty,$$
we have to choose (E).

Math Subject GRE 1268 Question 55


Redux calls dispach function but it does not change the store

Question: I am writing LoadingComponent which should return a Spinner when some data is loading and when it is done it should return this.props.children.
I am getting the data at componentWillMount:
class LoadingComponent extends React.Component {
    componentWillMount() {
        this.props.userActions.onUserAuthChange();
        this.props.currencyActions.getCurrencies();
    }
}

I check if one of user or currencies is loading and if so return Spinner:
 render() {
    const {loadingUser, loadingCurrencies} = this.props;

    if (loadingCurrencies || loadingUser) {
        return (
            <Spinner/>
        )
    }
    return (
        this.props.children
    )
}

Here is where I connect the state to props:
const mapStateToProps = state => ({
  user: state.user,
  loadingUser: state.loading.loadingUser,
  loadingCurrencies: state.loading.loadingCurrencies,
});

const mapDispatchToProps = dispatch => ({
  userActions: bindActionCreators(userActions, dispatch),
  currencyActions: bindActionCreators(currencyActions, dispatch),
});

const ConnectedLoading = connect(mapStateToProps, mapDispatchToProps)
(LoadingComponent);

export default withRouter(ConnectedLoading);

And the loadingReducer:
const loadingReducer = (state = initialState.loading, action) => {
  switch (action.type) {
    case actionTypes.LOADING:
        return {...state, isLoading: action.loading};
    case actionTypes.LOADING_USER:
        return {...state, loadingUser: action.loadingUser};
    case actionTypes.LOADING_CURRENCIES:
        return {...state, loadingCurrencies: action.loadingCurrencies};
    default:
        return state;
  }
};

The thing is that loadingUser and loadingCurrencies are always false. This is getCurrencies function which dispatches with true when the data starts downloading and after that dispatches with false:
export const getCurrencies = () => async dispatch => {
    try {
        dispatch(loadingCurrencies(true));
        const currencies = await get();
        dispatch(loadCurrencies(currencies.rates));
        dispatch(loadingCurrencies(false));
    } catch (e) {

    }
}

I am using the LoadingComponent at App.js:
 render() {
    return (
        <LoadingComponent>

                <Route path='/:lang' render={props =>
                    languages.hasOwnProperty(props.match.params.lang) ?
                        <Navbar {...props}/> :
                        <Redirect to={`/${defaultLanguage}`}/>}
                />
                <Layout/>

        </LoadingComponent>
    )
}

This is the reducer function which listens for loadCurrencies(currencies.rates):
const currencyReducer = (state = initialState.currency, action) => {
  switch (action.type) {
    case actionTypes.LOAD_CURRENCIES:
        return {...state, currencies: action.currencies};
    case actionTypes.CHANGE_CURRENCY:
        return {...state, current: action.current};
    default:
        return state;
  }
}

During debugging noticed that at the LoadingComponent the Redux Dev Tool is not active and it starts to be active at LoadingComponent's children. Actually, when I set breakpoint at the reducer the state changes... And after Redux Dev Tool starts to be active I can observe that the loading states actually had been changed false -> true -> false. I would highly appreciate if someone could help.
Comment: can you post the reducer that listens to `loadCurrencies(currencies.rates)`?
Comment: Where is the part where you connect your Loading component to the store through `connect()` ?
Comment: What happens when your empty catch is caught? You should remove that whole try/catch wrapper
Answer: I would suggest adding redux-logger to your store: https://www.npmjs.com/package/redux-logger. This will help identify the sequence of events firing.
My initial thought is that you might have a race condition between loadCurrencies and loadingCurrencies returning. If loadCurrencies is a promise, then loadingCurrencies should dispatch in a then block to indicate the promise has returned.
IMO having bool arg methods is a code smell, and since the loading state is tied to the actual load method, it makes sense to have loading be a part of the same reducer. A pattern I typically follow is:
action
export const getCurrencies = () => {
  return dispatch => {
    dispatch(requestCurrencies()) // loading: true
    return api.getCurrencies()
      .then(currencies => dispatch(receiveCurrencies(currencies)))
  }
}

export const requestCurrencies = () => ({
  type: REQUEST_CURRENCIES,
  loadingCurrencies: true
})

export const receiveCurrencies = currencies => ({
  type: RECEIVE_CURRENCIES,
  currencies,
  loadingCurrencies: false
})


Have all data structures an abstract data type?

Question: I some places I'm reading contradictory things about this topic, for example here
Is heap an abstract data type? If so, what about priority queues?
The answer was:

both priority queues & heaps are data types (more accurate; abstract data type or ADT)

But here
Is Heap considered an Abstract Data Type?

Heap is not an ADT. It is a Data Structure.

And for example in the book:
Java Software Structures,International Edition [John Lewis, Joseph Chase]
it has a heap as ADT and a DS with this code:
public interface HeapADT<T> extends BinaryTreeADT<T>
{
/**
* Adds the specified object to this heap.
*
* @param obj the element to be added to this heap
*/
public void addElement (T obj);
/**
* Removes element with the lowest value from this heap.
*
* @return the element with the lowest value from this heap
*/
public T removeMin();
/**
* Returns a reference to the element with the lowest value in
* this heap.
*
* @return a reference to the element with the lowest value in this heap
*/
public T findMin();
}

The main question is if we say that all behaviour definition of a DS is an ADT, for example

List is an ADT of Static and Dynamic Array, linked-list
Stack, is an ADT, but you can implement the stack with an array or a linked list, but finally this stack is a data structure
Queue, the same that Stack
Heap, the same that Stack

So abstract data type is the behaviour that you'll implement with another data structure that has its own ADT.
Is this correct?
Thanks
Comment: This question has been asked to death here and on softwareengineering, as well. See https://softwareengineering.stackexchange.com/questions/148747/abstract-data-type-and-data-structure, or just do a Google search on [difference between abstract data type and data structure].
Comment: Might softwareengineering is a best place, but i think that a google search is not enought because have a lot of "versions", and what is the reall source of true about this, if some people defined heap like ADT, and antoher like and DS. And some people define the heap like and a DT, when you can implement this with pointer too. But I think that some people only say this like parrots because never put references of a book or similinar, and like I did, some times this books have contradictions betwen them like Algorithms 4th and Java Software Structures.
Comment: Like you can see in the second question from here https://softwareengineering.stackexchange.com/questions/148747/abstract-data-type-and-data-structure

```ADT: List
DS:  ArrayList, LinkedList...```

But if you read this DATA STRUCTURES IN C++ by N. S. KUTTI, P. Y. PADHYE they define the Array like ADT and DT
Answer: An Abstract Data Type, as you said, describes the behavior (or "semantics") of an entity (usually from the point of view of those who use that entity). So in your examples, stacks, queues, lists, etc...
A data structure is just a particular way of organizing data. So it is just one way to represent a data type.

The main question is if we say that all behaviour definition of a DS is an ADT

I wouldn't say that. If I define a data structure that represent the classical example of a Car (again, considering a data structure just as a way to organize data), the behavior of that data structure does not necessarily represent an ADT.
Comment: Of course that car doesn't represent and ADT, but you can abstract that car with a particular behaviours and then it become in an ADT. Right?
Comment: I think we're veering too much into metaphysics. I mean, an ADT exists because it's useful, not because of some intrinsic property. A car is not "abstract" enough to be considered an ADT. IMHO simply because it is a very concrete thing. A list of messages can be represented in the abstract as a queue (an ADT). That is, an ADT is meant as an abstraction. It doesn't derive from a data structure, but it can be implemented with a data structure. I have the impression you're thinking about this backwards, or maybe it's just me and I can't express clearly what I mean.
Comment: You are explaining perfectly, the real problem for my understand is, why someone can say that a heap is not and adt, for example, because you can implemente this with an array, and with a pointer, maybe not in the same time complexity, but I think that is an ADT too, also, for example can you say that dinamic array are and ADT, or is an dinamic array a data structure of a list?, who define officialy list? thus, you can say too that you have the array like adt and its implementation like a DT, right? thanks for your answers
Comment: I'll try to put it in other terms (*very* simplified and *not rigorous at all*): an ADT is "I can do these operations on an entity", a data structure is "to implement this entity I need to do this". A heap is an implementation detail. You can insert things and get things from it, but this is also the definition of a Map (which is an ADT). A heap is a particular way of implementing a map. Just like you can implement queues, lists and stacks (even maps, if you like wasting time :P) with a dynamic array. Hope this helps :)
Comment: @FedericoklezCulloca *a heap is a particular way of implementing a map.* Not really. I mean, you *could* implement a map in a heap, but it would be terribly inefficient: like a list. Heap is an implementation of the priority queue ADT. A map is something quiet different: https://en.wikipedia.org/wiki/Associative_array
Comment: @JimMischel you're right, I was thinking of hash tables, not heaps. I got confused.
Comment: @FedericoklezCulloca the last comment is very clear for understand thanks
Comment: @FedericoklezCulloca I response in the other question, if you can check it too: https://stackoverflow.com/a/57594669/11901332


clock() is not letting me store in a clock_t variable

Question: I am writing some code for a C2000 microcontroller, and I am trying to time certain segments of my code using time.h. However, when i enter this code:
clock_t begin = clock();

It sends back a bunch of errors.  Including one that says: error: function call is not allowed in a constant expression.  But I don't believe it is a constant expression.
Does anyone have an idea what might be going on here?
Further errors include:

--output_all_syms --cdebug_asm_data --preproc_with_compile -- preproc_dependency="Example_2802xAdcTempSensor.pp"  "../Example_2802xAdcTempSensor.c"
      "../Example_2802xAdcTempSensor.c", line 155: error: expected a "}"
      clock_t start = clock();
"../Example_2802xAdcTempSensor.c", line 155: error: function call is not
            allowed in a constant expression
    clock_t start = clock();
                    ^

Thanks in advance.
Comment: am suspecting there's a missing `;` in a previous line, a missing `}`, or some such...
Comment: Can you show us the exact code ?
Comment: That's a strange error.
Comment: The rest of the "bunch of errors" might be important. Especially if the one you've chosen to share with us isn't the first one.
Comment: @WumpusQ.Wumbley Ok I'll add some more.
Comment: That's peculiar; can you make a **short** program that reproduces the error (and show how to make it go away)? If you did that as an answer I would definitely give it a +1!
Comment: @Eman No need to hide it. ;-)
Comment: @Floris That's why Eman disappeared… he just found it. ;-)
Comment: @BitFiddlingCodeMonkey Nope still no luck.
Comment: `line 155: error: expected a "}"` AHA! I was right… Show more code. The error is not what you think. There is a hanging open-bracket somewhere.
Comment: @Floris one of the errors that I just added does say that that it expected a "}" as you can see above.  But I fail to see how or why.
Comment: So show us lines 1 through 156 (at a minimum) and we'll cast our beady eyes on it.
Comment: @Floris You're right it seems to be something else.  Let me poke around a  little and I'll see if I can figure out what.
Comment: Yes, let us steal you awesome code! ;-)
Comment: @Floris It looks like what it was, is that I was defining the variable inside `main()`.  Once I moved it outside it worked fine.  Thanks for the help.
Answer: Split it into two lines:
clock_t begin;
begin = clock();

The compiler wants the initialization to be a constant expression (per the error message) - which a function call is not.
By splitting it like this you are saying "when the program is running and gets to this point, that is the time I want to evaluate this function". And all will be well.
Comment: I have tried this and it still doesn't work
Comment: It says that `begin = clock();` is not compatible with `clock_t begin;`
Comment: Can you show complete code (`#include`s, compile directives, ...) of the smallest program that has this error (probably just a dozen lines max) - and then show the complete error listing as well?
Comment: Did you `#include ` ?
Comment: Yes i did include ``
Comment: Is `begin` `const` somehow?
Answer: It turns out that the definition just had to be moved outside of the main loop.  Once I did this it worked fine.
Comment: This is really weird. Can you reduce the code to show an example of it failing? Also what compiler/platform are you using?


float em algum elemento, e a div não acompanha o conteúdo

Question: Estou tentando flutuar um elemento para a direita, e este elemento está dentro de uma div sem tamanho definido. O problema é que quando o flutuo o elemento p a div não acompanha o conteúdo.
Segue o código HTML:

Conteúdo dentro da div

E o CSS:
#divPrincipal{
    border: 1px solid red;
}

#divPrincipal p{
    border: 1px solid blue;
    float: right;
}

Como resolver isto?
Comment: Testei o position, e apliquei nele um left de 1000px. O conteúdo saiu fora da div. Isso porque o elemento p está sendo tratado como um bloco, eu posso defini-lo com um display: table. Seria uma solução.
E sobre o width: 100%, não resolveu a situação não.
Comment: Afinal, você está querendo alinhar a `div` a direita ou os elementos da `div`, ou mesmo ambos?
Comment: O elemento!

Quando disse que a div não acompanha o conteúdo, é poque a div tem seu height como se fosse no tamanho 0px;
Comment: Kazzkiq já respondeu.
Answer: Você precisa limpar o float para o elemento pai assumir o tamanho dos seus filhos com float. Existem várias maneiras de fazer isto, mas a mais moderna atualmente seria usando algo como esta solução:
.cf:before,
.cf:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.cf:after {
    clear: both;
}

Onde esta classe CSS seria adicionada ao seu elemento pai, sendo que o HTML ficaria assim:

Conteúdo dentro da div

Exemplo: FIDDLE


Date API: Proper method of parsing dates

Question: I'm working on a simple event sign up module. The functionality is split in two modules, one which provides an Event content type with title, description and date (from - to) fields, and the second with sign up functionality and sign up window dates for Event content type. The problem is that I don't seem to find a way to properly parse and do comparisons and calculations on the event/signup dates.
Date API documention is quite light on specifics on this area, so it has not been much of a help.

How can I use the Date API to obtain DateObject from the event date stored on the node?
How can I determine whether the stored event is an all day event?
Answer:
How can I use the Date API to obtain DateObject from the event date
  stored on the node?

Offhand, I'm not 100% sure the right way to do this. It sounds like you want to use the DateObject to perform some calculations -- not just to run through a theme field_formatter. This date issue thread has some code kinda trying to use date fields and their values, but doesnt help much.
Simply because I can understand it (and have used this module myself) I recommend trying out the sub-module of Date, date_api, and an additional 3rd party module: field_extract.
With field extract you can easily (and correctly) access a fields value for instance as a timestamp:
<code>  // Extract from a date, this extracts the first value and provides a
  // formatted date output, uses the specified format, by name.
  $event_timestamp = field_extract_value('node', $node, 'field_event_time', 0, array('format' => 'timestamp'));
</code>
You can then use the DateAPI to create a DateObject:
<code>$date = new DateObject($event_timestamp);
</code>

How can I determine whether the stored event is an
  all day event?

Use the date_is_all_day() function found in the date_api module, it compares 2 date fields to check if they encompass a full day.
<code> function date_is_all_day($string1, $string2, $granularity = 'second', $increment = 1) { ... }
</code>


Diamond Problem

Question: Wikipedia on the diamond problem:
"... the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C?"
So the diamond looks like this:
  A
 / \
B   C
 \ /
  D

My question is, what happens if there is no such class A, but again B and C declare the same method, say foo(). Isn't this the same problem? Why is it then called diamond problem?
Example:
class B {
    public void foo() {...}
}

class C {
    public void foo() {...}
}

class D extends B, C {
}

new D().foo();

Comment: @Neil Butterworth  language should not matter in this as this is more a concept issue. Languages like C++ allow this but Java and C# does not.
Comment: In short: The "triangle" can only fail at compile-time (and can be fixed by being more explicit at the call-site), but the "diamond" can fail at run-time because of `A* a = new D();` followed by `a->foo();`.
Comment: what language are you asking about?
Comment: And this is why "multiple inheritance" is a dirty word...
Answer: Its not the same problem.
In the original problem, the overriden method can be called from A. In your problem this can't be the case because it does not exist.
In the diamond problem, the clash happens if class A calls the method Foo. Normally this is no problem. But in class D you can never know which instance of Foo needs to be called:
         +--------+
         |   A    |
         | Foo    |
         | Bar    |
         +--------+
            /  \
           /    \
          /      \
+--------+        +--------+
|   B    |        |   C    |
| Foo    |        | Foo    |
+--------+        +--------+
          \      /
           \    /
            \  /
         +--------+
         |   D    |
         |        |
         +--------+

In your problem, there is no common ancestor that can call the method. On class D there are two flavors of Foo you can chose from, but at least you know that there are two. And you can make a choice between the two.
+--------+        +--------+
|   B    |        |   C    |
| Foo    |        | Foo    |
+--------+        +--------+
          \      /
           \    /
            \  /
         +--------+
         |   D    |
         |        |
         +--------+

But, as always, you do not need multiple inheritance. You can use aggegration and interfaces to solve all these problems.
Comment: The Wikipedia article talks about calling foo() from D, though.
And what about calling foo on a D from outside D like new D().foo() (also in my example)?
Answer: In the diamond problem, class D implicitly inherits the virtual method from class A. To call it, class D would call:
A::foo()

If both classes B and C override this method, then the problem comes of which actually gets called.
In your second example however, this isn't the case as class D would need to explicitly
state which was being called:
B::foo()
C::foo()

So the problems are not actually the same. In the diamond problem you aren't referencing the derived classes, but their base class, hence the ambiguity.
That's how I understand it, anyway.
Note that I'm coming from a C++ background.
Comment: I don't know C++, but wouldn't it be the same problem if you'd call foo from outside D, say new D().foo()? Then the example without A would also be problematic, right?
Comment: @cretzel, yes, in that case you also have a name clash problem.
Comment: I think in most cases the compiler (for C++ at least) will give an error due to the ambiguity. It has on the compilers I've used, I'm not sure what the C++ standard says about it.
Comment: @icabod So, when you write `A::foo()`, what is called is not the method in class A, but one of the methods in A's children, which causes the ambiguity. But what if you want to call class A's `foo()`? How do you do that?
Answer: Your second example is nowhere near the diamond problem because compiler has the ability to detect the available functions one level up of inheritance.
Once the compiler gets to know that you are using same-named functions in two base classes, it will throw error: member 'foo' found in multiple base classes of different types.
Comment: There are other answers that provide the OP's question, and they were posted some time ago. When posting an answer [see: How do I write a good answer?](https://stackoverflow.com/help/how-to-answer), please make sure you add either a new solution, or a substantially better explanation, especially when answering older questions. You can comment on old answers instead.
Answer: The diamond problem only arises from incorrect type/ontology modeling.  It doesn't exist in properly-modeled systems.
The problem arises usually because developers define classes for entities based on their roles not their types.  They elevate what it can do above what it actually is.  The entity object carries the role not the type.
A person is a person, for example, from birth to death regardless of whether he gets married (Husband), visits mom (Son), or lands a great job (Employee).  The roles for Person can be implemented with interfaces or components or mixins—fuel in the argument to prefer composition to inhertiance.
It would be reasonable to allow an entity's type to be replaced via some state machine transition.  Thus, a Person could be replaced with Werewolf (full moon) or Vampire (neck bite) as the result of a state transition.  The entity (some fixed GUID) remains regardless of the transition.  But even this can be modeled differently—a Person with Lycanthropy and/or Vampirism.  Of course, modeling to accommodate many facets can be a challenge, but it it has nothing to do with the typical limitation that classes may participate in a single inheritance chain.
An UnverifiedEmailAddress could transition to a VerifiedEmailAddress, but this is not a great example because it probably ought use a value object rather than a reference object.  A better example could involve a WorkingPurchaseOrder transitioning to a SubmittedPurchaseOrder via a submit function.  The function would likely return an immutable replacement (such as a Persistent Object) and be swapped into some observable state container.

Diamond Problem


CMake: find_file() does not search recursively

Question: I'm trying to use the arduino-cmake framework but my Arduino-SDK is not recognized correctly. Searching for the cause I found the following:
        find_file(${PLATFORM}_BOARDS_PATH
            NAMES boards.txt
            PATHS ${PLATFORM_PATH}
            DOC "Path to Arduino boards definition file.")

where ${PLATFORM}_BOARDS_PATH expands to ARDUINO_BOARDS_PATH-NOTFOUND.
PLATFORM_PATH correctly points to /opt/local/arduino-1.8.7/hardware/arduino and inside you can find avr/boards.txt.
So everything seems to be Ok, right?
Changing PATHS inside the find_file() command to ${PLATFORM_PATH}/avr gives the right result - so it looks like find_file does not search recursively.
What do I do wrong? arduino-cmake seems to be working for others so I guess there must be a solution to this without altering paths like this..
Comment: This is intended behaviour that `find_file` doesn't search recursively. Note, that [cmake/Platform/Arduino.cmake](https://github.com/queezythegreat/arduino-cmake/blob/master/cmake/Platform/Arduino.cmake) explicitly describes what is a **platform directory** (which is specified by `PLATFORM_PATH` variable), see the line `# register_hardware_platform(HARDWARE_PLATFORM_PATH)` and below.
Answer: As @Tsyvarev pointed out, find_file() and find_path() do not search recursively. In many cases, you can substitute these commands with the file(GLOB_RECURSE ...) command (see more details here).
In your example, you could write something like:
file(GLOB_RECURSE ${PLATFORM}_BOARDS_PATH boards.txt)


What is the term when two people sing in harmony, but they aren't singing the same notes?

Question: I'm not a musician, and I know basically nothing about music, and music theory and what-not. (I basically just know a few common terms, and how to play chords)
In most songs with two or more people singing, (Duets specifically) the singers almost always sing in harmony, but not the same notes. What term is used to describe this? I want to be able to learn how to do it, but I don't know the specific term to do more research on it.
Comment: That's called singing in harmony.
Comment: If they're singing the same note, they are *not* singing in harmony—they're just singing the same note.
Comment: Singing the same note is unison
Comment: A good place to start might be the wikipedia page on 'vocal harmony'. And then watch a bunch of episodes of "Glee" for examples. :)
Comment: I would just note that the word "harmony" *as a musical term of art* means specifically that singers are singing *different notes,* as implied in the comments.  But the word "harmony" was formerly used more broadly to denote pleasant sounds, and for a lay person it could still reasonably be used that way today.  In Micrologus, Guido d'Arezzo calls the octave the most harmonious of intervals, saying that other intervals can never be fully harmonious; this does not agree with modern use of the word.
Answer: The term "harmony" itself is what you are looking for.
Being able to sing in harmony (2 or more different voices) with someone however doesn't require any more skills or theory than singing alone or in unison (same notes, only one voice) because everyone learns "his notes" as he would do singing alone. The only thing I could think of is having a good ear, maybe good relative pitch, but that is required for soloists singers too.
The hard part is composing or improvising the harmony and that requires a lot of different music theory skills, not only the harmony part. If this is what you are looking for, I would suggest to start with generic music theory or if you are really serious about it, take piano lessons.
Comment: `Being able to sing in harmony (2 or more different voices) with someone however doesn't require any more skills or theory than singing alone or in unison ` I don't know that this is true. I've seen people who are used to singing in unison and have great difficulty "ignoring" the notes that other people are singing and not matching them.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/91562/discussion-on-answer-by-xandru-what-is-the-term-when-two-people-sing-in-harmony).
Answer: Singing together but different notes is singing in harmony. Singing the same notes would be singing in unison.
Comment: Singing the same note might also be called "doubling".
Comment: @ToddWilcox Interesting. In my 30 years of singing and recording I've never heard that. When recording, yes, you double it, when singing live (meaning multiple people singing the same notes), they're singing in unison. Might be a stateside thing.
Comment: @DarrenSweeney doubling is commonly used in orchestration, as in, "the second flute doubles the first violin section" or "the clarinet doubles the tenor part."
Comment: "Doubling" also sometimes implies that two voices or instruments are playing the same note but one or more octaves apart.  Most often used when said voices are not in the same range, e.g. "The trombone part is doubling the trumpets."
Answer: From a strictly music theory point of view, one might call it counterpoint. The original Latin phrase "punctus contra punctum" (note against note) denotes just that. The term indicates two or more voices, each having their own independent melody (the horizontal aspect in written music), resulting in a harmony (the vertical aspect).
Comment: Counterpoint's usually much more than simple parallel harmony, though; with lines that are independent, usually with contrasting rhythms and/or shapes, and can stand alone as melodies in their own right.
Comment: Exactly what I was thinking, if "not the same notes" means "a harmonizing melody in a different rhythm" for the OP.
Comment: @gidds is correct, counterpoint is generally in reference to a very specific set of strictures with regard to *how* one constructs interdependent yet individual melodic lines that, when combined, create specific harmonies.
Comment: Contrapuntal, and it is seen for guitar.
Answer: It is called polyphonic singing aka overtone chanting, harmonic singing, or throat singing. Bjork does some (but NOT all) of her singing in a polyphonic manner.
Also refer to Wikipedia documentation as follows:
Overtone singing – also known as overtone chanting, harmonic singing, or throat singing – is a type of singing in which the singer manipulates the resonances (or formants) created as air travels from the lungs, past the vocal folds, and out of the lips to produce a melody.
The harmonics (fundamental and overtones) of a sound wave made by the human voice can be selectively amplified by changing the shape of the resonant cavities of the mouth, larynx, and pharynx.[1] This resonant tuning allows singers to create apparently more than one pitch at the same time (the fundamental and a selected overtone), while actually generating only a single fundamental frequency with their vocal folds.
<code> Each note is like a rainbow of sound. When you shoot a light beam through a prism, you get a rainbow. You think of a rainbow of sounds when you sing one note. If you can use your throat as a prism, you can expose the rainbow – through positioning the throat in a certain physical way, which will reveal the harmonic series note by note.[2]
</code>
https://en.wikipedia.org/wiki/Overtone_singing#Mongolia_and_Buryatia
Comment: This seems to refer to a single person producing multiple tones apparently at once. The question is rather about two different people singing together but different notes.
Comment: This is a great answer written for the wrong question. The question mentions two people.


Tabela com select e submit

Question: Olá amigos estou tentando fazer uma tabela, sendo para cada item da tabela aparece um <select> e um submit que vai enviar dados via POST, como é relativo quantas unidades vai aparecer não é possível prever quantidades. Infelizmente da forma que fiz qualquer submit envia o último da lista e não seu respectivo.
É possível fazer essa ação?
Quais erros cometi?
Estou cogitando refazer todo código já que parece que fiz de uma forma errada, porém estou um pouco confuso.Alguém pode me dar dicas.
Segue alguns trechos do código.
Parte do corpo da tabela
   $query="SELECT DISTINCT `clientes`.`nome`, `ficha_de_moveis`.`id_controle` , `ficha_de_moveis`.`valor-total-controle`,`ficha_de_moveis`.`datamontagem`, `ficha_de_moveis`.`status` from `clientes` join `ficha_de_moveis` on `clientes`.`id_cliente` = `ficha_de_moveis`.`id-cliente`";
    $sql=mysqli_query($conn,$query);
    while($row= mysqli_fetch_array($sql)){
        $numero = $row['id_controle'];
        $cliente = $row['nome'];
        $sobrenome = $row['sobrenome'];
        $valor = $row['valor-total-controle'];
        $data = $row['datamontagem'];
        $data = date("d-m-Y",strtotime(str_replace('/','-',$data)));
        $status = $row['status'];
        echo"

            $numero
            $loja
            $cliente $sobrenome
            $valor
            $data

            <select class='form-control' name='statusm'>
            <option value ='$status'>$status</option>
            <option value=''>----------</option>
            <option value='APROVADO'>APROVADO</option>
            <option value='EXECUTANDO'>EXECUTANDO</option>
            <option value='CONCLUIDO'>CONCLUIDO</option>
            <option value='CANCELADO'>CANCELADO</option>
            </select>

            <button type='submit' name='mudarStatus' class='btn btn-primary'>
                 Montar
            </button>

";
    }

Metodo:
   if(isset($_POST['mudarStatus'])){

                            $mudar_status=$_POST['statusm[]'];
                            echo$mudar_status;
                            echo $controle;

Answer: <select class='form-control' name='statusm'>

Todos os seus selects tem o mesmo name, por isso só o último é reconhecido. Você pode usar name="statusm[]" para enviar todos como um array (que é o que parece que seu código PHP está buscando) ou usar nomes dinâmicos baseados na identificação de cada um. Aí vai da sua preferência.
Caso opte pelo array, no PHP você poderá usar somente $_POST['statusm'].

Tabela com select e submit


Inspect shows ??? in Rad Studio 10.3.2

Question: Rad Studio 10.3.2, create a new Windows VCL app C++. Put a breakpoint at the Form1 constructor. If I inspect "this" and the debugger shows ???? for any variable.
I am having really a lot of problems with 10.3.2, not only this one (std::variant not work, CLANG stops, ...). I would say that it has a lot of bugs but now I would ask if somebody has a similar problem.
Comment: Had the same problems and switched back to 10.3.1. Quality Central has been unavailable for some days, but there are some contributions to this misconduct.
Comment: Thank you. After days trying it, finally I switched back to 10.3.1. It also has bugs, but at least, the debugger works.
Answer: It is a known bug in 10.3.2 and is currently being fixed by Embarcadero.
The bug is tracked as RSP-25527 | RSP-21126 (currently these are marked as duplicates but a request has been made to separate them).
They report that you can work with 64 bit windows ... provided of course you are not trying to link to external libraries or COM objects that are only available as 32 bit.
I can confirm that I have tested a Win64 VCL project and I can confirm that I do have the variables visible in the Inspect Window.  You may have to manually add the 64 bit Windows target.
(I am having some problems with my 64 bit debug setup at the moment - I am loading packages which include debug info (as per the Events window it states the library has debug info) but I am unable to step into some of them which I normally can do with Win32.  I do have the variables visible to me though.)
Comment: If you have access to the Embarcadero quality portal, they released a hot fix for this issue on Friday. I have tried it and I can confirm that with the patch I ***do*** have local variables visible. Quality portal URL: https://quality.embarcadero.com/
Comment: A Further comment - it appears the values shown are not reliable so IMHO you cannot rely on them for debugging purposes.  It may be to do with my project setup (debugging inside a BPL with objects inheriting from another BPL) but I cannot confirm that.

Inspect shows ??? in Rad Studio 10.3.2


python variable scope

Question: I have started to learn about python and is currently reading through a script written by someone else. I noticed that globals are scattered throughout the script (and I don't like it).. Besides that, I also noticed that when I have code like this
def some_function():
    foo.some_method()
    # some other code

if __name__ == '__main__' :
    foo = Some_Object()

    some_function()

even though I don't pass in foo into some_function(), but some_function is still able to manipulate foo (??!). I don't quite like this although it is somewhat similar to Javascript closure (?). I would like to know whether it is possible to stop some_function() from accessing foo if foo is not passed in as a function argument? Or this is the preferred way in python??! (I'm using python 2.5 under ubuntu hardy at the moment)
Answer: That script has really serious issues with style and organization -- for example, if somebody imports it they have to somehow divine the fact that they have to set thescript.foo to an instance of Some_Object before calling some_function... yeurgh!-)
It's unfortunate that you're having to learn Python from a badly written script, but I'm not sure I understand your question. Variable scope in Python is locals (including arguments), nonlocals (i.e., locals of surrounding functions, for nested functions), globals, builtins.
Is what you want to stop access to globals?  some_function.func_globals is read-only, but you could make a new function with empty globals:
import new
f=new.function(some_function.func_code, {})

now calling f() will given an exception NameError: global name 'foo' is not defined. You could set this back in the module with the name some_function, or even do it systematically via a decorator, e.g.:
def noglobal(f):
    return new.function(f.func_code, {})
...
@noglobal
def some_function(): ...

this will guarantee the exception happens whenever some_function is called. I'm not clear on what benefit you expect to derive from that, though. Maybe you can clarify...?
Comment: just finished removing the globals, I'm currently looking at nonlocals (locals of surrounding functions - for nested functions)

I want to reduce the amount of non-local used probably because of a habit I brought from coding in PHP - if a variable is not passed into a function, then the variable doesn't exist in the function (which IMO, it is easier to debug if bad things happen)
Comment: @Jeffrey, yes wrt globals, but nonlocals, especially if a function is just accessing them and NOT reassigning them (the latter being really an option only in 2.6 and later with the `nonlocal` keyword), are not really a problem -- and I speak on the basis of decades of hard-won experience;-).
Answer: As far as I know, the only way to stop some_function from accessing foo is to eliminate the foo variable from some_function's scope, possibly like:
tmp = foo
del foo
some_function()
foo = tmp

Of course, this will crash your (current) code since foo doesn't exist in the scope of some_function anymore.
In Python, variables are searched locally, then up in scope until globally, and finally built-ins are searched.
Another option could be:
with some_object as foo:
    some_function()

But then, you'll have to at least declare some_object.__exit__, maybe some_object.__enter__ as well.  The end result is that you control which foo is in the scope of some_function.
More explanation on the "with" statement here.
Comment: Replacing globals with passed argument values is always challenging.  It seems like there's always one more silly reference to the global floating around.  Therefore, when fixing this global mess, rename your legacy global variables as you rewrite your functions to take arguments instead of globals.  Then things break for the right reason.
Answer: In python, something like foo is not a value, it's a name.  When you try to access it, python tries to find the value associated with it (like dereferencing a pointer).  It does this by first looking in the local scope (the function), then working its way outwards until it reaches the module scope (i.e. global), and finally builtins, until it finds something matching the name.
That makes something like this work:
def foo():
    bar()

def bar():
    pass

Despite the fact that bar doesn't exist when you defined foo, the function will work because you later defined bar in a scope that encloses foo.
Exactly the same thing is going on in the code you post, it's just that foo is the output of Some_Object(), not a function definition.
As Alex said, the fact that you can write code like that does not mean that you should.

python variable scope


Abrir Modal com Delay e Depois de Fechado não Abrir Mais

Question: Estou tentando criar um modal bootstrap como tela de saudação de uma página. A parte dele abrir com delay eu consegui fazer sem problemas, mas preciso que quando o usuário fechar ele, ele não volte a ser exibido na próxima vez que o mesmo logar na tela. O código do modal é o padrão do bootstrap e vai conter apenas um texto simples.
$(window).on('load',function(){
    var delay = 1000;
    setTimeout(function(){
        $('#notificacao').modal('show');
    },delay);
});

Comment: eai gnomo deu certo?
Answer:     $(window).on('load',function(){
    var delay = 1000;
    setTimeout(function(){
          // puxa o item no localstorege
        let janela= localStorage.getItem('janela');
        //verifico se e igual a null
        if(janela == null){
        $('#notificacao').modal('show');
        // seto o item no local storege para que ele n seja mais null
        localStorage.setItem('janela', 'true');
        }
    },delay);
});

Answer: localStorage - nos permite armazenar dados de forma simples e sem expiração, ou seja, ficam lá enquanto não apagarmos por código ou pelo próprio navegador.
Sintaxe para salvar dados em localStorage: localStorage.setItem("chave", "valor");
Sintaxe para leitura de dados de localStorage: var nomeVariavel = localStorage.getItem("chave");
Sintaxe para remover dados de localStorage: localStorage.removeItem("chave");
$(window).on('load',function(){
    var isshow = localStorage.getItem('isshow');
    if (isshow== null) {
        localStorage.setItem('isshow', 1);

        setTimeout(function() {
            $('#notificacao').modal('show');
        }, 1000);
    }
});


Find Correlation between food likes!

Question: I need help in this problem. Really i'm in bad situation. I have these data and i should find a correlation between food likes. i'm not familiar with statistics. would you show me any example for this problem. i have no idea for that.
Comment: At the least, you must explain for us what the data coding means! Without that no possibility for an answer.
Answer: How about just try correlations between any of two variables using Pearson or Spearman correlation coefficient.
The followings are SAS code and I use the top 10 observations in your table,
<code>data a;
input active gender age pizza salad chocolate coffe;
datalines;
1 1 54 1 0 0 1
1 1 38 1 0 1 0
1 2 34 0 1 1 0
1 1 23 0 0 0 0
0 2 46 1 1 1 0
0 2 46 1 0 1 0
0 2 54 0 1 0 1
1 1 58 0 1 1 0
1 1 25 1 1 1 0
0 1 33 0 0 0 1
;
run;

proc corr data=a spearman Pearson;
var active gender age pizza salad chocolate coffe;
run;
</code>
Results:

It seems Coffee and Chocolate are negatively correlated (r=-0.8017, p=0.0053), i.e people who prefer coffee will not like Chocolate, and vise visa. It seems reasonable, since Coffee is bitter and Chocolate is sweet. I did not see correlations between any other two variables.
The analysis is simple but I hope it can help you.
Answer: The "food like" variables look like binary values, so for each pair (e.g. pizza and salad), you could use Pearson's correlation. For a general discussion about correlations between binary vectors, see this question.
It would probably make sense to also divide the data by the other variables. E.g. is there a different correlation between pizza and pasta preference for men and for women?
Answer: You can do one of two things:
1) Multinomial logistic regression.
2) Boxplots on segmented data.
Comment: thank you, thank you. for your answer. would you show me an example about it. i'm badly need it
Comment: The multinomial logistic regression will not work because choice of choose pizza, salad, chocolate and coffee is not mutually exclusive.

Find Correlation between food likes!


Can I safely uninstall "Citrix Tools for Virtual Machines"?

Question: Having several virtual servers with Windows 2008 R2 at our web hoster (Germany's "1&1", they seem to use Citrix Xen), I have every now and then some servers that hang (RDP login screen hangs forever).
Only turning the server off and on again via the hoster's web control panel helps "resolving" this.
After this reboot, I find an entry in the event log:

Log name: System
  Source: xennet6
  Event ID: 5001
The description for Event ID 5001 from source xennet6 cannot be found.
  Either the component that raises this event is not installed on your
  local computer or the installation is corrupted. You can install or
  repair the component on the local computer.
If the event originated on another computer, the display information
  had to be saved with the event.
The following information was included with the event:
\Device\NDMP1 Citrix PV Ethernet Adapter #0

When looking in the "Uninstall Programs" in Windows I see an entry

"Citrix Tools for Virtual machines".

From pure guessing, I could imagine that this tool may be a cause for the issue.
So I searched Google and Citrix Xen forums to see and information for what this tool is intended and whether it would be safe to remove it.
Unfortunately I found no answer. What I found is this long thread on the Citrix forums, which I do not understand fully.
Therefore my question is:
Is it safe to uninstall "Citrix Tools for Virtual machines" from my Windows 2008 R2 64-Bit Server?
("Safe" in terms of "The server still boots and runs normally")
Update 2013-04-23:
Following the fantastic answer of syneticon-dj, I contacted the 1&1 support, asking about how to fix the server halts. They first suggested to:

Disable IPv6.
Delete all not-required network adapters.

Since I already did both without success, I pointed them to this Server Fault posting, asking whether it is safe to upgrade Xen Tools as pointed out in the Rackspace KB article.
They answered something vague like:

"Give it a try, from our point-of-view, nothing should go wrong. If it real helps you have to see afterwards".

So I now have one server updated five days ago with no more errors since then; I updated another server today, no errors there, too.
(I did a snapshot of the server through the 1&1 web UI console before upgrading the tools)
In addition, just to tell you, I've also uninstalled Cobian Backup which I really don't trust that much. I now dow my backups without the Volume Shadow Copy service with a simple script and WinSCP.
Update 2013-05-31:
Just as a future reference on how to get the Citrix Tools for Windows:

Go to the download page on the Citrix server or use this direct download page. (version 6.1 as of writing)
Find "XenServer-6.1-install-cd.iso" (If you don't find it, here is a direct link that hopefully does not expire).
Extract the ISO to a folder (e.g. simply double-click the ISO file on Windows 8 or use Iso Buster)
Find the folder "client_install"
Copy the content to your Windows 2008 Server.
Execute "windows-pvdrivers-xenlegacy.exe" by double-clicking.

It also seems that the previously disabled IPv6 got re-enabled by the installation process. So be sure to remove the "Internet Protocol Version 6 (TCP/IPv6)" check box again in the properties of the Citrix PV Ethernet Adapter #0.
Update 2013-06-14:
A newer version for the Citrix Xen Tools for Windows is available here (alternative download). This is an extract from the Hotfix XS61E010.
Update 2013-08-08:
There is a new version 6.2 available on this download page.
Update 2013-10-28:
We solved the issues by moving the server(s) away from the Xen hosting provider to another provider that has real hardware machines. (Google-translated blog article about the details for those interested)
Update 2014-05-13:
This is the link to the downloads of the Xen Tools that my hosting provider officially told me by email.
Answer: Short answer: no, it is not. From a recent RackSpace KB article possibly outlining the root cause of your problem:

Uninstalling the existing XenServer Tools software will render your server inaccessible.

This is due to the simple fact that the XenServer tools contain paravirtualized drivers (networking, storage) necessary for the virtual system to function correctly. Also:

An earlier version of the XenServer Tools software [...] has been found to cause server instability in rare cases. [...]
If the listed version is less than 6.0-58937 you should upgrade.
Comment: @UweKeim the proper way would involve asking 1&1 support for an updated version. You could refer them to the thread in the Citrix forums you've linked and to the Rackspace KB article and indicate that you suspect that your machines might be affected by a bug resolved in a more recent XenServer tools release. If this is not feasible, download the current XenServer release ISO from the [Citrix downloads](http://www.citrix.com/downloads/xenserver.html), [extract the tools from the ISO](http://forums.citrix.com/message.jspa?messageID=1376222) and check if the newer version resolves your problem.
Comment: @UweKeim important: installing a newer version of XenServer tools all on your own likely puts your servers into a state which would be considered "unsupported" by 1&1. Make sure you have a backup or a snapshot to revert to, should things go bad.
Comment: Is there some official download for the Tools or could I use the RackSpace one?
Comment: Thanks a lot! I'll take a snapshot before proceeding. And I'll mark your answer as "accepted", because I do think it is phantastic!


How to Access Files on my computer through Docker

Question: I am running Docker on my Windows 10 Home computer. I am trying to run the following code
 $ docker run -i -t -v /Users/Maddy/Desktop/Docker:/home bcain/lensing /bin/bash

which gives me the following
 DOCKER-lensing >

which then I can input the program I need to run (lenstool) that uses a file on my computer (MACS0417.par) which lives on my computer in /Users/Maddy/Desktop/Docker
Docker-lensing > lenstool MACS0417.par -n

which then gives me
You are running openMP version of lenstool with 1 threads
You can change the number of threads by set environment variable OMP_NUM_THREADS
ERROR: file MACS0417.par not found

The path to the files I want to access from my computer was specified with
-v /Users/Maddy/Desktop/Docker

I have researched other similar questions that aloud me to check to see if my local drive was successfully located under docker volume and It is.
to check this I did the following:
docker volume ls

which reads
DRIVER                 VOLUME NAME
local                   UsersMaddyDesktopDocker

Am I missing something? I am a beginning coder and begining Docker user. Thank you for your time and I probably left some vital information out so please ask what other information you need. Thank you in advance,
-Maddy
UPDATE May 22nd 2018-
I have looked up and followed the directions for docker compose. I am now trying to edit the volumes but am not quite sure how I would go about doing this. The code I have in my yml file so far is this
version: '3'
services:
  web:
    build: .
    ports:
     - "5000:5000"
    volumes:
     - .:/code
  redis:
    image: "redis:alpine"

I understand that I need to add something under volumes but I am not sure what I should put? (I am currently looking more into this but if anyone can guide me more I would be very appreciative!)
Answer: If you want to mount anything then you will have to map it from your local to the desired location on the container.For that you need to create a docker compose file , inside that yaml there is place holder called volumes there you need to specify the location of  local file : to the place in the container. You can search for docker compose documentation and you will get an idea.
Comment: Ok thank you for your help! I have looked up and followed the directions on the docker compose documentation and will add more of my questions about this above


Measure $\mu$ is 0.

Question: I am reading the paper of Balazard ,Saias and Yor. Let, $$f(z)=(s-1)\zeta(s) $$ where $s=\frac{1}{1-z}$ and $\zeta(s)$ denotes the Riemann zeta function. Denote by $$\exp\left[\int_{-\pi}^{\pi}\frac{e^{i\theta}+z}{e^{i\theta}-z}d\mu(\theta)\right]$$ the singular interior factor of $f.$
Denote by $$f^*(e^{i\theta})=\lim_{r\to 1^-}f(re^{i\theta})$$
Then by Generalised Jensen's formula $$\frac{1}{2\pi}\int_{-\pi}^{\pi} \log|f^*(e^{i\theta})|d\theta=\log|f(0)|+\sum_{|\alpha|<1,f(\alpha)=0}\log\frac{1}{|\alpha|}+\int_{-\pi}^{\pi}d\mu(\theta)$$

The measure $\mu$ associated to the singular interior factor of $f$ is 0. For this it suffices to reuse the argument developed by Bercovici and Foias for the interior factor of the functions $(\theta-\theta^s)\zeta(s)\frac{(s+\frac{1}{2})}{s}$

Question How does the measure $\mu$ associated to the singular interior factor of $f$ is $0$?.
Comment: Welcome to MSE! Your question is a good one, but a complicated one. Oftentimes it takes a day or two or three for a tricky question to be answered, and this one has only been up for an hour! There's no need to spam the comments with requests for an answer.
Comment: @HallaSurvivor Thank you for your kind advice. I will keep this in mind.
Comment: Please answer. I will happily give it a check mark.
Comment: Is there another answer by using the method used by Bercovici and Foias??
Answer: This result involves a bunch of theorems in Hardy Space theory which can be found in the classic references by Duren or Garnett (chapter II especially)
I will quote the relevant theorems and then explain how they imply the result:

If $f \in H^p(\mathbb D), p>0$, then $f$ has non-tangential finite limit on the unit circle ae $d\theta$; if we call that $f^*(e^{i\theta})$, one has $\log |f^*| \in L^1(d\theta), |f^*| \in L^p(d\theta)$

There is a (unique up to constants of modulus one) decomposition $f=BSF$ where $F$ is outer (non-zero and determined by $\log |F^*|=\log |f^*|$), with $|F^*|=|f^*|$ ae, $B$ is a Blaschke product with the zeroes of $f$ inside the unit disc and $S$ is a singular inner function which is determined by a positive singular measure (wr $d\theta$) $\mu$; both $|B^*|=|S^*|=1$ a.e. $d\theta, |B(z)|, |S(z)| <1, |z|<1$ (unless either is trivial so identically $1$)

If $f$ is analytically continuable across some arc $I$ of the unit circle, then $B,S,F$ are so too (and of course vice versa) which concretely means that $B$ has no zeroes accumulating there and the measure $\mu$ has support disjoint from $I$

If the singular factor is non-trivial (ie measure $\mu \ne 0$, so $S$ is not $1$), then there is a point $e^{i\theta}$ for which $f(z) \to 0, z \to e^{i\theta}$ non-tangentially; this is very easy to see when $\mu$ is a point mass at some $e^{i\theta}$ so $S(z)=e^{-c\frac{e^{i\theta}+z}{e^{i\theta}-z}}, c>0$ hence $S$ decays exponentially at $e^{i\theta}$ while $F$ cannot increase too much since $F^*$ is in some $L^p$

Now for $f(z)=(s-1)\zeta(s), s=\frac{1}{1-z}$, one easily shows that it is in $H^p$ for all $p<1/2$ so it has a decomposition $f=BSF$ as above; we know that $(s-1)\zeta$ is analytically continuable across the finite part of $\Re s =1/2$ which corresponds with $f$ being so across $|z|=1, z \ne 1$; by Theorem 3 above, it follows that the singular measure $\mu$ which determines $S$ is concentrated at $1$ or trivial. If we were in the first case we would get $\lim_{r \to 1, r<1}f(r)=0$ (Theorem 4 above)
But now $x=\frac{1}{1-r}>0, x\to \infty, r \to 1$ and  $f(r)=(x-1)\zeta(x)$ by defintion; but this would mean $\lim_{x \to \infty, x>0}(x-1)\zeta(x)=0$ and that is of course not true as the limit is infinity; hence $S=1$ and the measure $\mu$ is zero. Incidentally $B=1$ is equivalent of course with RH so $f$ is outer iff RH is true
Comment: edited to make it that clear
Comment: Thanks a lot. Why does $\lim_{r \to 1, r<1}f(r)=0$?
Comment: theorem 4 in the post - edited again to make that clear; the singular factor decays exponentially then, while the modulus cannot increase too fast - see references for rigorous proof)
Comment: $\lim_{x \to \infty, x>0}(x-1)\zeta(x)=0$ and that is not true as the limit is infinity; hence $S=1$. How is $S=1$?
Comment: the measure $\mu$ is either concentrated at $1$ and then $S(z)=e^{-c\frac{1+z}{1-z}}, c>0$ or the measure $\mu$ is trivial (identically zero) so $S=1$; we want to prove the latter as per Balazard et others and we show that the former (measure non-zero concentrated at $1$) leads to a contradiction that a limit is, on one hand, zero from Hardy Space theory and on the other hand infinity from zeta function theory
Comment: Thanks. Why are we taking $lim_{ r \to 1, r<1} f(r)$. Why are we taking $r \to 1$? $f(z) $ has a singularity at $z=1$. So are we taking $r=|z| $ or $r=z$?
Comment: Because we so choose to get the required contradiction; by general theory we are allowed to take non tangential limits and radial limits are the simplest such, so they definitely qualify
Comment: I am asking that why are we taking limit as $r \to 1, r<1$ of $f(r)$? What is $r$ here?
Comment: not sure of the question $z=r, 0 \le r<1$ is in the unit disc so we can take the limit $r\to 1$ of $f(r)$; in general of course it may or may not exist for an arbitrary function defined in the unit disc; here we know that if the singular measure is nontrivial, this limit must be zero
Comment: So here $z=r$ or $|z|=r$?
Comment: $z=r$ as we take a radial limit; more generally we could take a non tangential limit but that is unnecessary here
Comment: So if $f(z)=\frac{z}{i-z}\zeta(\frac{1}{i-z})$ then $r=i$?
Comment: I mean $f(z)=\frac{z}{i-z}\zeta(\frac{1}{i-z})$ has a singularity at $z=i$ , so $r=i$?
Comment: Please reply. This is my last doubt.
Comment: If $r =i \in \mathbb{C}$ then we cannot write $r<1$ in the limit. As complex numbers don't have ordering.
Comment: your use $ir$ that tends radially to $i$
Comment: Are you saying that $\lim_{r\to 1, r<1} f(ir)$?
Comment: Are you saying that $\lim_{r \to 1, r<1} f(ir)$? I will give your answer a check mark after this doubt.
Comment: do you mean $\lim_{r\to 1, r<1}f(ir)$?
Comment: wait - $1/(i-z)$ doesn't send the unit circle into the critical line but into the line $\Im s =-1/2$ so one would need $f(z)=\frac{z}{i-z}\zeta(\frac{i}{i-z})$ to see stuff about the critical line
Comment: So the limit is $\lim_{r\to 1, r<1} f(ir)$? If we had this hypothetical function.
Comment: yes - nothing changes - this is a rotation of the other function
Comment: $f(z)=(s-1)\zeta(s)$ where $s=\frac{1}{1-z}$ so $f(z)$ has a singularity at $z=1$. So in the limit $\lim_{r\to 1, r<1}f(r)$ why we are taking only $r\to 1$.
Comment: because we CHOOSE that; we have a goal - prove that $\mu =0$ and a method - show that if $\mu \ne 0$ we get a limit zero on one hand and same limit non-zero on the other hand; choosing $r \to 1$ gives us the second part, Hardy space theory gives us first part
Comment: Thanks a lot. Can't we prove $\mu=0$ by using the method used by Bercovici and Foias?
Comment: this is their method adapted to this situation - they discuss a different function which is related to $\zeta$ but which appears in a different more general criterion about critical strip zeroes (Beurling criterion about $L^p$ density of some function space corresponding with no zeroes in $\Re s >1/p$ ); a few deeper Hardy space results like Beurling invariant space theorem is needed there
Comment: Thank you so much. I am giving your answer a check mark. Can you please give a reference for $\mu=0$?
Comment: Which book should I refer for Theorem 4? Duren? Or Garnett?
Comment: not sure about your question for a reference - Balazard et others paper will do as they use the result; the proof above is based on the Bercovici Foias reference but I made it explicit to include the theorems one uses as the article of Foias and Bercovici is written for professional mathematicians so all this stuff is well known and actually it is fairly trivial stuff for the paper's level which has some difficult non-trivial stuff; Balazard et others paper is on the other hand fairly elementary but highly unlikely to lead anywhere as RH goes beacuse of that
Comment: Please give me a reference for Theorem 4.
Comment: I gave you a proof sketch but look in  Garnett chapter II
Comment: So in Garnett Chapter 2 Theorem 4 is given? Can you please tell me the page number. Please.
Comment: Is it theorem 6.2 page 73?
Comment: it follows from Theorem 6.2 page 73 (which implies applying l'Hopital enough times that $S(r)/(1-r)^n \to 0, r \to 1$ (in the case here of $\mu$ concentrated at $1$ but non-trivial) while $|(1-r)^3F(r)|$ is bounded since $F \in H^{1/3}$ (actually one can easily show that $|(1-r)^3F(r)| \to 0$)
Comment: In , $S(r)/(1-r)^n$ why are we dividing by $(1-r)^n$?
Comment: $f(r)=S(r)F(r)B(r), |B(r)| \le 1$ so $f(r)=((1-r)^3F(r))\frac{S(r)}{(1-r)^3}B(r)$ and now all terms are bounded, while the middle one goes to zero, so the limit is zero - note that $F(r)$ is unbounded (actually $O(1/(1-r)^2)$ by general zeta theory) but $S(r)$ would decrease very fast, faster than any $(1-r)^n$ if it were nontrivial
Comment: Thank you so much. I am indebted to you for your kind gesture and help. Which book should I follow if I want to study Hardy spaces having no background of it?
Comment: Duren is the standard (and easiest reference) and I always keep it handy; Garnett is good but more advanced; since the subject is so vast, it also depends on what you want to get; Chapters 1-3 in Duren are excellent for a quick intro
Comment: Thanks again. It's very helpful. I will follow it religiously
Comment: You have answered many questions on MSE but you have not asled a single question. Why?

Measure $\mu$ is 0.


Janela customizada diferente da padrao em python

Question: oi, gostaria de um exemplo de janela em Python, diferente da padrão, como eu faço isso ???
este é o meu codigo:
from tkinter import =
root = Tk()
theLabel = Label(root, text="This is too easy")
theLabel.pack()
root.mainloop()

Answer: Não tenho certeza se entendi o diferente, mas você pode mudar o tema das janelas para utilizar elementos nativos do sistema (X11, Windows, etc.) com o comando from ttk import *:
Exemplo:
Sem o ttk:

Com o ttk:

Exemplo gerado com:
from Tkinter import *
from ttk import *  # basta acrescentar ou retirar esta linha
root = Tk()
Frame(root)
if (root is not None):
    root.title("Teste")
    theLabel = Label(root, text="This is too easy")
    theLabel.pack(fill='both')
    sair = Button(root, text="Sair", command=quit)
    sair["state"] = "normal"
    sair.pack(fill='both')
    root.mainloop()


simple_form - set default text for "select" element

Question: I am using simple_form gem in order to create my forms. In one case, I am using "collection" method in order to build a select input element.
What I want, is to set a default text of this "drop down" as a selected option, but the option should not be selected.
For example, if I have a languages list, I want to have a selected options with text "Select language". It's should not be selected as well, in order for validates:presence of the field to work.
Answer: :prompt option is responsible for that.
<code>= simple_form_for :user do |f|
  = f.input :lang, collection: ["Ru", "En"], prompt: "Select language"
</code>


North American expansion team reaching Championship final in inaugural year

Question: The Las Vegas Golden Knights have reached the Stanley Cup finals in the 2017 - 2018 season after beating Winnipeg Jets in the western conference finals. This has been a big surprise as the Knights joined the NHL on the same season and most expansion teams don't even qualify for playoffs on their first year. But the Knights have a chance to be the first NHL team to win the Stanley Cup in their first year.
Has there been any other North American major league teams that made it all the way to the cup finals on their first year? If so list the team, league, year, and the outcome of the finals.
Answer: Baltimore Stallions:
In 1994 the Baltimore Stallions made it to the Grey Cup finals, in their inaugural year, making them the most successful American team in CFL history. Despite not winning the 1994 Grey cup, they lost by 3 points to the BC Lions, they went on to win the Grey cup in 1995 against  Calgary Stampeders
Chicago Fire Soccer Club:
In 1998 the Chicago Fire Soccer Club began as one of the Major League Soccer's (MLS) first expansion teams. That year, they won both the MLS Cup as well as the U.S Open cup, achieving a double, where a soccer team has won a country's top tier division and its primary cup competition in the same season.
Minneapolis Lakers:
The 1947-48 season was Minneapolis Lakers inaugural season in the NBA and they won the National Basketball League championship in a 3-1 series final against the Rochester Royals. The Lakers went on to win their division and championship the following 1948-49 season as well.
Answer: In 1949 The AAFC(All-American Football Conference) closed it's doors or went bankrupt and the NFL invited the Browns, and 2 others, into their league in 1950. In the Browns first Season they went 10-2 and beat the LA Rams(on a last minute field goal) 30-28 to win their first of four National Football League championships. While not truly an "expansion" team it was their first year in the NFL.
Link
Answer: For the 1967-68 season, the NHL expanded from 6 to 12 teams. All the new teams were grouped in the West Division. The division champions were the Montreal Canadiens (original 6) and the St. Louis Blues (expansion team). The Canadiens won the Stanley Cup Finals 4-0.
The 1973-4 Flyers were the first of the expansion teams to win the Cup.
Comment: Thanks for the answer, can you also provided sources to your answer


host can not recognized in postgres

Question: We have seen a issue in log
FATAL:  lock file "/tmp/.s.PGSQL.5432.lock" already exists
HINT:  Is another postmaster (PID 4696) using socket file "/tmp/.s.PGSQL.5432"?
LOG:  could not bind IPv4 socket: Address already in use

We have deleted /tmp/.s.PGSQL.5432.lock
We restarted the postgres service the service restarted
But the psql -h localhost -d database -U newuser
shows error role 'newuser' does not exists
but if we connect without host
psql -d database -U newuser

It worked, How can We work with host options ?
Is there we ,missing somthing after deleting tmp file?
Comment: well, restart machine and try.
Comment: Note this user's very similar post http://stackoverflow.com/q/31546303/398670
Answer: Same as the last one, you have two instances of PostgreSQL running on the machine.
You delete the socket file rather than shutting down the instance. This allows your second instance to start, but it's only listening on the unix socket. Presumably listen_addresses is unset/empty so it doesn't attempt to bind to a TCP/IP socket, since it'd fail if it tried and port 5432 was already in use.
The other instance is still running and still listening on port 5432 for TCP/IP connections. When you specify -h localhost you get a TCP/IP connection instead of the default unix socket connection, so you are connecting to the other instance of PostgreSQL on your system.
All your problems are caused by going around deleting and killing things rather than identifying the underlying problem - the second PostgreSQL instance - and addressing that.
Comment: I found
listen_addresses = '127.0.0.200, localhost' # what IP address(es) to listen on;
Comment: Sure, but you have two instances of PostgreSQL running.  Figure out what's starting the other instance and disable it. How to do that depends on the OS you are using and how you installed PostgreSQL. If you're on Ubuntu for example, see https://help.ubuntu.com/community/PostgreSQL
Comment: Yes we found psql (8.4.20, server 9.4.4) our data is in 8.4 . How to disable 9.4?
Comment: @Debadatt **How to do that depends on the OS you are using and how you installed PostgreSQL**. So....

host can not recognized in postgres


setting horizontal panel to MGWT layout panel exactly center without considering device width

Question: I'm developing an app using mgwt.I'm having an horizontal panel which is added with two mgwt buttons. MGWT's layout panel is the parent(i.e;asWidget()returning layoutPanel). Now I want to make
my hPanel exactly center to the layout panel. I dont want to read device width and using margins anymore.I want to done this through styles. I've done as below.But not succeeded.
my current result is, hPanleButtons is displaying at left side of window but not at center.
<code>    DOM.setStyleAttribute(hPanelButtons.getElement(), "cssAlign", "center");
    DOM.setStyleAttribute(hPanelButtons.getElement(), "styleAlign", "center");
    DOM.setStyleAttribute(layoutPanel.getElement(), "cssAlign", "center");
    DOM.setStyleAttribute(layoutPanel.getElement(), "styleAlign", "center");
hPanelButtons.getElement().setAttribute("style", "align:center");
</code>
i tried using all above individually but no use. please help me on this.
Thanks in advance.
Answer: finally I achieved my goal.I'm posting the answer so that it'll be useful to people who are facing the same requirement. I used DOM style attributes for doing this. Here is my code:
<code>DOM.setStyleAttribute(hPanelButtons.getElement(), "marginLeft", "auto");
DOM.setStyleAttribute(hPanelButtons.getElement(), "marginRight", "auto");
DOM.setStyleAttribute(hPanelButtons.getElement(), "marginTop", "auto");
DOM.setStyleAttribute(hPanelButtons.getElement(), "marginBottom", "auto");
</code>
its working fine.


Pandas groupby and find row count difference where values of columns are interchanged

Question: I want to group this datafarme by col A and B and find the difference between the count where value of column B is column A and vice-versa.
Dataframe:

A
B

112
456

112
456

112
456

456
112

456
112

113
457

113
457

457
113

457
113

GroupBy Table:

A
B
count

112
456
3

456
112
2

113
457
2

457
113
2

Now Using this groupby table I want to compute the difference where colB == colA and colA == colB. Not sure how to get this expected result from the groupby table above
Expected Result:

A
B
Diff

112
456
1

113
457
0
Comment: @ignacioct Added details, does it make sense now?
Comment: I didn't understand what you are trying to achieve very well. Could you elaborate?
Comment: yes! I will give it a thought
Answer: I've developed a solution, but it is Python programming and it does not use a lot of Pandas tricks. Maybe somebody knows how to do it with Pandas magic and it is much more efficient. But, here goes my two cents:
First of all, I've reproduced your scenario:
<code>columnA = [112, 112, 112, 456, 456, 113, 113, 457, 457]
columnB = [456, 456, 456, 112, 112, 457, 457, 113, 113]

df = pd.DataFrame()
df["A"] = columnA
df["B"] = columnB

groupByTable = df.groupby(df.columns.tolist(),as_index=False).size()

groupByTable
</code>
Afterwards, the idea is to iterate through the rows of this dataframe, and if we find a tuple (A,B), and we had previously found the tuple (B,A), we compute the difference and save it in a dictionary. Finally, this dictionary is converted in a dataframe.
<code># Create a dictionary to know which elements has been visited
previousElements = {}

# And a dictionary for counting
diff = {}

# Iterate over rows
for index, row in groupByTable.iterrows():

    # Current row as a tuple
    currentTuple = (row["A"], row["B"])

    # Checking if we have visited the same tuple, but inverted
    if (row["B"], row["A"]) in previousElements:

        # As convention, we set the key for the diff dictionary as (smaller_value, larger_value)
        key = (row["B"], row["A"]) if row["B"] <= row["A"] else (row["A"], row["B"])

        # Calculating the diff and storing it in the diff dictionary
        diff[key] = abs(row["size"] - previousElements[(row["B"], row["A"])])

    # If we haven't see this tuple inverted, we store it in the previousElements dictionary
    else:
        previousElements[currentTuple] = row["size"]

# Now, we transform this dictionary in a pandas dataframe
outputDF = pd.DataFrame(columns=["A", "B", "diff"])

for key, value in diff.items():
    outputDF = outputDF.append({'A': key[0], 'B': key[1], 'diff': value}, ignore_index=True)

outputDF.head()
</code>
The result is the following:

A
B
diff

112
456
1

113
457
0


Proof about $z\cot z=1-2\sum_{k\ge1}z^2/(k^2\pi^2-z^2)$

Question: In Concrete Mathematics, it is said that
$$z\cot z=1-2\sum_{k\ge1}\frac{z^2}{k^2\pi^2-z^2}\tag1$$
and proved in EXERCISE 6.73
$$z\cot z=\frac z{2^n}\cot\frac z{2^n}-\frac z{2^n}\tan\frac z{2^n}+\sum_{k=1}^{2^{n-1}-1}\frac z{2^n}\left(\cot\frac{z+k\pi}{2^n}+\cot\frac{z-k\pi}{2^n}\right)$$
The trigonmetric identity is not hard, but I cannot understand the rest:

It can be shown that term-by-term passage to the limit is justified, hence equation (1) is valid.

How can we conclude that? Thanks for help!
Answer: This identity is also proven in this answer, but the limit of the trigonometric identity is a cute trick, too.
Concrete Mathematics claim:
For the limit claimed in Concrete Mathematics, we need a few things.
First, by inspecting the graph of $\frac{1-x\cot(x)}{x^2}$ for $-\frac{3\pi}{4}\le x\le\frac{3\pi}{4}$, we have
$$
\left|\frac1x-\cot(x)\right|\le|x|\tag{1}
$$
Next, the Mean Value Theorem says
$$
\begin{align}
|\cot(\delta+x)+\cot(\delta-x)|
&=|\cot(x+\delta)-\cot(x-\delta)|\\
&\le2\delta\sup_{[x-\delta,x+\delta]}\csc^2(\xi)\\
&\le\color{#C00000}{8\delta\,\csc^2(x)}\\
&\le\color{#C00000}{2\pi^2\delta/x^2}\tag{2}
\end{align}
$$
if $\color{#C00000}{2\delta\le|x|\le\frac{\pi}{2}}$.
Finally, note that since $0\le k< 2^{n-1}$, $0\le\frac{k\pi}{2^n}<\frac{\pi}{2}$
Using $(1)$, we get
$$
\begin{align}
&\left|\frac{z}{2^n}\left(\cot\left(\frac{z+k\pi}{2^n}\right)+\cot\left(\frac{z-k\pi}{2^n}\right)\right)-\left(\frac{z}{z+k\pi}+\frac{z}{z-k\pi}\right)\right|\\
&\le2\left|\frac{z}{2^n}\right|\frac{|z|+k\pi}{2^n}\tag{3}
\end{align}
$$
Using $(2)$, we get, for $2z\le k\pi$,
$$
\begin{align}
\left|\frac{z}{2^n}\left(\cot\left(\frac{z+k\pi}{2^n}\right)+\cot\left(\frac{z-k\pi}{2^n}\right)\right)\right|
&\le2\pi^2\left|\frac{z^2}{2^{2n}}\right|\left(\frac{2^n}{k\pi}\right)^2\\
&\le2\pi^2\left(\frac{z}{k\pi}\right)^2\tag{4}
\end{align}
$$
Estimate $(3)$ is used to control the difference between the series for small $k$, and $(4)$ to control the remainder in the sum of the cotangents for large $k$.
Pick an $\epsilon>0$, and find $m$ large enough so that $2z\le m\pi$ and
$$
\sum_{k=m}^\infty\frac{1}{k^2}\le\epsilon\tag{5}
$$
Then we have the following estimate for the tail of the sum
$$
\sum_{k=m}^\infty\frac{z^2}{k^2\pi^2-z^2}\le\frac43z^2\epsilon\tag{6}
$$
Combining $(4)$ and $(5)$ yields
$$
\sum_{k=m}^{2^{n-1}-1}\left|\frac{z}{2^n}\left(\cot\left(\frac{z+k\pi}{2^n}\right)+\cot\left(\frac{z-k\pi}{2^n}\right)\right)\right|\le2z^2\epsilon\tag{7}
$$
Summing $(3)$ gives
$$
\begin{align}
&\sum_{k=1}^{m-1}\left|\frac{z}{2^n}\left(\cot\left(\frac{z+k\pi}{2^n}\right)+\cot\left(\frac{z-k\pi}{2^n}\right)\right)-\left(\frac{z}{z+k\pi}+\frac{z}{z-k\pi}\right)\right|\\
&\le2\left|\frac{z}{2^n}\right|\frac{m|z|+m^2\pi/2}{2^n}\tag{8}
\end{align}
$$
Just choose $n$ big enough so that $(8)$ and $\displaystyle\left|\frac z{2^n}\cot\frac z{2^n}-\frac z{2^n}\tan\frac z{2^n}-1\right|$ are each less than $\epsilon$ and we get that the term-by-term absolute difference is less than
$$
\left(\frac{10}{3}z^2+2\right)\epsilon\tag{9}
$$
Comment: Well, but I wonder why term-by-term passage is justified. Peter's proof is just using squeeze theorem, but I don't know whether there's a systematical theory to explain it, maybe uniform convergence?
Comment: @FrankScience: sorry for taking so long, but I hope this answers your question.
Answer: NOTE: This is incomplete. A tighter bound should be produced. Anyone able to do so is free to edit and add it.
For $x$ near the origin, $\cot x \sim \dfrac{1}{x}$. Since $\dfrac{1}{2^n}\to 0 $ we can use this. More precisely,
$$\frac{1}{x}-1<\cot x <\frac{1}{x} $$
Namely, we can dissect
$$z\cot z=\frac z{2^n}\cot\frac z{2^n}-\frac z{2^n}\tan\frac z{2^n}+\sum_{k=1}^{2^{n-1}-1}\frac z{2^n}\left(\cot\frac{z+k\pi}{2^n}+\cot\frac{z-k\pi}{2^n}\right)$$
into
$${A_n} = \frac{z}{{{2^n}}}\cot \frac{z}{{{2^n}}} = \cos \frac{z}{{{2^n}}}\frac{{\frac{z}{{{2^n}}}}}{{\sin \frac{z}{{{2^n}}}}} = \cos u\frac{u}{{\sin u}} \to 1$$
$${B_n} = \frac{z}{{{2^n}}}\tan \frac{z}{{{2^n}}} = \frac{z}{{{2^n}}}\sin \frac{z}{{{2^n}}}\frac{1}{{\cos \frac{z}{{{2^n}}}}} = \frac{{u\sin u}}{{\cos u}} \to 0$$
where $u \to 0$.
Then we have
$$\eqalign{
  & \frac{{{2^n}}}{{z - k\pi }} + \frac{{{2^n}}}{{z + k\pi }} - 2 < \left( {\cot \frac{{z + k\pi }}{{{2^n}}} + \cot \frac{{z - k\pi }}{{{2^n}}}} \right) < \frac{{{2^n}}}{{z - k\pi }} + \frac{{{2^n}}}{{z + k\pi }}  \cr
  & \frac{z}{{z - k\pi }} + \frac{z}{{z + k\pi }} - \frac{z}{{{2^{n - 1}}}} < \frac{z}{{{2^n}}}\left( {\cot \frac{{z + k\pi }}{{{2^n}}} + \cot \frac{{z - k\pi }}{{{2^n}}}} \right) < \frac{z}{{z - k\pi }} + \frac{z}{{z + k\pi }}  \cr
  & \frac{{2{z^2}}}{{{z^2} - {k^2}{\pi ^2}}} - \frac{z}{{{2^{n - 1}}}} < \frac{z}{{{2^n}}}\left( {\cot \frac{{z + k\pi }}{{{2^n}}} + \cot \frac{{z - k\pi }}{{{2^n}}}} \right) < \frac{{2{z^2}}}{{{z^2} - {k^2}{\pi ^2}}} \cr} $$
Comment: Summing up equation (5) and use squeeze theorem. Thanks. Incidentally, your $\LaTeX$ with nested $\lbrace\cdots\rbrace$ is awful, so I've edited your post.
Comment: I suggest that you be famailiar with $\LaTeX$. I find it more convenient to use $\LaTeX$ directly if you can spend half an hour learning it. Some tutorials are useful, say, lshort.
Comment: @FrankScience OK, but don't crop my answer. Thanks.
Comment: @FrankScience I don't nest the parenthesis, MathType does. It'd have been more prudent to ask, you know.
Comment: @FrankScience I know some $\LaTeX$ but I can't waste $10$ mins coding it, thanks anyways.


Python + Machine Learning : string matching problem

Question: I have been given one problem to solve:
The problem is explained below:
The company maintains a dataset for specifications of all the products (nearly 4,500 at present) which it sells. Now each customer shares the details (name, quantity, brand etc.) of the products which he/she wants to buy from the company. Now, the customer while entering details in his/her dataset may spell the name of the product incorrectly. Also a product can be referred by many different ways in the company dataset. Example : red chilly can be referred as guntur chilly, whole red chilly, red chilly with stem, red chilly without stem etc.
I am absolutely confused about how to approach this problem. Should I use any machine learning based technique? If yes, then plz explain me what to do. Or, if it is possible to solve this problem without machine learning then also explain your approach. I am using Python.
The challenge : customer can refer to a product in many ways and the company also stores a single product in many ways with different specifications like variations in name, quantity, unit of measurements etc. With a labeled dataset I can find out that red bull energy drink(data entered by customer) is red bull (label) and red bull(entered by customer) is also red bull. But what's the use of finding this label? Because in my company dataset also red bull is present in many ways.  Again I have to find all the different names of red bull in which they present in company dataset.
My approach:
I will prepare a Python dictionary like this:
<code>{
"red chilly" : ['red chilly', 'guntur chilly', 'red chilly with stem'],
"red bull" : ['red bull energy drink', 'red bull']
}
</code>
Each entry in the dictionary is a product. whose keys are the sort of stem names of the products and the values are the all possible names for a product. Now customer enters a product name, say red bull energy drink. I will check in the dictionary for each key. If any value of that key matches, then I'll understand that the product is actually red bull and it can be referred as red bull and red bull energy drink, both ways in the company dataset. How's this approach ?
Comment: Check out this link:
https://medium.com/@adriensieg/text-similarities-da019229c894
And this: https://github.com/Shikhargupta/Machine-Learning-and-Pattern-Recognition
Answer: This problem was like me and I had to find the keyword to solve these issues.
The keyword: Fuzzy String Matching (Approximate String Matching).
Particularly the [Levenshtein distance][1] to determine the similarly of two string:
Example: red chilly vs red chilly using Levenshtein distance. Leven_distance(string1, string2) = 0.8.
You can also reference these links:

https://stackoverflow.com/questions/5859561/getting-the-closest-string-match?rq=1
https://www.analyticsvidhya.com/blog/2021/07/fuzzy-string-matching-a-hands-on-guide/
https://stackoverflow.com/questions/10383044/fuzzy-string-comparison
https://stackoverflow.com/questions/14260126/how-python-levenshtein-ratio-is-computed
#Fuzzy_string_matching #Approximate_string_matching
[1]: https://en.wikipedia.org/wiki/Levenshtein_distance


Applying the Benjamini-Hochberg correction with a low number of comparisons

Question: I want to run an experiment with 4 variants (3 and a control), comparing the 3 variants to the control. I want to correct the alpha for multiple comparisons. I have 2 ways:

Benjamini-Hochberg procedure
Bonferroni correction

What are the trade-offs of using any of the two?
Comment: For comparing three treatments to one control, check out the Dunnetts test, which is designed for exactly that scenario.
Answer: These procedures address multiplicity in very different ways.
Bonferroni but also others like Holm's step-down, Hochberg's step-up, and Hommel's step-up will (in order from least to most powerful) control the family-wise error rate, i.e. they will ensure that the type I error rate is at most $\alpha$ across all $n$ tests, so you'll just have a single type I error with probability $\alpha$. This is appropriate in a confirmatory setting. Bonferroni is the easiest to implement but also the most conservative, it's also important to note that Hochberg and Hommel are only valid under at most weakly positive (and ideally no) correlation of your tests.
Benjamini-Hochberg (and Benjamini–Yekutieli, Storey-Tibshirani) will control the false discovery rate, i.e. they ensure that out of $n$ tests at most a fraction $\alpha$ are a type I error, not just a single one. This is usually done in more exploratory settings where possible promising findings are to be replicated. Benjamini-Hochberg in particular also assumes at most very weak dependence of tests, this assumption is relaxed in the other FDR methods. An issue here is that they don't work well if you only have a small number of tests (and I would call 4 small in this context), this has to do with having to consider division by 0 as 0 in the martingale theory that underpins BH - I'm not too familiar with the details though. The key point is that this is a minor concern when $n$ is large, but not so when $n$ is small making FDR a completely meaningless concept for $n=1$.
In your situation I would recommend a FWER procedure.
Comment: Small addition: Every procedure that controls FWER automatically also controls FDR. See Goemann & Solari (2014): 10.1002/sim.6082 for the details.


How to add feature values from one csv to another based on another feature rows

Question: I have 2 csv files as below. I have to add the Lat and Long features from one csv to another based on the ID

Based on the ID, I have to add the columns Latitude and Longitude to CSV 1 (ID 1 has different values and ID 2 has different values and so on.
Can anyone please tell me how to do this using python?
Answer: I recommend you use the pandas library. If you've not come across it before, it's a very widely-used library for data manipulation that makes this task very easy. However, it's not part of the standard library that comes packaged with Python, so depending on your environment you may need to install it using PyPi. Guides like this might help if you've not done that before.
With pandas installed in your environment, you can run the following code (substitute in your file paths for csv1.csv and csv2.csv).
import pandas as pd

# Load the csv files into dataframes and set the index of each to the 'ID' column
df1 = pd.read_csv('csv1.csv').set_index('ID')
df2 = pd.read_csv('csv2.csv').set_index('ID')

# Join using how='outer' to keep all rows from both dataframes
joined = df1.join(df2, how='outer')
print(joined)

# Save to a new csv file
joined.to_csv('joined.csv')

I made some simple sample data to demonstrate the result of running the code:
csv1.csv:
ID,my_feature
1,banana
2,apple
3,pear

csv2.csv:
ID,latitude,longitude
1,7,-4
4,10,15

Printed output:
       my_feature  latitude  longitude
ID
1      banana       7.0       -4.0
2       apple       NaN        NaN
3        pear       NaN        NaN
4         NaN      10.0       15.0

Output to joined.csv:
ID,my_feature,latitude,longitude
1,banana,7.0,-4.0
2,apple,,
3,pear,,
4,,10.0,15.0


Train/test split and leave-one-out

Question: I need to build and evaluate a classifier over 100 examples. There are reasons for which I need to use a leave-one-out cross validation approach, and I have a doubt on how I should proceed.
Which, among the 2 following options, is the correct one?
a) perform a LOO by creating 100 folds over 1-VS-99 and consider the average performance on the 100 folds as the performance for my classifier
b) split the 100 examples on 70 for training and 30 for test, then apply the LOO strategy only to the 70 training examples (with 1-VS-69 folds), and then evaluate the model by applying it on the 30 test examples
Comment: What is the purpose of the LOO on the training in the second case?
Comment: I was thinking to keep a set of examples just for testing purposes, completely separated from the training process. Similarly as suggested in this flow diagram on sklearn documentation: https://scikit-learn.org/stable/_images/grid_search_cross_validation.png . Does it make sense?
Comment: If you have hyper-parameters to tune, yes.
Comment: so option b without the need of fine tuning hyper-paramters doesn't make sense?
Answer: Cross validation is commonly used for hyper-parameter (HP) tuning or having a more stable test performance estimate. If you're to tune some HPs in your algorithm, case (b) definitely makes sense, though I'd advise an outer CV for the test since dataset is small. But, if there is no HP to optimize and you only want to evaluate the test performance, case (a) is better (has less variance), especially in small dataset like yours, because test performance will not be affected by your test set choice.
Comment: What do you mean by outer CV? I also have a small dataset (20 samples) trying to solve a binary classification prediction problem that is moderately unbalanced(Class 1 = 8, Class 2 = 12). My understanding is that I have to use LOOCV because of the super small dataset but I am not sure if I should use it on whole dataset or train dataset. Help would be greatly appreciated. I'm hypertuning and more using TPOT an autoML algorithm that uses GAs to find best ML pipeline.
Comment: @AchilleasPavlou here outer CV is for performance eval, and inner CV is for model & feature selection. Read "nested CV" in the forum or other sources for better understanding. I think TPOT does the inner part for you (with the training fold), and you'll apply outer cv (i.e. use TPOT several times)

Train/test split and leave-one-out


CoreOS, Docker networking, more than one bridge?

Question: I have a server with 4 ethernet-cards. With the switching hardware I put all 4 cards in different VLANs. With the default networking on CoreOS I get single bridge for the containers, with a private IP address range. And besides that, I can control the hosts networking, and forward ports.
What I want is to control which container connects to which physical port, without exposing the hosts networking stack to the containers. I thought of multiple bridges: one for each physical card, making the physical port of each card to a member of the respective bridge, and connect containers to the bridge I specify. I would have control over the VLAN membership of the containers.
But i'm not sure if docker can handle this. I know how to connect Docker to a custom bridge, but I couldn't find any hints how to connect it to several bridges. Can it do something like that? Is there any other solutions on how to control which VLAN my containers belong to?
thanks,
__
s.
Comment: This doesn't solve your problem, but I often see individual ports max out. If you're connecting to the same physical network, might you see better port utilization if you configure bonding, and then do the vlans over the bond? That could also provide some redundancy in case one of the ports fail (or are otherwise disabled)
Answer: It's not an easy solution but its doable with openvswitch running on your host machines. You want to do something like
http://fbevmware.blogspot.com/2013/12/coupling-docker-and-open-vswitch.html