Is there any algorithmic way to split a piano MIDI into left and right hand parts?

Question: Equivalently, how can I split notes across a staff in the most "correct" way?
Something simple would be to just split the parts across a particular note (i.e., middle C), but this would be much less than ideal. Any solutions welcome: professional software, academic algorithms, or half-baked ideas.
Comment: Do you hope to find something that works in real time, or something that works on a recorded sequence of notes?
Answer: With my MIDI sequencer, you figure that out on your own.  You drag rectangles around the hand's notes that are the easiest to pick out, and that'll move them to that other hand's track.
So, manually, you:

Figure out if the piece is even playable by a human - sometimes it's for a computer to play (a bunch of hugely complex, blisteringly fast arpeggios a human has no hope of playing).
Play through the song and see where your thumbs end up.
Edit the MIDI and pick out the notes that need to move.
Move them.

You really can't do this in an automated fashion.  There are too many variables (like hand span, fingering, hands hopping over each other, a finger on one hand poking in 2 notes, there's all kinds of craziness that can happen).
So, you get a piano player, and have him/her do it.
Your question kind of boils down to "how do you place your hands when playing a piano piece."
Answer:  Learn to play the piano.
Comment: This is true enough.  Plenty of metrics are possible but none will be perfectly accurate.  It's not uncommon for me to take issue with the way the composer or editor has set the fingering, either; there's no objective standard, which is sort of required for something algorithmic.
Comment: yeah, if humans can't even figure it out, well, ya just can't expect a computer to be able to.
Comment: Canonical examples which would confound an algorithm: Mozart sonata hand-crossings, Goldberg Variations hands overlapping-interwoven, Liszt and Debussy's extra staves, Ligeti Etudes hold a chord with one hand while the other races through the held notes.  Get a computer to do those, and it'll probably also drive a car in rush hour.


A uniformity for a space is pseudometrizable iff it has a countable base

Question: Definition. Given a set $S$, a uniformity on $S$ is a filter $\mathcal{U}$ in $S\times S$ with the following properties:
(a) Every $A\in \mathcal{U}$ includes the diagonal $D:=\{\langle s,s\rangle:s\in S\}$.
(b) For each $A\in \mathcal{U}$, we have $A^{-1}:=\{\langle y,x\rangle:\langle x,y\rangle\in A\}\in \mathcal{U}$.
(c) For each $A\in \mathcal{U}$, there is a $B\in \mathcal{U}$ with $B\circ B\subset A$.
Theorem A uniformity $\mathcal{U}$ for a space $S$ is pseudometrizable (it is the pseudometric uniformity for some pseudometric $d$) if and only if $\mathcal{U}$ has a countable base.
Proof. "If": Let the uniformity $\mathcal{U}$ have a countable base {$U_n$}. For any $U$ in a uniformity $\mathcal{U}$, applying (c) twice, there is a $V\in \mathcal{U}$ with $(V\circ V)\circ(V\circ V)\subset U$. Recursively, let $V_0:=S\times S$. For each $n=1,2,...$,
----------------------------Below is what I don't understantd----------------------------------
let $W_n$ be the intersection of $U_n$ with a set $V\in \mathcal{U}$ satisfying $(V\circ V)\circ(V\circ V)\subset V_{n-1}$.
----------------------------Above is what I don't understantd----------------------------------
Let $V_n:=W_n\cap W_n^{-1}\in\mathcal{U}$. Then {$V_n$} is a base for $\mathcal{U}$, consisting of symmetric sets, with $V_n\circ V_n\circ V_n\subset V_{n-1}$ for each $n\geq 1$.
My question is: $V_n$ is intersection of $W_n$. $W_n$ is intersection of $U_n$. What's the usage of $V$ there?
Answer: The $U_n$ are a priori unrelated elements of the uniformity, and for the remainder of the proof (to construct the pseudometric) we need them to be sort of nicely decreasing "with room to spare", and symmetric too. So we construct $V_n \subseteq U_n$ that are still in $\mathcal{U}$ (so they remain a base for $\mathcal{U}$ ) but we want them to be symmetric and "decreasing with room to spare" in the sense that $V_n \circ V_n \circ V_n \subseteq V_{n-1}$ for all $n$. The construction goes in steps to show how the different axioms for a uniformity are used here:
$V_0$ is trivial, to get started (it's a member of any uniformity). For the recursion we assume we have $V_{n-1}\in \mathcal{U}$ (at stage $n$) and we want to find a $V_n$ as needed.
Then find $V' \in \mathcal{U}$ such that $(V' \circ V') \subseteq  V_{n-1}$ by (c) applied to $V_{n-1}$ and then apply (c) to $V'$ and we have $V\in \mathcal{U}$ such that $V \circ V \subseteq V'$ and combining these we get
$$(V \circ V) \circ (V \circ V) \subseteq V_{n-1}\tag{1}$$
Then define $W_n = V \cap U_n \subseteq U_n \in \mathcal{U}$ (as entourages form a filter) which takes care of being a subset of $U_n$ but because $W_n \subseteq V$ we also have from (1):
$$(W_n \circ W_n) \circ (W_n \circ W_n) \subseteq V_{n-1}\tag{2}$$
which implies (we don't need four sets but only three, we can omit one because $\Delta_X \subseteq W_n$ by (a)):
$$W_n \circ W_n \circ W_n \subseteq V_{n-1}\tag{3}$$
But the $W_n$ is not yet symmetric, so we note that by (b) $W_n^{-1} \in \mathcal{U}$ too and $V_n := W_n \cap W_n^{-1}$ is symmetric (easy reasoning: $(x,y) \in V_n \to (x,y) \in W_n \land (x,y) \in W_n^{-1}$ so $(y,x) \in W^{-1}_n \land (y,x) \in W_n$ so $(y,x) \in V_n$) and $V_n \in \mathcal{U}$ as entourages are filters so closed under finite intersections. As $V_n \subseteq W_n$ we have
$$V_n \subseteq U_n \text{ and } V_n = V_n^{-1} \text{ and } V_n \circ V_n \circ V_n \subseteq V_{n-1}\tag{4}$$
and $V_n$ is our required set in the recursion. The proof makes all intermediate steps explicit (which is needed when you start uniformity theory), later you just say "we need some entourage and we can assume it's symmetric and small enough etc." but the above are the steps behind such reasoning. Hope it clarifies things.
Comment: Why is it necessary to apply (c) twice? If we start from $V\circ V\subset V_{n-1}$, can we arrive at $V_n\circ V_n\subset V_{n-1}$
Comment: @JunkWarrior yes but the proof wants 3 : $V_n \circ V_n \circ V_n \subseteq V_{n-1}$ which we easily get from 4 copies.
Comment: Why does the proof use 3 if 2 also works?
Comment: @JunkWarrior read the rest of the proof. There must be a reason. See what the $V_n$ are used for.


Formal proof of limit

Question: By using $\epsilon-\delta$ definition, prove that $$\lim_{x\rightarrow1}\frac{3}{x^2}=3$$
Here is what I have tried.
$$|\frac{3}{x^2}-3|=3|\frac{1}{x^2}-1|=3|\frac{1-x^2}{x^2}|=3\frac{|x-1||x+1|}{x^2}$$
So I have problem with how to elimate the denominator.
Comment: You want to put a bound on the term $3|x+1|/x^2$ so you can then easily choose a $\delta$ given $\epsilon$. To do that, bound $x$ near $1$, for example $|x-1| < 1/2$. Then generate as crude upper bound for $3|x+1|/x^2$ as you like, so long as it's finite. Call it $M$. I.e., $|3/x^2 - 3| < M|x-1|$. Then given $\epsilon > 0$, choose $\delta = \min(1/2, \epsilon/M)$.
Answer: Given $\epsilon > 0$, choose $\delta = \text{min}\left(\frac{1}{2},\frac{\epsilon}{30}\right) \to |1|-|x| < |1-x|=|x-1| < \delta < \dfrac{1}{2} \to |x| > \dfrac{1}{2}$, and $|x+1| = |x-1+2| < |x-1|+|2| < \delta + 2 < \dfrac{1}{2} + 2 = \dfrac{5}{2} \to \left|\dfrac{3}{x^2} - 3\right| < 3\cdot |x-1|\cdot \dfrac{5}{2}\cdot \dfrac{1}{\left(\frac{1}{2}\right)^2}=30|x-1|< \epsilon$
Answer: Since $x$ is close to $1$ then $1/x^2 < 4$ and $|x+1|<3$.
Comment: Don't understand why would anybody down vote the reply, but I guess this forum is no different from other. At least they should point out the mistake. The OP asked how to eliminate denominator, which is exactly what I did.

Formal proof of limit


DOM GetElementByTagName

Question: I am attempting to collect all the H1 tags from a block of code.  I am attempting to use this within a class and im keep getting errors and im unsure if it is because of the insertion into the class or if im coding it wrong as i am new to DOM coding.
Error: Fatal error: Call to undefined method DOMDocument::getElementByTagName()  This error refers to:
$head1 = $this->doc->getElementByTagName('H1');

File calling the class
<?php
include('../includes/configuration.php');
include('../functions/class.php');

$reports=new Functions();

$sql = mysql_query("SELECT * FROM user_urls LIMIT 1") or die(mysql_error());
if (mysql_num_rows($sql) > 0){
    $recc = mysql_fetch_array($sql);
    $id=$recc['id'];
    $content=$recc['content'];

    $reports->content=$content;

    $test=$reports->collectHeadings();
    print_r($test);
}
?>

Class File
class Functions{
var $content;
var $doc;

public function collectHeadings(){
    $this->loadContent();
    $head1 = $this->doc->getElementByTagName('H1');
    return $head1;
}

public function loadContent(){
    $this->doc = new DOMDocument();
    $this->doc->loadHTML($this->content);
}
}

Comment: There is a DOMDocument class in php, which supports many of the XML selection and manipulation methods that the DOM accessible to javascript implements.
Comment: Am I lost here but getElementsByTagName, isnt that a javascript function? (Not php)(with a s)???
Answer: Ok it turns out you spelt it getElementByTagName, whereas the method is actually getElementsByTagName.
Comment: I thought so too, but OP is doing that inside `collectHeadings`
Comment: right you are. i'll see if i can figure anything else out and edit, otherwise will delete. thanks.
Comment: I am sort of new here, is it good practice to leave the incorrect part in your answer when you edit it (for posterity)? Or should I completely replace it?
Comment: :-) right you are about the typo. Doesn't matter editing it. In fact it is better to edit it, if you want to completely rewrite your answer (as is this case), so that you do not confuse those who read it..
Comment: Thank You.  I need to get to sleep.

DOM GetElementByTagName


How to show that a given vector field is not complete in $\mathbb{R}^2$

Question: Suppose $X=(y^2,x^2)$ is a vector field in $\mathbb{R}^2$, show that there is an integral curve starting from some point $(c,c)$ is not defined on all $\mathbb{R}$, that is, $X$ is not complete in $\mathbb{R}^2$.
Answer: Note that the integral curves of this vector field are the curves $y^3=x^3+c$. In particular, the point $(c,c)$ moves along the line $y=x$ with $dx/dt=x^2$. The solution with $x(0)=c$ is $x(t)=c/(1-ct)$, which is only defined up to $t=1/c$.
Comment: @vanabel: looking at the streamlines cannot tell you that the vector field is complete. The key point is not the geometry of the streamlines, but the magnitude of the vector field along these streamlines - to be complete the flow trajectories must be defined for all *time*, not all space/length parameter.
Comment: I almost reach this answer too. The question is
1. Only when $y[t]\neq0$, we can show that the integral curves is $y^3=x^3+c$, how about the case of $y=0$?
2. Although the curve $x(t)=c/(1-ct)$ has a  singular time at  $t=1/c$, but can we claim that the solution can not be extended to $R$?
Comment: There's no problem with $y=0$. Note that we can write the differential equation in the form $x^2\,dx-y^2\,dy=0$. For your second question, note that the point shoots off to  infinity (say, when $c>0$) as $t\uparrow 1/c$.
Comment: If rather, we consider the integral curve starting from $(x_0,y_0)$, where $x_0\neq y_0$, then similarly, we obtain in this case:
\begin{cases}
    x(t)=\frac{1}{1/x_0- t}\\
    y(t)=-\sqrt[3]{\left(1+\frac{1}{(x_0t-1)^3}\right)x_0^3-y_0^3}.
    \end{cases}
When $t\to 1/x_0$ (assume that $x_0\neq0$), we also have $x(t)\to\infty$, but it seems that it can be extended to $R$ by consider the Stream of vector field. see fig added in the original question.


Give an example of continuously differentiable function that satisfy some properties

Question: Can you give an example of continuously differentiable function that satisfy this properties:
Let $\{(a_i, b_i)\}_{i=1}^{\infty}$ be the family of open subintervals of $[0,1]$ with rationals endpoints. For each $i\geq 1$, let
$$g_i:[a_i,b_i]\to [0,1]$$
be a continuously differentiable function such that

$g_i(a_i)=1$, $g_i(b_i)=0$,
$\lim_{x\to a_i^+} g_i^{\prime}(x)=0$,
$\lim_{x\to b_i^-} g_i^{\prime}(x)=0$.

I have tried to make some examples, this is my attempt:

$g_i(x)=\frac{b_i-x}{b_i-a_i}, a_i\leq x \leq b_i$. But, this function not satisfy properties poin (3) and (4).
\begin{align*}
g_i(x)=\begin{cases}
1,& a_i\leq x < \frac{a_i+b_i}{2}\\
\frac{16x-4a_i-12b_i}{a_i-b_i},& \frac{a_i+b_i}{2}\leq x < \frac{a_i+3b_i}{4}\\
0, & \frac{a_i+3b_i}{4}\leq x \leq b_i
\end{cases}
\end{align*}
This function satisfies properties poin (1)-(4), but this is not continuously differentiable.

Finally, I got stuck on finding an example of that function.
Any helps will be appreciated.
Comment: The functions
$$g_i(x):=\cos^2{\pi(x-a_i)\over2(b_i-a_i)}\qquad(i\geq1)$$
would do. –  I think you have not properly described your problem, since you also talk about *one* function that should be constructed. Are you planning to concatenate the $g_i$ somehow?
Comment: Are your intervals disjoint?
Comment: @Kavi Rama Murthy I think yes, my intervals are disjoint..
Comment: @Christian Blatter Yes, I will concatenate the $g_i$ with $f_i$, where $f_i$ is defined by $$f_i(x)=\begin{cases} 1, xb_i \end{cases}$$, then I will show that $f_i$ is continuously differentiable on $[0,1]$. Okay, I'll try the function that you give.
Answer: Hint. There are 4 conditions so try a polynomial with 4 c0-efficients, i.e. a cubic $$g(x)=\frac {x-b}{a-b}\cdot (\,A(x-a)^2+B(x-a)+1\,).$$
Comment: Are A and B arbitrary constant? Or can I take for example : A=1, B=2?
Comment: @MathLearner. Compute what g(x) and g'(x) are when x=a  and when x=b, and compare those to Conditions  1.,2.,3. to find what A  and B must be.
Comment: oh I see.. thank you! I will try.


How to solve the following multiple linear regression problem?

Question: I have given function values say "$y$" which is dependent on $x$ and $\log(100-x)$, how shall I solve this problem using linear regression - as in I want my model to be like $$y = Ax + B\log(100-x).$$
I could do it by taking $x$ as one variable and $100-x$ as another, but is that wrong?
Is there any other way this could be done using multiple linear regression where $x$ and $\log(100-x)$ are taken as different variables?
Am I committing a mistake by taking $x$ and $\log(100-x)$ as different variables since they are dependent on each other?
How to solve using linear multiple linear regression in R?
Comment: You might be interested in http://stats.stackexchange.com/questions/148638.
Answer: If you really want to construct a model such as $y = A x + B \log(100 - x)$  (that is, you know that is how your model SHOULD perform in real life, e.g., based on some physical or biological or chemical arguments), then just do that by treating $x$ and $\log(100 - x)$ as your covariates and perform a linear regression to estimate the coefficients $A$ and $B$.
Answer: Linear regression can be used in some non linear regression problems if you define new variables that contains the non linearity.  You should do the linear regression $y=A X +B U$ , where $U = log(100-x)$. There is no mistake in doing that, you are searching a linear regression function adding a dimension to the problem.
For example, if you want to adjust the polynomial $Y=AX^2 +BX +C$, you should define a new variable $U = X^2$, and it isn't any mistake on doing that. It is a very common practice while doing regressions.


Can I safely wrap functions using this scheme?

Question: I'd like to wrap several fs functions so that each one of them will retry on error until success.
My purpose is to wrap those functions while leaving the rest of my code completely unchanged.
Here is my scheme:
First, I implement the following file, named fix.js:
const _fs = {};

module.exports = function(fs) {
    for (const funcName of ["readFileSync", "writeFileSync", "appendFileSync"]) {
        _fs[funcName] = fs[funcName];
        fs[funcName] = function(...args) {
            while (true) {
                try {
                    return _fs[funcName](...args);
                }
                catch (error) {
                    console.log(error.message);
                }
            }
        };
    }
};

Then, in my code, immediately after fs = require("fs"), I call require("./fix")(fs).
Is this scheme safer, or should I worry about any sort of undefined behavior?
For example, I am assuming that the _fs object in file fix.js will continue to "live" after the require("./fix") statement is executed, but I'm not so sure that this assumption is correct.
Answer: Fast answer is "Yes, is safe".
Long answer is "Yes, is safe but...". Explaining:
Is safe because it will work as you expect and will not break nothing. Until here, everything is fine.
The problem comes if the error you get is unsalvable until you manually do something. For example a "permissions error". The code will be looping forever until you solve that manually, also maybe clogging CPU or disk I/O, and is impossible to add small delays between retries without eating CPU for free. That's the problem of synchronous functions actually.
If you get the EBUSY problem you talked about in other post, it will eat one entire CPU in the loop and a lot of disk I/O operations until the file is not busy, so there are chances that will slow the operations that the other process is doing to the file. If you only have 1 core, the operations will slow a LOT. Is not optimal. If you have a complex situation, you must avoid sync fs functions. The best you can do now is to use fs non-blocking functions and wait a bit of time before the next check. Waiting a single tick can be really a change in optimization here. You can try to use async and await to keep the inline feeling, without callbacks, but free the event loop and not eat extra CPU and disk I/O.
By the way, those are extra details. In general is safe to wrap fs functions.
Comment: The "other process" is a process which I wish wasn't there. So there's no performance issue in my case (instead of my script failing, it will just do some printing until it can continue). Thank you so much!!!


How to learn to play bass guitar from chord sheets as a rhythm guitarist?

Question: I'm primarily a rhythm (acoustic) guitarist with a little bit of music theory. Mainly I play songs from a chord sheet in my church band, no score.
I'm interested to learn a bit of bass as I was given one but am unsure how to figure out what to play from a chord chart... I mean GGGG CCCC EEEE DDDD fits but that's like a rhythm guitarist just playing one downstroke per beat!
Comment: A Bass Teacher is excited about getting a new  student.  He learns all the notes on the E string in for his first lesson. Next week he comes in and the instructor shows him all of the notes on the A string. The third week comes, the teacher is waiting, but  he never shows up. Annoyed, he calls him to see where he is.  "Oh, sorry man, I got a gig...". Root, Fifth(up) or Fifth(down) & Octave are enough to get going.
Comment: That's... kinda what a lot of bass parts are like. If you can read guitar tab you can read bass tab. If you want to play along with chords then you either just play the root note of the chord (or lowest note for inversions or slash chords) or you have to make up an arpeggio or melody to go with the chords. Getting some bass tabs online for songs that you listen to often will probably be helpful in understanding. Contrast U2 with James Brown and you'll see bass has a wide range of ways to play it.
Comment: In most cases if you start on the root note of the chord (or bass note in inversions) and play the chord tones (three notes on major/minor chords four on 7ths, dim etc.). you will be playing something that works. Bass guitar is a rhythm instrument and the notes should fall in time with the  beat.
Comment: I suppose I feel a bit nervous of volunteering to fill in in our church (amateur) band one week with no gauge of my abilities. Is it fair to say that if I can keep the rhythm and keep it very simple, I am 'safe' not to ruin everything?
Answer: Remember that you're part of the rhythm section! Don't underestimate the responsibility that comes with playing a very simple line - even just roots - with even feel in a way that locks in with the drummer, fits the feel of the song, and drives it forward. Even in 4/4, just playing quarter notes won't always do the job (or if it does, your bandmates are a bit unadventurous when it comes to choosing songs...) and even parts that are just straight quarter notes have to be played with the right feel.
One thing that's a bit different to being a rhythm guitarist thrashing away is the importance of muting. Of course muting is important with all guitar styles, but with bass you need to take particular care to be (usually) playing one note at a time only, and to get the notes starting and stopping at the right time for the feel of the song. You also need to use muting to control the timbre of your bass - with a very simple bassline, I'm often using left hand muting to slightly dampen notes in the quieter passages before opening up for e.g. the later choruses.
As Rockin' says, you can experiment with branching out into chord tones and passing tones  - and there is a skill in doing that in a way that doesn't compromise the rhythmic foundation. Ultimately you can work up to how to construct walking basslines, though they won't fit with every style.
Try to come up with a little 'library' of simple bass riffs that you can play on each chord root involving fifths and octaves, thirds and sevenths (remembering that the intervals in the riff will need to be modified depending on the chord type.) To get some ideas listen to some different styles like straight pop and rock songs, punk, disco, techno, and hip-hop. Don't forget to move down from the root as well as just using the chord tones above.
If you are a guitarist already, it is true that you might not have a huge amount to learn in the 'what notes to play' department. But bass isn't just about that - there are a number of right-hand techniques to master if you wish, such as: playing with a pick; straightforward playing with fingers; 'fingerstyle funk' using multiple fingers to cross strings and throw in 'dead' and half-muted notes; using your thumb as Abraham Laboriel or Victor Wooten do; and, of course, the dreaded 'slap' (which doesn't have to mean sounding like Flea - it can be just subtly throwing a couple of slapped notes in for timbral interest.)
Comment: Great point about muting.  Particularly about the concept of playing notes how long they are supposed to be.  Note lengths can really change a groove.
Comment: I would also tend to agree that you don't *have* to play every style to become a master but as you've said, it can really help with the style that you want to play.  In particular, I would point out how much you can learn about the tone of the instrument by playing slap bass since it is so far removed from the normal finger style approach.
Comment: "not really a well-rounded bassist until you've mastered a number of right-hand styles" –perhaps, though many great bassist actually specialise completely in just _one_ of these styles and won't normally use anything else.
Comment: @leftaroundabout It's certainly true that many prominent bassists are famous for one style... and many of those are genuinely masters of just that one style, while others are more flexible than their best-known repertoire would suggest. There's also often a lot of respect given to the kind of 'session' bassist who isn't necessarily a household name but is often the inspiration behind a big hit, and they can often really turn their hand to anything. Even if you want to develop one distinctive style, learning a breadth of styles and appropriating the elements you like from each is one way to go.
Comment: The OP seemed to be asking partly about how to get a bit of variety into a 'playing for fun' situation though, which was where I was coming from.
Comment: Agreed. Just, it shouldn't be _necessary_ to use a whole lot of different techniques. In fact, many bassists who practise lots of different techniques can't do any of them _really well_, and as a result they either play only stuff where the various sound changes can barely distract from the basic thematic idealessness, or they play far too much stuff that does more harm than benefit, musically.
Comment: @leftaroundabout I'm probably a bit guilty of that myself! I guess there's a balance to be struck; without (as we were talking about elsewhere) having infinite time to practice, there's always something to be said for focusing on one thing that's really you; and there's also the "what should they know of Slap Bass, who only Slap bass know?" aspect (http://www.telelib.com/authors/K/KiplingRudyard/verse/volumeXI/englishflag.html)  in that sometimes influences from outside your style can actually help you define that style.
Comment: @leftaroundabout having decided that you're dead right - especially your last comment - I changed it :)
Answer: Generally speaking, the role of bass in most music is to add depth to the harmonic content and provide a connection between drums and pitched instruments.  There are a very, very large variety of ways to approach the bass, so if you're interested in becoming a bass player, as opposed to just playing the bass, then you will need to spend a good amount of time looking into the different styles and approaches for all of the genres that you are interested in playing.
One thing that is usually lost on a lot of guitar players is the feel needed when playing bass (as I mention above the difference between playing bass and being a bass player).  Bass is often thought to be easy by guitar players because it's like the same instrument but you only have to play one note at a time but that leaves out the nuance.  Tone is very important and a good bass player will not only know how to dial in all the knobs but how to attack the strings for the sound they need.  For instance, Jaco gets some of his tone from play close to the bridge, which will have a thinner tone and tighter sound.  Playing closer to the neck will give you a warmer, more rounded tone.  Getting in touch with this really helps.  As a bass player myself, I am just as often thinking about the tone when writing as I am the actual notes.  I've experienced really liking a part when played near the neck and thinking it was awful when played over the pickups or near the bridge (and vice versa).  The tone can completely change how the bass line is functioning or experienced.
The most basic approach is to play the root note of a given chord.  Different genres or songs within genres will call for a different approach for rhythms.  You can play big whole notes (or one note per chord), or consistent 1/4s, 1/8s, etc.  Once you start to explore syncopation, you will find a variety of ways to handle this as well.  You can follow the guitar/keyboard rhythms, follow the vocal rhythms, follow the drum beat, or have a rhythm of your own within the song to act against the other instruments.
For note choices, it's good to remember the basic function of the bass: to connect rhythm and harmony.  Many chord progressions (if not most) will have chords whose bass notes are not very close together interval-wise.  Many players will choose to find notes to connect bass notes that are not intervalically close to smooth out the motion from chord to chord.  One example of this is a "walking bass line", which consists mostly of small intervals (seconds and thirds) moving at a consistent pace, usually 1/4 notes.  This is the standard Jazz approach to bass but is also used in lots of other genres at different times, perhaps most commonly in Blues.
You will also find that 'root-5' bass lines are very common, with country and bluegrass probably being the most common place to find them in more modern music.  The root and 5th of a chord are the most 'solid' sounding chord tones and can be played fairly consonantly for just about any chord/chord progression.  Clearly this is a different approach than the small intervals found in a walking bass line, however, you will find that a similar effect of smoothing out the feeling of distance between notes will apply when moving from chord to chord.
From there you can get creative, as long as your band mates allow it... A lot of modern (pretty much 60s and beyond) bass lines are essentially a part of their own and help define the song itself, not just supporting the other instruments.  This is very common in Fusion and Funk, as well as some approaches to Rock, Soul and RnB.  It can really happen in any genre though, like "Kind of Blue" with the bass taking the melody.
If you're interested in checking out the full extent of bass possibilities, I would recommend Jaco Pastorius, Stanley Clarke, Victor Wooten, and Les Claypool (and there are a lot more).  Les Claypool is an interesting example due to his unique approach.  He functions as the main instrument in many of his songs, often fulfilling both the bass and harmony roles, but has his own style that is very aggressive, dissonant and unique.  It is also very interesting to listen to his compositions and notice when he is playing more standard bass lines and how he brings his unique flavor to those standard lines.
Hopefully this gets you off to a good start!  Happy Bass Tickling!!!
Comment: !! At the end of "Superbad", James Brown yells out, "BOOTSY! Lemmie hear ya!" He also can be heard saying, "C'mon Phelps! C'mon Phelps!" He's referring to Phelps "Catfish" Collins, Bootsy's brother, who was playing guitar.
Comment: Some additional names for your research: Stu(art) Hamm, Dave LaRue, Geddy Lee.
Comment: Bootsy Collins (James Brown), Christopher Wolstenholme (Muse), and of course Wilton Felder (Mowtown, including *I Want You Back*) are other names to look at.
Comment: Absolutely agree with those additional suggestions (can't believe Bootsy didn't come to mind for me in particular) but I would say Bootsy would be best connected with Parliament, the most funkenest of PFunks that ever funked this great earth.  I honestly didn't even know he had played with James Brown.


Horizontally and vertically align image in div

Question: I'm using Bootstrap and WordPress.
I've been researching how to horizontally and vertically align an image inside a div (classic problem, apparently). I used the answer to this question to vertically align my image: How to vertically align an image inside div
Now I need to horizontally align it. I know to do that, you normally add margin: 0 auto;
The problem is that the method that I followed uses margin:auto; and it undos the vertical align if I change it to margin:0 auto;
I started to make a JSFiddle of the problem, but I couldn't replicate it. So I think it's something in Bootstrap that is overriding it, but I'm not sure what.
Here is the basic code I'm using from the vertical align solution on the other stackoverflow question:
HTML

CSS
.container {
     position: relative;
     width: 100%;
     overflow: hidden;
}

.crop-featured-2 {
    height: 100px;
    width: 200px;
    position: relative;
    border: 1px solid red;
    padding: 5px;
    display:block;
}
.crop-featured-2 img {
    min-height: 100px;
    width:100%;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    border:0px;
    padding:0;
}

You can see the problem at http://ucaftercruz.com/upcoming/?page_id=30. It's the slider at the top and the problem is in the .carousel-inner div. Resize the browser to around 800px wide to be able to really see the issue.
Thanks so much in advance!
Comment: Hey, thanks misterManSam!! That actually eliminated my need to horizontally align the image in the div.
Comment: Are you saying it's the `carousel-indicators` div that you are having problem with?
Comment: No, it's the divs within .carousel-inner I'll update my question to clarify
Comment: I don't see a problem except that your images are jumping and the pager is not showing in different widths. Can you specify what exactly is your issue?
Comment: At browser width 800px, you can see that the images are aligned vertically in the middle of the div, but are anchored to the left. I would like them to be aligned vertically and horizontally in the middle.
Comment: I removed `width: 575px` on `.crop-featured-2` and it **stretches at all viewport widths**.
Comment: @Tara - It also fixes the slide indicators at all widths, nice touch
Answer: I had a look at your web page. I think the issue solves it self if you just remove the width rule from this selector:
.crop-featured-2 {
  height: 320px;
  width: 575px;
  position: relative;
}

instead use
.crop-featured-2 {
  height: 320px;
  position: relative;
}

Answer: Try this
.crop-featured-2 {
position: relative;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%);
}


Pegando valores de um for

Question: dúvida bem simples mesmo.
Tenho a seguinte lista:
fruits = {"apple":"123", "banana":"456", "cherry":"789"}
for fruit in fruits:
  print(fruit)

Como faço para no meu retorno apareça os números de cada?
Da forma que está o retorno é: apple, banana e cherry
mas preciso que o retorno seja: 123, 456, 789
Answer: Voce pode usar o valor que voce ja conseguiu extrair como chave no dicionario:
fruits = {"apple":"123", "banana":"456", "cherry":"789"}
for fruit in fruits:
  print(fruits[fruit])

ou pedir os valores do dicionario com values():
fruits = {"apple":"123", "banana":"456", "cherry":"789"}
for value in fruits.values():
  print(value)

Comment: Simples assim! Top! Obrigado
Answer: Você deve imprimir assim:
print(fruits[fruit])

Pegando valores de um for


Is there a name for the incomplete measure completing the anacrusis?

Question: In a piece that starts with an anacrusis/pickup measure and ends, or ends a repeating section, with a compensating incomplete measure, is there a term for that final measure?

incomplete measure can describe both the starting and ending measures.
anacrusis and pickup refers only to the starting measure.
??? refers only to the ending measure?
Answer: I don't think there is a specific term for it.  Cute options would be calling it a katacrusis or a dropoff bar, with a somewhat moderate chance of people getting your meaning.  They would also be sort-of candidates for an official term if such a one would often be asked for.  But I don't think that happens often enough that some term would have had a chance to be solidly established.
P.S.: I see that Wikipedia in its entry for "anacrusis" refers to the completing bar as "complement" which seems as nice a term as any.
Comment: Hehe, I like your inventions! It looks like *katacrusis* might already have a definition in ancient Greek or biblical scholarship, as a rhetorical "parenthetical aside": https://www.google.com/books/edition/Paul_Through_Mediterranean_Eyes/07QM_otHMp8C?hl=en&gbpv=1&dq=katacrusis&pg=PA70&printsec=frontcover https://www.inthebeginning.org/chiasmus/xfiles/john12_20-36.pdf
Answer: The simplest way to describe it would be to use its bar number. As for an actual name of this kind of incomplete bar; I don't know of one.
Incidentally, a pickup bar at the beginning of a piece is bar 0.
Comment: Never noticed 'bar 0' before - but it's right. Still learning...  +1.


Busca de termos "fora de ordem" no texto em PHP e MySQL

Question: Estou montando um simples sistema de busca para um banco de artigos de um evento científico estudantil. Adaptando códigos de alguns guias que achei na internet o sistema está funcionando todo certinho. O único problema é que ele só retorna resultados com palavras exatas.
Por exemplo: Se eu quiser retornar um artigo que fale sobre Organização da Informação e pesquisar por "Organização Informação", o sistema não retorna nada. O usuário precisa por na busca exatamente "Organização da Informação".
Encontrei um tópico aqui no Stack que me parece conter a solução do problema nas respostas, no entanto, não consegui aplicar no meu sistema. Segue o link: Busca com LIKE ou MATCH..AGAINST em duas colunas
Peço que analisem meu código e me auxiliem, se possível, em como encaixar as dicas no meu sistema ou se tiver um modo melhor de fazer, que por favor me deem uma luz.
Segue o código PHP que estou utilizando para a busca (Removi apenas os códigos relativos à paginação dos resultados):
<?php
// A busca
$busca = $_GET['consulta'];
$busca = mysql_real_escape_string($busca);
$sql = "SELECT * FROM `artigos` WHERE (`ativa` = 1) AND ((`titulo` LIKE '%".$busca."%') OR (`resumo` LIKE '%".$busca."%') OR ('%".$busca."%')) ORDER BY `grupo` DESC LIMIT ".$inicio.", ".$_BS['PorPagina'];

// Executa a consulta
$query = mysql_query($sql);

// Mostra resultados
echo "
";
while ($resultado = mysql_fetch_assoc($query)) {
$titulo = $resultado['titulo'];
$resumo = $resultado['resumo'];
$link = 'http://meusite.com.br/artigos/' . $resultado['link'];
echo "
";
echo ''.$titulo.'
';
echo "
";
echo '
'.$resumo.'
';
echo "
";
}
echo "
";

?>

Desde já, agradeço a ajuda.
Abraços!
Comment: Exatamente tens aqui a solução: http://pt.stackoverflow.com/a/13181/7210 onde estás a ter dificuldade.
Comment: Jorge, mencionei justamente este link na minha dúvida. O problema é que não funcionou. Utilizei da seguinte maneira: Substituí a string "$pesquisa = 'carro verde amassado ';" por "$pesquisa = $busca".
Comment: Esse link é o mesmo para o seu problema, quando vc implementou chegou a dar algum resultado?
Comment: Tentei trocar o AND por OR, mas nada. Continua apenas retornando os termos exatos. Se alguma palavra estiver entre eles, a busca não retorna nada.
Answer: O problema era apenas falta de conhecimento em PHP, mas após muitas tentativas modificando o código do link acima, consegui. Segue o resultado para que outros com a mesma dúvida consigam fazer.
<?php
// A busca
// Salva o que foi buscado em uma variável
$pesquisa = str_replace( array( ',', '.', '%', '-', '/', '\\' ),' ', $_GET['consulta'] );
// Usa a função mysql_real_escape_string() para evitar erros no MySQL
$pesquisa = mysql_real_escape_string($pesquisa);
$palavras = explode( ' ', $pesquisa ); // dividindo as palavras pelo espaço
$palavras = array_filter($palavras); // eliminando ítens vazios

// Monta a consulta
$sql = 'SELECT * FROM artigos ';
$cola = 'WHERE ';

//Aqui você pode juntar vários campos no concat.
$campo = 'CONCAT( titulo, " ", resumo)';

foreach ($palavras as $palavra) {
$palavra = trim($palavra); //Removendo espaços em branco
$palavra = mysql_real_escape_string($palavra); //Precisa da conexão com o banco!
$sql .= $cola.campo.' LIKE "%'.$palavra.'%" ';
$cola = 'AND ';
}
// Executa a consulta
$query = mysql_query($sql);

// Mostra resultados
echo "
";
while ($resultado = mysql_fetch_assoc($query)) {
$titulo = $resultado['titulo'];
$resumo = $resultado['resumo'];
$link = 'http://meusite.com.br/artigos/' . $resultado['link'];
echo "
";
echo ''.$titulo.'
';
echo "
";
echo '
'.$resumo.'
';
echo "
";
}
echo "
";

?>

Obrigado pela ajuda!
Abraços.


Finding the values of $x$ such that $[x^2]=[x]^2$ ($[\cdot]$ denotes the floor function)

Question: I was trying to find the values of $x$ that makes the equation $[x^2]=[x]^2$ true where $[\cdot]$ denotes the floor function. I tried doing the following:
Let $x=n+r$ where $n=[x]$ and $0\leq\ r<1$. Then $x^2=n^2+2nr+r^2$ which implies that $[x^2]=[n^2+2nr+r^2]=n^2+[2nr+r^2]=[x]^2=n^2$. Subtracting both sides of the equation by $n^2$ I obtained $[2nr+r^2]=0$ if and only if $0\leq\ 2nr+r^2<1$. I got stucked in here. Any suggestions or hints that can you give me?
Answer: Write $x=n+r$, where $n\in\mathbb{Z}$ and $0\le r\lt1$. Then we want
$$
\left\lfloor n^2+2nr+r^2\right\rfloor=\left\lfloor(n+r)^2\right\rfloor=\lfloor n+r\rfloor^2=n^2\tag1
$$
If $r=0$, then $(1)$ is true. Thus, we have any $x\in\mathbb{Z}$ is a solution.
Now, assume $0\lt r\lt1$. $(1)$ requires
$$
0\le2nr+r^2\lt1\tag2
$$
To satisfy the left-hand inequality of $(2)$, we need
$$
2n+r\ge0\tag3
$$
So we need $n\ge0$. To satisfy the right-hand inequality of $(2)$, we need
$$
0\lt r\lt-n+\sqrt{n^2+1}\tag4
$$
which is equivalent to
$$
n\lt x\lt\sqrt{n^2+1}\tag5
$$
Therefore, we get the complete solution set to be
$$
x\in\mathbb{Z}\cup\bigcup_{n=0}^\infty\left(n,\sqrt{n^2+1}\right)\tag6
$$
Comment: I really liked your solution! Thank you very much!
Comment: Can eq.6 be simplified to $$x\in\bigcup_{n=0}^\infty\bigg[n,\sqrt{n^2+1}\bigg)\tag6$$?
Comment: @AccidentalFourierTransform: that leaves out all the negative integers.
Comment: @robjohn Ah, right. Silly me.
Answer: $$0\leq\ 2nr+r^2<1$$
Solve$$ 2nr+r^2-1=0$$ for $r$ in terms of $n$.
$$ r=-n\pm \sqrt {n^2+1} $$
For $$-n- \sqrt {n^2+1} <r< -n+\sqrt {n^2+1}$$
We get $$0\leq\ 2nr+r^2<1$$
Since $r\ge 0$, we just need $$ r< -n+\sqrt {n^2+1}$$
For example if $n=10$, we have to have $r<\sqrt {101}-10 \approx 0.049875$
Comment: The inequality $0 \leqslant 2nr + r^2$ is not for free when $n < 0$, which makes the answer incomplete.
Answer: I'm not sure there is going to be a "clean" solution of this, you will have to consider various cases.

If $r=0$ the inequalities are clearly true.
If $r>0$ and $n<0$ then $2n\le-2$ so $2n+r<0$ so $2nr+r^2<0$ and there is no solution.
The remaining case is $r>0$ and $n\ge0$.  Then $0\le2nr+r^2$ is certainly true, so you have to solve $2nr+r^2<1$ to find $r$ in terms of $n$.

See if you can finish it from here.
Answer: I think that you have done almost everything. In your notation you have the following inequalities: $r>=0$, $r<1$, $r^2+2nr-1<0$. The last one gives $r<\sqrt{n^2+1}-n$. This gives possible values of $r$ for given $n>=0$. For negative $n$ your computation is not correct.


Representation of quaternion group over $\mathbb{C}$ and $\mathbb{R}$

Question: The quaternion group of order 8 has an irreducible two dimensional representation over $\mathbb{C}$ but how does one show that this representation cannot be defined over $\mathbb{R}$?
Comment: No, that's not right. The dihedral group of a square has a 2-dimensional irreducible representation over $\mathbb{C}$ which can be conjugated to be over $\mathbb{R}$.
Comment: Please don't give orders to the group (you are using the imperative mode). If you have a question, *ask*, don't *tell*.
Comment: I was wondering, if you know that quaternions already admits an 2x2 matrix representation over C, and had there been another 2x2 matrix representation over R, these two must be isomorphic. But that must mean then there's a (linear) isomorphic map $f: R \rightarrow C$. But that's impossible. Thanks for all the comments.
Answer: There are sophisticated ways you can do this, but I think its best to push it through in a straightforward way. Here are two approaches; I'm deliberately not giving the details because this is a good homework problem:
Algebraic: Let $C$ be the subgroup $\{ 1, i, -1, -i \}$ of the quaternions. Let $V$ be the real representation of $C$ where $i$ acts by $\left( \begin{smallmatrix} 0 & 1 \\ -1 & 0 \end{smallmatrix} \right)$.
Suppose that the two dimensional representation of the quaternions could be defined over $\mathbb{R}$. Show that the restriction of this representation to $C$ is isomorphic to $V$. In other words, you can always choose a basis where $i$ acts by $\left( \begin{smallmatrix} 0 & 1 \\ -1 & 0 \end{smallmatrix} \right)$. Now write down the equations $ij=ji^3$ and $j^2=i^2$ and try to solve them
Geometric: Any representation on $\mathbb{R}^2$ can be conjugated to preserve the standard inner product; meaning that the action is by rotations and reflections. A case by case analysis should show you pretty quickly that you can't find rotations and reflections of the plane that give an action of the quaternions.
Comment: Many thanks. I still had to use the geometric argument for the algebraic one: that there is a conjugation that takes $\rho(i)$ to $\left( \begin{smallmatrix} 0 & 1 \\ -1 & 0 \end{smallmatrix} \right)$, where $\rho: Q \rightarrow M_{2}(\mathbb{R}^2)$ is a representation of Q over the real.


google analytic doesn't display current user

Question: I am implementing Google analytic for my app tracking in android. i follow Google document which is mention in that document but it is not display any active user in analytic dashboard.
My code is in Application Class
private static GoogleAnalytics sAnalytics;
private static Tracker sTracker;

sAnalytics = GoogleAnalytics.getInstance(this);

synchronized public Tracker getDefaultTracker() {
    // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
    if (sTracker == null) {
        sTracker = sAnalytics.newTracker(R.xml.global_tracker);
    }

    return sTracker;
}

In Activity
  Tracker mTracker;
  MyAppplication application = (MyAppplication) getApplication();
    mTracker = application.getDefaultTracker();

    mTracker.setScreenName("User Profile");
    mTracker.send(new HitBuilders.ScreenViewBuilder().build());

In Manifest File
 <receiver android:name="com.google.android.gms.analytics.AnalyticsReceiver"
        android:enabled="true">
        <intent-filter>
            <action android:name="com.google.android.gms.analytics.ANALYTICS_DISPATCH" />
        </intent-filter>
    </receiver>
    <service android:name="com.google.android.gms.analytics.AnalyticsService"
        android:enabled="true"
        android:exported="false"/>

    <receiver android:name="com.google.android.gms.analytics.CampaignTrackingReceiver"
        android:exported="true">
        <intent-filter>
            <action android:name="com.android.vending.INSTALL_REFERRER" />
        </intent-filter>
    </receiver>
    <service android:name="com.google.android.gms.analytics.CampaignTrackingService" />

in global_tracker
 <string name="ga_trackingId" translatable="false">UA-10*******-1</string>

use This Gradel dependence
compile 'com.google.android.gms:play-services-analytics:10.2.4'

Comment: please edit with your complete code so other's can easily help you.
Answer: google anyltic is working only for old user.For new user you must have to add firbase.


What are the advantages/ disadvantages of 4 or 6 string basses for a beginner?

Question: I've been researching the topic and I like the 6 string bass, but looking on YouTube, Yousician, and other resources, most guides on how to play the bass are for 4 strings. Even Yousician, which I was going to use, only has guides for 4 string bass. Should I just get a 4 string or get the 6 string and not use the additional 2 strings when using guides for 4 strings?
In other words, as a beginner, would one be better served starting with a 4 or 6 string bass, considering the disadvantages/advantages of one to the other?
EDIT: Well thank you for the responses, it seems I'm either going to get a 4 string and learn by tabs, which seems to be plenty of videos and web sites with tabs. Or, I'm going to get the 6 string and screw tabs and learn bass by notes, which I do know how to read. Most sheet music isn't really free, though I could sit there and convert 4 string tabs into 6 string tabs. For me, it's not a bad idea, I'll have to dabble with that while I wait for the 1st, when I get paid. This may help me decide.
Comment: I agree that this kind of question can't really be answered, though IMO it _could_ make a good question if you rephrase it to something like "what are possible disadvantages in learning electric bass on a bass with more than 4 strings"?
Comment: It will depend also on the type of music and band you're looking to play (in). I find in most cicumstances, a 5 string is sufficient, as 6 takes you into guitar territory, although you can play chords on one. But that's taking the guitarists job. I recommend 5 string!
Comment: A 4-string bass does everything a bass SHOULD do.  A 6-string encourages you to over-play.   But I don't suppose that will stop you wanting one :-)
Answer: Consider your level of playing

but looking on YouTube and yousician and stuff most guides on how to play the bass are all 4 string guides

The fact you have stated you're looking at Yousician and YouTube suggests that you're new to playing bass. When you're in the early in the stages in learning the last thing you want is added complexity.  Is it really necessary to have two extra strings when you're not going to play them?

should I just get a 4 string or get the 6 string and not use the 2 strings when using guides for 4 strings?

As a beginner, a 6 string bass is going to make finding your strings with your plucking hand more difficult. This is because you will have two extra strings to work-around and you should be watching your fretting hand and not your plucking hand. The neck is also going to be significantly wider, which initially, is going to make it more difficult to get your hands around comfortably. And finally, the scale length is likely to be longer. A longer scale length will mean that the frets on your bass will be further apart, requiring you to stretch your fingers further.
Edit: Tim has noted that some basses can have smaller dimensions and still have more strings. This will, overall, make the bass much easier to play. However, because of the smaller dimensions, the strings will be closer to together and may make it a little more difficult to change strings.
What is appealing about 6 string bass?

I've been researching the topic and I like the 6 string bass

What is the primary reason for wanting to obtain a 6 string bass?

Do you find the range of notes available on a 4 string bass is not enough?
Do you want to be able play notes at a lower and higher frequency than E standard without retuning?
Are there arpeggios or melodies you cannot reproduce easily on a 4 string or 5 string bass?

If you cannot answer 'yes' to any of these questions then I think that 6 string bass is not for you; not at this stage in your playing.
Have you considered 5 string bass?
If you must absolutely have an extended range bass, could you compromise for 5 strings instead? There are some advantages of playing a 5 string bass that you shouldn't overlook. A 5 string bass will give you a slightly extended range with access to more notes at a lower frequency, just like the 6 string. There is only 1 additional string to learn rather than 2 with a slightly narrower neck than a 6 string. This allows for easier playability.
And, of course, similar disadvantages from the 6 string bass. There is still the issue of a longer scale-length to deal with because of the lower tuned B string. Again, this means frets will be further apart and requires more stretching or travel.
Think about long term progression
If this is your first bass, I would strongly recommend that you start with 4 strings. You should make learning as smooth a process as possible, and unfortunately, starting with an extended range bass does not aide that.
Hopefully, you will be playing bass guitar for many years to come so consider that this may not be the last bass you decide to purchase. As your ability progresses and you have a better fluency with playing, you can begin to progress onto basses with more strings. You may find that in the future you prefer only extended range, but remember it takes a more advanced level of playing to make full use of the extra strings.
Attempting to learn 6 strings while learning essential techniques will slow down your initial progress

tho i could sit there convert 4 string tabs into 6 string tabs for me

The time spent working how to move notes from a 4 string to 6 string will detract from the time you can spend on fundamentals. No real conversion is needed from 4 string to 6 string, since all the strings on the 4 string tab will exist on your 6 string bass.

or im going to get the 6 string and screw tabs and learn bass by notes

There is value on learning how to move notes to the extra strings, e.g. F# on the low E string to an F# on the low B string. But, this should not be your focus at a beginner stage of playing.
Ideally, you want to have full attention on basic scales, note positions, reading tablature, without having to think about those two extra strings. Once you have learnt many of these skills, it's very little work to apply this to a bass with more strings afterwards.
You can still learn all of these techniques on a 6 string bass, but it will leave more questions in your mind every time you learn a new topic. How do play this scale on my other two strings?. Asking questions is always good, but I worry this will be a little overwhelming for you without someone to guide you through the process of what to learn first, and what to leave for later.
Are extended range basses all complexity?
Definitely not! They're fun, expressive, and very versatile. But owning an extended range bass before you can play is like exploring a new country without a map or guide. I think you should see 6 string bass as long term goal, and begin working towards it at a steady pace, starting with 4 strings.
I wish you luck on your musical endeavours.
Comment: The scale length of a 5 string is usually no different from a 4 string, as the B string is a heavier gauge. There are 5 strings with the same neck width as 4 strings - the strings are closer to each other. One of the main advantages of a 5 string is that there is no need to go down 5 frets (for example) to play a V under the I you play on the E string - just play that new note on the B string. Otherwise, good points. Interesting to look at an 8 string bass - F# - F...
Comment: I have several basses.All the SGC Nanyo basses are the same at 34",be it 4 string,  5 string, fretless, and I have a BEAD strung at the same. My Steinberger fretless 5 is also 34".  I have had a 5 string with 4 string dimensions, but the gaps between strings were too tight for my playing. I use 40/60/80/100/120 on most of my 5 strings, with no tuning, intonation or playing problems. The low B is always a thicker string, so the tension is similar on each string. Perhaps I'm just lucky! Certainly think I am,  playing Bass Collection (the older ones).
Comment: Thanks for the feedback Tim. However, I seem to find 5 string has a longer scale length. For example Squier V has a 34.0" scale length vs. the 4 string variant that has a 30.0" scale length. The nut is at a length of 51mm on the 5 string vs. 38.1mm on the 4 string thus also making the neck wider. The longer scale length helps increase the tension in the strings and therefore maintains a more consistent tension in lower tuned strings. Dingwall basses, for example, are designed with fanned frets purposely to combat issues of scale length in extended range basses.
Comment: Certainly different to what I'm used to. =) I think you are lucky with your collection. Interesting to know these basses have similar dimensions despite having different numbers of strings.
Comment: It seems obvious, really. If the scale length is shorter all round, the strings need to be of a different gauge, as in thicker, to retain the same tension. Or, use lower tension, typically -10-15%, which gives more of a thud, if that's what you want.  So I wonder what gauge the low B might be on a short scale bass of normal tension.
Comment: Certainly a good question, the tone would be interesting to note with the gauge. I do agree with your statement of tension vs. scale length. I personally prefer a fanned fret, the tension and gauge are well balanced across the strings.
Comment: Never tried it, but the theory is good. As I said, mine are all intonated well, so there's no tuning issues anyway. With the ratios I use, the tensions match well.
Answer: Partly addressing the edit - if you read bass dots, then this is a better way forward.There's a lot of work out there for the quite rare beast - a bass reader! Sad to say, a lot of the tabs are inaccurate, don't help with timing ( unless the dots are there too), and are one individual's version of where and what to play. On bass, there are usually two or three different places (positions) to play lines, and the choice should be that of the player, not the tabber.
If you go for a 6 string, then initially, disregard the outer two strings, and get used to playing and reading the standard notes on standard strings. Then it's a matter of adapting by moving up 5 frets and down one string for the same. For me, the B string is somewhere to go under the E, rather than play actual lower notes than E most of the time.
More often than not, the top C doesn't get used except for chords and popping, so I still advocate a 5 string. Another thought is that if you're visiting without your bass, finding a 6 string to use won't be easy.
However, as a raw beginner, I'd advocate starting with a 'simple' 4 string, finding your way round that for a couple of years, by which time you'll be ready for the next stage, and will also have made decisions on what else you need in a new bass - no. of strings, string spacings, pups, scale length, active/passive, etc.
Answer: I would agree. Start with a 4 string gain traction in the basics then move up later. I own a four string and a six string bass. There are advantages and disadvantages to both. I personally got a six string for the tonal range more than anything. They are very fun to play but also more difficult. My six string has less space in between strings than my four string (even though they are sister units made both made by Schecter) This "small" difference greatly changes the dynamics of playing technique "basics" like slapping and muting. Because of these considerations sometimes I prefer my four string over my six string and vice versa.
Comment: My 6 string is by Alden, and the spacing is only a little different from my 5s. D>G at the bridge is 16mm on Bass Collection against 15mm on Alden.On the 4s it's 17mm. So not a huge difference, and one of the reasons I went for Alden 6 string.
Answer: I'd say go for the 6-stringed. From what I can tell, having more range is nothing but an advantage when it comes to it all, playing, composing, improvising...
The techniques are practically the same, finger and pick playing, you can actually incorporate more techniques, two-handed tapping, hybrid picking (?), higher (relatively to the 4-stringed) pitched melodies, extended chords... There's also the advantage of going vertically (i.e., up and down the strings instead of horizontally through the neck) to play wide intervals.
The disadvantages I can see, would be the wider neck, making the playing uncomfortable, but I believe you eventually get used to it as with every other instrument, and the price of the extra strings for when you want to change them. Other than that, my vote goes to the 6 stringed.
Comment: Perhaps for an intermediate player with some experience, but the OP appears to be a beginner. Otherwise he wouldn't be posing the question.
Comment: agree, seeing anything other than what you have in your hands on-screen or on-page is just confusing.  His progress needs to be incremental and smooth, with no bumps in the road that cannot be got over with a little practice, rather than find _youre on the wrong strings again_
Answer: I started with an Ibanez SR-1200 Premium bass in 2014 as a beginner. After sitting in the corner of a coffee shop for two years learning to play the instrument and learning to read standard notation bass clef via a Beatles book of transcriptions for their songs. In 2016, I started playing Contemporary Christian music for a church. After about a year of working from Praise Charts, Tabs and piano sheet music, I found that the piano bass lines were often written out of range of my four string bass. So, I elected to purchase a 6 string bass. The 6 string bass solved the problem of sheet music piano bass lines written below low E for my four string bass. Also, the 6 string gives me more access to notes from the same position on the fret board making it easier for me to focus on the sheet music rather than my finger placement on the fret board unless changing position. True, there is the contention that one should master a four string bass before moving to a 5 or 6 string bass but my move to a 6 string was out of necessity rather than want. Moreover, in the absence of a guitarist, I was often asked to play chords. The 6 string bass with C, G, D and A strings work rather well for playing chords.  My four string bass works well for music written in the 50s, 60s and 70s but with the introduction of ERB basses in the late 70s and beyond and bass parts written for 5 and 6 string basses for many songs, my Ibanez GVB 36 6 string became the best choice for me and my applications.  Choosing the right bass for the job required dictated the choice for playing a 6 string bass.
Comment: "the problem of sheet music piano bass lines written below low E for my four string bass" – you realise that piano as-written in bass clef is actually an octave higher than when a bass player plays from the same sheet? (Some people say "bass is a tranposing instrument", IMO it makes more sense to just say it usually plays in octave-bass clef, rather than regular bass clef.) Yes, piano has a range of notes that goes below bass, but they're quite seldom used, more as a thundrous effect than as an actual bass part. So, realistically speaking you can cover piano-bass parts just fine with 4str.
Comment: 6 string gives me more access to notes from the same position on the fret board – that's a valid point, but I'd argue it's probably not a good idea to make this a habit. Playing on high strings in low position tends to give an overly bright, thin sound that doesn't really have the spectral characteristics a bass part needs to fit well in a band mix; playing on low strings in high position tends to produce a muddy, unresponsive sound. IOW, for best sound you should probably often switch position regardless.
Comment: This leaves the point about ERB. Sure! It's great to be not limited by the 4-string's limit, but be able to produce some _really_ earth-shaking notes when you want. Arguably a fifth string is the way to go for Yet, it's not the _only_ way. Octaver effects can get you lower than any bass you can reasonably play with your hands. IMHO they actually do a _better_ job at it, in particular the analogue ones, because the electronic synthesized signal is not subject to the inharmonicity and transient-response problems you get with very low plucked strings. ...
Comment: ... Also, such effects make it a conscious decision when to make musical use of the subbass jackhammer. All too many 5-string players use their power too often and in ways that doesn't benefit the music. – This one is definitely a matter of taste though.


Is "$ax+b$" group amenable?

Question: Is the so-called "$ax+b$ group" (the group of affine maps on $\mathbb R$) amenable?
One reprersentation for $ax+b$ group is the set of 2 by 2 matrices for form
$$\begin{bmatrix}x & y \\0 & 1\end{bmatrix};\,\,\,x,y\in\mathbb R, x>0$$ endowed with the usual multiplication. The left Haar measure is given by $\frac{dxdy}{x^2}$
Answer: It is solvable, thus it is amenable.
https://en.wikipedia.org/wiki/Amenable_group#Examples
Answer: Every solvable group is amenable - for a proof see Theorem $4.6.3$ here. Note that the affine group $Aff(\mathbb{R}^n)$ is solvable if and only if $n=1$ (which is the group above). For a discrete subgroup $\Gamma$ in $Aff(\mathbb{R}^n)$ are equivalent: $(1)$ $\Gamma$ is amenable, $(2)$ $\Gamma$ is virtually solvable.

Is "$ax+b$" group amenable?


java.lang.NumberFormatException in db2jcc.jar

Question: I am hitting this exception in a Java application. I extract the JAR file and try to check what is the root cause of this, but I fail to get it, because I can't debug on it.
I have the source JAR file, but every time I attach it in my workspace, it still shows me "the source attachment does not contain the source for the file ad.class".
The following is the error stack:
<code>Caused by: java.lang.NumberFormatException: For input string: "A"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:59)
    at java.lang.Integer.parseInt(Integer.java:460)
    at java.lang.Integer.parseInt(Integer.java:510)
    at com.ibm.db2.jcc.c.ad.<init>(ad.java:80)
    at com.ibm.db2.jcc.b.f.<init>(f.java:55)
    at com.ibm.db2.jcc.b.b.ib(b.java:1760)
    at com.ibm.db2.jcc.c.p.a(p.java:2490)
    at com.ibm.db2.jcc.b.b.a(b.java:470)
    at com.ibm.db2.jcc.b.b.<init>(b.java:264)
    at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:163)
    at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
    at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:294)
    at org.apache.commons.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1247)
    at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1221)
    at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880)
    at org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider.getConnection(InjectedDataSourceConnectionProvider.java:46)
    at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:111)
    at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2101)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1325)
    at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
    at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:132)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:225)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:308)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
    ... 12 more
</code>
How can I debug this?
Comment: The message is clear. A is not a Number
Comment: If you Need more help, you have to add your code
Comment: @Jens, As you can see, all the class in the error stack is open source class file, not the code that I write. Thus, I am not sure why it throw this error.
Comment: no prior research about the exception
Comment: @Jens I found the solution and post the solution at below.
Comment: @Ravi I found the solution and post the solution at below.
Answer: I think, the problem lies where you passed DBCP connection pool values - min count, max count etc. You have passed "A" in place of an integer.
Please check your spring context file or properties file where you provided database connection parameters.
Answer: I found the solution, its cause by the db2jcc.jar is too old for the db2 version. I found the solution here and manage to fix it.
https://www-01.ibm.com/support/docview.wss?uid=swg21625290
Comment: It was because you have not mentioned the prior research and effort you have put in and the things you have tried, additionally after you have researched and found the solution upvoting it.
Answer: "A" is not a number you're probably trying to insert a string value into a variable or array that only allows numbers, make sure you declare your variables and arrays correctly. If your put atention in the error you are tryingtry put a String value into integer. I hope you can solved your error with my help pass a good day


Unable to access site after deleting an entry from the database

Question: The entry views.view.media from the config table in phpmyadmin was accidentally deleted. When visiting the site it giving the error The website encountered an unexpected error. Please try again later. I'm unable to login or access any page. What can I do to fix this problem? It's drupal 8.2.4.
Comment: Can you go to your server's error log and check what it says there? Or just get the entry back from a backup.
Comment: I didn't had access to the server log but I was able to fix the issue by updating drupal core.
Answer: You can try installing the views in a similar configuration to your current site, on another install, and then copy that row from the database in that install to your current site.
Comment: I was able to fix the issue by updating drupal core.


Retornar propriedade num relacionamento ManyToMany

Question: Tenho um relacionamento ManyToMany entre 2 classes. Campannha e Empresa. A Annotation da classe Campanha está assim:
/**
 * @ORM\ManyToMany( targetEntity="JN\Entity\Empresas\Empresa")
 * @ORM\JoinTable(
 *      name="campanhas_empresas",
 *      joinColumns={
 *              @ORM\JoinColumn(
 *              name="campanhaId",
 *              referencedColumnName="id")},
 *      inverseJoinColumns={
 *              @ORM\JoinColumn(
 *              name="empresaId",
 *              referencedColumnName="id")}
 * )
 **/
private $empresas;
/**
 * @return mixed
 */
public function getEmpresas()
{
    return $this->empresas;
}

/**
 * @param mixed $empresas
 */
public function addEmpresas($empresas)
{
    $this->empresas->add($empresas); //ArrayCollection
}

A questão é que quando eu acesso o método GetEmpresas, volta como resultado isto:
object(Doctrine\ORM\PersistentCollection)[609]
  private 'snapshot' =>
array (size=3)
  0 =>
object(Proxy\__CG__\JN\Entity\Empresas\Empresa)[644]
  public '__initializer__' =>
object(Closure)[392]
  public '__cloner__' =>
object(Closure)[393]
  public '__isInitialized__' => boolean false
  private 'id' (JN\Entity\Empresas\Empresa) => string '3' (length=1)
  private 'tipo_cadastro' (JN\Entity\Empresas\Empresa) => null
  private 'idMatriz' (JN\Entity\Empresas\Empresa) => null
  private 'razao_nome' (JN\Entity\Empresas\Empresa) => null
  private 'fantasia_contato' (JN\Entity\Empresas\Empresa) => null
  private 'categoria' (JN\Entity\Empresas\Empresa) => null
  private 'campanhas' (JN\Entity\Empresas\Empresa) => null

Que está completamente correto. Eu queria saber como eu faço para acessar, por exemplo, o id ou qualquer outra propriedade acima. Tentei fazendo um for-each assim:
foreach($this->getEmpresas()->toArray() as $item){
        $emp .= $item->getId.' - '.$item->getRazaoNome.'; ';
    }

Mas deu o seguinte erro:

Notice: Undefined property: Proxy__CG__\JN\Entity\Empresas\Empresa::$getId

Obrigado
Answer: O próprio erro já te deu a resposta.

Notice: Undefined property: Proxy__CG__\JN\Entity\Empresas\Empresa::$getId

No seguinte bloco, você chama a propriedade getId, que não existe.
foreach ($this->getEmpresas()->toArray() as $item) {
    $emp .= $item->getId.' - '.$item->getRazaoNome.'; ';
}

Acredito que seja apenas um erro de digitação, faltando os parênteses do método getId():
foreach ($this->getEmpresas()->toArray() as $item) {
    $emp .= $item->getId() . ' - ' . $item->getRazaoNome . '; ';
}

Comment: Foi o sono. Realmente após algumas boas horas de programação eu já não analisava mais corretamente. Assim que acordei eu consegui ver o erro. Obrigado


Link to image uploaded for a Post object in ActiveAdmin?

Question: I can successfully create a Post in ActiveAdmin, and I can successfully upload an image to go with it. Now, my issue is that while the "Post#show" action will tell me the path to the image, I would like that to also be a link. I'm including a picture of what I'm talking about for clarity below.

In the very bottom field, it's clear that the image was successfully uploaded. ActiveAdmin even tells me where to find it, but the path it gives me is simple text. I would like it to be a link to that picture instead. Is there an easy _path function that I'm forgetting?
Answer: The simplest way to achieve that is cutomizing your show page for Post model. It is also described in the official ActiveAdmin document of Customizing the Show Screen
ActiveAdmin.register Post do
  show do
    attributes_table_for resource do
      row :id
      row :title
      row :slug
      # ...
      row :image do
        span link_to(resource.image.path, resource.image)
        span img(src: resource.image.path)
      end
    end
  end
end

The other approach I think is possible is to extend ActiveAdmin's default AttributesTable component to handle your image attribute.
Comment: Thats a huge help! Thank you! Now, do you know how I can add a path to the image directly under the image as it is shown? I know I can do it by adding another `row :image` underneath the block, but is there a way to do it within the `row :image do...end` block?
Comment: @elersong Updated my answer that adds a span to show the image. Please refer http://www.activeadmin.info/docs/12-arbre-components.html#text_node


What is $P(A\mid B)(C\mid D)$? Is this the same as $P(A\mid B) \times P(C\mid D)$?

Question: I'm curious about the general case but also need to understand if $P(A|B)(C|D)$ is the same as $P(A|B) \times P(C|D).$
In equation (7), it states

Is this the same as $P(u|f,s) \times P(f|s)$ ?

The article is available at https://mechanicaldesign.asmedigitalcollection.asme.org/article.aspx?articleid=2297650
Answer: Your understanding is correct. I think there is a typo in the original source. In general it holds that
\begin{equation}
p(x,y|z) =  p(x|y,z) p(y|z)
\end{equation}
and therefore,
\begin{equation}
p(x|z) = \sum_y p(x,y|z) = \sum_y p(x|y,z) p(y|z)
\end{equation}
Comment: Thank you for helping.
Comment: You are welcome. Please accept the answer if you found it helpful.


System.IO.FileNotFoundException : Could not find file

Question: I am using file upload control. But when I try to read uploaded file, it's looking for folder where project is created and giving error.
The code for this
 <input type="file" name="file" />
 <button type="submit">Upload File</button>

and
[HttpPost]
    public IActionResult UploadFile(IFormFile file)
    {
        string FileName = file.FileName;
        if (file != null && file.Length != 0)
        {
            FileStream fileStream = new FileStream(FileName, FileMode.Open);
            using (StreamReader streamReader = new StreamReader(fileStream))
            {
                string line = streamReader.ReadLine();
            }

        }
    }

Comment: You should use the [CopyTo(Stream)](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.iformfile.copyto?view=aspnetcore-2.0#Microsoft_AspNetCore_Http_IFormFile_CopyTo_System_IO_Stream_) method instead of using the `FileName` property Or better use the [OpenReadStream()](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.iformfile.openreadstream?view=aspnetcore-2.0#Microsoft_AspNetCore_Http_IFormFile_OpenReadStream) method to get a readable stream.
Answer: Use enctype = "multipart/form-data" inside your form action. You can use razor @using (Html.BeginForm())
@using (Html.BeginForm("UploadFile", "YourController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" />
    <button type="submit">Submit</button>
}

Source code view sample here
And inside your controller, you can use a method controller like this:
public async Task<IActionResult> UploadFile(IFormFile file)
{
    var uploadPath = Path.Combine(hostingEnv.WebRootPath, "uploadsfolder");

    using (var fileStream = new FileStream(Path.Combine(uploadPath, file.FileName), FileMode.Create))
    {
        await file.CopyToAsync(fileStream);
    }
    return RedirectToAction("Index");
 }

Source code controller sample here
This should work properly
Answer: If you are trying to read the uploaded file using stream, you can use the following,
        string result;
        if (file != null && file.Length != 0)
        {
            using (var reader = new StreamReader(file.OpenReadStream()))
            {
               result = reader.ReadToEnd();
            }
        }

Or, if you are trying to save the uploaded file somewhere in the server then you should use the CopyTo method like below example,
        var destinationPath= Path.GetTempFileName(); //Change this line to point to your actual destination
        using (var stream = new FileStream(destinationPath, FileMode.Create))
        {
            await formFile.CopyToAsync(stream);
        }


Como sobrescrever o método OnItemSelected de um Spinner?

Question: estou tentando sobrescrever o método OnItemSelected de um Spinner no meu Fragment, da mesma forma que fiz com o Button, mas não está dando certo... Como eu conseguiria o mesmo resultado?
Dentro do OnCreate, o bloco comentado funciona perfeitamente, mas quero dar uma "limpada" nele, pois tenho mais de um spinner neste layout e desse jeito está ficando bem poluído.
Outra dúvida: Se possível, alguém poderia me explicar como funciona esse método OnNothingSelected e como utilizá-lo de forma mais eficaz?
Na expressão "if (itemSelecionado != ". . .")" é porquê o primeiro elemento do meu spinner é uma string com ". . .", pra não deixar nenhum item já selecionado de começo, tem alguma forma melhor de resolver isso?
Meu código é o seguinte:
Vetarano2.kt
com.mtsa.escudeiro_rpghelper.fragments

import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.Button
import android.widget.Spinner
import android.widget.Toast
import com.mtsa.escudeiro_rpghelper.R

class Veterano2 : Fragment(), View.OnClickListener, AdapterView.OnItemSelectedListener {

    private lateinit var spinner: Spinner
    private lateinit var button: Button

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {

        // Inflate the layout for this fragment
        val fragView = inflater.inflate(R.layout.fragment_veterano2, container, false)

        initViews(fragView)
        initListeners()

        // SPINNER RAÇA
        /*
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                val selecionado = parent.getItemAtPosition(position) as String
                Toast.makeText(context, "Opção escolhida: $selecionado", Toast.LENGTH_SHORT).show()
            }
            override fun onNothingSelected(parent: AdapterView<*>) {}
        }
        */

        return fragView
    }

    private fun initViews(v: View) {
        spinner = v.findViewById(R.id.spinner2)
        button = v.findViewById(R.id.button2)
    }

    private fun initListeners() {
        spinner.onItemSelectedListener = this
        button.setOnClickListener(this)
    }

    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        when (view?.id) {
            R.id.spinner2 -> {
                val selecionado = parent?.getItemAtPosition(position) as String
                Toast.makeText(context, "Opção escolhida: $selecionado", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onNothingSelected(parent: AdapterView<*>?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.button2 -> {
                Toast.makeText(context, "SALVAR", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

fragment_veterano2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="64dp">

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/array_example"
        android:spinnerMode="dropdown" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="64dp"
        android:text="Button" />
</LinearLayout>

arrays_diversos.xml
<resources>
    <string-array name="array_example">
        <item>AAAAA</item>
        <item>BBBBB</item>
        <item>CCCCC</item>
        <item>DDDDD</item>
        <item>EEEEE</item>
    </string-array>
</resources>

Obrigado, desde já!
EDIT: Editei o código para melhor visualização, mas o problema persiste
Answer: Sobre como setar o onItemSelectedListener(this) (como se fosse no java) você faz como o código comentado onItemSelectedListener = this
Comment: Fiz a alteração, mas ainda assim não funcionou...
Answer: Descobri meu erro, era apenas falta de atenção... não tenho que chamar na view e sim no parent u_u
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        when (parent?.id) {
            R.id.spinner2 -> {
                val selecionado = parent.getItemAtPosition(position) as String
                Toast.makeText(context, "Opção escolhida: $selecionado", Toast.LENGTH_SHORT).show()
            }
        }
}


Date of birth saving to MYSQL DB with timestamp or date column type

Question: i am using MYSQL database and would like to know which of this is a good practice.
way 1 - use column type in DB as timestamp. i.e will contain values like 2012-11-13 00:00:00
way 2 - use column as Date. i.e will contain values like 2012-11-13 in the database.
The question here is, to Store DOB. do we really need timestamp as the column type ? also the time section (00:00:00) is not required for a DOB in my opinion.
Should it be timestamp because, then we can store the value as hidden so no body can view it even when somebody see the DB. to view, we must use strtotime() available in php.
Please let me know the correct way to store DOB in database.
Comment: There are v rare cases we need time for DOB ,usually `date` type is enough for the needs
Comment: If you need only **date** of birth and not **date and time** of birth in your application then the answer is obvious - use `DATE` as data type. The only good practice is not using a data type with time part when you don't actually use it because querying **properly** against `timestamp`/`datetime` is much trickier in most cases.
Comment: it really depends what your application needs.. if your application (Frontend) is not concerned of `timestamp` then go for only `date` as a good database admin try to keep the data which is needed if time is not needed then why to use `timestamp`
Comment: i suppose that you need 'timestamp' in the case that two or more persons born same date and you want to know who is older/younger. if you need this use 'timestamp' else 'date'
Answer: I recommend to use DATE.
TIMESTAMP has a range of '1970-01-01 00:00:01' to '2038-01-19 03:14:07' (UTC), so it doesn't fit for DOB in most cases.
It is possible to use DATETIME, but you should ask yourself: do you want users to fill in time of birth? If not - use DATE.
Usually it's not a big deal, but you may also consider required storage:
<code>DATE:      3 bytes
TIMESTAMP: 4 bytes
DATETIME:  8 bytes
</code>


Loop e como ativar edição para escrever em javascript

Question: Estou fazendo um bloco de notas e estou com algumas duvidas, eu quero que quando se faça um click no botão "adicionar" adicione mais um postit para isso, posso usar o loop ou tenho que usar outro comando?
No botão com a caneta quando fizer click ativa a edição para começar a escrever eu não faço a menor ideia do que usar para fazer isso, alguem poderia me recomendar um site ou me explicar como posso fazer isso?
Na tag do textarea aquela parte amarela so se move na vertical como posso fazer para se mover tambem na horizontal.

var btn = document.querySelector(".btn-apagar");
btn.addEventListener("click", remove);
var textotitle = document.querySelector(".tarefas");

function remove() {
  textotitle.parentNode.removeChild(textotitle);
}
* {
  margin: 0;
  padding: 0;
  line-height: 1;
  box-sizing: border-box;
  /* outline: 1px solid tomato; */
  border-collapse: collapse;
  border-spacing: 0;
  font-family: Arial, Helvetica, sans-serif;
}

.emcima {
  max-width: 64rem;
  margin: 0 auto;
}

.espaco {
  margin-top: 20px;
}

body {
  background-color: #eaeaea;
  padding: 20px;
}

button {
  cursor: pointer;
}

h1 {
  font-size: 18px;
  text-transform: uppercase;
}

ul {
  padding: 0;
  list-style: none;
}

.A {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 2px solid #aaa;
}

.titulo {
  background-color: transparent;
  border: 0;
  border-bottom: 1px solid #666;
  margin-right: 10px;
  display: inline;
}

.btn-mais {
  border: 0;
  color: #111111;
  padding: 5px 10px;
  border: 1px solid #999999;
  border-radius: 6px;
  display: inline-block;
}

header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.tarefa {
  background-color: yellow;
  padding: 10px;
  max-width: 300px;
}

.btn-escrever,
.btn-apagar {
  border: 0;
  background-color: transparent;
  padding: 3px 5px;
}

textarea {
  width: 100%;
  background-color: transparent;
  border: 0;
}

Tarefas

    <button type="button" class="btn-mais">Adicionar</button>

          <input type="text" class="titulo" placeholder="Título">
          <button type="button" class="btn-escrever">✒</button>
          <button type="button" class="btn-apagar">✂</button>

        <textarea name="" placeholder="Texto da tarefa" class='texto'></textarea>

Answer: fiz uma coisa rápida aqui. Em relação ao botão adicionar, creio que é só fazer com que o Javascript adicione tags do post it. O problema eu acho é em relação ao espaço, aconselho usar o Bootstrap em relação a isto. Na caneta, eu fiz da seguinte forma:
Coloquei um display: none; para o usuário não poder escrever. Em seguida, configurei o botão de adicionar. Assim que o usuário clicar no botão, irá aparecer o input e o textarea para ele poder escrever. Também removi o display: inline; da sua class .titulo.
HTML:
<button type="button" onclick="aparecer()" class="btn-escrever">✒</button>

CSS:
.titulo {
  background-color: transparent;
  border: 0;
  border-bottom: 1px solid #666;
  margin-right: 10px;
}

.titulo, .texto {
  display: none;
}

JAVASCRIPT:
function aparecer() {
  document.querySelector('.titulo').style.display = "block";
  document.querySelector('.texto').style.display = "block";
}

Em relação ao tamanho do textarea, ele está aumentando para a horizontal sim. O que não está aumentando é a cor, pois ele não tem. A cor amarela é da class .tarefa. Para resolver isto, basta remover o background-color: transparent; do textarea e colocar a cor que preferir.


How do I display a field twice in a node's display?

Question: In my full node display I want to show the same field twice, in a different mode each time.
Specifically, I have a collection of images, I want one up top and the rest below in my already existing gallery view of the node. What I don't know how to do is to show the field for my image twice in a single node display. Is there a module that will allow me to do this with a minimum of fuss?
Comment: check this https://drupal.org/node/1059636 and http://drupal.stackexchange.com/questions/42061/render-or-print-image-in-a-drupal-7-node-tpl
Answer: Should be pretty easy if you use Display suite:
Add a dynamic field (admin/structure/ds/fields/manage_ctools) and select the entity type (node).

Your new field should be in the manage display tab of the entity type selected, activate it (put it in the section you want).
Click on the gear icon and then 'select content'

Then drill down in the options (node -> the field you would like to duplicate)

If you don't use display suite just print that field in a tpl.php file.
Comment: I've added screenshots, sorry they are in french :)
Comment: You lost me after selecting the `Node` checkbox.
Comment: I created the field and I think I correctly referenced the entity, but I can't find it to insert it in `admin/structure/types/manage/mynodetype/display`
Comment: The screenshots are a big help. And once upon a time, I could read French too. I can't seem to find the dynamic field in the `Manage Display` tab of the node editor.
Comment: Sorry mate, can't really help you more than this
Comment: You need to do the following to see the field in the display.

"Select A Layout" in the display for the content type and click save. Once you do that, the custom field you created will show up, as will the buttons that will allow you to create more custom fields directly from that page.

https://www.drupal.org/node/1162240#comment-7519979
Comment: Also make sure Display Suite Extras and Display Suite UI modules are enabled.
Answer: If you don't use Display suite for the given view mode, you can use https://www.drupal.org/project/entdispfieldui instead. (in combination with a number of other modules)

Choose a way to integrate 3rd party composer libraries: Either using composer_manager, or using https://github.com/drupal-composer/drupal-project
Download and enable entdispfieldui and required modules, including cfrplugindiscovery (shipped with cfr).
Scroll to the bottom of the view mode configuration page, create a new entdisp field, save.
Move the newly created entdisp field up to the place where you want it.
Configure the entdisp field as "Field with formatter", choose the field + formatter you like.
Alternatively, choose "Image with processor" or "Images" (for multiple-value), then choose the image field as the source.

I have a collection of images, I want one up top and the rest below in my already existing gallery view of the node.

This complicates the matter a bit. I am not sure if the usual formatter settings allow to specify which field items to display (e.g. only the first item, or all except the first). Something like this can be achieved with new custom renderkit components, but it depends a bit on your exact requirements.


Python Datetime Formatted as "1/1/1990"

Question: In python how would I format the date as 1/1/1990?

dayToday = datetime.date(1990,1,1)
  print dayToday

This returns 1990-01-01, but I want it to look like 1/1/1990. (Jan 1 1990)
Comment: @MattBall Not a duplicate if OP cares about leading `0`.
Comment: that is how sane people store their dates. :)
Comment: @mgilson Combined, it's a duplicate, but I'm not sure it's applicable when neither of those answers OP separately on both how to format from a date, and to fix leading `0`. Flag it if you feel like it.
Answer: Try to look into python datetime.strftime
dayToday = datetime.date(1990,1,1)
print dayToday.strftime('%Y/%m/%d')
>>> 1990/01/01
print dayToday.strftime('%Y/%b/%d')
>>> 1990/Jan/01

Answer: Use the datetime.strftime function with an appropriate format string:
>>> now = datetime.datetime.now()
>>> print now.strftime('%Y/%m/%d')
2013/04/19

Comment: Not the format OP asked for. Both regarding leading `0` and order of dates.
Answer: Others have showed how to get the output 1990/01/01, but assuming you don't want the leading zeros in there, the only way that I know of to do it is to do the string formatting yourself:
>>> '{dt.year}/{dt.month}/{dt.day}'.format(dt = dt.datetime.now())
'2013/4/19'

Answer: With the correct format and a without leading 0:
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%-m/%-d/%Y")
'4/19/2013'

Reported to only work for Linux, but I haven't tested anything else personally.
Tested and working for 2.7.3 and 3.2.3 on Linux x64.
Comment: Are you sure?  This gives me:  `'-m/-d/2013'`.  Maybe platform specific?  (I'm using OS-X)
Comment: @mgilson It seems it's a Linux-only.
Comment: Tested on my linux machine and it works there.  Which makes me feel good.  I was trying stuff like this before I finally came up with the answer I did and none of it worked.  Now I know why :)

Python Datetime Formatted as "1/1/1990"


Open Python IDLE in current virtual environment

Question: Using the Windows command line, how can I open a Python file inside the current virtual environment that I am in?
For example, say I'm in my virtual environment:
<code>(env) C:\MyFolder>
</code>
and then I want to open my Python file:
<code>(env) C:\MyFolder>mypythonfile.py
</code>
The .py file will open in IDLE but not inside the (env) environment
Comment: You have to open it with python, it can't open without any program. So type python mypythonfile.py.
Comment: When I enter `file.py` in Command Prompt, it runs the file rather than opening it in an IDLE editor.  Maybe you customized your file associations.  If `python` runs some version of 3.x, `python -m idlelib file.py` will open it in an IDLE editor, and I would expect the same within (env).
Answer: To achieve this via 3 steps:
Suppose that you are using windows system and have open a cmd window.

Activate your virtual environment:
venv/Scripts/activate  (venv is the path of your virtual environemnt)

You could use this command "where python" to check if your virtual environment is activated. If success, it should point to your virtual environment path at the first line.

Launch idle within your virtual environment:
python -m idlelib.idle

A IDLE window should be popped up. You can check if this is within the virtual environment by import a package only installed in the virtual environment but not in the local python.

Now from the idle open the file that you want to edit:
Click 'File - Open' in sequence, and then choose the file.

Now you can just try to press 'F5', you will see this file would be run in the virtual idle.


Minimize $\int_0^1 A(x)dx$ given $\int_0^1 \frac{dx}{A(x)}\le \text{constant}$

Question: The following problem is derived from a Finite element problem.
We have a beam which is subject tot a constant axial force. With out loss of generality the beam can have a variable section area $A(x)$. The beam cannot exceed a certain strain value, that is, it cannot be shorten by more than a given percentage. We want the beam to be with the smallest possible volume.
I have no idea how to approach the following optimization problem. Let $Volume=\int_a^bA(x)dx$. The constraint is given by $\int_a^b \frac{1}{A(x)}dx\leq const$.
Hence:
 $$\min_{A} \{Volume\} \\S.T. \int_a^b \frac{1}{A(x)}dx\leq const$$

How do I approach such a problem if at all possible?
If not, is there a way to solve this, given the relaxation of $A(x)$ being a polynomial function lower than the 4th (inertia momentum) degree?
Comment: Hunch: You're going to need to massage your constraint, maybe something like this: $\int_a^b\left[\operatorname{Const}-\frac{1}{A(x)}\right]\,dx\ge 0,$ then combine it with the minimization integral using a Lagrange multiplier.
Answer: This is not a general approach, but it will lead you to the final answer quickly.
Let's say $\int_a^b \frac{dx}{A} \le K$ for some given constant $K$, then by Cauchy Schwarz
$$K \int_a^b A(x) dx \ge \int_a^b \frac{dx}{A(x)} \int_a^b A(x) dx \stackrel{CS}{\ge} \left(\int_a^b dx\right)^2 = (b-a)^2$$
This  leads to following lower bound for the integral $$\int_a^b A(x) dx \ge \frac{(b-a)^2}{K}$$
Since this lower bound is achieved by the constant function $A(x) = \frac{b-a}{K}$, the minimum volume is $\frac{(b-a)^2}{K}$.

For a general approach, you need to set this up as a calculus of variation problem with constraint.
The constrainted Lagrange has the form
$$\mathcal{L}(x) = A(x) + \lambda\left(\frac{1}{A(x)} - k\right)$$
for unknown constant $\lambda$ and $k$.
You proceed to solve the associated Euler-Lagrange equation
$$\frac{\partial \mathcal{L}}{\partial A} - \frac{d}{dx}\left(\frac{\partial \mathcal{L}}{\partial A'}\right) = 0$$
In this case, the EL-equation tell us
$$1 - \frac{\lambda}{A(x)^2} = 0$$
This means the solution which minimize the functional $\int_a^b A(x) dx$ subject to constraint $\int_a^b \left( \frac{1}{A(x)}  - k\right) dx =  0$ is probably a constant function. Finally, you need to verify by suitable choice of constant value of $A(x)$, you will get the actual minimum.
To make this precise, it probably take one or two chapters from a book. I will just stop here.
Answer: First I will show that any minimum value of the integral you are considering can be attained by a constant function $A(x).$ Then, once you assume $A(x)$ is constant, the answer falls into your lap.
For the sake of simplicity, I will assume that we are integrating over the interval $[0,1]$ instead of $[a,b]$. I will also assume that $A(x)\le 1$ for all $x\in [0,1]$, which I think is a reasonable assumption because "beams" are typically longer than they are thick.
So, to restate the question, we want to find a function $A(x)$ that minimizes
$$I=\int_0^1 A(x)dx$$
with the constraint that
$$\int_0^1 \frac{dx}{A(x)}\le C$$
where $C$ is some given constant.
To solve this problem, we will make use of the following fact, which can be verified using integration by substitution: if $f$ is an integrable function on $[0,1]$, then
$$\int_0^1 f(x)dx=\int_0^1 \frac{f(\frac{x}{2})+f(\frac{x+1}{2})}{2}dx$$
Now suppose that $A_m(x)$ is a "well-behaved" function that minimizes $I$. Then, by the above identity, $I$ takes on the same value if we use the function
$$\frac{A_m(\frac{x}{2})+A_m(\frac{x+1}{2})}{2}$$
instead. Further, notice that
$$A_m(x)\le 1 \implies \frac{2}{A_m(\frac{x}{2})+A_m(\frac{x+1}{2})}\le \frac{1}{2} \bigg(\frac{1}{A_m(\frac{x}{2})}+\frac{1}{A_m(\frac{x+1}{2})}\bigg)$$
Which implies that
$$\int_0^1 \frac{2dx}{A_m(\frac{x}{2})+A_m(\frac{x+1}{2})}\le \int_0^1 \frac{dx}{A_m(x)}\le C$$
This is all that we need! This demonstrates that if $A_m(x)$ is a "minimizing function," then the function
$$\frac{A_m(\frac{x}{2})+A_m(\frac{x+1}{2})}{2}$$
is also a "minimizing function." If we repeat the same process with this function, we see that
$$\frac{A_m(\frac{x}{4})+A_m(\frac{x+1}{4})+A_m(\frac{x+2}{4})+A_m(\frac{x+3}{4})}{4}$$
is also a "minimizing function." In fact, repeating this process infinitely many times shows that the constant function function
$$\int_0^1 A_m(t)dt$$
is also a "minimizing function." This proves that for any function minimizing the given integral, there exists a constant function that also minimizes it; for this reason, you may assume that your function $A(x)$ is constant.
So let $A(x)=A$ be constant. Then we have
$$\int_0^1 \frac{dx}{A}=\frac{1}{A}\le C$$
and so $A\ge 1/C$, implying that $I\ge 1/C$ and $I=1/C$ is the minimum value of your integral. Done!