Tirar animação do button e deixar apenas o campo do CEP visível

Question: Estou com uma dificuldade na qual não consigo resolver... Eu não entendo muito de JavaScript e por isto resolvi perguntar.
Estou editando este site em HTML: https://artnaweb.com.br/pediragua/
E quero tirar a animação do da caixa "Serviço Delivery" e deixar apenas o campo do e-mail.
Segue o código:

$(function() {
 $(".form-button").click(function(t) {
     if (!$(this).hasClass("active")) {
         var i = $(this).hasClass("full-width"),
             s = $(this).outerWidth();
         i && (s = $(this).parent().width());
         var n = $(this).find(".input"),
             a = s - $(this).find(".icon").outerWidth() - $(this).find(".submit").outerWidth() - (n.outerWidth() - n.width());
         i ? n.animate({
             width: a
         }) : n.css("width", a), n.css("display", "inline-block"), $(this).addClass("active"), n.focus()
     }
 }), $(document).click(function(t) {
     $(t.target).hasClass("form-button") || $(t.target).parents().is(".form-button") || $.each($(".form-button.auto-close.active"), function() {
         var t = $(this).find(".input");
         t.css({
             width: 0,
             display: "none"
         }), $(this).removeClass("active")
     })
 })
 });
  body {
margin:0;
padding:0;
min-width:320px;
background:#eee;
font-family:Montserrat,sans-serif;
font-weight:400;
}

form {
max-width:500px;
margin:0 auto;
}

form .row {
margin:10px 0;
}

form h2 {
margin:50px 0 30px;
color:#333;
text-transform:uppercase;
}

form h2 small {
display:block;
margin-top:5px;
color:#999;
font-weight:400;
font-size:14px;
}

.form-button {
vertical-align:top;
white-space:nowrap;
overflow:hidden;
font-size:0;
border-radius:6px;
color:#fff;
display:inline-block;
cursor:pointer;
}

.form-button button.input,.form-button button.submit,.form-button input.input,.form-button input.submit,.form-button label.input,.form-button label.submit,.form-button.active .cta .text {
display:none;
}

.form-button.red {
background:#E74C3C;
}

.form-button.red .submit:hover,.form-button.red:hover {
background:#D64541;
}

.form-button.red .input,.form-button.red .submit,.form-button.red.active {
color:#D64541;
}

.form-button.blue {
background:#22A7F0;
}

.form-button.blue .submit:hover,.form-button.blue:hover {
background:#3498DB;
}

.form-button.blue .input,.form-button.blue .submit,.form-button.blue.active {
color:#3498DB;
}

.form-button.green {
background:#00aae6;
}

.form-button.green .submit:hover,.form-button.green:hover {
background:#03A678;
}

.form-button.green .input,.form-button.green .submit,.form-button.green.active {
color:#0888AD;
}

.form-button.purple {
background:#00bbf2;
width:500px;
}

.form-button.purple .submit:hover,.form-button.purple:hover {
background:#f30015;
}

.form-button.purple .input,.form-button.purple .submit,.form-button.purple.active {
color:#f30015;
}

.form-button button,.form-button input,.form-button label {
vertical-align:top;
font-family:inherit;
color:inherit;
background:0 0;
border:none;
padding:0;
margin:0;
font-size:16px;
height:50px;
line-height:50px;
}

.form-button button:focus,.form-button input:focus,.form-button label:focus {
outline:0;
}

.form-button button.cta,.form-button input.cta,.form-button label.cta {
cursor:pointer;
padding-right:16px;
}

.form-button button.cta .icon,.form-button input.cta .icon,.form-button label.cta .icon {
vertical-align:top;
font-size:20px;
height:50px;
line-height:50px;
padding-left:16px;
}

.form-button button.cta .text,.form-button input.cta .text,.form-button label.cta .text {
text-transform:uppercase;
margin-left:12px;
}

.form-button button.input,.form-button input.input,.form-button label.input {
width:0;
height:16px;
line-height:20px;
padding:17px 5px 17px 15px;
}

.form-button button.submit,.form-button input.submit,.form-button label.submit {
cursor:pointer;
height:50px;
line-height:50px;
font-size:20px;
padding:0 10px;
}

.form-button button.submit:hover,.form-button input.submit:hover,.form-button label.submit:hover {
color:#fff;
}

.form-button.active {
background:#fff!important;
}

.form-button.active .cta {
cursor:auto;
padding-right:0;
}

.form-button.active .submit {
display:inline-block;
}

.fa2 {
margin-top:0!important;
}

        Serviço Delivery

    <input type="text" placeholder="Digite aqui seu CEP" id="share" name="share" class="input" />
    <button type="button" class="submit" onclick="saiesquerdaentradireita()">

    </button>

    Não sabe o CEP? Digite seu endereço.

Muito obrigado!
Comment: Não ficou muito claro o que você quer fazer. Poderia explicar melhor?
Comment: Primeiro você [pede como animar](http://pt.stackoverflow.com/questions/181825), depois como tirar a animação? Acredito que dá para manter a discussão na mesma pergunta.
Comment: Possível duplicata de [Como deixar formulário do CEP deslizando igual o site do ifood?](http://pt.stackoverflow.com/questions/181825/como-deixar-formul%c3%a1rio-do-cep-deslizando-igual-o-site-do-ifood)
Comment: Oi amigos... Desculpa se eu não fui claro... Eu quero apenas deixar o campo do CEP visível... sem a necessidade de clicar no button "serviço delivery" entende? eu quero tirar esta animação que faz abrir o campo do CEP.. E
Comment: Dá um click() no botão dentro de $(document).ready(function(){    })
Comment: Oi amigo @Onaiggac como eu disse na descrição, eu não entendo muito de Javascript... poderia formatar esta parte do código por favor? muito obrigado!
Answer: Tenta algo assim
$(function() {
    $(".form-button").click(function(t) {
        if (!$(this).hasClass("active")) {
            var i = $(this).hasClass("full-width"),
            s = $(this).outerWidth();
            i && (s = $(this).parent().width());
            var n = $(this).find(".input"),
            a = s - $(this).find(".icon").outerWidth() - $(this).find(".submit").outerWidth() - (n.outerWidth() - n.width());
     i ? n.animate({
         width: a
     }) : n.css("width", a), n.css("display", "inline-block"), $(this).addClass("active"), n.focus()
 }
 }), $(document).ready(function(){
         $('.cta').click();
     })
 });

Agora é disparado um click nos elementos com classe 'cta' após o término no carregamento da página.
Comment: Olá Amigo.. muitíssimo obrigado!
Realmente agora funcionou! :)
Porém quando eu clico no body do site, o botão volta... por um acaso vc sabe como resolver?
veja: https://artnaweb.com.br/pediraguafinal/
Mais uma vez obrigado!
Comment: Atualizei o código removendo o evento click() do document
Comment: Poxa cara... funcionou perfeito!
Super obrigado... Me desculpa qualquer ofensa.. sou noob ainda em Javascript.. rs
Grande abraço!
Comment: Tranquilo. Abs.


Dynamic SQL Set Golang

Question: I have a doubt about the structure of a SQLite query. I'm trying to update a user-selected value in the table referencing the row by the username.
The table is called Data and has these columns: USERNAME,PASSWORD,ADDRESS,NOTES.
I'm using SQL drivers for GO (_ "github.com/mattn/go-sqlite3"), here's my query:
...
stmt, err := db.Prepare("UPDATE Data SET ?=? WHERE USERNAME=?")
check(err)
res, err := stmt.Exec(splittedQuery[0], splittedQuery[1],splittedQuery[2])
...

From this sequence I can only get a syntax error: near "?": syntax error.
How should I manage this? If it's a trivial question I'm sorry, I'm just new to GO and trying to learn something out of it.
Thanks
Comment: You can not use placeholder for column names.
Comment: Those aren't placeholders. They're parameters similar to Go function arguments. The values never become part of the query. The server compiles the query into an execution plan and then executes it with the supplied parameter values. Next time the same query is encountered, the server uses the existing execution plan with the new parameter values
Comment: It's for that reason that object names (tables, columns, functions etc) can't be passed as parameters. It's like asking to pass function *names* to Go functions and somehow end up calling the function
Answer: You cannot do that in SQL. It's not specific to sqlite either. Parameterized placeholder are only for value, you cannot change the structure of the query with that. Here are some documentation links for your reference:

https://jmoiron.github.io/sqlx/#bindvars
https://use-the-index-luke.com/sql/where-clause/bind-parameters

What you are trying to do is building a dynamic query. You can do that by building your query string yourself:
query := "UPDATE Data SET " + col_name + "=? WHERE USERNAME=?"

But depending from the source of your data for the column_name you need to be cautious of sql injection (this is a whole other topic, for fun you can look at that https://imgs.xkcd.com/comics/exploits_of_a_mom.png).
There are also a few library available to help you with that. For example to name one, you can check this one https://github.com/Masterminds/squirrel
Comment: These aren't placeholders, they're parameters, similar to function arguments in Go.  You can't pass table and column names for the same reason you can't pass type and variable names in Go. The value never becomes part of the query. The server compiles the query into an execution plan and *then* executes it with the supplied parameter values.

Dynamic SQL Set Golang


Redieecionamento na tela de login (HTML5/PHP)

Question: Como faço o redirecionamento na tela de login onde serão 3 tipos de usuário:
1-Admin
2-Funcionário
3-Cliente
E cada um será redirecionado para páginas diferentes.
Comment: atribua um campo oculto, por exemplo: cod_tipo_usuario. Assim quando voce enviar o POST , o arquivo fará um IF ou um switch....e dependendo do resultado, já envia para a página correta
Comment: não entendi muito bem o que vc quer fazer, vc poderia editar a pergunta e acrescentar mais detalhe do problema a ela?
Comment: Faça um [tour](http://pt.stackoverflow.com/tour) tbm para aprender como o site funciona.
Comment: Sua pergunta está ampla demais. Veja se algo aqui ajuda: http://pt.stackoverflow.com/search?q=redirecionamento+php+is%3Aquestion - Sugiro uma lida em [Ask], e depois um clique em [edit] para você explicar melhor seu problema, com base nas orientações.
Answer: Pode usar o header do PHP
<code>if($tipoUsuario=='admin'){
    header('Location: url/do/admin.php');
}else if($tipoUsuario=='usuario'){
    header('Location: url/do/usuario.php');
}else if($tipoUsuario=='cliente'){
    header('Location: url/do/cliente.php');
}
</code>
É isso que precisa?
Comment: Era isso mesmo Neuber Oliveira, muito obrigado.


"Wrong" key signature for a score in F dorian?

Question: TL;DR I'm a bit confused on which key signature to use for a score in F dorian: 4 flats or 3 flats?
I wrote this arrangement of Mad World by Gary Jules back in 2012 using 3 flats as key signature. There were no accidentals in the score.

Then some guys in the comments noticed that the first chords is Fm, so I should have used 4 flats instead. The reasoning seems correct to me, so I updated the score using 4 flats (I basically added D flat).

The problem is that I had to write D natural everywhere, because the notes were correct with only 3 flats, so I basically had to "cancel" the D flat I just added.
I'm a bit confused about which key signature to use: given the notes to me it seems obvious that the "correct" key signature to use is Eb - Cm (3 flats). On the other hand, the first chord of this song is Fm, so it should be Fm (4 flats).
Comment: Just because the first chord is an Fm chord doesn't mean that the piece needs four flats. An Fm chord in an F Dorian piece seems rather natural. I would keep 3 flats.
Comment: My previous knowledge about the song and the harmonic context don't agree with this, but I'll mention it anyway: the first phrase could also sound like finding tonic in Eb major. :D (There's Ab right before with even a leading tone. But then again, with the same reasoning the fifth measure would probably be resolution to Ab. Silly.)
Comment: Related: https://music.stackexchange.com/questions/41225/is-f-lydian-mode-in-the-key-of-c-major
Answer: Upon listening to it, F minor is the tonic chord. It does have Dorian characteristics like you say, namely a major IV chord and melodic D naturals. Is that good enough reason to write it in a key signature of 3 flats? Ultimately it's your call. Here are somethings to think about:
The case for 4 flats:

Players that read are used to having the key signature be fundamentally in whatever minor or major key the song is in regardless of the modal characteristic of the song, and reading the appropriate accidentals.
By putting the song in 3 flats you are chancing someone feeling that the relationship between the actual song and the key signature to be a little odd at first glance.
Since you're using a notation program the D naturals shouldn't be a big chore to add to the music.
Even in non modal music a major IV chord (Bb) is fairly common. Going from i to IV is like a ii-V but starting on the tonic and not resolving but usually going back to the i.

The case for 3 flats:

Like you said, there are no accidentals, it is a very clean looking piece of music.
Historically it is not unheard of to use key signatures to notate modal pieces, or for that matter to use non-traditional key signatures.
For clarity's sake it might not be a bad idea to include a note at the beginning indicating F Dorian if you choose to go this route.
Comment: Regarding the note, I am referring to literally writing "F Dorian" somewhere at the beginning of the piece, perhaps above the first chord symbol or close to the left margin.
Comment: I've seen lots of folk tunes where "F dorian", etc. - the mode - is written at the head of the score.
Comment: Why do you say this is in F minor when there is never a Db? It sounds firmly dorian to me starting in the second bar.
Comment: *"Since you're using a notation program the D naturals shouldn't be a big chore to add to the music."*: I know, musescore added the D naturals automatically, I was complaining about the benefit of having 4 flats, not about the effort to write the naturals. *"For clarity's sake it might not be a bad idea to include a note at the beginning indicating F Dorian if you choose to go this route"*: which note should I add and where?
Comment: @bjb568 This question is not about whether this song Is in F minor or F Dorian, I was just making the point that F minor is the tonic chord, Dorian or otherwise. This question is about how to notate the OP's arrangement, I made a legitimate case for both 3 and 4 flats. Ultimately it is up to the OP to decide how to write it out.
Comment: I also don't understand how you can say this piece is in F minor.  It's not- it's in F Dorian.  It doesn't just have "Dorian characteristics", it's Dorian through and through.  The only "advantage" I can see to writing in four flats and cancelling the Db every time is to insinuate that Dorian is a kind of modification of the "real" key of minor, which is not only historically just about backwards, but ignores the fact that Dorian is very common in popular music- probably more so than minor.  No musician is going to have trouble learning this.  Adding a fourth flat is a classical affectation.
Comment: @ScottWallace Did you read the comment I made before yours?
Comment: @JohnBelzaguy I did indeed read your comment.  But your post starts with "Upon listening to it I agree that the song is fundamentally in F minor." And that's simply not the case.  F Dorian is not the same as F minor.
Comment: @ScottWallace That is true but they are both minor keys. Check my edit, better?
Answer: I agree with the other answers that both are possible, but would err towards four ♭s. Why? Well, the piece isn't really modal Dorian. The vocal melody doesn't use D♮ for the whole verse, and when it does go to that note in the bridge/chorus it's a big reveal. (In spite of The B♭ major chord having turned up earlier in the accompaniment already... but it's worth noting that in the Tears For Fears original, the first verse has just a monophonic synth bass, which also doesn't feature D♮!)
Having an accidental then in the chorus then is not only not detrimental, it actually highlights the note's function.
X:1
L:1/8
M:C
K:Fm
%%score T1
V:T1           clef=treble
% 1
[V:T1] r2 F F A A c c | =dB
w: And I find it kind of FUN-NY!

Comment: I don't hear that personally. But yeah, it's definitely not a typical Dorian feel either. Overall the piece feels much more Aeolian, and then for the chorus it kind of modulates. (The intro of the Gary Jules version is the chorus part, which throws it around a bit.) I wouldn't even say to F-Dorian, because the B♭ major is almost treated as more tonic than the F minor.
Comment: This phrase (though not necessarily later ones) even looks like a F melodic minor which would have the D♮.
Comment: There D natural appears in the first bar in the melodic line and in the chords in the second bar. It appears again several times in the chords. Thus it is of no surprise when it appears in the melodic line later on. There is no D flat anywhere in the piece, neither in the melodic line nor in the chords.
Comment: @LarsPeterSchultz that's the intro of the Gary Jules version you're talking about (as I said, it basically uses the chorus as the intro). This does not happen in the original. And the original _does_ contain a couple D♭s too, though only in the weird chromatic brass fills in the later verses.
Answer: The key of a song is not determined by the first chord(s).
The Fm and Bb chords "exist" in Eb major (and, therefore, F dorian) and F minor (as a borrowed chord from major).
Ultimately, the key signature is a guide for the person reading the score. It's your call as the arranger whether you want that person to think of the arrangement in F dorian, in which case three flats is the way to go, or in F minor, in which case use four flats with D naturals in the score.
Answer: In the Baroque period the standard minor key signature was a so-called "dorian" signature, meaning it didn't put a flat on the sixth scale degree, and flats were added as accidentals in the score. So, F minor in the Baroque was three flats, C minor was two flats, etc. Putting the extra flat on the sixth degree in key signatures is a more modern practice.
So there isn't really a right or wrong way in regard to 3 versus 4 flats. It's a matter of general practice. Keep in mind that Baroque practice wasn't for music in dorian mode, it was just the practice for key signatures for minor key music.
I don't think there is a general practice for more modern modal style music. I've seen scores that work both ways. Anyone reading the score should be able to understand either way. Three flats and a tonic of F will be "dorian." Four flats, tonic of F, and consistent D natural accidentals, would also be "dorian."
I put "dorian" in quotes just to indicate despite key signature and tonic, it's possible a piece might not really sound dorian depending on how the harmony/tonality is handled. So, three flats, tonic F, is a sort of provisional dorian.
Answer: Some people perform music by thinking in terms of mechanical actions related to sharps and flats.  Some people perform music by playing the sounds mentally and then operating their instrument or voice to match.  For people using the former approach, having a key signature minimize the use of accidentals may helpful, but for people using the latter approach having accidentals in places where music does something "unusual" may be more helpful.
Although you ask about Dorian, I think an example in Mixolydian may illustrate the point better.  Consider the song "Little Drummer Boy".  If the key note is C, the first seven measures won't contain any B flats or B naturals.  If the Bb at the start of the eighth measure isn't marked with an accidental, people unfamiliar with the song may likely perform it as a B natural even if there's a Bb in the key signature, since they'll have gone seven measures without ever playing a Bb, and most songs which have a key note of C and use a lot of E naturals would use a B natural as well.
Comment: One of the first times I've ever dared disagree with @Tim, BTW...
Comment: @BobBroadley - only just picked up on the comment! Please disagree if necessary! I do make mistakes sometimes, if only to prove I am human after all..! Other times I say what I believe: if we can't do that, then surely we're not human. Keep up the good work!
Comment: Great answer. Personally, I agree with this approach. Notation is just a means to an end: for most proficient readers accidentals in the music *emphasise* the modal quality and impart more "quick" information.
Comment: In other words: a half-second glance to the left confirms F Minor, and a half-second scan through the first few bars spots D naturals, suggesting F Dorian. 1 second to learn a lot about the music, and also to set up what to expect to *read*.
Answer: The point of having a key signature is to give the reader an idea of what's happening as he reads through the piece. 3 flats means he'll expect those 3 notes to be flattened each time they occur, and play appropriately. Unless they get cancelled with an accidental.
Unfortunately that doesn't happen in minor keys, where often the leading note - not marked in the key signature - needs sharpening. It can be the same niggle with modal pieces.
In this piece, with a tonal centre of F, it could be construed as being in key F minor. However, with B♭major cropping up constantly, it obviously isn't. It's in F Dorian, the parent of which is E♭ major. So, those are the notes which will play 'not natural' more often than any other - 3 flats - B♭, E♭ and A♭.
Putting D♭ in the key signature is somewhat of a red herring, and also means each and every D♭ note will need cancelling. Were that the case, most players would soon realise that actually, the key signature putting it into F minor is not ringing true, and it's really a piece in F Dorian, so using the F Dorian key signature (3♭) would suffice.
A good sightreader would play the piece were it written either way - a lot wouldn't give either a second thought. And it would sound exactly the same either way, too. My vote is for 3♭, but with a note on top - 'F Dorian'.
Comment: If someone unfamiliar with The Little Drummer Boy were playing it in G, would they be more likely to correctly play the F natural in measure 8 (about 20-25 seconds into the piece) if the piece were notated with one sharp but the note had a natural accidental, or if the piece was notated without any sharps or flats?
Answer: I'd say write in three flats.  Dorian is a legitimate mode and shouldn't be looked at as a kind of modification of minor.  If musicians don't understand Dorian, they can and should learn- it's not rocket science.
Answer: Sheet music is for the performer. "There are three flats consistently used throughout" is the information the performer needs. You are essentially lying to the performer in including D-flat in the key signature, telling them to expect that some of the Ds may be flattened. I see no benefit in this.
Comment: I disagree.  "The tonic is F" is also information that the performer needs.  Given the rarity of modal music, a performer seeing 3 flats will expect the tonic to be C or E-flat, which isn't the case.
Comment: The performer doesn't need to just play the notes.  They need to play the notes with the right subtle differences of emphasis on different notes to make the music make sense.  A performer who has the wrong idea of what the tonic is will get that wrong.  It's true that any performer who has heard the piece once will (possibly only intuitively) know what the tonic is and get it right, but imagine someone sight reading it cold.
Comment: @AlexanderWoo The performer literally doesn't need to know the tonic, at least, not unless they plan on extended improvisation. Modal music is also very common today, especially dorian and aeolian as "substitutes" for minor in pop; I'd guess that it's been common since the 60s.
Comment: @AlexanderWoo I re-iterate: modality is common in pop music. Even if I agree that it's important to indicate the tonic -- which I don't, we'd use different key signatures for major and minor if that were the case, and anyway, I couldn't name a single composer who indicated every single key change throughout, e.g., the development section of a sonata -- major/minor is just a bad assumption for pop music. Some pop music doesn't even have a clear single tonic, performers just need to learn to use their ears if this is really such a concern for them.
Comment: This may well be different between different musical subcultures/traditions/communities.  But at least in all the communities I've ever made music with (UK/US/Canada, mostly classical music, some folk + pop), @AlexanderWoo's comment is absolutely right — indicating the tonic takes precedence over using fewer accidentals.  I would definitely expect a piece in F dorian to use a standard F minor key signature + accidentals, and I'd find it just a bit distracting to read it with 3 flats.
Comment: I agree, 3 flats is much more clear if you want to play the notes
Comment: @AlexanderWoo - if the 'performer' is reading the dots, he will do just that. Not consider mode or key, just play. The difference isn't even academic..


Adding Standard Widget to Homescreen programmatically

Question: Is it possible to add existing widgets like calender, Music widgets to HomeScreen in Android programmatically?
Thanks,
Bhavani
Comment: What you want to add to your Homescreen? Describe briefly here.
Comment: Say,I want to add Calender widget to Home Screen from my application
Answer: No you can't. Only you can create a widget host yourself and let user add existing widgets to that.


If $f:R \to R$ is a continuous function and there are $a \geq 0$ and $b \geq 0$ such that $\|f(x)\| \leq a\|x\| + b$ then $f$ is uniformly continuous.

Question: I must verify if the following statement is true: if $f:R \to R$ is a continuous function and there are $a \geq 0$ and $b \geq 0$ such that $|f(x)| \leq a|x| + b$ then $f$ is uniformly continuous.
My idea:
It's false. Let $b \in R$. We define $f$ recursively: In the interval $[0,1]$, $f$ increases linearly from $0$ to $b$ in $[0,1/2]$ then decreases to $0$ in $(1/2,1]$, put $x_1=1$. Already defined $f$ in $[0,x_n]$, we put $f$ on $[x_n,x_n+1/n]$ also from $0$ increasing to $b$ then decreasing to $0$, linearly, and put $x_{n+1}=x_n+1/n$. Since $\sum 1/n$ diverges, this process define a continuous function $f:[0,\infty] \to R$. Setting $f(x)=-f(x)$ for $x < 0$. $f$ is a continuous function in the hypothesis of the question ($a=0$) that cannot be uniformly continuous since for any $\epsilon < b$ and for any $\delta > 0$, if we take $1/n < \delta$, we have $|\left(x_n+1/n \right) - x_{n+1}| < \delta$ and $|f(x_n+1/n) -f(x_{n+1})| = b > \epsilon $.
Is my idea wrong? Thanks in advance!
Comment: Presumably, when you write $||f(x)||$ etc., you mean $|f(x)|$ etc.?
Comment: The converse is true. If $f:\mathbb{R}\to\mathbb{R}$ is uniformly continuous then there exists $a,b\in\mathbb{R}$ such that $$|f(x)|\leq a|x| +b $$ for all $x\in\mathbb{R}.$
Comment: Yes! Sorry if it wasn't clear.
Comment: You should edit your post accordingly.
Answer: If you consider $f(x)=xsin(x)$ then you have that
$|f(x)|\leq |x|$ but in any case $f$ is not uniformly continuos.
In any case your counter-example is correct.
Comment: You beat me to it!


How to make async methods that return a boolean?

Question: I have the following method:
     public static boolean getIsUp()
     {
         String method = "isup.php";
         AsyncHttpResponseHandler response = new AsyncHttpResponseHandler(){

         @Override
             public void onSuccess(String content) {
            if(Integer.parseInt(content) == IS_UP_CONTENT)
                //code to return true
            else
                //code to return false
        }

     };
     get(method, null, response);
 }

How would you fill the //code to return true and //code to return false so that the method return the appropriate response? Is that even possible?
Comment: Before you continue, read [this](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java).
Comment: And on top of reading that... instead of `if (condition) else` and writing what will be nearly identical code twice... why don't you just return what the (correct) comparison will evaluate to?
Comment: @SotiriosDelimanolis Ooops, there was supposed to be an Integer.parseInt(content) instead of just content.
Comment: Do you have to use `AsyncHttpResponseHandler`. Does it provide a callback mechanism? Can you instead use a `ScheduledExecutorService` and block on the returned `Future`?
Comment: @SotiriosDelimanolis I am using loopj's AsyncHttpClient and it uses the AsyncHttpResponseHandler. I just took a look at the ScheduledExecutorService, and it seems like a hacky solution. But maybe that is because I am a C# developer and we are just used to the async and await keywords that basically does all this for you.
Comment: That's what `Future.get()` does. It waits until the `Callable` you submit to the `ExecutorService` has finished and returned a value. Maybe `loopj` has corresponding behavior. I've never used it.
Comment: Hmmm. I'l make sure to look into that, thanks!
Answer: I think you should not use an AsyncHttpResponseHandler inside a non-async method if you want to instantly return an result.
What you can do is using an AsyncTask and the onPostExecute Callback

This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.


Traits of calypso music?

Question: I'd like to compose my own calypso music, but I've not been exposed to enough calypso in my lifetime to be able to do so intuitively.
Of course, calypso is instantly recognisable as such, but why?
What "trademarks" are there within calypso music that make it sound, well, like calypso music? What chord structures, rhythms, and melodic patterns will help make my own piece sound more like calypso?
Answer: The following is lifted directly from http://www.misswardmusic.com/caribbean.html
Calypso: Originally the national dance of Trinidad and Tobago, calypso is particularly associated with carnival. It has:

4/4 time with syncopation
acoustic and bass guitar or band with trumpets, saxophones, electric guitars, drum kit and Latin percussion
often uses three-beat rhythms with two long beats followed by a short beat
often uses call and response
simple harmony
verse and chorus songs
topical, witty lyrics - often satirical

Here is a sample Calypso rhythm:

I have no special knowledge about calypso, but I think the list above is nice on concise and matches nicely with my perception as a casual listener.
One other suggestion: try finding folk song books in the library and browse for those in a calypso style. You might be able to find a folk song book devoted to calypso. The 1950's and 1960's in America showed a lot of interest in the general public, Harry Belafonte's first record was released in the early 50's. A lot of these folk song were published shortly after in the 1960's, maybe the 1970's too. I think these could be valuable resources for you.

Traits of calypso music?


Regression model for prediction using intermediate outcomes

Question: Is it appropriate to include intermediate outcomes in a predictive model?
It is quite clear that one should not control for post-treatment variables / intermediate outcomes when the goal is causal inference, but I wasn't sure if the same advice should hold when one's goal is to build a model for prediction.
Here is some context for my question: I'm trying to build a model that predicts if a college student will earn a bachelor's degree within 6 years of high school graduation using a large observational data set. I have data on students' high school variables (HS GPA, test scores, number activities participated in, etc.), some data on the students' college experiences (delayed enrollment in college, full-time / part-time status, transferred within two years of enrolling), as well as data on the characteristics of the college they attend. In other words, I have student level and institutional level data. I would account for the nesting of students within a particular institution.
Some have told me that the student level data on college experiences are intermediate outcomes and I shouldn't include them in the model. It isn't clear to me if I should / could include the college experience variables (which could be considered intermediate outcomes) in the predictive model, and if I do include them, how they should be treated.
Comment: Can you say what you are going to use the model for?  I am skeptical that you are really only interested in prediction.
Comment: Here's my idea. I have comparable and consistent data from three cohorts of students spanning the 1980s, 1990s, and 2000s. My goal is to see if the predictive ability of the model/variables has changed across cohorts. Given that these are observational data, I think the parameter estimates should only be interpreted as the predicted difference in the response of two individuals that differ by one unit on the regressor in question and that have the same value on all other regressors. I am not making inferences about changes or causality. Thank you.
Answer: I'd strongly discourage including those intermediate outcomes, for the sake of interpreting the parameters. Let's translate "predicted difference in the response of two individuals that differ by one unit on the regressor in question and that have the same value on all other regressors" into the terms of the study question: if you include the intermediate outcomes in the model, you're only comparing students who delayed enrollment to others who delayed enrollment, and comparing students who went to similar colleges to each other. If students with lower high school GPA are also more likely to delay college enrollment, and students who go to private colleges have higher GPAs, a model that includes both variables will only be useful for predicting a student finishing college based on their GPA if you also already know what kind of college they went to. Is that the prediction you need?
Comment: I believe I understand you're comment, but I'm not sure the interpretation is the issue. I thought the comparison would be those that delayed enrollment to those that did not delay, all else being equal (including college characteristics). The college characteristics I have include things like public/private, enrollment size, and funding. Does that help to clarify? I've added more detail to the original post.
Comment: That's right, it's the "all else being equal" that causes the problem, if you know that in fact there is a correlation between the predictors. Then the coefficients only estimate the "independent" effect of, say, GPA adjusted for college characteristics. But since GPA influences what college a student goes to, adjusting for college will mask the effect of GPA on the final outcome.


How to create the the same fragment several times into a Layout?

Question: I have a fragment to register customer addresses (called "address") that contains a "+" button.
I want to create another fragment below this containing the same content so that the customer can add as many addresses as he wants to.
I know it's possible to create components one by one programatically. But, this fragmet is a bit complex and I dont want to create it dynamically.
Is that possible to insert the same fragment several times inside a layout of the fragment itself?
Answer: I got it!
<code>    @Override
public void onClick(View v) {
    LinearLayout newlayout = new LinearLayout(getContext());
    newlayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    newlayout.setId(ConfigFragment.generateViewId());
    LinearLayout parentlayout = (LinearLayout) view.findViewById(R.id.regpet_frame_main);
    parentlayout.addView(newlayout);
    ConfigFragment.openFragment(new RegPetFragment(), newlayout.getId(), getChildFragmentManager(), getString(R.string.title_reg_pet));
}
</code>
Surely new questions will come!!!
Comment: You'd be better off with a class that `extends View` rather than `extends Fragment`
Comment: @cricket , should I just change `extends Fragment ` for `extends View`?
Comment: It's not that easy no. My point was that Fragment seems overkill for what you seem to be doing with dynamic layouts.
Comment: @cricket_007, I'm a newbe here! If you could help me with this, I'd be very tankful! Is there a link to a tutorial or something else that could help me?
Comment: I don't have anything, sorry. I'll phrase the question this way: Why are you not using an `ArrayAdapter` to load a `ListView`? Even if you didn't want it to scroll, that is essentially what I think you've done here.


Windows language for non-unicode programs change leads to error finding font

Question: I have a legacy C++ program I have to maintain. We runs on Windows 7. Recently I encountered a bug in a pdf generation section of the code.
I change Windows' Language for non-unicode programs to Korean (Korea), restart, then run the app. In the pdf generation code, there's this line:
pdf_font = pdf.load_font(L"Malgun Gothic", L"unicode", L"");

(I have no idea what goes inside pdf.load_font)
pdf_font here is -1. If the Language for non-unicode programs is English, there's no problem and pdf_font contains a valid value.
It's as if setting Language for non-unicode programs to Korean (Korea) hides Malgun Gothic font which can be seen before.
I'm not sure if this is a Windows issue or library issue. Any pointers are welcome.
Answer: A general tip, for legacy app that don't support unicode you better run windows in the language it's supposed to be unless you recode the app to be unicode friendly.
I told it as Iam french, and even new application can fail if windows is in english and the french language pack is installed, it need the french windows.


Add dropdown list in tablesorter.js

Question: I want filter and sort option in html table. I tried 'tablesorter.js',
I can sort the table fields by using this module. But I can't add drop down list and filter box with table fields.
Anybody can help me??
Comment: Show Your Code !! Where it gets problem ?
Comment: please tell me how to add dropdown list and filterbox in tablesorter.js http://tablesorter.com/docs/#Demo now my application works like this
Comment: I want to add dropdown list and filter box with the fields.
Answer: Try Using  This.
This is HTML table shorter.
OR
 (DEMO)  for short using drop-down list
$('table').tablesorter();

$('select').change(function(){
    var column = parseInt($(this).val(), 10),
        direction = 1, // 0 = descending, 1 = ascending
        sort = [[ column, direction ]];
    if (column >= 0) {
        $('table').trigger("sorton", [sort]);
    }
});

Comment: I tried it. I want to add dropdown list and filter box with the fields.
Comment: You know any other modules for doing the same??
Comment: You know how to add the dropdown list in a particular field only. For example add dropdown list only to 'Alphabetic' field??
Comment: see this fiddle http://jsfiddle.net/viralshah/Yke6M/38/ Else to short click on other columns and you ll have sorting
Comment: I want dropdown list on table header field. when we click on this dropdown all values in this field will list(no duplicate values). when we select one value from the list, corresponding rows will disply on table. I need this functionality. please help me.
Answer: You can add a drop down list filter to the table column by adding a class="filter-select" to the  for that column in the .

Col 1>	Col2

Or you can add a filter function for that column:
filter_functions : {

    // Add select menu to 3rd column (column numbers are zero-based).
    // Set the column value to true, and/or add "filter-select" class name to header
    2 : true,
}

Add dropdown list in tablesorter.js


Least degree of a polynomial given value of polynomial at $6$ points

Question:
If $p(x)$ is a polynomial of degree $n$ such that $$p(-2)=-15,\ p(-1)=1,\ p(0)=7,\ p(1)=9,\ p(2)=13,\ p(3)=25.$$
Then smalest possible value of $n$ is
Options $(a)\; 2\;\;(b)\; 3\;\; (c)\;\; 4\;\; (d)\; 5$

Try: Tracing curve on coordinate axis, it gave one point of intersection Further $p(x)$ must be an odd degree polynomial. And slope of function is not same in each interval. So it is not linear. So it must have least degree $3$.
Can someone explain me if I am doing right? Thanks.
Otherwise please provide solution.
Comment: I see six points but your title only says five.
Answer: Construct a difference table.
$$\begin{array}{rrrrr}-15&&&&\\
&16&&&\\
1&&-10&&\\
&6&&6&\\
7&&-4&&0\\
&2&&6&\\
9&&2&&0\\
&4&&6&\\
13&&8&&\\
&12&&&\\
25&&&&\end{array}$$
Since the fourth differences are all $0$ and the third differences are not, $p(x)$ can be fitted with a third degree polynomial but not a second degree one.
Answer: There is exactly one fifth (or lower) degree polynomial passing through six points.  You can find it, for example by Newton interpolation or by writing the polynomial as $ax^5+bx^4+\ldots+f$ and writing six simultaneous equations to relfect the data you have.  Solve them for $a,b,c,d,e,f$.  If $a \neq 0$ the polynomial has degree $5$.  The fact that $p(0)=7$ gives $f=7$.
Comment: I'm curious if you know of a simpler method. The phrasing of the question seems to make me think it should be easier than solving so many simultaneous equations (perhaps there is a lot of cancellation that is revealed when actually writing it out, though). I otherwise agree with your answer, I just find it cumbersome. :)
Comment: @Moo:  yes, it is asking for the minimum $n$.  If a cubic fits, it is the unique polynomial of fifth degree or less going through the points and the answer is $b$.  Certainly one could solve for a line going through two points and see it doesn't fit a third, then the quadratic going through three and see it fails, then a cubic going through four and see it works.  Whether that is easier than doing the general solution and finding $a=b=0$ I don't know.
Answer: You do not need to calculate any interpolation polynomial. Here, it is about the minimum degree. So the given points should have a property that makes it possible to find the degree quickly.
When you look at the points you see that the given $x$-values are consecutive integers.
So, you can make a quick check by calculating the first, second and third differences of the sequence of the $y$-values:

sequence: -15,1,7,9,13,25
first differences: 16,6,2,4,12
second differences: -10,-4,2,8
third differences: 6,6,6

As the third differences are constant the degree must be 3.


RailsTutorial: Why is there always some session?

Question: I am following Railstutorial. Now at Chapter 8 where it talks about session.
I am trying to verify session cookie is destroyed everytime user logs out
I am using Firebug->cookie tab to verify that.
But I notice there is always some session whether I login or not.
The only difference I noticed was that there is new session id before login, after valid login and after logout.
So my question is why is there some session everytime
Answer: I'm currently following the Railstutorial as well and have been wondering this myself. I assume you're referring to this exercise in the tutorial (section 8.3):

By checking the site cookies, confirm that the session is correctly
  removed after logging out.

The way I read it, this implies that the session cookie should be removed after logout, but that doesn't seem to be the case. I couldn't really find specific information on this online, so I quickly set up an empty Rails app to see if it would set cookies, too. Lo and behold, apparently every Rails app automagically creates a session cookie, even when you don't do anything session-related in your app-specific code.
This doesn't answer what exactly Rails stores in that cookie, but at least I'm not going crazy. I think the exercise should be removed or at least changed.
Answer: Sessions are used to keep miscellaneous data for your application's users.
Their existence shouldn't depend on whether your users are signed in or not.
For example, a weather website asking users to select their metric system, should be able to remember their choice without requiring them to sign in first.
Of course there are other reasons to always have a session assigned to your users (like logging etc).


How do I use a typed array using a shared buffer efficiently in JavaScript?

Question: In my code I have an object that contains a series of pixel coordinates. Performance of this object is critical because it's being used in a 60fps game where the output cannot always be cached.
After experimentation and benchmarking, a 3D array proved to be the fastest way of implementing it when using untyped arrays:
var PixelCollection = function() {
    this.pixels = [];
};

PixelCollection.prototype = {
    add: function(x, y) {
        var pixels = this.pixels;
        if (pixels[y]) {
            pixels[y].push(x);
        } else {
            pixels[y] = [x];
        }
    },
    each: function(callback) {
        var pixels = this.pixels;
        for (var y = 0, m = pixels.length; y < m; y++) {
            var row = pixels[y];
            if (row) {
                for (var i = 0, mm = row.length; i < mm; i++) {
                    callback(row[i], y);
                }
            }
        }
    }
};

In some situations, the object is not fast enough, so I tried a Uint8Array implementation, using a 2D array:
var WIDTH = 255;
var HEIGHT = 160;

PixelCollection = function() {
    this.pixels = new Uint8Array(WIDTH * HEIGHT);
};

PixelCollection.prototype = {
    add: function(x, y) {
        this.pixels[WIDTH * y + x] = 1;
    },
    each: function(callback) {
        var pixels = this.pixels;
        for (var i = 0, m = pixels.length; i < m; i++) {
            if (pixels[i]) {
                callback(i % WIDTH, Math.floor(i / WIDTH));
            }
        }
    }
}

This is slower. I thought it would be faster because writing to - and reading from Uint8arrays is faster, but since I'm creating a huge object for every PixelCollection object, retrieving pixels is way slower because it takes longer to iterate over all pixels. (Note: I also tried the implementation above with an untyped array: it is a lot slower)
A PixelCollection typically does not have all pixels set. However, the bounding box may span the entire canvas so I do need to create the array using a buffer this big.
There may be a way around that though. I can create one big shared buffer and use a byte offset for every PixelCollection. So when PixelCollection P1 would take up 100 bytes, then PixelCollection P2 would start at byte offset 100. This uses memory more efficiently, but I would need to keep track of the range of bytes every PixelCollection uses (is this what C calls "pointers"?).
Annoying part: when P1's bounding box expands, I need to shift P2 to make space for P1. And I would need to set a safe buffer size for the shared buffer, so I need to make a safe guesstimation of how much memory it needs.
Implementing this is possible, but it would require lots of time, trial and error.
So before start on this: does it seem a good way to do it? Are there better or simpler ways to do this? Do you know any example implementations I could learn from?
Edit: I added a jsperf in case you want to try your hand at an optimization.
Please add to this jsperf if you have a brilliant idea for an optimization.
Comment: You could do it a much simpler way mathematically like this; http://pastebin.com/8ey5a65m
Comment: Your second implementation of `each` is doing a lot more math, have you factored that out as a cause of the speed difference? You can track the values to pass into `callback` rather than using `%` and `/` each time... Another difference (if I'm reading this right) is that you do a lot less traversing in the first implementation when the second dimensions are small (e.g., you haven't done that many calls to `add` for a given `y`).
Comment: I cannot remove that math because I *always* need both x and y in the callback function.
Comment: @ Blaise: That doesn't follow. I didn't say not to pass them in. I said: *"You can track the values..."* E.g., have `x` and `y` variables that you increment and roll over as appropriate.
Comment: Sorry, you're right, you said *tracking*. But tracking also requires math and it is slow as well in my test. (Tracking code inside the for loop: `if (i && i % xss.WIDTH === 0) { x = 0; y++; }`). And in reply to *Another difference ...*: Yes, a 3D array is indeed faster because it has to iterate less. But I cannot make a 3D implementation much faster, but I may be able to improve by making a 2D array very fast (using a typed array).
Comment: A nested loop is faster than doing `%`, `Math.floor` and `/`, you can still use a nested loop with your 2D structure
Comment: @Pudge601 Thanks for your demo code. It's still slow unfortunately. I think the only way to make it faster is by making it iterate less, which can only be done by *not* allocating the theoretical maximum size.
Comment: @PaulS: Could you show me pseudo/demo code?
Comment: @Pudge601: We can do even better than that. There's no reason at all for multiplication or division for this nested loop. Just increment `i`, `x`, and `y` where appropriate, and wrap `x` when `x === WIDTH` (using a comparison, not `%`). (Entirely possible this won't solve the problem, but it eliminates the expensive math.)
Comment: The complexity of the math is not the problem. Even with all math removed (so non-functional), it takes way more time than the 3D version. I would really like advice on a solution that involves a shared buffer.
Comment: @Blaise compare using e.g. `var WIDTH = 255,
    HEIGHT = 160,
    i, j,
    u = new Uint8Array(WIDTH * HEIGHT);
for (i = 0; i < u.length - WIDTH; i += WIDTH)
    for (j = 0; j < WIDTH; ++j)
        u[i + j];`
Answer: By slower I guess you mean running PixelCollection.each? The second example might be slower if there aren't that many points that are set to 1, as it still checks all possible locations whilst the first only runs through added points. If you really want every possible nanosecond at any cost (in this case memory), then you can pre-allocate the maximum size in two Uint8Arrays and separately keep track of the size.
var WIDTH = 255;
var HEIGHT = 160;

var PixelCollection = function() {
    this.pixels.length = 0;
    this.pixels.x = new Uint8Array(WIDTH * HEIGHT);
    this.pixels.y = new Uint8Array(WIDTH * HEIGHT);

};

PixelCollection.prototype = {
    add: function(x, y) {
        this.pixels.x[this.pixels.length] = x;
        this.pixels.y[this.pixels.length] = y;
        this.pixels.length++;
    },
    each: function(callback) {
        var pixels = this.pixels;
        for (var i = 0; i < this.pixels.length; i++) {
            callback(this.pixels.x[i], this.pixels.y[i]);

        }
    }
};

If you know a limit to the number of additions the PixelCollection will have then you can reduce the memory usage. You could even combine the two arrays into one double length alternating x and y values.
However, if you want to be able to remove individual points this method gets tricky, also it's unlikely to be much faster than your first method with @Pudge601's loop change.
Comment: Thank you for your answer. This makes `each` a lot faster, but now I have other issues: [PixelCollection also has other public methods like `has` and `remove`](https://github.com/blaise-io/xssnake/blob/master/shared/pixel_collection.js) which now require iterating = expensive, and preferably I need to be able to sort as well so I can [optimize painting](https://github.com/blaise-io/xssnake/blob/master/client/js/shape_cache.js#L54), and I don't see how that can done cheaply without copying `.pixels`. — I will prepare a jsperf this weekend so I can share benchmarks and insights.
Comment: @Blaise don't use things like your `each` in tight spots like... ever. It's very slow compared to simply iterating it with a for loop from the outside, which might be uglier but performs a lot better.
Comment: @Blaise also remember that the most important thing in the world right now is __ram line caching__. You __must__ iterate it the same way it's stored in memory, so that the CPU cache can fetch close by numbers in chunks rather than not. See http://jsperf.com/ram-line-caching
Comment: @BenjaminGruenbaum: Thanks for your comments. I'm aware of `each` being slower than necessary due to the overhead of a closure / callback fn. However, I don't want to remove it right now because I would access the internal workings of PixelCollection, which hasn't completely settled yet. I haven't heard of ram line caching, but I think my 3D array is doing exactly that. Can you confirm?


Conditional probability of min and max of two dice

Question: Consider the following problem, from Tijms's Understanding Probability:

Two dice are rolled. Let the random variable $X$ be the smallest of the two outcomes and let $Y$ be the largest of the two outcomes. What are the conditional mass functions $P (X = x | Y = y)$ and $P (Y = y | X = x)$?

My attempt:
$$
P(X=x, Y=y) = \begin{cases}
  \frac{1}{36} & \text{if }x=y \\
  0            & \text{if }x>y \\
  \frac{2}{36} & \text{if }x<y \\
\end{cases}.
$$
For the individual probabilities, we have that one of the two outcomes is fixed and has to be equal to the minimum/maximum, the other dice can roll any number between the minimum and 6, or between 1 and the maximum. The order does not count, so I multiply by 2:
$$
P(X=x) = \frac16 \frac{6-x+1}{6}\cdot 2,
$$
and
$$
P(Y=y) = \frac16 \frac{y}{6}\cdot 2.
$$
Putting everything together, we have:
$$
P(X=x|Y=y) = \frac{P(X=x,Y=y)}{P(Y=y)} = \begin{cases}
  \frac{1}{2y} & \text{if }x=y \\
  0           & \text{if }x > y \\
  \frac{1}{y} & \text{if }x < y \\
\end{cases}.
$$
and
$$
P(Y=y|X=x) = \frac{P(X=x,Y=y)}{P(X=x)} = \begin{cases}
  \frac{1}{2(6-x+1)} & \text{if }x=y \\
  0           & \text{if }x > y \\
  \frac{1}{6-x+1} & \text{if }x<y
\end{cases}.
$$
Does it sound right?
Answer: Partial answer due lack of time
For $P(Y=y)$ I have something slightly different. I´ve worked with the table below:
$P(Y=y|X=x)$
$$ \begin{array}[ht]{|p{2cm}|||p{0.5cm}|p{0.5cm}|p{0.5cm}|p{0.5cm}|p{0.5cm}|p{0.5cm}|p{0.5cm}|p{0.5cm}|p{0.5cm}|}  \hline \text{ X/Y }  & 1 &2 &3 &4 &5 &6  \\ \hline \hline \hline 1 &\frac{1}{36} &\frac{2}{36} &\frac{2}{36}& \frac{2}{36}& \frac{2}{36}& \frac{2}{36}\\  \hline  2& &\frac{1}{36} &\frac{2}{36} &\frac{2}{36} &\frac{2}{36} &\frac{2}{36} \\ \hline 3& & &\frac{1}{36} &\frac{2}{36} &\frac{2}{36} &\frac{2}{36}\\ \hline 4 & &  & &\frac{1}{36} &\frac{2}{36} &\frac{2}{36} \\ \hline  5 & & & & &\frac{1}{36} &\frac{2}{36} \\ \hline  6& & & & & &\frac{1}{36}  \\ \hline \end{array}$$
Now we can sum up the cells in column $y$ to obtain $P(Y=y)=\frac{2\cdot y-1}{36}$.
We can check if this is plausible by calculating the sum ( sanity check).
$\sum\limits_{y=1}^6 P(Y=y)=\sum\limits_{y=1}^6\frac{2\cdot y-1}{36}=\frac1{36}\cdot \left(  2\cdot \sum\limits_{y=1}^6  y-\sum\limits_{y=1}^61 \right)=\frac1{36}\cdot \left(  2\cdot \frac{6\cdot 7}{2}-6 \right)=1$
This is the result we have expected.
Comment: I get something a little different, for example for the first row of the table:
$$
P(X=1) = 1 - \left(\frac56\right)^2 = \frac{11}{36}
$$
and
$$
P(X=1, Y=y) = \begin{cases}
\frac{1}{36} & \text{if }y=1 \\
\frac{2}{36} & \text{if }y>1
\end{cases},
$$
so that:
$$
P(Y=y|X=1) = \begin{cases}
\frac{1}{11} & \text{if }y=1 \\
\frac{2}{11} & \text{if }y > 1
\end{cases}.
$$
Comment: @J.D. This is the same what I have. For instance, $P(Y=2|X=1)=\frac{\frac{2}{36}}{\frac{11}{36}}=\frac{2}{11}$. This is the second cell of the first row divided by the sum of the first row.
Comment: @J.D. If there is no question left than mark the answer as accepted. Thanks
Comment: I'll try to solve this again soon, so as to give a full solution to the problem, then I'll accept it. Thanks for your help.
Comment: @J.D. If you want I can give you some hints how you can obtain the table.


Como estabelecer uma comunicação, em um mesmo arquivo, entre múltiplas tags PHP

Question: Boa noite.
A questão é a seguinte, estou fazendo um programa de conta bancária, em que primeiro, em um arquivo.html, eu recupero alguns dados via formulário, e os envio para um outro arquivoX.php. Neste mesmo, além de recuperar os dados digitados pelo usuário, eu criei um objeto "conta1", cuja classe está definida em um outro arquivoY.php.
O que fiz agora foi fechar a tag php do arquivoX, criar um formulário para depósito ou saque de valores, e abrir uma nova tag para que nesta eu recupere estes dados, e realize as operações de get e set com o objeto. O problema é que nesta nova tag o objeto "conta1" não é reconhecido, e então gostaria de saber como faço para resolver isso.
<?php

        $tipo_conta = isset($_GET["tipo_conta"]) ? $_GET["tipo_conta"]: null;
        $cpf_cliente = isset($_GET["cpf_cliente"]) ? $_GET["cpf_cliente"]: null;
        $nome_cliente = isset($_GET["nome_cliente"]) ? $_GET["nome_cliente"]: null;

        require_once 'Conta_bancaria.php';
        if($tipo_conta != null && $cpf_cliente != null && $nome_cliente != null){
            $conta1 = new Conta_bancaria($tipo_conta, $cpf_cliente, $nome_cliente, "não definida", null, true);
        }
        print_r($conta1);
        $conta1->setNum_conta("450-12");
        echo "
 O número da conta foi definido e é {$conta1->getNum_conta()}.
";
        if($tipo_conta == "CC" || $tipo_conta == "cc"){
            $conta1->setSaldo(100);
        }
        else if($tipoconta == "CP" || $tipoconta == "cp"){
            $conta1->setSaldo(150);
        }
        echo "
 Por ser um conta do tipo {$tipo_conta} o saldo inicial padrão é de {$conta1->getSaldo()}.
";
        echo "
 Senhor(a) {$conta1->getDono()}, veja abaixo os dados atualizados de sua conta bancária:
";
        print_r($conta1);

    ?>

 Depósito ou saque

        <form method = "get" action = "?">
            Se for depositar, informe o valor a ser depositado: <input type = "number" name = "deposito" />

            Se for sacar, informe o valor a ser sacado: <input type = "number" name = "saque" />

            <input id = "botao_enviar" type = "submit" value = "Enviar"/>
        </form>

    <?php /* AQUI FAREI OPERAÇÕES DE MUDANÇA DOS DADOS DO SALDO COM OS VALORES DE DEPOSITO OU SAQUE */
        $deposito = isset($_GET["deposito"]) ? $_GET["deposito"]: null;
        $saque = isset($_GET["saque"]) ? $_GET["saque"]: null;
        require_once 'Conta_bancaria.php';

        if($saque == null && $deposito == null){
            echo "
 Nenhum valor foi digitado
";
            exit();
        }
        else if($saque != null && $deposito != null){
            echo "
 ERRO! Não é possível depositar e sacar simultâneamente
";
            exit();
        }
        else if($deposito != null && $saque == null){
            /* depositar*/
        }
        else if($deposito == null && $saque != null){
            /*sacar*/
        }
     ?>

Comment: Pensei agora na possibilidade de passar o objeto da primeira tag como "parâmetro referência" para um método do arquivo da classe, e recuperar um "clone" do objeto chamando a mesma função na outra tag. Seria possível?
Answer: Olá...
Se você quiser manter o objeto '$conta1' entre as requisições, terá que salvá-lo em algum lugar, possivelmente nesse caso, o ideal é o superglobal $_SESSION.
Faça o seguinte:
    // no começo do script
    session_start(); //para iniciar a sessão

    //antes de criar um objeto, veja se ele já existe. Se não existir, crie-o
    require_once 'Conta_bancaria.php';
    if(isset($_SESSION['conta']){
        $conta1 = $_SESSION['conta'];
    } else {
        if($tipo_conta != null && $cpf_cliente != null && $nome_cliente != null){
            $conta1 = new Conta_bancaria($tipo_conta, $cpf_cliente, $nome_cliente, "não definida", null, true);
            $_SESSION['conta'] = $conta1;
        }
    }

Comment: Estou aprendendo PHP, acabei querendo dar uns passos a mais durante um vídeo de getter setter e constructor, trazendo a inserção de dados por HTML.
Mas essa solução que tu me deu acho que entendi, na sessão em que farei os getter e setters para depósito e saque, que serão chamadas para modificação do método saldo, eu defini que esta mesma sessão será igual a sessão anterior que foi igualada ao objeto '$conta1'.
Comment: Na primeira tag PHP, basicamente criei o objeto, no bloco de código do else do if, e fiz isto: $_SESSION['conta'] = $conta1;
Foi o que eu entendi do que dissestes.
Já na segunda tag PHP, onde irei receber os dados de depósito ou saque, fiz o seguinte:
session_start();
$_SESSION['dep_saq'] = $_SESSION['conta'];
Isto é, esta nova sessão será igual a sessão anterior. É isso?
Comment: Mais ou menos isso. A sessão é um objeto que persiste no servidor enquanto o usuário está conectado. Caso não hajam requisições por um período especificado, ela expira, do contrário, cada vez que ela é acessada, esse período é renovado. Com o uso dela, você pode 'transferir' ou 'enviar/receber' dados entre páginas/requisições.


Estimate MLE of discrete distribution with two parameters in R

Question: I want to estimate the MLE of a discrete distribution in R using a numeric method.
My data looks like this:
data1<-c(5,2,2,3,0,2,1 2,4,4,1)
If we assume it follows a negative binomial distribution, how do we do it in R? There are a lot of tutorials about estimating mle for one parameter but in this case, there are two parameters ( in a negative binomial distribution)
And it involves a gamma function, which makes it more complicated.
Any ideas?
Edit: I wish to use optim in R or other methods.
log-likelihood:

I'm having trouble with constructing it in R.
Comment: You'll need to write down the negative log likelihood. What have you tried? Where are you stuck?
Comment: What part of constructing it in R is giving you trouble?
Comment: Did you want to code something to estimate the MLE yourself, or are you looking for libraries to do so
Comment: Have you tried using the `lgamma` function?
Comment: $\Gamma(x+r)$ is the ordinary gamma function, so `gamma(x+r)`. If you want $\log(\Gamma(x+r))$, you'd have to use `lgamma(x+r)`.
Comment: As a first attempt I'd probably load the MASS library (which comes with R) and fit a negative binomial GLM with a constant model (`y~1`), then use the additional functions that MASS supplies to estimate the other parameter.
Comment: I want to use optim in R but I'm not sure how to do it
Comment: I added it in the question!
Comment: [https://www.ime.unicamp.br/~cnaber/optim_1.pdf ] I try to follow this instruction to do it but I don't know how to construct the log likelihood code because there are two parameters and a gamma function
Comment: how would you do $\Gamma(x+r)$ with `lgamma`?
Comment: ok! thank a lot. I will try
Answer: Firstly, your equation for the log-likelihood function for the negative binomial distribution looks wrong to me, and it's not clear how your $\beta$ enters into the parameterisation of the distribution.  In any case, I will show you how to do this kind of problem using the standard parameterisation of the negative binomial distribution.  If $X_1,...,X_n \sim \text{IID NegBin}(r, \theta)$ then you should have:
$$\begin{align}
\ell_\mathbf{x} (r, \theta)
&= \sum_{i=1}^n \log \text{NegBin}(x_i |r, \theta) \\[6pt]
&= \sum_{i=1}^n \log \Bigg( \frac{\Gamma(x_i+r)}{x_i! \Gamma(r)} (1-\theta)^r \theta^{x_i}  \Bigg) \\[6pt]
&= \sum_{i=1}^n \log \Gamma(x_i+r) - \sum_{i=1}^n \log (x_i!) - n \log \Gamma(r) + nr \log (1-\theta)  + \log (\theta) \sum_{i=1}^n x_i \\[6pt]
&= \sum_{i=1}^n \log \Gamma(x_i+r) - n \tilde{x}_n - n \log \Gamma(r) + nr \log (1-\theta)  + n \bar{x}_n \log (\theta), \\[16pt]
\end{align}$$
where $\bar{x}_n \equiv \sum_{i=1}^n x_i / n$ and $\tilde{x}_n \equiv \sum_{i=1}^n \log (x_i!) / n$.  The first-order partial derivates of this function are:
$$\begin{align}
\frac{\partial \ell_\mathbf{x}}{\partial r} (r, \theta)
&= \sum_{i=1}^n \psi(x_i+r) - n \psi(r) + n \log (1-\theta), \\[12pt]
\frac{\partial \ell_\mathbf{x}}{\partial \theta} (r, \theta)
&= - \frac{nr}{1-\theta} + \frac{n \bar{x}_n}{\theta}. \\[6pt]
\end{align}$$
The second partial derivatives show that the log-likelihood is concave, so the MLE occurs at the critical points of the function.  The MLE for the probability parameter is $\hat{\theta}(r) = \bar{x}_n/(r + \bar{x}_n)$, and you can use this explicit form to write the profile log-likelihood:
$$\begin{align}
\hat{\ell}_\mathbf{x} (r)
&\equiv \ell_\mathbf{x} (r, \hat{\theta}(r)) \\[12pt]
&= \sum_{i=1}^n \log \Gamma(x_i+r) - n \tilde{x}_n - n \log \Gamma(r) + nr \log \bigg( \frac{r}{r+\bar{x}_n} \bigg) + n \bar{x}_n \log \bigg( \frac{\bar{x}_n}{r+\bar{x}_n} \bigg) \\[16pt]
&= \sum_{i=1}^n \log \Gamma(x_i+r) - n \tilde{x}_n - n \log \Gamma(r) + nr \log (r) + n \bar{x}_n \log (\bar{x}_n) - n(r+\bar{x}_n) \log (r+\bar{x}_n), \\[16pt]
\end{align}$$
and its derivative:
$$\begin{align}
\frac{d \hat{\ell}_\mathbf{x}}{dr} (r)
&= \sum_{i=1}^n \psi(x_i+r) - n \psi(r) + n \log (r) - n \log (r+\bar{x}_n). \\[16pt]
\end{align}$$
(This derivative matches the initial partial derivative with the substituted MLE for the probability parameter.)  In order to compute the MLE we need to maximise the profile log-likelihood function, which is equivalent to finding the solution to its critical point equation.  We first find the MLE for $r$ and then use the this to get the MLE for $\theta$ from its explicit form.  This can be done using standard optimisation or root-finding functions.

Objective function: For this kind of constrained optimisation problem it is best to first convert to unconstrained optimisation, so we will optimise the transformed parameter $\phi \equiv \log r$, which has the (minimising) objective function:
$$\begin{align}
F_\mathbf{x}(\phi)
\equiv - \hat{\ell}_\mathbf{x} (e^\phi)
&= - \sum_{i=1}^n \log \Gamma(x_i+e^\phi) + n \tilde{x}_n + n \log \Gamma(e^\phi) - n \phi e^\phi \\[6pt]
&\quad - n \bar{x}_n \log (\bar{x}_n) + n(e^\phi+\bar{x}_n) \log (e^\phi+\bar{x}_n), \\[16pt]
\frac{d F_\mathbf{x}}{d\phi}(\phi)
&= - e^\phi \sum_{i=1}^n \psi(x_i+e^\phi) + n e^\phi \psi(e^\phi)
- n (\phi+1) e^\phi \\[6pt]
&\quad + n e^\phi (1+\log (e^\phi+\bar{x}_n)). \\[16pt]
\end{align}$$
Minimising this objective function will give you the MLE $\hat{\phi}$ from which you can then compute $\hat{r}$ and $\hat{\theta}$.  We implement this below and give an example.  (You should also note that there are certain pathological cases in this estimation problem.  The negative binomial distribution has a variance that is never smaller than its mean, so it has difficulties with any dataset with a sample variance smaller than its mean.  In some cases (which occur with non-zero probability even under the model) the inferential problem will lead to the estimate $\hat{\phi} = \hat{r} = \infty$ and $\hat{\theta} = 0$ (see e.g., here).  In this case your numerical search for the MLE will technically "fail" but it will stop after giving you a "large" value for $\hat{\phi}$ and a "small" value for $\hat{\theta}$

Implementation in R: We can implement the computation of the MLE in R by using the nlm function for nonlinear minimisation.  For this iterative optimisation we will use the method-of-moments estimator as the starting value (see this related question for the MOM estimators).  Here is a function that computes the MLE of the parameters of the negative binomial for any valid input for the observed data vector x.
MLE.nbinom <- function(x) {

  #Check input
  if (!is.numeric(x))           stop('Error: Data x should be non-negative integers')
  if (any(x != as.integer(x)))  stop('Error: Data x should be non-negative integers')
  if (min(x) < 0)               stop('Error: Data x should be non-negative integers')

  #Compute sample quantities
  n       <- length(x)
  bar.x   <- mean(x)
  tilde.x <- sum(lfactorial(x))/n

  #Set objective function
  NEGLOGLIKE <- function(phi) {
    r     <- exp(phi)
    OUT   <- - sum(lgamma(x+r)) + n*tilde.x + n*lgamma(r) -
               n*r*phi - n*bar.x*log(bar.x) + n*(r+bar.x)*log(r+bar.x)
    D1    <- - r*sum(digamma(x+r)) + n*r*digamma(r) - n*r*(phi+1) +
               n*r*(1+log(r+bar.x))
    attr(OUT, 'gradient') <- D1
    OUT }

  #Compute MLE
  START.r <- max(bar.x^2/(var(x) - bar.x), 1e-4)
  NLM     <- nlm(f = NEGLOGLIKE, p = log(START.r))
  MLE.r   <- exp(NLM$estimate)
  MLE.t   <- bar.x/(MLE.r + bar.x)
  MAX.LL  <- -NLM$minimum

  #Give output
  list(MLE.r = MLE.r, MLE.theta = MLE.t, loglike.max = MAX.LL) }

Now let's try this function on some simulated data from the negative binomial distribution.  (Noting that the base function rnbinom uses a slightly different parameterisation from our density above.)
#Generate data from negative binomial distribution
set.seed(1)
r     <- 3
theta <- 0.8
x     <- rnbinom(n = 10^6, size = r, prob = 1-theta )

#Compute the MLE
MLE.nbinom(x)

$MLE.r
[1] 2.998328

$MLE.theta
[1] 0.8001082

$loglike.max
[1] -3341525

As you can see, our MLE function comes reasonably close to recovering the true parameters used to generate the data.  (You should note that the MLEs are biased but consistent estimators in this case.)  With a bit more work you could compute the relevant second-order partial derivatives and use these to compute the standard error matrix for the estimator.  I will leave this as an exercise for the reader.
Comment: Thanks a lot! Your answer is perfect.
Comment: However, I don't quite understand $\hat{\theta}(r)$. Did you just claim it?
Comment: It comes from solving the critical point equation for $\theta$.  (Give it a go.)


equivalent? algebraic definition of a partial isometry in a C*-algebra

Question: An element $a\in\mathfrak{A}$ (unital C*-algebra) is a partial isometry if $a^*\cdot a $ is projection.
Can one recover the equivalent caracterizations of a partial isometry in $\mathcal{B}(\mathcal{H})$ but for an abstract C*-algebra? namely:
$a\ \text{partial isometry} \Leftrightarrow a^*\ \text{p. iso} \Leftrightarrow a^*a\ \text{projection} \Leftrightarrow aa^*\ \text{projection}\Leftrightarrow aa^*a=a \Leftrightarrow a^*aa^*=a^*$
The only thing I can see is that the last two ones (are of course equivalent and) imply the others
Comment: Just embed $\mathfrak{A}$ into some $\mathcal{B}(\mathcal{H})$
Comment: I guess one can proove it by saying that it holds in a faithful representation, but...
Answer: Yes, this can be done without making the $C^*$-algebra concrete in $B(H)$. All we need is that $z=0$ iff $z^*z=0$, which follows from the $C^*$-identity $\|z^*z\|=\|z\|^2$.
Lemma Let $a\in A$. The following assertions are equivalent.
1 - $p=a^*a$ is idempotent, i.e. $p^2=p$.
2 - $aa^*a=a$
3 - $a^*aa^*=a^*$
4 - $q=aa^*$ is idempotent.
Proof
$1\Rightarrow 2:$ Here is the main trick. Set $z:=aa^*a-a$. Note that $z^*z=p^3-p^2-p^2+p=0$, whence $z=0$.
$2\Rightarrow 3:$ Take the adjoint.
$3\Rightarrow 4:$ Left-multiply $3$ by $a$.
$4\Rightarrow 1:$ Applying $1\Rightarrow 2$ to the element $a^*$ instead of $a$, we get $a^*aa^*=a^*$. Right-multiplication by $a$ yields $1$. $\Box$
By definition, an element $a$ is a partial isometry in an abstract $C^*$-algebra if $a^*a$ is a projection. Of course, the latter is always self-adjoint. So $a$ is a partial isometry iff $a^*a$ is idempotent. It follows in particular that $a$ is a partial isometry iff $a^*$ is a partial isometry.
Remark Two projections $p,q$ as above are called Murray-von Neumann equivalent. The lemma above helps prove that the latter is an equivalence relation (namely transitivity, which is the slightly tricky part).


How are contextual arguments specified explicitly in the URL?

Question: The examples in contextual arguments simply call for specifying them with slashes without specifying the name of the filter, but if you wish to apply the second or third filter in the contextual link, what syntax should be used?
eg if there are contextual filters, on field_1, field_2 and field_3 and you want to ignore field_1 and field_2 in the URL, how do you write the URL for field_3 only?
Even if you want to apply only the first filter, but specify it explicitly in the URL, what is the syntax for it?
PS. When contextual fields for different fields are applied are they combined with OR or AND? are they
Answer: Contextual filters always use AND operator between them. Unless you use a special module to change it Views Contextual Filters OR.
But there are conditions under which a Contextual filter will show all the results as if it hasn't been applied. This means that it could be seen as if the OR operator is applied.
Contextual filters have two major options in their configuration:
`When the filter value is NOT available`

and
`When the filter value IS available or a default is provided`

Under the former options there is always the Exceptions setting, where the default value is all (you can change it if you think it would be better for UX).
But this means that you can use that expression in the URL as a way to temporarily cancel that Contextual filter, so you can test the others if you have more than one.
field_1_value/all/all
or in your case to ignore the first and the second one:
all/all/field_3_value
To apply the first one only you can use:
field_1_value/all/all
but you could also use
field_1_value
if you have configured the last two Filters to use
Display all results for the specified field or
Provide default value.
There is also the setting Action to take if filter value does not validate under Specify validation criteria where you can choose the option Display all results for the specified field. So you can also use this in combination with other settings, if it makes sense in your specific case.
Setting up a Contextual filter isn't a trivial thing, there are different "paths" that can come out out of a single filter, and you'll get a different set of results.


Try Catch - URL link not exist

Question: I need to read some Data from URLs - but depending on the string (ICAO) - the URL does not sometimes exist (it is not valid). In this case - I should get "N/A" - but that does not work... only when all three URLs are readable - it is working.
        [Invoke]
    public List<Category> getWeather(string ICAO)
    {
        try
        {
            List<Category> lstcat = new List<Category>();
            Category cat = new Category();
            string fileString;
            bool isexists = FtpDirectoryExists("ftp://tgftp.nws.noaa.gov/data/observations/metar/stations/" + ICAO);
            if (isexists == true)
            {
                WebClient request = new WebClient();
                string url = "http://weather.noaa.gov/pub/data/observations/metar/stations/" + ICAO;
                byte[] newFileData = request.DownloadData(url);
                fileString = System.Text.Encoding.UTF8.GetString(newFileData);
                cat.Cat = "METAR";
                lstcat.Add(cat);
                cat = new Category();
                cat.Cat = fileString;
                lstcat.Add(cat);
                url = "http://weather.noaa.gov/pub/data/forecasts/shorttaf/stations/" + ICAO;
                newFileData = request.DownloadData(url);

                fileString = System.Text.Encoding.UTF8.GetString(newFileData);
                cat = new Category();
                cat.Cat = "Short TAF";
                lstcat.Add(cat);
                cat = new Category();
                cat.Cat = fileString;
                lstcat.Add(cat);

                url = "http://weather.noaa.gov/pub/data/forecasts/taf/stations/" + ICAO;
                newFileData = request.DownloadData(url);

                fileString = System.Text.Encoding.UTF8.GetString(newFileData);
                cat = new Category();
                cat.Cat = "Long TAF";
                lstcat.Add(cat);
                cat = new Category();
                cat.Cat = fileString;
                lstcat.Add(cat);

            }
            else
            {
                fileString = "N/A;N/A";
            }
            return null;
        }
        catch (Exception)
        {

            throw;
        }
    }

Comment: If that FTP URL is valid, you're not going to reach the `"N/A;N/A"` string. Also, you're going through all the trouble of adding items to `List lstcat`, but then you're always returning `null`- is this really the behavior you want?
Comment: Nope. I want that for each URL - which does not response - to get a "N/A".
Like
METAR
N/A
But it still shows the other URL content items.
Comment: Hey Bjoern- did either answer work for you? If so, please click the checkmark for one of them to mark it as accepted.
Answer: Create a method to check the remote file exists or not.
   make a Heder request to the URl, if the sattus code is 200 or 302 then return true
    otherwise false;
HttpWebResponse response = null;
var request = (HttpWebRequest)WebRequest.Create(/* url */);
request.Method = "HEAD";

try
{
    response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
    /* A WebException will be thrown if the status of the response is not `200 OK` */
}
finally
{
    // Don't forget to close your response.
    if (response != null)
    {
        response.Close()
    }
}

Answer: Okay, I think I see what you want to do. I re-worked your code so that it fits what's actually needed.
Right now, it seems like the first Category in lstcat has the description (such as "METAR") of the first URL, the second Category in lstcat has the fileString that matches it, and so on. This is very vague and cumbersome. Instead, make it so that one Category object contains everything you need to know about a URL:
public class Category
{
    public string description;
    public string fileString;
    //Other fields you might use somewhere else...

    public Category(string description, string fileString /*, other fields, if any...*/)
    {
        this.description = description;
        this.fileString = fileString;
        //Initialize others...
    }
}

I then eliminated all the duplication in the original code, by putting all the URL download code into a separate function.
[Invoke]
public List<Category> getWeather(string ICAO)
{
    bool isexists = FtpDirectoryExists("ftp://tgftp.nws.noaa.gov/data/observations/metar/stations/" + ICAO);
    if (isexists)
    {
        List<Category> lstcat = new List<Category>();

        addCategoriesToList(
            lstcat,
            "http://weather.noaa.gov/pub/data/observations/metar/stations/" + ICAO,
            "METAR"
        );
        addCategoriesToList(
            lstcat,
            "http://weather.noaa.gov/pub/data/forecasts/shorttaf/stations/" + ICAO,
            "Short TAF"
        );
        addCategoriesToList(
            lstcat,
            "http://weather.noaa.gov/pub/data/forecasts/taf/stations/" + ICAO,
            "Long TAF"
        );

        return lstcat;
    }
    else
    {
        return null;
    }
}

private static void addCategoriesToList(List<Category> lstcat, string url, string description)
{
    string fileString;
    //Use "using" so that `request` always gets cleaned-up:
    using (WebClient request = new WebClient())
    {
        try
        {
            byte[] newFileData = request.DownloadData(url);
            fileString = System.Text.Encoding.UTF8.GetString(newFileData);
        }
        catch
        {
            fileString = "N/A";
        }
    }

    lstcat.Add(new Category(description, fileString));
}

I think this accomplishes what you want, in a much cleaner and straightforward way. Please let me know if that is indeed the case!

Try Catch - URL link not exist


MigraDoc PDFSharp Table overflow text

Question: I am creating a big table with MigraDoc.
I have two issues I don't know how to solve exactly:

If the content (Paragraph) of a cell is too long it breaks and I got 2 lines in my cell. I don't want this behavior. I want that the text which does not fit in the first line of the cell is hidden.
If a word is too long I want also that the characters which are outside of the cell are hidden. Now they are displayed in the next cell :/ and are overlapping with the content of the next cell...

Do you know how to fix this issues?
Answer: This behavior is by design.
Use MeasureString to measure your text before you add it and truncate at the correct place (maybe adding "..." if you want).
See also:
http://forum.pdfsharp.net/viewtopic.php?p=6158#p6158
Comment: thx - the method in your postet link is a nice snippet. Only had to change a few things.

MigraDoc PDFSharp Table overflow text


iOS 8 Unique Identifier (Serial Number preferred)

Question: I am working on an enterprise app and need access to programmatically retrieve the device's serial number. Is there an API or any documentation on how to retrieve this in iOS 8? From what I can tell, this functionality has been removed in iOS 8.
Is there a suitable replacement identifier for the serial? I need something that is reliable and will never change even if the device is reset.
It will be for enterprise usage so App Store approval is not a concern.
Comment: Looking at [this answer](http://stackoverflow.com/a/15224410/860000), there was a way to get the serial number in iOS7 and earlier but it is no longer available in iOS8.  Your best bet is probably to store a UUID in the keychain you can track across apps and reinstalls but not resets.
Comment: What specifically are you trying to accomplish by knowing the serial number of the device?
Comment: The purpose of the app is for tracking repairs performed to iPads and for inventory purposes. I need to have a way of keeping the history of an iPad permanently tied to that iPad. It's crucial that the identifier doesn't change because the company I work for erases all of the iPads on an annual basis.
Comment: Added an extra edit that may help.
Answer: You're up a creek here. The two "tracking" features are Advertising Identifier and Identifier for Vendor. The former can be reset within the Settings app quite easily while the latter will reset once the user uninstalls all apps with the root bundle identifier associated with the app suite. Both also change with a device reset of course.
If you're deploying the app with an MDM solution you will have access to that device's UDID as it still flows forward to MDM servers, you just can't access it programmatically in your code. The complete deprecation of UDID, serial number and MAC address (even with private APIs) stomped all over some custom utilities I wrote within our Enterprise to try and accomplish something similar to what you're looking to do. If you find somethingthats consistent I'd love to see the follow-up!
EDIT:
I had an epiphany while circling back to this situation again. If you are in fact using AirWatch (I can't speak to Mobile Iron, etc) you can setup the console to send a keychain value to each device at the time of app install. From there the app will be able to consume the value AirWatch sends down. The same goes for any attribute that AirWatch harvests for the device (serial, UDID, MAC, etc). While this workaround comes with a big caveat (using AirWatch for deployment) it will work. Since Apple neutered all Serial Number work arounds win iOS8 this is the most viable option I have found.
Comment: Dan, I was coming back to this issue again after having the same MDM idea. I was hoping to avoid needing to tap into the MDM's data due to not having full access to write scripts. I came up with an alternative workaround that's admittedly a bit bizarre. Apple's GSX service (for self-servicing accounts) has an API for retrieving diagnostic information. I can request that the user manually input the serial number, then upload it into GSX diagnostics. I load the diagnostic page in the background and if it comes back without error, I know the serial is valid and can save in keychain.
Comment: That very well may work. Given the scope of my environment (user base and user technology level) I'm forced to remove human error as much as possible. Great potential workaround, though.


"Error: cannot set property appendChild() of null

Question: No meu código eu fiz uma função para criar um botão e logo após o usuário clicar nele o botão e o outro conteúdo alterado são apagados.
Eu consegui chegar nesse ponto, porém botão fica no final do body. Para resolver isso precisei usar a função elementoPai.appendChild(node);, o que seria o seguinte resultado no meu código:
var pai = document.getElementById("form1");

var b1fechar = document.createElement("BUTTON");

b1fechar.setAttribute("id", "b1fechar");

b1fechar = document.getElementById("b1fechar");

pai.appendChild(b1fechar);

Esse seria a parte interessante do código.
Javascript inteiro aqui embaixo (arquivo .js):
var pai = document.getElementById("form1");

//Funções básicas de texto para output visual no site
function GetMoveInfo()
{
    var ictext = document.getElementById("ictext").innerHTML = iceBeam.info;
    var b1fechar = document.createElement("BUTTON");
    b1fechar.setAttribute("id", "b1fechar");
    b1fechar.addEventListener("click", closeIcebeam, true);
    b1fechar.innerHTML = "Fechar";
    pai.appendChild(b1fechar);
    //document.createTextNode(""); para criar texto para outras ocasiões.

};

Tudo funciona até a linha 8.
HTML do site:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Em construção</title>

<form id="form1">
<input type="radio" id="icebeam" name="mov" value="icebeam">
  Icebeam

  <button type="button" onclick="GetMoveInfo()" id="showicebeam">+Informações</button>

  <input type="radio" id="flamethrower" name="mov" value="flamethrower">
  Flamethrower

</form>

Comment: `b1fechar = document.getElementById("b1fechar");` pq atribuiu um valor a um elemento que já tinha valor, e ainda nem foi adicionado ao DOM? isso vai resultar null, o `getElementById` vai ler documentos que fazem parte do DOM, e o seu ainda não foi inserido nesse exemplo. Fora isso, na function `GetMoveInfo()`, onde foi definida a variável "pai"? Aproveite e remove a tag `java`, pq esse código nada tem de java, use `javascript`
Comment: Aceito sugestões para melhoria do código também, obg.
Comment: @RicardoPontual não tem a tag java... Tem apenas a tag javascript. Vou rever esse erro que você comentou, obg.
Answer: Perdão, porém a sua pergunta ficou bem confusa, e só analisando o código não ficou claro qual era sua intenção. Não leve a mal, provavelmente você está começando, tente usar nomes de variáveis e funções mais claros e comentar o código explicando o que cada bloco faz.
Eu fiz uma versão do seu código reformulada, o resultado é o que imaginei que fosse sua intenção, espero ter ajudado e que você aprenda muito ainda nesse mundo da programação.
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Em construção</title>

<form>

        First Option
        <input type="radio" id="icebeam" value="firstoption">
        <button type="button" id="more" class="more-1" onclick="showContent(this)">More</button>

        First Option
        <input type="radio" id="icebeam" value="firstoption">
        <button type="button" id="more" class="more-2" onclick="showContent(this)">More</button>

</form>

Esse código vai verificar a classe CSS do botão para saber qual conteúdo exibir dentro da classe Pai.
Comment: Olá, já ia fazer uma semana e ninguém respondia, imaginei que havia algo errado :/ . Colocando a sua resposta aqui vi que a ideia que eu queria era exatamente isso, eu vou dar uma mexida agora a partir dela. Sim, eu estou começando mesmo, acabei de fazer dois cursos a uma semana atrás. Muito obrigado pela ajuda :)
@LucasBezerra


Row selection combining condition on index and condition on a column in a pandas dataframe

Question: I want to select rows from a dataframe based on values in the index combined with values in a specific column:
df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [0, 20, 30], [40, 20, 30]],
                  index=[4, 5, 6, 7], columns=['A', 'B', 'C'])

    A   B   C
4   0   2   3
5   0   4   1
6   0  20  30
7  40  20  30

With
df.loc[df['A'] == 0, 'C'] = 99

I can select all rows with column A = 0 and replace the value in column C with 99, but how can I select all rows with column A = 0 and the index < 6. In other words, I want to combine selection on the index with selection on the column.
Answer: You can use multiple conditions in your loc statement:
df.loc[(df.index < 6) & (df.A == 0), 'C'] = 99

Comment: @Peruz It is not. The search expressions `(df.index < 6)` and `(df.A == 0)` each independently create boolean series as masks of the data, and the `&` operator combines them.
Comment: Is pandas actually smart so that it first selects  on the index (faster, hash table, etc.) and only afterwards in the selected subset looking for `df.A == 0`?
Answer: The canonical method is to reduce all boolean conditions into a single boolean condition and filter the frame by it.
So for the task at hand, to filter a dataframe by a condition on its index and its columns, write two boolean conditions and reduce into one using & (as suggested by @sacuL).
Some alternative methods:

eval() may be used for a readable condition
df.loc[df.eval('index < 6 and A == 0'), 'C'] = 99

A function may be passed to loc:
df.loc[lambda x: (x.index < 6) & (x['A']==0), 'C'] = 99


Fazendo uma função LINQ que possa ser chamado numa consulta no EF

Question: Tenho a seguinte expressão:
Where(cd => cd.Modal == modal)
    .Select(s => s.Volume)
    .DefaultIfEmpty(0)
    .Sum()

que uso pára fazer um mesmo calculo diversas vezes dentro de algumas querys através do LINQ e tentei criar o seguinte extension method, porém ao executar minha consulta ele dá a seguinte mensagem de erro:

LINQ to Entities does not recognize the method 'system decimal
  CalculateVolume'

Método:
public static decimal CalculateVolume(this IEnumerable<MyEntity> query, Modal modal)
{
    return query.Where(cd => cd.Modal == modal)
              .Select(s => s.Volume)
              .DefaultIfEmpty(0)
              .Sum();
}

Segue um exemplo de como tentei executar o comando:
var modal = 1;
_context.EntityTeste
    .Select(c => new
    {
        Current = c.MyEntity.CalculateVolume(modal)
    })

A entidade MyEntity é uma lista dentro da EntityTeste.
Como posso fazer para que eu consiga transformar esse trecho de código que é repetido diversas vezes numa instrução que o LINQ entenda e execute no banco de dados?
Comment: Acredito que nesses casos a melhor opção é o Dapper.
Comment: @GeorgeWurthmann Como o Dapper poderia ajudar num caso destes?
Comment: @LINQ já tive um problema muito parecido e pra não carregar tudo em memória pra poder chamar o método fizemos uma função no BD e fizemos uma query usando a função usando o Dapper. Mas no meu caso era cálculos com data.
Comment: Mas pra fazer uma uma função no banco e chamar na query não precisaria do Dapper, certo? Dá pra fazer com o EF...
Comment: No EF6 isso é um pouco complicado e nem tudo funciona como deveria funcionar, no EF Core que houve um grande avanço nesse aspecto pode ser feito, o problema que eu não consegui visualizar qual SQL você precisa executar, [poderia editar a sua pergunta e exemplificar melhor](https://pt.stackoverflow.com/posts/386398/edit), está vago um pouco e do jeito que você fez ele não vai entender aquilo como uma expressão `Linq`.
Answer: Não vou afirmar que não seja possível fazer no SQL Server que suporta a criação de função com .NET, mas o processo não é tão trivial, e não estou dizendo que fica bom ou mesmo se dá mesmo. Em outros bancos de dados certamente não dá. Para executar no banco de dados este tem que suportar isto, não tem como um algoritmo escrito em C# magicamente vá para o banco de dados e execute lá.
Qualquer solução que use será executada na memória. Se estiver usando um IQueryable haverá uma conversão do que dá para uma consulta, possivelmente SQL porque deve estar usando um DB assim), que será enviada para o banco de dados e retornará os dados filtrados, mas sem a parte de filtro que ele não sabe como converter, aí os dados que vierem rodarão em memória fazendo o filtro do seu método gerando o resultado final do jeito que deseja.
Também não estou dizendo que não tem como fazer essa query dar o mesmo resultado totalmente em SQL escrevendo o LINQ de outra forma, mas parece que não.
De forma geral qualquer coisa que saia muito do trivial é melhor passar uma query SQL e evitar LINQ.
A questão do não reconhecimento deve ser por algo que não está no código apresentado, pode ser que o método não esteja disponível neste escopo mesmo. Mas não importa porque não fará o que deseja.
Answer: Pesquisei um pouco e achei trechos dizendo que você deve usar List<> em função de trabalhar com objetos iteráveis.
Portanto, tente adicionar o método ToList() antes do .Where:
public static System.Linq.Expressions.Expression<Func<decimal>> CalculateVolume(this IEnumerable<MyEntity> query, Modal modal)
{
    return () => { return query.ToList().Where(cd => cd.Modal == modal).Select(s => s.Volume).DefaultIfEmpty(0).Sum(); };
}

Isso irá carregar a sua tabela na memória, então, tome cuidado com pesquisas grandes.
Além disso, passei seu código para um System.Linq.Expressions.Expression<Func<>> e usei lambda para retornar o seu código.
Pesquisei sobre isso aqui.
Comment: Não quero ter que carregar o objeto em memória para fazer isso, quero fazer isso na query
Comment: Tente então só mudar o tipo de retorno do método.