Independence of $\min(X,Y)$ and $\max(X,Y)$ for independent $X$, $Y$?

Question: What's the reasoning for checking the independence of
$$\min(X,Y)$$ and $$\max(X,Y)$$ for independent r.v.s $X,Y$?
Is it possible that $\min$ and $\max$ both select the same r.v. in which case they would be dependent? No, because that would mean that $X=Y$, i.e. $X$ and $Y$ would not be independent.
Does the independence regarding functions of independent r.v.s apply here? Yes? In that case $X,Y$ independent $\implies$ $\min(X,Y),\space \max(X,Y)$ independent.
Comment: It doesn't really make sense to say two random variables are dependent "when such and such happens."  They're either independent or not, no matter what values they happen to take on.  I'll also point out that $X = Y$ does not imply they're dependent because they could both equal the same constant with probability one.
Comment: I don't know why people are downvoting this. Independence is both incredibly important and counter-intuitive. +1
Comment: +1  upvoting on the ground that questions leading to interesting answers must have some merit!
Comment: @mavavilj A deterministic r.v., i.e. an r.v. which equals a constant with probability one, is independent of itself.  You can check that from the definition of independence.  You appear to be relying on a layman's definition of dependence (non-independence) which does not properly address this case.
Comment: @dsaxton I've thought that a r.v. is always dependent with itself?
Comment: Define image(X)  (I would think it means the image of the function from the outcome space, i.e., the set of values the random variable may take, but then why would $1$ be special compared to any other number?)
Answer: If $X$ and $Y$ are independent continuous random variables, then $\max(X,Y)$ and
$\min(X,Y)$ are independent random variables if and only if one of the
following two conditions holds:

$P(X > Y) = 1$
$P(X < Y) = 1$

Note that the above conditions mean that $P(X=Y) = 0$ but this does
not mean that $(X=Y)$ is the same as the impossible event, that is,
there is no outcome $\omega$ in the sample space for which
$X(\omega) = Y(\omega)$. Those thoroughly confused by this notion
should recall that they might have been told that
for a continuous random variable $V$,
$P(V = a) = 0$ for all real numbers $a$ even though it is manifestly
true that $V$ can take on value $a$ for some particular $a$,
and if they have
swallowed that whopper, then accepting that $P(X=Y)=0$ does not
mean that the event $(X=Y)$ will never occur is just a small
additional stretch of their credulity.
When $X$ and $Y$ are independent discrete random variables, then
the above condition needs to be relaxed slightly, and it is possible
to have $P(X=Y) > 0$. For example, if $(X,Y)$ takes on values
$(1,0), (2,0), (1,1), (2,1)$ with equal probability $\frac 14$, then
$(\min(X,Y), \max(X,Y))$ takes on values $(0,1), (0,2), (1,1), (1,2)$
with equal probability $\frac 14$ and thus $\min(X,Y)$ and
$\max(X,Y))$ are
independent. A little thought will show that $(\min(X,Y), \max(X,Y))$
is the same as $(Y,X)$ in this case. A little further thought will
show that if $P(X=Y)>0$, then it must be that there is a unique
$a$ such that $P(X=a, Y= a) >0$ and that for all other real numbers
$b$, $P(X=b, Y= b) =0$. For independent discrete random variables
$X$ and $Y$, the probability mass function has nonzero values at
all points on a rectangular grid, and this grid must be strictly
below or strictly above the line $x=y$ or must have only one point
(the upper left corner or the lower right corner) on the line $x=y$;
the point $(1,1)$ in the example above.

An interesting follow-up question is:
When  $X$ and $Y$ are dependent random variables, is it possible for
$\max(X,Y)$ and $\min(X,Y)$ to be independent random variables?
to which the answer is Yes, it is possible.  Consider the case when
$X$ and $Y$ are jointly continuous random variables uniformly
distributed on the set
$$\left\{(x,y)\colon \frac 12 \leq x \leq 1,
 0 \leq y \leq x-\frac 12\right\}
\bigcup
\left\{(x,y)\colon 0 \leq x \leq \frac 12,
 \frac 12 \leq y < x + \frac 12\right\}$$
The joint density of the minimum and maximum can be worked out
as described here
where it is shown that if $Z = \min(X,Y)$ and $W = \max(X,Y)$,
then
$$f_{Z,W}(z,w) =  \begin{cases}
f_{X,Y}(z,w) + f_{X,Y}(w,z), & \text{if}~w > z,\\
\\
0, & \text{if}~w < z.
\end{cases}
$$
Applying this, it can be shown that the joint density of
$Z$ and $W$ is uniform on interior of the square with vertices
$(0,\frac 12), (\frac 12, \frac 12), (\frac 12, 1),
(0,1)$, and so $Z \sim U[0,\frac 12]$ and $W \sim U[\frac 12,1]$
are independent random variables.
Comment: So do the first two conditions say the same as $X≠Y$?
Comment: @mavavilj What do you mean by $X\neq Y$ when $X$ and $Y$ are random variables?


What makes a melody the "main melody" of a song?

Question: A melody cannot exist with just one note, it requires 2 which implies that more change could be the biggest factor in making a melody the center of a composition. I am essentially making the assumption that providing a melody with more movement (rhythmic variation) would be the core element in causing it to stand out (be the "main melody").
Although, I also understand that to an extent, it is a matter of perspective on what the "main melody" of a song is. I'm wondering if there are any other factors that i'm missing in making a melody the center (main melody) of a composition AND if my assumption above about rhythmic variation being the main tool for creating a distinct melody would be correct.
Not that the it 100% exists per se, I am slightly of the belief that a listener can decide what melody he/she cares the most about within a composition. But, what are the various ways a "main melody" differentiates itself from the other voices?
Comment: Melody is not just a number of notes (from one and more), but their **duration**. And, to an extent, their dynamics.
Comment: Some clarification, please. Are you asking for a definition of "melody" (i.e. "necessary and sufficient conditions"), how to differentiate the "main" melody from other melodies in a song, or something else?
Comment: You don't even need two different notes: e.g. "One Note Samba"
Comment: Speaking of "Mars" from *The Planets*, its first 2 measures have the harp part playing notes in alternating octaves, making it the part with the most movement. Yet that part can barely be heard at all in the orchestral mix, with the repeated-note melody being far more prominent. Clearly, movement isn't everything.
Comment: @PiedPiper In "One Note Samba"'s defense, there are eventually some other notes.
Comment: A part will tend to stand out if it is louder, or higher in pitch. More movement does not necessarily make a part stand out - consider the Passacaglia from Bach's Passacaglia and Fugue. Also - do you consider the 4-note theme of Beethoven's 5th symphony to be a melody in the sense you are talking about?
Comment: The first 2 measures of "Mars" from *The Planets* better be a melody despite being the same note repeated a lot, right?
Comment: And - ask any jazzer, they'll tell you it's the original melody, but - any amount of other melodies will fit the chord sequence. Where does that leave us?
Comment: I think the concept of melody is like the concept of music itself. 98% of people would agree on what music is and what melodies are, but it's also difficult to define either term. If we can't pin down what a melody is, it's even harder to clarify what a "main" melody is.
Comment: Note, the comments section here isn't a permanent or official part of the question. I'm going to take the liberty of adding your clarification to the question itself; you can also make more edits if you'd like. (Also, side note: It's not always a given that there even *is* "a melody"! There are lots of kinds of music where it's not a priority.)
Comment: See the notion of [Hauptstimme](https://en.wikipedia.org/wiki/Hauptstimme), by the way. So looks like you're narrowing your interest to contexts in which there *are* multiple simultaneous "melodic" [linear] voices. Note, the answer might not just be in the notes chosen, but instrumentation. Schoenberg says there "human voice is always Haupstimme when present." Making a melody more prominent can be as simple as giving it a louder dynamic marking, or giving it to an instrument with a bold or incisive tone.
Comment: Correct. I'm wondering how to differentiate the "main melody", not that it actually exists per se (because I am of the belief that it's down to perspective). I'm asking what factors contribute to one voice standing out more than another. And I was also making the assumption that melodies with more movement stand out more so I was wondering if that is an accurate assumption.
Comment: @AndyBonner That the human voice is always the main melody when present is an interesting assertion coming from Schoenberg. I'm surprised almost nobody agreed that rhythmic variation is what most makes a voice stand out (which still seems to be the case from what i've heard in music in my life). But nonetheless, there's a lot of good answers so thank you. I'd never heard of Haupstimme until now.
Answer: There's a popular phrase "I know art when I see it".  There should be a similar "I know a melody when I hear it".
If you were to separate out all the instruments or singers into their own tracks, and listen to each separately, it should be obvious which is the main melody - it's the one that still sounds like a tune. But it's possible that the melody changes between instruments as the song progresses.
An accompaniment can span a much larger range than the melody.  It can have a more complex rhythm than the melody. But if you play it on its own, it still sounds like an accompaniment to something.
The human brain is good at "locking on" to tunes, in the same way that it's possible to listen to one conversation in a crowded room.  So the melody sounds dominant, even if it is no louder than the accompaniment.
Comment: Polyphony complicates things a lot. I swear my ability to listen to a certain Well-Tempered Klavier Fugue in F Minor is ruined because the first recording of it I listened to ruthlessly emphasized its topmost line instead of its subject above all else.
Answer: We should probably start by saying music does not always use melody. Some percussion music, ambient music, etc. could be considered with work with other musical aspects but not melody.
Also, not all music has a "main" melody where other melodic material can some how be labelled as subordinate to the main melody. Some duets and contrapuntal music will use multiple melodies that are equal in terms of importance.
Having made those caveats, I would say the thing that distinguishes melody to be either unique to stand as a proper melody or as a "main" melody above subordinate material is the extent that melody can be distinguished as unique from other existing melodic material.
What I'm driving at is the difference between common figuration patterns like Alberti basses or segments of scale runs compared to a proper melody. Consider an Alberti bass accompaniment, for example, this accompaniment from a Mozart piano sonata...

Such a pattern can be found all over in classical music. It isn't unique. It's the same broken chord pattern of lower tone, upper, middle, upper applied to chord progression I I V4/2 I. Notice also that the top pitch throughout is all G. It provides some degree of melodic material, because the chord is broken into a line of single pitches. But compare its un-unique pattern to bona fide melody based on broken chord material, for example, this from Bach...

...which has a much more unique identity. Notice that as the line unfolds with broken chord material the top of each beat forms a continuous ascent C D E. Also, examine the note top note ascending/descending direction of each move. In terms of both the overall contour of the line and its note to note details it isn't like a simple Alberti bass pattern.
When you consider just the direction changes of a melody that aspect is called melodic contour. You can examine melodic contour at various levels. Direction only, interval of change, or even pitch letter. Although interval or pitch letter only, without octave reference, would leave the exact direction of movement unclear.
Nevertheless, even pitch letters alone are enough of a unique melodic identifier that Haydn's complete works were indexed by Bryant and Chapman in A Melodic Index to Haydn's Instrumental Music. An example of the melodic incipits by letters only looks like this...

Another well known example of unique melody working only with pitch change and melodic contour is Fux's species counterpoint lessons where the cantus firmi are all given in whole notes, like this...

The point is that melodic contour alone is enough to create unique melodies. What amount of pitch variety is enough to create a unique melody, a melody that is not likely to be confused with another? Bryant and Chapman's index of Haydn's melodies would seem to provide a good standard. But I don't know if they or some other scholar tried to quantify a degree of uniqueness in the index.
You can also achieve melodic uniqueness from plain common patterns using rhythm. Notice in comparing the Mozart and Bach examples that along with a difference in contour the rhythm of the Mozart accompaniment is all eighth notes, while the Bach melody used sixteenths, eighths, and rests.
You can take a plain scale...

...and add only rhythm to create a unique melody...

Getting back to your original question of what makes a "main" melody, I think, at least in part, you can determine that by find the melodic line that is most unique ,among the various parts, in terms of melodic contour and rhythm. In this example from a Mozart string quartet...

...notice how the top line, the first violin, is much more unique in terms of melodic contour and rhythm that the other parts. That makes the first violin, at least in that particular passage, the "main" melody, and the other parts are accompaniment.
Not all music will work this way. There is not always a clear main melody.
In a duet, like this one by Mozart, the parts a even in terms of melodic uniqueness and interest.

Another example could be a hymn like this...

...where the four SATB parts are meant to be roughly equal, in terms of relative ease to sing and interesting line for each part of a chorus, and the rhythm in all half notes underscores the part equality.
Also, understand that the idea of a "main" melody does not have to be fixed to one part. In a fugue the subject and its answer would be the "main" melodic ideas. As a fugue unfolds the subject and answer get stated in the various voices. So the main melodic ideas jump around between parts in that kind of composition.
There are other more obvious ways to know what is the "main" melody.
In a pop song it's typical that the person singing the lyrics has the main melody.
Playing the main melody louder is another way to "bring out" the main melody. For example, this Chopin prelude...

...where the main melody is in the treble clef but has relatively little movement compared to the bass clef accompaniment. Later in the short piece the treble clef develops an interesting contour making clear it is the main melody.

A melody cannot exist with just one note, it requires 2

To the extent pitch contour strongly impacts melodic uniqueness that is true, but there will be examples to find that challenge that contention. Surely, rhythm and dynamics would be ways to make a one pitch take on a level of interest and uniqueness to become a main melody. (I assume you meant 2 different pitches rather than literal notes. Two notes, like two quarter notes, and then you're done, will not make a decent melody!)

if my assumption above about rhythmic variation being the main tool for creating a distinct melody would be correct.

I think this is correct. Rhythm is a very important factor in developing good melody.

What makes a melody the “main melody” of a song?


How to turn a function into a probability density whilst maintaining the shape of the function?

Question: I have a series of functions, each one supposedly representing the density of a random variable across agents. Each function also has a domain, which describes what values of the random variable are valid.
Now, if I remember my stats classes correctly, if I take the integral of one of the functions across the values described by the function's domain, I should get a value of 1.0.  This does not happen however.
Is there a normalization technique that can turn a function into a true probability density, yet maintains the shape of the function?
All the functions are of the form $\frac{a}{bx}+c$, where $x$ is the random variable, and $a,b,c$ are varying constants.
Answer: If you have a non-negative integrable function $f$ with domain $D$ such that
$$ k = \int_{D} f(x) dx < \infty $$
Then $f(x)/k$ is a probability density on $D$. The value $k$ is known as the normalizing constant.
Edit: In your example you said that $f(x) = \frac{a}{bx} + c$ for known constants $a,b,c$. In that case, the indefinite integral is simple to compute and the normalizing constant would be
$$ k = \left[ \frac{a \log(x) }{b} + cx \right]_{D}$$
if $D$ is an interval $(A,B)$ then this simplifies to
$$ k = \frac{a}{b} \cdot \log \left( \frac{B}{A} \right)  + c(B-A) $$ Therefore $$ g(x) = \frac{\frac{a}{bx} + c}{\frac{a}{b} \cdot \log \left( \frac{B}{A} \right)  + c(B-A)}$$ is a probability density on $(A,B)$.


How many draws to have a 90% chance of getting the ace of spades?

Question: You have a standard 52-card deck, and you want to take the minimum number of draws from a random/shuffled deck such that you have a 90% chance of drawing the ace of spades. How would you find the minimum number of draws to achieve this 90% probability of succeeding in drawing the ace of spades at least once, for both the case of replacement and non-replacement?
Comment: do you replace the cards when you draw them?
Comment: Related: [What is the average number of cards dealt until the ace of spades turns up?](https://math.stackexchange.com/questions/2238077/what-is-the-average-number-of-cards-dealt-until-the-ace-of-spades-turns-up)
Answer: Without replacement is (for once) easier. The Ace of Spades is equally likely to be in any of the $52$ positions, so we need to draw $n$ cards, where $n$ is the smallest integer $\ge (0.90)(52)$.
For with replacement, the probability we don't see the Ace of Spades in $n$ draws is $\left(\frac{51}{52}\right)^n$. We want this to be $\le 0.1$. Thus we want $n\ln(51/52)\le \ln(0.1)$, or equivalently $n\ge \ln(10)/(\ln(52/51)$.
Comment: Do you know the probability/statistic terms for each of these replacement and with replacement that you did? Like a vocabulary term like "number of trails to successfully get a percent chance of at least one outcome with replacement" so I can Google it online and learn. Thank you


Ideal Class Group is finite

Question: I'm having trouble understanding the proof given in class that the ideal class group of finite algebraic extension is finite.
Here it is (with my questions):
First, a lemma: Any class of ideals in $Cl(K)$ contains a representative $L$ for which $\mathcal{O}_K \subset L$ and $[L:\mathcal{O}_K]<(\frac{4}{\pi})^{r_2}\cdot\frac{n!}{n^n}\cdot\sqrt{|Disc(\mathcal{O})|}$.
Proof:

I'm already confused because the proof does not start by taking a certain class in $Cl(K)$ so I don't understand its structure.

Take a lattice $M$ in $K$ such that $\mathcal{O}_K=\mathcal{O}(M)$ where
$\mathcal{O}(M)=\{x\in K \mid xM \subset M\}$.

Why does such $M$ exist?

W.L.O.G we have $M \subset \mathcal{O}_K$ (I'm fine with this step because we can multiply $M$ by some scalar to make it so).
By Minkowski's theorem, we have $|Nm_{K/\mathbb{Q}}|\leq (\frac{4}{\pi})^{r_2}\cdot\frac{n!}{n^n}\cdot\sqrt{|Disc(\mathcal{O}_K)|}\cdot[\mathcal{O}_K:M]$.

Where did the $[\mathcal{O}_K:M]$ factor come from? I don't see it in Minkowski's theorem.

So $\alpha\mathcal{O}_K \subset M$ because $M$ is both a lattice and a ring.

I don't understand this implication.

Take $L=\alpha^{-1}M$.

Since we didn't start with a specific class, I don't understand what this $L$ has to do with anything.

We now have $[\alpha^{-1} M:\mathcal{O}]\leq[\alpha^{-1}M:M]=|Nm_{K/\mathbb{Q}}(\alpha)|\leq (\frac{4}{\pi})^{r_2}\cdot\frac{n!}{n^n}\cdot\sqrt{|Disc(\mathcal{O})|}$.
That ends the proof of the lemma. The proof of the theorem itself is then more clear.
Comment: Are you reading a particular book?
Comment: Your question is very detailed, but this is a very common lemma when proving the finiteness of the class group. Read Chapter 5 in Marcus' "Number Fields", in particular, your question is Theorem 37 (and see its corollaries 1 and 2), in page 135.
Comment: @ÁlvaroLozano-Robledo: No. Unfortunately, the course does not follow a book.
Comment: @ÁlvaroLozano-Robledo: Is there anything I should add to make helping me easier?
Comment: Quick guesses: 1) $M$ will represent an arbitrary class, 2) any fractional ideal has this property (I thinks that's the way it plays out, but haven't fully checked), 3) $M\le{\cal O}_K$, so
$$|Disc(M)|=|Disc({\cal O}_K|\cdot [{\cal O}_K:M]^2,$$ 4) The assumption was that the product of any element of $M$ and any algebraic integer is still in $M$, 5) $L$ and $M$ are in the same class in the class group.
Answer: Usually, the proof goes in the following way.
Let $M'$ be a fractionnal ideal. Write $M'=aM$ with $M\subseteq O_K$. By Minkowski, there exists $\alpha\in M$ non-zero such that
$$ \mathrm{Nm}_{K/\mathbb Q}(\alpha) \le C [O_K: M]$$
where $C=(4/\pi)^{r_2}(n!/n^n)\sqrt{|Disc(O_K)|}$. Let $L=\alpha^{-1}M$. Then
$$[L:O_K]=[\alpha^{-1}M: O_K]=[M: \alpha O_K]=\mathrm{Nm}_{K/\mathbb Q}(\alpha)/[O_K: M]\le C.$$
By construction, $L=(a\alpha)^{-1}M'$ is a representative of the class of $M'$.
Comment: @user18119 To prove only the finiteness of the class group of a number field K, you don't need Minkowski's bound. The mere existence of the constant C can be shown elementarily, see e.g. Marcus' "Number Fields", chap.5, thm.35

Ideal Class Group is finite


Convert inline assembly code to C++

Question: I am working on a cpp project. The project need to be migrated to 64 bit. It contains some Inline assembly code which cannot compile on x64.
This is the Function which contain the assembly code:
void ExternalFunctionCall::callFunction(ArgType resultType, void* resultBuffer)
{
#if defined(_NT_) || defined(__OS2__)

    // I386

    // just copy the args buffer to the stack (it's already layed out correctly)
    int* begin = m_argsBegin;
    int* ptr = m_argsEnd;
    int arr[1000], i=0;
    while (ptr > begin) {
        int val = *(--ptr);

        __asm push val
    }

    void* functionAddress = m_functionAddress;

    // call the function & handle the return value.  use __stdcall calling convention
    switch (resultType) {
    case voidType:
        __asm {
            call functionAddress
        }
        break;
    case pointerType:
    case int32Type:
        __asm {
            call functionAddress
            mov ebx, resultBuffer
            mov dword ptr [ebx],eax
        }
        break;
    case floatType:
        __asm {
            call functionAddress
            mov ebx, resultBuffer
            fstp dword ptr [ebx]
        }
        break;
    case doubleType:
        __asm {
            call functionAddress
            mov ebx, resultBuffer
            fstp qword ptr [ebx]
        }
        break;
    }

I used stack, array to migrate this "asm push val" but didn't work. Although, It don't throw any compilation error but logic didn't worked.
So, I want to ask, What can I use in C++ instead of "__asm push val". Any help will be appreciated.
Comment: Standard C++ does not include inline assembly language or any operations for directly modifying the CPU's stack....  You've more  chance of useful advice if you explain what your function's doing with the stack afterwards?  If it's preparing values for a function call or something, there may be some other way to supply the arguments.  It's likely highly specific to your OS and/or compiler, which you haven't stated.
Comment: Surely this isn't the only assembly instruction in the program? How do you use the pushed value? For the moment there isn't enough information to help you.
Comment: You'll need to show more code so we can know what's being done with the value pushed onto the stack.
Comment: Is this some kind of "variable arguments" function call? If so, how wide is the range of arguments?
Comment: Hi Konrad/Michael/Tony/Mats,

Now you can see the complete code of function, which contains the asm code.
Comment: Do you have any control about the function you call through `m_functionAddress`?
Answer: The problem isn't solvable in general; that's because the comment,
// call the function & handle the return value.  use __stdcall calling convention

indicates reliance on 32bit calling conventions.
In 32bit x86, stdcall means that all arguments are passed on the stack, in reverse order (i.e. the last arg is pushed first. That is, if arg[0] is at addr then arg[1], no matter it's type, is at addr + sizeof(arg[0])). That's the reason why the following code in your sample:
// just copy the args buffer to the stack (it's already layed out correctly)
int* begin = m_argsBegin;
int* ptr = m_argsEnd;
int arr[1000], i=0;
while (ptr > begin) {
    int val = *(--ptr);

    __asm push val
}

actually can work - because it simply doesn't matter what exactly is there, what type the arguments are; all that's relevant is that each and every one of them is in a known memory location, and known-to-be-consecutive-in-memory. If you know that argument N is at addr, then you can know argument N+1 is at addr + sizeof(arg[N]).
That's what the comment says, "it's already layed out correctly" - unfortunately, this is not true in 64bit mode. The code therefore cannot be "ported"; there is no equivalent to port to.
Calling conventions that are at least partially register based - as is Win64 on x64 (64bit x86) behave differently. For those, it depends on what types of arguments the called functions take (you can, in Windows, pass four integer-type args in general-purpose registers plus some float-type args in XMM registers). You therefore need to know more about the signature (prototype) of the function you call than simply "it takes N arguments" in order to be able to correctly marshal args from an "anycall" type wrapper like the above. In 64bit mode, for every function you'd wish to call through your wrapper, you need to know not just how many args there are in total, but also how many are in general-purpose regs, how many in XMM regs, and how many on the stack.
The "call a func through a pointer and copy the return value to a known location" part is portable and can be expressed in plain C/C++. But the part that gets the arguments for this, as per above, does not port in any straightforward way between 32bit stdcall and any 64bit x86 calling convention I know of (neither Win64/x64 nor the UN*X x86_64 conventions allow to predict both the locations and total stack memory usage of all arguments for a function given just the number and types of the args but not their ordering).
What exactly you need to do depends much more on the callers/users of the above class ExternalFunctionCall than on the small little sample of inline assembly you've shown. It's particularly necessary to know how the members m_argsBegin and m_argsEnd are initialized and where. Can you provide a few more details on how the class looks like (all member variables/functions), as well as examples on its actual use ?
Comment: Thanks Frank, I would like to ask one more thing. Can't we separate this asm code in asm/s file? A separate asm file can compile on x64 through MASM64.exe. If possible, please tell me how can we do this?
We have migrated all other asm code to cpp, only "__asm push val" is remaining. You can see the code of complete function above.
Comment: @user2118116: as already stated, there's _more_ to do than simply "replace the `__asm push val` with some 64-bittishness". This "more" is _outside the function_ - it's _both_ in the entire class as well as, and that's where your biggest piece of work is, _at the actual places where instances of this class are created/used_. No easy way out here, sorry. Your question about porting this to 64bit is a bit like saying "my x86 code uses `lcall` in inline assembly and I need to port it to ARM, so I want to know the ARM instruction that does `lcall`".
Comment: @FrankH. Full ACK on this. I suggested the OP in a duplicate of this: 「The best thing you can do is to rewrite the entire function using [libffi](http://sourceware.org/libffi/) or [dyncall](http://dyncall.org/) instead.」
Answer: There are several things which you need to solve. (I looked up your code on another question). As I understood this code is a wrapper to call pretty abstract function located at specified address which expects certain amount of data in stack and can return different things based in ArgType.
If you want to wrap it through plain C you have to define several functions prototypes (based on return value) to use then on your switch, but then you have to solve another problem, which is more tricky.
Problem with porting such things in C is that you don't know upfront an amount of arguments (data size) you have to push in stack, so you will have troubles defining prototype.
Let's say func(char c) will definitely push in stack 1 byte (but also not always right because of data alignments).. in your case you have to think about solution which will have set of parameters with an equal size to size of data you need to be on the stack. Which at first glance not something you can do straight away.
UPD. you can do it with func( char [] param ); but it also has issues which were explained in answer above.
Comment: You know, it's not that bad an answer, but the last paragraph, particularly "you have to think about solution", kind of ruins it for me. The OP wouldn't be asking for help if they could think of something. They obviously tried very hard to solve it on their own.
Comment: Sorry to disappoint you.. May be 'you have to think' indeed was a bit hard, but I have excuse that I am not native English speaker.. I mean that I really don't know the exact solution for last step, and what I wrote was more kind of out laud thinking rather then ready made answer. And another thing is that from what I read in OP question (actually both of them), I would consider to be 'obviously tried very hard to solve' is applicable.
Answer: I realize this is a somewhat old question, but I just stumbled upon: xbyak.
Perhaps what you're looking for?
Comment: Hi Nix,
I want to replace the asm code from this context:

    int* begin = m_argsBegin;
    int* ptr = m_argsEnd;
    int arr[1000], i=0;
    while (ptr > begin) {
    int val = *(--ptr);

    __asm push val
    }
Basically I want to replace the statement "__asm push val" with Cpp code.
Thanks
Comment: What are m_argsBegin and m_argsEnd?
Comment: @Nix- Both of these are int*

Thanks

Convert inline assembly code to C++


Deploying asp.net Mvc Web application

Question: when i was running my application from vs every thing goes OK i deployed the application and run it from IIS7 on a machine run windows 7 the website run OK but i icons and images in content folder dosn't appear in the webpages also when i try to navigate this image told me that files not found
Comment: It would help if you could provide some more information on your deployment and the project itself. Are you running from a virtual directory versus a rooted application, do you use absolute paths for your images, etc?
Answer: It's usually the small things we overlook when programming (and deploying)

Make sure your virtual directory is pointed to the correct place
Make sure your content is all published
Make sure the permissions on your virtual directory is correct

More information would help to determine exactly what is going on though.
Answer: I suspect you are referencing your images with a path that different between VS web server and the way you have the site setup in IIS.
For example if you used
<link href="../../Content/Somefile.css" />
to reference a CSS file (or an image) keep in mind that path might not be correct on your IIS machine.
You might need to update such paths to something like
<link href="<%: Url.Content("~/Content/Somefile.css") %>  />

Deploying asp.net Mvc Web application


Select from table not in another table

Question: I have two tables, each with the following fields: IDnumber, SectionNumber, Date. There is overlapping information in the two tables.
How do I select only rows that do NOT overlap (ie. in one table but not the other)?
Answer: You can use a NOT IN in your WHERE clause.
SELECT IDnumber, SectionNumber, Date
FROM table1
WHERE IDnumber NOT IN (SELECT IDnumber FROM table2)

OR NOT EXISTS
SELECT IDnumber, SectionNumber, Date
FROM table1 t1
WHERE NOT EXISTS (SELECT IDnumber FROM table2 t2 WHERE t1.IDnumber = t2.IDnumber)

Comment: +1. Or an `OUTER JOIN` and only return the rows with `NULL` values in the joined table. :-)
Comment: @user1572544 if this is helpful be sure to accept it as the answer via the checkmark on the left. :)
Comment: For sql server in particular, use `NOT EXISTS` if performance matters. Citation: http://stackoverflow.com/questions/2246772/whats-the-difference-between-not-exists-vs-not-in-vs-left-join-where-is-null
Answer: Which DBMS?
If SQL Server, then it's almost what you wrote in the title...
SELECT *
FROM Table1
WHERE IDnumber NOT IN (SELECT IDnumber FROM Table2)

Answer: SELECT *
FROM Table1 t1 left join Table2 t2
on t1.id=t2.id
where t2.id is null

Answer: If you want to compare multiple columns, you need an outer join:
select table1.*
from table1 left outer join
     table2
     on table1.id = table2.id and
        table1.SectionNumber = table2.SectionNumber and
        table1.date = table2.date
where table2.id is null

In the case where you might have many matches between the tables, then the join can be inefficient.  Assuming you only want those three fields, you can use a trick that avoids the join:
select id, SectionNumber, date
from ((select 0 as IsTable2, id, SectionNumber, date
       from table1
      ) union all
      (select 1 as IsTable2, id, SectionNumber, date
       from table2
      )
     ) t
 group by id, SectionNumber, date
 having max(isTable2) = 0

Select from table not in another table


How to vertically center text in IE 11 without a fixed height?

Question: I'm trying to "clone" the TOC from this google-codelabs page here:
https://codelabs.developers.google.com/codelabs/cloud-app-engine-aspnetcore
So far, it works perfectly in Google-Chrome and Firefox.
But Internet Explorer (11)...
Juddging from Item 3, it seems like IE doesn't properly align the bullet vertically in the middle.
Why  ?
How can I properly align the bullet and the text vertically in the middle in IE 11 ?

This is what I have (or see fiddle):
<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="0" />
    <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
    <meta http-equiv="pragma" content="no-cache" />

    <meta charset="utf-8" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <meta http-equiv="Content-Language" content="en" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />

    <meta name="google" value="notranslate" />
    <title>Simple Page</title>

    <paper-item class="toc-item paper-item-0" role="option" tabindex="0" aria-disabled="false" aria-selected="true">
        1
        Overview
    </paper-item>

    <paper-item class="toc-item paper-item-0" role="option" tabindex="-1" aria-disabled="false">
        2
        Setup and requirements

Line 1

Line 2

Line 3

Line 4

Line 5

Line 6

    </paper-item>

    <paper-item class="toc-item paper-item-0" role="option" tabindex="-1" aria-disabled="false">
        3
        foo
    </paper-item>

        4
        foo

Comment: IE11 screen https://yadi.sk/d/sHOZamgd3EBykb
Comment: Everything you need to know about aligning items centrally: http://stackoverflow.com/questions/19461521/how-to-center-an-element-horizontally-and-vertically
Comment: Possible duplicate of [How to center an element horizontally and vertically?](http://stackoverflow.com/questions/19461521/how-to-center-an-element-horizontally-and-vertically)
Answer: try this code:
<paper-item class="toc-item paper-item-0" role="option" tabindex="0" aria-disabled="false" aria-selected="true">
    1
    Overview
</paper-item>

add this code to paper-item tag
paper-item
{
 display:flex;
 align-items: center;
}

Answer: Change box-sizing: content-box; to box-sizing: border-box; in the .toc-item rule
Updated fiddle

.paper-item-0 {
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -ms-flex-direction: row;
  -webkit-flex-direction: row;
  flex-direction: row;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
  font-family: 'Roboto', 'Noto', sans-serif;
  -webkit-font-smoothing: antialiased;
  font-size: 16px;
  font-weight: 400;
  line-height: 24px;
  position: relative;
  min-height: 48px;
  padding: 0px 16px;
  border: 1px solid hotpink;
}

.toc-item {
  font-size: 14px;
  color: #9e9e9e;
  overflow: hidden;
  border-radius: 4px;
  padding: 6px 16px;
  box-sizing: border-box;
}

.bulletStyle {
  display: inline-block;
  font-style: normal;
  width: 24px;
  min-width: 24px;
  background-color: #fff;
  border-radius: 50%;
  text-align: center;
  height: 24px;
  vertical-align: middle;
  line-height: 24px;
  border: 2px solid #bdbdbd;
  margin-right: 8px;
  font-weight: 400;
}

.lineAbove::before {
  position: absolute;
  top: 0px;
  left: 30px;
  bottom: calc(50% + 12px);
  content: '';
  display: block;
  border-left: 1px solid #bdbdbd;
  #width: 0;
  #height: 44px;
  z-index: 1;
  #margin-top: 1px;
  #margin-left: 11px;
}

.lineBelow::after {
  position: absolute;
  top: calc(50% + 12px);
  left: 30px;
  bottom: 0px;
  content: '';
  display: block;
  border-left: 1px solid #bdbdbd;
  #width: 0;
  #height: 44px;
  z-index: 1;
  #margin-top: 1px;
  #margin-left: 11px;
}

/*
        .lineAbove::before
        {
            border-color: #2196f3;
        }
        */

.tocText {
  font-size: 14px;
  color: #9e9e9e;
  padding: 6px 16px;
}
<paper-item class="toc-item paper-item-0" role="option" tabindex="0" aria-disabled="false" aria-selected="true">
  1
  Overview
</paper-item>

<paper-item class="toc-item paper-item-0" role="option" tabindex="-1" aria-disabled="false">
  2
  Setup and requirements

Line 1

Line 2

Line 3

Line 4

Line 5

Line 6

</paper-item>

<paper-item class="toc-item paper-item-0" role="option" tabindex="-1" aria-disabled="false">
  3
  foo
</paper-item>

  4
  foo


How to create hypervolume and surface attainment plots (for 2 objectives) using Python?

Question: Does anyone know how to create a plot like the one below using Python? I would like to know how to plot the straight lines and the shaded area.
Hypervolume + Surface Attainment plot:
Both hypervolume and surface attainment are used as performance indicators for a multi-objective optimisation algorithm.
Comment: looks like planar slice of the hyper volume projected onto 2D. SO first select plane cells from volume and then use basis vectors mapping `u,v` as plot `x,y` in case of `xy` plane  you can use directly `x,y` and ignore all other dimensions.
Answer: I managed to figure this out by myself in the end. Here is my approach (compares the performance of the multi-objective algorithm before and after a certain change):
import matplotlib.pyplot as plt

cases = ['before', 'after']
objectives = ['obj1', 'obj2']
colors = ['green', 'red']

data = {case : pd.read_csv(case +'.csv', index_col=False) for case in cases}

fig, axes = plt.subplots()
for j, case in enumerate(cases):
    obj1 = sorted(data[case][objectives[0]].values)
    obj2 = sorted(data[case][objectives[1]].values)

    #Plot the first two pts outside the loop to display the label
    axes.plot([obj1[0], obj1[0]], [obj2[0], obj2[1]],
              color=colors[j],
              label=case)
    axes.plot([obj1[0], obj1[1]], [obj2[1], obj2[1]],
              color=colors[j])

    for i in range(2, len(obj1)):
        axes.plot([obj1[i - 1], obj1[i - 1]], [obj2[i - 1], obj2[i]],
                  color=colors[j])
        axes.plot([obj1[i - 1], obj1[i]], [obj2[i], obj2[i]],
                  color=colors[j])

axes.set_xlabel(objectives[0])
axes.set_ylabel(objectives[1])

axes.plot(nadir_r[0],
          nadir_r[1],
          '*',
          label='nadir')
axes.plot(ideal_r[0],
          ideal_r[1],
          'x',
          label='ideal')

plt.xlim(nadir_r[0], ideal_r[0])
plt.ylim(ideal_r[1], nadir_r[1])

axes.legend(loc='best')

This would produce the following plot (which shows that the "change" had a negative impact).
Any constructive criticism is welcome.
Comment: please, add "import pandas as pd" and either provide the ".csv" file or replace it by a in-code data.
Answer: Try the function below.
It produces this:

import numpy as np
import matplotlib.pyplot as plt

def plot_hyper_volume(x, y, reference_point):
    x = np.array(x)
    y = np.array(y)

    # Zip x and y into a numpy ndarray
    coordinates = np.array(sorted(zip(x, y)))

    # Empty pareto set
    pareto_set = np.full(coordinates.shape, np.inf)

    i = 0
    for point in coordinates:
        if i == 0:
            pareto_set[i] = point
            i += 1
        elif point[1] < pareto_set[:, 1].min():
            pareto_set[i] = point
            i += 1

    # Get rid of unused spaces
    pareto_set = pareto_set[:i + 1, :]

    # Add reference point to the pareto set
    pareto_set[i] = reference_point

    # These points will define the path to be plotted and filled
    x_path_of_points = []
    y_path_of_points = []

    for index, point in enumerate(pareto_set):

        if index < i - 1:
            plt.plot([point[0], point[0]], [point[1], pareto_set[index + 1][1]], marker='o', markersize=4, c='#4270b6',
                     mfc='black', mec='black')
            plt.plot([point[0], pareto_set[index + 1][0]], [pareto_set[index + 1][1], pareto_set[index + 1][1]],
                     marker='o', markersize=4, c='#4270b6', mfc='black', mec='black')

            x_path_of_points += [point[0], point[0], pareto_set[index + 1][0]]
            y_path_of_points += [point[1], pareto_set[index + 1][1], pareto_set[index + 1][1]]

    # Link 1 to Reference Point
    plt.plot([pareto_set[0][0], reference_point[0]], [pareto_set[0][1], reference_point[1]], marker='o', markersize=4,
             c='#4270b6', mfc='black', mec='black')
    # Link 2 to Reference Point
    plt.plot([pareto_set[-1][0], reference_point[0]], [pareto_set[-2][1], reference_point[1]], marker='o', markersize=4,
             c='#4270b6', mfc='black', mec='black')
    # Highlight the Reference Point
    plt.plot(reference_point[0], reference_point[1], 'o', color='red', markersize=8)

    # Fill the area between the Pareto set and Ref y
    plt.fill_betweenx(y_path_of_points, x_path_of_points, max(x_path_of_points) * np.ones(len(x_path_of_points)),
                      color='#dfeaff', alpha=1)

    plt.xlabel(r"$f_{\mathrm{1}}(x)$", fontsize=18)
    plt.ylabel(r"$f_{\mathrm{2}}(x)$", fontsize=18)
    plt.tight_layout()

    plt.show()

x = [3.237887527110896, 3.253687689154591, 2.6652460044515833, 4.457925635186012, 3.2080041315472436,
      3.196941509672105, 3.1489091846746784, 3.3727329491336504, 3.2980773800599184, 3.330938419470396,
      3.0504985412687606, 3.9698249482752517, 3.1229599570521005, 3.1278496698518365, 3.3410372676796367,
      3.267339581661665, 3.1531143837247226, 3.13276172330508, 3.2136444869087857, 3.123114522218978,
      2.8975316624890177, 3.855654194881272, 2.982889291813081, 4.001132534228973, 3.222172022988187,
      3.2918121975763426, 3.119437722697402, 3.1915652020314855, 3.228511161109151, 3.410632525789594,
      3.303983909300615, 3.23152665486737, 3.12295981695552, 3.123114522218978, 3.2134999576177727, 3.3042667387038263,
      3.379569640868453, 3.2597834943233255, 3.2365405477218783, 3.2911687133624765, 3.1835704013006616,
      3.1363291696973903, 3.1422814239459718, 3.1202417240558282, 3.1311337111075535, 3.630375287962374,
      3.181708872213033, 3.2993090610457774, 3.130988434129236, 3.12295981695552]

y = [3.5471650938674886, 3.446106995806536, 4.203717903464938, 2.53919767967234, 3.550936505497275, 3.553107544090778,
      3.648527616343033, 3.3076630507066875, 3.3498580074252184, 3.320019542824605, 3.752735495100324,
      2.853419245618656, 3.71421025754152, 3.709380479951111, 3.307305266656153, 3.5468875845765266, 3.7140635724580386,
      3.6981877554394647, 3.6799057516573295, 3.714041693123077, 3.831023904192475, 2.873083146950819,
      4.195177914971685, 2.8302302203075165, 3.4285829711629616, 3.3624540805968035, 3.7156683374998387,
      3.5623734317415163, 3.627757758118092, 3.2755855532302336, 3.318743777730811, 3.7213811168338164,
      3.714210410334474, 3.714041693123077, 3.45357840149967, 3.6337156456167627, 3.270784928858892, 3.400665041601096,
      3.5451613263457076, 3.357372990242752, 3.5705676117602683, 3.6930983812240736, 3.687202266647831,
      3.717332517575802, 3.7061199284167357, 3.1769420991200708, 3.492240477791187, 3.512518414215774,
      3.7040103293332383, 3.714210410334474]

ref = [max(x), max(y)]

plot_hyper_volume(x=x, y=y, reference_point=ref)


Question about imbalanced training and test sets

Question: I was wondering something about imbalanced datasets. It's not the usual 'what should I do with my imbalanced training set'.
I have an imbalanced training set with 1:2 = positive:negative examples. I have a test set with about 1:13 ratio as well (I need a separate test set since I would like to compare my model to existing models. The test set was compiled from incoming examples after the compilation of the training set, hence the different ratio.)
Now, I have trained a model and I have created a confusion matrix (CM) from the CV and from the test set as well.
The CM of the test set looks like this:
               observed true       observed false
pred. true          94                  90
pred. false         29                 1554

It has a sensitivity = 0.76, specificity = 0.95, MCC = 0.59, precision = 0.51, F1 = 0.61 etc.
However, after that I realised that these measures very much depends on the ratio of the two classes. I have tried two scenarios.
First, I have balanced the test set like thr training set, having a 1:2 ratio. I got this:
               observed true       observed false
pred. true          94                  13
pred. false         29                  233

It has a sensitivity = 0.76, specificity = 0.95, MCC = 0.74, precision = 0.88, F1 = 0.81 etc. It is clear, that the first two did not changed, however others greatly improved.
Then, I trid a 1:1 balanced dataset:
               observed true       observed false
pred. true          94                   7
pred. false         29                  116

It has a sensitivity = 0.76, specificity = 0.95, MCC = 0.72, precision = 0.93, F1 = 0.84 etc.
To be clear, I totally understand why sensitivity and specificity remains the same, and not affected by sample ratio. However, MCC is widely used to compare models and to evaluate model's performance. I know
I would like to be fair in model building and comparisons and would not like to use the scenario that best fits my goals if that is not the proper one. So which one (or any other) is reasonable to use?
Thanks for answers.
Answer: I think if in actual use your classifier is used on a set with a 1:13 imbalance, you should validate on a set with the same imbalance.
As for which measure to use, all these can be understood as simple cost functions, where each misclassfication is weighted equally heavy, or not at all, as precision doesn't penalize false negatives. The best classifier is then the one that minimizes cost.
In practice, these simple cost functions are often not realistic. Perhaps you can estimate a reasonable cost (in currency or in a relative way) of misclassifications, and use that to find the "best" model.


Adding Attributes issues in xsl

Question: The Below is my input xml
<code>             <ServiceIncident xmlns="http://b2b.ibm.com/schema/IS_B2B_CDM/R2_2">
             <ProviderID>INC0011731</ProviderID>
             <ProviderPriority>4</ProviderPriority>
             <WorkflowStatus>NEW</WorkflowStatus>
            <ServiceProvider1>
               <Person Role="AffectedUser">
               <ContactID>ITELLA_BRIDGE_USER</ContactID>
               <FullName>Chad Whaley</FullName>
               </Person>
           </ServiceProvider1>
</code>
Below is my xsl code iam using but iam not getting the required output.
<code>           <xsl:template match="r2:Person/@Role">
           <xsl:attribute name="Role">ReportedBy</xsl:attribute>
           </xsl:template>
</code>
My problem is i want to get onemore person Role="ReportedBy" in output under serviceprovider root tag and Person Role="AffectedUser" should not replaced with this value.This value should also be there in output.
Comment: How about reading the comments and answer to your last question (http://stackoverflow.com/questions/21902249/picking-multiple-attributes-in-xslt) before asking a new one?
Answer: Ah, I see. I initially misread the request (or it was edited since my first response).
Since XSLT is a programming language there are multiple possible answers and you haven't given us enough information about your requirements to prefer one or another. Here's one suggestion:
Assuming your stylesheet is based on the identity transform with transforms spelling out the exceptions (one of the better ways to write most stylesheets), add another identity template modified to (a) match on the Person-with-appropriate-role element, and (b) after processing that element, insert another which has the new information.
<code><xsl:template match="r2:Person[@Role!='AffectedUser']">
    <xsl:copy/>>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
    <Person Role="ReportedBy"/>
</xsl:template>
</code>
Comment: This will **replace** the existing @Role attribute - not **add** another one, as requested (ill-advisedly, IMHO) by the OP.
Comment: Ah, I see what they're asking. Corrected.

Adding Attributes issues in xsl


How to take count of particular column with respective of the particular row in r

Question: My data looks like this:

I want to calculate the total number of passes in each positions respectively and likewise the total number of fails in each positions respectively in R. How can  I achieve that?
Here is the output of dput(head(data1))
PS:fail ==fail lens_bubble
Comment: Please include a data example by pasting the output of `dput(head(df))` into your question.
Comment: Don't post photos. Just copy/paste that in your question
Comment: @LAP .It can be found above
Answer: It is much easier to perform this kind of analysis when the data is in a tidy format. You can learn more about what that means here.
First let's create an example of your data.
library(tidyverse)
set.seed(327)

dta <- tibble(
  tool_number = 200:212,
  Err = sample(c("pass", "fail"), size = 13, replace = TRUE),

  pos01 = sample(c(0, 1), size = 13, replace = TRUE),
  pos02 = sample(c(0, 1), size = 13, replace = TRUE),
  pos03 = sample(c(0, 1), size = 13, replace = TRUE),
  pos04 = sample(c(0, 1), size = 13, replace = TRUE),
  pos05 = sample(c(0, 1), size = 13, replace = TRUE),
  pos06 = sample(c(0, 1), size = 13, replace = TRUE),
  pos07 = sample(c(0, 1), size = 13, replace = TRUE),
  pos08 = sample(c(0, 1), size = 13, replace = TRUE),
  pos09 = sample(c(0, 1), size = 13, replace = TRUE),
  pos10 = sample(c(0, 1), size = 13, replace = TRUE),
  date = sample(seq(
    as.Date("2017-01-01"), as.Date("2017-12-31"), by = "day"
  ), 13)
)

The next step uses the gather() function to change the layout of your data to make it tidy.
dta <- gather(dta, key = position, value = value, pos01:pos10)

Now you can use the group_by() and summarise() functions to find the number of passes and fails for each position.
dta %>%
  group_by(Err, position) %>%
  summarise(count = sum(value))

# # A tibble: 20 x 3
# # Groups:   Err [?]
# Err position count
# <chr>    <chr> <dbl>
#   1  fail    pos01     2
# 2  fail    pos02     1
# 3  fail    pos03     3
# 4  fail    pos04     0

If you want to the data to look more like it did when you started, you can spread() the results.
dta %>%
  group_by(Err, position) %>%
  summarise(count = sum(value)) %>%
  spread(key = Err, value = count)

# # A tibble: 10 x 3
# position  fail  pass
# *    <chr> <dbl> <dbl>
#   1    pos01     2     4
# 2    pos02     1     2
# 3    pos03     3     4
# 4    pos04     0     5

Answer: I agree with Andrew about tidy data, but a base R solution would be
sapply(data1[, 3:12], function(x) sum(x[data1$Err == "pass"]))

and respectively
sapply(data1[, 3:12], function(x) sum(x[data1$Err == "fail"]))

Comment: In the rest of the data there are  numbers other than 1's and 0's like 30,20 which means the 30products are passed in position 1, 20 products failed in position 2 and so..on.Here i want to get the count of products in each positions which got passed and which got failed.
Comment: @ LAP Thank you so much...Here x means the column name right??
Comment: and i am getting this kind of output
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
Comment: Please copy the text from your second image into the question. I cannot copy the code from the picture and it is kinda difficult to come up with a working solution without having example data.


Multiply two pandas series matching on series index

Question: I have 2 pandas series
Series 1:
2016-01-31  10
2016-01-31  20
2016-03-31  30
2016-03-31  40
Series 2:
2016-01-31  2
2016-03-31  3
I want to multiply Series 1 and Series 2 matching on index:
Answer
2016-01-31  20
2016-01-31  40
2016-03-31  90
2016-03-31  120
Answer: Use mul with parameter fill_value=1:
s = s1.mul(s2, fill_value=1)
print (s)
2016-01-31     20
2016-01-31     40
2016-03-31     90
2016-03-31    120
dtype: int64


A função password_hash do PHP é um wrapper para a função crypt?

Question: A função password_hash me parece um wrapper que adiciona uma camada de alto nível na função crypt, pois ela traz uma configuração padrão que poderia ser feita com crypt manualmente.
Acontece o mesmo com a função password_verify, que parece equivalente a isso:
function password_verify($password, $passwordHash)
{
     return (crypt($password, $passwordHash) === $passwordHash);
}

Tenho essa curiosidade em saber se são wrappers adicionados para crypt nas versão mais recentes do PHP.
OBS: Sei que o código acima é inseguro, pois está vulnerável a timming attack, porém é só uma forma de tentar ilustrar a ideia. O ponto é saber se é um wrapper ou não. Portanto, segurança não é o foco desta pergunta.
Desde já, agradeço.
Answer: Esse código é inseguro, por usar ===.
O password_hash também suporta o Argon2, nas últimas versões do PHP, coisa que não é suportada pelo crypt. O crypt também varia de plataforma para plataforma, e nem todos os algoritmos podem estar disponível, inclusive pode nao existir o BCrypt.
A função crypt também exige um salt, que deve ser único. No password_hash isso é gerado internamente na função.
Entretanto, sim, ele é um wrapper. Isso é mencionado na documentação:

"password_hash() is a simple crypt() wrapper and compatible with existing password hashes"


Boolean Algebra-Simplification Assistance Needed

Question: I have to show that (!(P.Q) + R)(!Q + P.!R) => !Q by simplifying it using De Morgan's Laws. Here is what I did but I'm not sure it's right.
(!(P.Q) + R)(!Q + P.!R) => !Q
(!P + !Q + R)(!Q + P.!R)
!(P.Q) + !P.P.!R + !Q + !Q.P.!R + R.!Q + R.P.!R
!(P.Q) + 0 + !Q + !Q.P.!Q + R.!Q + 0
!(P.Q) + !Q + !Q(1 + P.!R + R)
!(P.Q) + !Q + !Q
!Q + !(P.Q)
!Q(1 + !P)
!Q
Hope that's clear enough.
Comment: The sedond line: how did $(P' · Q' + R)$ turn into $(P' + Q' + R)$?
Comment: De Morgan's Law !(P.Q) = !P + !Q, did I do it wrong?
Comment: But there is $P' · Q'$ and not $(P · Q)'$.
Comment: Yeah sorry about that I wasn't sure how to type it out. It's P.Q Negated with the line above it, so I think it should be !(P.Q) I'll have to edit the question if this is right,
Comment: Actually since $Q'$ is in both conjunts of the second line expression, you can factor it out immediately: $(P' + Q' + R)(Q' + PR') = Q' + (P' + R)(PR')$ which implies $Q'$
Comment: Does the reset of the expression cancel itself out? If so then thanks!! Oh, and is the way I did it still right?
Comment: No the rest of the expression does not cancel itself out and that's not what you want to prove. It's just $Q' + x \implies Q'$ but $Q' + x \iff Q'$ doesn't hold. Your way is still right modulo the point I just made.
Comment: So the question isn't to simplify the left side until it's !Q? If so, then I'm guessing I should have included the right side ( => !Q) and simplify the whole expression? If so, how do I know when to stop symplifying? I'm sorry about all these questions but I always had a problem with symplifying expressions.
Comment: Aww man sorry about it but I made a mistake when typing out the question its (!(P.Q) + R)(!Q + P.!R) <=> !Q, so it's asking me to simplify the left side to prove that it's equal to !Q?
Comment: Your question is to prove that $((PQ)' + R)(Q' + PR) \implies Q'$ is a propositional tautology which is the same as simplifying $((PQ)' + R)(Q' + PR) ≤ Q'$ to $1$.
Comment: Ok, in that case $(P' + R)(PR')$ actualy cancels itself out however it wouldn't be needed for the alteranative question. You should definitely write the question accordingly to what do you want to ask…
Answer: Indeed, your work is correct. Let's shorten things up, though, using the Distributive Law  (D.L.) twice immediately following the application of DeMorgan's:
$\begin{align}(\overline{P\cdot Q} + R)\cdot (\overline Q + P\cdot \overline R) &= (\overline P + \overline Q + R)\cdot(\overline Q + P\cdot \overline R) \tag{DeMorgan's} \\ \\ & =  \overline Q + (\overline P + R)(P\cdot \overline R) \tag{D.L.} \\ \\ & = \overline Q + (\color{blue}{\overline P\cdot P}\cdot \overline R) + (\color{red}{R}\cdot P\cdot \color{red}{ \overline R}) \tag{D.L.}\\ \\ & = \overline Q + \color{blue}{ 0} + \color{red}{\bf 0} \tag{$A \cdot \overline A = 0$}\\ \\ &= Q'\end{align}$
Comment: $\Large{+}^\infty $
Comment: @amWhy: very instructive +1
Answer: Yes your simplification is right, but can be done shorter way:
$((PQ)' + R)(Q' + PR') = (P' + Q' + R)(Q' + PR') = Q' + (P' + R)(PR') = Q' + P'PR' + RPR' = Q' + 0 + 0 = Q'$.


Consultar funcionarios com nomes iguais e CPF diferentes

Question: Problema:
Preciso consultar funcionários que possuem nomes iguais porém com CPF diferentes.
Segue exemplo da estrutura da tabela
create table #tmp (nome varchar(255), cpf varchar(255))

insert into #tmp values ('lucas tiago', '35859764847')
insert into #tmp values ('lucas tiago', '12345678980')
insert into #tmp values ('joao da silva', '35859764847')
insert into #tmp values ('joao santos', '12345678981')

nome             cpf
lucas tiago      35859764847
lucas tiago      12345678980
joao da silva    35859764847
joao santos      12345678981

No exemplo acima, o funcionario lucas tiago tem 2 cadastros, porem com cpf diferentes,
quero que traga apenas esses 2 registros.
Como fazer a consulta ?
Comment: Vê se te ajuda: https://pt.stackoverflow.com/questions/414077/procura-duplicidade-na-tabela/414082#414082
Comment: ué? Não seria só buscar pelo nome? Se nenhum CPF se repete, só haverá um "Fulano Silva" com CPF 123, mas se existe outro "Fulano Silva" com CPF 456, e vc realizar a busca pelo nome "Fulano Silva", vai retornar todos os: Fulano Silva. Não é isso ou há outra questão fora esse SELECT .. `nome LIKE '%Fulano Silva%'`. Fiquei curioso e seria interessante vc colocar no corpo da questão a instrução SQL que vc montou, como está o seu SELECT
Answer: No seu caso, teria que fazer um join com a mesma tabela linkando o nome e utilizando having count:
SELECT

    #TMP.NOME
    ,#TMP2.CPF

FROM
    #TMP
JOIN
    #TMP AS #TMP2
ON #TMP2.NOME = #TMP.nome

GROUP BY
    #TMP.NOME,
    #TMP2.CPF

HAVING COUNT(#TMP.NOME) > 1```

Comment: Ótimo, resolveu meu Problema. Muito Obrigado!


add columns to a table based on core data readout in specific order

Question: The situation:
there are two tables, a main table and a secondary table. the main table is connected to a core data database.
i have set up the core data and the main table just like i wanted it.. everything is working fine and i am happy about it.
now i have to add the columns to the second table.
basically the second tableview has a single column (image & text table cell view). i would need to add a column for each row of the first tableview (the one conected with the core data's array controller) as a checkbox column, and the header of this column should have the value stored in arrangedobjects.header. but this is not it. these new columns should be in a specific order: ascending order, based on the arrangedobjects.order value from the first table.
this should be executed whenever i hit a update button on the interface.
so the questions are:
-how can i add columns to the second table view based on the number of rows of the first tableview?
-how can i order the columns based on the value stored in a column from the first tableview?
-how can i set the column to a checkboxcolumn programatically?
-how can i programmatically set the column header to a value stored in the arraycontroller?
example of the desired result:
TABLE 1 (connected to core data)
<code> somecolumn | header | order | somecolumn | somecolumn
 ------------------------------------------------------
 text        hd1       3       text         text
 text        hd3       1       text         text
 text        hd4       7       text         text
</code>
Structure of TABLE 2: (all checkbox columns except the first, column order based on "order" field of TABLE 1, column header based on "header" filed of TABLE 1)
<code> existingcolumn | hd3 | hd1 | hd4
</code>
again, PLEASE be as clear as possible.
thank you
Best regards
Igor
I already made a similar question in the past, but this one has way more content in it, thats the reason why i am starting a new one. i searched the web and found no answer to this specific question. also please keep in mind that i am a newbie at objective-c/cocoa programming so please be clear in your answers.
Answer: -how can i add columns to the second table view based on the number of rows of the first tableview?
Create dynamic columns. you can use <code>[tableView addTableColumn];</code> inside loop for rows.count
-how can i order the columns based on the value stored in a column from the first tableview?
Order means...OrderBy? Sorted, You never sort a tableview, you sort the model array. Sort the array and populate the table.
-how can i set the column to a checkboxcolumn programatically?
For checkbox implementation, find a project here.
Draw a checkBoxCell in the column you want to have checkbox. Or you can do it programatically.
I did it by IB.
You need to create an array that will store the states for each(number of rows) checkboxes.
<code>- (id)init {
    self = [super init];
    if (self) {

        states=[[NSMutableArray alloc] initWithObjects:@"1", @"0", @"1", nil];
    }
    return self; }

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    NSLog(@"Num of rows---- %ld", [names count]);
    return [names count];
}
</code>
Check for tableIdentifier having value "check".
<code>- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    if ([[tableColumn identifier] isEqualTo:@"name"]) {
        return [names objectAtIndex:row];
    }
    else if ([[tableColumn identifier] isEqualTo:@"check"]) {

        return [states objectAtIndex:row];
    }
    else if ([[tableColumn identifier] isEqualTo:@"states"]) {
        return [states objectAtIndex:row];
    }
    return 0;
}
</code>
Update the value of checkbox as per on/off.
<code>- (void)tableView:(NSTableView *)tableView setObjectValue:(id)value forTableColumn:(NSTableColumn *)column row:(NSInteger)row {
    [states replaceObjectAtIndex:row withObject:value];
    [tableView reloadData];
}
</code>
-how can i programmatically set the column header to a value stored in the arraycontroller?
Use this category, or can use one line statement:
<code>@interface NSTableColumn(SetTitle)

- (void)setTitle:(NSString *)inTitle
{
    [[self headerCell] setStringValue:inTitle] ;
    [[[self tableView] headerView] setNeedsDisplay:YES];
}

@end
</code>
EDIT:
Checkbox programatically:
<code>- (NSCell *)tableView:(NSTableView *)tableView dataCellForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    NSButtonCell *cell=[[NSButtonCell alloc] init];
    NSString *strDisplayPlaylistName;
    strDisplayPlaylistName=[playListNameArray objectAtIndex:row];
    [cell setTitle:strDisplayPlaylistName];
    [cell setAllowsMixedState:YES];
    [cell setButtonType:NSSwitchButton];
    return cell;
}

- (void)tableView:(NSTableView *)aTableView setObjectValue:(id)anObject forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex {
    NSCell *aCell = [aTableColumn dataCellForRow:rowIndex];
    [aCell setNextState];
    //NSCell *aCell=[aAddedCells objectAtIndex:rowIndex];
    //[aCell setNextState];
}
</code>
Comment: thanks, but your answer covers only the checkbox managing part of the question. not the adding of the columns based on teh coredata readout, the adding of the checkboxes programmatically, order the columns based on the readout? thanks!
Comment: updated, but not sure about correctness... it too long, and i cant compile check, atleast you will get some idea
Comment: hello! thanks for your answer! by order i mean that i can specify with a numeric value the order or the column. (see example in first post) by "set a checkboxcolumn programmatically" i do not mean to set the check on/off. i mean that if i add a column programmatically (addTableColumn) then i have a textbox column. i have to change this programmatically to a checkboxcolumn. sorry if this was not clear! thanks!
Comment: You want checkbox programatically?
Comment: you wrote: "Draw a checkBoxCell in the column you want to have checkbox. Or you can do it programatically.

I did it by IB."  what i need is to do it programmatically, not with IB.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/23590/discussion-between-sharkyenergy-and-akv)


An elementary question on stochastic processes

Question: First of all some definitions:

Let $(X_t)_{t\in T}$ be a family of random variables on the probability space $(\Omega,\mathcal{A},P)$. We call $(X_t)_{t\in T}$ a stochastic process. Set $\mathbb{R}^T:=\times_{t\in T}\mathbb{R}$ and $\mathcal{B}^T:=\bigotimes_{t\in T}\mathcal{B}$.  Then
  $$
\Phi\colon\Omega\to\mathbb{R}^T, (\Phi(\omega))_t:=X_t(\omega)
$$
  is a $\mathcal{A}-\mathcal{B}^T$-measurable function and $P_{\Phi}:=P\circ\Phi^{-1}$ is the distribution of the process $(X_t)_{t\in T}$ on $\mathbb{R}^T$.

Let $(X_t)_{t\in T}$ be a stochastic process on $(\Omega,\mathcal{A},P)$ and $\Phi$ as above. Then $(\pi_t)_{t\in T}$ is a stochastic process on $(\mathbb{R}^T,\mathcal{B}^T,P_{\Phi})$ which has (because of the definition of $\Phi$) the same distribution on $\mathbb{R}^T$ as $(X_t)_{t\in T}$. It is called canoncial process for $(X_t)_{t\in T}$.

I hope the question is not too silly, but why does $(\pi_t)_{t\in T}$ have the same distribution as $(X_t)_{t\in T}$?
I define
$$
\varphi\colon\mathbb{R}^T\to\mathbb{R}^T, (\varphi(x))_t:=\pi_t(x).
$$
Now it think my question can be reformulated as: Why is
$$
P_{\Phi}=P_{\Phi}\circ\varphi^{-1}?
$$
Answer: Because, even if this is not explained in the question, the functions $\pi_t$ ought to be the canonical projections, then the function $\varphi$ defined in the post is the identity.
Comment: Yes, or simply that, $\varphi^{-1}$ being the identity, Anything$\circ\varphi^{-1}=$Anything.
Comment: Ah, and then it is: $\varphi\circ\Phi=\Phi$ which means: $P_{\Phi}\circ\varphi^{-1}=(P\circ\Phi^{-1})\circ\varphi^{-1}=P\circ (\Phi^{-1}\circ\varphi^{-1})=P\circ (\varphi\circ\Phi)^{-1}=P\circ\Phi^{-1}$?


Which is more likely with perfect six-side dice?

Question: Find the probability of the following
$(i)$ to roll a $1$,then a $2$ and then a $3$ on consecutive roll of a single dice,
$(ii)$to roll three identical dice and have the outcome be a $1$,a $2$ and a $3$.
Which is more likely with perfect six-side dice?

My Attempt:
Probability to roll a $1$,then a $2$ and then a $3$ on consecutive roll of a single dice$=\frac{1}{6}\times\frac{1}{6}\times\frac{1}{6}+\frac{5}{6}\times(\frac{1}{6})^3+(\frac{5}{6})^2\times(\frac{1}{6})^3+(\frac{5}{6})^3\times(\frac{1}{6})^3+.....$
$=\frac{1}{36}$
Probability to roll three identical dice and have the outcome be a $1$,a $2$ and a $3=\frac{6}{216}=\frac{1}{36}$
There are 216 sample points in the sample space when we throw three dices and record the outcomes.Out of them six are favourable.$(1,2,3),(1,3,2),(2,1,3),(2,3,1),(3,1,2),(3,2,1)$
So the two events are equally likely.
But the book answer says $(ii)$ event is more likely.I dont know how.Is some mistake i have made.Please help me.
Comment: The wording of (i) has some ambiguity in it. Your interpretation of (i) is that you can roll the dice as many times as you like until you get those three numbers in order. It makes some mistakes in its setup as you do not consider rolling 1, others, then 1, 2, 3 or 1, 2, others, then 1, 2, 3. With that factored in you should get 100%. The interpretation implied in (i) of the question is that the dice are only rolled 3 times total.
Answer: The first one should just be ${1\over6}\times{1\over6}\times{1\over6}$ and nothing else if you assume you only have three chances of rolling (which is much more natural to think in my opinion and is probably what the intention of the question).
However, based on your formula you seem to assume you have infinitely many chances of rolling.
But you are still wrong because you did not count the cases for, for example $4,5,1,2,5,1,2,3$ in which "1" appears but "123" does not fully appear. If you really had infinite number of chances the probability would converge to $1$.
Answer: Let's rephrase the question:
Which is more likely with perfect six-sided dice?

Roll $1$ die $3$ times and get 1, then 2, then 3
Roll $3$ dice $1$ time and get 1, 2, 3

Obviously, without even computing the probabilities, the second option is more likely.
This is because in the first option the order matters and in the second option it doesn't.

That said, let's compute the probabilities:

Roll $1$ die $3$ times and get 1, then 2, then 3:

$$\frac{1}{6^3}=\frac{1}{216}$$

Roll $3$ dice $1$ time and get 1, 2, 3:

$$\frac{3!}{6^3}=\frac{6}{216}$$


Show that $F((X))$ is a field and that $\mathbb Q((X))$ is the fraction field of $\mathbb Z[[X]]$.

Question: 1) Let $F$ be a field and $$F((X))=\left\{\sum_{n=m}^\infty a_nX^n\mid m\in \mathbb Z, \ \ a_n\in F {\rm \ for  \ all \ } n \geq m \right\}.$$
I have shown that $F((X))$ is a ring but how can I show that all elements are invertible ?
2) How can I show that $\mathbb Q((X))$ is the fraction field of $\mathbb Z[[X]]$ ? I tried to show that if $R$ is an integral domain and $K$ its fraction field then $K((X))$ is the fraction field of $R[[X]]$ but I didn't succeeded.
Comment: Are you sure $\mathbb{Q}((X))$ is the fraction field of $\mathbb{Z}[[X]]$? I'm 80% sure that this doesn't hold for general integral domains, and 50% sure that it's not true for $R = \mathbb{Z}$.
Answer: If you have a nonzero element in $F((X))$, then you can assume it is
$$
f=\sum_{n\ge m}a_nX^n
$$
with $a_m\ne0$. Then
$$
f=X^m\sum_{n\ge m}a_nX^{n-m}=
X^m\sum_{n\ge 0}a_{n+m}X^n
$$
Now a power series
$$
\sum_{n\ge0}b_nX^n
$$
with $b_0\ne0$ is invertible in $F[[X]]$: you want to find $(c_n)$ so that
$$
\biggl(\,\sum_{n\ge0}b_nX^n\biggr)\biggl(\,\sum_{n\ge0}c_nX^n\biggr)=1
$$
which means $b_0c_0=1$ and, for $n>0$,
$$
\sum_{k=0}^n b_{n-k}c_k=0
$$
The equation for $n=1$ gives $c_1$, the one for $n=2$ gives $c_2$ and so on. More formally,
$$
c_0=b_0^{-1},
\qquad
c_n=-b_0^{-1}\sum_{k=1}^n b_{n-k}c_k\ \ (n>0)
$$
so $c_n$ can be determined as soon as $c_0,\dots,c_{n-1}$ have been.
Since $f$ is the product of two invertible elements in $F((X))$, it is invertible.
Unfortunately, $\mathbb{Q}((X))$ is not the field of fractions of $\mathbb{Z}[[X]]$, so the statement you were given cannot be proved, see What is the fraction field of $R[[x]]$, the power series over some integral domain?
Answer: For (1), we can use explicit formula: if the degree of the leading term of $f$ is less than the degree of the leading term of $g$, then we have geometric series that converges in the field of Laurent series:
$$ \frac{1}{f - g} = \frac{1/f}{1 - g/f} = \frac{1}{f} + \frac{g}{f^2} + \frac{g^2}{f^3} + \ldots $$
For example, to invert $s$, we can take $f$ to be its leading term and $g = f-s$. The resulting formula only requires inverting scalars.

I believe (2) to be false, but can't work out the details at this moment. Instead, I believe the fraction field to be the subfield of elements of the form $a X^n f(bX)$, where $a,b \in \mathbb{Q}$, $n \in \mathbb{Z}$, and $f \in \mathbb{Z}[[x]]$.
That is, I conjecture that the fraction field is the subfield of rational Laurent series for which the coefficients' denominators don't grow too fast. (and the above conjecture a specific meaning of 'too fast')


Use google cloud mysql database in .net application on local machine

Question: How can we use google cloud database for local.net web application without deployed .net app on google cloud?
Comment: What database do you want you use?
Comment: using MySQL database
Comment: Can you give some details about what problems you are running into.  For example, have you followed the instructions on [this page](https://cloud.google.com/sql/docs/mysql/connect-external-app) for connecting to a Cloud SQL instance from an external application?
Answer: You can connect directly to Cloud SQL using either of the following options:

whitelisting your IP address and connect using the Public IP of your instance
you can run the Cloud SQL proxy locally which will forward the traffic to the instance


How can I draw a graph with a date axis using C++ and ZedGraph?

Question: I have successfully used the C++ example project to draw graphs from my C++ project using ZedGraph. However there is no example with Date axis for C++.
The following code is taken from the C# example found at
http://zedgraph.org/wiki/index.php?title=Tutorial:Date_Axis_Chart_Demo. Please see my comments with the text //JEM// to see where my problem is
    PointPairList list = new PointPairList();
    for ( int i=0; i<36; i++ )
    {
        double x = (double) new XDate( 1995, 5, i+11 );

        >  //JEM //This line above doesn't work in
        > C++.

        double y = Math.Sin( (double) i * Math.PI / 15.0 );
        list.Add( x, y );
    }

    ....missing code...

    // Set the XAxis to date type
    myPane.XAxis.Type = AxisType.Date;

    //JEM //This one also doesn't work even if I change it to the
    //syntax that C++ understands, that is,
    myPane->XAxis->Type = AxisType->Date;

Comment: So you took a bunch of C# code, tried to just change the symbols around and make it work? There's no way that it going to happen. You need to get a real C++ example and use that.
Comment: It looks like ZedGraph is only usable at this point from managed code, so I've re-tagged it as such.
Answer: Maybe C++ has some problems with the anonymous variables?
Try to create a XDate object first before converting it to double.
XDate date = new XDate( 1995, 5, i+11 );
double x = (double)date;

Answer: Thanks Gacek.
This is how it finally went down. Your answer was the turning point!!!
    for ( int i = 0; i < basin.DY; i++ ){
           XDate dato(1995,9,i,0,0,0); //date
           double x = (double)dato;
            //double x =  i;
           double y =  basin.Qsim[i];
           double y2 = basin.Qobs[i];
            list->Add( x, y );
            list2->Add( x, y2 );
    }
    //set the XAXis to date type
    myPane->XAxis->Type = AxisType::Date;

here is the constructor for the  Xdate type for c++ from sourceforge dot net documentation/html/M_ZedGraph_XDate__ctor_3.htm.
  XDate (int year, int month, int day, int hour, int minute, double second)
I have also found a detailed example on this link http://www.c-plusplus.de/forum/viewtopic-var-t-is-186422-and-view-is-next.html
with the following code
        /// ZedGraph Kurve //////////
private: void CreateGraph( ZedGraphControl ^zgc )
{
   GraphPane ^myPane = zgc->GraphPane;

   // Set the titles and axis labels
   myPane->Title->Text = "Gewichtskurve";
   myPane->XAxis->Title->Text = "Tag";
   myPane->YAxis->Title->Text = "Gewicht in Kg";

   // Make up some data points from the Sine function
    double x,y;
   PointPairList ^list = gcnew PointPairList();
   for ( int i=0; i<36; i++ )
   {
     x = (double) gcnew XDate( 1995, 5, i+11 );
      y = Math::Sin( (double) i * Math::PI / 15.0 );
      list->Add( x, y );
   }

   // Generate a blue curve with circle symbols, and "My Curve 2" in the legend
       LineItem ^myCurve = myPane->AddCurve( "Trainingskurve", list, Color::Blue,
       SymbolType::Circle );

       XDate ^xdatum = gcnew XDate ( 1995, 1, 1);
       xdatum->AddDays ( 1 );

       myPane->XAxis->Type = AxisType::Date;

Comment: Great, glad I helped a bit. You should either accept mine or yours answer to mark this question as solved.


Display all font file characters

Question: I'm wondering if there is a way to display all font file characters using HTML/CSS/JS/PHP?
Let's say I would like to display all possible "Arial" characters. Or characters from custom @font-face font.
Answer: Fonts can map a wide range of Unicode characters, using codes from 0 to 0x10FFFF. Thus if you really want to see everything in any random font, doing it in a loop as has been suggested in other answers is really going to be problematic. Even for the "simple" example of Arial, the lowest mapped character is U+0020 and the highest is U+FB02. Not everything in that range is mapped, however, so if you did that in a loop you'd end up with a lot of empties. Not to mention it would likely be pretty slow.
To do what you want effectively, you're going to need something to crack open the font file, examine the cmap table, and get a list of mapped characters (not a range). I'm not sure what your setup is, but you could probably do this server-side with something like FreeType or some such.
Comment: Valuable information. Thank you! I just wanted to obtain something like Windows 7 "Character Map" where it displays all possible chars the font comes with.
Comment: Yep. The only way to do that is to look at the font's cmap table (and that's precisely what Character Map does).
Answer: I would like to suggest you try GD library imagettftext() function.
Example from manual:
<code>// Set the content-type
header('Content-Type: image/png');

// Create the image
$im = imagecreatetruecolor(400, 30);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);

// The string with character sets
for($i=0; $i<256; $i++){
     $text.= chr($i);
}

// Replace path by your own font path
$font = 'arial.ttf';

// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
</code>
Comment: You would have to generate a new image with ajax if you wanted to change the font with jquery or you would have to have all images pre-rendered.
Comment: It's a nice feature but I was more interested in printing content (all characters) from font file (like arial.ttf). Your answer will be surely useful, too in some cases.
Comment: In my edit I have included the testing string that has all the characters.
Answer: You can just use the chr function with a for loop. You will have some characters that don't exist but it is quick and easy. If you want you can be more specific about your start and end ascii value.
<code>for($x=1;$x<=255;$x++) {
    echo chr($x) . " ";
}
</code>
Then you can just us jquery to change the font face dynamically.
Comment: There's no guarantee that 0-9, a-z and A-Z will be in any random font, particularly an @font-face font which may have been subsetted to reduce the size. The only way to be sure is to examine the specific instance of the font.
Comment: Thanks! I think that this answers the question, however, I'd like to also skip missing characters. Is there any range for those characters? How can I know what is the number of first and last available character?
Comment: Different fonts have different available characters. I'm not sure how you would skip the blank ones. I'll play around with it and see if I can figure something out.
Comment: Are you looking mainly for 0-9, a-z, and A-Z? Those should be available in all fonts and we can narrow it down to those ranges.
Answer: I had a similar situation, and I resolved it parsing the .svg file. So if you don't have the file in SVG you can convert ttf to SVG and then parse it to get the unicode of the available characters.

Display all font file characters


How to notate scores when the keys don't admit a heptatonic scale?

Question: I was playing with microtonality. Specifically, equal temperaments other than 12edo. Since the point of equal temperaments is versatility, I wanted them to admit a notion of key signatures similar to those of the standard 12edo. My requirements were:

The white keys shall represent the default scale.

The perfect fifth (C-to-G) shall approximate Pythagorean, and the white keys shall be along the generated circle of fifths.

No monotonic scales.

Sharps (resp. flats) shall be positive (resp. negative).

One unit of sharp (that is, for example, half-sharp if appropriate) on an appropriate white key shall transpose the scale (whatever the default scale was).

After some investigation, it turns out many of EDOs don't admit a heptatonic scale. For 22edo as an example, it doesn't admit a heptatonic scale, but a pentatonic scale. Picking the pentatonic major mode as an example, some examples of key signatures are (+/- for one step, #/b for two steps):

(White key position in steps: C=0, D=4, E=8, G=13, A=17)
C pentatonic major: C, D, E, G, A
C# pentatonic major: C#, D#, E#, G#, A#
D pentatonic major: D, E, G-, A, C-
E pentatonic major: E, G-, A-, C-, D-
E+ pentatonic major: E+, G, A, C, D
G pentatonic major: G, A, C-, D, E
A pentatonic major: A, C-, D-, E, G-

For 41edo as another example, it doesn't admit a heptatonic scale either, but a dodecatonic scale. That is, we need to take extra characters for some white keys. Let me notate them by Cyrillic (+/- for one step):

(White key position in steps: C=0, Д=3, D=7, Э=10, E=14, F=17, Ф=21, G=24, Я=27, A=31, Б=34, B=38)
C chromatic: C, Д, D, Э, E, F, Ф, G, Я, A, Б, B
Ф chromatic: Ф, G, Я+, A, Б+, B, C+, Д+, D, Э+, E, F+
Ф+ chromatic: Ф+, G+, Я++, A+, Б++, B+, C++, Д++, D+, Э++, E+, F++
F chromatic: F, Ф-, G, Я, A, Б, B, C, Д, D, Э, E
G chromatic: G, Я, A, Б, B, C, Д+, D, Э, E, F, Ф

So far, what I've defined are the white key names, the scale they represent, and how key signatures work for them. This arises some questions. The standard five-lines score is designed for the major scale, which is heptatonic. Would it be appropriate to modify the number of lines, so pentatonic/dodecatonic/whatever scale could be notated over? If so, how would clefs work?
Comment: Have you seen microtonal accidentals before? I think they have been pretty popular for notating music that is not 12ET
Comment: @ToddWilcox In my perspective, most microtonal accidental systems, such as sagittal, just "don't cut it". My question is not about what accidentals look like anyway.
Comment: Why the downvote?
Comment: I'm only wondering why you're trying to invent a new way to notate something when a way to notate it already exists and is already understood by others. If your question about a downvote is to me, I didn't downvote
Answer: Your question is based on a partial misconception. The five-line staff is not based on the major scale (it predates major/minor tonality) and has more to do with readability: fewer lines admit too few notes; more lines are visually confusing.
The staff lines and spaces represent white keys. As such, they can retain that meaning, and the five-line staff, within any system you develop. The clefs just assign a particular line or space to a particular pitch. So you could create clefs that correspond to your "new" white keys.
This staff, new clefs, plus appropriately defined accidentals, should allow for your scales to be fully notated in a way that looks like the standard heptatonic scales: that is, one line or space per note-name.
Comment: @Dekkadeci One line would be C, the adjacent space would be Д, the next line would be D, the next space Э, and so forth. The in-between notes would be accommodated by accidentals.
Comment: How do you support the 41edo dodecatonic scales (that the question mentions) in your answer? One space/line per edo? One space/line per 2-3 edo and accidentals to match? I've read that 19edo reaches the limit of our note names and typical accidentals to represent notes with unique pitch classes with unique note labels: assign single flats, sharps, and naturals to every note name, and the maximum we can support is 21edo.
Answer: It took me a bit to figure out what you mean by "admit a heptatonic scale". The sharp sign results in going up 7 5ths and down 4 octaves. Your last requirement ("One unit of sharp...") requires the sharp to equal one edostep, correct? Assuming heptatonicism, it only does so for the sharp-1 edos, which are edos 5, 12, 19, 26, 33, 40 and 47. Whereas 22edo is a sharp-3 edo, because from C to C# is 3 edosteps. And 41edo is a sharp-4 edo.
The Stern-Brocot tree (with improper fractions such as 9/15 included) in the region around 4/7 and 3/5 makes it easy to find an edo's sharpness. The sharp-1 edos define a sharp-1 line. The sharp-2 line is roughly parallel to the sharp-1 line.
The S-B tree also tells you what "framework" allows your last requirement to be met. 22edo's 5th is 13 edosteps, and one of 13/22's S-B ancestors is 3/5, which implies a pentatonic framework. Likewise one of 24/41's ancestors is 7/12, implying a dodecatonic framework.
You can indeed notate 22edo pentatonically and 41edo dodecatonically. You can change the number of lines in the staff from 5 to 4 or 7 or whatever. You can use the standard clefs, which are actually just giant letters. The treble clef is a G, and the low G note is circled. The bass clef is an F, and the high F lies between the two dots.
But there are many edos that cannot be notated by only changing the framework. Consider edos 15, 21, 24 and 34. These are improper fractions on the Stern-Brocot tree. The circle of 5ths does not include every note, and microtonal accidentals are absolutely unavoidable.
In addition there are edos for which the appropriate framework will be too large to be practical. For example, 49edo requires a 22-note framework. 59 requires 27 notes, but there are only 26 letters!
So alternate frameworks are not a complete answer. Might as well stick with the heptatonic framework and standard staffs and clefs. Then the years that musicians have spent learning to effortlessly sight-read will not be for naught!
So assuming the heptatonic framework, which microtonal accidentals to use? This paper explains how to notate edos 5-72 using only two new accidentals: https://tallkite.com/misc_files/notation%20guide%20for%20edos%205-72.pdf. 22-edo would be notated as
C, ^C/Db, vC#/^Db, C#/vD, D, ^D/Eb, vD#/^Eb, D#/vE, E, F, ^F/Gb, vF#/^Gb, F#/vG, G, ^G/Ab, vG#/^Ab, G#/vA, A, ^A/Bb, vA#/^Bb, A#/vB, B, C
Comment: I was also getting hung up on "admitting".  Thanks for making sense, and welcome!


Why is the name "orthogonality"?

Question: Let $G$ be a finite abelian group and $\hat G$ be the character group of $G$.Let $G=\{a_1,a_2,...,a_n\}$ and $\hat G=\{f_1,f_2,...,f_n\}$.$a_1$ is the identity of $G$ and $f_1$ is the principal character.Then we have the following relations:
$\sum\limits_{i=1}^n f_i(a_j)=\begin{cases}n &\text{if }j=1\\0&\text{otherwise} \end{cases}$
and,
$\sum\limits_{j=1}^n f_i(a_j)=\begin{cases}n &\text{if }i=1\\0&\text{otherwise} \end{cases}$
I want to know why these are called "orthogonality" relation.I want to find suitable reason for nomenclature.
The definition of orthogonal which we know is something like $f_i(a_j)=\begin{cases} 1 &\text{if } i=j\\0&\text{otherwise}\end{cases}$
But here it is not so.So can someone explain me the reason behind the name "orthogonality".
Comment: Your definition describes orthonormality.
Answer: These relations say that the characters of $G$ are orthogonal for the inner product $\langle .,. \rangle$ defined on $\mathbb C^{G}$ (the space of all functions from $G$ to $\mathbb{C}$, which has dimension $n$) by
$$\langle \varphi, \psi \rangle  = \frac{1}{n} \sum_{g \in G} \overline{\varphi(g)}\psi(g)$$
Comment: I edited the post as set of all functions from $X$ to $Y$ is denoted by $Y^X$,
Comment: @KishalaySarkar Yes, typo.
Answer: The orthogonality of the first relation can be extracted if we write $a_j$ as a product of two elements. That is
$$
\frac1n\sum_{i=1}^n\overline{f_i(a_u)}f_i(a_v)=
\begin{cases}
1 & u=v \\
0 & \text{otherwise}
\end{cases}
$$

Why is the name "orthogonality"?


Z3 returning unknown for a simple query involving integer division

Question: Here is a simple Z3 query that involves integer division (i.e., nonlinear operations):
(declare-const a01 Int)
(declare-const a02 Int)
(assert(or (= (/ a01 a02) 2) (= (/ a02 a01) 2)))
(assert( > a01 0))
(assert( > a02 0))
(check-sat)

Z3 returns uknown for when attempting to solve this query. I understand that nonlinear integer arithmetic is undecidable, but I was still hoping that Z3 would be a bit less fragile in practice.
Please let me know if I am missing some obvious parameters that I could set for Z3 to help it to solve such queries. I am using Z3 4.4.1 and I tried the version on rise4fun too. Thanks!
Answer: Use div instead of /.
(declare-const a01 Int)
(declare-const a02 Int)
(assert(or (= (div a01 a02) 2) (= (div a02 a01) 2)))
(assert( > a01 0))
(assert( > a02 0))
(check-sat)


Confusion on delta function

Question: How should one deal with $\delta(x-y)\partial_x[f(2x+y)\delta(x+y)]$? In other words, what is
\begin{equation}
\int\phi(x,y)\delta(x-y)\partial_x[f(2x+y)\delta(x+y)] dxdy ?
\end{equation}
My attempt was
\begin{align}
& \int\phi(x,y)\delta(x-y)\partial_x[f(2x+y)\delta(x+y)] dxdy \\
=&\int\phi(x,y)\delta(x-y)[\partial_xf(x)\delta(x+y)+f(x)\partial_x\delta(x+y)] dxdy\\
=&\phi(0,0)f'(0) + \int\phi(x,y)\delta(x-y)f(x)\partial_x\delta(x+y) dxdy
\end{align}
I am not 100% sure if the steps above are correct. Also, I am still confused by the term $\int\phi(x,y)\delta(x-y)f(x)\partial_x\delta(x+y) dxdy$.
Please help, thank you very much!
Answer: Hint: notice that $$f(2x+y)\delta(x+y)=f(-y)\delta(x+y)$$can you finish now?
Comment: Thank for the hint. However, I still don't know how to deal with two delta functions with a derivative on one of them, $\int \phi(y,y)f(-y)\delta(x-y)\partial_x\delta(x+y) dxdy =?$
Answer: The usual product rule still holds. We have
$$g(x, y) = \frac \partial {\partial x}(f(2 x + y) \delta(x + y)) =
2 f'(2 x + y) \delta(x + y) + f(2 x + y)\delta'(x + y), \\
\int_{-\infty}^\infty \delta(x - y) g(x, y) \phi(x, y) dy =
g(x, x) \phi(x, x), \\
\int_{-\infty}^\infty g(x, x) \phi(x, x) dx =
f'(0) \phi(0, 0) - \frac 1 4 \frac d {dx} (f(3 x) \phi(x, x)) \bigg\rvert_{x = 0} = \\
\frac {f'(0) \phi(0, 0) - f(0) \phi^{(1, 0)}(0, 0) - f(0) \phi^{(0, 1)}(0, 0)} 4, \\
\delta(x - y) g(x, y) =
\frac {f'(0) \delta(x, y) + f(0) \delta^{(1, 0)}(x, y) + f(0) \delta^{(0, 1)}(x, y)}
4.$$

Confusion on delta function


Apresentar uma caixa de texto formatada para preenchimento

Question: Bom dia
Senhores, pesquisei na internet inteira mas acho que não soube me expressar por isso venho lhes perguntar…
tenho um comando VB para alterar o ip do win7 mas gostaria que o comando perguntasse qual ip eu gostaria de colocar segue comando…
' ## Script para alterer ip da Placa de Rede ##

Set objWMIService = GetObject("winmgmts:\.\root\cimv2")
Set colNetAdapters = objWMIService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE")

strIPAddress = Array("10.10.0.7") 'Coloque o IP fixo
strSubnetMask = Array("255.255.255.0") 'Coloque a Mascara de SubNet

strGateway = Array("10.1.1.1") 'Coloque o Gateway
strGatewayMetric = Array(1)

strDNS = Array("184.108.40.206","126.96.36.199") 'Coloque o IP DNS

For Each objNetAdapter in colNetAdapters
    errEnable = objNetAdapter.EnableStatic(strIPAddress, strSubnetMask)
    errGateways = objNetAdapter.SetGateways(strGateway, strGatewaymetric)
    objNetAdapter.SetDNSServerSearchOrder strDNS
Next

Na parte strIPAddress = Array("10.10.0.7") 'Coloque o IP fixo gostaria que abrisse uma caixa de texto pra o usuário alterar o final ou se não for possível o ip inteiro, por exemplo:
10.10.0.___

Comment: Para apresentar uma caixa de texto personalizada vc pode usar o componente "Microsoft Maked Edit Control", com ela é possível criar mascaras para o texto.
Answer: A forma mais simples é utilizando um inputbox. Exemplo:
ip = InputBox("Coloque o IP fixo", "Mudar IP")

Uma outra forma mais trabalhosa mas que traria resultados estéticos melhores seria fazer um form e chamar ele retornando o resultado pra sua variavel.
Comment: strIPAddress = Array InputBox("Frase de descricao", "Titulo da box") 'Coloque o IP fixo
Comment: deste jeito nao entendi muito bem?
Comment: alterei para ficar mais claro
Comment: Bom se eu entendi ficaria assim
Comment: strIPAddress = InputBox("Coloque o IP fixo", "Mudar IP")
Comment: vou ser sincero nao eh minha praia vbs
Comment: sim, é isso, a caixa de texto irá aparecer com o titulo mudar ip e uma descrição escrito coloque o ip fixo junto de um input e os botões ok e cancelar


Pandas datetime format to prevent NaT

Question: I am reading in an excel file into python with pandas.
xls = pd.ExcelFile("filename.xlsx")
df = xls.parse('Sheet1')
I have a column in my dataframe (time_since_illness_onset) with datetime objects of the form:
1900-01-03 00:00:00
1900-01-04 04:30:00
I would like to parse these so that I have a column for days, hours and seconds (the year and month here is meaningless).
I had used the following code:
df['time_since_illness_onset'] = pd.to_datetime(df['time_since_illness_onset'], errors='coerce')
df['time_since_illness_onset'] = df['time_since_illness_onset'].dt.day + df['time_since_illness_onset'].dt.hour/24. + df['time_since_illness_onset'].dt.minute/60./24

It seemed to work fine. However, I noticed that for datetimes that are less than one day the above code turns the dates into NaT.
As an example, I had a row in the original dataframe like this:
22:00:00
And after I manipulated the dataframe with the two lines above it turned into a NaT. Any help would be greatly appreciated, thank you!!
Answer: You can specify format of parsed datetimes and then use combine_first for replace NaT by default datetimes parsed without specifying format:
print (df)
  time_since_illness_onset
0      1900-01-03 00:00:00
1      1900-01-04 04:30:00
2                 22:00:00

a = pd.to_datetime(df['time_since_illness_onset'], errors='coerce')
b = pd.to_datetime(df['time_since_illness_onset'], format='%H:%M:%S', errors='coerce')
c = b.combine_first(a)
print (a)
0   1900-01-03 00:00:00
1   1900-01-04 04:30:00
2   2018-01-26 22:00:00
Name: time_since_illness_onset, dtype: datetime64[ns]

print (b)
0                   NaT
1                   NaT
2   1900-01-01 22:00:00
Name: time_since_illness_onset, dtype: datetime64[ns]

print (c)
0   1900-01-03 00:00:00
1   1900-01-04 04:30:00
2   1900-01-01 22:00:00
Name: time_since_illness_onset, dtype: datetime64[ns]

s = c.dt.day + c.dt.hour/24. + c.dt.minute/60./24
#if format HH:MM:SS one default day is necessary substract
df['time_since_illness_onset_new'] = s.where(b.isnull(), s - 1)
print (df)
  time_since_illness_onset  time_since_illness_onset_new
0      1900-01-03 00:00:00                      3.000000
1      1900-01-04 04:30:00                      4.187500
2                 22:00:00                      0.916667

Comment: Thank you! However, not the time is encoded incorrectly. The "time_since_illness_onset_new" for 22:00:00 should 0.91667. How do I do this most efficiently? Thanks!

Pandas datetime format to prevent NaT


Is Android activity really visual representation

Question: Why we call android activity visual representation of android app when it also does background tasks which have nothing to do with visual representation.
Answer: A lot of programmers consider it a bad programming style to write code for background tasks into an Activity class. When aiming towards a clean architecture one would ideally only find representational code in activities. Thus, updating the views that make up the activity. As your question implies, background tasks are better found in separate classes that make up the business logic layer of an Android app.