How to handle click on ScrollView in Fragment?

Question: How to handle click on ScrollView in Fragment?
<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ExampleFragment">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/myScroll">
        </ScrollView>

</FrameLayout>
</code>
And in Fragment I'm trying:
<code>@Override
public void onStart() {
    super.onStart();

    ScrollView refresh = (ScrollView) getActivity().findViewById(R.id.myScroll);
    refresh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast toast = Toast.makeText(getActivity().getApplicationContext(), "TEST", Toast.LENGTH_LONG);
            toast.show();
        }
    });
}
</code>
But after clicking nothing happens.
Any other idea to handle a click on a fragment? This does not have to be a ScrollView. I tried also for FragmentLayout but it returns a lot of bugs.
Comment: did you make debugging? does onclick function run properly? Does the toast show runs properly but does not occur on your screen? Where does the error occurs exactly?
Answer: use this code in onCreateView
<code> ScrollView refresh = (ScrollView) getActivity().findViewById(R.id.myScroll);
refresh.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast toast = Toast.makeText(getActivity().getApplicationContext(), "TEST", Toast.LENGTH_LONG);
        toast.show();
    }
});
</code>
Answer: The reason for the onClickListener of ScrollView being ignored is explained here.
You could add an onTouchListener instead like this.
<code>    refresh.setOnTouchListener(new View.OnTouchListener() {
        /**
         * Called when a touch event is dispatched to a view. This allows listeners to
         * get a chance to respond before the target view.
         *
         * @param v     The view the touch event has been dispatched to.
         * @param event The MotionEvent object containing full information about
         *              the event.
         * @return True if the listener has consumed the event, false otherwise.
         */
        @Override
        public boolean onTouch(View v, MotionEvent event) {
           Toast toast = Toast.makeText(getActivity().getApplicationContext(), "TEST", Toast.LENGTH_LONG);
           toast.show();
           return false;
        }
    });
</code>


Exponential growth of a combinations expression

Question: Assume $K,K\cdot a$ positive integers with $K\cdot a< K$. I have the expression $\binom{K}{K\cdot a}$ and the author says that it grows exponentially with $K$ when $a$ is fixed. Why is that?
Comment: By $Ka$ do you mean the product $K\times a$ or $K_a$, a distinct integer from $K$?
Comment: @Mark Thanks, I have made an edit to clarify that it's actually a product
Comment: Are both $K$ and $Ka$ supposed to be positive?
Comment: @Mark Yes, they are
Comment: what about $a=1$...
Comment: I don't think $a$ has to be an integer (so as an example, $K = 8, a = 2$ might work).
Comment: @Rustyn I guess I'll have to make a lot of edits. Please see above. Let's stick to the case of strict inequality
Comment: @Mark First, I did not say that $a$ has to be an integer, $K\cdot a$ has to  be. Second, in your example you set $a$ as an integer.
Answer: Easiest way to explain this is probably via Stirling's approximation to the factorial.
Stirling's approximation is
$$
n!\sim\sqrt{2\pi n}\left(\frac{n}{e}\right)^n\text{ as }n\to\infty.
$$
Recalling that
$$
\binom{K}{Ka}=\frac{K!}{(Ka)!(K(1-a))!},
$$
this implies
$$
\begin{align*}
\binom{K}{Ka}&\sim\sqrt{\frac{2\pi K}{4\pi^2KaK(1-a)}}\cdot\frac{\left(\frac{K}{e}\right)^K}{\left(\frac{Ka}{e}\right)^{Ka}\left(\frac{K(1-a)}{e}\right)^{K(1-a)}}\\
&=\sqrt{\frac{1}{2\pi Ka(1-a)}}\cdot\left(\frac{1}{a^a(1-a)^{1-a}}\right)^K\\
&=C\cdot\frac{1}{\sqrt{K}}\cdot D^K
\end{align*}
$$
with $C$ and $D$ constants (depending on $a$) defined in the obvious way.
Now, because $Ka<K$, we have $a\in(0,1)$. (We must have $a>0$; $a=0$ does not yield exponential growth here.)  You can verify that this implies $1< D\leq 2$, so that this is an exponentially growing function.
Comment: Thanks, can you give me a hint on the proof of $D\geq2$?
Comment: That's equivalent to showing that $a^a(1-a)^{1-a}\leq\frac{1}{2}$.  To that end: take the logarithm to get $a\ln(a)+(1-a)\ln(1-a)$.  You can find the maximum of this by differentiation; then, you can finish using monotonicity of the exponential.
Comment: Hmm... hold on a sec.  I've made a mistake here.  $a^a(1-a)^{1-a}$ has a MINIMUM of $\frac{1}{2}$.  One sec.
Comment: Alright, fixed.  And you can show it by showing the minimum of $\frac{1}{2}$, as described above, combined with $a^a(1-a)^{1-a}<1$.
Comment: OK, I have made some calculations here. So, for the first part $D\leq2$ we have $\vartheta /\vartheta a(a\mathrm{ln}a+(1-a)\mathrm{ln}(1-a))=0\Rightarrow ln(a/(1-a))=0\Rightarrow a=1/2$ which yields only the maximum of $D$ or equivalently the minimum of $a^a(1-a)^{1-a}$. How can I get the other bound?
Comment: Just note that $0<a<1$ implies $a^a\in(0,1)$ and $(1-a)^{1-a}\in(0,1)$.


Como posso remover 'R$\xa0' de um resultado obtido?

Question: Estou coletando dados de um determinado site, onde ao coletar alguns valores estou enfrentando algumas dificuldades e gostaria de ajudar para resolver.
Tenho o seguinte código:
valores = soup_anuncio.find_all('span', attrs='ek9a7p-0')
categoria_valores = []
for i in valores:
    valor = i.get_text()
    categoria_valor.append(valor)
    print(categoria_valor)

E o valor retornado (em str) é:
['R$\xa01.417', 'R$\xa01.200', 'R$\xa0185', 'R$\xa018', 'R$\xa028', 'R$\xa02.848']

Eu tentei tirar o R$\xa0 do resultado de algumas formas, mas não consegui.
Como eu posso conseguir apenas os números em formato int?
Comment: Você quer valores monetários e int? Vai perder os centavos.
Comment: Os valores não tem centavos. Na verdade onde está o ponto é um separador de 1000
Answer: Se o objetivo é remover de uma string o símbolo de moeda brasileira e o ponto separador de milhar, itere por cada uma das strings pegue uma fatia do quarto caractere ao último para remover o símbolo de real mais o espaço e do que sobrar remova o ponto separador de milhar com str.replace() e então a converta para int pois como dito nos comentários os valores não possuem centavos.
categoria_valor = ['R$\xa01.417', 'R$\xa01.200', 'R$\xa0185', 'R$\xa018', 'R$\xa028', 'R$\xa02.848']

vals= [int(v[3:].replace('.','')) for v in categoria_valor]

print(vals)
#[1417, 1200, 185, 18, 28, 2848]

Teste o código no IdeOne
Aplicando no seu código:
valores = soup_anuncio.find_all('span', attrs='ek9a7p-0')
categoria_valor = [int(v.get_text()[3:].replace('.','')) for v in valores]


Logistic Regression: Classification Tables a la SPSS in R

Question: In SPSS output there is a pretty little classification table available when you perform a logistic regression, is the same possible with R? If so, how?
Comment: You should post an example of the SPSS output you want to replicate in R, or explicitly detail what the SPSS output is reporting
Comment: Good idea, output added for clarity. Thanks for the suggestion Andy.
Answer: I'm not aware of a specific command, but this might be a start:
# generate some data
> N <- 100
> X <- rnorm(N, 175, 7)
> Y <- 0.4*X + 10 + rnorm(N, 0, 3)

# dichotomize Y
> Yfac <- cut(Y, breaks=c(-Inf, median(Y), Inf), labels=c("lo", "hi"))

# logistic regression
> glmFit <- glm(Yfac ~ X, family=binomial(link="logit"))

# predicted probabilities
> Yhat <- fitted(glmFit)

# choose a threshold for dichotomizing according to predicted probability
> thresh  <- 0.5
> YhatFac <- cut(Yhat, breaks=c(-Inf, thresh, Inf), labels=c("lo", "hi"))

# contingency table and marginal sums
> cTab <- table(Yfac, YhatFac)
> addmargins(cTab)
        YhatFac
Yfac   lo  hi Sum
  lo   36  14  50
  hi   12  38  50
  Sum  48  52 100

# percentage correct for training data
> sum(diag(cTab)) / sum(cTab)
[1] 0.74

Comment: How would I generate Yfac if my variable is already a 1/2 dichotomous variable saved as a factor in R?
Comment: Nevermind, worked like a charm, just set Yfac <- df$dichotomous.var
Answer: Thomas D. Fletcher has a function called ClassLog() (for "classification analysis for a logistic regression model") in his QuantPsyc package. However, I like @caracal's response because it is self-made and easily customizable.


Save a copy of a large response stream to file on web server

Question: I have a large XML file that I'm producing from an SQL database and streaming to the client's web browser using the System.Xml.XmlWriter object.  The problem is, every time a user hits the web page, the 170MB file is produced in the DB and transfered again.
I would like to stream the file to the user so they get it as quick as possible, and then save the result to a file on the web server.  Future requests would then check first to see if the file exists. If it does, it would send the file instead of calling the DB.
My question:  How would I store what was written to the Response.Output object to a file?
Answer: You can use a buffer, save part of the data to the buffer, and at the same time send them and save them... here is an example:
byte[] buffer = new byte[4096];
int sourceBytes;
do
{
    // read it - or fix the buffer content
    sourceBytes = fs.Read(buffer, 0, buffer.Length);

    // out put to the client
    context.Response.OutputStream.Write(buffer, 0, sourceBytes);
    // saved it to the file.
    sWriter.Write(buffer, 0, sourceBytes);

} while (sourceBytes > 0);

Answer: Maybe something like this:
var filePath = "c:\\temp\\file.dat";
if(System.IO.File.Exists(filePath))
{
  using(var stream = System.IO.File.OpenRead(filePath))
     WriteToResponseStream(stream);
}
else
{
    byte[] file = GetFileFromDb();
    WriteToResponseStream(new MemoryStream(file));
    System.IO.File.WriteAllBytes(filePath, file)
}


Integral with inverse trig functions and u substitution

Question: I've been trying to find the integral of $\dfrac{dx}{x \sqrt{x^2-4}}$. Currently, following the example problem, I have it as $\dfrac{1}{2} S \dfrac{1\,du}{x \sqrt{4 [(\frac{x}{2})^2-1]}}$. From what I've got it looks like it's going to the formula matching $\sec^{-1}(x)$. But at this point I'm not sure what to do now about the 4 in there that will get me to the $1/2$ coefficient. I have $u = x/2$, and $du=\frac{1}{2} \, dx$. The answer given is $-\frac{1}{2}\csc^{-1}(\frac{x}{2})+C$. The opposite trig function from what I thought and with a negative somehow.
Comment: Nothing wrong with a trig sub, but you don't not HAVE to use a trig sub. Try a substitution $\sqrt{4-x^2}=t$ and see what happens
Comment: Sure, that's certainly fine (didn't catch that from your post), but with integration it is always good to know that there is more than one way to skin a cat :)
Comment: Well, the whole point of the problem and lesson was learning trig subs so that's what I'm doing.
Answer: \begin{align}
& \frac{dx}{x \sqrt{x^2-4}} = \frac{dx}{x\sqrt{4\left(\left(\frac x 2\right)^2 - 1\right)}} = \frac 1 {\sqrt 4} \cdot \frac{dx}{x\sqrt{\left( \frac x 2 \right)^2 - 1}} = \frac 1 2 \cdot \frac{dx/2}{\frac x 2 \sqrt{\left( \frac x 2 \right)^2 - 1}} \\[10pt]
 = {} & \frac 1 2 \cdot \frac{du}{u\sqrt{u^2 -1}} = \frac 1 2 \cdot \frac{\sec\theta\tan\theta \, d\theta}{\sec\theta\sqrt{\sec^2\theta - 1}} = \frac{d\theta} 2.
\end{align}
Answer:
$$
\int\frac{dx}{x\sqrt{x^2-4}}
~=~
\int\frac{x\cdot dx}{x^2\sqrt{x^2-4}}
~=~
\frac12\int\frac{d\big(x^2-4\big)}{\Big[\big(x^2-4\big)+4\Big]\sqrt{x^2-4}}
~=~
\frac12\int\frac{dt}{(t+4)\sqrt t}
$$

Now let $t=u^2.~$ :-$)$
Comment: Or, in the first step already, let $t=\sqrt{x^2-4}$. It is quiet intuitive...
Answer: It looks like the problem is the radical, namely: $\sqrt{x^2 - 4}$. If you make the trig substitution $x = 2\sec \theta$, then $\sqrt{x^2 - 4} = \sqrt{4(\sec^2 \theta - 1)} = \sqrt{4 \tan^2 \theta} = 2\tan \theta$. Similarly, $\frac{dx}{d \theta} = 2\sec \theta \tan \theta$, so $dx = 2\sec \theta \tan \theta \ d\theta$. So, the integral is:
$$\int \frac{2 \sec \theta \tan \theta}{(2\sec \theta)(2\tan \theta)} \ d\theta$$
$$ = \frac{1}{2}\int d\theta$$


replace image with rollover fade

Question: I am trying to replace an image with another image on rollover and use a fade.
I have 2 images water_bag.jpg and water_bag-hover.jpg
I am trying to replace one on rollover with the following javascript:

My html is just this:
<a  href="<?php echo tep_href_link(FILENAME_EVENTS); ?>">

What am I doing wrong?
Comment: That's not your HTML, that's your PHP.
Comment: sorry a mix.. Just some php in the href
Answer: you are setting the src to just '-hover.jpg'
you need to do this to set it to the new image:
$('.my_img').parent().append($('.my_img').clone().attr('src',$('.my_img').attr('src').replace('.jpg','-hover.jpg')).fadeIn('slow'))

Comment: Wouldn't that result in the image's src being akin to `path.to/image.jpg-hover.jpg`?
Answer: Here's simple way: set one image as a background, and fade in another on top:

JS:
$('body').find('*[hoverImg]').each(function(index){
    $this = $(this)
    $this.wrap('
')
    $this.parent().css('width',$this.width())
    $this.parent().css('height',$this.width())
    $this.parent().css('background-image',"url(" + $this.attr('hoverImg')+")")
        $this.hover(function() {
            $(this).stop()
            $(this).fadeTo('',.01)
        },function() {
            $(this).stop()
            $(this).fadeTo('',1)
        })
})

DEMO: http://jsfiddle.net/Diodeus/gYyBL/
Comment: Thanks. This worked well. I'd just replace the second width with height.. My pictures aren't squares.

replace image with rollover fade


A total newbie wants to learn how to write songs. What does he need?

Question: I am recently being interested in writing my own songs/my own music. However, I'm a newbie when it comes to music. I am not really musically talented nor inclined. I only know basic guitar chords and strum patterns. I know how to locate notes in the keyboard but that's about it (I don't even know proper finger position). I don't know how to read sheet music (I'm learning, though). I know the scale goes like CDEFGAB but that's about it. I am not tone deaf but I can't identify notes (tone deaf is not being able to identify if the notes being played have changed, right?)
So, aside from learning a main instrument, what else should I learn before I start making my own music?
Comment: Just a comment: *why* do you want to write songs?  Sure you can learn to "write songs" (and people even claim you can "learn be creative").  But why?  It's cool?  It gets the girls?  It's something one is supposed to do?  Or do you want to learn to write them because you just *have to*?  Because they are in you, and want to get out?  Because they're clamoring to get heard, for you make them get heard?  Since you say you're not even musically inclined (I take that as "Music doesn't really mean *that* much to me".  Wrong?  Correct please), it doesn't sound like this is an "inner urge".  So, why?
Comment: @JürgenA.Erhard: I want to learn how to make music because *I want to*. I took up Software Engineering because I wanted to make software (video games, to be exact). I joined the Guitar Club (when I was in high school) because I wanted to play the guitar. I entered Japanese class because I wanted to speak Japanese. Is it not enough reason to want to do something in order learn to do something?
Comment: @JürgenA.Erhard: By *not being musically inclined*, I meant I was not raised/did not grow in a music-filled environment (none of the members of my family knows how to play any kind of musical instrument, except the mouth, if that's an instrument). Sorry if it gave the wrong idea, English is not my mother tongue.
Comment: sorry, the thought of your mother tongue crosse my mind briefly, but your name made me go "Nah, he speaks English" ;-)  Oh, and the voice *is* musical instrument (it's called "singing", but I'm unsure if that's what you mean with "play the mouth" or if they're just very talkative :D)
Comment: Let me compare this, just for explanation, with writing books.  You shouldn't "want to become a writer" because of prestige, or money, or any such thing.  Because it's hard work (yes, @Silver :D), and it's not that rewarding in the mentioned aspects for the *vast* majority of "writers".  The Stephen Kings of this world are a rare exception.  So: if you want to become a writer (or any creative occupation at all), do it because you *have to*.  Because you feel drawn to it.  To *it*, not to the "side effects" of it.
Comment: Disclaimer: the above is my (strong, obviously) personal opinion.
Comment: @Lance Gray: then I think you should reformulate: ''not being musically inclined'' means you are not being ''drawn'' towards music, but the rest of your question suggests that you are, and that you merely feel you have to travel quite a distance to get where you want to be. This seems contradictory.
Comment: What happens when you try to play a spontaneously made-up tune? Are you wanting to write melodies, parts, arrangements, or all of the above, and maybe more?
Answer: First and most important thing you need to know: there is no such thing as "talented" or "not talented". Everything boils down to hard work and practice, so you definitely can do it!
It is quite easy to start composing your own songs if you know a few bits of theory. Particularly, you will need scales and chords that are formed within a scale. This is quite a big topic to learn, but you don't need to be a scale master to start. All you need to know, is that notes from one scale will sound good together if you put them in almost any order and the same goes for chords that are formed from those notes.
Let's take C major scale, that you mentioned in your question:
C-D-E-F-G-A-B-C
There are 7 basic 3-note chords that can be formed from those notes:
C
Dm
Em
F
G
Am
Bdim

For mainstream music, you, most often, can forget about the Bdim chord - it is not used so often. So, you have 6 chords at you hands, that sound good together, no matter how you place them. You start experimenting and make up a chord progression by moving the chords around. For example:
C / Am / F / G

Do you like how that sounds? If not, then just change the order of the chords or use others:
C / Em / G / F

Continue this, until you have a chord progression you like.
Then make up a rhythm. This might be some basic strumming or picking pattern, depending on what kind of song you are composing. For the last chord progression a good simple picking pattern will do:
$5.3 $4.0 $2.1 $3.0 $2.1 $1.0 $2.1 $3.0  $6.0 $5.2 $2.0 $3.0 $2.0 $1.0 $2.0 $3.0  $6.3 $5.2 $2.0 $3.0 $2.0 $1.3 $2.0 $3.0  $6.1 $5.3 $2.1 $3.2 $2.1 $1.1 $2.1 $3.2

That's it, you are a song writer! Start simple and than turn on your imagination.
Here is a PDF document with all the chords in all the keys, it's a great place to start: http://www.nextlevelguitar.com/pdf/chordsineachkey.pdf
A great video on the topic:
Comment: Disagree with the "there's no such thing as 'talent'".  Strongly.  It's popular, sure, because "everyone can be anything" is nice to hear.  But it's misleading.  That's not saying that working on your talent (however much it is, it's not all or nothing) doesn't have its place or isn't important.  But talent exists.
Comment: @Jürgen A. Erhard that's strongly subjective. I'm saying this successful people never say "I am successful because I'm talented", they always say "It's because I worked hard". Losers, however, really like to say "I have no talent, what can I do?". That's my point of view, of course. Really recommend this book:  http://en.wikipedia.org/wiki/Outliers_(book)
Comment: Thank you very much for this information. I really appreciate it(even though it'll take some time to digest all of these lol)! I have a few questions, though. On the C Major scale, am I only limited to those chords (C-Dm-Em-F-G-Am)? If I change one of them, say C to Cm, is it still C Major scale. And another one, will you suggest electronic music (virtual instruments)? (Second question seems like a whole new topic so it's okay not to answer)
Comment: Cm is straying outside the key of C major. That's not to say you can't do it. There are no rules, only conventions. Sticking to conventions is good for beginners because they're conventions that have become common for a reason.
Comment: @slim: Oh, I see. These keys/scales also apply to other instruments, right?
Comment: Yep, the scales are independent of the thing that makes the sounds (there is some extra complexity to do with the naming of notes on brass instruments, but I suggest you ignore that until you need it)
Comment: @Silver: I never heard a successful person say either.  They say lots and lots of things.  But these utterances are usually not among those things.  Not in this pure form, anyway.   And I didn't say that hard work doesn't play a part.  But... thanks for the book recommendation.  At least the WP article mentions "talent" twice :D  And it seems to argue that circumstances play at least as big a role as hard work.  I think I can agree to that.  ;-)
Comment: If your band has a keyboard player, and guitarist(s) are somewhat beyond beginner, then C major is a good key. If your band does _not_ have any keyboard player, it is easier to use the key of A as in [slim's answer](http://music.stackexchange.com/a/4943/249).
Comment: @JürgenA.Erhard I tend to believe that "talented" people are people who, for whatever reason, be it previous experiences or genes, find it easier to learn something than most others. Some people just find it easier to write music than others. They still have to work at it, but they may not need to spend as much work on it as another person. Bottom line, everything requires *some* work (I believe you stated as much before, just repeating you). "Talent" is not for a lack of work.
Comment: Oh, of course there's tak
Answer: Short answer:

(Note that this is in a different key to Silver Light's answer; the "three chord trick" in A major is easier for beginner guitarists because it doesn't involve a barre chord)
The long answer fills countless books. I quite like Rikky Rooksby's "How to write songs on guitar", which as well as covering a good amount of music theory, also includes tips on lyrics.
Still, you have enough to write a song right there.
One tip I would give right away is - don't get too hung up on being original. Hundreds of successful and popular songs follow the same 12 bar blues chord progression. It's better to start writing derivative crap, than to write nothing at all. You can get sophisticated and original later.
Writing something good > writing something bad > writing nothing at all.
Since you're not going to write something good right away, don't be afraid to write bad songs until you get better.
Comment: @lance: when you play the guitar, the strings' anchor/vibration node is on the fret, not on your finger. It doesn't matter where you finger is, as long as the string is held firmly on the fret. Hence that representation.
Comment: Thank you very much for the answer and advice. I'll be sure to look that book up. I have a question, why, in that image, is the G chord marked on the frets and not on the usual places (the space between frets)?
Comment: Just a different way of presenting the same information. The image is the famous cover of a 1970s punk fanzine.
Comment: "you're not going to write something good right away"... you know, all generalizations and absolutes are wrong, 100% of all cases.  Just as here.  The *likelihood* is very, very, very small, but it's not impossible.
Answer: I'm an amateur singer/songwriter who only recently started writing music. Before that, I only knew how to sing (choir) and play some basic guitar chords. I really didn't know anything about scales (still don't have a solid grasp on them), I didn't read sheet music (I still don't!)-- I only really had that desire to create music. In short, I'd say I was at a stage similar to where you are now.
Fast forward about a year - and I've been able to write and record (demos) a fair number of originals. Still a long way from professional, but both the results and process of my songwriting make me happy.
Here are the things that helped me in my own journey:
1. Keeping a scratchpad of thoughts and tunes.
I keep a journal for writing memories, rants, dreams, inspirations, random thoughts, etc. I did this even before I started songwriting-- eventually I realized that it made a good repository for material for writing lyrics. In addition, whenever I get sudden bursts of inspiration for a tune (this usually happens in the car!), I make sure to record it right away. I just use the voice recording utility on my phone or laptop, whichever's at hand. This way I have a repository of little song snippets.
2. Having a convenient songwriting tool.
In my case this is Garageband on my laptop! The interface is intuitive enough for me to be able to easily compose songs even without knowing how to read sheet music. I don't mean to say that this is the "best" music composition software or anything-- it's just that I personally found this to be the most convenient tool to use for my own songwriting. Each composer will have his/her own favourite tool, and it doesn't even have to be digital, it could just be a guitar and a pencil and paper. It just has to be something easy and comfortable for you.
3. Learning and performing my favourite songs.
"Good artists copy, great artists steal." Every time you study a song and practice performing it, you can learn something about rhythm, melody, and/or harmony, plus you develop your "ear". I don't know if I'm wording this correctly-- but when you develop your "ear", you're able to notice more subtle nuances in the music, and you can tell if it sounds "right" or if it sounds even slightly "off", and then you can figure out why and fix it.
4. Taking voice lessons.
I'm assuming that when you write your songs, you intend to have vocals? If so, I would also advise taking some voice lessons (or at least regularly vocalising with scales), even if you don't plan to perform the songs yourself. Voice training develops your "ear" as well.
And lastly, this is cliché but, I think the most important thing was that I just kept at it, and I put in the hours. I agree with the answers above, start simple, and writing something bad is better than writing nothing. Good luck and enjoy! :)
P.S. Glad you asked this question because I'm learning a lot from the answers here too.
Comment: "I only really had that desire to create music." same here
Answer: What the total newbie needs is to partner with someone who is experienced at songwriting. Be willing to be the experienced person's apprentice and discard your ego. Be willing to learn, collaborate, and share ideas
It's hard to find good people who will let you work with them, but it is very helpful.
Answer: It's really cool you are so interested in writing songs, and I am sure you'll be great at songwriting and music if you keep practicing regularly.
So what I learned as a good way for writing songs is similar to what the best answer here says.

Play some chords you know/like and place them the way they sound nice to you. So if you want them to be C-D-A-F or C-F-D-A (that is called chord progression). First I'd try to make a chorus, it's the main part of the song and some songs just have the chorus chords throughout the whole song.
After you know which chords you want to play you can decide on the rhythm and dynamics. How fast do you want them to play? How loud? You might consult songs you like and check how they've done it.
You must have some inspiration in you, some need for expression. So maybe you are happy and want to express that or sad or melancholic or furious. While playing your chords start singing along whatever comes to your mind. That will be your melody. Some singers say it's easier for them to write the lyrics first. So consider doing so, just a phrase or two should be enough for the beginning. Or add it later or leave it out altogether.
Now you have a melody, words, chords and you know the rhythm and dynamics. The most important thing in my opinion now is NOT TO GIVE UP on the idea ("Oh, it just sounds like another song I know" or "Doesn't sound good" – at least that's what I always think) – just play it once or twice and record yourself. If you keep on doing all these steps regularly, you'll have a good collection of ideas. Coming back to them after a few days you'll maybe have some further ideas for improvement. And with your musical practice, new chords, melodies, and techniques will come into your "pool" of song possibilities. Because there is nothing you can do WRONG when writing a song.

I hope you will find the tips helpful! :) Here is an article with the first 10 steps of how to write a song, might be helpful, too. All the best for all beginning songwriters :)
Answer: If you're not an accomplished player of some instrument, with experience of playing a wide range of styles, don't write songs to an instrument.   You'll just be locked into the narrow horizons of your (lack of) technique.   If you're a words man, look for a musical collaborator.  Same if you're a melody genius.   (If you're neither, and don't really play an instrument properly, what makes you think you have something to offer songwriting?)
But however you do it, do it a LOT.   And FINISH your songs.  Tonight's job is to write a song about fish.  You have until midnight to COMPLETE it (or at least to complete your contribution to it - words, tune, whatever).  Yes, I know some parts could be improved, but get to the end, write a complete song.  Tomorrow, start a new one.  After a year, you'll have written 100 songs.  I absolutely guarantee they will be getting better.  A lot better.
Yes, of course you can re-visit old material.  Good songs often use ideas from two or more previous projects.   But basically, stick to the song-a-day routine. Too many people have just a handful of songs which they've been fiddling with for years.  There's no progress that way.
Answer: The answers given above are good, however, for the beginning you only need what you already know. One way to write a simple song is:

Write some lyrics.
Find the chords on the guitar that sound good together. Usually 4 chords at most are enough.
Play the chords and try to sing any melody that sounds good while playing those chords. If you are happy with it, with the melody, you just made a song.

Bonus: to make a song more interesting, try to use (all or some of) the same chords, but in different progressions for the chorus. Then of course because you have different chords, try to fit there a different melody.
Later you may become interested on how to compose better and better songs... My advice is:

Play on a musical instrument as much as possible because often a moment of the inspiration arrives after many hours of playing and then record it and you will use it in your next song.
Play different musical instruments to boost the creativity, especially the ones that make you develop a good hearing. I often find that after playing several hours on the violin (creatively and improvising, not reading from the music sheet) I have much better ideas when I grab the guitar again.
Learn the theory. This will help you understand your ideas in a more coherent way and you will be able to get most out of them, but without the first 2 points, I find the theory quite limited in helping to compose music.

So who am I that I give you advice? I am an amateur musician who never had any music lessons apart from those at my primary school. I mainly sang and played for enjoyment on the guitar, violin and piano. I still do not know much theory, but would like to learn more. And here is an example of what I composed with the advice I give you: With Respect.
As you can see, the channel is new because I started composing only recently. I believe that with my advice you can also make a good progress.
My friend followed those steps and after 1 hour, she almost had her first song ready - when she played it at the concert, people really liked it.
Answer: I know your feelings bra, I feel much in the same boat as you. Started playing music maybe way too late in life and I've gotten to the point where I can play bits and pieces of hundreds of songs and I've only bothered to learn a few songs the whole way through but I'm getting to that point to where I feel like I have no originality. I can almost play while reading a tab for most easy going songs if I know the tune and how it goes just like singing but once you hit that feeling like oh I've mastered a few Billy talent songs or a RHCP song you think well I still can't make jack shit songs myself and perhaps thats because I never turned up to music class in school and I don't know how to find a note or really even how to use a chord progression. Then I also feel like half my problem is that I'm used to flowing progression stuff but the covers I like to play are all jumpy and jazzed up and it doesn't feel like its me or what not in the moment, makes me feel like a few buzzes or vibs or put me in a happy state but I want to play that piece that defines me.
However what is slowly getting me there is I've stripped right back to basics, I don't typically sing to the songs I play, in fact I can't multi task like that at the moment. But if you pick something simplistic that you can sing along to or maybe get a singer who can improvise and play with others keep getting fresh ideas, think about the processes they come up to, to bring the vocals they have like are they singing about world issues, is that what you want to be or like are you just going to sing about the random twinkee that you ate the other day for example because you could be all kinds of different and nobody can really tell you how you want to write your song because they don't know you.


Non-static method cannot be referenced from a static context .setRetryPolicy

Question: Some kind guy gave me an answer to my question by posting code, however it isn't complete from the looks of it. I think its supposed to be a short timed-out kinda function, but it says "Non-static method setRetryPolicy (com.android.volley.RetryPolicy)' cannot be referenced from a static contex"
I don't exactly know how to fix this myself, so I'd really appreciate if someone had a quick fix for this.
Here is the code;
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,responseListener,errorListener);
                int socketTimeout = 500000;//30 seconds - change to what you want
                RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
                StringRequest.setRetryPolicy(policy);
                // Creating RequestQueue.
                RequestQueue queue = Volley.newRequestQueue(CreateUser.this);

                // Adding the StringRequest object into requestQueue.
                queue.add(registerRequest);

It gives that error at in the 4th line. This is also a continuation of my previous questions on trying to make a basic register script in Android Studio. Thanks in advance
Answer: I believe it's meant to be
registerRequest.setRetryPolicy()

as that's the StringRequest instance in your code, and then one dealt with further down.
However, you really should just ask the person who posted the answer next time.


How do I dismiss a progressView when it's fully loaded?

Question: I have a progress view that tracks the status of a Youtube video loading via WKWebView. When it's loaded, I want to dismiss the progressView because when I click back onto the main page of my app, the status bar is still there (but it doesn't display anything and takes up space, blocking other elements of my app). How do I, when the progressView is completely loaded, dismiss the progressView?
This is my class that deals with the WKWebView.
import UIKit
import WebKit

class VideoPlayViewController: UIViewController, WKNavigationDelegate {

    var webView: WKWebView!
    var progressView: UIProgressView!
    var videoURL: String = ""

    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: videoURL)!
        webView.load(URLRequest(url: url))
        webView.allowsBackForwardNavigationGestures = true

        //Progress View/ Refresh Button
        progressView = UIProgressView(progressViewStyle: .default)
        progressView.sizeToFit()
        let progressButton = UIBarButtonItem(customView: progressView)
        progressView.progressTintColor = UIColor(red: 254, green: 53, blue: 98)

        let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let refresh = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(webView.reload))
         refresh.tintColor = UIColor(red: 254, green: 53, blue: 98)

        toolbarItems = [progressButton, spacer, refresh]
        navigationController?.isToolbarHidden = false

        // Lets the progress bar change according to what the Observer sends back (# from 0-1)
        webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)

    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            progressView.progress = Float(webView.estimatedProgress)
        }
    }
}

If you need more info / more code, let me know.
Answer: override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

    guard let keyPath = keyPath else { return }

    switch keyPath {
    case "estimatedProgress":
        // If you are using a `UIProgressView`, this is how you update the progress
        progressView.isHidden = webView.estimatedProgress == 1
        progressView.progress = Float(webView.estimatedProgress)

    default:
        break
    }
}

and don't forgot to deinitialize the observers
 deinit {
    //remove all observers
    webView.removeObserver(self, forKeyPath: "estimatedProgress")
}

Comment: https://imgur.com/a/AYA9mst - this is a link for images of the app. What I'm trying to do is dismiss the footer view or whatever it is that displays the progress view. what your solution does is just delete the progress bar itself, but not the whole footer bar view thing. (although I appreciate the code). any idea on how to fix it now?
Answer: Check webView(_:didFinish:) method of WKNavigationDelegate
Answer:
You have to set typeable:

public typealias isCompletion = (_ isCompleted: Bool?) -> Void

And add variables like this in class:

var completion: isCompletion?

Now you have to create a method :

func webViewLoad(_ iscompleted:@escaping isCompletion){
    completion = iscompleted
    let url = URL(string: videoURL)!
    webView.load(URLRequest(url: url))
    webView.allowsBackForwardNavigationGestures = true
}

You have to set completion in the delegate method

func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
    print("finish to load")
    completion(true)
}

You can call this method from viewdidload like this:

    // show loading from here
    webViewLoad { (flag) in

    //hide loading here

    }


Imprimir várias matrizes separadamente

Question: Gostaria de saber se tem como imprimir essas três matrizes sem que tenha de criar vários for's, a impressão das mesmas na tela deve ser separada. ( preciso de uma alternativa por que tenho pouco espaço e o código ficou bem extenso quando fui imprimir da maneira convencional )
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>

int main () { setlocale(LC_ALL,"Portuguese");

    int mat1[100][100], mat2[100][100], mat3[100][100], linha = 0, coluna = 0;

    // red, blue, green

    printf("\nInforme o número de linhas e colunas: ");
    scanf("%i %i",&linha,&coluna);

    for ( int i = 0; i < linha; i++){
        for ( int h = 0; h < coluna; h++){
            printf("\nInforme um digito para linha %i, coluna %i matriz red: ",i, h);
            scanf("%i",&mat1[i][h]);
        }
        system("cls");
        for ( int j = 0; j < coluna; j++){
            printf("\nInforme um digito para linha %i, coluna %i matriz blue: ",i, j);
            scanf("%i",&mat2[i][j]);
        }
        system("cls");
        for ( int q = 0; q < coluna; q++){
            printf("\nInforme um digito para linha %i, coluna %i matriz green: ",i,q);
            scanf("%i",&mat3[i][q]);
        }
        system("cls");
    }

    // imprimir toda a primeira, depois a segunda e por fim a terceira...

    return 0;
}

Answer: Se você quer imprimir 3 ou mais, é melhor colocá-las juntas.
int matriz[3][100][100];
int x,y,z;
for(x=0; x<3; x++)
    for(y=0; y<100; y++)
        for(z=0; z<100; z++;){
            printf("entre o valor da matriz %x, linha %d, coluna %d: ", z,y,z);
            scanf("%d", &matrz[x][y][z]);
         }

for(x=0; x<3; x++)
    for(y=0; y<100; y++)
        for(z=0; z<100; z++;)
            printf("matriz %d[%d,%d]: %d",x,y,z,matriz[x][y][z]);

O primeiro for anda pelas matrizes (x == total de matrizes) e os outros 2 percorrem linhas e colunas.
Assim você pode percorrer quantas matrizes você quiser, e deixa o código mais organizado;

Imprimir várias matrizes separadamente


Equivalent of a debug macro in Java

Question: I'm writing a program that reads structures from a file. For debugging purposes, it would be very convenient if I could have a compile-time toggle that prints the names and values of everything read which could be disabled for better performance/code size in the production version. In C, I could use the preprocessor like such to accomplish this:
#ifdef DEBUG
  #define READ(name, in) { name = read(in); printf("#name: %d\n", name); }
#else
  #define READ(name, in) { name = read(in); }
#endif

void myreader(mystream_t *in)
{
    int a, b, c;

    READ(a, in);
    READ(b, in);
    READ(c, in);
}

Is there any way I can reproduce this construct? I thought about this:
private static final boolean DEBUG_ENABLED = true;

private int debugRead(MyInputStream in, String name) {
    int val = in.read();

    if (DEBUG_ENABLED) {
        System.out.println(String.format("%s: %d", name, val));
    }
    return val;
}

public MyReader(MyInputStream in) {
    int a, b, c;

    a = debugRead(in, "a");
    b = debugRead(in, "b");
    c = debugRead(in, "c");
}

However, this requires me to type the name of all the variables twice as well as storing the strings corresponding to all the names even on the release version. Is there a better approach to this?
EDIT: The biggest concern I have is code verbosity. The last thing I want is to have my code cluttered with debug/print/trace statements that obscure the actual reading logic.
Comment: what about a logger? with level options? debug, info , fatal , error..
Comment: There is not much you can do. #defines create actual source code for the compiler. That concept does not exist in Java (there are preprocessors and you can generate code but not that easily)
Comment: Well, there is no such concept of `PreProcessor` in java. There is `Annotation` unfortunately not close enough.
Comment: @Kowser The solution proposed in that question is interesting, but the biggest drawback is (1) needing to store the name of the variable being read in the bytecode, and (2) needing to pass it around.
Answer: I'm not sure if this is an apples to apples solution, but one thing that's idiomatic in Java is to use a logging framework.  With it, you can execute log.debug wherever you might need debugging.  SLF4j is a common facade for logging frameworks.  You could just use it with JUL logging.
Usually you leave the logging code there and you configure the logger externally to either print or not print the messages.
If you're using SLF4j, the debug message will look like this:
log.debug("Setting the creation timestamp to {}", timestamp);

Most loggers can be configured to tell you what time, class and method the logging message came from.
This has some pros and cons compared to what you're used to.
Cons

I have to admit, this will take a lot of effort to learn when all you really want right now is a System.out.println.

Most of the loggers are configured on the classpath.  The classpath is a non-trivial part of java to learn but you will have to learn it eventually anyway.  It's really important to understand.

It won't automatically print out the name of the variable passed in.  AFAIK, you'll have to write that detail yourself

Pros

Using a logger is very robust.  You can leave the code there for production and dev mode and just configure the verbosity appropriately
It can automatically print out the context of the class/method and date of the message and other things like that
You can configure the output in lots of different ways.  For example, "output to the console and log.txt but when that file becomes > 100mb, rollover the old data to log2.txt and keep at most 5 log files."
Comment: Could you give an example of using logging that doesn't increase code verbosity? For example, if I did `a = in.read(); log.debug("read a: %d", a);` for all my reads, my code would quickly become unreadable. And if I put the logging+reading in a method, I would still need to pass the name of the variable to the method, or else the logging would be useless.
Comment: Nitpick: Better to use `log.debug("Setting the creation timestamp to {}", timestamp);` (avoid string concat and parameter evaluation unless debugging is actually turned on).
Answer: To the general problem of emulating C/C++ macros in Java, there are several solutions.  The particular case of logging is usually resolved in a simpler way.  The simplest, conceptually closest, and puristic form is abstracting the macro in an interface and producing alternative implementations:
public class Sample {

    class mystream_t {
    }
    public int read(mystream_t is) {
        return 0 ;
    }
    static final boolean DEBUG= false ;

    interface ReadType {
        public void apply(int[] name,mystream_t in);
    }
    ReadType READ; {
        if( DEBUG ) {
            READ= new ReadType(){
                public void apply(int[] name,mystream_t in) {
                    name[0]= read(in) ; System.out.printf("#name: %d\n",name);
                }
            };
        } else {
            READ= new ReadType(){
                public void apply(int[] name,mystream_t in) {
                    name[0]= read(in) ;
                }
            };
        }
    }
    void myreader(mystream_t in) {
        int[] a= new int[1], b= new int[1], c= new int[1];
        READ.apply(a, in);
        READ.apply(b, in);
        READ.apply(c, in);
    }
}

This makes use of a simple, static form of code injection.  I tried to make the code as close as possible to the original.
The second most relevant way of emulating C/C++ macros in Java requires Annotations and Annotation Processing.  It's even closer to C/C++ macros, but requires more effort and resorts to a mechanism that could not be considered pure part of the language.
And the third one is using an Aspect-Oriented Programming framework like AspectJ.
Comment: Is this written in Java?  That won't compile
Comment: @MarioRossi: I don't think you can assign to a local variable in Java outside of its scope at all. Or get to a local variable name dynamically. Please do a minimum effort and focus on that.
Comment: @tieTYT  Please do a minimum effort and focus on the concepts behind.  Once you have corrected any mistake, your are welcome to edit my answer and post it there if not too long nor changing the answer essentially.
Comment: @Thilo  Sorry, what local variable?  READ?  Of course it is in scope!  What are you talking about?
Comment: `int a, b, c; READ.do(a, in);` There is no way this will assign to `a`.
Comment: @Thilo,  OMG, the bottom of the question is completely different.  But I'll make the change.
Comment: compiling / running http://ideone.com/1Gtinq
Comment: @Thilo  What were you saying about local variables assigned out of scope?  Learned a bit Java here?

Equivalent of a debug macro in Java


REDHAT VM to run as HOST

Question: I'm running a RHEL5 w/ 1 VM, that VM runs it's own LVM (boot, swap and root).
so now what I need is to be able to boot directly into that VM bypassing my host enviroment and making my VM is a host, I figured since it's has it's own LVM i should be able to load it up directly.
VM itself is a RHEL5 and currently host runs RHEL5 w/ XEN VM
Comment: Please make this readable english. I don't understand what you are trying to do.
Comment: I think he's got a RHEL5 hosting a VM of some kind.  He wants to boot the VM install directly on the hardware without bothering with the RHEL5 host (ie a non-VM install).  But without knowing more about the setup, I couldn't answer the question.
Comment: What is the VM's operating system?  When you sah "has its own LVM", is that on a real disk or a virtual one?  VMware or Xen (since I'm presuming KVM in RHEL 5 is too new for anyone to have actually deployed it yet)?
Comment: i just rephrase it, i hope this is better
Answer: If I've understood you correctly, you want the HOST to not boot, and only the HOSTED VM to boot?
That's not possible without doing a V2P migration. The hypervisor has to be running, or the VM cannot.
Comment: Warren is correct. The host OS must be running since that is where the hypervisor lives. If you want a small footprint host try VMWare ESXi.
Comment: What's V2P? and what's Hypervisor? XEN can be fully virtualized and/or PARA virtualized, fully virtualized it's like you running full blown OS without any modifications, para is slightly modified OS
Comment: @alexus, I thought you'd know :) ..The "hypervisor" is the virtualization engine you're running. "V2P" is the shorthand for "virtual to physical".
Answer: Are you attempting to move your VM out of the virtual environment onto the parent physical server?
If so, it's possible cloning software like Clonezilla may do this.  Boot Clonezilla inside the VM, clone the virtual disk to a network attached storage device (or something else) outside the VM, then boot Clonezilla on the physical machine and clone that image down to the bare metal.
Somebody correct me if this won't work!
Comment: backup, backup, backup before trying!
Comment: It will only work if the real hardware is close enough to the VM's hardware that the "VM" can boot on the bare metal.  If the bare metal requires some fancy ethernet or RAID controller driver, you might not get anywhere.
Comment: in Linux - quite possible actually
Comment: my hardware close enough, at least i'd like to think so and I want to give it a shot...

REDHAT VM to run as HOST


Next and Previous Page Buttons for iFrame content

Question: I made a website where there are a bunch of links that load into an iframe. There are buttons that allow the user to navigate to the next and previous links in the list. I used this to do that.
var i = 0, links = $('a').toArray();
  $('.next').click(function() {
  i++;
  if(i === links.length){ i = links.length - 1; }
  $('.frame').attr('src', links[i]);
});
//loads next link in iframe

$('.prev').click(function() {
    i--;
    if(i < 0){ i = 0; }
    $('.frame').attr('src', links[i]);
});
//loads previous link in iframe

The problem is that if a user clicks on say the 3rd link, and then clicks the next button, it does not go to the 4th link, but rather to the 2nd link, since the click function just changes the value of i which is set to 0 by default.
To solve this I thought of creating another variable that stored the current link loaded in the iframe as such:
var current = $('.frame').contents().get(0).location.href

and then setting the value of i according to the index value of the current link as such:
var i = links.indexOf(current)

Note: I am aware that
$('.frame').contents().get(0).location.href

will cause cross-domain errors. The links I am using are from the same domain so this won't be a problem.
Sadly, this doesn't work. Any clue where I'm going wrong? Here's a fiddle.
JSFiddle
I have to use only Javascript (Jquery is fine). Please keep in mind that creating an array with the links inserted manually is not an option since there are a large number of links and more being added.
Answer: Your problem is that your i variable keep the previous index from the previous clicking on the next/prev buttons. You should fixc your code, that when the user clicks any link, i will update, as follows:

var i = 0, links = $('a').toArray();

$('.next').click(function() {
 i++;
 if(i === links.length){ i = links.length - 1; }
 $('.frame').attr('src', links[i].href); // To get the src you must get href attribute
});
//loads next lesson in iframe
$('.prev').click(function() {
 i--;
 if(i < 0){ i = 0; }
 $('.frame').attr('src', links[i].href); // To get the src you must get href attribute
});
//loads previous lesson in iframe
$('a').click(function() {
  i = links.indexOf(this);
});
.nav {
 top: 0;

 z-index: 2;
 width: 100%;
 background: #212121;
}
.nav button {
 font-size: 25px;
 color: white;
 padding: 10px;
 width: 100px;
   border-color: white;
    border-radius: 8px;
   background-color: #212121;
 margin: 5px;
}
/*nav menu buttons*/

.frame {
   height: 50vh;
   width: 100%;
   border: solide white 1px;
}

body {
   background: #212121;
   color: white;
   font-family: 'Nanum Gothic', 'calibri';
   margin: 5px;
}
/*body view*/

a {
   padding: 5px 0px 5px 30px;
 display: block;
   font-size: 20px;
   color: white;
}

  <button class="prev">Prev</button>

  <button class="next">Next</button>

Link 1

Link 2

Link 3

Link 4

Link 5


Why is expression/statement/variable executed before object init?

Question: Consider following code
class A():
    print("hello")
    value = 44
    def __init__(self):
        print("init")

if __name__ == "__main__":
    pass

Output:
>>>
hello
>>>

The variable or expression... are inside class but outside any methods. By running this script I would expect that nothing happens because I didn't instantiate anything. Why is the interpreter executing it?
Comment: Note that `if __name__ == "__main__": pass` does nothing
Comment: Does this answer your question? [Order of execution with python class](https://stackoverflow.com/questions/55793567/order-of-execution-with-python-class)
Comment: or [Why does a class' body get executed at definition time?](https://stackoverflow.com/q/26193653/4518341)
Answer: Code inside a class statement is executed immediately, as part of executing the class statement. Your code is roughly equivalent to
# Execute the body of the class statement
print("hello")
value = 44
def __init__(self):
    print("init")

# Call type, passing names defined in the body as a dict
# as the third argument
A = type("A", (), {'value': value, '__init__': __init__})

# Clean up the names, as they are not left in the global namespace
del value, __init__

Once the class A is defined, the only code that gets executed upon instantiation is the body of _init: a = A() is roughly equivalent to
a = A.__new__(A)
a.__init__()

Comment: Thank you now I understand it.
Answer: From the docs:

Class definitions, like function definitions (def statements) must be executed before they have any effect. (You could conceivably place a class definition in a branch of an if statement, or inside a function.)
...
In practice, the statements inside a class definition will usually be function definitions, but other statements are allowed, and sometimes useful


Evitar quebra de linha (encavalando) em col-md bootstrap

Question: estou fazendo um grid que irá aparecer alguns produtos, até 3 por linha, em mobile 1 por linha, o problema é que a altura varia e dai nos monitores ele 'encavala' um por cima do outro.
Solução seria colocar um
height: 270px fixo, porém para layout mobile não posso.
Meu HTML

1 - teste de linha Gigante e sempre vai dar algum problema

2 - teste

3 - teste

4 - teste

5 - teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste teste

                    1 - teste de linha Gigante e sempre vai dar algum problema

                    2 - teste

                    3 - teste

Exemplo no fiddle
https://fiddle.jshell.net/dorathoto/mt0rb3kj/3/
No fiddle é difícil de visualizar a tela grande, para ver como ele enrosca.
Tentei fazer através de: Mas acho que devo ter confundido algo, pois deveria funcionar.
@media (min-width: 768px) {
    .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 {
        max-height: 146px !important;
    }
}

@media (min-width: 992px)
{
.col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 {
    max-height: 250px !important;
}
}

Mas sem sucesso.
Update [18/05/2016]
Foi proposto o uso da <div class="row"> a cada 12 elementos.
Mas se tenho uma opção que varia de acordo o dispositivo, ou seja para tela -md- seria a cada 3 itens uma row, mas para tela -sm- a cada 2 itens e para -xs- 1 item por row.
Abaixo uma imagem que ilustra o meu problema
Comment: Isso me parece caso para flexbox
Answer: A sua quantidade de grids esta errada, mesmo que use o .row, o .col-*-4 deve ter apenas 3 divs em um mesmo .row
Pra saber se a quantidade sempre some os .cols o total DEVE ser sempre 12, ou seja:

Se for usar apenas .col-*-4 então será 3, pois 4+4+4 = 12
Se usar .col-*-6 será 6+6=12
Também pode fazer 6+3+3=12 por exemplo.

No seu caso tem oito divs com .col-*-4, então 8x4=32, ou seja o resultado é diferente de 12 e por isto ocorre o problema ou outros problemas (que provavelmente você tentou resolver com CSS e acabou se amarrando na gambiarra que agora esta gerando este problema).
Recomendo que leia a documentação http://getbootstrap.com/css/#grid antes de usar, pois apesar de fácil de entender muitas coisas no bootstrap não são intuitivas só de usar, como esta em inglês vou por alguns trechos importantes do GRID aqui:

Os .rows devem ser colocados dentro de um .container (com largura fixa) ou .container-fluid (largura total) para o alinhamento e preenchimento adequado (se não possuir isto irá afetar as margens).
Use os .rows para criar grupos horizontais de colunas.
O conteúdo deve ser colocado dentro de colunas (.col-*-*) e colunas deve ser sempre filhas de .row e de nenhum outro elemento.
Os .col-* geram espaçamentos entre eles. O espaçamento é compensado no .row através de margem negativa.
Colunas de grade (.col-*) são criados para ter especificamente disponíveis 12 colunas que você pode estender. Por exemplo, três colunas iguais usaria três .col-xs-4.
Se mais do que 12 colunas são colocados dentro de uma única fileira, cada grupo de colunas adicionais irão para quebrar para uma nova linha.
As classes .col- aplicam-se o width:; para telas com tamanho maior ou igual ao tamanho minimo (definido nos medias-queries) e acaso o dispositivo tenha a tela menor, ele irá substituir pela classe .col- definida para telas menores. Portanto se usar qualquer classe .col-md-* para um elemento não só irá afetar o seu estilo em dispositivos do tamanho de tela escolhido (md, lg, sm, etc), mas também afetar telas maiores se uma classe .col-lg-* não estiver presente (isso é um exemplo).

O mais correto seria algo como:

            Foo bar baz

            Foo bar baz

            Foo bar baz

            Foo bar baz

            Foo bar baz

            Foo bar baz

            Foo bar baz

            Foo bar baz

            Foo bar baz

Comment: Comentário adicional, traduzir esse texto ao pé da letra da documentação é bem dificil de ler, até mesmo pra quem sabe inglês, tentei adaptar o texto usando explicações do meu próprio entendimento do bootstrap, se tiver algum erro fique a vontade pra corrigi-lo.
Comment: Mas é se fosse "col-md-4 col-sm-2" como faria o row? Se pra um vai ser com 3 itens e outro com 6?
Comment: @Dorathoto todos sm tem que dar 12, assim como todos md tem que dar 12. Ou seja se tem 3 colunas, vai ter que ficar algo como: `  `
Comment: É mas no caso de produtos todos iguais não poderia fazer um com o resto e sim algo padronizado, no texto q Vc traduziu no 2° item diz q se passar mais de 12 fará quebra de linha, isso que eu quero, mas sem encavalar.
Comment: @Dorathoto sem encavalar? Como seria isto? Se esta falando do conteudo dos cols vazando no exemplo https://fiddle.jshell.net/dorathoto/mt0rb3kj/ tente usar `overflow: hidden` (claro que o conteudo vai sumir)
Comment: Cara não posso pensar que essa seja a única solução, pois se tenho um sistema  não posso colocar row a cada 3. se ele for sm ficaria com 1 linha com 2 produtos e 1 produto na linha de baixo
Comment: @Dorathoto hoje a noite, quando sair do trabalho tento fazer algo que funcione, pois é possivel adicionar mais de 3, mas a questão é entender quais classes aplicar no pra hora certa como, xs-12 seria pra resolução A, md-6 seria pra B, etc. Faz assim me manda um desenho na pergunta de como gostaria em cada resolução.
Comment: ok, atualizando a pergunta, grato


How can I make a field appears when you check on a checkbox?

Question: I'm making a module and on the administration page there is a form and I want to make one of the fields appears only when user check on a checkbox. Like the option to add a new content to a menu.
Comment: Please add the code snippet of the custom module for better understanding.
Comment: It's a normal form ,,, $form[]
Comment: the simplest method, without having to get into ajax callbacks, etc - is to add the elements to the form from the start, and then a bit of jquery to hide, and then show the element you want
Answer: You can use #states from FormAPI that drupal provides.
Below is the link
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#states
Below is the code from drupal form api
<code>$form['email_canceled']['settings'] = array(
    '#type' => 'container',
    '#states' => array(
      // Hide the settings when the cancel notify checkbox is disabled.
      'invisible' => array(
       ':input[name="email_canceled_toggle"]' => array('checked' => FALSE),
      ),
    ),
  );
</code>
Answer: Also you can use like this
<code>$form['field_image']['#states']['visible'] = array(':input[name="field_checkbox[und]"]' => array('value' => 1));
</code>
so only when the check box is checked the field image will be displayed otherwise it will be hidden.


How to solve for the parameters in a logistic function?

Question: I want to find the parameters of a logistic function. I read the guide here. It has a very clear explanation, but it did not have the final solution that I need.
Now, we will consider a basis logistic function:
$$h_\theta(x^{i})=\frac{1}{1+e^{-\theta_0-\theta_1x}}$$
We want to find $\theta_0$ and $\theta_1$ subject to minimum cost function:
$$J(\theta)=-\frac{1}{m}\sum_{i=1}^{m}y^{i}\log(h_\theta(x^{i}))+(1-y^{i})\log(1-h_\theta(x^{i}))$$
We use the notation:
$$\theta x^i:=\theta_0+\theta_1 x^i_1 $$
Then
$$\log h_\theta(x^i)=\log\frac{1}{1+e^{-\theta x^i} }=-\log ( 1+e^{-\theta x^i} ),$$
$$\log(1- h_\theta(x^i))=\log(1-\frac{1}{1+e^{-\theta x^i} })=\log (e^{-\theta x^i} )-\log ( 1+e^{-\theta x^i} )=-\theta x^i-\log ( 1+e^{-\theta x^i} ),$$
and
$$J(\theta)=-\frac{1}{m}\sum_{i=1}^m \left[y_i\theta x^i-\theta x^i-\log(1+e^{-\theta x^i})\right]=-\frac{1}{m}\sum_{i=1}^m \left[y_i\theta x^i-\log(1+e^{\theta x^i})\right],~~(*)$$
where the second equality follows from:
$$-\theta x^i-\log(1+e^{-\theta x^i})=
-\left[ \log e^{\theta x^i}+
\log(1+e^{-\theta x^i} )
\right]=-\log(1+e^{\theta x^i}). $$
All I need now is to compute the partial derivatives of $(*)$ w.r.t. $\theta_j$.
As
$$\frac{\partial}{\partial \theta_J}y_i\theta x^i=y_ix^i_j$$
$$\frac{\partial}{\partial \theta_j}\log(1+e^{\theta x^i})=\frac{x^i_je^{\theta x^i}}{1+e^{\theta x^i}}=x^i_jh_\theta(x^i), $$
The above steps are correct, but it did not have the solution for $\theta_0$ and $\theta_1$. We can take the derivative and put it equal $0$. Namely,
$$\frac{\partial J(\theta)}{\partial \theta_0}=y-\frac{e^{\theta_0+\theta_1 x}}{1+e^{\theta_0+\theta_1 x}}=0~~(*)$$
$$\frac{\partial J(\theta)}{\partial \theta_1}=yx-\frac{xe^{\theta_0+\theta_1 x}}{1+e^{\theta_0+\theta_1 x}}=0 ~~(**) $$

Are $(*)$ and $(**)$ correct?
Assume that $y$ and $x$ are known. How do you represent $\theta_0$ and $\theta_1$ by $y$ and $x$?
Answer: They didn't supply the final solution because there is no closed form solution for estimating the parameters of a logistic regression.  Instead, an iterative search algorithm is used.  The most common choice is the Newton-Raphson algorithm, but there are many possibilities.
Comment: This is one difference comparison with linear regression (Gradient descent), right? Thanks
Comment: That's right, @user8264. The non-linear transformations in the GLiM mess it up, but in a linear model there is no problem.


How should the mediation formulas be applied?

Question: I was reading through the material on the mediation formulas [1] and do not understand how to apply it in cases where Y, the outcome is binary and Pr(Y) is estimated using logistic regression and Z, the mediator is continuous.
All the texts I have referred to suggest that there is no closed form solution when Pr(Y) is estimated using logistic regression but there is a closed form when probit regression is used. I was trying to figure this out by applying the mediation formulas using the simplest case where we have:
<code>X where x = control, x' = treatment,
Z is a continuous mediator
Y is a continuous outcome
</code>
Setting this mediation up, we have:
[Eq1] $Y = \beta_0 + \beta_1X_y + \beta_2Z + \varepsilon_1$
[Eq2] $Z = \gamma_0 + \gamma_1X_z + \varepsilon_2$
And the mediation formulas state:
[Eq3] Direct effect, $DE_{x,x'}(Y) = E(Y_{x', Z_x}) - E(Y_x)$
[Eq4] Indirect effect, $IE_{x,x'}(Y) = E(Y_{x, Z_{x'}}) - E(Y_x)$
Under no confounding, we have:
[Eq5] $DE_{x,x'}(Y) = \sum_{z}{[E(Y|x', z) - E(Y|x,z)] P(z|x)}$
[Eq6] $IE_{x,x'}(Y) = \sum_{z}{E(Y|x, z)[P(z|x') - P(z|x)}$
First question:
Are [Eq3] and [Eq4] re-expressions of pure direct [Eq7] and total indirect effects [Eq8] as presented in many other literature?
[Eq7] $DE_{x,x'}(Y) = E[Y(x', Z(x))  - Y(x, Z(x))]$
[Eq8] $IE_{x,x'}(Y) = E[Y(x', Z(x')) - Y(x', Z(x))]$
If it is, then why is [Eq4] not [Eq9]?
[Eq9] $IE_{x,x'}(Y) = E(Y_{x', Z_{x'}}) - E(Y_{x'})$
Second question:
How should [Eq5] be applied? In this case, Z is a continuous variable so what should P(z|x) be? I see in various other sources that suggest that when all variables are continuous, you can just substitute in the terms as in [Exp1].
[Exp1] $DE_{x,x'}(Y) = [\beta_0 + \beta_1x' + \beta_2 * (\gamma_0 + \gamma_1x)] - [\beta_0 + \beta_1x + \beta_2 * (\gamma_0 + \gamma_1x)]$
[Exp1] appears to follow [Eq7] but I do not follow how this is an application of [Eq5].
I was hoping that understanding how [Eq5] and [Eq6] are applied in the continuous Z and Y case can help me understand why there is no closed form expression for the direct and indirect effects of the following mediation model:
[Eq10] $Pr(Y) = [1 + exp({-(\beta_0 + \beta_1X_y + \beta_2Z + \varepsilon_1)})]^{-1}$
[Eq11] $Z = \gamma_0 + \gamma_1X_z + \varepsilon_2$
where
$\varepsilon_1$ follows a logistic distribution
$\varepsilon_2$ follows a normal distribution
[1] Pearl J. The Causal Mediation Formula - A Guide to the Assessment of Pathways and Mechanisms. Prevention Science. 2012 Aug;13(4):426–36.
Answer: Let's start by computing $\sum_{z}E[y|x', z]p(z|x)$. If $z$ is continuous, you just change the summation to integration, and $p(z|x)$ now refers to the density,
$$
\begin{align}
\int_z E[y|x', z]p(z|x)dz &= \int_z(\beta_0 + \beta_1x' + \beta_2z)p(z|x)dz\\
&=\beta_0 + \beta_1x' + \beta_2\int_zzp(z|x)dz\\
&=\beta_0 + \beta_1x' + \beta_2E(z|x)\\
&=\beta_0 + \beta_1x' + \beta_2(\gamma_0 + \gamma_1x)
\end{align}
$$
Thus, we have that,
$$\int_{z}(E[y|x', z]- E[y|x, z])p(z|x)dz = [\beta_0 + \beta_1x' + \beta_2(\gamma_0 + \gamma_1x)] - [\beta_0 + \beta_1x + \beta_2(\gamma_0 + \gamma_1x)]$$
Now, if you posit a logistic regression for $y$, then you have to solve the following integral,
$$
\begin{align}
\int_z E[y|x', z]p(z|x)dz &= \int_z p(y=1|x', z)p(z|x)dz\\
&=\int_z \text{logit}^{-1}(\beta_0 + \beta_1x' + \beta_2z)p(z|x)dz\\
&=\int_z \frac{1}{1+e^{-\beta_0 - \beta_1x' - \beta_2z}}p(z|x)dz
\end{align}
$$
Which you can see is not as straightforward as the linear case. In fact, as per this answer,  most likely there isn't a closed form solution and you will need to use simulation or other types of approximation.
Regarding your other questions, yes Eq3 is equal to Eq7, you just wrote the potential outcomes differently. Eq4 and Eq8 are both indirect effects, just having a different reference for how we are holding the X not via mediation fixed (one is fixing at $x$ and the other fixing at $x'$). As to your Eq9, remember that $E[Y_{x'}] = E[Y_{x', Z_{x'}}]$ by composition, so that equation is effectively equal to zero.
Comment: Thanks for your explanation. in the last line of the integration in the case of a logistic regression, why wouldn't one be able to integrate p(z|x) as in the previous continuous case and use E(z|x)?
Comment: @JackeJR the logit function is not linear, we can't simply move the integral inside like in the linear case.
Comment: Pardon the ignorance, why can we do that in the linear case and not the logistic case?
Comment: @JackeJR integration (or in this case, expectation)  is a linear operator https://en.wikipedia.org/wiki/Linearity_of_integration#cite_note-1. As a simple example, you can always write $E[aX+bY]= aE[X] + bE[Y]$ but in general for an arbitrary function $g(\cdot)$, $E[g(X)] \neq g(E[X])$.
Comment: @JackeJR Here you can see that the integral most likely does not have a closed form solution https://math.stackexchange.com/questions/207861/expected-value-of-applying-the-sigmoid-function-to-a-normal-distribution. In this case you can compute it with monte carlo simulations, or you can use approximations.


Using Docker4Drupal in Production vs. its commercial Wodby solution

Question: I've been playing with https://github.com/wodby/docker4drupal on a DigitalOcean droplet and am utterly amazed at how it all works.
However, it recommends that people use https://wodby.com/ for production and I'm wondering if I have to; it seems like an unnecessary step when my testing has four sites running perfectly in "production mode".
Does anybody know in what way Docker4Drupal is designed to be run in a local environment when it seems so well on a regular server?
This isn't a question of money.. Just effort. I'm a one man show and don't need dev/staging/production for what I'm working on right now.
Answer: Disclosure: I'm a Docker4Drupal maintainer and Wodby co-founder.
We do not limit usage of our images, it's MIT licensed, so if you want - go ahead and deploy the images in production. However, you'll have to do some work before that, e.g. set up a router, certificates, cron, etc. Configuring usual stuff with containers is not always obvious especially if you're not proficient with containers. Since we already handle all of this in our platform we've added this recommendation (people asked us about production). Also, stability requirements are higher for production (including freezing the docker version).
Originally, we created docker4drupal just to provide a local environment for our customers (instead of connecting Vagrant) but later it became obvious that it is valuable for many drupalers including those who do not use Wodby. In other words, historically, it was prod > local transition, not the other way around.


Calculating the probabilities of a die "weighted" by another die

Question: I don't think I have the math chops to solve this problem without heavy approximation, so I'm pitching it here. Here's the premise:
Suppose that you were to throw two N-sided dice. If the number rolled by the first die is less than or equal to that of the second, then the ultimate result of the dice roll is the number face-up on the first die. If the second die rolls a lower number, you must reroll both dice. You must continue rolling both dice until a definitive outcome is reached. Here are some examples of how this would play out with a 6-sided die:

First die: 4, Second die: 5 =>
4 ≤ 5 => Outcome: 4

First die: 2, Second die: 1 =>
2 > 1 => Outcome: Reroll =>
First die: 1, Second die: 6 =>
1 ≤ 6 => Outcome: 1

First die: 6, Second die: 2 =>
6 > 2 => Outcome: Reroll =>
First die: 4, Second die, 3 =>
4 > 3 => Outcome: Reroll =>
First die: 3, Second die: 3 =>
3 ≤ 3 => Outcome: 3

My question is this: For any value of N, is there a formula I could use to calculate the probability of any single possible outcome (e.g. chances of rolling a 13 when N = 20)? If so, what is that formula? Thank you!
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: I assume your two dice are distinguishable (for instance, they have different colors) because otherwise it doesn't make sense to talk about the "first die" and the "second die".
You pick $x$ and $y$ and throw the result out if $x > y$, so the result is equally likely to be any of the pairs $(x, y)$ with $1 \le x \le y \le n$.
The pairs with smallest value $x$ are $(x, x), (x, x+1), \ldots, (x, n)$ and there are $n - x + 1$ of them.    The total number of pairs $(x, y)$ with $x \le y$ is $n(n+1)/2$.  So the probability of getting $x$ with this procedure is
$${n-x+1 \over n(n+1)/2}$$
For example:

when $n = 6$ the probability of getting $1$ is $6/21$; the probability of getting $2$ is $5/21$; and so on down until the probability of getting $6$ is $1/21$.
when $n = 20$ the probability of getting $x = 13$, as you asked about, is $(20 - 13 + 1)/(20 \times 21 / 2) = 8/210$.

I'm guessing you have some gaming application in mind, and the idea is to have a method that's weighted towards giving the smaller numbers - if so, this works.
Answer: Fix an $N$, define the random variable $X$ to be the outcome of your process. You want to find its distribution, namely for each $k\leq N$ you want to find $Pr(X=k)$.
How can we find it?
For that we'll define another random variable, $Y$, which is the result of a single game (rolling both dice once), $Y$ can get the out comes $1,...,N$ and $reroll$.
Now notice that $$ Pr(X=k)=Pr(Y=k)+Pr(Y=reroll)Pr(X=k) $$
Since we can divide the event "our processes ends with k" to two disjoint smaller events:
"the processes ends on the first game and yields k" which has probabilityh of $Pr(Y=k)$
or
"the first game ends with $reroll$ and then the processes proceed and ends with $k$" which has the probability $Pr(Y=reroll)Pr(X=k)$
It's easier to calculate the distribution of $Y$. And as we saw, it will be enough for calculating the distribution of $X$.
Now The calculations :)
denote $x_k:=Pr(X=k),y_k=Pr(Y=k),\varepsilon=Pr(Y=reroll)$
we have $$x_k=y_k+\varepsilon x_k$$ so we get $$ x_k = \frac{1}{1-\varepsilon}y_k$$
$y_k=\frac{N-k+1}{N^2}$ - because only the pairs $(k,k),...(k,N)$ (out of $N^2$ possible pairs) are part of the event "output $k$ after the first game".
Calculating $\varepsilon$, notice $|A|+|B|+|C|=N^2$ where $A$ is the event "first die result is stricly grater", $B$ is the event "second die result is stricly grater" and $C$ is the event "both dice output the same number". Notice $Pr(A)=Pr(B)$ (from symmetry) and $Pr(C)=\frac{1}{N}$, hence $Pr(A)=\frac{N-1}{2N}$. Since the event $\{Y=reroll\}$ is exactly the enent $A$, we get $\varepsilon=\frac{N-1}{2N}$.
In total $$Pr(X=k)=x_k=\frac{1}{1-\varepsilon}y_k=\frac{2N}{N+1}\frac{N-k+1}{N^2}=\frac{2(N-k+1)}{N(N+1)}$$
$$\blacksquare$$


Can be certain items in an array be compared for something to be true - C#

Question: i have been having trouble getting this code to work is there something wrong with it or am i just doing it wrong
string a = teams[1];
string b = wins[1];
int numWins = 0;
while (o < wins.Length)
{
    if (a != b)
    {
        numWins++;
    }
    o++;
}

numOfWinsLabel.Text = numWins.ToString();

it is adding to the counter when both of them are equal in the txt files that i have set
Can someone plz help me?
Comment: It would be helpful if you more clearly explained what your intended result is, and what the current output of the program is.
Comment: For one o is not declared
Comment: @Sam he wants the counter to increment when the team is the winner
Answer: You seem to want to walk through the arrays, and you seem to try to use the o variable to point to each element. But you're not "telling" the arrays to actually use the o variable.
What happens in that case is that the variables get assigned the values of index 1 and they never change. It's also worth noting that arrays usually start at index 0.
Try the following:
int numWins = 0;
for (int o = 0; o < wins.Length; o++)
{
    string a = teams[o];
    string b = wins[o];

    if (a != b)
    {
        numWins++;
    }
}

numOfWinsLabel.Text = numWins.ToString();

This of course also assumes that the teams has at least as much elements as the wins array, or you'll get an exception.
I've changed the while to a for as it's more suitable for situations where you already know the number of times you want to loop.
Comment: Excellently explained!
Comment: In this case `numWins` should be an array.  Otherwise you are incrementing the counter any time any team wins.  So it will always end up equaling wins.Length
Comment: @SamHazleton I don't know what the arrays contain, and frankly I don't understand what you think the arrays contain.


How to store an uploaded swf file in a MySQL database using PHP?

Question: How do I store an uploaded swf file in a MySQL database using PHP?
Answer: The best way is to store the file on disk, and then store the metadata (like filename, and possibly other fields such as uploader) in the database. This way you will get a faster database, because you don't need to have large BLOB fields in the table, and you will also serve the files faster since they can be read directly from disk instead of sent through the MySQL connection over the network.
So when the file is uploaded, give it a unique filename and store it in a folder on disk. Then store metadata (including the unique filename) in the database. If you have trouble defining a unique filename, just save the metadata first and have an AUTOINCREMENTed column in the database that you use as filename.
Answer: // here u can upload swf files also

<?php
//define a maxim size for the uploaded images in Kb
 define ("MAX_SIZE","100");

//This function reads the extension of the file. It is used to determine if the file  is an image by checking the extension.
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

//This variable is used as a flag. The value is initialized with 0 (meaning no error  found)
//and it will be changed to 1 if an errro occures.
//If the error occures the file will not be uploaded.
 $errors=0;
//checks if the form has been submitted
 if(isset($_POST['Submit']))
 {
    //reads the name of the file the user submitted for uploading
    $image=$_FILES['image']['name'];
    //if it is not empty
    if ($image)
    {
    //get the original name of the file from the clients machine
        $filename = stripslashes($_FILES['image']['name']);
    //get the extension of the file in a lower case format
        $extension = getExtension($filename);
        $extension = strtolower($extension);
    //if it is not a known extension, we will suppose it is an error and will not  upload the file,
    //otherwise we will do more tests
 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif") && ($extension != "swf"))
        {
        //print error message
            echo '
Unknown extension!
';
            $errors=1;
        }
        else
        {
//get the size of the image in bytes
 //$_FILES['image']['tmp_name'] is the temporary filename of the file
 //in which the uploaded file was stored on the server
 $size=filesize($_FILES['image']['tmp_name']);

//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
    echo '
You have exceeded the size limit!
';
    $errors=1;
}

//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="images/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
    echo '
Copy unsuccessfull!
';
    $errors=1;
}}}}

//If no errors registred, print the success message
 if(isset($_POST['Submit']) && !$errors)
 {
    echo "
File Uploaded Successfully! Try again!
";

 }

 ?>

 <form name="newad" method="post" enctype="multipart/form-data"  action="">

<input type="file" name="image">

<input name="Submit" type="submit" value="Upload image">

 </form>


Perform INSERT or UPDATE with the same stored procedure?

Question: I'm writing a personal application to handle my railroad time slip tickets.  I have a lot of the application already programmed.  A quick rundown of what the application does....

Get tickets from my email box and parses the HTML into class objects
INSERTS that ticket into an SQL database

What I ran into is, my "Additional Pay" can change after the payroll department reviews the possible additional pay I may get.  When I sent myself a new ticket, the only thing that will change is that "Additional Pay".
I would like to put all the logic to check for an existing ticket and either INSERT or UPDATE within SQL rather than my C# application.
I've created a test database and a simple console application that reproduces the issue I'm having, just to make pasting "all" the code here simple.
Here's my table in SQL
CREATE TABLE [dbo].[Tickets]
(
   [id] [int] IDENTITY(1,1) NOT NULL,
   [TicketNumber] [nchar](10) NULL,
   [StraightTime] [money] NULL,
   [OverTime] [money] NULL,
   [AdditionalPay] [money] NULL,

   CONSTRAINT [PK_Tickets]
       PRIMARY KEY CLUSTERED ([id] ASC)
               WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
                     IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
                     ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]) ON [PRIMARY]
GO

Here's my INSERT that does work
ALTER PROCEDURE [dbo].[spTickets_Insert]
    @TicketNumber nchar(10),
    @StraightTime money,
    @OverTime money,
    @AdditionalPay money,
    @id int = 0 OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO dbo.Tickets (TicketNumber, StraightTime, OverTime, AdditionalPay)
    VALUES (@TicketNumber, @StraightTime, @OverTime, @AdditionalPay);

    SELECT @id = SCOPE_IDENTITY();
END

Here's my C# console application
using Dapper;
using System.Data;

Console.WriteLine("Adding ticket to database using stored procedure");

using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(@"Server=(LocalDb)\\MSSQLLocalDB;Database=TestSQL;Trusted_Connection=True;"))
{
    TicketModel ticket = new TicketModel();
    ticket.TicketNumber = "MC1234";
    ticket.StraightTime = (decimal)234.76;
    ticket.OverTime = (decimal)64.21;
    ticket.AdditionalPay = (decimal)200.12;

    var p = new DynamicParameters();
    p.Add("@TicketNumber", ticket.TicketNumber);
    p.Add("@StraightTime", ticket.StraightTime);
    p.Add("@OverTime", ticket.OverTime);
    p.Add("@AdditionalPay", ticket.AdditionalPay);
    p.Add("@id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);

    connection.Execute("dbo.spTickets_Insert", p, commandType: CommandType.StoredProcedure);

    ticket.id = p.Get<int>("@id");
}

public class TicketModel
{
    public int id { get; set; }
    public string? TicketNumber { get; set; }
    public decimal? StraightTime { get; set; }
    public decimal? OverTime { get; set; }
    public decimal? AdditionalPay { get; set; }
}

Here is the new stored procedure I'm trying to get working
ALTER PROCEDURE [dbo].[spTickets_InsertUpdate]
    @TicketNumber nchar(10),
    @StraightTime money,
    @OverTime money,
    @AdditionalPay money,
    @id int = 0 OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    IF EXISTS (SELECT 1 FROM Tickets WHERE TicketNumber = @TicketNumber)
    BEGIN
        UPDATE dbo.Tickets
        SET AdditionalPay = @AdditionalPay
        WHERE TicketNumber = @TicketNumber;
    END
    ELSE
    BEGIN
        INSERT INTO dbo.Tickets (TicketNumber, StraightTime, OverTime, AdditionalPay)
        VALUES (@TicketNumber, @StraightTime, @OverTime, @AdditionalPay);

        SELECT @id = SCOPE_IDENTITY();
    END
END

I change ticket.AdditionalPay to another value, and change dbo.spTickets_Insert to dbo.spTickets_InsertUpdate in my console application to test the UPDATE.
When I do that, I get this error:

System.ApplicationException: 'Attempting to cast a DBNull to a non nullable type!  Note that out/return parameters will not have updated values until the data stream completes (after the 'foreach' for Query(..., buffered: false), or after the GridReader has been disposed for QueryMultiple)'

I THINK I know that this is because I have that OUTPUT parameter in my stored procedure. I have spent a few hours Googling how to fix this.  I've looked at OUTPUT Inserted.TicketNumber, and several variations of that.
I'm hoping it's just a syntax thing that I'm not aware of. I am learning many SQL items, stored procedures being one of them, with this project.
I know I can do this check in my C# code and just call either an INSERT or UPDATE stored procedure, but I'd like to combine them and just let SQL handle it if possible.
Thanks!
I've tried using the UPDATE statements OUTPUT parameter with no luck
Comment: Your "update" here will not create a new record, hence you return no value from scope_identity(). But your C# logic expects a value. You will have to decide how to handle that. As it is this is simply the problem you have - what do you want Update to return, since it can't return a scope_identity() value. To put this another way, in your ELSE clause (for insert) you have a select query: `SELECT @id = SCOPE_IDENTITY();`. But in the IF clause (for update) you have no select query. This mismatch is your problem I think.
Comment: You might want to read about [this upsert antipattern](https://sqlperformance.com/2020/09/locking/upsert-anti-pattern)
Comment: Correct, this is the problem I'm having.  Dapper in my C# application is expecting @id as the output variable.  I'm able to provide that in my INSERT.  I don't know if I can do that in my UPDATE.  Is it possible to send the "id" of the row UPDATEd?  If so, what would that syntax look like?
Comment: I read through the link @Stu provided and the information there made sense, so I created a new stored procedure.  It works as expected in SQL Management Studio, but I'm still getting the same error through C# code, the DBNull error.  I'm not sure how to post the new stored procedure though.
Answer: Just to get a resolution to this topic....
I was pretty sure I didn't use the "id" in my C# code, so I changed it a bit to not return the SCOPE_IDENTITY() on my INSERT, which meant I didn't need to figure out how to return the "id" on my UPDATE.  I would still be interested if it's possible to do, but I got my stored procedure working.
Comment: 100% it's possible to do,. But you need to decide what id to return. It makes complete sense that you return the ID of the record you just updated. This is trivial to get.
Comment: If you post the actual code your'e using in the answer (to help others infuture) I could suggest a change


Do page arguments in hook_menu get sanitized?

Question: The title pretty much says it all.
If a callback is defined in a hook_menu, such as
function mymodule_menu ()
{
    $items = array();

    $items["mymodule/foo/%"] = array(
        "page callback" => "mymodule_foo",
        "page arguments" => array(2),
        "access arguments" => array("mymodule permission"),
        "type" => MENU_CALLBACK,
    );

    return $items;
}

function mymodule_foo ($parameter)
{
    // do stuff
}
When the callback gets called, has $parameter been sanitized, or is this the responsibility of the module?
I always sanitize in the module, but have never seen this stated either way and haven't found where callbacks get called from core.
Answer: In D6
menu_execute_active_handler() calls the callback. However it gets it's arguments from menu_get_item(), which uses arg.
I can't see any sanitizing in any of that. So it looks like the answer is no.
In any case extra sanitizing can't hurt.
Comment: Thanks.  This confirmed my suspicions, and also reminded me to try replacing space with underscores when searching core files for how something is implemented.
Comment: Extra sanitizing *can* hurt because double-escaped special characters can become hard to read.


How to make first line colored and bold in PHP?

Question: I am a novice.

<?php echo $order['store_address']; ?>

This results in address including name of person and address on next line. I want to make persons name bold but failed to use first-line pseudo element. How can i make it bold.
Comment: Can you post what are you getting from DB??
Is it stored with html or just plain text???
Comment: Its an invoice print, where the $order['store_address'] gives Seller's address with his name on first line
Answer: Why not use the pseudo element ::first-line ? It's exactly what you want
Answer: You can use the pseudo element ::first-line.
OR
Also you can place your php in HTML tags(such as div, p, span, heading, etc.) and style it using css.
For Example,

<?php echo $order['store_address']; ?>


Using "Tab" key to move from NSTextField to NSMatrix

Question: I have a Cocoa Form (xib) which contains some NSTextFields and an NSMatrix of NSButtonCells. I can use the "Tab" key to tab though the NSTextFields, but the NSMatrix gets skipped over.
I want to be able to tab into the NSMatrix, and tab from one button to the next within the matrix.
I have put in the following line of code, but it is having no effect:
[mtxMyMatrix setTabKeyTraversesCells:YES];

Can anybody help with this problem or point me to an example? I have searched for hours with no success.
Comment: Have you tried setting "Next Key View" for one of the text fields to be the matrix itself?
Comment: Thanks - yes I have. The focus jumps over the matrix to the text field after it, ignoring the matrix.
Answer: I had a similar problem and the solution I found was fiddling with the "first responder" setting. Specifically, making sure that the entire form didn't refuse, and each individual field likewise accepted first responder status. Again, the whole form, and each field as well. I too searched for a while... :( I'm also noob.
Comment: This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](http://stackoverflow.com/questions/ask). You can also [add a bounty](http://stackoverflow.com/privileges/set-bounties) to draw more attention to this question once you have enough reputation.


Choose at least N from large groups

Question: Having 40 aces and 60 kings in a deck of hundred (100), what is the probability of a sample of 50 cards containing 25 or more aces?
Is it required to do sum over binomial distributions for 0 to 24 to archive to the probability or is there "math" way obtaining result (distribution like binomial but for limited non-independent groups).
Raw power solution would lead to something like this
$\mathbb{P} = 1 - \sum^{24}_{i = 0} \frac{permutations\ of\ i\ aces}{total \ permutations} =\ ??$
Is it solvable by hand?
Answer: There is a pencil-and-paper method which avoids summing binomial probabilities, provided you have a table of cumulative Normal distribution probabilities and are happy with an approximation.
The exact distribution of the number of aces is a Binomial distribution with parameters $n=50$ and $p=0.4$, which has mean $\mu = np = 20$ and variance $\sigma^2=np(1-p) = 12$.  This distribution can be approximated by a Normal distribution with the same mean and variance.  We want to find $P(X \ge 25) = 1 - P(X \le 24)$.  Since the Binomial distribution is discreet and the Normal distribution is continuous, we apply a "correction for continuity" and find $P(X \le 24.5)$.  We have
$$X \le 24.5$$
if and only if
$$\frac{X-\mu}{\sigma} \le \frac{24.5 - 20}{\sqrt{12}} = 1.30$$
and $(X- \mu)/\sigma$ has (approximately) a Normal distribution with mean zero and variance one, so we can look up the cumulative probability in a table, with the result that
$$P \left( \frac{X-\mu}{\sigma} \right) \le 1.30\approx 0.9032$$
so the probability of having 25 or more aces is about $1-0.9032=\boxed{0.0968}$.
This result compares fairly well with the exact result of
$$1- \sum_{i=0}^{24} \binom{50}{i}(0.4)^i (0.6)^{50-i} =0.0978$$
for the Binomial distribution but requires less computation, again assuming you have a table of Normal probabilities available.
Answer: You must be careful here on how the sampling is done.
a) With replacement , i.e. you shuffle the deck, draw a card and take note of it for your sample,
put it back, reshuffle and proceed to a new draw.
In this case the probability of extracting an ace is constant for each draw, and you can
use the binomial distribution as already suggested.
b) Without replacement, i.e. you shuffle the deck and extract your sample , sequentially or randomly choosing
out of the cards remaining in the deck.
In this case, instead, the probability of drawing an ace is not constant along the draws, as it depends on the result
of all the precedent ones.
As the space of equi-probable events you shall consider that of all possible outcomes of the shuffling, i.e. the permuations
of the deck, and count the aces appearing in the first $s$ draws, which will become your sample of $s$ elements.
Refer to this Wikipedia article on this subject.
Therefore, given a deck with $a$ aces and $b$ kings , a sample of $s$ cards, and denoting by $p(k;a,b,s)$ the probability
of having $k$ aces in the sample,then
in the case  with replacement you have
$$
\eqalign{
  & p_{\,r} (k;a,b,s) =   \cr
  &  = \left( \matrix{
  s \cr
  k \cr}  \right)\left( {{a \over {a + b}}} \right)^{\,k} \left( {{b \over {a + b}}} \right)^{\,s - k}  =   \cr
  &  = {1 \over {\left( {a + b} \right)^{\,s} }}\left( \matrix{
  s \cr
  k \cr}  \right)a^{\,k} b^{\,s - k}  \cr}
$$
while in the case without replacement it is
$$
\eqalign{
  & p_{\,o} (k;a,b,s) = {{\left( \matrix{
  a \cr
  k \cr}  \right)\left( \matrix{
  b \cr
  s - k \cr}  \right)} \over {\left( \matrix{
  a + b \cr
  s \cr}  \right)}} =   \cr
  &  = {{a!} \over {k!\left( {a - k} \right)!}}{{b!} \over {\left( {s - k} \right)!\left( {b - s + k} \right)!}}{{s!\left( {a + b - s} \right)!} \over {\left( {a + b} \right)!}} =   \cr
  &  = {{a!b!} \over {\left( {a + b} \right)!}}{{s!} \over {k!\left( {s - k} \right)!}}{{\left( {a + b - s} \right)!} \over {\left( {a - k} \right)!\left( {b - s + k} \right)!}} =   \cr
  &  = {1 \over {\left( \matrix{
  a + b \cr
  a \cr}  \right)}}\left( \matrix{
  s \cr
  k \cr}  \right)\left( \matrix{
  a + b - s \cr
  a - k \cr}  \right) \cr}
$$
which is a Hypergeometric Distribution.
The two probabilities become close when the sample size is small wrt the population ($s<<a,b$)
but are quite different for large sample sizes.
Take a small example, which is easy to verify by drawing a sketch, with $a=2, \; b=4, \; s=3$, together with that in your post ($a=40, \; b=60, \; s=50$):
the result are as depicted below

Concerning the question if it is possible to compute by hand
$$
\eqalign{
  & P(25 \le k) = \sum\limits_{25\, \le \,k\, \le \,40} {p_{\,o} (k;40,60,50)}  =   \cr
  &  = {1 \over {\left( \matrix{
  100 \cr
  50 \cr}  \right)}}\sum\limits_{25\, \le \,k\, \le \,40} {\left( \matrix{
  40 \cr
  k \cr}  \right)\left( \matrix{
  60 \cr
  50 - k \cr}  \right)}  \cr}
$$
I do not see any practical way, if not resorting to the approximation via the Normal
distribution, as suggested by @akward. Only that the variance in the second case is quite less
than the Binomial distribution.
Answer: I don't think there is another way than the following.
Let 50 be the sample size and if you draw an ace, it's a succes. If not, it's a fail. The probability you draw an ace is 40%. With these figures you can model it as a binomial distribution and you can find the answer to:
$ P(x\geqslant25)$ , where $x$ is the amount of times you draw an ace in this sample of 50.
You can find this via the CDF of the binomial distribution:
$\sum_{k=25}^{50} \binom{n}{k}p^k(1-p)^{n-k}$
, where $N = 50$ , $k = 25,26,...N$, $p =0.40$
or via excel:
$1-BINOM.DIST(24,50,0.4,TRUE)$
As a result: the probability of a sample of 50 cards containing 25 or more aces is roughly 9.78%

Choose at least N from large groups