Advice: 'Real' Musical Ability?

Question: I have been playing my instrument for almost 11 years now; I have mastered the technique, I can play my scales and chords forwards, backwards and upside-down, sightread most reasonable music, identify isolated intervals, scales and chords with reasonable fluency, understand the fundamentals of tonal harmony, and have played a large repertoire of music. In short, I have done everything I was supposed to do, although, of course, these things are not perfect.
However, I do not feel that I have 'real' musical ability - I feel that I still lack a 'natural' connection between what I hear, what I read and what I play. I cannot 'hear' real music on the page without playing it, I cannot naturally 'translate' real music that I hear (either aurally or mentally) into my playing, I cannot 'see' real music that I hear as music on the page.
Does an experienced musician have advice on moving past this phase, from ability in drills to  'real' musical ability? If this can be practised, how should it be done?
Comment: You are missing your heart.  What do you *feel*?  You didn't once mention what music makes you feel.  If you cannot play it without looking at it, you don't know it in your heart.  If you don't know it in your heart, you can't really feel it.  If you can't feel it, you can't connect to it.  If you can't connect to it, how is a listener going to?
Comment: There's a thing, I forget what it's called, from psychology. It's basically people who think they are awesome at something usually aren't, and people who put a lot of work into something and still feel like they aren't that great are usually a lot better than they think they are, at least from the point of view of a naive observer. This might be part of your feeling like you're missing something in your ability.
Comment: @ToddWilcox  Dunning Kruger effect: https://en.wikipedia.org/wiki/Dunning%E2%80%93Kruger_effect
Comment: What styles of music are you playing?
Answer: It sounds like you actually have quite a bit of "real" skill already. I'm not sure there's such a thing as "fake" skill. Are you sure you might not have a touch of Imposter Syndrome going on?
But beyond that, you mention that where you feel that you lack is in being able to translate back and forth between what you see on a page and what you hear in your head. So for example, you might see two notes on adjacent spaces, and recognize them as an interval of a third, but you can't hear a third in your head?
The solution to this is to learn ear training (and the related skill of audiation), which I notice is conspicuously absent from your list of technical and theoretical skills. There are a number of questions on this site about the topic, but here are two to get you started.

What are the most effective ear training methods?
How do you practice Audiation (playing music in your head)?

Personally, I would recommend learning to sight-sing as an excellent way to start learning this skill. Singing has a way of exposing what music is in your head, without the technical difficulties of playing an instrument getting in the way.
Once you learn ear training, you'll also be able to improvise better, because you'll be able to imagine a certain pattern of notes being played, and then be able to figure out which notes you should play to realize that pattern on your instrument.
Answer: Whilst music, obviously, can be played and enjoyed on your own, it's a bit like communication. Needs someone else. Try to find someone or some two or three others to play with. Find ways to share/split songs up between you, so you become part of a jigsaw, part of a team. This will help to understand how the music is put together, how it all fits, without having to do it all yourself. It'll give some breathing and thinking space. It's also far more enjoyable ! Playing football/tennis/etc. is no fun on your own !
Answer: I think you've misunderstood what technique is. Technique is a tool; it is a means to an end and that end is the embodiment of an 'artistic image'. Heinrich Neuhaus, defines 'artistic image' as "the content, meaning and poetic substance, the essence of music." Neuhaus advocates that the student should learn to grasp the artistic image in the very early stages of studying music as it is the "what", the artistic image, that will determine the "how", the technique. According to the great pedagogue Tobias Matthay, it is counter-productive to dissociate technique from its purpose. The routine hammering through an arbitrarily prescribed set of scales and arpeggios is not the most effective means of attaining technique. I'd say you've spent too many years being counter-productive and the damage is probably done but who knows...maybe you can turn it around. Watch some masterclasses with Benjamin Zander on youtube. If you don't find them moving, if he can't help you understand and connect with music, then you are probably a zombie. Stop "playing" the music like it's some artefact. Experience it.
Comment: There are precious few absolutes in music. Just because someone does not connect with what Benjamin Zander is teaching, does not mean that he/she can not produce great music.
Comment: @Meaningful Username der
Answer: I was in a similar boat, and for me, the mystery thing you're looking for is "aural awareness". If I could go back in time to little me, I would have me working on it much sooner, much more. What has worked for are the following:

ear training on your instrument: get good at playing back any random set of pitches. I use "GoodEarPro" on the ipad. It's great
play simple tunes by ear starting on random pitches. Start with xmas carols, beatles songs, and eventually you'll build up to tricky stuff like Duke Ellington and Cole Porter
transcribe by ear (without writing it down). Find recordings you like, learn it by ear, and practise playing with the recording  perfectly, and by memory/ear only. This will help you "get inside" the music like nothing else.

Do that for an hour or two a day for a year and your "real musicianship" will skyrocket, given that you already have the other foundations in place. It's a tragedy of modern music education that the most important thing can be the least stressed for years. Part of the issue is that it's so simple there's not much to teach, just tons to do. If you read historical accounts from way back, it was normal to have tons of ear training early, and it's how all the old time jazz greats learnt. Hope that helps and good luck!

Advice: 'Real' Musical Ability?


How to achieve this layout on all devices excluding tablets

Question: I am not worried about tablets at the moment, just android phones. I have some pay as you go LG phone that I use to develop on. I have a frame layout with a VideoView and a WebView in it.
My XML file defined the width and height at specific pixels and that worked fine for testing on my one device. I tried it on another device which had a larger screen and they dont fill the window like on my go phone.
I was wondering how I can fill the top half of the screen with my video and the bottom half with and image. I tried layout_width as match_parent, but then I wasn't sure how to define the height. Here is the layout I want to achieve on all devices.

and my layout.xml
<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/mobile_vforum_bg"
    >
    <VideoView
        android:id="@+id/vidPlayer"
        android:layout_width="320px"
        android:layout_height="240px">
    </VideoView>
    <WebView
        android:id="@+id/slideHolder"
        android:layout_width="320px"
        android:layout_height="240px"
        android:layout_gravity="bottom">
     </WebView>
</FrameLayout>

Obviously I cant use a pixel amount here, so what are my options? Thank you and I hope my question was clear enough.
Answer: Use a vertical linearlayout, and specify layout_weight="1" for both views.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/mobile_vforum_bg">
    <VideoView
        android:id="@+id/vidPlayer"
        android:layout_weight="1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    </VideoView>
    <WebView
        android:id="@+id/slideHolder"
        android:layout_weight="1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
     </WebView>
</LinearLayout>

Answer: Why are you using a FrameLayout?  That is meant for when you want to overlay views. In this case a simple LinearLayoutwith orientation="vertical" should do the trick.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/mobile_vforum_bg"
    >
    <VideoView
        android:id="@+id/vidPlayer"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    </VideoView>
    <WebView
        android:id="@+id/slideHolder"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
     </WebView>
</LinearLayout>

Comment: That is not going work across all phones.  If you need the FrameLayout for something else, than just put these two items within a LinearLayout within the FrameLayout.
Comment: Im pretty sure I need to use FrameLayout. I removed a ListView that sits on top of both VideoView and WebView. It is opened via the Menu button. I removed it because I didn't think it was relevant to the question, but apparently I was mistaken. So with that said, I guess I am overlaying views.
Comment: I think I found the answer. I kept my layout the same, but rather than `320px` I did `320dip` and that seems to solve the issue across all the different resolutions


Why does ${\rm cov}(Y_{ij}, Y_{ik}) = \sigma_u^2$ in the model $Y_{ij} = \mu + u_i + e_{ij}$?

Question: Consider $Y_{ij} = \mu + u_i + e_{ij}$ where $\mu$ is a constant and $u_i ∼ N(0,\sigma_u^2
)$ is the subject $i$ random effect which is independent of the error term $e_{ij} ∼ N(0,σ_e^2)$. I can't figure out why $${\rm cov}(Y_{ij}, Y_{ik}) = \sigma_u^2$$
Can anyone please explain?
Answer: Well,
$$ {\rm cov}(Y_{ij}, Y_{ik})
= {\rm cov}(u_{i} + e_{ij}, u_{i} + e_{ik})
$$
since the constant term, $\mu$, does not affect variances or covariances. By the bilinearity of covariance we have
$$ {\rm cov}(Y_{ij}, Y_{ik})
=
{\rm cov}(u_{i}, u_{i})
+ {\rm cov}(u_{i}, e_{ik})
+ {\rm cov}(e_{ij}, u_{i})
+ {\rm cov}(e_{ij}, e_{ik})
$$
By independence of $u_{i}$ and each $e_{ij}, e_{ik}$ and independence between $e_{ij}$ and $e_{ik}$ (which must be assumed for this model to make sense), the 2nd, 3rd and 4th terms are all zero above (since independence between two variables implies that their covariance is 0). So,
$$ {\rm cov}(Y_{ij}, Y_{ik})
=
{\rm cov}(u_{i}, u_{i})
= {\rm var}(u_{i}) = \sigma^{2}_{u}

$$
Comment: To cover the case when $j=k$, you may add a Kronecker delta to Macros's answer: $\mathrm{Cov}[Y_{ij},Y_{ik}]=\sigma^2_u+\sigma^2_e\,\delta_{jk}$.
Comment: or you could just note that $${\rm cov}(Y_{ij},Y_{ij}) = {\rm var}(Y_{ij}) = \sigma^{2}_{u} + \sigma^{2}_{e}$$
Comment: You are right. I'm just pointing a way to make the formula work for every $i,j,k$.


What is the probability that a contestant is a guitarist? The events are independent?

Question: $50$ pianists, $30$ violinists, and $20$ guitarists take part in a music competition.
$10\%$ of the pianists, $33\%$ of the violinists, and $10\%$ of the guitarists attend this contest for the first time.
a) Select at random a contestant who attends the competition for the first time.   Show that the probability that this contestant is a guitarist is (approximately) $0.118$.
b) Consider the events "the contestant is a guitarist" and "the contestant attends the competition for the first time", are these events independent?
Solve:
a) This what I did: I think that I have to calculate the probability that the contestant is a guitarist given that he partecipate to the competition the first time,
; $P(G|F)=\frac{P(G\cap F)}{P(F)}=\frac{0.1}{0.169}=0.59$. Considering $P(F)=\frac{0.1*50+0.33*30+0.1*20}{100}=0.169$ the percentage that a contestant is going for the first time, $P(G)=\frac{20}{50+30+20}=0.2$ the probability that a contestant is a guitarist, and $P(G\cap F)=\frac{0.1*20}{20}=0.1$ the probability of the intersection of the guitarists than are going for the first time. The result is quite different from the answer, where I'm wrong?
b) If two events are independent we know that: $P(G\cap F)=P(G)*P(F)=0.2*0.169=0.0338\neq0.1$. So in my opinion the two events are dependent, right?
Thanks in advance!
Comment: For $a$, did you mean $.188$?
Comment: "30  violinists"..."33 of the violinists"????
Comment: @JohnDourma yes, it should be the correct probability
Comment: @DavidG.Stork sorry, I forgot the %, now it is correct! :)
Comment: In $P(G)$ you calculate the probability that a contestant is a pianist, not a guitarist
Comment: @user289143 you are right, corrected
Answer: $P(G \cap F)=0.02$ since there a $2$ guitarists attending for the first time out of $100$ contestants.
$P(F)= \frac{0.1 \cdot 50 + 0.33 \cdot 30 + 0.1 \cdot 20}{100} \sim 0.17$
$P(G|F)=\frac{P(G \cap F)}{P(F)}=\frac{0.02}{0.17} \sim 0.118$
For part b) $P(G) \cdot P(F)=0.2 \cdot 0.17=0.034 \neq 0.02 = P(G \cap F)$ , hence the events are dependent
Comment: Thanks for the answer! Now it's clear :)


Error parentkey and childkey are identical in Stimulsoft

Question: I want to created a master-detail Report.
I have two classes PayStub & Payments that payments have foreignkey of PayStubId.
public class PayStub
{
 public int PayStubId { get; set; }
 public int Code { get; set; }
 public string Name { get; set; }
}
public class Payment
{
 [ForeignKey("PayStub ")]
 public int PayStubId { get; set; }
 public  PayStub PayStub { get; set; }
 public int Amount{ get; set; }
 public string Description{ get; set; }
}

I've tried two ways:

Business object.Insert parent business object & child business object and in wpf.
report.RegBusinessObject("PayStub", payList);
report.RegBusinessObject("Payments", paymentList);

this show master and don't show detail.

DataTable.Insert two DataTable and a relation for this.

in wpf:
report.RegData("PayStub", payList);
report.RegData("Payments", paymentList);

I get error parentkey and childkey are identical.
Answer: I change models like this.
public class PayStub
{
public int PayStubId { get; set; }
public int Code { get; set; }
public string Name { get; set; }
public List<Payment> Payments{ get; set; }
}
public class Payment

{
   [ForeignKey("PayStub ")]
   public int PayStubId { get; set; }
   public  PayStub PayStub { get; set; }
   public int Amount{ get; set; }
   public string Description{ get; set; }
   }
and set payments value in PsyStubList.
and set BusinessObject only for PayStub
report.RegBusinessObject("PayStub", payList);


If a Rails model has_many children, how do I store the id of the first?

Question: I'm new to Rails, so it's possible I'm overlooking something simple.  I have a Rails model called a story.  Each story has_many segments, and each segment belongs_to a story.  I use the same form to create both the story and its first segment by using a fields_for section of the form and setting the story model to accepts_nested_attributes_for :segments.  I am currently able to use the form to create both a story and a segment simultaneously.
The problem is that each story also needs to store the id of its first segment, but when I'm saving the story, the segment hasn't yet been saved, so it doesn't yet have an id to store in the story, and I haven't been able to find a handle for the segment after the form is submitted so that I can save the segment first before the story is created.  So my question is how do I save a record of the first_segment_id inside the story?
The following code may be relevant:
in app/models/story.rb
class Story < ActiveRecord::Base
    attr_accessible :segments_attributes
    has_many :segments
    accepts_nested_attributes_for :segments
end

in app/models/segment.rb
class Segment < ActiveRecord::Base
  attr_accessible :words
  belongs_to :story
end

in app/views/stories/_ form.html.erb
<%= form_for(@story) do |f| %>

  #...stories fields...

  <%= f.fields_for :segments do |segment_form| %>

      <%= segment_form.label :words %>

      <%= segment_form.text_area :words %>

  <% end %>

    <%= f.submit %>

<% end %>

in app/controllers/stories_ controller.rb
  def new
    @story = Story.new

    @segment = @story.segments.build

    # If I try replacing the above with @segment = @story.segments.create
    # then I get the error message "You cannot call create unless the
    # parent is saved," which is problematic because I need to find some way
    # to get the id of @segment to save in the parent story, but the segment
    # won't have an id until after it has been saved.

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @story }
    end
  end

  def create
    @story = Story.new(params[:story])

    #  @segment.save
    #  @story.first_segment_id = @segment.id
    #  If I uncomment the above two lines, I get the error message
    #  "undefined method `save' for nil:NilClass".  It appears that
    #  @segment hasn't been passed from the "new" method above to
    #  this method as a handle of the first segment created, so I'm not
    #  able to save it to get an id for it before saving the story.
    #  Is there some way to save the segment here?

    respond_to do |format|
      #...if @story.save...
    end
  end

The params hash submitted by the form looks something like:
{ "story"=>{ Various_other_story_fields,
 "segments_attributes"=>{"0"=>{"words"=>"dfsdsa"}}},
 "commit"=>"Create Story"}

Is there a way to save the first segment's id in the story?  I think perhaps I need to add a before_create inside my story model instead, but I'm not sure how do to this.
Answer: I would approach this differently, adding a numeric sort_order column to Segment so that you're not relying on Segment ids to determine what order they go in. Then you can define something like the following on your Story model rather than explicitly referencing the first segment in the database:
def first_segment
   segments.order(:sort_order).first
end

If you're certain you need to store the first segment ID in the story, you can .save the story so that it knows its ID, saves its children, and knows their IDs. Something like:
def create
   @story = Story.new(params[:story])
   @story.save # Save the story and its child segment so that they both have IDs
   @story.first_segment_id = @story.segments.first.id
   @story.save
   ...
end

Comment: I don't think the second way you suggest will work.  It tries to get the id of the segment before that segment has been saved, at which point the segment doesn't have an id.
Comment: +1 The first way you suggest could work, and it has directed me toward the even simpler method of just using segments.first (because the first one created should always be the one with the first id, and in my case, the order doesn't change)...I can't believe I've been overlooking that for days, but then I am *very* new to Rails.  However, the thing that concerns me about calling the .first method every time is that it's inefficient. It is something that will be done quite frequently, so if possible I'd still like to find a way to store the individual id.
Comment: Sorry, I should've made it clearer that that code is intended to run after you've already saved the story (without a foreign key yet) and the segment once. But yes, using the IDs as a sort can work as long as you don't need to change the sorting. I don't think that will be inefficient: I suspect most DB servers are smart enough to just jump to the first record in the clustered index that matches the foreign key.
Comment: To make that second code block run automatically after the story is saved, where would you place it?  Toward the end of the create method in the controller?  In an after_save callback in the model?
Comment: Yes, that works.  I'm quite surprised to find that you can save a story a second time without having to pull it from the database again.  Saving it the first time seems to have populated the local variable with the segment id.  Interesting.
Answer: You should be able to do something like:
class Story < ActiveRecord::Base
    attr_accessible :segments_attributes
    has_many :segments
    has_one :first_segment
    accepts_nested_attributes_for :segments
end

def new
    @story = Story.new

    @segment = @story.segments.build
    @story.first_segment = @segment
    ...

You'll have to add story_id to your segment table.
Comment: So if I'm understanding you correctly, first_segment would be its own model??  I'm not really getting a full picture of how it would relate to the other models.  Can you please be a bit more explicit?
Comment: It's a has_one relationship, so the foreign key is in the owned model (see http://guides.rubyonrails.org/association_basics.html#the-has_one-association). Due to the way rails implements associations, what this does is just create a new relationship between the records in the db. The only caveat is that once the story is saved, Story#first_segment and Story#segments.first will have the same data but will NOT be the same object
Comment: Haha, the page you link to is all-too-familiar.  (I've been staring at it for most of today.)  +1 for suggesting a way that could work, but if possible I'd like to find a way that works without having to create an extra model.  I may need to update the segment, so storing them in two places is less than ideal.  Also, each segment has a fair chunk of text associated with it, so storing it in only one place would be best for memory.
Comment: You don't need to create a new model. first_segment uses your existing Segment model.


Bwv 639 Bach/Busoni note length and symbols

Question: I am currently spending some time with this piece of music and I am a bit confused as to how long I should hold some of the notes and what some of the symbols mean.
In blue: Should i repeat/hold the lowest F?
In red: How long should I hold the Ab?
In yellow: Repeat/hold F?
In green: What does this connecting line between the notes mean?

Thank you
Comment: Yes that does look odd doesn't it.  It might be worth looking at some performances on YouTube (or elsewhere) and see what the "experts" do.
Comment: Good question - good answer of Lars Peter! I can't explain the ties, but imaging an arrangement I would keep an I at them distributing those notes to the different voices in a setting for SATB.
Comment: Blue is a tie: the note is repeated by the thumb but not by the pinkie. Yellow is a tied finger change: left thumb takes over from right thumb without repeating the note.
Answer: It is music original written for organ where you have more than one manual plus pedals. Busoni made piano editions of many of Bach's organ pieces and your image shows Busoni's piano version.
Maybe it can help to understand the voices in the music by looking at Bach's original and thereby understand what is going on. Below is an image from Bach's handwriting and an image where the 3 parts are written in 3 staffs. The sheet music can be found on IMSLP on this link: BWV 639
Fraction from BWV 639 Bach's handwriting:

Fraction from BWV 639 Bach, the three parts notated in three staffs:
Answer: The blue circled tie is likely a slur because the german text under it says "bass smooth and stately" and the slur reinforces the technique you should be following for the bass line of the piece.
the red circled tie is a slur from the a to the g, including the stemmed down f.
the yellow circled section:
 - first tie is a slur from the bass note to the f so the high f is not sounded twice and specifically played after the low f.
 - second tie is a tie so the high f is still only sounded once
the green circled section contains another slur so the high f is not sounded twice and specifically played after the low f.
Comment: Agreed, except blue is almost certainly a tie (from style comparison to the other ties and slurs) for the lower note (restrike the higher though).


Como incrementar uma variável sob determinada condição

Question: Estou com um probleminha para resolver em SQL.
Necessito incrementar uma variável sel2 a partir de uma condição definida em sel1, por exemplo:
linha | sel1 | sel2
1     |  1   |  1
2     | -1   |  -1
3     | -1   |  -2
4     |  1   |  1
5     |  1   |  2
6     |  1   |  3
7     | -1   |  -1

assim por diante
tentei resolver por meio do seguinte código:
SELECT t1.linha ,
       t1.sel1 ,
       SUM(t2.sel1) sel2
FROM #A AS t1
INNER JOIN #A AS t2 ON t1.linha>= t2.linha
GROUP BY t1.linha,
         t1.sel1
ORDER BY t1.linha ASC

No entanto, o resultado incrementa acumulativamente, assim:
linha | sel1 | sel2
1     |  1   |  1
2     | -1   |  -1
3     | -1   |  -2
4     |  1   |  2
5     |  1   |  3
6     |  1   |  4
7     | -1   |  -3

O fato é que não consegui obter o resultado esperado. Será que alguém  teria alguma ideia par a solução.
agradeço
Answer: Boa tarde, isto pode ser feito desta forma:
create table #tmp1 (Linha int, Sel1 int, Sel2 int)
go

insert into #tmp1
            select Linha = 1, Sel1 = 1, Sel2 = 0
    Union   select Linha = 2, Sel1 = -1, Sel2 = 0
    Union   select Linha = 3, Sel1 = -1, Sel2 = 0
    Union   select Linha = 4, Sel1 = 1, Sel2 = 0
    Union   select Linha = 5, Sel1 = 1, Sel2 = 0
    Union   select Linha = 6, Sel1 = 1, Sel2 = 0
    Union   select Linha = 7, Sel1 = -1, Sel2 = 0
go

select * from #tmp1

declare @sel2 int = 0
update  #tmp1
    set Sel2    =   @sel2
    ,   @sel2   =   @sel2 + Sel1

select * from #tmp1

Answer: Agradeço a resposta
É interessante, no entanto o problema persiste
o caso é que a variável "sel1" é previamente definida (é ela que define a condição), se o valor seguinte é igual ao anterior, soma com o anterior, se for diferente, teria que tomar aquele valor como o início da contagem, por exemplo:
linha | sel1 | sel2
1     |  1   |  1
2     | -1   |  -1
3     | -1   |  -2
4     |  1   |  1
5     |  1   |  2
6     |  1   |  3
7     | -1   |  -1
.     |  .   |  .
.     |  .   |  .
.     |  .   |  .
Não sendo fixado o valor para "linha"
executei o código que sugeriu, mas não deu certo


Task List Throws "Collection was modified; enumeration operation may not execute."

Question: Creating a list of Tasks to run parallel like this:
<code>if (call.Item.PictureDetails != null)
{
    List<Task> lstTasks = new List<Task>();
    foreach (var url in call.Item.PictureDetails.PictureURL.Cast<string>().ToList())
    {
        var newTile = AddNewPicTile(url);
        lstTasks.Add(Task.Run(() => {
            UploadPicture(newTile);
        }));
    }
    // Run all pic upload tasks in parallel...
    await Task.WhenAll(lstTasks);
}
</code>
Execution throws "Collection was modified..." exception but I can't figure out why.    I use similar code to this elsewhere in my app where I perform a while() loop that reads data from a database and it works fine.   Like this...
<code>        SqlDataReader rdr = cmd.ExecuteReader();
        if (rdr.HasRows)
        {
            while (rdr.Read())
            {
                RadTileElement newTile = AddNewPicTile(rdr["PictureUrl"].ToString());   //...must create this var here otherwise we won't be able to access rdr from a background thread (it will be closed by then)

                lstTasks.Add(Task.Run(() => {
                    UploadPicture(newTile);
                }));
            }
        }
        rdr.Close();
    }
    conn.Close();
}

// Run all pic upload tasks in parallel...
await Task.WhenAll(lstTasks);
</code>
What is it about the string list that could cause it to yell at me like that?
Comment: *but I can't figure out why* - because something somewhere is modifying the collection while something somewhere is enumerating it. Which collection is complaining? Don't forget that enumerations happen that you cannot see; `ToList()` enumerates, for example
Comment: Try: `List list = call.Item.PictureDetails.PictureURL.Cast().ToList(); foreach (var url in list)`
Comment: @PoulBak - I did try that syntax with no change in result.
Comment: @CaiusJard - it's not clear which collection is complaining.   Looking at the call stack, it's in   mscorlib.dll!System.Delegate.DynamicInvokeImpl and a bunch of other system level objects...tracing backward all the way to my calling method (which has no collections).     So I'm assuming it has something to do with the List collection that is executing from Task.WhenAll()
Comment: Post the stack and the definitions of AddNewPicTile and UoloadPicTle. Do any of these methods called here use a shared list? If you turn on "break when thrown" for all exceptions (debug menu>> windows >> exception settings >> tick next to CLR exceptions) does va break at a different place?
Answer: Actually - problem was not related to List.  Not even in the code posted.    Thanks to Caius Jard who got me looking elsewhere for it.


Proving that 3 set statements are equivalent

Question: Let $A$ and $B$ be (non-empty) sets and $f:A\rightarrow B$. Prove that the following statements are equivalent.
a) $f$ is one-to-one.
b) There is a function $g:B\rightarrow A$ that satisfies $(g \circ f)=I_A$.
c) If $h:C\rightarrow A$ and $k:C\rightarrow A$ satisfy $(f \circ h)=(f \circ k)$ then $h=k$.
Apologies in advance if my formatting is not ideal. Note "o"=composition
Thanks!!
Comment: What parts have you done so far?
Comment: @DonAntonio I'm struggling with it overall. I know my definitions, just confused how to connect them.
Answer: a) $\implies$ b)
Since $f: A \to B$ is an one-to-one, it is a bijection onto its image.   Hence, there is an inverse $h: f(A)  \to A$.  Choose a point $x \in A$.   Define $g: B \to A$ by
$$
g(y) =
\begin{cases}
h(y) && y \in f(A) \\
x && \mbox{else}
\end{cases}
$$
Then $g\circ f = I_A$.
Answer from Left Inverse: An Analysis on Injectivity
b) $\implies$ c)
Suppose we have $f\circ h = f\circ k$. Then, applying $g$ from b) to both sides, we get
$$g \circ f\circ h = g\circ f\circ k$$
$$h = k$$
c) $\implies$ a)
Assume $f(a) = f(b)$ with $a \neq b$. Then define
$k,h: A \rightarrow A$ with
$$k(x) := \begin{cases} b &&x=a \\
a &&x = b\\
x &&\mbox{ else}\end{cases}.$$ Take for $h:= I_A$. Then we have $f\circ k =f \circ h$ but $f \neq h$.
Answer from: How to prove that monos are injective?
Comment: Did you use the "axiom of choice" method for a=>b?
Comment: Makes sense. Thank you for all the help
Comment: I don't believe so, no. But I think you need to use the axiom of choice to prove that if a function is onto (i.e. surjective) then it has a right-inverse
Comment: I'm confused about the c)==>a) part of the proof
Comment: What's $f(g(a))$? From how we defined $g:A\rightarrow A$, it's $f(b)$. As we assumed $f(a) = f(b)$, we get that $f(g(a)) = f(a).$ Similarly, $f(g(b)) = f(b)$ (check this!). As $h$ is the identity on $A$, $f(h(a)) = f(a)$ and $f(h(b)) = f(b)$. For any other point $x$ in $A$, $f(g(x)) = f(x)$ and $f(h(x)) = f(x)$. So $f\circ g = f\circ h$, because the two functions agree on all points in their domain. However, $g$ is not equal to $h$, because $g(a) = b \neq a = h(a)$. Feel free to ask if this isn't clear
Comment: I understand what you did here. But how does this show that f is one-to-one?
Comment: The definition of one-to-one is that whenever $f(a) = f(b)$, we have $a=b$. Here, we started by assuming $f(a) = f(b)$ and $a\neq b$ and then arrived at a contradiction. Hence, our assumption must have been wrong and so we must've had $f(a) = f(b)$ and $a=b$
Comment: okay that clears things up a bit. I think I'm still mostly confused because in the question statement c) is using function k and h from C-->A, and I don't see this anywhere in the proof
Comment: The statement of c) is simply saying that if $h$ and $k$ have the same domain ("$C$"), then whenever you have $f\circ h = f\circ k$, you must have $h = k$. In our example, the two functions do indeed have the same domain: $A$ (which corresponds to $C$ in the definition).
Comment: THank you, I understand that part now. Just clarifying in part c)-->a), what the domain for x is? I think its domain is A?
Comment: Do you mean the domain of $f$? If so, then yes, that's $A$.
Comment: I mean the x in the definition for function k(x). Where k(x)=x when x=else
Comment: Oh, ok. Well yeah, when we write $k(x)$ we're gonna want $x$ to be in $k$'s domain, which is $A$
Answer: $1)\Rightarrow 2)$ $\forall y\in B$ then $y\in Im(f)$ or $y\notin Im(f)$, if $y\in Im(f)$ then $\exists x_y \in A; f(x_y)=y$
let define $g:B\to A$ by form $g(y)=x; y \notin I(f)$($x$ fixed point ) or $g(y)=x_y; y \in I(f)$
by definition $g$ we have $domain(g)=B$. Let be $y,y'\in B; y=y'$ then
case$(1)$: if $y,y'\in I(f)$ then
 $\exists x_y,x_{y'}\in A; f(x_y)=y, f(x_{y'})=y'$ then $g(y)=x_{y},g(y')=x_{y'} $ . we have $f$ is one-to-one and $y=y'$ then $f(x_y)=f(x_{y'})\Rightarrow x_{y}=x_{y'}\Rightarrow g(y)=g(y') $
case$(2)$: if $y,y'\notin I(f)$ then $g(y)=g(y')=x$
in two case we have $g(y)=g(y')$ then $g$ well defined and $g$ is a map and
$(g\circ f)(x_y)=g(f(x_y))=g(y)=x_y=id(x_y)$
$2)\Rightarrow 3)$ we have $h:C\to A$ and $k"C\to A$ by $2)$ there is $t:A\to C; t\circ h=t\circ k=I$, we have $f\circ h=f\circ k\Rightarrow t\circ f\circ h=t\circ f\circ k \Rightarrow h=k$
$3)\Rightarrow 1)$ $f(x)=f(y)\Rightarrow f(h(a))=f(h(b))\Rightarrow fh(a)=fh(b)
 $ by $3)$ $h(a)=h(b)\Rightarrow x=y$ then $f$ one to one map.


Laravel Audit Method audits does not exist

Question: i'm trying to get the last username who update the form using LARAVEL AUDITING but i always end up with this error "Method audits does not exist." but in my database audit already exist and working but i can't make it work in my controller..
Controller: (eg. I'm trying to get the last user who updated the table)
public function show($id, Request $request)
{
    //
    $leads = Lead::findOrFail($id);
    $diff = $request->audits()->with('user')->get()->last();

    // show the view and pass the nerd to it
    return view('leads.show')->with('leads', $leads)->withDiff($diff);;
}

Blade:

 Revision by {{ $diff->user->name }}

Comment: have you defined the relationship in your models?
Comment: i have the answer already hehe thanks
Answer: i found the answer by my self i did some mistakes..
Controller:
public function show($id, Request $request)

{
$leads = Lead::findOrFail($id)->audits()->with('user')->get()->last();

return view('leads.show')->with('leads', $leads);

}


Mahalanobis distance in a hierarchical cluster analysis in SPSS

Question: I am conducting a hierarchical cluster analysis in SPSS on my database with several neuropsychological and psychiatric variables. In my database, some of my variables (that is, two pairs of variables) have correlations $r > .80$. My first thought was to eliminate these variables from my cluster analysis.
However, another option is to use Mahalanobis distance as the distance measure, because this measure takes the correlation in account (according to, e.g., Multivariate Data Analysis by Hair et al.).
My question is, if there is a way as to perform the hierarchical cluster analysis in SPSS using the Mahalanobis distance? I am not familiar with R or SAS, so my preference would be a method using SPSS.
Comment: There is no much use of Mahalanobis distance in cluster analysis, typically, because covarince matrices can be different for different clusters, and you don't know clusters in advance. If your variables strongly correlate but your clustering method "prefers" uncorrelated features, do PCA first to ortogonalize them. If you still think you need a SPSS function to compute a matrix of Mahalanobis distance between cases (pairwisely) - I have written one. (Unfortunately, my web-site is currently offline, so you can't take it, then leave me your email and I'll send.)
Answer: IBM advises against using the Mahalanobis' distance in clustering. See here.
In hierarchical clustering, you need to define the distance between the clusters (as they are formed) and the remaining unclustered data points. So while the Mahalanobis' distance is a sensible measure between data points, it is hard to generalize it to a measure of the distance between clusters. I think that's the point IBM is trying to make.
I would add that if you really want to base your analysis on the covariance structure of the data, perhaps something like SEM or factor analysis would be the way to go.
Another approach would be to transform the data into PC scores ... then do the cluster analysis on the scores. Yes, this is a kludge, and I don't know how you would explain the results to a client, but it would be a way to adjust for the covariance structure. If the data are meaningfully correlated, then you might be able to reduce the dimensionality by taking the first few PC scores and base your clustering on that.


What happens to socket when the internet connection goes off suddenly?

Question: I have a server and many clients. My clients send messages through server. If a client connects to server, my server puts socket reference of this client to a Sock array. If another client sends message to this first client server checks whether first client is connected to server or not using a boolean array, if it is online then sends message to first client using the socket reference in array otherwise sends messages to database.
Every client sends close signal before logout to server so that it can update the boolean array.But if internet connection of first client goes off suddenly ,then boolean variable in the array will still be true. For this purpose i want to make a thread in server which checks boolean array,if any index in array is true ,i want to check whether socket corresponding to it is open or not. What method of socket should i use- socket.isConnected() or socket.isClosed() or any other?
Comment: 'if internet connection of first client goes off suddenly' - what does that mean?  The problem is that 'the internet' does not really exist as an entity you can connect to, so you cannot detect connection to it, or not.
Answer: The only way to be sure a connection is working is by receiving a heartbeat, or message at a regular interval.
There is isConnectd() which means; have I ever connected and isClosed() which means; did I call close() on my side, but these don't do what you might want.
Comment: If internet connection goes off how can i use socket reference to check whether it is still connected? What will happen to this socket?
Comment: @abc like I said, the only way is to expect a message/data to be sent to you and if it doesn't get sent, you time-out the socket connection.
Comment: Now i am making a thread from my service which sends some message to server at regular interval . But when service is stopped this thread is not stopping by itself . How to handle this so if my service is stopped, on server socket timeout can happen.
Comment: You need a thread which regularly checks that you have read some data from a connection e.g. set a timestamp of the last read somewhere. Where this exceed some timeout, close the Socket which will trigger an exception on a blocking thread. You can use one heartbeat monitor thread for all your connections.
Comment: Thanks all issues handled. I was sending a message to server on logging off so on that time  server closes the socket and an exception is created in thread so thread terminate and if internet connection goes off, a timeout exception occurs and in catch block server sets boolean value corresponding to that socket to false in the array.


could not read column value from result set in Hibernate Native Query

Question: <code> SELECT
  CONCAT(CREG.FIRSTNAME, ' ', CREG.LASTNAME) AS NAME,
  CASE WHEN CR.CAMPAIGNTYPE = 'NPS'
    THEN NPSSCORE
  ELSE CSATSCORE END                         AS SCORE,
  IFNULL(cast(CC.TEXT AS CHAR(255)), '')     AS COMMENTS,
  CREG.ID                                    AS CLIENTID,
  CR.ID                                      AS CAMPAIGNRESPONSEID,
  CI.ID                                      AS ISSUEID
FROM CUSTOMER_ISSUES CI INNER JOIN (SELECT DISTINCT ISSUEID
                                    FROM ISSUE_DEPARTMENT_MAPPING
                                    WHERE CUSTOMERUSERID = 91 AND ISSUE_STATUS = 'New') IDM
    ON CAST(CI.FEEDBACK_DATE AS DATE) BETWEEN '2016-06-05' AND '2016-06-11' AND IDM.ISSUEID = CI.ID
  INNER JOIN CAMPAIGN_RESPONSE CR ON CR.ID = CI.CAMPAIGN_RESPONSE_ID
  INNER JOIN CLIENT_REGISTRATION CREG ON CREG.ID = CR.RESPONSECUSTOMERID
  LEFT OUTER JOIN CAMPAIGN_COMMENTS CC ON CC.CAMPAIGN_RESPONSE_ID = CR.ID;
</code>
The above query is running in the mysql-console properly ,but when I am integrating with the Hibernate,following error is thrown by Hibernate.
[BigIntegerType] could not read column value from result set: ID; Column 'ID' not found.
Comment: set `show_sql=true` get the SQL printed on log/console, check whether it runs fine in mysql-console. how are you binding parameters? also post complete stack trace
Answer: Try getting rid of the alias names in your SQL query.
Basically what happens here is when you run
<code>SELECT
  CONCAT(CREG.FIRSTNAME, ' ', CREG.LASTNAME) AS NAME,
  CASE WHEN CR.CAMPAIGNTYPE = 'NPS'
    THEN NPSSCORE
  ELSE CSATSCORE END                         AS SCORE,
  IFNULL(cast(CC.TEXT AS CHAR(255)), '')     AS COMMENTS,
  CREG.ID                                    AS CLIENTID,
  CR.ID                                      AS CAMPAIGNRESPONSEID,
  CI.ID                                      AS ISSUEID
</code>
in JDBC it returns the column as CREG.ID  instead of ClientID.
So try running the query without the aliases, typically, there is a problem in JDBC with this. If you still insist on using aliases,add the following entry to JDBC URL in configuration file
[useOldAliasMetadataBehavior=true]
Comment: After removing the alias from all the id columns ,it worked!


Exception raised on special folder in Windows 7

Question: In my application I use the following command to get all files from a selected path:
foreach (string currentFile in Directory.EnumerateFiles(@"c:\", "*.*", SearchOption.AllDirectories))
{
    //some logic here
}

The thing is that when trying to access certain directories such as c:\Documents and Settings I get an UnauthorizedAccessException.
The folder mentioned above doesn't show in Windows Explorer or in the .NET System.Windows.Forms.FolderBrowserDialog and i can't find a specific attribute of this folder so I could filter the enumeration by.
I tried this and this but with no use.
Is there any kind of attribute or parameter I can use to restrict this kind of directories from my loop?
Comment: Windows Explorer simply doesn't list "Documents and Settings" because it's marked as a hidden system folder. It doesn't care whether it's accessible, if you configure Explorer to show hidden and system files and folders, it'll show up, but it'll still be inaccessible.
Answer: Directory class does not provide a means to skip over inaccessible files and folders. You can write your own directory scanning method, that will recursively go into each folder and skip it if exception occurs.
Comment: There's no way to check for this by checking the `DirectoryInfo` parameters?
Comment: You can get access control list using DirectoryInfo.GetAccessControl() and then try to figure out if you have the permissions. But I see no reason for doing it, as catching exception would be easier to implement and understand.
Comment: Ended up with this solution: http://stackoverflow.com/a/929418/1092181, apparently (and surprisingly) it is easier to catch the `exception` rather than checking for permissions. Thanks a lot!
Answer: Can't you just get a Sys Admin to give your user read permissions to all the files? Sounds like there are things you can't access. Though I don't discourage you from solving this issue by excluding these files just from a portability standpoint(I can't speak directly to how to do this unfortunately).
Comment: Our security officer would have a heart attack if he read this answer.
Comment: I don't want to access unauthorized directories. I just want to skip them.


Comparison between Servlet Context and Third party Cache(like ehcache)

Question: In my web application I have many static list. These static list are generated by querying from database. Now I'm generating this list during start up of my application server and store them in the Application Context. I can do the same using a third party object cache framework like ehcache. Now the question is which one is the better approach. Is there any limitation if I use the Application Context.
Answer: If you know this dataset is static and fits in memory, the you are fine with your ApplicationContext.
What a caching solution would do is give your more flexibility around eviction - based on limits you would set yourself - and expiry - based on how fresh the cached data must be - of cached elements.
Comment: is right in the context servlet listener define a static list, and a static get of the list, and access it via servletcontextlistener.getlist() ??


Como dar um comando EXECUTE IMMEDIATE em um banco ORACLE partindo de uma aplicação JAVA?

Question: O erro é quando executo:
execute immediate 'update teste set num = 1234 where num = 1';

Exceção:
java.sql.SQLSyntaxErrorException: ORA-00900: instrução SQL inválida

Comment: Olá @lucasRomero, bem vindo ao [pt.so]. Em qual contexto você está tentando realizar este comando? Se é via aplicação não bastaria um update? Se não me falhe a memória, o `execute immediate` é para ser utilizado dentro de triggers e funções
Comment: Essa linha que eu postei é apenas de teste, as que serão executadas eu não tenho acesso.
Comment: Renan, a parte do comando `update teste set num = 1234 where num = 1` está beleza, já testei select, insert, update e delete. Porém não executei testes com o `execute immediate`.
Comment: Removi meu comentário anterior porque realmente estava errado [de acordo com o manual](http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/update_statement.htm). A coluna `num` é realmente numérica?
Comment: É numérica. Se eu executar apenas `update teste set num = 1234 where num = 1` dá certo, o problema é quando eu acrescento `excute immediate`.
Answer: Você deve utilizar somente o comando de update
update teste set num = 1234 where num = 1

O EXECUTE IMMEDIATE é somente para executar sentenças SQL dentro de blocos de funções ou triggers PL/SQL (vide documentação)


Como implementar um SVG?

Question: Bem, o SVG é muito importante para a web, uma vez que é vetorial e posso redimensioná-lo à vontade. É um formato de imagem escrito em xml e é um dos padrões de imagem para web.
Mas, quando tento implementá-lo numa página web, ele simplesmente não me obedece! Ele fica garrado na parte superior esquerda da página.
Alguém sabe me dizer como faço para manipulá-lo?
Exemplo de código de uma imagem SVG:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="210mm"
        height="297mm" version="1.1" shape-rendering="geometricPrecision"
        text-rendering="geometricPrecision" image-rendering="optimizeQuality"
        fill-rule="evenodd" clip-rule="evenodd" viewBox="0 0 21000 29700"
        xmlns:xlink="http://www.w3.org/1999/xlink">
 <g id="Camada_x0020_1">
  <metadata id="CorelCorpID_0Corel-Layer"/>
  <circle fill="red" cx="10092" cy="13553" r="1508"/>
 </g>
</svg>

O código acima pode ser visto num browser, é um simples círculo. O problema é que eu não consigo posicionar este tipo de imagem na forma que eu quero. Como faço isso?
Comment: Qual comportamento você está esperando que ele tenha ao ser aberto no browser? Pois é como abrir um link para uma imagem, o browser simplesmente renderiza o resultado e exibe para você ancorado no canto superior esquerdo.
Comment: Você está abrindo o svg direto no browser, ou embutindo em um html?
Comment: Eu abro esse SVG no Chrome e tudo parece normal. Talvez eu não esteja entendendo qual é o problema.
Comment: Ah desculpa. Corrigi a pergunta e adicionei um exemplo. Espero que entenda agora =D
Comment: Abrindo direto no browser. Será que estou passando algum argumento inválido? Pois não conheço ainda sobre xml/xhtml e os svg são escritos nessa linguagem
Answer: Na verdade o SVG que você postou não é um simples círculo. É um objeto que contém um círculo. É importante distinguir isto pois se você estiver tentando posicionar o círculo, não vai funcionar a menos que você entenda o objeto no qual ele está contido.
É importante entender os atributos que você está usando para descrever o SVG. Vou remover os que são irrelevantes para esta questão e manter apenas os outros:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
     width="210mm" height="297mm"
     viewBox="0 0 21000 29700"> ... </svg>

Você está usando os atributos height e width em mm, então essa unidade valerá para os valores que você estiver usando dentro do SVG. O viewBox é o seu sistema de coordenadas. Você está associando 210mm com 21000, e 297mm com 29700. Vou dividir isto por 100 para ficar mais fácil de trabalhar:
<svg xmlns="http://www.w3.org/2000/svg" width="210mm"  height="297mm" version="1.1" viewBox="0 0 210 297">
   <g id="Camada_x0020_1">
      <circle fill="red" cx="100.92" cy="135.53" r="15.08"/>
   </g>
</svg>

O que você tem aqui é uma tela de 210x297mm com um círculo situado mais ou menos no meio.
Eu fiz um JSFiddle onde troquei mm por px para que o SVG inteiro fosse visível na tela. O fiddle contem um bloco de HTML antes, que empurra o SVG para uma posição diferente (veja que ele não fica preso na parte superior da página).

Texto em HTML

<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
     width="210px"
     height="297px"
     viewBox="0 0 210 297">
    <g>
        <circle fill="red" cx="100.92" cy="135.53" r="15.08"/>
    </g>
</svg>

Você pode posicionar esse SVG na página como quiser usando CSS. Eu pus uma borda em volta dele para distinguir o SVG (retângulo invisível de 210x297px) do círculo (vermelho, que tem 15.08px de raio):
svg {
    border: solid blue 1px;
}

Se você quiser usar apenas o círculo, você pode definir um viewBoxque tenha exatamente as dimensões dele:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
     viewBox="0 0 200 200">
    <circle fill="red" cx="100" cy="100" r="100"/>
</svg>

E não usar o heighte width, deixando o controle para fazer no CSS ou usar o tamanho default (que será definido pelo elemento pai):

   <svg> ... </svg>

Assim você define as dimensões que desejar. O viewBox é um sistema de coordenadas relativo. Ele vai se adequar às coordenadas absolutas (em cm, mm, px) que você definir através de atributos, CSS ou contexto. Se você usar um CSS contendo:
#circulo {
    width: 150px;
    height: 150px;
}

O div terá dimensões 150 x 150px e reduzirá o SVG proporcionalmente. O comportamento default é não distorcer a imagem, então a menor dimensão determinará o tamanho do círculo. Experimente variar as dimensões e veja o que acontece.
Veja JSFiddle no. 2
Você pode agora tratar o SVG como qualquer outro componente do DOM, alterar seu posicionamento com CSS, acessar componentes internos identificados com ID via CSS ou JavaScript, etc.
Eu usei um exemplo de SVG embutido na página, mas tudo também vale para SVG incluído via tag  (exceto a possibilidade de acessar elementos internos do SVG via DOM). Veja JSFiddle no. 3. Lembrando que se usar um SVG externo dessa forma, você não pode omitir os atributos de namespace e versão (que o HTML5 tolera e assume default se você não usar).
Answer: Olha esse exemplo que fiz no JSFiddle, no link tem a referência de onde produzi a imagem, é só clicar em preview HTML, e depois no console pegar o código fonte.

Como implementar um SVG?


How to add the data received from UIAlertview text field to a local variable?

Question: I have button set up, and when it gets clicked, an alertview will appear with a text field. I want to get the data from that variable and trigger an addition function which adds the value of the text field to a local variable and displays the data in a label. How can I do that?
Answer: Set the delegate property of UIAlertView and have that object conform to UIAlertViewDelegate. Namely, respond to alertView:clickedButtonAtIndex:, during which you can inquire regarding textFieldAtIndex.
Answer: I'm assuming you've already got the UIAlertView with a UITextField (either using the UIAlertViewStyleSecureTextInput, UIAlertViewStylePlainTextInput, or UIAlertViewStyleLoginAndPasswordInput).
I'm also going to assume that you've set up the UIAlertViewDelegate so that it gets called properly when a button on the UIAlertView is pressed. So, to get the value of the UITextField, in your alertView:clickedButtonAtIndex: you add the following code (assuming only one UITextField - if you have multiple, just change the parameter passed to textFieldAtIndex:
NSInteger textFieldValueAsInteger = [[alertView textFieldAtIndex:0].text integerValue];
NSInteger finalValue = textFieldValueAsInteger + someOtherIntegerThatYouAlreadyDeclared;

Displaying it largely depends on your your UILabel etc are set up, but basically:
UILabel *labelToDisplayResults = [[UILabel alloc] initWithFrame:self.view.frame];
[self.view addSubview:labelToDisplayResults];

[labelToDisplayResults setText:[NSString stringWithFormat:@"%d", finalValue]];

That should do it. Let me know if you have any other follow-up questions.
Answer: You need to set a delegate for the alert view, and that object should adopt the UIAlertViewDelegate protocol. The delegate will then receive a -alertView:willDismissWithButtonIndex: message before the alert is dismissed. Your delegate's implementation of that method can get the text from whatever text fields are in the alert -- use -textFieldAtIndex: to get the different text fields.


Is it okay to remove the cork from a trumpet's mute?

Question: I bought a mute for my trumpet because I want to practice playing in my dorm.
However, it is not very effective in minimizing the noise I make when I play.
I suspect that it is the pieces of cork that prevent complete obstruction of sound from within the trumpet.
So, will it be okay to detach these pieces of cork so that my mute will fit in more snugly into my trumpet? Or will it just destroy the mute and not lead to any desired results?
Please refer to the attached image (it depicts the 'cork' in my mute).
Comment: IIRC there are different types of mutes.. Some are for altering the sound more than quieting it. You might look into ["trumpet practice mutes"](https://en.wikipedia.org/wiki/Mute_(music)#Practice_.28whispa.2C_whisper.2C_or_hotel.29) as they have a better seal for silencing the trumpet.
Comment: Yeah.. metal on metal is never good. In the link for the homemade mute they talked about [using rubber wetherstripping](https://upload.wikimedia.org/wikipedia/commons/3/39/Practice_mute_crop.jpg) to wrap around the mute and make a good seal with the bell. That might work if you take the cork off.
Comment: @Thauwa, in a comment below you say your mute is a straight mute. A straight mute and a practice mute are not the same thing. If you want to practice really quietly you need a practice mute, not a straight mute. A straight mute would be used more commonly for performance rather than for practice.
Comment: @BobBroadley, thank you. The online store from which I bought the mute from titled their product as a 'Practice Mute'. I realized that it was a Straight Mute only after I Google'd what a Straight Mute was (I was not knowledgeable enough at the time of purchase to distinguish between the different types of mutes by inspecting the product's images). Anyway, I requested to return this mute.
Comment: @charlie - just to say that if you "make a good seal" then no air will be able to escape from the bell at all and the instrument will be unplayable. Practice mutes let the air escape whilst reducing the audible volume.
Answer: I would just like to point out that those corks are there for three reasons. The first is to hold the mute inside your bell, the second is to protect the finish on the inner bell from being scratched by the metal of the mute, or vice-versa. The third and perhaps most important is to allow the air a way of getting out of your horn.
If you look at the other end of your mute, you may notice there is no hole in it. So if you remove the corks, then put the mute in the bell, there will be no way for the air to escape the bell. This would either stop you from playing the horn at all, or you might blast the mute out of the trumpet like an air cannon. ;)
The practice mutes that were mentioned do indeed seal completely around the inside of the bell, but they also have a small hole in the other end to allow for airflow. They are a bit restrictive to play, but they do accomplish the job.
The mute in your picture is a performance mute, and while it makes the sound of your horn a bit "tinny," as you have mentioned it does not really quiet it much.
I think in your case what you want is an actual practice mute; Humes & Berg's Stonelined Practice Mute for trumpet is fairly effective and pretty inexpensive.
I would suggest seeing if the store you bought it from will allow you to exchange it.
Answer: Those pieces of cork are what's holding the mute inside your trumpet! I wouldn't recommend removing them - unless you only wish to play lying on your back.
Is this a straight mute? You may find a cup mute more effective at muffling your sound - although I'd recommend asking advice on that first. (As Charles mentions, a practice mute with a full ring of cork may be what you're looking for instead - they're a new one on me.) If you're serious about this, you may also want to investigate silent brass systems, which are specifically designed for this sort of thing, but I don't believe they're cheap.
Comment: If you're prepared to tape it to your trumpet, that may work - but remember if you ever use the mute for gigs, you'll likely need to take it in/out quickly, which won't allow time for taping. If you're looking for a cheap, temporary solution, perhaps you'd be best taping folded paper in between the cork gaps, and seeing if you can create a full seal that way - with out removing anything.
Comment: Haha thanks! It appears to be a Straight Mute. Hmm I'll consider getting a Cup Mute after some consultation. Are you sure that this mute (without cork) wouldn't fit? It does appear to fit in smoothly, and I can always use some non-destructive adhesive tape to hold it in place. I just want to work on my playing in an affordable way.
Answer: Sorry to be a wet blanket, but the correct answer is: do NOT practice in the dorm . I speak as a longtime musician who spent countless hours in practice rooms and practice cubes provided by college music departments for exactly that reason.   Aside from the fact that, even with a heavy mute, you will annoy other dorm residents, you can't learn an instrument properly if you only practice with a mute.
EDIT: in light of the info provided in the comments about no access to practice rooms, I'm kinda stuck for a better answer.  Maybe you can get 'lucky' and find a storage room or laundry room in the dorm basement you could use to practice.
Answer: Do yourself the biggest favor and purchase the Yamaha Silent mute. Ether the new $200 model or the old $100 model. Either feels virtually natural, and volume is not an issue. They have microphone pickups in the mute so when you plug the system in, it sounds quite real. As a pro player, this thing has saved me on many occasions. Warming up before gigs is the main one, but being able to practice almost anywhere is the best. Hotel room, dorm, apartment, etc. People can hear it in the same room as a faint whisper.
http://www.musiciansfriend.com/brass-instruments/yamaha-sb7xc-silent-brass-system-for-trumpet?source=3WWRWXGP&gclid=CI7NytLY68ECFQqTaQodhlQAUg&kwid=productads-plaid%5E83573845947-sku%5EJ05787000000000@ADL4MF-adType%5EPLA-device%5Ec-adid%5E53736456387
If you can afford it, do it. You won't regret it.
Answer: I would sand it down slighty so that it could go in easier. I exhale air into my bell (fogging up) to help it stay in.


Android: Unable to update custom notification when I kill my app

Question: I am downloading multiple files one after the other in service. I want to update download progress in notification. But my notification doesn't update when I kill my app. Download works on different thread. Download works fine in when app is running. When I kill app from recent section, I am unable to update notification.
Here is my DownloadService class
public class DownloadService extends Service {

public static DownloadMap<String, Downloadables> map = new DownloadMap<String, Downloadables>();
private static Thread thread;
private DownloadCancelReceiver receiver;

public DownloadService() {
}

public class BackgroundThread extends Thread {
    int serviceId;
    private DownloadMap<String, Downloadables> map;

    private SpeedRevisionDatabase helper;

    private final int notificationId = 1;
    private RemoteViews remoteViewsSmall, remoteViewsBig;
    private NotificationManagerCompat notificationManager;
    private NotificationCompat.Builder mBuilder, mBuilderComplete, downloadFailBuilder;

    public BackgroundThread(int serviceId, DownloadMap<String, Downloadables> map) {
        this.serviceId = serviceId;
        this.map = new DownloadMap<>();
        this.map.putAll(map);
    }

    @Override
    public void run() {

        remoteViewsSmall = new RemoteViews(getApplicationContext().getPackageName(), R.layout.download_notification_small);
        remoteViewsBig = new RemoteViews(getApplicationContext().getPackageName(), R.layout.download_notification);

        Intent cancelDownload = new Intent("CANCEL_DOWNLOAD");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100, cancelDownload, 0);
        remoteViewsBig.setOnClickPendingIntent(R.id.tvCancel, pendingIntent);

        notificationManager = NotificationManagerCompat.from(DownloadService.this);
        mBuilder = new NotificationCompat.Builder(DownloadService.this, "default");
        initChannels(DownloadService.this);
        mBuilder.setContentTitle("Download is in progress")
                .setContentText("Please wait...")
                .setSmallIcon(R.mipmap.download)
                .setOngoing(true)
                .setCustomContentView(remoteViewsSmall)
                .setCustomBigContentView(remoteViewsBig)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        notificationManager.notify(notificationId, mBuilder.build());

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        try {

            String path = getApplicationContext().getApplicationInfo().dataDir + "/" + "UEP";
            File uepFolder = new File(path);

            if (!uepFolder.exists()) {
                uepFolder.mkdir();
            }

            int i = 0;
            while (map.entrySet().iterator().hasNext()) {
                Log.e("WhileCheck", "Now i is " + i);
                Map.Entry data = (Map.Entry) map.entrySet().iterator().next();
                try {
                    Downloadables download = (Downloadables) data.getValue();
                    if (NetworkUtil.getConnectivityStatus(getApplicationContext()) == 0) {
                        throw new InternetDisconnectedException("Internet Disconnected");
                    }

                    HttpURLConnection urlConnection;
                    InputStream inputStream;

                    //finding file on internet
                    try {
                        URL url = new URL(download.URL);
                        if (url.toString().endsWith(".xps")) {
                            url = new URL(url.toString().replace(".xps", ".pdf"));
                        }

                        urlConnection = (HttpURLConnection) url.openConnection();
                        urlConnection.connect();
                        inputStream = urlConnection.getInputStream();

                    } catch (IOException e) {
                        Log.e("IOException", "" + e.getMessage());
                        i++;
                        map.remove(data.getKey());
                        notificationManager.notify(notificationId, mBuilder.build());
                        continue;
                    }

                    //Downloading file over internet
                    File file = new File(uepFolder + "/" + download.FileName + "" + download.Format + ".download");
                    try {
                        int fileSize = urlConnection.getContentLength();
                        FileOutputStream fileOutput = new FileOutputStream(file);
                        byte[] buffer = new byte[1024];
                        int bufferLength = 0;
                        int count = 0;
                        int previousProgress = 0;
                        while ((bufferLength = inputStream.read(buffer)) > 0) {

                            if (this.isInterrupted()) {
                                throw new InterruptedException("Thread has been kill (Destroyed)");
                            }

                            fileOutput.write(buffer, 0, bufferLength);
                            count += bufferLength;

                            int progress = (int) (count * 100L / (float) fileSize);

                            if (previousProgress > 999) {
                                updateProgress(map.insertedCount, i, progress, download.Name);
                                notificationManager.notify(notificationId, mBuilder.build());
                                previousProgress = 0;
                            }
                            previousProgress++;
                        }
                        fileOutput.close();
                    } catch (IOException e) {
                        Log.e("IOException", "" + e.getMessage());
                        i++;
                        map.remove(data.getKey());
                        continue;
                    }

                    File actualFile = new File(uepFolder + "/" + download.FileName + "" + download.Format);
                    file.renameTo(actualFile);
                    Log.e("Downloaded",""+actualFile.getAbsoluteFile());

                } catch (InterruptedException | InternetDisconnectedException e) {
                    throw e;
                }
                i++;
                map.remove(data.getKey());
                Log.e("Downloaded", "Remaining files are "+map.size());
            }
            Log.e("WhileCheck", "While End");

            // Due to thread, sometime the sequence of code flow is not in correct flow, and "Download complete" Notifaction is getting shown
            // Hence this check is required.
            if (this.isInterrupted()) {
                throw new InterruptedException("Thread has been kill (Destroyed)");
            }

            notificationManager.cancel(notificationId);

            mBuilderComplete = new NotificationCompat.Builder(DownloadService.this, "default");
            initChannels(DownloadService.this);
            mBuilderComplete.setOngoing(false)
                    .setContentTitle("Download Complete")
                    .setColor(Color.WHITE)
                    .setSmallIcon(R.drawable.download);
            notificationManager.notify(2, mBuilderComplete.build());

            Log.e("DownloadingService", "File downloaded successfully");
            stopSelf();
            map.insertedCount = 0;

        } catch (InterruptedException e) {
            closeNotification();
            Log.e("InterruptedException", "" + e.getMessage());
        } catch (InternetDisconnectedException e) {
            stopSelf();
            closeNotification();
            showNotification("Internet disconnected", "Download failed. Try again later.");
            Log.e("InternetDisconnect", "" + e.getMessage());
        }
    }

    private void updateProgress(int totalFiles, int currentFileCount, int currentProgress, String fileName) {

        remoteViewsSmall.setTextViewText(R.id.tvOverAll, currentFileCount + "/" + totalFiles);
        remoteViewsSmall.setProgressBar(R.id.overallProgress, totalFiles, currentFileCount, false);

        remoteViewsBig.setTextViewText(R.id.tvOverAll, currentFileCount + "/" + totalFiles);
        remoteViewsBig.setTextViewText(R.id.tvFileName, "Downloading " + fileName);
        remoteViewsBig.setTextViewText(R.id.tvCurrentProgress, currentProgress + "%");
        remoteViewsBig.setProgressBar(R.id.overallProgress, totalFiles, currentFileCount, false);
        remoteViewsBig.setProgressBar(R.id.currentProgress, 100, currentProgress, false);
    }

    public void closeNotification() {
        if (notificationManager != null)
            notificationManager.cancel(notificationId);
    }

    public void showNotification(String title, String message) {
        downloadFailBuilder = new NotificationCompat.Builder(DownloadService.this, "default");
        initChannels(DownloadService.this);
        downloadFailBuilder.setOngoing(false)
                .setContentTitle(title)
                .setContentText(message)
                .setColor(Color.WHITE)
                .setSmallIcon(android.R.drawable.stat_sys_warning);
        notificationManager.notify(3, downloadFailBuilder.build());
    }
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    if (intent != null) {
        ArrayList<Downloadables> list = (ArrayList<Downloadables>) intent.getSerializableExtra("downloadList");
        for (Downloadables d : list) {
            String key = d.Name + "" + d.FileName;
            map.put(key, d);
        }

        if (thread == null || !thread.isAlive()) {

            thread = new BackgroundThread(startId, map);
            receiver = new DownloadCancelReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
            intentFilter.addAction("CANCEL_DOWNLOAD");
            registerReceiver(receiver, intentFilter);
            thread.start();
        }
    }
    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    Log.e("Service", " Stop");
    try {
        thread.interrupt();
    } catch (Exception e) {
        Log.e("Exception", "" + e.getMessage());
    }

    map.clear();
    unregisterReceiver(receiver);
    //closeNotification();

}

public static class DownloadCancelReceiver extends BroadcastReceiver {

    public DownloadCancelReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equalsIgnoreCase("CANCEL_DOWNLOAD")) {
            Intent intent1 = new Intent(context, DownloadService.class);
            context.stopService(intent1);
        }
    }
}

public void initChannels(Context context) {
    if (Build.VERSION.SDK_INT < 26) {
        return;
    }

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationChannel channel = new NotificationChannel("default", "Channel name", NotificationManager.IMPORTANCE_LOW);
    channel.setDescription("Channel description");
    channel.setImportance(NotificationManager.IMPORTANCE_LOW);
    channel.setSound(null, null);
    notificationManager.createNotificationChannel(channel);
}

private class InternetDisconnectedException extends Exception {

    public InternetDisconnectedException(String message) {
        super(message);
    }
}

public static class DownloadMap<String, Downloadables> extends HashMap<String, Downloadables> {

    public int insertedCount;

    @Override
    public Downloadables put(String key, Downloadables value) {
        insertedCount++;
        return super.put(key, value);
    }
}
}

And From activity I start service like this.
ArrayList<Downloadables> list = helper.GetVideoFileList();
Intent intent1 = new Intent(SRDownloadActivity.this, DownloadService.class);
intent1.putExtra("downloadList", list);
startService(intent1);

I can even Add files to HashMap while downloading is in progress. It also worked fine.
I am unable to figure it out why it is not running in background since it is on different thread.
Here is my notification look like
Answer: Threads are killed by the Android OS even if the main app is still working and they dont have access to the UI thats why u should use AsyncTask class its a like a thread that works in background but it has access to the UI of the main. And the jobdispatcher class can help u assign jobs in the background
Here is a good tutorial https://youtu.be/das7FmQIGik


Non-homogeneous linear recurrence relation

Question: I have this recurrence relation to solve:
$$a_{n+1}=3a_n+2^{n-1}-1.$$
The homogeneous part's solution is obviously $a_n=k3^n.$ Now I don't know how to solve the original equation, but I do know what to do in the case of a seemingly analogous differential equation. Consider the equation $$y'=3y+2^{x-1}-1.$$ The homogenous part is solved by $y=Ce^{3x}.$ To find the solution of the non-homogeneous equation, I put $y=C(x)e^{3x}$. Then $y'=C'(x)e^{3x}+C(x)3e^{3x}$. But then, substituting, I get $$C'(x)e^{3x}+C(x)3e^{3x}=3C(x)e^{3x}+2^{x-1}-1,$$ or $$C'(x)e^{3x}=2^{x-1}-1,$$ which can be easily solved.
Now, I thought what I should do for my recurrence relation is just take $a_n=k(n)3^n$ like for the differential equation, but this doesn't seem to work. The problem is that now the equation doesn't simplify after the analgous substitution. Simply, if $a_n=k(n)3^n$, then $a_{n+1}=k(n+1)3^{n+1},$ and not $k(n+1)3^n+k(n)3^{n+1}.$
So what's the algorithm here? If possible, please make the algorithm easy to remember by analogy with the algorithm for differential equations given above (for an example equation, but I hope it's clear what I do in the general case). I'm looking more for a way to remember this than for a way to understand it fully. Sorry if this approach offends anyone, but I'm sure that if I know the answer and have an easy way to remember it, then I can figure out a way to understand it.
Comment: No, they're exactly as complicated; you can translate from one to the other by taking Taylor series resp. by constructing exponential generating functions (http://en.wikipedia.org/wiki/Generating_function).
Comment: The algorithm involves substituting terms that resemble the non-homogeneous parts up to polynomial factors, which here means trying something like $a_n = C(n) 2^n + D(n)$ where $C, D$ will end up being polynomials. There's a good reason for this but it requires a little mathematical sophistication to appreciate in full generality.
Comment: @QiaochuYuan Does it mean that linear recurrence relations are inherently more difficult or complicated than linear differential equations? I didn't give a proof that my way of solving the differential equation works, but I could produce a proof without much trouble. It seems, from what you're saying that here both the algorithm and its justification are more complicated. Do I understand you correctly?
Answer: Your approach will work fine for the difference equation. $$k(n+1)3^{n+1}=k(n)3^{n+1}+2^{n-1}-1$$
Hence $3^{n+1}(k(n+1)-k(n))=2^{n-1}-1$, which you can solve the same way as in the differential equation case.  In discrete-land $f(n+1)-f(n)$ serves the same role that $\frac{d}{dx}f(x)$ does in continuous-land.
Nb. In neither case would I choose this approach to use; it's usually easiest to use undetermined coefficients with a suitable guess, as @Qiaochu suggests.
Comment: Oh, fantastic, I completely missed that. So solving for $k$ will involve a summation instead of the continuous-case integration, right?
Comment: That's right, @Bartek.
Comment: Oh, and that's not good, because, while I know how to integrate, I don't really know how to sum. But in this particular case, I get partial sums of geometric progressions, so I can do it. Great! Thank you very much! :)
Comment: My pleasure, glad to be of service.
Answer: Can use generating functions directly, no guessing. Define $A(z) = \sum_{n \ge 0} a_n z^n$, multiply the recurrence by $z^n$ and sum over $n \ge 0$ to get,
after recognizing a few sums:
$$
\frac{A(z) - a_0}{z}
  = 3 A(z) + \frac{1}{2} \cdot \frac{1}{1 - 2 z} - \frac{1}{1 - z}
$$
Solve as partial fractions:
$$
A(z)
  = \frac{a_0}{1 - 3 z}
      - \frac{1}{2} \cdot \frac{1}{1 - 2 z}
      + \frac{1}{2} \cdot \frac{1}{1 - z}
$$
Everything in sight is a geometric series:
$$
a_n = a_0 \cdot 3^n - \frac{2^n - 1}{2}
$$


Several variants in a page

Question: Is it possible to use several variants in a page?
In the page I made only one variant is shown.
Answer: The first variant that "passes" will be the one that is shown.
So if the first (top) variant does not have any conditions limiting when it is displayed, it will always be the one that is shown.

Several variants in a page


The angle between the $x$-axis and the vector that reachs the $2$-norm of a matrix

Question: Suppose we have a matrix $A\in \mathbb{R}^{2\times 2}$. We have the $2$-norm defined as $\left \|A\right \|_2=\max_{\left \|x\right \|_2=1}\left \|Ax\right \|_2$.
We know that in order to find a unit vector $v$ such that $\left \|Av\right \|_2=\left \|A\right \|_2$, we have to find the eigenvalues of $A^TA$, take the greatest eigenvalue, find a corresponding eigenvector and finally normalize it.
Of course, this would lead us to two different solutions: a vector $v$ and its corresponding additive opposite. Nevertheless, we will take the one with non-negative value of $x$ (i.e. the one which is to the right of the $y$-axis).
Once we have this vector, it is easy to find the angle it forms with the $x$-axis. But I have the following question: Is there any better way to find this angle, providing that it is the only information we want?
This question arises from the following example: if $A=\begin{pmatrix}
1 & 1\\
0 & 1
\end{pmatrix}$, the eigenvalues of $A^TA$ are $\frac{3\pm \sqrt{5}}{2}$, and the calculation becomes very difficult. Moreover, I found a solution (which I could not understand) that finds the angle without finding the vector. This is the solution:

Have to maximize the function $f\left (\theta\right )=\cos^2\theta +2\sin\theta\cos\theta +2\sin^2\theta=1+\sin2\theta+\sin^2\theta$ and so setting the first derivative to be zero: $0=f'\left (\theta\right )=2\cos2\theta +2\sin\theta\cos\theta=2\cos2\theta+\sin2\theta$. That is $\tan2\theta=2$.

Maybe this can be generalized in order to obtain a general way to find this angle? In that case, I would like to have a better-explained solution. I do not understand where the function $f$ comes from.
Answer: Because your setup is $2\times2$, you can work with less theory. Since you only need to look at real vectors $(x,y)$ with $\|(x,y)\|=1$, you may assume that $x=\cos\theta$, $y=\sin\theta$. So now (for your particular $A$) you are looking at
\begin{align}
\|A(x,y)\|^2=\|(x+y,y)\|^2
&=(\cos\theta+\sin\theta)^2+\sin^2\theta=\cos^2\theta+\sin^2\theta+2\cos\theta\sin\theta+\sin^2\theta\\
&=1+2\cos\theta\sin\theta+\sin^2\theta\\
&=1+\sin2\theta+\sin^2\theta.
\end{align}
Now you are looking for $\theta$ that maximizes this expression, so differentiate and equate to zero.
If you have $A=\begin{bmatrix} a_{11}&a_{12}\\ a_{21}&a_{22}\end{bmatrix}$, now the function to be maximized will be
$$
(a_{11}\cos\theta+a_{12}\sin\theta)^2+(a_{21}\cos\theta+a_{22}\sin\theta)^2.
$$


Yes to all overwrites in interactive mv/cp/rm?

Question: So I've aliased the commands rm/cp/mv to use interactive (-i) mode by default to avoid accidentally deleting things, but sometimes this is pretty inconvenient.
I would like to be able to say 'y' to all the prompts of the form:
mv: overwrite `file_1'? y
mv: overwrite `file_2'? y

without typing 'y' many many times.  Is there a way to do this?
Comment: I do not understand what you exatly want. Please edit your answer to describe it more (what you tried to do and what you really expected)
Answer: Use command mv to circumvent the alias and use --force if that doesn't stop mv from bothering you with questions (e.g., because of permissions).
yes | aCommand is the standard way to supply lots of y's to aCommand, but in this case that seems unnecessary.
Comment: So I can't do this "interactively", i.e. use mv -i and then once it starts prompting me, tell is "yes to all"?
Comment: This kind of thing is generally quite hard to do unless the program directly supports it (and I believe mv doesn't support this). Cancelling the action (Ctrl-C) and starting from scratch tends to be easier.
Comment: agree that you can't switch horses in the middle of the stream. Another solution like `command mv`, is to use  the full path you the cmd. i.e. `/bin/mv files ...` when you want to skip the `-i` part. Good luck.
Answer: you can use back slash before cp
\cp -rf /from/directory/* to/directory


Generalization of Hat matrix diagonal elements $h_{ii}$ formula to multiple linear regression

Question: In this question, the OP states a formula for the hat matrix diagonal elements. I was wondering what would be a generalization of that formula to the multiple linear regression model.
Comment: The generalization is given at the very beginning of the answer in your referenced question: compute the diagonal elements of $X(X^\prime X)^{-}X^\prime.$
Answer: The ith diagonal element of H, $h_{ii}=x_i^T(X^TX)^{-1}x_i$. Also,
The Mahalanobis distance between an individual point $xi$ and the mean of the data set is given by $$MD(x_i)=\sqrt{(x_i-\bar x)^T S^{-1}(x_i-\bar x)}$$
where $S$ is the sample variance–covariance matrix. For a model with an intercept, the leverage and the squared Mahalanobis distance of a point i are related as $$h_{ii}=1/n + \frac{1}{n-1}MD^2(x_i)$$
This last expression seems useful to me... Is there a context where we can be sure that $h_{ii}$ is of the order $O(1/n)$?
See this link for more information, and from where this summary was taken from


What does this SQL error mean?

Question: I am getting the following error when running a migration on Laravel. It seems the error comes up when it reaches the part of the migration that updates the User table.
SQLSTATE[23000]: Integrity constraint violation: 1452
Cannot add or update a child row: a foreign key constraint fails
(`priatek`.`#sql-52e_a`, CONSTRAINT user_usertypeid_foreign` FOREIGN KEY
(userTypeId`) REFERENCES `UserType` (`userTypeId`))
(SQL: alter table `User` add constraint user_usertypeid_foreign foreign key
(`userTypeId`) references UserType` (`userTypeId`))

Migration
public function up()
{
    Schema::create('UserType', function (Blueprint $table) {
        $table->increments('userTypeId');
        $table->string('name');
        $table->string('description')->nullable();
        $table->boolean('viewUser');
        $table->boolean('viewSponsor');
        $table->boolean('viewQuestion');
        $table->boolean('createUser');
        $table->boolean('createSponsor');
        $table->boolean('createQuestion');
    });

    UserType::create([
        'name'           => 'Executive',
        'viewUser'       => 0,
        'viewSponsor'    => 1,
        'viewQuestion'   => 0,
        'createUser'     => 0,
        'createSponsor'  => 0,
        'createQuestion' => 0,
    ]);

    //more UserType creations...

    Schema::table('User', function ($table) {
        $table->integer('userTypeId')->unsigned();
        $table->integer('operatorId')->unsigned();
        $table->integer('sponsorId')->unsigned()->nullable();

        $table->foreign('userTypeId')->references('userTypeId')->on('UserType');
    });

    // more unrelated stuff...
}

Comment: You are trying to insert (update) a key that already exist....
Answer: The problem is when you add the foreign key to the table, all your users must already have a valid userTypeId.  But because you are just now creating that new column, they will not have this.
Before you can create the foreign key, you have to make sure all your users have a valid user type (the user type needs to be created and the userTypeId is set appropriately on each user).
So what you need to do is add the additional columns onto the User table, then run some update queries to make sure all users have their userTypeId set, then add the foreign key after the updates are finished.
Comment: I see what you mean, it's entering 0 for those new foreign keys. I made them nullable since some users might be of type "Admin" and those foreign keys are irrelevant to them.
Comment: Admittedly, I was not aware nullable foreign keys were not only possible, but recommended for situations like these so I'm happy you explained as I did not consider that a solution.
Comment: I wasn't aware either :/. I'll know in  the long run if it works for this project.

What does this SQL error mean?


Solving an equation using 'replacement'

Question: I have this equation:  $$ a \cdot 2^a = b$$  and need to find solutions for $a$.
And I know it's complicated and has to do something with the $W$ function.
But I've come up with a way which does not work for some-reason... and I would like you to have a look and help me find the mistake!
We can write any number $a = 2^k$ where $k$ isn't necessarily in $\mathbb{N}$ or $\mathbb{Z}$
so we have: $2^k \cdot 2^{2^k} = b$ which gives: $2^{2^k +1} =b $ and thus: $2^k + 1 = \log_2{b}$
And we get that $k = \log_2(\log_2b -1)$  and thus $a = 2^k = 2^{\log_2(\log_2b -1)} = \log_2b -1$
However this does not work! Why? Here is an example:
$a \cdot 2^a = 24$  In my example $a = \log_2(24) -1 \approx 3.58$ but it is actually $3$ ...
Edit: I am so dumb.. it should be $2^{2^k + k}$ ... Is there a way to solve this kind of equation?
Thank you!
Answer: $2^k \cdot 2^{2^k} = 2^{k + 2^k}$, not $2^{1+2^k}$.
EDIT: The solutions of $a 2^a = b$ are $$a = \frac{W(b \ln(2))}{\ln(2)}$$
where $W$ is a branch of the Lambert W function.  If you want real solutions:
there is none if $b < -1/(e \ln(2))$.  If $b = -1/(e \ln(2))$, the only real solution is $-1/\ln(2)$.  If $-1/(e \ln(2)) < b < 0$, there are two real solutions,
one with the "$-1$" branch and one with the principal branch of $W$.  If $b \ge 0$, the only real solution is with the principal branch.
Comment: @StackOMeow $a2^a = b \Rightarrow ae^{\ln(2^a)} =b\Rightarrow ae^{a\ln(2)}=b \Rightarrow a\ln(2) e^{a\ln(2)}=b\ln(2)$

on the left side we now have the form $xe^x$ where $x=a\ln(2)$ therefore, we have
$a \ln(2)=W(b\ln(2))\Rightarrow a=\frac{W(b\ln(2))}{\ln(2)}$
Comment: I've spotted the mistake as soon as I posted it... I am so tired haha... is there a way to solve it? more explicitly where $b = 24$ ? I mean, only $a=3$ makes sense.. but is it the only solution? why?
Comment: Thank you sir. But how did the Lambert came into play? We should use it only if we have the form $x \cdot e^x$ but here we have $x 2^x$

Solving an equation using 'replacement'


Error trying to run Scala Application inside Eclipse

Question: I'm using Eclipse Scala plugin. I created a simple program:
object HelloWorld {
  override def main(args: Array[String]) {
    println("Hello World!")
  }
}

I can run this program from the menu: Run As -> Scala Application
However, with this code
object HelloWorld extends Application {
  println("Hello world!")
}

I get this error message: "Selection does not contain a main type"
Does anyboby know how to solve this?
Comment: in NetBeans you get such error when SCALA_HOME environment variable is not set
Comment: This question is not about NetBeans.
Answer: This is a known bug. In a version of scala plugin for eclipse that I use this bug is repeatable only for objects in default package.
By the way, the usage of Application trait is not recommended - see corresponding documentation for details.
Comment: +1 WAS a known bug. It's fixed in the latest versions http://www.assembla.com/spaces/scala-ide/tickets/1000094-extends-application. And in fact the Helios version is not yet supported.
Comment: As of Scala 2.9, the `Application` trait will migrate from being "not recommended" to being "advocated".  The problems with it have been resolved and, after all, it is so much cleaner to write...
Comment: My object is in package com.example


Why can we substitute the exponential function while deriving the characteristic equation

Question: I'm studying the way characteristic equation works. The derivation, according to Wikipedia, follows:
We have a function $y(x)$ and an equation
$$a_n y^{(n)} + \cdots + a_1 y' + a_0 y = 0.$$
Then we substitute $$y = e^{rx}.$$
Why can we make such a substitution? I suspect we can't represent any function as $e^{rx}$. Besides it is said that $\forall z: e^{z} \neq 0$ (can you point me to a proof too), so if $\exists x_0: y(x_0) = 0$ then we can't represent this value in this substitution.
Comment: A word: ansatz (https://en.wikipedia.org/wiki/Ansatz).
Comment: A similar technique is used to solve linear difference equations with constant coefficients. Thus $a_{n}-5a_{n-1}+6a_{n-2}=0$ has the characteristic equation $r^{2}-5r+6=0$ and solution is of the form $a_{n}=A\cdot 2^{n}+B\cdot 3^{n}$. However in this case the characteristic eqn is not arrived by a guess but by finding the sum $\sum a_{n}x^{n}$ as a rational function of $x$ whose denominator is the characteristic polynomial. I strongly believe that there is something similar going on here in case of a differential eqn and it is definitely not based on guess.
Comment: It's just a guess. It turns out to be a good guess.
Answer: We only bravely try$^*$ to substitute $y=e^{rx}$ in
$$a_n y^{(n)} + ... + a_1 y' + a_0 y = 0. $$
We get then
$$a_n r^ne^{rx} + ... + a_1 re^{rx} + a_0 e^{rx} = 0.\tag 1$$
If we substitute $x=0$ (or if we divide both sides by $e^{rx}>0$) then we get the famous characteristic equation:
$$a_n r^n + ... + a_1 r + a_0  = 0.$$
We realize now that having solved this characteristic equation in $r$ and having substituted the solutions in $(1)$ for $r$ then we get a series of solutions of the differential equation.
Why?
Just imagine that $r_i$ is a solution of the characteristic equation and we substitute it for $r$ in $(1)$. Now, we have
$$a_n r_i^ne^{r_ix} + ... + a_1 r_ie^{r_ix} + a_0 e^{r_ix}=0 $$
since $e^{r_ix}>0$ for all $x$ we can divide both sides of this equation by $e^{r_ix}$. Then we do get zero exactly because $r_i$ is a solution. And , of course, this is the case for all $i$.
Note that we haven't yet determined all of the solutions. The result of our brave action is only a set of solutions.
$^*$ See the comment to the OP by  Martín-Blas Pérez Pinilla.
Edited because the last question remained unanswered
I've just realized that the OP asked the following question at the end of his/her post:
"Why can we make such a substitution? [$e^rx$] I suspect we can't represent any function as $e^x$. Besides it is said that $\forall z \ e^z\not =0$ (can you point me to a proof too), so if $\exists \ x_0 : y(x_0)=0$ then we can't represent this value in this substitution."

Of courese we cannot represent any functions as $e^x$. (To be honest I do not understand this sentence.)
Why is it true that $\forall z :\ e^z\not =0$? The most general case is when $z=a+ib$, a complex number. Then $e^z=e^{a+ib}=e^ae^{ib}.$ Here $a$ is real so $e^a$ is never zero. The question reamins: is there a real $b$ for which $e^{ib}=0$? That is impossible because the absolute value of $e^{ib}$ is $1$ independently of the argument $b$.
Even if $\exists \ x_0 : y(x_0)=0$ there are functions $y$ that can be represent by a homogenuous linear differential equation. Remember, the linear combinations of the solutions of such a differential equations are solutions to it as well. Let's see an example.

Solve the following differential equation:
$$y''+y'-2y=0.$$
The characteristic equation is $r^2+r-2=0$ whose solutions are: $r_1=-2$ and $r_2=1$. That is,  $y_1(x)=e^{-2x}$ and $y_2(x)=e^x$ are certainly solutions. But the linear combinations are also solutions! So
$$y(x)=e^{-2x}-e^x$$
is a solution again. Substituting $0$ for $x$ we get that $y(0)=0$ when $y$ is a solution.
So, even if we cannot describe all kinds of functions as solutions of certain differential equations, the existence of an $x_0$ for which $y(x_0)=0$ is not an obstacle.
Comment: Let's suppose we have determined all $n$ complex roots of our characteristic equation. How can we find out whether there are no other solutions? (For example when solving $\ddot{x} = -\omega^2 x$ we find all solutions if we're using the characteristic eqn)
Comment: Our differential equation is a linear homogenous one with constant coefficients. The linear combinations of the solutions are also solutions. To prove that there are no other solutions is another issue.
Comment: So what's the use of the characteristic eqn if we want to solve the differential equation? If we can't show there are no other roots, it gives us nothing. When dealing with polynomials we can say there can be maximally $n$ distinct roots, so pointing out all $n$ roots solves the problem. Besides, these examples: http://ocw.mit.edu/courses/mathematics/18-03sc-differential-equations-fall-2011/unit-ii-second-order-constant-coefficient-linear-equations/modes-and-the-characteristic-equation/MIT18_03SCF11_s12_2btext.pdf say "find all solutions" and the char.eqn is used. Why does this hold?
Comment: Sorry, I cannot give more. Please, consult appropiate text books.
Comment: @marmistrz: I've spent some more time to better understand what your real problem might have been. I've made an attempt to clarify my answer for you.
Comment: I think you have a minor error: if you want the roots to be $-2$ and $1$ then the characteristic polynomial is $r^2-r-2$. Both solutions to $r^2+2r+1=0$ are $-1$.
Comment: @Ian: Thx; I've corrected.
Answer: I would refer to that (setting $y= e^{rx}$) as "an educated guess".