How do I prove these three statements true/false?

Question: I am still being taught maths at school, so all these fancy symbols like $\sum$ I have no idea about (although writing it out through mathjax, I think it possibly means the "sum" of something) but I believe to have made three potential discoveries of always finding a prime number:
$1. \qquad (2n + 1)^2 - 2 = p$
$2. \qquad n^3 - (n - 1)^3 = p$
$3. \qquad \text{The first number after $(2n)^2$ to have the number $7$ as its last digit is always prime.}$
I do not know if these are facts, but I do not know how to prove if any of these are true or false.

My Attempt:
$$(a + b)^2 = (a + b)(a + b) = a^2 + ab + ba + b^2 = a^2 + b^2 + 2ab \tag1$$
$$\implies (2n + 1)^2 = (2n)^2 + 1^2 + 2\times 2n\times 1 = 4n^2 + 4n + 1$$
$$\implies (2n + 1)^2 - 2 = 4n^2 + 4n + 1 - 2 = 4n^2 + 4n - 1= p$$
$$\implies 4n^2 + 4n - 1 - p = 4n^2 + 4n - (1 + p) = 0$$
$$\therefore n = \frac{-4 \pm \sqrt{16 - 16(1 + p)}}{8}$$
This is where I get stuck because any prime number must be greater than $1$ which implies that we will be square rooting a negative number in the numerator of the above fraction. Doing a little bit of research, the square root of a negative number is not "real" so how can there be real solutions for $n$ such that $(2n + 1)^2 - 2 = p?$ For example, $(2\times3 + 1)^2 - 2 = 47$ which is a prime number. I cannot see if I am doing something wrong here. Is this a contradiction of some sort?
$$(a - b)^3 = (a - b)(a - b)(a - b) = \cdots = a^3 - 3a^2b + 3ab^2 - b^3\tag2$$
$$\implies (n - 1)^3 = n^3 - 3\times n^2\times1 + 3\times n\times1^2 - 1^3 = n^3 - 3n^2 + 3n - 1$$
$$\implies n^3 - (n^3 - 3n^2 + 3n - 1) = n^3 - n^3 + 3n^2 - 3n + 1 = 3n^2 - 3n + 1 = p$$
$$\implies 3n^2 - 3n + (1 - p) = 0$$
$$\therefore n = \frac{3 \pm \sqrt {9 - 12(1 - p)}}{6}$$
Since $(1 - p) < 0$ then this implies that $12(1 - p) < 0$ and so we will be square rooting a positive number in the numerator of the above fraction because:
$$\forall (x, y) \in \mathbb{Z}, \ x - (-y) = x + y > 0 : x = 9\land 12\mid y$$
But I am unsure that I completed this problem correctly because I used the same steps of working out compared to $(1)$, however I cannot find a problem here. For example:
$$(\pm 3)^3 - 2^3 = 19 \qquad \text{ and } \qquad \pm 3 = \frac{3 \pm \sqrt {9 - 12(1 - 19)}}{6}$$
But as for $(3)$, I do not know where to begin. Could somebody please help me and show me step by step how to prove any one of these statements true or false? You do not have to prove all three statements true or false, but if you wish to do so, it would be much appreciated. I tried solving for $n$ via the quadratic formula, and completing the square just gave me a simplified fraction for $n$ and nothing more. If you are willing to use other mathematical techniques of solving for $n$, please be clear and try not to skip too many steps in the process. Thank you in advance.

Edit: Can I just say, this was my first question on the MSE and it said "be clear" and "be specific" and things like that, so I tried to make this question as understandable as possible, and for my first question, I got +10 which is AMAZING! Thank you so much all of you people for helping me with this. Your answers and explanations were very clear and helped me have a further understanding of these problems, and now I can use other methods of solving problems like these (or perhaps simply trial and error). I absolutely love this community even if some math questions are WAY beyond my years! Once again, thank you so much! :)
Comment: A suggestion:  in testing forms like this, you need to look at a lot of examples, not just the first two or three.  There are a lot of small primes so if you only look at small numbers you get a distorted view of things.
Comment: Note:  it's not too hard to prove that there is no non-constant polynomial $p(n)$ with integer coefficients that only takes prime values.  Worth doing as an exercise.
Comment: For examples like the last one you can construct counterexamples as follows - since the final digit is controlled, take $n$ a multiple of $5$ so that $(2n)^2$ ends in a zero - then you know that "last digit $7$" means adding $7$. Then if $(2n)^2$ is a multiple of $7$ the sum will have a factor equal to $7$ and won't be prime. So $n$ a multiple of $35$ will provide counterexamples. This strategy of knowing some part of the result (like the last digit), identifying a divisor, and then controlling the bit you don't know about so that it shares the same divisor is useful to know.
Comment: @AndrewTawfeek  Well, $\mathbb Z \to \mathbb Z$ will do.  It's a divisibility claim, not a statement about positivity.
Comment: Sorry, are you saying that $(2n+1)^2-2$ is always prime?  But $11^2-2$ isn't.
Comment: @lulu Regarding the polynonial, $p: \mathbb N \to \mathbb N$, correct?
Comment: @AndrewTawfeek  Historical trivia:  Pretty sure this was first shown by Goldbach.  In any case, it's old.  And it's worth mentioning Euler's example $n^2+n+41$ which gives primes for $n\in \{0,1,\cdots, 40\}$.
Comment: @lulu I'll give the problem you offered a shot. And thats interesting! I don't know much about Goldbach admittingly -- I'm currently reading through *Men of Mathematics* and don't believe he's included. Also, thats definitely a formula worth remembing, thanks for bringing it up. :)
Comment: any non-constant polynomial can't always be prime.
Comment: To prove any of them false it suffices to find a single counter-example. For 1. take n=5 (or n=8). For 2. take n=6 (or n=9). For 3 take n=6 (or n=9).  There is no known simple formula for producing primes in spite of thousands of years of study.
Comment: I think your solutions of the quadratic equations are wrong. $4n^2 + 4n - 1= p$ is satisfied by $n=1$ and $p=7$ , but $n = \frac{-4 \pm \sqrt{16 - 16(1 + p)}}{8}$ isn't
Comment: Thank you all for your comments. Lucky I'm not one of those guys that cannot take constructive criticism, but a mathematician must be prepared for feedback like this :)
Answer: For the first proposition $n=5$ is a counterexample.
$$(2\cdot 5 +1)^2 -2 = 7 \cdot 17$$
For the second proposition, $n=6$ is a counterexample.
$$6^3-(6-1)^3=7\cdot 13$$
For the last proposition, $n=6$ is a counterexample.
$$(2\cdot 6)^2=144 \text { and } 147=3\cdot 7^2$$
Comment: @user477343 On the note of proving things like this though, I highly recommend reading up on a method of proof called *induction*. Good try though!
Comment: Well, if you don't bound n>1, 2 can be contradicted with n=1.
Comment: Oh, sorry about that. I must have overlooked that. I mean, $7\times17 = 119$ which looks like a prime number....yeah perhaps I need to test just a little bit more...
Comment: @user477343 Please see my edit for the remaining propositions.
Comment: Ok thank you for those.
Comment: @AndrewTawfeek thanks for that. I will look into it :) And also, it seems like every counter example is divisible by 7.
Comment: @user477343 No divisible by $7$ is not necessary, for example for 1, $n=11$ gives $527=17\times 31$. For 2, $n=8$ gives $169=13^2$. For 3, $n=9$ gives $327=3\times 109$.
Comment: @EspeciallyLime I know $7$ wasn't necessary, I was just lazy. Turned on my calculator and put $f(x)=\frac{(2x + 1)^2 - 2}{7}$ then scrolled through the table to spot integers. Factors of $7$ are easy to overlook so figured its worth a shot. For the final proposition though, it just happened to have a factor of $7$.
Answer: You can disprove such a statement by finding a counterexample.

For small values of $n$ you can do this manually. There are at least 2 counterexamples for $n\le 10$ for each of your claims.
Your claims are wrong for at least 50% of all $n\le100$. For larger $n$ these values increase. So if you select an arbitrary two digit number you have at least 50% chance to find a counterexample. You can use Wolfram Alpha to check if a number is a prime number.
To check a larger range of values you can write a program, e.g. in Python or Mathematica.
Comment: Yes I have heard of Mathematica whilst browsing on this site, but thank you for this. How do they put it? "I give you a (+1)" :)
Answer: Disproving by simple counterexample is the right approach.
In your (1), the quadratic formula result has a sign error.  It should be $\sqrt{16+16(1+p)}$, not $16-16(1+p)$.
Building solutions using the quadratic formula requires a lot of steps where there can be errors, so you should always test the result with a simple case, e.g. plug $n=1$ into (1), get $p=7$, and see if those values solve your quadratic.
Comment: Welcome to MSE. Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: Ok I will fix my error. Thank you. And by the way, even though you have not used mathjax, I still understand your comment so thank you. +1


Xamarin Forms Switch toggles block ui

Question: I currently trying to implement two linked Switch element.
When one is toggled the other is untoggled.
But when my event is triggered, the clicked Switch do not finish is toggled.
The XAML :
<StackLayout Orientation="Horizontal" HorizontalOptions="CenterAndExpand">
                    <Switch x:Name="WomanGenderSwitch" IsToggled="true"  Toggled="HandleWomanToggled" Scale="0.5">
                    </Switch>

                    <Switch x:Name="ManGenderSwitch" Toggled="HandleManToggled" Scale="0.5">
                    </Switch>

                </StackLayout>

Code Behind :
void HandleManToggled(object sender, Xamarin.Forms.ToggledEventArgs e)
        {
            var s = sender as Switch;
            if (s.IsToggled)
                WomanGenderSwitch.IsToggled = false;
            else
                WomanGenderSwitch.IsToggled = false;
        }

  void HandleWomanToggled(object sender, Xamarin.Forms.ToggledEventArgs e)
    {
        var s = sender as Switch;
        if (s.IsToggled)
            ManGenderSwitch.IsToggled = false;
        else
            ManGenderSwitch.IsToggled = false;
    }

Comment: can you also put _HandleWomanToggled_ event handler code ?
Comment: @ParsaKarami done :)
Comment: so why you need `if (s.IsToggled)` statement when if true or false the code runs `ManGenderSwitch.IsToggled = false;`?
Comment: @AkashKava Is not appropriated comment. If i'm not using MVVM is because i'm not able to use it according to specification
Answer: You can re-use the same Handler for both Switches and since toggling the other Switch will cause its handler to be invoked you need to disable it otherwise you end up with a non-ending event ripple:
XAML:
<StackLayout Orientation="Horizontal" HorizontalOptions="CenterAndExpand">
    <Switch x:Name="WomanGenderSwitch" IsToggled="true"  Toggled="HandleToggled" Scale="0.5" />

    <Switch x:Name="ManGenderSwitch" Toggled="HandleToggled" Scale="0.5" />

</StackLayout>

Remove/Re-add handler to break event chain:
void HandleToggled(object sender, Xamarin.Forms.ToggledEventArgs e)
{
    var aSwitch = ((sender == WomanGenderSwitch) ? ManGenderSwitch : WomanGenderSwitch);
    aSwitch.Toggled -= HandleToggled;
    aSwitch.IsToggled = !aSwitch.IsToggled;
    aSwitch.Toggled += HandleToggled;
}

Or using a flag to break the event chain:
bool busy;
void HandleToggled(object sender, Xamarin.Forms.ToggledEventArgs e)
{
    if (busy == true) return;
    busy = true;
    var aSwitch = ((sender == WomanGenderSwitch) ? ManGenderSwitch : WomanGenderSwitch);
    aSwitch.IsToggled = !aSwitch.IsToggled;
    busy = false;
}

Comment: I will try this and mark as answer if it will work :)
Answer: As Parsa said, your code does the same think regardless of IsToggled.
Try something like this:
void HandleManToggled(object sender, Xamarin.Forms.ToggledEventArgs e)
        {
            var s = sender as Switch;
            if (s !=  null)
            {
                WomanGenderSwitch.IsToggled = s.IsToggled == false;
            }
        }

  void HandleWomanToggled(object sender, Xamarin.Forms.ToggledEventArgs e)
    {
        var s = sender as Switch;
        if (s !=  null)
        {
            ManGenderSwitch.IsToggled = s.IsToggled == false;
        }
    }

Comment: You can not do that as you will end up with a non-ending event chain, you have to break the event chain somehow (removing the handler temporarily or use a flag to break the chain)

Xamarin Forms Switch toggles block ui


Altered Dorian scale ( Misheberak scale or Ukrainian Dorian scale)

Question: First of all, thanks to everyone for this great web site .
I have a question about Altered Dorian scale (Misheberak scale,Ukrainian Dorian scale)

C Altered Dorian Scale :   C D Eb F# G A Bb.
A Altered Dorian Scale :   A B C D# E F# G.

But i cant find scales for other keys on internet.
Could someone write me  how would be this scales ,

B Altered Dorian Scale = ?
C# Altered Dorian Scale = ?
D Altered Dorian Scale = ?
D# Altered Dorian Scale = ?
E Altered Dorian Scale = ?
F Altered Dorian Scale = ?
F# Altered Dorian Scale = ?
G Altered Dorian Scale = ?
G# Altered Dorian Scale = ?

Thanks you so much , i'll so glad
I just searched scales for scary and dark composing.  Altered Dorian Scale ( Misheberak scale or Ukrainian Dorian scale) is really good for my hears to compose.
Answer: The C and A Altered Dorian scales you show, are simply Dorian Modes with fourth degrees raised by a Semitone. So, to work out the Altered Dorians starting on the other pitches: firstly, work out the Dorian modes starting on each of these pitches; secondly, raise the fourth degree of each of these modes by a semitone.
There are two easy ways to work out the Dorian Mode (or scale) starting on any particular pitch:

use the notes of the Major scale (and so, major key signature) two semitones below the root of your Dorian. For instance, B Dorian has the same notes as A Major, as A is two semitones lower than B (B-Bb-A). A Major has a key signature of three sharps: F#, C# and G#. So the notes of A Major are A-B-C#-D-E-F#-G#. These notes, starting on B, give B Dorian: B-C#-D-E-F#-G#-A. If you then raise the fourth degree by a semitone, you get your Altered Dorian: B-C#-D-E#-F#-G#-A.
follow the pattern of T-S-T-T-T-S-T between consecutive degrees of the mode (scale), where T is a Tone (equal to two semitones) and S is a Semitone. To give another example, E Dorian has: E-F#-G-A-B-C#-D, as E-F# is a tone, F#-G is a semitone, and so on. Again, you then raise the fourth degree to get your Altered Dorian: E-F#-G-A#-B-C#-D.

EDIT: Here are each of the scales you asked for...

B Altered Dorian: B-C#-D-E#-F#-G#-A
C# Altered Dorian: C#-D#-E-Fx-G#-A#-B
(Fx is F Double Sharp, so this scale would be better spelled as
Db Altered Dorian: Db-Eb-Fb-G-Ab-Bb-Cb)
D Altered Dorian: D-E-F-G#-A-B-C
D# Altered Dorian: D#-E#-F#-Gx-A#-B#-C# (this would be better spelled as Eb Altered Dorian: Eb-F-Gb-A-Bb-C-Db)
E Altered Dorian: E-F#-G-A#-B-C#-D
F Altered Dorian: F-G-Ab-B-C-D-Eb
F# Altered Dorian: F#-G#-A-B#-C#-D#-E
G Altered Dorian: G-A-Bb-C#-D-E-F
G# Altered Dorian: G#-A#-B-Cx-D#-E#-F# (this would be better spelled as Ab Altered Dorian: Ab-Bb-Cb-D-Eb-F-Gb)
Bb Altered Dorian: Bb-C-Db-E-F-G-Ab (A# Altered Dorian doesn't really make sense, as A# Dorian is the same as G# Major, which is a key used in theory but little in practice, as it has six sharps and a double-sharp - Ab Major is used instead, as it has four flats)

Two further things to note:

when writing out diatonic scales and modes, and those which are alterations of a diatonic mode, such as this one, you should use each letter name once, adjusting with accidentals where necessary.
the Altered Dorian scale appears to be the fourth mode of the Harmonic Minor scale. In other words, each Altered Dorian has the same notes as the Harmonic Minor scale starting on a root seven semitones higher. Or, another way to think of this: if you start playing a Harmonic Minor scale from its fourth degree, you get an Altered Dorian.
Comment: Well done, Bob. Well beyond the call of duty! +2 deserved...
Comment: Too kind, too kind...
Comment: Thank you so much Bob Broadley. I don't know to say Thank but you really teached me so much thing today .
Comment: No problem. Have fun with using these scales!
Comment: Dear Bob ,  the Altered Dominant scale and the Altered Dorian Scales are same right ?
Comment: Oops! No I didn't mean to write that; I'll change it.
Comment: @Alter: Note that this scale is simply the fourth mode of harmonic minor, i.e., A dorian #4 = E harmonic minor, etc. Since it's probably much easier to find a list of harmonic minor scales, this might be the easier path ...
Comment: Last question about it ...   Fx (F double sharp)  means  G ?   What means  Fx - I should play G note  for Fx ?
Comment: Yes, on piano, Fx and G are the same note.
Answer: The Mishberak scale is more appropriately called the 4th mode of the minor harmonic. Play any minor harmonic, go to the 4th note, and start your scale there. Altered Dorian is clumsy. But if you want to think of the Mishberak that way, it's just the Dorian mode with a sharp 4.


NPM: cannot find module './lib' after upgrading to Node.js 5.0 on OS X

Question: Background
I just upgraded from Node.js v4.1.1 to v5.0.0 on my Mac. I used the node-v5.0.0.pkg installer from the node website because I don't have nvm or n installed, and I didn't install through Homebrew or MacPorts).
Problem
Now, every time I run npm I get the following error in my terminal:
Error: Cannot find module './lib'
    at Function.Module._resolveFilename (module.js:337:15)
    at Function.Module._load (module.js:287:25)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/request/node_modules/hawk/index.js:1:80)
    at Module._compile (module.js:425:26)
    at Object.Module._extensions..js (module.js:432:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
npm ERR! Darwin 14.5.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm"
npm ERR! node v5.0.0
npm ERR! npm  v3.3.6
npm ERR! code MODULE_NOT_FOUND

npm ERR! Cannot find module './lib'
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

I can't even re-install NPM through the traditional method of running npm install -g npm because the package manager itself doesn't work.
How do I get NPM working again on my Mac?
Comment: Note: this is a Q&A pair so others can benefit from what I've learned. But if anyone else has something to add, feel free!
Answer: Solution:

rm -rf /usr/local/lib/node_modules/npm
Reinstall node js v5.0.0

Other notes:
Looks like other people are running in to the same problem (see issue #3606). It sounds like a fix is in the works, so this issue will probably be resolved in the next release. In the interim, the only solution is to completely purge npm from your system and reinstall.


Evaluate $\lim\limits_{x\to 0}\frac{\int\limits_0^{x^2}\sec^2 t \, dt}{x\sin x}$

Question: Question :
Evaluate $\lim\limits_{x\to 0}\dfrac{\int\limits_0^{x^2}\sec^2 t \, dt}{x\sin x}$.
I hahe not got any idea how to evaluate. How can I do this?
Comment: l'hopital rule!
Comment: HINT: https://www.wyzant.com/resources/lessons/math/calculus/derivative_proofs/tanx
Answer: When you are walking very close to $x=0$ (both sides I mean), you will find out that $$\tan(x^2)\approx x^2, ~~\sin(x)\approx x$$ Use these two facts. I assumed you can handle the definite integral first.
Answer: You may use $\int \sec^2 x\, dx = \tan x$:
$$\dfrac{\int\limits_0^{x^2}\sec^2 t \, dt}{x\sin x} = \frac{\tan (x^2)}{x \sin x} = \frac{\sin (x^2)}{x^2}\cdot\frac{x}{\sin x}\cdot \frac{1}{\cos (x^2)} \stackrel{x \rightarrow 0}{\longrightarrow}1$$
Answer: Using L'Hospital rule
$$y=\dfrac{\int\limits_0^{x^2}\sec^2 (t) \, dt}{x\sin x}=\frac{\frac d {dx}\left({\int\limits_0^{x^2}\sec^2 (t) \, dt}\right)}{\sin(x)+x \cos(x)}$$ Now, for the numerator, use the fundamental theorem of calculus to get
$$y=\frac{2x \sec^2 (x^2) }{\sin(x)+x \cos(x)}$$ Close to $x=0$, the denominator is $\sim 2x$ and the remaining looks to be simple.
Comment: I think you mean the numerator is around $2x$?
Comment: @TobyMak. No, the denominator  since, close to $x=0$, $\sin(x)+x\cos(x)\sim x + x$. But, the numerator too, for sure. Then the limit. Cheers.
Answer: This is preferable when the integrand can't be integrated easily. By virtue of the standard limit $\lim_{x\to 0}\dfrac{\sin x} {x} =1$ the denominator $x\sin x$ can be replaced with $x^2$ and then putting $z=x^2$ we can see that the desired limit is equal to $$\lim_{z\to 0}\frac{1}{z}\int_{0}^{z}\sec^2 t\, dt$$ By fundamental theorem of calculus the above limit is equal to $\sec^2 0=1$.


Showing previous and next pager links regardless of the page one is in

Question: Drupal hides the previous link  of a pager if you are the first page,and the next link if you are on the last page. Is there way I can keep the links from disappearing, just in a disabled state? Can I do this without using php?
Answer: Probably not, to do this you would have to use theme_views_mini_pager().
Reference: http://drupalcontrib.org/api/drupal/contributions%21views%21theme%21theme.inc/function/theme_views_mini_pager/7
Example:
<code>if (empty($li_previous)) {
   $li_previous = " ";
}
</code>
That is whats doing it...
Answer: No - not without PHP, not without overriding the pager template in Views to do this. You could be able to do this in CSS if the views pager rendered the links but did not display them but the template excludes them. If you're willing to try creating a custom pager template, this article explains the basic steps.
Comment: The link is dead.


Link to nodes in WYSIWYG Editor and Domain Access

Question: I  have a Drupal installation using Domain Access.
Is there a solution for inserting links on nodes using WYSIWYG-Editor considering if the node is published to the particular domain.
For Example:
Node A, published to domain Y and Z, has a link to node B, published only to domain Z.
Viewing node A on domain Z the link is rendered as a link. Viewing node A on domain Y the link is rendered as plain text (without

Thanks in advance
Comment: Are you using the [WYSIWYG](http://www.drupal.org/project/wysiwyg) module or [CKEditor](http://drupal.org/project/ckeditor) or the like?  Which WYSIWIYG editor are you using if you are using the former?
Comment: I'm using WYSIWYG with TinyMCE
Answer: See the LinkIt project.
Its flexible API should let you hook into the node listing logic it uses to inject SQL to group node listing by Domain. You should be able to make a plugin with it ... I see no existing solution off-hand (I've used LinkIt and DomainAccess, but not had users linking around sub-domains from the WYSIWYG. My domains were very separate from one another).


Append content to div via jquery

Question: My project is a kind of blog, with posts and comments area. I'm trying to make it async with jquery ajax. My problem is that when a new comment gets inserted asynchronously it appears in the div  twice, and all the other comments disappear. If i refresh the page it looks fine.
VIEW:
<section id="comments_section_<?php echo $p1['post_id'];?>"> //THIS IS THE OUTPUT WHERE NEW COMMENTS WILL BE APPENDED

     <?php
       $data['comments'] = $this->model_mutamba->getComments($p1['post_id']);

       if($data['comments'] != ""){ ?>
               <div class="comments_container" id="comments_container_<?php echo $p1['post_id'];?>">

        <?php   foreach ($data['comments'] as $c){
                $user_img3 = $this->model_mutamba->getUserPicId($c->aluno_id);
               ?>

                <img style="height:32px;" src="<?php echo site_url();?>img/users/portfolio/<?php echo $user_img3;?>" alt="" class="align-left" />

                    <?php echo $this->model_mutamba->addSmilies($c->comment);?>

                        <?php
                              $c_date = explode('-', substr($c->comment_date,0,-8));

                              $date_num_word = monthNumToWords($c_date[1]);

                        echo substr($c->comment_date, 11,-3)." ".$c_date[2]." de ". $date_num_word . " ". $c_date[0];?>

      <?php } ?>

       <?php  } ?>

JS:
 function comment(post_id,input){

    var comment = $(input).val();
    var output = '#comments_section_'+post_id;

    if(comment != ""){
        $.ajax({
                type:"POST",
                url:base_url+"mutamba/insertNewComment",
                data: {comment: comment, post_id:post_id},
                cache:false,
                success:function(response){
                    $(output).html(response);
                $(output).append(response);

                }
        });

    }
}

CONTROLLER:
function insertNewComment(){
     if($this->session->userdata('is_logged_in')){

            $email= $this->session->userdata('email');
            $comment= $this->FilterData($this->input->post('comment'));
            $post_id= $this->FilterData($this->input->post('post_id'));

            $this->load->model('model_mutamba');
            if($this->model_mutamba->insertNewComment($email,$comment,$post_id)){
                  $this->load->model('model_user');

                 $count = $this->model_mutamba->countPostComments($post_id);
                  ?>

                     <?php
                     $this->load->model('model_user');
                    $user_img = $this->model_user->getUserPic($email);

                           echo '

                               '.$this->model_mutamba->addSmilies($comment).'

                                ';
                                           $date = date(date('Y-m-d H:i:s'));
                                          $c_date = explode('-', substr($date,0,-8));

                                          $date_num_word = monthNumToWords($date[1]);

                                    echo substr($date, 11,-3)." ".$c_date[2]." de ". $date_num_word . " ". $c_date[0].'

';

            }

      }else{
         redirect("inicio");
            }

 }

Will appreciate any help,
Thanks in advance
Comment: On success you are using .html() and .append(). This is creating your response to repeat.
Answer: This is happening  because in your AJAX success callback, you are adding response to the output TWICE - once with .html() and then again with .append().
.html(response) removes the previous HTML in your webpage, thats why you dont see other comments and it adds response to it.
With .append(response), it is adding response to the bottom of the div, that is the reason you are seeing the response twice!
Remove $(output).html(response) from the success callback and it will work fine.
So, your function needs to look like this:
 function comment(post_id,input){
    var comment = $(input).val();
    var output = '#comments_section_'+post_id;

    if(comment != ""){
        $.ajax({
                type:"POST",
                url:base_url+"mutamba/insertNewComment",
                data: {comment: comment, post_id:post_id},
                cache:false,
                success:function(response){
                  $(output).append(response);
                }
        });
    }
}

Comment: LMAO!!! It must be the tiredness lol. too many days and nights no sleep at all m8. cheers
Comment: @sunrisepoet I am glad that my answer is helping. Please mark this answer as accepted and upvote if it has solved your problem. :)
Comment: just out of curiosity, is it alright to have javascript in the controller the way i did? or is it bad practice? if bad practice, what it the right way to do it? thanks again
Comment: @sunrisepoet It is a bad practice. Ideally, you should have JS code in .js file, PHP code in .php file and so on. Also, having `` elements inside `
Comment: Right so how can I append html content through javascript or append new html elements eg. ``, if i can't write `` in js? are'n they just strings?
Comment: @sunrisepoet You are getting me wrong. You can write `` anywhere in the HTML `` tag, except the `
Answer: function comment(post_id,input){
var comment = $(input).val();
var output = '#comments_section_'+post_id;

if(comment != ""){
    $.ajax({
            type:"POST",
            url:base_url+"mutamba/insertNewComment",
            data: {comment: comment, post_id:post_id},
            cache:false,
            success:function(response){
                //$(output).html(response);    //Comment this line or the line below it.
            $(output).append(response);
            }
    });
}

}
Comment: @EternalHour: I have given the explanation on the comment below the question. If you time just look at that also
Comment: You need to include it with your answer, not in the comments.
Answer:

append

Append content to div via jquery


AES encryption and the need for Integrity

Question: I did some research on the topic but could not find anything similar to my question. So I hope some of you great guys may help me out.
I want to use AES128 encryption (CFB-Mode) for the networking in my application between two individual clients. The data being exchanged consists only of textual strings of a specific structure, for example, the first bytes allways tell the recipient the kind of message they are receiving, so they can process them. With AES I want to ensure the confidentiality of the message, but now the question of "integrity" arises.
Normaly you would consider using a MAC. But isn't it guaranteed that nobody has altered the message, if the recipient is able to decrypt it correctly, i.e. that the message can be used correctly in his application because of the string's format? Wouldn't altering (even 1 bit) the encrypted message by a third party result in garbage during decryption?
Furthermore let's assume that the application is a multi-party peer-to-peer-game, where two of the players are communicating with each other on a private but AES-encrypted channel. Now the originator of the message is not playing fair and intentionally sending a fraudulent encrypted message to convey an impression that the message has been altered by a random third party (to force a player to quit). Now the recipient would have no chance to determine if the message has been altered or if the sender acts fraudulent, am I right? So Integrity would not be of much use in such a situation and could be neglected?
This may sound like an odd and out of world example. But it's something I recently encountered in a similar application and I am asking myself if there is a solution to the problem or if I got the basic Idea of AES encryption.
Answer: As you said, you may detect changes in the format of the plain text message after encryption. But at what level would it go wrong? Do you have something that is large and redundant enough to be tested? What are you going to do if the altered plain text results in some obscure exception somewhere down the line? With CFB (like most modes) an attacker can make sure that only the last part of the message is altered, for instance, and leave the first blocks intact.
And you are worried about cheats as well.
In my opinion, you are much better off using a MAC or HMAC algorithm, or a cipher mode that provides integrity/authentication on top of confidentiality (EAX or GCM for instance). If you are sure nobody else has the symmetric key, an authentication check (such as a MAC) will prove that the data has been signed by the correct key. So no, the user cannot claim that the data has been changed in transport if the authenticity checks succeed.
The next question becomes: can you trust that the symmetric key is only in possession of the other player? For this you might want to use some sort of PKI scheme (using assymetric keys) together with a key exchange mechanism such as DH. But that is for a later, if you decide to go that way.
Comment: Thanks. So if someone would change for example the last few bits of the message, the first part would decrypt correct and the part after the alteration would result in gibberish? Would it be a good option to use a secret between two parties instead and compute with PBKDF2 two different keys, so one can be used to encrypt and one for MAC? I would still have no chance to distinguish altered messages from fraudulent behaviour, but at least I am always able to detect the alterations. Concerning the last part: at the moment I am just assuming that the key/secret has already been exchanged securely.
Comment: PBKDF2 is too heavy for that. If you've already got a secret key, you might as well encrypt some counter value for each, or - what I would prefer - calculate a hash with the minimum number of bits for the key. The input of the hash would be the concatenation of the secret and a 4 byte counter (big endian). E.g. SHA-1( | 00000001) for the first 16 byte key and SHA-256( | 00000002) for the second 32 byte key.
Answer: This is a bit out of my depth, but...
Yes, modifying the encrypted bytes of an AES encrypted message should cause the decryption to fail (this has been my experience with the c# implementation). The client who decrypts will know the message is invalid. EDIT: apparently this is not the case. Looks like you'd need a CRC or hash to verify the message was successfully decrypted. The more serious problem is if the secret AES key is leaked (and in a peer-to-peer environment, the key has to be sent so the receiver can decrypt the message at all). Then a 3rd party can send messages as if they were a legitimate client, and they will be accepted as OK.
Integrity is much harder. I'm not entirely sure how robust you want things to be, but I suspect you want to use public key encryption. This allows you to include a hash of the message (like a signature or MAC) based on the private key to assert the message validity. The receiver uses the public key to verify the hash and thus the original message is OK. The main advantage of public key encryption over symmetric encryption like AES is you don't have to send the private key, only the public key. This makes it much harder to impersonate a client. SSL/TLS uses public key encryption.
In any case, once you have identified a client sending invalid messages, you're in the world of deciding to trust that client or not. That is, is the corruption due to malicious behaviour (what you're worried about)? Or a faulty client implementation (incompetence)? Or a faulty communications link?. And this is where encryption (or at least my knowledge of it) won't help you any more!

Additional regarding integrity:
If you assume no one else has access to your secret key, a CRC, hash, or HMAC would all suffice to ensure you detected changes. Simply take the body of your message, calculate the CRC, hash, whatever and append as a footer. If the hash doesn't match when you decrypt, the message has been altered.
The assumption that the secret key remains secret is quite reasonable. Especially if after some number of messages you generate new ones. SSH and WiFi's WPA both generate new keys periodically.
If you can't assume the secret key is secret, then you need to go to PKI to sign the message. With the AES key in a malicious 3rd party, they'll just generate whatever messages they want with the key.
There may be some mileage in including a sequence number in your message based on a RNG. If you use the same RNG and same seed for both parties, they should be able to predict what sequence number comes next. A 3rd party would need to intercept the original seed, and know how many messages have been sent to send valid but forged messages. (This assumes no messages can ever be lost or dropped.)
Comment: Additionally you can look into DES technologies to verify integrity.
Comment: SSL/TLS uses symmetric cryptography to secure application data, so both sides end up with knowledge of the symmetric keys.
Comment: Symmetric ciphers (during encryption/decryption) use 1:1 relation between plain text and cipher text for each encrypted block. In other words, there is no way to detect a failed encryption at that level. The only thing you can detect are changes in the plain text after decryption. One of these changes is padding, which is normally part of the encryption mode, so that *may* be detected - however padding may very well be accidentally be right. CFB however does not even use padding, so there is no way to detect failed decrypts.
Comment: @GregS - both sides = the owner of the private key and the server being connected to in the handshake, which is way better than sending a clear text symmetric key
Comment: I don't want to use Public-Key-Encryption at this point, at least not for all the messages, because of the performance. It is a viable option for key-exchange, though. At the moment I am just assuming that the symmetric key has been exchanged securely already, so I can use AES for message encryption.
Comment: @Fenriswolf Fair enough, PKE is rarely used beyond key exchange because of perf. I'll edit my answer for some more integrity ideas (although I'm 99.9% sure I'm out of my depth now!)


Entity Framework - Inserting entity with multiple models and databases

Question: I have my domain split into multiple Entity Framework models. I have some shared entities that span multiple models (named Lookup), however, these are replaced with "using" references using the methods described in Working With Large Models In Entity Framework. However, what makes my case slightly more unique is that I'm also separating these models into multiple databases (one per model).
I'm having a problem inserting one of my shared entities into my common DB. It's failing with the error:

The member with identity
  'Harmony.Members.FK_ResidentialAddress_ResidenceTypeLookup'
  does not exist in the metadata
  collection.

That foreign key that it's referring to does not exist on the "common DB". But I'm also not working with the entity on the other side of the relationship (named ResidentialAddress); nor do I even have the context that would contain the other entity initialized (named MembersDb). However, both models are compiled into the same assembly.
There are no navigation properties going from Lookup to ResidentialAddress. Though there is a navigation property in the other direction (which I won't be persisting - only using in memory).
My MetadataWorkspace for the EntityConnection of the CommonDb context was explicitly initialized with only the SSDL/CSDL/MSL for the data required for that database. I have confirmed there is no references to the foreign key mentioned in that set of schema data.
var metaAssembly = typeof(CommonDb).Assembly;
var schemaResources = new string[]
{
    String.Format("res://{0}/Common.ssdl", metaAssembly.FullName),
    String.Format("res://{0}/Common.csdl", metaAssembly.FullName),
    String.Format("res://{0}/Common.mdl", metaAssembly.FullName),
}
MetadataWorkspace metadata = new MetadataWorkspace(schemaResources, new []{ metaAssembly });
EntityConnection connection = new EntityConnection(metadata, myDatabaseConnection);

POSSIBLE CLUE: It does work when I go into the generated classes and remove all of the EdmRelationshipAttribute attributes along with their paired EdmRelationshipNavigationPropertyAttribute from the related models (MembersDb).
Key questions:

So why is it that Entity Framework is trying to do something with the relationship that is for an entity that is neither in scope and nor will it be affected by the insertion of the record!?
I am happy to have the generated code remove the attributes mentioned above, but I still want the navigation properties to remain. How would I go about altering the CSDL to achieve that?

NOTE: Persistence of the "child" models is not a priority, nor is the integrity of their now cross-DB foreign keys. These databases are persisted using SQL CE but they were originally generated from a single master SQL Server database.
Answer: If each part of your model is written to a separate database, then perhaps the edmx files should not know about each other (about entities or relationship to entities that do not belong to them).

How about trying one of the following approaches:
(To end up with same entities classes for  each part, but make EF oblivious of connections between them.)

Remove the "usings" from edmx + cancel auto generation and create classes yourself.
Remove the "usings" from edmx + modify t4 template to read more than one edmx when creating the classes.
Copy edmx files aside so you have two sets of edmxs.
 3.a. Use set #1 for auto generation of entities.
 3.b. Modify set #2 by removing the "usings" and use for generation of repository classes (objectsets).

Let me know if one of these works.
Good luck,
Danny.
Comment: Danny, I've ended up going with something similar to option 2. I build a generator (using EdmGen2 as a starter) that allows removal of properties. I went to some extra effort to manually generate (I wrote the CodeDom) the navigation properties that I first removed from the CSDL.


jQuery: function which still acts on old selection

Question: I have a function that acts on a selection (passed by means of the argument 'sel'): when I hover with the mouse upon the items in the selection, another element in the same selection ('.extLink') is animated.
The function is:
function animo(sel) {
    sel.hover(
        function () {
            $('.extLink').stop().animate({right: '-5px'}, 'fast');
        },
        function () {
            $('.extLink').stop().animate({right: '0'}, 'fast');
        }
    );
}

The selection changes by clicking on certain elements of the page. But it happens that, despite the selection correctly changes, the function continues to work even on items that were part of previous selections, ie .extLink is animated when I pass on these items too.
I made some tests and saw that the selection is done properly. What could therefore be the cause of this behavior? What I'm doing wrong?
The HTML on which the function acts is as follows (extracted from the DOM):

310 Raccolte di statistiche generali

320 Scienza politica

330 Economia

340 Diritto

328 Il processo legislativo

330 Economia

340 Diritto

        ...

350 Amministrazione pubblica; arte militare

360 Problemi e servizi sociali; associazioni

It works as following:

clicking on a X element (elsewhere) of the page, the class 'attivo' is added to the li.ref-x (in the example li.ref-2);
at the same time, the div.quadri is cloned from its original position in the page and appended to the last li.attivo;
inside the div.quadri there is a.extLink;
the selection I pass to the animo() function is li.attivo, so when I move the mouse on the li.attivo elements (and consequently on div.quadri too) a.extLink is animated.

All this works well, the problem comes after:

when I click a Y element of the page, the class 'attivo' is added to li.ref-y (e.g li.ref-3) and removed from li.ref-x, then the div.quadri is removed from li.ref-x and a different div.quadri is cloned inside li.ref-y;
now a.extLink is animated when I move the mouse not only on li.ref-y (i.e. li.attivo) but also on li.ref-x though they haven't the class 'attivo' anymore.
Comment: if you pass `.extLink` as `sel` all classes will animate, how do you call `animo()` ?
Comment: I've added some HTML and description in my first question
Answer: Removing the attivo class from elements after you've selected them and registered event listeners on them won't stop the listeners from being called, and your listeners perform the animation based only on class name extLink, not context.  Try something like one of these:
Remove listeners from previous selection
var previous_sel = $();

function animo( sel ) {

  // Assumes jQuery 1.7

  previous_sel.off( "mouseenter mouseleave" );

  previous_sel = sel;

  // ... rest of your current function

}

Use delegated registrations
This will only call the listeners for elements that have class attivo at the time the event occurs.
function animo() {

  // Use appropriate selector to get the relevant UL

  var ul = $( "ul" );

  var selector = "li.attivo";

  ul.on( "mouseenter", selector, function () {

    ul.find( selector + ' .extLink' ).stop().animate(

      { right : '-5px' }, 'fast'

    );

  } );

  ul.on( "mouseleave", selector, function () {

    ul.find( selector + ' .extLink' ).stop().animate(

      { right : '0' }, 'fast'

    );

  } );

}
// animo

Limit the context
Limit the context to extLinks within sel.
function animo( sel ) {

  sel.hover(

    function () {

      sel.find( '.extLink' ).stop().animate( { right : '-5px' }, 'fast' );

    },

    function () {

      sel.find( '.extLink' ).stop().animate( { right : '0' }, 'fast' );

    }

  );

}


Google Cloud Storage: Upload a lot of small files at once?

Question: is there any good strategy to upload 100s of thousands of files at once?
Uploading through fuse takes ages, naturally. Is there a way to upload a tar and unzip it on GCS?
Answer: Okay, that was easy:
<code>gsutil -m rsync -d -r uploads
</code>
gsutil in general has a lot of options and is much faster than fuse.


populating nid in a custom field

Question: When creating a new node, I need to populate/fill a custom field with a value of the current node's id. What hook should I use to fill my custom field with newly created nid ($node->nid)?
I tried to use hook_node_presave but it was NULL, currently I am thinking to use hook_node_insert but as documentation says :

after the node is inserted into the node table in the database,

Does that mean if I assign the new value to my custom field it will be/not be saved to database?
Comment: Editing or Changing Drupal nid's are not allowed since they are unique and generated by Drupal to keep track of content. What is the reason you are looking for to change the nid's ?
Comment: i am not trying to change the nid i am just trying to copy its value after creating a new node to my costum field
Comment: It might help if you explain a bit more about what you are trying to achieve, since although we can probably tell you how to do what you're asking, there is most likely a better way to get there.
Comment: Are you trying to reference one node with another ? Or do you want to display the node id in custom field which will be visible when you edit node ? Or something else ?
Comment: what is your drupal version ?
Comment: method is differenct in drupal 6 and drupal 7 for achieve it. what is your drupal version? after this please tag your drupal version
Comment: what i want is  to display the node id in custom field which will be visible when you edit/view the node
Answer: I guess I found a solution for this problem:
function mymodule_node_insert($node) {
  $node->field_custom_field['und'][0]['nid'] = $node->nid;
  node_save($node)
}

I saved the changes to database with node_save()
Answer: if you are drupal 6  use hook_nodeapi
function MODULENAME_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'presave':
      $nid=$node->nid;
       // $nid  is exist and you can put it in your field
       //something like this
       $node->field_yourfieldname['und'][0]['value'] = $node->nid;
       // this parameters related your field name and field type I suggest you in here ou print $node first and according it accompolish
      break;
   }
  }

and if you are using drupal 7 use hook_node_insert
function hook_node_insert($node) {
    $nid = $node->nid;
   // $nid  is exist and you can put it in your field
              //something like this
       $node->field_yourfieldname['und'][0]['value'] = $node->nid;
       // this parameters related your field name and field type I suggest you in here ou print $node first and according it accompolish
   }

Comment: if i make any changes to the node with hook_node_insert, are the changes that are made to custom field saved to the database or i need to invoke some function to save it to database?
Comment: no need any additional function.

populating nid in a custom field


unable to create new draft programatically for published node

Question: I am using workbench_moderation module.
When I edit the node and save it using node_save($node) it is changing the status of actual node to draft and original node is getting unpublished.
While I want to keep original node as published and want to create new reversion in draft status.
I used below code too but it is not working form me(It is immediately publishing my changes).
node_save($node);
workbench_moderation_moderate($node, 'published');

Comment: new reversion or new revision?
Comment: Are you sure no other code is executed by custom module or rules?  How about checking the publishing status after node_save($node)?
Answer: I've not tested or checked against the source code but I think you should try to node_load after node_save and before workbench_moderation_moderate.
node_save($node);
$saved_node = node_load($node->nid);
workbench_moderation_moderate($saved_node, 'published');


Uniform convergence in $\sup$ and $\inf$ convolutions

Question: In this paper, the authors introduce on p.645 ($11^{th}$ page of the paper) the $\sup$ and $\inf$ convolutions for a continuous, bounded function $w:\mathbb{R}^n \times [0, \infty) \to \mathbb{R}$
$$ w^{\varepsilon}(x,t) = \sup_{y,s} \left( w(y,s) - \frac{1}{\varepsilon} \left(|x-y|^2 + (t-s)^2 \right)\right)$$
$$w_\varepsilon(x,t) = \inf_{y,s}\left( w(y,s) + \frac{1}{\varepsilon} \left(|x-y|^2 + (t-s)^2 \right)\right) $$
Amoung the properties they cite for these functions, they list:

$w_\varepsilon \leq w \leq w^\varepsilon$
$||w^\varepsilon||_\infty, ||w_\varepsilon||_\infty \leq ||w||_\infty$
If $w^\varepsilon(x,t) = w(y,s) - \frac{1}{\varepsilon}\left(|x-y|^2 + (t-s)^2 \right)$ then $|x-y|,|t-s| \leq \sqrt{ 2 ||w||_\infty \varepsilon}$
$w^\varepsilon, w_\varepsilon \to w$ uniformly as $\varepsilon \to 0^+$ on compact subsets of $\mathbb{R}^n \times [0, \infty)$

The first three are not so hard to show and build upon one another. For instance, using 2, one can prove 3 by contradiction.
However, 4 is giving me some trouble. The authors indicate that 4 should follow from the uniform continuity of $w$ on compact sets. My attempt was the following:
We want to show that for given $\delta>0$, there is a $\gamma>0$ such that $\gamma > \varepsilon >0$ implies $|w(x,t) - w^\epsilon(x,t)| < \delta$.
For given $\varepsilon >0$, 3 implies
$$w^\varepsilon(x,t) = \sup_{|x-y|,|t-s| \leq \sqrt{ 2 ||w||_\infty \varepsilon}} \left( w(y,s) - \frac{1}{\varepsilon} \left(|x-y|^2 + (t-s)^2 \right)\right)$$
So, we can replace the $\sup$ with a max. Thus, for any $\varepsilon$ there are $y_\varepsilon, s_\varepsilon$ such that
$$ w^\epsilon(x,t) =  w(y_\varepsilon,s_\varepsilon) - \frac{1}{\varepsilon} \left(|x-y_\varepsilon|^2 + (t-s_\varepsilon)^2 \right)$$
Thus, $|w(x,t) - w^\epsilon(x,t)| \leq |w(x,t) - w(y_\varepsilon, s_\varepsilon)| + \frac{1}{\varepsilon} \left(|x-y_\varepsilon|^2 + (t-s_\varepsilon)^2 \right)$
This is where I ran into trouble. The first term I can bound by uniform continuity. However, I do not see how I can bound the second term by anything that goes to $0$, since we might have $|x-y_\varepsilon| = \sqrt{ 2 ||w|_\infty \epsilon}$ , giving:
$$ \frac{1}{\varepsilon} \left(|x-y_\varepsilon|^2 + (t-s_\varepsilon)^2 \right) \geq 2 ||w||_\infty$$
I must be missing something but I cannot tell what it is. If someone could let me know what it is, I would be very appreciative. How do we make sure that the last term goes to 0? Does anyone have a hint?
Answer: Since $w^\epsilon\geq w$, we have $|w^\epsilon(x,t)-w(x,t)| = w^\epsilon(x,t) - w(x,t) = w(y_\epsilon,s_\epsilon) - \frac{1}{\epsilon}(|x-y_\epsilon|^2+|t-s_\epsilon|^2) - w(x,t) \leq w(y_\epsilon, s_\epsilon) - w(x,t).$


Integer times vector bundle notation in Hatcher

Question: In Hatcher's vector bundles and K-theory, p45, there is a proposition written "If $q$ is a polynomial clutching function of degree at most $n$, then $[E,q] \oplus [nE,\mathbb{1}] \approx [(n+1)E,L^nq]$ for a linear clutching function $L^nq$.
Here $E$ is a vector bundle and $[E,f]$ denotes the vector bundle constructed by $E$ and the clutching function $f$. However I have no clue what $nE$ or $(n+1)E$ mean, and naturally no definition or explanation of the notation is given. The proof of the proposition mentions that $(n+1)E$ has direct summands, so I thought it might be the direct sum (interpreted appropriately for vector bundles) of $E$ $n+1$ times, but I am not sure so I was hoping someone who understands this notation could confirm this.
Answer: It's only semi-true at best that "naturally no definition or explanation of the notation is given," see the first paragraph under "Ring Structure" on page 40:

We can simplify notation by writing for the element $\epsilon^n \in K(X)$ just as $n$. This is consistent with familiar arithmetic rules. For example, the product $n E$ is the sum of $n$ copies of $E$.

In other words, it is the tensor product $\epsilon^n \otimes E \cong \bigoplus_{i = 1}^n E$.
I say semi-true because this definition is technically given on the level of classes, not on the level of bundles; but really this shouldn't pose a problem, and going back and forth tacitly between these two things is common in the literature. Also, do keep in mind that this is not a finished, published book, so don't be too harsh on it :)

If you're just here for the punchline: Yes, your interpretation of the notation is correct.


$(2^{x^{2}-1} - 8)(\sqrt[4]{1-5x}) = 0$ Solve the equation.

Question: $(2^{x^{2}-1} - 8)(\sqrt[4]{1-5x}) = 0$ Solve the equation and find the biggest root.
I understand that either $(2^{x^{2}-1} - 8)$ or $(\sqrt[4]{1-5x})$ shoud be equal to $0$. Solving this further I get that $x=2$ or $x=-2$ or $x= \frac{1}{5}$.However, the answer in my book says that the answer is $\sqrt{3}$. Could you please, clarify ?
Answer: If you allow the factors to become imaginary numbers, then plugging $\sqrt3$ into the LHS of the equation doesn't give you $0$ so it is incorrect. If you don't allow imaginary numbers, then both $2,\sqrt3$ don't belong to the domain of the solution because $1-5x$ becomes negative. In this case the solutions will be $-2,1/5$ only. Note that $\sqrt3$ is a solution of$$(2^{x^2}-8)(\sqrt[4]{1-5x})=0$$if imaginary numbers are allowed.


causal effect and relationship

Question: I understand, in a correlation, r just signifies the relationship between two variables, and we CANNOT deduce that there is a causal relationship in the case of a correlation.
By contrast, we use a linear Regression analysis to predict y from x, using the equation y= mx+c. Can we discuss that there is a causal effect in this case?
Answer:
By contrast, we use a linear Regression analysis to predict y from x, using the equation y= mx+c. Can we discuss that there is a causal effect as well?

No. Consider the univariate regression where your coefficient m is intimately related to the correlation coefficient r.
You can study causality using linear regression, but in and of itself it doesn't say anything about causality. You can run and use regression when there's no causal relationship.
Comment: Vyas: Sure, why not?  And then you could just switch the variables in your regression and thereby conclude, with equally firm logic, that level of satisfaction has an impact on the beauty of products.  That will enable you to (mis)use statistics to conclude that anything causes anything else.
Comment: As I understand, m is the rate of change (steeper slope of the graph), and r tests the relationship between the two var. I understand that we cannot infer causality in the case of Regression unless conditions (i) or (ii) are satisfied. My hypothesis predicts that users derive higher level of satisfaction (y) with beautiful products (x).  How do I ideally interpret the following: y=2+ 0.22x. Larger (or smaller) values of y are associated with larger (or smaller) values of x.Can I deduce that "users derive higher level of satisfaction from greater product aesthetics?"
Comment: Or is it wiser to use the word "impact" or "influence" when can are interpreting regression or correlation results. For example, is it proper to say that beautiful products have an impact on level of satisfaction?
Comment: @Vyas, you cannot say anything about causal relationship from regression outputs. That's just a sad fact. There's no way around this, and using "influence" or "impact" is just using euphemisms, doesn't cut it. Establishing causality is difficult in what you're trying to do. The terms "predictor" and "dependent" variable are artifacts of the history, the regressions were first used in the context where the causality was out of the question, at least the direction of it. In your case, unless you already know the direction of the causality from other research the regression won't help you
Comment: @Vyas, if you already know that x causes y, then yes, you can use the regression to measure the strength of the causal impact or to otherwise study its properties. How would you know? Maybe it's obvious in your field of research, maybe there are other facts and considerations that leas you to believe that x causes y. However, even in this case I doubt that the univariate regression would be convincing. A simple factor such as a price may impact both x and y in your equation. If I buy 10,000\$ watch for 100\$ on the auction, I'll be aestethically satisfied
Answer: You are correct by saying you cannot deduce causal relationships when there is a statistically significant test of r=0, r being the Pearson correlation coefficient.
Statistical testing of the least squares regression slope (what you call m) is equivalent to tests of Pearson correlation coefficient: if one is non-zero, the other is non-zero. Tests of these hypotheses are asymptotically equivalent.
A necessary but insufficient condition to infer causality: you must either 1) randomize a cohort of participants to receive an experimental treatment or 2) control for confounding in a pseudoexperimental design using a multivariate model (estimating partial correlation or adjusted regression coefficients).
Suggested reading: Causality by Pearl 2nd ed, Causal Inference by Hernan, Robbins, Causal Diagrams for Epidemiologic Research by Greenland, Robins, Pearl.
Answer: First of all, as Aksakal pointed out as well, regression coefficients and (partial) correlation coefficients are linked, with the latter basically being a normalized version of the former.
Having noted that, you reason (I think) that because we can use a regression to "predict" y from x, this implies a kind of causality flowing from x to y. The problem is that prediction says nothing about causality. For example, the height of the sun in the sky is causally related to how light it is outside. Clearly, the sun being higher in the sky causes more illumination, and not the other way around. Yet, we can use our observation of how light it is outside to predict the height of the sun in the sky. I guess this can seem a bit misleading since the word "prediction" has a connotation of one event (causally) preceding another, but in this context the term is used more broadly to mean something similar to "inference".
Answer: Say your x variable is the dollar value of goods imported from year 2007 - 2017, and your y variable is private health spending for a person in year 2007 - 2017 as well. You plot x, y, and see a clear increasing and linear trend between x and y, and you can definitely fit a regression model to get the m. But there is no causal relationship in this case, rather a lurking variable (the common year). The association between x and y are just due to the fact that both imports and health spending grew rapidly in those years.
Reference: Introduction to the practice of statistics, chapter 2.4.

causal effect and relationship


cyclic vector exists for symmetric operator iff there no repeated eigenvalues

Question: Considering a symmetric operator $A$ acting on a finite dimensional Hilbert space $H$, we say $x\in H$ is a cyclic vector for $A$ if the set of finite linear combinations of $\{A^n x:n=0,1,2,...\}$ is equal to $H$. I am looking for a proof of whether $A$ must have a cyclic vector iff $A$ has no repeated eigenvalues. Hints are welcomed.
Comment: It would be helpful if you comment on what have you attempted and tried so far.
Comment: If $H$ is of finite dimension, then "dense" is a strange term to use; $H$ itself is the only dense subspace.
Comment: Is your Hilbert space real or complex? When you say that $A$ is symmetric do you mean that $A$ is self-adjoint or that some matrix representing is equal to its (regular, non-conjugate) transpose?
Comment: Up to isomorphism you can assume that the Hilbert space is $\mathbb{C}^n$ and the operator is represented by a diagonal matrix $$\begin{bmatrix} \lambda_1 && \\ & \ddots & \\ &&\lambda_n \end{bmatrix}$$This way we are reduced to a problem in linear algebra. Have you tried this already?
Answer: I will assume that we are talking a real Hilbert space. Everything works the same in the complex case if we use "hermitian" instead of "symmetric".
Note that, from your definition, the condition "$A$ has a cyclic vector $x$" is equivalent to
$$\tag{1}
H=\{p(A)x:\ p\in\mathbb R[t]\}.
$$
If we fix an orthonormal basis for $H$, the fact that $A$ is symmetric guarantees that $A$ is diagonalizable, i.e. $A=VDV^T$, with $V$ orthogonal and $D$ diagonal containing the eigenvalues of $A$ (counting multiplicities) in its diagonal.
As $p(A)=Vp(D)V^T$, condition $(1)$ translates into
$$\tag{2}
H=\{p(D)y:\ p\in\mathbb R[t]\},
$$
where $y=V^Tx$.
The key observation is that $\{p(D):\ p\in\mathbb{R}\}$ is a vector space (since $\mathbb R[t]$ is), and that
$$\tag{3}
\dim\{p(D):\ p\in\mathbb{R}\}=\text{the number of distinct eigenvalues of }A.
$$
This can be seen from the fact that $p(D)$ is the diagonal matrix with diagonal $p(D_{11}),\ldots,p(D_{nn})$, and that given distinct numbers $\lambda_1,\ldots,\lambda_k$, the set $\{(p(\lambda_1),\ldots,p(\lambda_k)):\ p\in\mathbb R[t]\}$ equals $\mathbb R^k$
Now, if we have equality in $(2)$, then the set on the right has dimension $n$, and by $(3)$ we get that $A$ has $n$ distinct eigenvalues.
Conversely, if $A$ has $n$ distinct eigenvalues, then choosing $y$ to be the vector with all its coordinates equal to one (i.e. the sum of the unit eigenvectors for $A$), we get that the set on the right-hand-side on $(2)$ has dimension $n$, and so it equals all of $H$.


finding a unique integer using mod

Question: Consider two different prime numbers $x$ and $y$. Show that the following is true: For every pair of numbers $m$ and $n$ so that $0\le m<x$ and $0\le n< y$, there is a unique integer $q$, where  $0\le q<xy$, so that:$$q\equiv m \mod x\\ q\equiv n \mod y$$
To start this problem, I'm thinking that we have to find the number of $q$'s in the range $[0,xy)$ that can have the same result modulo $x$ and modulo $y$ and count how many $q$'s there are.
Comment: Do you already know the Chinese Remainder Theorem?
Answer: Since $x$ and $y$ are prime numbers, use Euclid's Algorithm to find $r$ and $s$ such that $rx + sy = \gcd(x,y)=1$. Take $q\equiv (nrx+msy) \mod xy$.

finding a unique integer using mod


RN Navigation - Draw Navigator

Question: Meu app vai possuir vários tipos de navegação em diferentes telas.
Comecei utilizando a index com stacknavigator e numa segunda página to tentando configurar a DrawNavigator e não estou conseguindo.
Vi em um post de exemplo como se tivesse que inciar e registrar o app com o draw primeiro. É isso mesmo?
Comment: Seria interessante você indicar qual post viu isso tambem.
Comment: Nesse: https://developerlife.com/2017/04/15/navigation-and-styling-with-react-native/
Answer: Eu consegui fazer utilizando com Stack e drawer. No meu caso o drawer é a primeira screen da Stack e funciona. O código está assim:
<code>const Drawer = DrawerNavigator({
  HomeDrawer: {
    screen: HomeScreen
  },
  SettingsDrawer:{
    screen: SettingsScreen
  }
});
const App = StackNavigator({
  Drawer: {
    screen: Drawer,
  },
  Home: {
    screen: HomeScreen
  },
  Settings: {
    screen: SettingsScreen
  },
  View: { screen: ViewScreen },
})

export default App;
</code>
Neste caso Home e Settings são acessiveis a partir do drawer e view só é acessivel a partir da stack.

RN Navigation - Draw Navigator


When t run my code with @test annotation, my code returns following error message

Question: <code>[RemoteTestNG] detected TestNG version 7.0.1
</code>

Exception in thread "main" java.lang.NoClassDefFoundError:
  com/google/inject/Stage
Comment: Hi @Bindu Gowda did you solve the issue
Answer: There is an open issue that is tracking this discrepancy.
See here: https://github.com/cbeust/testng/issues/2223
As an alternate, what you can consider doing is, to switch over to using IntelliJ because this problem is perhaps specific to the eclipse testng plugin.


Iterar sobre um array e salvar em um dict

Question: Dado esse array:
array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ...,
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint8)

Estou querendo iterá-lo para contar valores em cada linha e depois salva-los por linha.
O código abaixo está fazendo a soma geral. Gostaria de ter a contagem por linha.
def count(image):
    array = np.array(image)
    array[[ array == 0 ]] = 1
    array[[ array == 255 ]] = 0
    for row in array:
        unique, counts = np.unique(array[row,] , return_counts=True)
        d = dict(zip(unique, counts))
    return new

O resultado:
{0: 234710, 1: 515}

Answer: Bom dia,
Sua resposta está quase correta, para que seu script funcione você deve colocar o unique apenas em row não em array[row,], também não existe um identificador da linha, você pode criar um dicionário para cada linha, ou uma lista em cada posição um dicionário para a linha correspondente:
uma lista com um dicionario para cada linha:
def count(image):
    array = np.array(image)
    array[[ array == 0 ]] = 1
    array[[ array == 255 ]] = 0
    colecao = list()
    for row in array:
        unique, counts = np.unique(row , return_counts=True)
        d = dict(zip(unique, counts))
        colecao.append(d)

um dicionário para cada linha:
def count(image):
    array = np.array(image)
    array[[ array == 0 ]] = 1
    array[[ array == 255 ]] = 0
    count = 0
    colecao = dict()
    for row in array:
        unique, counts = np.unique(row , return_counts=True)
        d = dict(zip(unique, counts))
        colecao[count] = d
        count += 1

Verifique se alguma delas é útil para você.
Comment: Completei a primeira alternativa  com colecao = [] no início e return(colecao) no final e deu certo.
Comment: que bom que deu certo amigo, se a resposta lhe ajudou curta ela e marque como resposta, assim ajuda a outros responderem suas dúvidas. Abraços amigo.


Preventing horizontal drag scrolling on a 100% width page

Question: I've got a page design that uses CSS keyframes to make a min-height: 100%
 element containing page content slide in from the right. Once the element has animated to its final position, it is possible to "drag-scroll" the page horizontally by selecting and dragging the text, which I want to avoid.
Both the  and  elements are set to overflow-x: hidden;, which works for preventing scrollbars but still allows scrolling functionality. I do need users to be able to scroll the
 element vertically.
I'm assuming the problem is caused by the initial translateX value in the keyframe animation, but I'm not sure how to prevent the horizontal drag scrolling.
Here's a jsfiddle demonstrating the problem.
I appreciate any input.
Answer: Perhaps a javascript solution? How is the following:
function bindEvent(e, eventName, callback) {
    if(e.addEventListener) // new browsers
        e.addEventListener(eventName, callback, false);
    else if(e.attachEvent) // IE
        e.attachEvent('on'+ eventName, callback);
};

bindEvent(document.body, 'scroll', function(e) {
    document.body.scrollLeft = 0;
});


Windows: What could be the reason for a "paging file is too small" error even though there is plenty of physical memory available?

Question: In one of our applications, we received an error message indicating "The paging file is too small for this operation to complete" while the application was trying to load a DLL (a .NET assembly).
However, system metrics show there was plenty of physical (and virtual) memory available on the virtual machine. Unfortunately, we don't know the page file usage at that point. One specialty of the machine is that the page file is very small (3 GB, not OS-managed) when compared to the total physical memory (32 GB).
Why would we receive a page file error even though there is plenty of physical memory available?
This happened on a Windows VM managed by AKS (Azure Kubernetes Services), so we cannot simply change the page file settings. The application where the error occurred was running within a Kubernetes Pod on that VM.
Comment: `This happened on a Windows VM managed by AKS (Azure Kubernetes Services), so we cannot simply change the page file settings.` does the symptom occur on a  Windows system configured the same, and not in Kubernetes/Azure?
Comment: @GregAskew We cannot really reproduce the situation outside of the Kubernetes cluster, as the whole software system is designed for Kubernetes. I was hoping for general ideas on how that kind of error (paging file too small in the face of lots of physical memory available) could arise on a Windows Server system.
Comment: To whoever downvoted this issue, care to explain why, so I can improve the question?
Comment: `Why would we receive a page file error even though there is plenty of physical memory available?` Windows has a minimum page file size requirement. For a minimal page file, it requires that a small crash dump be selected.
Answer: We were able to do a few more experiments in the meantime and it turns out that hitting the container memory limit* also produces the ERROR_COMMIT_LIMIT error code (1455), which resolves to the message  The paging file is too small for this operation to complete. So, we were just misled by the message; the error was most likely caused by the application hitting its limits and had nothing to do with the paging file after all.
* The container memory limit is a Kubernetes concept which maps to the resource limits enforced by Windows Server Silos and Job Objects, see, e.g., here and here.
Answer: Windows best practice is to set the paging file size to equal to or greater than the total amount of available physical memory.
https://learn.microsoft.com/en-us/sharepoint/technical-reference/the-paging-file-size-should-exceed-the-amount-of-physical-ram-in-the-system
On how much did you set it?
Comment: As mentioned above, the paging file is set to about 3 GB (at 32 GB physical RAM). We cannot change this, the VMs are managed by Azure Kubernetes Services. Regarding the optimum paging file size: Thanks for the link! I've also found other recommendations such as https://learn.microsoft.com/en-us/troubleshoot/windows-client/performance/how-to-determine-the-appropriate-page-file-size-for-64-bit-versions-of-windows and . However, as we cannot change it anyway, it's probably moot.


Deleting items from a ListView using a custom BaseAdapter?

Question: I want the user to click a button ,
Remove item from list
I 've read a lot of questions, to remove the list item .
But I can not find any answer to my problem.
I do not know how to be able to structure my program
(According to the code below)
Anyone know what I need to add ?
java code:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_qusition);
    list=(ListView)findViewById(R.id.listView1);
    adapter=new Myadapter(getApplicationContext());
    String qustion=getResources().getStringArray(R.array.qustion);
    list.setAdapter(adapter);
 }

public class Myadapter extends BaseAdapter implements Filterable{

    LayoutInflater myInflater;

    public Myadapter(Context context) {
        myInflater=LayoutInflater.from(context);

        // TODO Auto-generated constructor stub
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return qustion.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
         final ViewHolder Holder;

        if(convertView==null)
        {
            Holder=new ViewHolder();
            convertView=myInflater.inflate(R.layout.item_custom_layout,null );
            Holder.qustion=(TextView)convertView.findViewById(R.id.text_qustion);
            Holder.delete=(ImageView)convertView.findViewById(R.id.imag_delete);
            Holder.heart=(ImageView)convertView.findViewById(R.id.imag_heart);
            Holder.share=(ImageView)convertView.findViewById(R.id.imag_share);

            convertView.setTag(Holder);

        }
        else
            Holder=(ViewHolder) convertView.getTag();
    Holder.qustion.setTextSize(size);
        Holder.qustion.setText(qustion[position]);

    //}
  Holder.delete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                //-----------delete item list

            }
        return convertView;
    }

Answer: You have an array qustion that represents the data in your adapter. What you would need to do is find out which index was deleted and remove that index from your array. This would be easier if your array was changed to an ArrayList. After removing the index call notifyDataSetChanged() in your adapter to update the view.
Comment: I have several buttons on a list item
Because of this , I can not use the Array List
Comment: Why can't you use an ArrayList? Your current code won't work anyway, qustion is declared in the scope of your activity's onCreate, it is not accessible in your adapter and you didn't even declare it as an array. Declare an ArrayList as a class variable to either your activity or your adapter and initialize it using the string array you retrieve from resources, then you can remove items from it.
Comment: Thanks a lot
Your comments ,
It helped me


Assuming n variables are conditionally independent given y, how do I compute p(y | x_1,...,x_n)?

Question: Referencing this question, I know that if $x_1$ and $x_2$ are conditionally independent given $y$ (big assumption), then
$$P(y | x_1,x_2) = \frac{P(x_1,x_2 | y)P(y)}{P(x_2 | x_1)P(x_1)}$$
$$ = \frac{P(x_1| y)P(x_2| y)P(y)}{P(x_2 | x_1)P(x_1)}$$
$$ = \frac{P(y| x_1)P(x_2| y)}{P(x_2 | x_1)}$$
How do I generalize to $n$ variables and compute $P(y | x_1,...,x_n)$? I don't know any of the priors, but I have all the single conditional probabilities (complete matrix)!

Summary

Known: $P(y|x_i), P(x_i|y)$, and $P(x_i|x_j), \forall i,j$
Assumption: $x_1,...,x_n$ are conditionally independent given $y$
Problem: Compute $P(y|x_1,...,x_n)$.

Any help would be appreciated!

UPDATE (reply to Xian):
So to further clarify my problem: I have a disease set $D=\{d_1,...,d_m\}$ and a symptom set $S=\{s_1,...,s_n\}$.
For a given disease, $d_i$, I know the probabilities of the symptoms, $p(s_1| d_i),...,p(s_n|d_i)$ (sparse).
For a given symptom $s_j$, I have probabilities $p(d_1 | s_j),...,p(d_m | s_j)$ (also, sparse).
Now, I want to compute $p(d_i | s_{\alpha_1},...,s_{\alpha_k}), \forall i\in[1:m]$, for $k\leq n$ (probability of each disease given a subset of symptoms).
If I understand your answer correctly, you're saying that for a given disease $d$, I can sample a synthetic patient with some symptoms based on the distribution of conditionals $p(s_j | d), \forall j$. But how would I incorporate $p(y|x_1)=p(d_i|s_1),\forall i$ into the sampling procedure so that I can account for the fact that, say, the common cold occurs more frequently than tuberculosis given cold-like symptoms?
Sorry for the confusion!
Comment: It seems to me that you need the full set of conditional probabilities $p(x_i | x_{-i})$, not just the pairwise conditional probabilities.
Answer: Since the $X_i$'s are independent given $Y$, the joint density of $(Y,X_1,\ldots,X_n)$ writes down as$$p(y)p(x_1|y)\cdots p(x_n|y)$$and hence the conditional of $Y$ given $(X_1,\ldots,X_n)$ is
$$\dfrac{p(y)p(x_1|y)\cdots p(x_n|y)}{\int p(y)p(x_1|y)\cdots p(x_n|y)\text{d}y}$$It simplifies into
$$\dfrac{p(x_1)p(y|x_1)p(x_2|y)\cdots p(x_n|y)}{\int p(x_1)p(y|x_1)p(x_2|y)\cdots p(x_n|y)\text{d}y}=\dfrac{p(y|x_1)p(x_2|y)\cdots p(x_n|y)}{\int p(y|x_1)p(x_2|y)\cdots p(x_n|y)\text{d}y}$$but I see no further simplification.
Comment: Thanks for the response @Xi'an. I don't actually have access to a dataset for this problem; however, I have the numerical values for the elements of the joint density $p(y|x_1),p(x_2|y),\cdots, p(x_n|y)$.

To numerically evaluate the integral in the denominator, would I just compute the joint density in the numerator for each possible value of $y$ and sum? Wouldn't I still be ignoring the prior in $dy$?
Comment: If you can evaluate the numerator, you can simulate from this distribution without knowing the value of the normalising integral in the denominator. This formula is correct for the conditional in $y$ : hence no you do not _ignore_ the prior.
Comment: My reply is long, so I updated the post!
Comment: If $Y$ has a discrete support, the integral in the denominator becomes a summation over all possible values $y$.


How did composers "test" their music?

Question: How did composers "test" their music, especially in multi-instrument works
(eg. chamber, orchestra) or in pieces for instruments they didn't know how to play?
Did they really have an orchestra (for example) next to them?
Now, we have DAWs and score-writing softwares that come with MIDI playback, but I'm really curious about the past.
Any answer is welcome.
Comment: Composers get things wrong all the time. There are countless examples of composers asking performers to do the impossible. Or sometimes it's not impossible but not idiomatic. Composers will fix these mistakes if they're made aware of them, but there are plenty of mistakes which are now permanent because the composer is long dead. If that piece is still part of the repertoire, then the "fix" is passed down by instrumentalists -- "in this piece, when you see x, just do y."
Comment: Keep in mind a DAW can let you do things that don't make sense for a real orchestra: play out of range, impossibly difficult passages, etc. In that sense a DAW is not necessarily a good test ground. Look for a book on orchestration. It should explain the conventions of instruments and give examples from real scores.
Comment: Towards the end of his life Beethoven was deaf and he still wrote the fantastic ninth symphony.
Comment: call a rehearsal?
Answer: Not all composers nowadays write using computers. Many still write by hand using ink or pencil.
Multi-instrument works (chamber, orchestra, etc) were written as either what's known as "piano-score" or "short-score". Many, many composers are / were pianists and so were able to check their music by playing through the piano score. Once they are satisfied with the music, they orchestrate it out to the size of the ensemble they're writing for.
To learn how to do this, a common practice at the time for students was to hand-copy well-known composers' music. From this practice they would learn what worked for different types of instruments. During those times, brass and woodwind instruments were not as technologically advanced as they are today, so many of the wind parts (especially brass) were not especially complicated (though there were obviously virtuosi on those natural instruments, thinking about Hadyn's trumpet concerto or Mozart's horn concerti).
Aside from these considerations, there are many sounds developed over the past century that weren't being used. For example, advances in technology have enabled composers to experiment with: sampling, recording, live-sound manipulation, electronic music, noise music, performance art, and multimedia art to name a few. As a consequence of science (i.e. electricity), many of these technologies did not exist and therefore the sounds / means of expression did not exist. This means a different level of experimentation, which means things are more standardized, which means things don't need to be checked as often.
If you're involved with music deeply enough and for long enough, you become very familiar with the instruments, their techniques, and the sounds that come from them, which brings me to my last point:
Experience. I've played horn though I wouldn't consider myself a horn player. When I write for horn, my experience tells me through my mind's ear how the horn will respond throughout it's range to different musical gestures. I don't need to go running to a horn player every time I write something for horn. That said, if I do write something and am not sure how it will come out, I'll reach out to a horn player for help; a whole orchestra is not needed.
Other composers have done / do / will do the same thing: use prior experience (mistakes) as a guide and ask questions of individual players when they need them. Many university programs offer orchestral "readings" for students, which can also offer invaluable feedback.
Comment: Oh, so _that's_ how Mozart and Beethoven did it!  Music was _simpler_ then!
Comment: @Nelson that statement about early pianos is incorrect.  Early pianos could play in many different keys, and the very name comes from the fact that the piano is intrinsically capable of playing at different dynamic levels.  You may be thinking of harpsichords, which are not pianos, but predated them, but those too could play in many different keys.  Temperaments permitting this were in use for hundreds of years before the invention of the piano.
Comment: @davidbak regardless of whether music was simpler, which I would argue is not true, composers were far better trained in those days than they are today.
Comment: @phoog - I agree that the music was not at all more simple, my point was misconstrued. Please see my comment reply to davidbak as well as my edited answer.
Comment: I thought the answer was pretty clear to begin with.  (Had I thought that davidbak's comment actually summarized your message, I would have addressed you explicitly as well in my response to him.)  The edit makes it clearer still.
Comment: A lot of instruments went through significant changes throughout the years. Early pianos are tuned to a single scale and do not have volume dynamic ranges.
Comment: @davidbak - Incorrect; music was hardly more simple; you've immaturely misconstrued my point (and I should edit my answer so it [my point] is more clear). Contemporary music incorporates a whole host of extended techniques that wouldn't have been / weren't used in previous periods. Also, composers incorporating electronic and other multimedia technologies are more likely to need to check their work throughout the process. This is what I meant by there being less "colors". The medium through which the music is expressed in no way affects how complex the actual musical material is.
Comment: @Neson - agreed with phoog here. You're likely thinking of precursors to the piano, but even then, those instruments could play in multiple tonalities. Rather, range, dynamic, and articulation possibilities on those instruments were more limited.
Comment: @jjmusicnotes Is it more likely that modern techniques *require* experimentation, or that modern techniques simply *allow* live experimentation to be possible? There are "do it right, once" and "get it right as you go along" strategies for almost any kind of creation, and a technique is typically chosen as a preference if multiple are available.
Comment: @jpaugh - that's its own interesting question: modern techniques typically require more experimentation; modern culture around new music in particular glorifies experimentation. Experimentation has *always* happened, though the historical rate was much slower. Technology has allowed people to constantly peek over the neighbor's fence, and thus, everything becomes compressed.
Answer: The more you listen to and work with music the more you "hear it in your head". After you become proficient at transcribing, it's perfectly possible to see a melody written out and "hear" it in your internal ear.
Doing the same for 2, 3 ... n voices is basically the same thing, just more of it (and of course requiring more practice and experience).
In fact, the real answer to this question varies by composer. Some had more or less a captive orchestra or choir to work with (like Bach for much of his career). Some like Beethoven couldn't even hear (eventually) and yet could write. Some worked mostly on piano, some (such as Tchaikovsky apparently) weren't particularly great at playing anything.
It's also instructive sometimes to look at scores (not only classical) and see how much, or often, how little, is going on. Sometimes there are many interwoven parts, but sometimes, although there is an orchestra, there is not much counterpoint happening. Then the artistry lies more in having a melodic idea which develops and remains interesting, and skill in orchestrating. Less is (sometimes) more.
In any case, it really comes down to the "internal ear" before anything else. Without this, you are unlikely to write anything that sounds much better than random as a start point.
Answer: First, I would note that any proficient classical composer likely knew the basics of how to play all the instruments being written for.  The composer may not have any great ability to perform on all instruments, but any good composer needs to understand how different instruments produce sound, where difficulties in execution arise (e.g., difficult fingerings, notes that will be more out of tune, etc.), as well as the capabilities of the ensemble being written for.
That's not to say that composers would always try out parts on said instruments themselves.  (They might do it, particularly for more difficult passages, perhaps even trying out a solo part with a skilled soloist on a specific instrument.)  But experienced composers, as noted in other answers, tended to be able "hear" music in their head.  It's not unlike how most people today commonly read written words without speaking.  Note that historically this wasn't always the case: there is some evidence that in the ancient word, reading silently was unusual and in some cases considered remarkable.  But obviously with practice most people can learn to read text and understand it without vocalizing it aloud.  Similarly, one can read music -- not only single melodic lines, but even large scores with many instruments, and understand them, knowing what they would sound like, without literally hearing them aloud.
I'd just add that a strong element of this is fluency in traditional music education, which gave lots of rules for producing music that "sounds good" by following technical principles.  For example, if one knows the detailed rules of renaissance counterpoint (as practiced by composers like Palestrina, and described in treatises such as those by the historical music theorist Zarlino), it's a lot easier to write music that will sound like good renaissance music simply by following the rules.  That's not to say there aren't other elements in making the music sound artistic and interesting, but simply following formulas and rules automatically will produce something that's likely to sound vaguely like "correct music" in that style.
Similarly, when it comes to other instruments and orchestras, composers were taught principles of orchestration: what instruments blend well together, what instruments contrast, how to create balance (dynamically, timbrally, etc.) within an ensemble, how to create well-voiced chords using different instruments, etc.  Most of these principles were at first passed down informally from teachers to students, but by the early 1800s, you had some teachers writing detailed books on orchestration.
Again, these principles can't guarantee that what you write will be interesting, but following these ideas and understanding these concepts will allow a skilled composer to create orchestral blends and interactions among the instruments that will generally sound competent.  Today, orchestrators for things like movie soundtracks often still make use of similar concepts: the actual "composer" for a movie may sketch out the ideas of melodies, themes, general instrumentation, and then a sketch of the overall piece, but orchestrators may fill in the details using standard principles.  Orchestrators in this case are often specialists, who worry about the actual details of real-world performance.  The trumpets and flutes playing together on a computerized score may seem fine, but in the real world, you might not be able to hear the flutes at all.  Or, what about the fact that wind players need to breathe?  It's easy to write a wind part that goes on forever on a computer, but it may not work in the real world.
Actual composers even today thus need to be able to evaluate music outside of computer simulation, particularly when writing for large ensembles.  My experience working with a lot of students who grew up in the era of computerized music writing is that they tend to write a lot of stuff that seems fine on the screen and in "playback," but could never work in a practical sense.  In some cases, things that sound reasonably good on computer will sound very different (or even bad) when executed on real-world instruments by real-world performers.
Still, composers did "test" their music in performance.  Today, we have a stronger sense of a finished "musical work" than was often true historically.  Composers in the past might be more likely to keep revising a work based on experience (and things that they noticed didn't work so well), but also based on the event, the specific ensemble including what players/singers were available, etc.  Look at the many versions of Handel's Messiah for example, where the piece was frequently altered from year to year based on what types of soloists might be present.  In the real world, the specifics of the performance -- even the specific players available -- can make a difference in what is most successful.
And it's not just historical composers that needed to "test" their music.  If you're orchestrating a score for a Hollywood film today, studio time with an entire orchestra is incredibly expensive.  You can't afford to realize in the middle of a studio session: "oops, this blend doesn't sound anything like it does on my computer" or "wow, the harmonics of that instrument are conflicting with those other instruments in the higher register" or "I didn't realize a bassoon will have real difficulty playing that particular trill, followed by that leap."  Such mistakes can literally cost hundreds or thousands of dollars in lost time.  That's not to say they never happen -- studio sessions will make changes as they are recording.  But skilled composers and orchestrators can avoid many of these problems just from their knowledge of "what sounds good" in the real world and what works practically, regardless of what a computer output might sound like.
Comment: "I didn't realize a bassoon..."   Yeah tell that to Stravinsky  :-)
Comment: Hi. Nice answer. I would like to ask though, where can I learn that " music education that makes it sounds good" ? It seems like a must learn principal for a composer. Thank you.
Answer: Some write with a piano to test out rhythms and chord progressions.  Some just hold all the sonorities in their heads.
But to your point about orchestral works,  I've had the pleasure of playing pre-publication pieces at summer music camps or other venues, often conducted by the composer.  The composer often modifies the final version after such "test performances."  In fact, if you read through enough "liner notes" you'll find that many classical composers rearranged symphonies or operas after initial published, public performances.
Comment: @jjmusicnotes  I fail to see the correlation between "always changing their mind" and not keeping music "in their head."   those are orthogonal traits.
Comment: I've read  about Debussy who made "his" orchestra crazy when testing and changing the orchestration during the final practice.
Comment: Beethoven was one who held it all in his head - he had to, towards the end. Makes him even more special, in that he actually could never have heard a lot of his work in later years, but it obviously worked.
Comment: @Tim - Have you seen any scans of Beethoven's manuscripts? They portray someone who was restless and always changing their mind; hardly someone who keeps the music "in their head". Mozart's manuscript on the other hand is very clean; which indicates that he knew exactly what he wanted and wrote it all out correctly the first time.

How did composers "test" their music?


Can I bounce the ball after it is rolling in Basketball?

Question: In Basketball, let's say I am dribbling and involuntarily the ball hit my hand wrongly and starts rolling (not bouncing). If I tap it from above and get it bouncing again, is that a double dribble? According to the links below it seems that re-bouncing a rolling ball is allowed.
Also, does it make a difference if the ball is rolling or just sitting on the floor when I hit it to make it bounce again?
https://en.m.wikipedia.org/wiki/Double_dribble
NBA violations
http://official.nba.com/rule-no-10-violations-and-penalties/
Dribble definition in NBA
http://official.nba.com/rule-no-4-definitions/#Dribble
FIBA says
http://www.fiba.basketball/documents/official-basketball-rules.pdf

Art. 24 Dribbling
  24.1 Definition
24.1.1 A dribble is the movement of a live ball caused by a player in control of that ball who throws, taps, rolls or bounces the ball on
  the floor.
24.1.2 A dribble starts when a player, having gained control of a live ball on the playing court throws, taps, rolls or bounces it on the
  floor and touches it again before it touches another player.
A dribble ends when the player touches the ball with both hands
  simultaneously or permits the ball to come to rest in one or both
  hands. During a dribble the ball may be thrown into the air provided
  the ball touches the floor or another player before the player who
  threw it touches it again with his hand. There is no limit to the
  number of steps a player may take when the ball is not in contact with
  his hand.

and about Double Dribble:

24.2 Rule A player shall not dribble for a second time after his first dribble has ended unless between the 2 dribbles he has lost control of
  a live ball on the playing court because of: • A shot for a field
  goal. • A touch of the ball by an opponent. • A pass or fumble that
  has touched or been touched by another player.

Reading the definitions above, it seems to me that when the ball is rolling on the floor (without bouncing) the dribble has not ended, therefore it wouldn't be double dribble to tap it and get it bouncing again
Answer: To my experiences, it is not considered to be a double dribble according the FIBA rules. I have this action being performed several times during a game when I was coaching. None of the referees did call a foul.
A more objective explanation is this: The rolling of the ball is also being considered as being part of the first dribble, so resuming the dribble without deliberately stopping the ball will not stop the dribble. Even if the ball has stopped rolling, the payer hasn't stopped the ball with its hands.


Comparar linhas de um arquivo txt em Python

Question: Estou tendo dificuldades em criar um script em Python para comparar linhas de um arquivo txt.
Basicamente, preciso percorrer um arquivo e verificar se um campo é igual a outro, lembrando que não pode se comparar toda a linha, e apenas uma parte, no caso o que eu desejo comparar é o primeiro valor antes dos dois pontos(:), segue o código:
from collections import Counter
arq = open("arquivo.txt")
linhas = arq.readlines()
for linha in linhas:
    x = linha.split(':')
    print(Counter(linhas)[x])

Estou recebendo o erro: TypeError: unhashable type: 'list'
Desse jeito, eu iria verificar se algum campo foi repetido, e então deletaria essa linha.
Answer: resultado = {}

with open('arquivo.txt') as arq:
    for linha in arq.readlines():
        x = linha.split(':')
        if len(x) == 2 and not x[0] in resultado:
            resultado[x[0]] = x[1]

with open('arquivo.txt', 'w') as arq:
    for i in resultado:
        arq.write(f'{i}:{resultado[i]}')

Esse novo codigo cria um dicionário e conforme vai lendo o arquivo adiciona (se não existir essa key) um item no dicionario que a key seria antes do ":" e o valor seria depois
depois disso ele abre o arquivo em modo de escrita (sobrescrevendo o arquivo original), passa por cada item do dicionario e escreve.
Answer: O método split retorna uma lista! na linha x = linha.split(":") a variável X recebeu então um valor de lista... quando você escreveu print(Counter(linhas)[x]) voce literalmente criou uma nova lista com um valor unico de outra lista dentro dela...
é como se vc tivesse feito [ [ X ] ]
você poderia deixar assim:
with open('arquivo.txt') as arq:
   linhas = arq.readlines()

for linha in linhas:
    x = linha.replace('\n', '').split(':')

    if len(x) == 2:
        if x[0] == x[1]:
            print(x[0])

primeiro eu utilizei o with junto com o open, essa é uma boa prática que impede que seu arquivo seja corrompido.
Armazenei as linhas em uma lista e rodei um for passando por elas e atribui na variavel linha
Rodei o método .replace('\n', '') para impedir que ele considere o "enter" no final da linha como um carácter e acabe atrapalhando o funcionamento do código
Rodei o método .split(':') que transformou a string em uma lista
Realizei um if len(x) == 2 para saber se realmente tinha um ":" na linha
Por ultimo realizei um if x[0] == x[1] para então saber se as duas divisões da string eram semelhantes!!
Comment: Muito obrigado pela solução, porém, acredito que tenha entendido errado, eu preciso comparar uma linha com a outra, exemplo:

123:Lucas
123:Silva
1234:Teste

No caso, a linha 2(123:Silva), seria deletada, pois já tem o ID 123 na linha 1, então ficaria apenas a linha 1 e 3 no arquivo de texto. Eu preciso comparar as linhas, e não comprar os valores de cada linha.