What's the point of connecting chords to modes when writing in an established key?

Question: Let's say I am in the key of C and trying to write a simple melody over some chords on the piano.
Chord progression: I (Cmaj) IV (Fmaj) V (Gmaj) I (Cmaj)
Let's take the IV chord for instance.
What's the difference between connecting the IV chord to the Lydian mode so I can use the pitches in F Lydian mode to create a melody versus just using the pitches in the key of C itself? Won't I be using the same pitches/notes anyways?
Is it not easier to just focus on the keys pitches during the progression to create a melody rather then having to think about each mode for each chord?
Answer: It sound like you may be mixing up "classical" versus "jazz" or "pop" approaches to harmony and melody.
I'm using "classical" in very broad sense to mean something like Western tonal harmony.

...connecting chords to modes...

Matching scales and modes to chords is a typical jazz/pop approach.

...using the pitches in the key of C...

Classical style doesn't match scales to chords, but rather works with the tones of the key.
You already point out that the tones of the modes are the tones of a key (when the progression is diatonic.) In fact there is a lot of overlap between these two approaches to harmony and melody.
At this point it's probably best to figure out what style you are working in and approach your work within that frame work. Of course you could be working in a style that mixes styles or is totally eclectic in which case we cannot have a "black or white" answer.
Your wording...

...writing in an established key... ...over some chords...

...makes me believe that your working in a "classical" and homophonic style.
A very common approach in homophonic style is to write the melody using the chord tones of the given progression. (There is a theoretical argument about whether melody is generated from chords or vise versa, but let's skip that.) Such chord derived melodies can be decorated with various non-chord tones both diatonic and chromatic.
Comment: "Classical style doesn't match scales to chords, but rather works with the tones of the key." This isn't true on either front. Firstly the jazz approach used by players up to and including the 70s was very similar to how one would improvise classically (albeit with an often different tonal vocabulary). Until the chord-scale system started being taught as the underpinning for jazz improvisation, jazz players looked at harmony much more like a classical composer might; you look at the pitch centre, the harmonic progression, the melody for its own sake, and you try and come up with something.
Comment: Secondly, this idea that classical harmony only cares about the tones of the key is not right either: classical harmony absolutely follows chords, it might not analyse it in the reductive way the chord scale system does, and it might not use the same nomenclature as jazz, but listen to Tchaikovsky, Chopin, Liszt, Ravel, Fauré... and you'll find they very much "follow the changes" as a jazzer would put it.  And they also more and more as the years roll on start using notes "just for colour" too, as jazzers do. It's not a coincidence either, a lot of cross-fertilisation has gone on.
Comment: This isn't meant to be one of those "jazz basically gets all of its good stuff from classical" comments, I'm not saying that at all, far from it. And I'm not a classical player, I'm really a jazz guy. But when you listen to classical music, especially from the romantic period, a lot of it absolutely sounds like a melody with changes. And not all of the same ways of moving through changes are used, of course not, as a jazzer you could literally write a lead sheet for a lot of it and it'd make perfect sense. http://youtu.be/YR5USHu6D6U http://youtu.be/KpOtuoHL45Y http://youtu.be/9E6b3swbnWg
Comment: I think you missed my comment... "there is a lot of overlap between these two approaches." Also, I think you misread some of my answer. I didn't say all jazz exclusively matches modes to chords. I said it is *typical* to jazz not to classical. Also, your wording '...only cares about the tones of the key" is not what I wrote. I think you must mean only the diatonic tones of the key, which is also not what I wrote. In fact I wrote that the melody can be decorated with tones both diatonic and chromatic.
Comment: My answer was mainly to *confirm* the OP's observation about two general approaches *without* making exclusive, misleading, or plainly false statements. Covering all the overlapping details and history of western music is beyond the scope of a Q/A forum.
Comment: Your comment about how Classical and Romantic styles "follow the changes" I think simply points out that the music is homophonic. While that's true, it doesn't really provide an answer to the OP's question or contradict anything in my answer.
Comment: My point about the classical examples wasn't just that they're homophonic, but that the melody wanders around implying chord changes, just as it does in jazz, dynamically changing what pitch sets are being used from moment to moment in order to imply different harmonic spaces.

Chord-scale thinking is simply a method to achieve what jazz (and classical) music have been doing for a while already, constructing melodies that fit a harmonic progression. The Tchaikovsky above could readily be understood in terms of modes over chords, looking bar by bar at what mode is being used for each (...)
Comment: (...) chord. Sure, Tchaikovsky didn't conceptualise his music that way, but then neither did Bird, Trane, Dizzy etc., that doesn't make the analysis less valid. They're all basically implying harmony while maintaining melodic integrity.

Your quote was "Classical style doesn't match scales to chords, but rather works with the tones of the key.". This draws a contrast that I don't think really exists (even if taken only as a simplified generalisation).

Please correct me if my interpretation of your statement is wrong, but I took this to mean that classical music works in reference (...)
Comment: (...) to the key (with some chromatic embellishment), whereas jazz works in reference to each chord, and conceptualises that in terms of modes. I don't think either is true, or at least that to the extent that either statement applies, they apply equally to both classical and jazz.

Chord scales aren't a reflection of a fundamental difference in the harmonic framework between jazz and classical, they're simply a tool some jazz players use to be able to improvise, and to analyse melody in retrospect (often from music that was never written or improvised with that approach in mind).
Answer: Yes, in your example it is absolutely overkill to think in terms of all those modes. However, what you're seeing is an example of "chord scale theory" and it's pretty central to jazz harmony. What you're seeing is just the simplest version of the central idea, which is:
Every chord should have a scale associated with it.
If you're staying strictly diatonic, you're just going to get the ioanian, the dorian, the phrygian, etc, which is just the major scale. But what if you got an E7, for example? It's probably resolving towards Am7, in which case it should take a mixolydian flat 13, flat 9, which is the go-to scale when resolving to a minor.
Another example might be Ebmaj7, which should take lydian, since it's a borrowed major chord from C minor and those will always take the lydian (we're still technically in C major, but this chord just popped up all the same).
There are a bunch of rules like that and you also have a lot of freedom of choosing other scales than the most standard ones. But at its heart, chord scale theory is meant to help you with tricky chords progressions.
Comment: I'm curious as to what the rationale behind your statement "E♭maj7 [...] should take lydian, since it's a borrowed major chord from C minor and *those will always take the lydian*". Are you simply observing this pattern, or claiming a theoretical explanation for this? Because if you have an explanation for why this is true, I'd like to hear it, if you don't mind.
Comment: Actually it's just something I got taught when taking harmonic theory in school and I myself never got it fully explained. i *think* the reasoning is that the ionian is such a tonic-inducing scale that you are going to be in a new key if you're using it. I.e. the lydian allowes you to play over borrowed chords without really modulating. Does that make sense?
Answer: If you're in the key of C major and thinking tonally, B natural will be an 'avoid' note over an F chord.  You can use it - heck, you can use anything - but it's not going to be emphasised as a harmony note.
However, if you're thinking modally, the B natural may well be strongly featured over a F chord!
Comment: A song I guess you've played hundreds of times, Moon River, does pretty well that. Bar 3. B melody over an F chord. Maybe Hank thought modally?
Comment: @Tim great example. I suppose that's the exception that proves the rule as the `B` avoid tone resolves into the `A` chord tone.
Comment: Yes, styles and 'theories' mix.  And I have to force myself not to substitute a juicy F7(#11) for the simple suspension EVERY time it occurs, save it up for the last one!


Duality - linear programming

Question: I have to find a respective dual programme for the given LP
$$ \max \ 2 x_1 + 2x_2$$
s.t. $ -x_1 - x_2 \ge -5 \\\phantom{-}x_1,\phantom{,,}x_2 \ge 0$
I got this:
$$\min \ 5y_1$$
s.t. $y_1 \ge 2 \\ y_1 \ge 0$
But I'm not convinced with this argument..
Answer: Your dual is correct. What confuses you, is that if you take the dual of the dual you take not the primal (exactly). This confusion should be resolved if you observe that $x_1, x_2$ appear only in the form $x_1+x_2$ in the LP and thus practically constitute one variable (as variable $w$ below).

Indeed, the primal can be equivalently written as $$\max b^T\mathbf x$$ s.t. $A\mathbf x\le c\\x_1,x_2\ge 0$
where $$b^T=(2,2), \qquad A=(1,1) \qquad \text{and}\qquad c=5$$
Obviously the optimal solution is $10$ for any choice of $x_1,x_2$ such that $x_1+x_2=5$. Observe that if we set $$w:=x_1+x_2$$ then the (LP) can be written as $$\max 2w$$ s.t. $w \le 5 \\ w\ge 0$
The dual is given by $$\min c^Ty$$ s.t. $A^Ty\ge b,\\ y\ge0$
which is equivalent to $$\min 5y$$ s.t. $y\ge2\\y\ge 2 \\ y\ge0$
again with obvious solution $y=2$ and value of the objective function equal to $10$ (which was expected due to the strong duality theorem).

Duality - linear programming


Corollary 1.4.4 Roy's "Special Functions" book

Question: Inside the proof of Corollary 1.4.4 Roy's "Special Functions", the book claims the following inequality without any details :
$|\dfrac{B_2}{a+ib} - \int_0^{\infty} \dfrac{B_2(t-[t])}{(a+ib+t)^2} dt| \le \frac14 \int_0^{\infty} \dfrac{1}{(a+t)^2+b^2} dt.$
My attempt : most probably $\frac14$ comes from that maximum of $B_2 - B_2(t) = t - t^2$ is $\frac14$ for $0 \le t \le 1$. Also $|a+ib+t|^2=(a+t)^2+b^2$. How these concludes the mentioned inequality of the book?
Here $B_n=B_n(0)$ is Bernoulli numbers and $B_n(t)$ is Bernoulli polynomials.
Answer: HINT:
Use
$$\frac{1}{a+ i b } = \int_{0}^{\infty} \frac{1}{(a+ i b+t)^2} dt$$


How many males and females attend an event

Question: The amount of attendees to an event follows a Poisson distribution with parameter $\lambda$. The probability of an attendee being male is $p$ and being female is $1-p$. Show that the random variables $M=$ 'amount of male attendees' and $F=$ 'amount of female attendees' follow Poisson distributions with parameters $\lambda p$ and $\lambda(1-p)$ respectively.
So far I have:
Let $A=$'number of attendees'
$$P(M=k)=\sum\limits_{i=0}^\infty P(M=k|A=i)P(A=i)=\sum\limits_{i=k}^\infty \binom{i}{k}p^k(1-p)^{i-k}\frac{e^{-\lambda}\lambda^i}{i!}=$$ $$=\frac{e^{-\lambda}(\lambda p)^k}{k!}\sum\limits_{i=k}^\infty \frac{\lambda^{i-k}}{(i-k)!}(1-p)^{i-k} =\frac{e^{-\lambda}(\lambda p)^k}{k!}\sum\limits_{j=0}^\infty \frac{\lambda^{j}}{j!}(1-p)^{j}$$
But I have no idea how to prove that this equals $\frac{e^{-\lambda p}(\lambda p)^k}{k!}$ or if this is the right approach.
Answer: Hint: $\sum_{j=0}^\infty \lambda^j (1-p)^j/j!$ is a very familiar Taylor series in $x = \lambda(1-p)$.
Comment: Oh! thanks. how did I miss that?
Answer: Note that: $$\sum_{j=0}^{\infty}\frac{(\lambda(1-p))^j}{j!}=e^{\lambda(1-p)}$$
Comment: Thanks! Don't know why I keep missing this things...


Control back button url in asp.net

Question: I want to be able to control history for back button.  If there are any postbacks on a page the back button counts these actions in history but what I want it to do is simply return to the previous page instead.
Is there a method to be able to do this?  I did look into history.replaceState(), would this work?
I did try using the onhashchange event to capture the back button being clicked but seemed to ignore it completely in chrome??
Answer: Well first of all you need to know about whether you are coding on HTML5 standards, since history object can be manipulated only in HTML5. Since you are coding ASP.NET it is valulale to know are you going to support old versions of IE and by old I mean previous to version 9.
Depending again by control, since you cannot control a web browser. Remember that Web is an open platform and user can navigate to wherever she desires to. Capturing the browser back button is not a trivial solution, it is hacky. There are too many browsers each with their click event, my suggestion is that start thinking in web scenario not a .NET application (I am coming from a .NET background myself).
I personally would either go for pushState or replaceState depending on the case. They are methods implemented across all browsers and will not be tricky to implement them. See this amazing MDN post Manipulating the Browser History . You can push a new state, create a new state and navigate to a certain point in user's browser experience, really easily and it is part of the HTML standard, so you are not hacking anything as simple as the following code:
window.history.back(); // Go back in history
window.history.forward(); //Go forward in history

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");  //Push your new desired state in URL

var stateObj = { foo: "bar" };
history.replaceState(stateObj, "page 2", "bar.html"); // Will use the current object
//insteadof creating another one

UPDATE: In case you want to force navigation to a HTML, just use the pushState or replaceState like the followings:
var enforcedPageToVisit = "
var stateObj = { pageName: "test" };
history.pushState(stateObj, "Page to visit evertime when you click back", enforcedPageToVisit);

Comment: Imagine a typical asp.net web forms application and a page has had several postbacks.  When clicking back it goes back to the previous action, I just want to be able to ignore these and go back to the previous page instead, will the above help me do this?
Comment: yes, indeed! Updated my answer for your case again.
Comment: I added the code above to Master Page and it made no difference, kept getting usual Confirm Page Submission type messages instead of returning to previous page.
Comment: add more code to question so that I can help. Where did u add the code and what did u expect it to be?

Control back button url in asp.net


Populating dropdownlist based on other dropdwonlist in struts 2

Question: I have two drop-down lists that are populated from the DB. I want to populate the second drop-down dynamically based on the selected item in the first drop-down.
Can you help me? Thanks in advance.
Answer: Struts 2 has a double select tag that can do this:
http://struts.apache.org/2.1.6/docs/doubleselect.html


Muscle pain when i do racewalking

Question: On the spotted zone marked in red below, I get pain after 4-5 days of race-walking. Sometimes it hurts only while walking or racewalking. But today I can`t even run.

I got a problem there before athletics from football and tennis, I guess.
I need some opinions on what could have caused it and suggestions on how to avoid it from happening again.
Could it be from increasing the intensity of training in the last 3 months?
From 10 km/day 4 days/week, now I do 15-20 km/day 6 days/week.
Answer: DISCLAIMER: I am not a doctor, nor do I claim any sort of medical expertise.  If you are experiencing discomfort beyond normal soreness, I would recommend seeing a competent doctor.  I merely intend to impart my personal insights and experience.
I'm not sure if I understand "Where is the red spoted zone", but the picture you provided is pointing to the sartorius (the upper line) as well as the quadricep ("quad" - the lower line).  If both of these are hurting it's probably two separate issues that could've been caused by any number of things.  The sartorius connects the interior knee to the anterior (outside) hip.  If you're consistently getting problems with this, your spine could be out of alignment which is causing your hip to pull in an unnatural direction.  As stated before, I would suggest seeing a competent chiropractor/sports medicine doctor.
I consider myself to be an above-average runner, but I've never run the 15-20k/day for 6 days/week as you mentioned. Your body needs rest and time to recover.  If you don't let your muscles recover, after time they become stressed and incredibly susceptible to increased injury (especially when there might be an existing injury that's been neglected).
This article talks about the necessities of recovery and how it might vary from person to person.  It might give you a better idea of how to maximize your recovery and workouts.
My suggestion: see a doctor.  Determine what the issue is, then when you've fixed it, you can ask for better help about how to avoid it.

Muscle pain when i do racewalking


Stirling number of the first kind expansion?

Question: I'm trying to expand this expression (for $1 \leq j \leq n+1$)
$$
\prod_{i=1 ; i\neq j}^{n+1} (x-i)
$$
in terms of Stirling numbers. The falling factorial $(x)_{n}$ is defined as
$$
(x)_{n}=\prod_{i=0}^{n-1} (x-i)=\sum_{i=0}^{n}(-1)^{n-i}
\begin{bmatrix}
n\\
i
\end{bmatrix}x^i
=\sum_{i=0}^{n}s(n,i)x^i
$$
where $s(n,i)$ is the Stirling number of the first kind.
This gives me the expression..
$$
\prod_{i=1 ; i\neq j}^{n+1} (x-i)=\frac{1}{x-j}\sum_{i=1}^{n+2}s(n+2,i)x^{i-1}
$$
Formula fixed.
Edit:
Formula is fixed, this solution works.
Answer: Lets get the definition of the Stirling numbers (of the first kind) in terms of falling factorials right
\begin{eqnarray*}
(x)_{n}=\prod_{i=0}^{\color{red}{n-1}} (x-i)=\sum_{i=0}^{n}(-1)^{n-i}
\begin{bmatrix}
n\\
i
\end{bmatrix}x^{\color{red}{i}} =\sum_{\color{red}{i=1}}^{n}(-1)^{n-i}
\begin{bmatrix}
n\\
i
\end{bmatrix}x^{i}.
\end{eqnarray*}
The zeroth term is zero $\begin{bmatrix}
n\\
0
\end{bmatrix}=0$ and can be included or ommited (for convenience.) Have a quick look at the numbers in Wiki
https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind#Table_of_values_for_small_n_and_k
In your formula there is no need for $i \neq j$ and it should look like this
\begin{eqnarray*}
\prod_{i=1}^{n} (x-i)=\sum_{i=1}^{n+1}(-1)^{n+1-i}
\begin{bmatrix}
n+1 \\
i
\end{bmatrix}x^{i-1}.
\end{eqnarray*}
Edit : The Stirling numbers satisfy the following recurrence relation
\begin{eqnarray*}
\begin{bmatrix} m+1 \\ k \end{bmatrix} = m\begin{bmatrix} m \\ k \end{bmatrix} + \begin{bmatrix} m \\ k-1 \end{bmatrix}. \\
\end{eqnarray*}
If you wish to omit one of the factors, you will need to omit the associated iteration and define a new sequence of numbers
\begin{eqnarray*}
\begin{bmatrix} m+1 \\ k \end{bmatrix} = m\begin{bmatrix} m \\ k \end{bmatrix} + \begin{bmatrix} m \\ k-1 \end{bmatrix} \! m=1,\cdots,j-1 \\
\begin{bmatrix} m+1 \\ k \end{bmatrix} = (m+1)\begin{bmatrix} m \\ k \end{bmatrix} + \begin{bmatrix} m \\ k-1 \end{bmatrix} \! m=j,\cdots,n. \\
\end{eqnarray*}
Comment: Oh ok, the article i was referencing redefined the index. Thanks, this makes sense.
Comment: I am trying to get the expression for $i \neq j$ though, i have updated the question with your formulas..


How can I reach the presentViewController method in my ViewController with this hierarchy? VC -> TableView -> Cell -> Button

Question: How can I reach the presentViewController method in my ViewController with this hierarchy?
<code>UIViewController -> UITableView -> UITableViewCustomCell -> UIButton
</code>
UIButton triggers foo, and foo is inside UITableViewCustomCell
<code>- (void)foo
{
    TWNumericKeyboardController *vc =
       (TWNumericKeyboardController *) [mainStoryboard instantiateViewControllerWithIdentifier:@"NumericKeyboard"];
}
</code>
From here, I need to reach my ViewController, so that I can call presentViewController.
How can I do this?
Thank you!!
Comment: Is there a reason you can't put the button's action in the controller that needs to do the presentation?
Comment: ... I really have to get some rest. Thank you Sir!
Answer: I would suggest putting the button's action method in the controller that needs to do the presentation. Depending on your current design, this might be a bit of work right now to set up, but I think it will pay off in understandability and flexibility in the future.


Liferay module listener : Unable to get who made a change to the model

Question: I have to create custom auditing for the User model to track by whom the user has been deleted. I have tried to create a Liferay module listener for the User model, but I am not able to get the detail by whom the user is being deleted.
Is there any way to get details about who made a change to the User model in Liferay module listener?

My Liferay environment detail

Liferay portal : liferay-ce-portal-tomcat-7.0-ga5
Database : postgres (PostgreSQL) 9.5.17
IDE : eclipse-oxygen 4.7.3a

/*
 * Below is the sample code that I have tried to create the Liferay module listener for the User model
 */
package com.test.useraudit.modellistner;

import org.osgi.service.component.annotations.Component;

import com.liferay.portal.kernel.exception.ModelListenerException;
import com.liferay.portal.kernel.model.BaseModelListener;
import com.liferay.portal.kernel.model.ModelListener;
import com.liferay.portal.kernel.model.User;

@Component(
    immediate = true,
    service = ModelListener.class
)

public class CustomUserModelListner extends BaseModelListener<User>{
    @Override
    public void onBeforeRemove(User user) throws ModelListenerException{
        System.out.println("In onBeforeRemove method");
        System.out.println("User detail :");
        System.out.println(user);
        super.onBeforeRemove(user);
    }

    @Override
    public void onAfterRemove(User user) throws ModelListenerException{
        System.out.println("In onAfterRemove method");
        System.out.println("User detail :");
        System.out.println(user);
        super.onAfterRemove(user);
    }
}

Answer: Yes it's possible.
There's an implicit thread local variable called ServiceContext that contains the calling context details.
Sample:
   @Override
    public void onBeforeRemove(User user) throws ModelListenerException{
            ServiceContext serviceContext =
                 ServiceContextThreadLocal.getServiceContext();

            System.out.println("Calling user:" + serviceContext.getUserId());
    }

Answer: Yes it's possible and that's included OOTB in Liferay. The delete events already it's trace. You can see the Audit Event and System Event table.
You could use the Audit Event Framework for your customisations.


Row won't add to the end my JTable using vectors

Question: I'm creating a Swing Application for work and I'm having issues with my JTable.
The process is to check to see if a file exist and if it does, retrieve the information from the file and populate the JTable.  This works fine.
I enter data into my textfields, select from dropdown box and when I click on the save button, I write the information to the file (which gets completed with no issue) and after the file is created, I would like to have the row added to my the end of the table.  This is where I'm having issues.
I end up calling the addRow method in the OutputTable my passing the data from what the user has entered.  The data is stored in the vector properly as you can see here:
d1 is[999999999, 27-May-2016, asdfasdf, OCOB, UA2, 1, asdf,     sadsadfasdf, IU2, 1, 28-May-2016, In Progress]
d2 is[999999999, 27-May-2016, asdfasdf, OCOB, UA2, 1, asdf,     sadsadfasdf, IU2, 1, 28-May-2016, In Progress]

But my dtm.addRow(data) won't add the row to the table.
Can someone help?
This is my class that retrieves the data from the file to populate the table at the beginning of my application.  Action is performed by a button.
My addRow method is in this class.
public class OutputTable {

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void populateTable(Vector data){

        Vector columnName = new Vector(12);

        columnName.addElement("ID");
        columnName.addElement("DATE
Retrieve");
        columnName.addElement("Name of
Module");
        columnName.addElement("Type of
Module");
        columnName.addElement("Environment
retrieve from");
        columnName.addElement("Stage
retrieve from");
        columnName.addElement("Working
location");
        columnName.addElement("Description
of changes");
        columnName.addElement("Environment
moved to");
        columnName.addElement("Stage
move to");
        columnName.addElement("Date of the
endevor");
        columnName.addElement("Current
Work
Status");

        DefaultTableModel dtm = new DefaultTableModel(data, columnName);

        final JTable table = new JTable();

        table.setModel(dtm);
        table.setFillsViewportHeight(true);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());

        JScrollPane scrollPane = new JScrollPane(table);
        table.getTableHeader().setPreferredSize(new Dimension(scrollPane.getWidth(),60));
        scrollPane.setViewportBorder(UIManager.getBorder("Table.scrollPaneBorder"));
        scrollPane.setBounds(10, 425, 875, 195);

        EndevorChanges.frmEndevorChanges.getContentPane().add(scrollPane);

}

    public static void addRow(String UserID, String DateRtrv, String ModRtrv, String ModType, String EnvFrom, String StgFrom, String WrkngLct, String Desc, String EnvTo, String StgTo, String DateTo, String WrkSts) {

        System.out.println("Im inside the addrow method.");

        Vector<Vector<String>> data = new Vector<Vector<String>>();
        Vector<String> d = new Vector<String>();
        Vector columnName = new Vector(12);
        String[] strngArray = {UserID, DateRtrv, ModRtrv, ModType, EnvFrom, StgFrom, WrkngLct, Desc, EnvTo, StgTo, DateTo, WrkSts};

    /*  columnName.addElement("ID");
        columnName.addElement("DATE
Retrieve");
        columnName.addElement("Name of
Module");
        columnName.addElement("Type of
Module");
        columnName.addElement("Environment
retrieve from");
        columnName.addElement("Stage
retrieve from");
        columnName.addElement("Working
location");
        columnName.addElement("Description
of changes");
        columnName.addElement("Environment
moved to");
        columnName.addElement("Stage
move to");
        columnName.addElement("Date of the
endevor");
        columnName.addElement("Current
Work
Status");
        */
        DefaultTableModel dtm = new DefaultTableModel(data, columnName);

        JTable table = new JTable();

        //table.setModel(dtm);

        System.out.println("the data is: " + data.toString());

        for (int lmnts = 0; lmnts < 12; lmnts++){
            d.add(strngArray[lmnts]);
            System.out.println("element" + lmnts + " value is: " + strngArray[lmnts]);
            System.out.println("d1 is" + d);
        }
        data.add(d);

        System.out.println("d2 is" + d);

        dtm.addRow(data);
        //dtm.insertRow(4, data);

        dtm.fireTableDataChanged();

        table.repaint();

        System.out.println("at the end of the method");

    }

}

Answer: Your row is in fact being added to a JTable's TableModel just fine, but the problem is that it's being added to the wrong JTable. Current problems that are immediately apparent:
public class OutputTable {

    public static void populateTable(Vector data){

        // .... code removed for brevity's sake

        // you create a *local* DefaultTableModel variable here. It is only visible within this method
        DefaultTableModel dtm = new DefaultTableModel(data, columnName);

        // Likewise, this JTable variable is *local*
        final JTable table = new JTable();

        // .....
    }

    public static void addRow(String UserID, String DateRtrv, String ModRtrv, String ModType, String EnvFrom, String StgFrom, String WrkngLct, String Desc, String EnvTo, String StgTo, String DateTo, String WrkSts) {

        // .....

        // this guy is a completely new unique DefaultTableModel object, again placed
        // within a local variable, one only seen within this method.
        DefaultTableModel dtm = new DefaultTableModel(data, columnName);

        // and a new local JTable
        JTable table = new JTable();

        // here you "repaint" this JTable, and it's not even displayed in your GUI
        table.repaint();

    }
}

You're declaring your variables and assigning your tablemodel and your JTable within a method, meaning these variables are only visible within this method and nowhere else.
You're then creating a new JTable and new table model within a separate method, updating the model, and expecting the visualized table (a completely separate and unique object) to be magically updated -- not going to happen.
You're over-using statics by doing any of this within static methods.

Suggestions:

Create private instance JTable and DefaultTableModel variables.
Create objects and assign them to these variables, either in a constructor or in an instance method.
When you need to update the model, use the variable above, and add a row. Problem solved!
Note that a BAD solution is to try to use static variables. Seriously, don't go there.

Also:

Try to get most all your code out of the static realm and into the instance realm.
The main method should be short, and should only be used to create your key objects, and then start them running, and that's it.
You appear to be using null layouts and setBounds(...). While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
You're mixing model and view code in dangerous and confusing ways. If you can separate these guys cleanly, you'll have a much easier time debugging and enhancing your program. For instance the table model creation and modification code should be separate from the code that adds JTables and JScrollPanes to the GUI.
Comment: thanx will go and modify my logic


Find all the sym links that point to a particular file

Question: I know that ls -l will give you the "number of links" but I'm looking for a command or combination of commands that will give me a list of all the symbolic links that point to a particular file.
Comment: The links you see with ls -l are *hard* links.  Symbolic links are something else entirely.  Just out of curiosity, why do you care about symbolic links?
Answer: Something like this might work:
find -L / -samefile /path/to/your/file
Obviously you'll need to replace /path/to/your/file with the file in question.
A brief explanation:

-L = treat symbolic links as if they were the file to which they refer
/ = search from the root of the file system
-samefile = find the files that are the same as this one
Comment: Huh.  I consider myself fairly conversant with `find` but I swear I learn about an option I'd never heard of before every couple weeks...
Comment: I didn't know about it myself until I read through the man page in order to answer this question ;)


Where in this example is masonry.js being initialized?

Question: In this example (which is working perfectly), http://codepen.io/anon/pen/CotJv
masonry.js is included, but after reading other tuturials, my understanding is that you have to not only import the script but also initialize masonry.
I currently have this codepen example working locally on my machine, but the reason I ask about how to initialize masonry is that I'm trying to change the gutter size, and I don't see anywhere to do that.
For example this line off the masonry.js website shows that you can set the columnWidth.
<code>var container = document.querySelector('#container');
var msnry = new Masonry( container, {
  columnWidth: 200,
  itemSelector: '.item'
});
</code>
In the codepen I've pasted above, I do not see anything similar to this line, so I'm wondering where I need to go in the code to set columnwidth and guttersize.
Also this codepen is basically a direct clone of the Tympanus masonry.js demo. http://tympanus.net/codrops/2013/07/02/loading-effects-for-grid-items-with-css-animations/
I have imported that entire demo from Tympanus onto my local machine and I don't see masonry.js being initialized anywhere.  There is something I'm definitely not understanding here.  Can I just take the snippet I posted above and paste in in my html in between  tags?  Any help would be appreciated here, all I'm trying to do is be able to control the column size and space between each picture.
Answer: Search for 'initialize masonry' in the HTML column
Comment: Okay so masonry.js is initialized inside animonscroll.js?


How is the ninth a fifth below a fifth?

Question: I am reading Vincent Persichetti's "Twentieth Century Harmony" and in the first chapter he mentions that

The most effective support tones are the fifth and the ninth, the fifth because it's a strong resonant interval and the ninth because it's the fifth below a fifth.

I didn't understand the reason the ninth is a an effective support tone is because it's the fifth below a fifth.. because if our bottom tone is an A (its fifth is an E and its ninth is a B) the fifth below the E is an A, not a B
So how is the ninth a fifth below a fifth?
Comment: Hi @Gilgamesh. The problem here is that you haven't quoted the book correctly. You've posted what looks like a quote in your question, but is actually text paraphrased by you! See my answer (below) for an explanation.
Answer: The ninth of a chord is, of course, not a fifth below the fifth of a chord.
However, I have just re-read the page in question from Persichetti's excellent Twentieth Century Harmony. Context is everything. This section of the book is dealing with resonance of chords, in particular in relation to the spacing of the Harmonic Series. The confusion here may be largely due to the passage being misquoted in the OP's question. Here is the full passage preceding the sentence quoted by the OP:

The principal of supporting resonance by lower sonority is occasionally applied to chordal structures. This colour device is used primarily when the composer works with chords in the upper register and needs to fill in toward the bass. In lower registers, the addition of tones is limited by the danger of muddy progressions. Most effective supporting tones are the fifth or ninth below the bottom tone of the chord because the fifth is a strong and resonant interval and the ninth is a fifth below the fifth.

Persichetti is describing notes a fifth below the existing bottom note of a chord and a ninth below the existing bottom note of a chord. This "ninth below" is a fifth below the "fifth below"! The passage below should make this clear:

Comment: All I can say is - +1... It probably helps to be ...well read amongst other things!
Comment: I've only answered the question...
Comment: Yes! Always a SE problem - giving a great answer for a flawed question. I would never have spotted this had I not read the book years ago, and just started re-reading it today...!
Answer: Seems a strange way to portray notes and intervals!
Taking A as root, a P5 above it is E. You're correct. A P5 above E is B. As in E>B =P5. I guess that's what the writer has in mind. It's generally accepted that intervals are counted from lower note upwards. It could have been phrased a whole lot better!
Comment: Actually, see Bob Broadley's answer: It's not that the phrasing is poor but that the quotation is taken out of context.  In context, it is clear that the "fifth" is the fifth *below,* so the ninth below *is* actually a fifth below the fifth.
Comment: Even worse - it isn't actually a quotation at all...
Answer: To address the 9th issue given any starting note (in the bass) the 9th is a 5th above the 5th of that note.  So in the key of C the 5th is G and the 5th of G is D, the second (or ninth) of C.  This pattern follows through the circle of 5ths.  In fact there is a harmony text (I forget the author) that demonstrates building the major scale in just tuning from three triads built on the I, the 5th above V, and the "5th" below IV.  And I place quotes to illustrate the possible confusion of a 5th below.  It is possible that when the author says 5th below he/she means descending to the 5 of the tonic.  But that would be an interval of a 4th (C-->G is a 5th, and G-->C is a 4th).  Notice that an interval of 5th below is the 4th of the tonic (walking down a 5th from C gets you to F).  The 5th below that (in my notation) is the dominant 7th of the tonic (as your example illustrates), e.g. the 5th below F is Bb.
Not sure how this author uses the term "5th below".  If it is consistent throughout the text the other occurrences should help.  It is also possible that the author means is judging these intervals relative to the lowest and not the tonic (but that's a stretch imo).  As for these being "supporting" intervals does the author discuss why this is in more detail?  Is it presumably based on resonance between harmonics?  If so then relative to what note are these intervals supporting?

How is the ninth a fifth below a fifth?


Will MySQL ALTER TABLE reformat field data?

Question: I need to alter a table to change the Type of a column. If the current column Type is DECIMAL(8,2) and I alter that column to be DOUBLE, will the already-existing data in the column also be changed to reflect the column's new Type?
Comment: Create a test table with some data with DECIMAL(8,2). Then do the alter table. After this test tell us what happened!
Comment: I think it does but you could just create a database and give it a go with some test data. Cheers
Comment: @OMG Ponies -- Thanks for the edit, much better now.
Answer: It should.  However, always be safe when altering existing tables.
My preferred way of doing this type of operation is:

make a backup
create a new column
update all rows moving the old data over to new column
inspect the new column for anything wrong and fix if necessary
delete the old column


jenkins pipeline readYaml how to use variable to specify key

Question: Suppose the yaml file is like this:
#test.yaml
0.6.5.1.0:
  module:
  - mysql
  - zk

0.7.1.0.0:
  module:
  - java

Now I want to get the module list of specified version, and the version is a variable, I try to write the jenkins pipeline like this:
yamlFile = readYaml file: test.yaml
version = '0.7.1.0.0'
moduleList = yamlFile.get("${version}").get(module)

but this can't work, yamlFile.get("${version}") is a null object, how can I achieve this?
Answer: This works for me:
pipeline {
    agent any
    stages {
        stage ('read') {
            steps {
                script {
                     def data = readYaml text: """
0.6.5.1.0:
  module:
  - mysql
  - zk

0.7.1.0.0:
  module:
  - java
  """
                   version = '0.7.1.0.0'
                   println data.get(version).get('module')
               }
            }
        }
    }
}

The output:
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on server in /home/user/workspace/task
[Pipeline] {
[Pipeline] stage
[Pipeline] { (read)
[Pipeline] script
[Pipeline] {
[Pipeline] readYaml
[Pipeline] echo
[java]
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

Comment: For some reason this is not working for me when I try to use it with toString() method. Here's my code

`envid = "dev"
  println(envid) //this is printing the app envid for example dev here
  datas = readYaml ( file: 'dev.yml')
   id = datas.dev.id.toString() /it's working and picking
  name = datas.get(envid).name.toString() // this is not working
`                              and dev.yml looks like
`
dev:
  id: 1
  name: test.      `
any suggestions here? @MaratC
Comment: if you ever get stucked into situation like mine where it does not work this way then check the type of the variable and convert it to string so that the get function can take it so my solution was to convert envid = var.toString() which resolved my problem.


Vim: Problems with indentation/alignment

Question: So I've got a problem (obviously). I read an interesting article about "Smart Tabs", and I've tested this in Emacs and it works perfectly fine.
So currently I'm using Emacs because I've tried this in vim and I can't quite get it to work. Here are the lines of my .vimrc which I think are pertinent to indentation.
<code>set autoindent                " auto/smart indentation
set cindent
set preserveindent
set copyindent
set smarttab                  " tab and backspace are smart
set tabstop=4                 " 4 spaces
set softtabstop=4
</code>
If you think something else could be causing the unexpected behavior as outlined below, my vimrc is here for you.
EXPECTED BEHAVIOR
I want a sample program to look like this, with me only typing the code and pressing the enter key every-so-often.
(each "->  " represents a tab, each "." represents a space)
<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[])
{
->  printf ("%s\n",
->  ........teststring);
->  function_with_many_arguments (bacon,
->  ..............................indentation,
->  ..............................problems);
->  return 0;
}
</pre>
</code>
That is, I want vim to use tabs ONLY for indentation; NEVER for alignment.
This is because if someone decreases their tab size, I want the function calls and multi-line argument sets to be aligned properly regardless of how many characters a tab is equal to.
CURRENT BEHAVIOR
I've looked at all of the resources I could find, and that's how I put together my vimrc.
Right now, instead of doing the expected behavior, this is what code looks like instead:
<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[])
{
->  printf ("%s\n",
->  ->  ->  teststring);
->  function_with_many_arguments (bacon,
->  ->  ->  indentation,
->  ->  ->  problems);
->  return 0;
}
</code>
What am I doing wrong? It looks to me like any and all alignment is just two tab characters, whatever they happen to be, and I want it to indent to the right column with spaces instead.
Comment: `:set cino=(0` taken form [here](http://stackoverflow.com/questions/88931/lining-up-function-parameter-lists-with-vim)
Comment: The linked duplicate doesn't answer the (mixed tab / space) indentation part, and unfortunately, that's hard to achieve automatically in Vim.
Answer: I think this problem went away from me when i started using YouCompleteMe plugin with clang completion. Btw it's one of the best plugins if you seriously want to develop C in Vim.


Sketching the vector field of -(r/||r||^3) where r = ?

Question:
Question: Sketch the vector field $$\vec F(x,y) = -\frac{\vec r}{||\vec r||^3}$$ in the plane, where $\vec r = \langle x,y\rangle$. Select all that apply.

A. The length of each vector is 1.
B. The vectors decrease in length as you move away from the origin.
C. All the vectors point toward the origin.
D. All the vectors point away from the origin.
E. The vectors increase in length as you move away from the origin.

What am I exactly graphing? I know $\frac{\vec r}{||\vec r||}$ is just the unit vector and it may have something to do with the question, but I'm not exactly getting how to sketch the actual graph.
Comment: Well, if $r/|r|$ is a unit vector, then multiplying it by $1/|r|^2$ will make it smaller as $r$ grows, right?
Answer:
This is how your vector field looks like.
Taken from http://www.lightandmatter.com/html_books/lm/ch22/ch22.html
That is, your vector field is the gravity forces field generated by a mass at the origin, up to a constant. To graph it it might help to note that the modulus of $F$ is a radial function and that the direction points to the origin...
Comment: The arrows should point outwards, no?
Comment: @YoTengoUnLCD No,  the minus sign is telling you that the directions are like in the picture. Take an easy example; $F(1,0)=(-1,0)$.
Comment: Oh yeah, of course, I thought the function was $r/|r|$! Sorry.


Find the 50th word of all permutations of word AGAIN ,when arranged accord to dictionary

Question: I have to Find the 50th word of all permutations of word AGAIN ,when arranged accord to dictionary.?There are 60 words with or without meaning ,but how do i find out 50th word .Thanks
*ATTEMPT**
Comment: why this question had been put on hold ?
Answer: Hints

The problem is slightly complicated because AGAIN contains two As.  First solve the problem for the word ABCDE.
How many permutations of ABCDE begin with A?  How many begin with B?  What letter does the 50th permutation begin with?  Consider  only the permutations that begin with that letter:  how many come before the permutation you are looking for and how many come after?
Comment: Can you please explain in my question about 50 th word .
Answer: Characters in ascending order=${A,G,I,N}\$
Number of words starting with A $=4!=24$.
Number of words starting with G $=\frac{4!}{2!}=12$.
Number of words starting with I $=\frac{4!}{2!}=12$.
Total numbers up until now=48.
49th word=NAAGI
50th word=NAAIG
Comment: how did you come up with 49th word ?
Comment: 49th number should begin with 'N' as you can see above and since it is the first word with N so it should be lexicographically increasing from the second term as {A,A,G,I} .


Why my program exit after I enter the key

Question: I am confused about this problem, cannot understand why the program always exited after I enter the first data. How to enter the String data?
import java.util.Scanner;
public class Caesar {

    public static String encode(String enc, int offset) {
        offset = offset % 26 + 26;
        StringBuilder encoded = new StringBuilder();
        for (char i : enc.toCharArray()) {
            if (Character.isLetter(i)) {
                if (Character.isUpperCase(i)) {
                    encoded.append((char) ('A' + (i - 'A' + offset) % 26 ));
                } else {
                    encoded.append((char) ('a' + (i - 'a' + offset) % 26 ));
                }
            } else {
                encoded.append(i);
            }
        }
        return encoded.toString();
    }

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        System.out.print("Enter key: ");
        int key = in.nextInt();
        System.out.print("Enter line: ");
        String str = in.nextLine();

        System.out.println( Cipher.encode( str, key ));

    }
}

Comment: @Jens readLine -> nextLine
Comment: @ScaryWombat  Yes you are right sorry
Answer: Because when you enter the Key you also push the <ENTER> key.  This char needs to be consumed before continuing, so try
    Scanner in = new Scanner(System.in);
    System.out.print("Enter key: ");
    int key = in.nextInt();
    in.nextLine();
    System.out.print("Enter line: ");
    String str = in.nextLine();

    System.out.println( Cipher.encode( str, key ));

Comment: Thank you so much!
Answer:  Scanner in = new Scanner(System.in);
        System.out.print("Enter key: ");
        int key = in.nextInt();
        System.out.print("Enter line: ");
        if (in.hasNext()) {
            String str = in.nextLine();
        }

or you can get input in a while


Core Data fetch returns zero records though table is not empty

Question: I'm a Swift newbie, building a Core Data app. I've built and run a sample app from Ray Wenderlich's site which works as expected.
I've lifted and modified the following excerpt from Ray's app:
var people: [NSManagedObject] = []

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    //1
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return
    }

    let managedContext = appDelegate.persistentContainer.viewContext

    // 2
    let fetchrequest = NSFetchRequest<NSManagedObject>(entityName: "Person")

    // 3
    do {
        people = try managedContext.fetch(fetchrequest)
        print("\(people.count) fetched from Person")
    }
    catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }
}

This works as expected. However, the following is what I've implemented in my app:
var players: [NSManagedObject] = []

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return
    }

    let managedContext = appDelegate.persistentContainer.viewContext

    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Golfer")

    do {
        players = try managedContext.fetch(fetchRequest)

        print("\(players.count) fetched from Golfer")
        // Load any saved players, otherwise load sample data.
        if players.count == 0 {
            // Load the sample data.
            // There are no players to load
            os_log("Loading sample players", log: OSLog.default, type: .debug)
            loadSamplePlayers()
        }
    }
    catch let error as NSError {
        print("Could not fetch Golfers. \(error), \(error.userInfo)")
    }
}

The sample code always returns the full results of the Person table and the person array count is always equal to the number of rows in the table.
However, for my version, it always reports that the players array has a count of zero. Consequently, the loadSamplePlayers() method is called each time (which adds three sample records into the Golfer table).
Using an SQL Lite database inspector, I can see that the Golfer table continues to grow after each invocation of the app.
I'm stumped on why these two, near-identical, code samples should behave differently.
Any insights would be much appreciated.
Thanks!
EDIT:
Here's the loadSamplePlayers() method and printDatabaseStats() which is also referenced:
private func loadSamplePlayers() {

    let sampleFirstNames: [String] = ["Casper", "Jocelyn", "Arthur"]
    let sampleLastNames: [String] = ["Vitturio", "Brown", "Mullard"]
    let sampleEmails: [String] = ["email@example.com", "email@example.com", "email@example.com"]
    let sampleHandicaps: [Double] = [16.2, 6.4, 27.2]

    let entity = NSEntityDescription.entity(forEntityName: "Golfer", in: managedObjectContext!)!

    for i in 1...3 {
        let player = NSManagedObject(entity: entity, insertInto: managedObjectContext)

        player.setValue(sampleFirstNames[i-1], forKeyPath: "firstName")
        player.setValue(sampleLastNames[i-1], forKey: "lastName")
        player.setValue(sampleEmails[i-1], forKey: "emailAddress")
        player.setValue(sampleHandicaps[i-1], forKey: "exactHandicap")
        // player.setValue(sampleMugshots[i-1], forKey: "mugShot")

        print("Prepare to save")

        do {
            try managedObjectContext?.save()
            players.append(player)
        }
        catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }

        print("There are now \(printDatabaseStats()) in the Golfers table")
    }
}

private func printDatabaseStats() -> Int {
    var count = 0
    managedObjectContext?.performAndWait {
        if let golferCount = try? self.managedObjectContext!.count(for: NSFetchRequest(entityName: "Golfer")) {
            print("\(golferCount) Payers")
            count = golferCount
        }
    }

    return count
}

This appears to work successfully as the print(...) methods produce the expected console messages and the Golfer table is populated and contains the rows as defined.
Comment: Hmm, not sure that looks right to me. Are you using the same managed context when you insert as when you retrieve?
Comment: Are you sure your entity name is correct? The tutorial uses "Person", not "Golfer". Can you show the `loadSamplePlayers()` method?
Comment: I've just edited the original question to include the method. NOTE: I'm attempting to implement the technique from the first sample in my own app which uses Golfer rather than Person.
Comment: The behaviour I'm seeing would make sense if I wasn't. As much of code is based on samples I'm trying to repurpose, it's possible I've defined the managed context twice. I'll follow this thread and report back.
Comment: Thanks for the steer. I picked through the code and there was a class variable*managedObjectContext* that was setup differently to how *managedContext* was. I made these the same and the issue is now resolved. Thanks again.
Comment: Awesome! Glad you got it resolved. Multiple managed object contexts are always fun.
Answer: Not included in the original question was a class definition, thus:
var managedObjectContext: NSManagedObjectContext? = (UIApplication.shared.delegate as? AppDelegate)?.managedObjectContext

This is defined differently to:
let managedContext = appDelegate.persistentContainer.viewContext

yet I was using them as if they were the same. I normalised the two so they are identical and the problem has gone.
Comment: Maybe you can accept your own answer so that it is closed?


Convergence of a series with repeated sines

Question: Show that the series
$$
\sum_{n=1}^\infty \frac{\sin\big(\sin(n)\big)}{n},
$$
converges.
More generally, show that for every $k\in\mathbb N$ the series
$$
\sum_{n=1}^\infty \frac{\sigma_k(n)}{n},
$$
converges, where $\sigma_1(x)=\sin(x)$ and $\sigma_{k+1}(x)=\sin\big(\sigma_k(x)\big)$.
Note. I am looking for an elementary proof, if such is available. I do know that such elementary proof exists, for $k=2$, since that case was  qualifying exam (University of Adelaide) a few years ago. On the other hand, I know of a non elementary proof (for $k$ general), using the nontrivial fact that $\dfrac{1}{2\pi}$ has finite irrationality measure. I imagine that any proof would have as a first step establishing the fact that the sequence
$$
\sum_{j=1}^n \sigma_k(j), \quad n\in\mathbb N,
$$
is bounded.
Update. Actually, using advanced tools (i.e., irrationality measure),
it turns out that even
$$
\sum_{n=1}^\infty \frac{\sigma_k(n)}{n^a},
$$
converges, for every $a>0$, and $k\in\mathbb N$,
while the same tools can not determine whether
$$
\sum_{n=1}^\infty \frac{\sin\big(\sin(\beta n)\big)}{n^a},
$$
converges, for every $\beta$.
Comment: Achtung, @Lucian: $\sin(\sin x)<\sin(x)$ only if $\sin x> 0$, i.e. only if $\left\lfloor\frac{x}{\pi}\right\rfloor$ is even!
Comment: $\sin x<x\iff\sin(\sin x)<\sin x$. (You can verify this geometrically, by noticing that the arc *x* is larger than the chord, which itself is larger than the sine, as the former is the hypotenuse, and the latter is the leg). Then use the fact that $\displaystyle\sum_{n=1}^\infty\frac{\sin n}n$ [converges to](http://en.wikipedia.org/wiki/List_of_mathematical_series#Trigonometric_functions) $\dfrac{\pi-1}2$, which you can prove by using either [Euler's formula](http://en.wikipedia.org/wiki/Euler's_formula), or the [alternating series test](http://en.wikipedia.org/wiki/Alternating_series_test).
Comment: What does "finite irrationality measure" mean?
Comment: Irrationality measure: http://en.wikipedia.org/wiki/Irrationality_measure#Irrationality_measure
Comment: Ah, that explains it, thnx.
Comment: Taking $A_k(n):=\sum_{j=1}^n \sigma_k(j)$ and $\phi(t):=\frac{1}{t}$ in Abel's summation formula (http://en.wikipedia.org/wiki/Abel%27s_summation_formula) it is
enough to prove that $\sum_{j=1}^n \sigma_k(j)=O\left(\frac{n}{\log^2 n} \right)$. I don't know it helps, but to transform a  sum to an integral generally easier to estimate.
Answer: To prove the convergence it is sufficient to show that
$$\left|\sum_{n=1}^{+\infty}\frac{\sin(kn)}{n}\right|= \left|\frac{\pi-k}{2}+\pi \left\lfloor\frac{k}{2\pi}\right\rfloor\right| < \frac{\pi}{2} \tag{1}$$
by regarding the LHS as the imaginary part of a geometric series and by applying Abel's lemma.
Then we have that the Fourier coefficients of $\sin(\sin x)$ decay pretty fast since $\sin(\sin x)\in C^3([-\pi,\pi])$. If we are allowed to write $\sin(\sin x)$ as its Fourier series and to switch the sums (this is crucial) we have:
$$\left|\sum_{n=1}^{+\infty}\frac{\sin(\sin n)}{n}\right|\leq K\sum_{k=1}^{+\infty}\frac{\pi}{k^2},$$
for istance. I am expecting that the same holds for $\sigma_k(x)$, since, in general, if $f(x)$ is an odd periodic function belonging to $C^{3}(\mathbb{R})$ and we are allowed to switch sums,
$$\sum_{n=1}\frac{f(n)}{n}$$
converges because the $k$-th Fourier coefficient of $f(x)$ is $o(k^{-2})$ and $(1)$ holds.
By using Bessel functions we can write:
$$\sin(\sin n)=\sum_{k=0}^{+\infty}2\cdot J_{2k+1}(1)\sin((2k+1) n),\tag{2}$$
where the convergence is uniform, but now we have to justify the sum-switch procedure. This is more-or-less the same as proving that the partial sums of $\sin(\sin n)$ are bounded. Exploiting $(2)$ we get:
$$\sum_{n=0}^{N}\sin(\sin n)\leq\sum_{k=0}^{+\infty}\frac{2\cdot J_{2k+1}(1)}{|\sin(k+1/2)|},$$
and we have to prove that the RHS is bounded. If we define $\|x\|$ as the distance between $x$ and the closest integer, we have:
$$\sum_{k=0}^{K}\frac{2\cdot J_{2k+1}(1)}{|\sin(k+1/2)|}\leq \sum_{k=0}^{K}\frac{1}{4^k(2k+1)!\cdot|\sin(k+1/2)|}\leq \sum_{k=0}^{K}\frac{1}{2^{2k+1}(2k+1)!\cdot\left|\frac{2k+1}{2\pi}\right|},$$
so, in order to prove that the partial sums of $\sin(\sin n)$ are bounded, it is sufficient to prove that there exists a positive number $C$ such that
$$
\left|\frac{2k+1}{2\pi}\right|\geq\frac{C}{(2k+1)!},\tag{3}
$$
holds for every $k$. This is much weaker than requiring that $2\pi$ has a finite irrationality measure: if the terms of the continued fraction of $2\pi$ do not grow too fast, since
$$\frac{1}{(a_n+1)q_n^2}<\frac{1}{q_{n}(q_{n+1}+q_{n})}<\left|2\pi-\frac{p_n}{q_n}\right|<\frac{1}{q_n q_{n+1}}<\frac{1}{q_n^2},
$$
holds for every convergent $\frac{p_n}{q_n}$ of $2\pi=[a_0;a_1,a_2,\ldots]$, $(3)$ follows from the Legendre theorem.
Comment: You have written "This gives:
$$\left|\sum_{n=1}^{+\infty}\frac{\sin(\sin n)}{n}\right|\leq K\sum_{k=1}^{+\infty}\frac{k}{k^3},$$
for istance." - How did you get that? Also, note that the ratio$$\frac{\sigma_{k+1}(x)}{\sigma_k(x)}$$ can be negative.
Comment: @Jack Actually, I just realized that $\sum_{n\geq1}{\sin{(nx)}\over n}$ doesn't converge uniformly (it converges to a discontinuous function, namely, $-\operatorname{arg}(1-e^{ix})$). Nor does $\sum_{n\geq1}{\sin{(nk)}\over n}$ converge absolutely when $k$ is an integer. So how do we justify the change in order of summation that leads to $\sum_{n\geq 1}f(n)/n = \sum_{k\geq 1}c_k\sum_{n\geq1} {\sin{(kn)}\over n}$?
Comment: Simply write $\sin(\sin n)$ as a Fourier series and use the fact that $\sum_{n=1}^{+\infty}\frac{\sin(kn)}{n}=\frac{\pi-k}{2}=O(k)$. Moreover, $\frac{\sigma_{k+1}(x)}{\sigma_{k}(x)}$ cannot be negative on $[0,\pi/2]$ since $\frac{\sin x}{x}$ is non-negative on $[0,\pi/2]$.
Comment: @Jack This is really cool; it took me a moment, though, to flesh out the core assertion you make at the beginning of your answer, namely, $\sum_{n\geq1}f(n)/n$ converges whenever $f$ is an odd periodic function in $C^4(\mathbb R)$. Correct me if I'm wrong, but it seems like you're suggesting we write $f(x) = \sum_{k\geq1}c_k\sin{(kx)}$, where $c_k=o(k^{-3})$, and then interchange the order of summation: $\sum_{n\geq 1} f(n)/n = \sum_{k\geq1}c_k\sum_{n\geq1}{\sin{(kn)}\over n}$. The change is justified because $\sum_{n\geq1}{\sin{(nx)}\over n}$ converges uniformly. Is this what you had in mind?
Comment: @Nick Strehlke: exactly. The next step is to prove that: $$\mathcal{S}_k=\sum_{n=1}^{+\infty}\frac{\sigma_k(n)}{n}=-\frac{1}{2}+O\left(k^{-1/2}\log k\right)$$ by using the inequality $\sigma_{k}(x)\leq\min\left(\sin(x),\sqrt{\frac{3}{k}}\right)$ that is also very nice.
Comment: Ouch. This is a major issue :/
Comment: So we have $\left|\sum_{n=1}^{+\infty}\frac{\sin(k n)}{n}\right|<\pi$ that is better than $O(k)$, but we really need something else to justify the exchange of sums. Is someone willing to fix this? The lack of uniformity is only due to the $k$s that are close to an integer multiple of $\pi$, but they cannot be "too many", since, as already pointed by the author, $\pi$ has a finite irrationality measure.
Answer: If $f(x)$ is an odd continuous function with range $[-a,a]$, and $f(x) \leq |x|$,  then $f^k(x)$ has the same property for all $k \geq 1$.
If a sequence $a_n$ has a symmetric (even) frequency distribution measure in the interval $[-a,a]$, then $f^k(a_n)$ has the same property.
Based on this, and taking $a_n$ to be the value of $(n \mod 2\pi)$ in $(-\pi,\pi)$, by Abel summation the $\sum \frac{f^k(a_n)}{n}$ converges if $s_n = f^k(a_1) + \dots + f^k(a_n)$ is $O(n^c)$ for $c < 1$.  Uniform distribution modulo $1$ gives only $s_n = o(n)$ which is an epsilon less than what we need.
The difference $d_n = |\frac{s_n}{n} - \int_{-\pi}^{\pi} f^k(x) dx|$ converges to $0$ by uniform distribution (applied to $f^k \circ g$ for $g$ that re-coordinatizates the interval to make the distribution uniform). For $f^k$ of bounded variation,  we are asking a special case of the discrepancy problem for sequence $a_n$ : is there a bound $d_n = O(n^{-u})$ for $u > 0$?
This power-of-$n$ improvement in the convergence is true for any sequence with a positive irrationality measure.  Maybe a sledgehammer but it shows the problem does not need any special property of $f(x)=\sin x$ except that $f^k$ have bounded variation (which holds if $f'$ exists and is continuous).
Answer: I could be totally wrong, but it seems to me that the analysis in de Bruijn's book, p. 157(see, esp, a couple of pages down, like p. 159, where the $x$ dependence is discussed) would seem to indicate that the series would diverge for large $k,$ at least.
Comment: Actually, it converges for every $k$, due to the fact that the measure of irrationality of $\frac{1}{2\pi}$ is finite. See http://mathoverflow.net/questions/150863/does-equidistribution-of-zero-average-due-to-irrationality-imply-boundedness.
Comment: I must be dense -- I don't see how the answer to this question follows from the one you are pointing to.
Comment: It follows since $f(x)=\sigma_k(x)$ is $C^\infty$, $2\pi$-periodic and of zero average, and $1/2\pi$ has finite irrationality measure. Therefore, $s_n=\sigma_k(1)+\sigma_k(2)+\cdots+\sigma_k(n)$ is a bounded sequence, for every $k$, due to http://mathoverflow.net/questions/150863/does-equidistribution-of-zero-average-due-to-irrationality-imply-boundedness, and by Abel summation method, the above series converges.
Comment: I think you misunderstand the question. $k$ is fixed, while in the Bruijn's book $k\to\infty$.
Comment: @vesszabo no, I did not misunderstand.
Comment: Then could you explain clearly what you mean? I don't understand your answer, and it seems I am not the only one.
Comment: @D.Thomine: Please be more specific. What do you want me to explain?
Comment: @Yiorgos S.Smyrlis: actually, my comment was for Igor Rivin.


Como fazer uma consulta mysql a partir de um array vindo do html?

Question: Eu sei que $cores me retornar os valores do formulário. Qual a melhor forma de fazer uma consulta no banco de dados com os valores da array $cores para buscar os carros que estão presentes nessa cor?
<?php
    //PHP
    if(isset($_POST['enviar'])){

        // Conexão com o servidor do banco de dados
        $con    = mysql_connect('host', 'user', 'pass') or die (mysql_error());
        // Seleção do banco de dados
        $dbb    = mysql_select_db('database', $con) or die (mysql_error());
        // Pega o post 'cor' e dá implode. Resultado: 00001,00002,00003 ...
        // Dependendo das cores que forem selecionadas no formulário.
        $cores  = implode(",", $_POST['cor']);
        // Pegamos os valores do array e comparamos com IN que é a mesma coisa que OR
        // com a diferença de IN ser uma instrução para a mesma coluna.
        $query  = mysql_query("SELECT * FROM carros WHERE cores IN (".$cores.")");
        // contador para confirmar a quantidade de registros retornados
        $count  = mysql_num_rows($query);
        // mostra os valores do array enviados pelo formulário
        echo $cores . "

";

        // enquanto houver resultados relacionados a busca, buscar!!!
        while($reslt = mysql_fetch_array($query)){

            echo "
";
                print_r($reslt['carro']);
            echo "
";

        }

    }
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<title></title>
<meta name="" content="">

    <form id="enviar" method="POST">
        <?php echo "
"; ?>
        <input type="checkbox" name="cor[]" value="00001">Vermelho
        <input type="checkbox" name="cor[]" value="00002">Azul
        <input type="checkbox" name="cor[]" value="00003">Amarelo
        <input type="checkbox" name="cor[]" value="00004">Verde
        <input type="checkbox" name="cor[]" value="00005">Branco

        <input type="submit" name="enviar" value="Enviar">
    </form>

URL de apoio: http://axitech.com.br/vista/teste1array.php
Comment: Respondendo ao seu **comentário** @user11989, quero que ele simplesmente busque e mostre todos os carros com as cores selecionadas no form.
Comment: Não ficou muito claro amigo, você quer exibir no caso uma lista com os carros que tenha uma determinada cor separando por seção?
Answer: Tenta assim amigo
if(isset($_POST)){
    $cores = implode(",", $_POST['cor']);
    $carros = mysql_query("SELECT * FROM carros WHERE cor IN(".$cores.")");
}

Answer: Tenta isso:
<form id="enviar" method="POST">
<?php
if(isset($_POST)){

    $cores = $_POST['cor'];
    echo '
';
    print_r($cores);

    $carros = mysql_query("SELECT * FROM carros WHERE cor LIKE '$cores'");

while ($row = mysql_fetch_array($carros))
{
echo "<input type=\"checkbox\" name=\"$row[cor]\">$row[cor]";
}
}
?>

    <input type="submit" name="enviar" value="Enviar">
</form>

SQLFiddle


How can Play Video file in android for specific time

Question: I have four MP4 videos. And I want to play all of them one by one. Each video should play
for a specific time for example 30 second. I have code like this:
VideoView videoView = (VideoView)findViewById(R.id.VideoView);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);

videoView.setVideoPath(PATH_TO_FILE);
videoView.setMediaController(mediaController);

videoView.start();

How can I change this code to run 4 videos one by one, and each video is played
for 30 seconds?
Answer: You could be checking for it's current position in a handler like this
private android.os.Handler mHandler;
private Runnable mRunnable;

mHandler = new Handler();
mRunnable = new Runnable() {
    public void run() {
        int currentPostion = mVideoView.getCurrentPosition());
        if(currentPostion >= 30 * 1000 || currentPostion == mVideoView.getDuration()) {
           // Play next video
        }
        mHandler1.postDelayed(this, 250);
    }
};
mHandler.post(mRunnable);


The criteria of commuting two formal power series,

Question: Let $f = x+\sum_{n=2}^{\infty} a_n x^n$ and $g = x+\sum_{k=2}^{\infty} b_n x^n$ be two formal series without constant term. Then
$$
f \circ g(x) =x+ \sum_{k=2}^{\infty} b_k x^k+\sum_{n=2}^{\infty} a_n (x+\sum_{k=2}^{\infty} b_k x^k)^n,
$$ Similarly, $$
g \circ f(x) =x+ \sum_{n=2}^{\infty} a_n x^n+\sum_{k=2}^{\infty} b_k (x+\sum_{n=2}^{\infty} a_n x^n)^k.
$$
Now, we have
$$
\left(\sum_{k=1}^{\infty} b_k x^k \right)^n = \sum_{i_1 + \dotsm + i_k = n} b_{i_1} \dotsm b_{i_k} x^n, \ i_k \geq 1.
$$
I want to get the conditions when $f(g(x))=g(f(x))$ i.e., when the two power series commutes each other. Then, $$x+ \sum_{k=2}^{\infty} b_k x^k+\sum_{n=2}^{\infty} a_n (x+\sum_{k=2}^{\infty} b_k x^k)^n=x+ \sum_{n=2}^{\infty} a_n x^n+\sum_{k=2}^{\infty} b_k (x+\sum_{n=2}^{\infty} a_n x^n)^k,$$
i.e., $$\sum_{k=2}^{\infty} b_k x^k+\sum_{n=2}^{\infty} a_n (x+\sum_{k=2}^{\infty} b_k x^k)^n=\sum_{n=2}^{\infty} a_n x^n+\sum_{k=2}^{\infty} b_k (x+\sum_{n=2}^{\infty} a_n x^n)^k$$,
i.e, $$\sum_{k=2}^{\infty} b_k x^k+\sum_{n=2}^{\infty} a_n x^n+\cdots+\color{blue}{\sum_{n=2}^{\infty} a_n (\sum_{k=2}^{\infty}b_kx^k)^n}=\sum_{n=2}^{\infty} a_n x^n+\sum_{k=2}^{\infty} b_k x^k+\cdots+\color{blue}{\sum_{k=2}^{\infty} b_k(\sum_{n=2}^{\infty}a_nx^n)^k}. $$
The first two terms of both sides cancels out and  comparing the last term of both sides i.e, coefficients of $x^{kn}$, we get
$$
a_n \left(\sum_{i_1 + \dotsm + i_k = n} b_{i_1} \dotsm b_{i_k}\right) = b_n \left(\sum_{i_1 + \dotsm + i_k = n} a_{i_1} \dotsm a_{i_k}\right),\ i_k \geq 2.
$$ But how to deal with middle $\cdots$ terms  ??
That is, what is criteria so that $f(g(x))=g(f(x))$. ?
Comment: Your lower summation index should be $2$ instead of $1$ since you already have $x$ by itself.
Comment: @Somos, oh, yes,thanks
Comment: I don't understand your question "But how to deal with middle ... terms??" What are you trying to do here? Please explain what you want to do.
Comment: @Somos, I want to find the criteria when $f(g(x))=g(f(x))$. I arranged the equality but having problem to compare the coefficients of $x$ from both sides. As you in the last equation,I compared the coefficient of $x^{kn}$. What about the other coefficients so that $f(g(x))=g(f(x))$  ?
Comment: When you equate the terms of $f(g(x))=g(f(x))$ you get, for example, the coefficient of $x^4$ giving $a_2^2b_2+a_2b_3=b_2^2a_2+b_2a_3$. You get similar equations for the higher coefficients.
Comment: @Somos, so I am searching the general form. I think if you put $n=3$ in my above last formula, it will be your result. In that case the last equation is the general result
Comment: I think you may want to use Faa di Bruno's formula for composition of exponential generating functions using the exponential Bell polynomials.
Comment: @Somos,no,it is simple that what I am asking.I am asking if $f \circ g=g \circ f$, then what is the $\text{relations among the coefficients}$ as you did for $x^4$. That is what I am asking for general term or for $x^n$.
Answer: No idea why you got stuck.
$$\sum_{n\ge 1} a_n (\sum_{m\ge 1} b_m x^m)^n=\sum_{n\ge 1} a_n \sum_{r \in \Bbb{Z}_{\ge 1}^n} \prod_{j=1}^n b_{r_j} x^{r_j} = \sum_{l\ge 1} x^l \sum_{n=1}^l a_n \sum_{r \in \Bbb{Z}_{\ge 1}^n, \sum_{j=1}^n r_j = l}\prod_{j=1}^n b_{r_j} $$
and $\sum_{n\ge 1} a_n (\sum_{m\ge 1} b_m x^m)^n=\sum_{n\ge 1} b_n (\sum_{m\ge 1} a_m x^m)^n$ iff $$\sum_{n=1}^l a_n \sum_{r \in \Bbb{Z}_{\ge 1}^n, \sum_{j=1}^n r_j = l}\prod_{j=1}^n b_{r_j}=\sum_{n=1}^l b_n \sum_{r \in \Bbb{Z}_{\ge 1}^n, \sum_{j=1}^n r_j = l}\prod_{j=1}^n a_{r_j}$$
Comment: Thanks. But I think the indices will  start from $n=2$ instead of $n=1$.
Comment: No, $a_1=1$, there is no reason to separate $x^1$
Comment: ok, It is clear now


As a soloist, should I face the audience or the conductor during long tutti sections?

Question: I am playing a violin concerto with an orchestra and a fairly large audience in a few weeks. So my question is, in the long Tutti parts where I don't play, should I face towards the audience, and what should my posture be like?
Comment: Why not watch what other known players do in videos?
Comment: Since this question was first written, the title has now been changed from a general enquiry as to stance/attitude into a straight either/or between 2 options not originally mentioned, which I'm sure was not the OP's intent.
Comment: @Tetsujin it is meant to be a general enquiry but the opinions offered are valid also
Answer: You could remain directly facing the audience, with the smile gradually dripping from your face to be replaced by something between boredom & abject terror...
...or you may find it a lot easier to just quarter-turn & watch the conductor.
You're still up there, looking professional, paying attention, but aren't being subjected to the actinic glare of the audience's gaze whilst having nothing to actually do.
You could look at your feet... but it doesn't come over well ;)
Comment: There's a third option. Visibly count out measures on your fingers while clearly mouthing "one two three four".
Comment: This was originally a rather facetious [though well-intentioned] comment-as-answer which has since taken on greater proportions. I which I'd listed **all** the wrong things to do whilst looking really really nervous ;) My intention was just that 'looking at the conductor' takes away the pressure of 'performance' when there's no performing to be done right now, whilst not looking or feeling a total £$%^& until it's your next turn.
Comment: Yeah, I knew that. I was extending the joke. Perhaps too far.
Comment: @ToddWilcox - ikr... it was just an opportunity I really could have extended into an essay/diatribe. I wish i'd taken the opportunity at the time - would feel unworthy to extend it now ;-)
Answer: It would be absolutely rude and unprofessional not to focus on the music when anybody but yourself is playing.  You are a soloist, not the sole player.  The others aren't just fluff between your parts.
And even if you think the audience has only eyes for you, then you should use this to make them aware of the music rather than engaging in a private conversation at the cost of other musicians.
See a primadonna handle this situation professionally: the first minutes of this video of Maria Callas singing Carmen are purely instrumental.  She stays focused on the music, staying in character, not really engaging with the audience and when her actual part comes, she not jumps into activity and then stops again but that part comes as a natural continuation of her posture during the long tutti parts.
Of course, operatic singing cannot be compared with instrumental soloing since the former is supposed to convey a character, but still the situations are not entirely dissimilar.
Comment: @Beanluc The first words of the title of the question are "As a soloist" and then the question starts with "I am playing a violin concerto with an orchestra" so I guess they are the soloist.
Comment: @11684 The original title was "Facing the audience/ orchestra" before another user and I edited it. So *maybe* the OP isn't actually the soloist... But I think it's heavily implied by the context. :P
Answer: Some performers prefer the "look busy" approach.  I once attended an oboe concerto performance in which the oboist swabbed out his instrument every time he had more than 4 measures' rest.  I suppose a violinist could rub down excess rosin, pretend to tweak the bow tension, re-set the comfy rag under the shoulder rest, etc.
In any case, looking attentive, and keeping an eye on the conductor, are good suggestions.  Then about 2 bars before your next entrance, turn to the audience, close your eyes as though in rapture, and dramatically prepare your posture and bow for the entrance.
Comment: Rubbing rosin off the strings during a quiet clarinet interlude sounds like an excellent prank.
Answer: My go-to approach for this is just to let your eyes guide the audience to where you believe their attention should be.  If you look at the orchestra after you have been the center of attention for a bit, they'll do the same thing.  Lead the audience to where you want them to be...both with your music, and with your body (and eye!) language.
Edit: Once it's your "turn" again, look out into the audience to command their attention.
Answer: As I have been doing it and haven't failed, is to keep giving the same show to the crowd, I mean looking at them, AND, periodically looking at the conductor/ main player. Remember my role? I commented it in another post @tetsujin is helping me, and yes, several times I feel like the soloist because of Techno music sounding when my guitar has no place, yet... Until wait for it... Bang! It sounds awesome for the crowd, but remember, never steal much attention after your part.


Docker: Error: Could not find or load main class org.springframework.boot.loader.JarLauncher

Question: I'm trying to containerize my service.
My Docker File:
FROM openjdk:19 as builder
WORKDIR application
ARG JAR_FILE=target/payment-service-0.0.1-SNAPSHOT.jar
COPY ${JAR_FILE} application.jar
RUN java -Djarmode=layertools -jar application.jar extract

FROM openjdk:19
WORKDIR application
COPY --from=builder application/dependencies/ ./
COPY --from=builder application/spring-boot-loader ./
COPY --from=builder application/snapshot-dependencies/ ./
COPY --from=builder application/application/ ./
EXPOSE 8080
ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"]

Console commands:
mvn clean package spring-boot:repackage
docker build -t payment-service .
docker run --network test_net --name payment-service -d payment-service

Then I see this error:
Error: Could not find or load main class org.springframework.boot.loader.JarLauncher

My target folder:

If my Dockerfile looks like that, all is works:
FROM openjdk:19

COPY target/payment-service-0.0.1-SNAPSHOT.jar payment-service.jar

ENTRYPOINT ["java", "-jar", "/payment-service.jar"]

Answer: Answer found:
Just change
ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"]

To:
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]


Two nameserver questions

Question:
In Godaddy's Zone File Editor, I can edit A/CNAME etc. including NS record. I am wondering if I change NS to another Nameserver, will my records, like A/CNAME, be deleted right away?
If I have more than two dns records, and they are mixed by different DNS servers,
for example,
ns1.abc.com
ns2.abc.com
ns1.efg.com
ns2.efg.com
will that cause any issue?

Thanks!
Answer: 1:  The timeframe in which they are deleted depends on the hosting provided and likely should be directed to their support.  It all depends on how they configure their nameservers.
2:  This depends on if all 4 namesevers have the same records.  If they all have the same records, this should not pose any issue.  Issues would only occur if you have different records on the various namesevers causing them to direct traffic to different locations.
Answer:
Depends on how Godaddy handles that. I know from other ISPs that they keep the records in their database for later reactivation. Nervertheless, the saved records do no longer apply if you change the NS responsible for your domain (they may still apply for the TTL you have set though because the records may be cached on other servers, routers or computers). Your new NS is the responsible NS for your domain then and onle the new one is authorized to answer to DNS requests for your domain.
what do you mean? Having 3 records and saving them on a separate DNS server or maintain different record sets on each DNS server?
You can answer this question to yourelf: when a client has to determine the IP for a domain name, it queries one of the DNS servers responsible for that domain name. It then receives the records which the DNS server has in its store. Depending on which server was queried the client may be directed to different hosts.

Two nameserver questions


svg create circles

Question: I am new to svg and dont know its structure.I want to create 10 circle in random positions.How can I do this inside a loop like for()  loop ?
<code><g id="rotateSquare">
 <circle cx="100" cy="50" r="20" stroke="black"
  stroke-width="2" fill="goldenrod" />
<text x="110" y="52" fill="red">10</text>
<animateTransform
    attributeType="XML"
    attributeName="transform"
    type="rotate"
    from="0,150,150" to="360,150,150"
    begin="0s" dur="1s"
    repeatCount="1"/>
</code>
Comment: Is your svg in embedded in some sort of HTML document? Are you able to use external scripts? You might want to add more specifics to your question.
Comment: My document is SVG and some HTML code are embedded into SVG.Also I can only use Javascript(no JQuery).Can I use HTML for the loop?
Comment: See http://phrogz.net/svg/svg_in_xhtml5.xhtml for an example of procedurally creating SVG elements and adding them to the DOM.
Answer: Try using the following:
<code>   var svgns = "http://www.w3.org/2000/svg";
   var new_circle = document.createElementNS(svgns, "circle");
</code>
then after you set the attributes, (cx,cy,r can be randomly generated via a function),
you can insert the new node you created into the svg document:
<code>   /*parent elemnt*/.appendChild(new_circle);
</code>
You can place this function into a loop and generate as many circles as you want. You could even randomize the colors!
Comment: I understood the logic thank you.But I am not sure how I will insert the new node into svg after declared the features.Do I need to create another method to insert into svg?
Comment: @Ecrin Your comment is answered already. See `appendChild` above.

svg create circles


Randint não gera números aleatórios na segunda vez que eu o utilizo

Question: Meu randint quando usado pela segunda vez ele não gera novos números aleatórios, ele permanece com os mesmos números gerados. Eu sei que em C quando isso acontece eu posso usar o srand(time(NULL)); , porém no Python eu não estou achando nada parecido
Mostrar 3 matrizes distintas
from random import randint

matriz = [[], [], []]

def gerar_matriz ():
    for c in range(len(matriz)):
        for i in range(0, 3):

            s = randint(0, 9)
            matriz[c].append(s)    # adiciona os números a matriz

for c in range(3):

    gerar_matriz()

    for c in range(len(matriz)):
        for i in range(0, 3):
            print(matriz[c][i], end=' ')
        print(' ')

    print ('\n')

Comment: o randint em seu uso normal gera números aleatórios sim. Por favor poste o código de como você está fazendo. (usar o valor de de time como seed do rand funcionaria, mas acho que você está errando em algo mais fundamental)
Comment: Eu postei o código
Answer: O problema é que você não está criando matrizes novas em cada chamada a gerar_matriz() - o que você faz é acrescentar novos números ao final de cada linha já existente.
E na hora de imprimir as linhas, você usou um tamanho fixo de 3, então vê sempre os três primeiros elementos da linha.É só trocar o seu for interno de impressão pra ver o que está acontecendo:
    ...
    for c in range(len(matriz)):
        for i in range(0, len(matriz[0])):  # alterei esta linha
            print(matriz[c][i], end=' ')
        print(' ')

Por isso que boas práticas de programação em geral pedem que façamos tudo dentro de funções - o seu código que cria uma matriz nova e que chama a geração de matrizes está fora de funções e não pode ser executado de forma a isolar a matriz, que é uma variável global.
Se você fizer assim, vai funcionar:
from random import randint

def gerar_matriz ():
    matriz = [[], [], []]

    for c in range(len(matriz)):
        for i in range(0, 3):

            s = randint(0, 9)
            matriz[c].append(s)    # adiciona os números a matriz
    return matriz

    def imprime():

        for c in range(3):

            matriz = gerar_matriz()

            for c in range(len(matriz)):
                for i in range(0, 3):
                    print(matriz[c][i], end=' ')
                print(' ')
        print ('\n')

    imprime()

Só o que fiz aí foi deixar de depender da "matriz" como uma variável global - ela é criada dentro da função gerar_matriz e retornada para quem chamou a função. (transformar o código de impressão numa função não é essencial, mas evita que o nome "matriz" seja de novo associado globalmente, e que outras funções eventualmetne fossem ver somente a última matriz gerada).
Uma outra coisa é que em Python raramente, raramente mesmo, se precisa usar for com range. Em geral estamos interessados nos elementos de uma sequência, não nos índices dos elementos, para depois buscar os elementos.
No caso da matriz, podemos fazer um for para obter cada linha, e dentro um for para obter cada elemento:
def imprime():

    for c in range(3):  # aqui sim, queremos repetir algo 3 vezes!
        matriz = gerar_matriz()

        for linha in matriz:
            for elemento in linha:
                print(elemento, end=' ')
            print()
    print ('\n')

Comment: Muito obrigado pela ajuda


component unexpectedly re-mounts every time i dispatch new state. Im using ContextProvider with useReducer

Question: I using Context.Provider + useReducer, i have function "fetchCars()" in my context for fetching cars which depends on selected filter value
May be noob question, but i can't understand why consumer-component named "Filters.jsx" is mounting every time after i changed filter value. And because of this i cant save values in useState of Filter.jsx component
Codesandbox link
https://codesandbox.io/s/peaceful-morse-21zj6m?file=/src/components/Filters.jsx
in Codesandbox you can see console print when filter changed
CarsContextProvider.jsx
import { useReducer, createContext, useCallback } from "react";

export const CarsContext = createContext()

const getCarsFromServer = (status) => {
    // dummy fetch
    const dataFromServer = [
        { id: 1, name: 'Volvo', status: 'notAvailable' },
        { id: 2, name: 'BMW', status: 'inStock' },
        { id: 3, name: 'Mercedes', status: 'notAvailable' },
        { id: 4, name: 'Audi', status: 'notAvailable' },
        { id: 5, name: 'Opel', status: 'inStock' },
        { id: 6, name: 'Renault', status: 'inStock' },
    ]

    return new Promise((resolve) => {
        setTimeout(() => {
            if (status === 'all') {
                return resolve(dataFromServer)
            }
            resolve(dataFromServer.filter(item => item.status === status))
        }, 500);
    })
}

const reducer = (state, action) => {

    switch (action.type) {
        case 'pending':
            return { ...state, loading: true }
        case 'success':
            return { ...state, loading: false, items: action.payload }
        case 'error':
            return { ...state, loading: false, error: action.payload }
        case 'setFilter':
            return { ...state, statusFilter: action.payload }
        default:
            break;
    }
}

const initState = {
    items: [],
    loading: false,
    error: '',
    statusFilter: 'all',
}

const CarsContextProvider = ({ children }) => {

    const [state, dispatch] = useReducer(reducer, initState)

    const fetchCars = useCallback(async () => {

        try {
            dispatch({ type: 'pending' })
            const data = await getCarsFromServer(state.statusFilter)
            dispatch({ type: 'success', payload: data })
        } catch (error) {
            dispatch({ type: 'error', payload: error })
        }
    }, [state.statusFilter])

    return (
        <CarsContext.Provider value={{ state, dispatch, fetchCars }}>
            {children}
        </CarsContext.Provider>
    )
}

export default CarsContextProvider

App.jsx
import CarsScreen from "./components/CarsScreen";
import CarsContextProvider from "./context/CarsContext";

function App() {
  return (
    <CarsContextProvider>
      <CarsScreen />
    </CarsContextProvider>
  );
}

export default App;

CarsScreen.jsx
import CarsList from "./CarsList"

const CarsScreen = () => {

    return (

            <CarsList />

    )
}

export default CarsScreen

CarsList.jsx
import { useContext, useEffect } from "react"
import { CarsContext } from "../context/CarsContext"
import Filters from "./Filters"

const CarsList = () => {

    const { state, fetchCars } = useContext(CarsContext)

    useEffect(() => {

        fetchCars()

    }, [fetchCars])

    if (state.loading) return
loading...

    return (
        <>
            <Filters />

                {state.items.map((car =>
{car.name}
))}

        </>
    )
}

export default CarsList

Filters.jsx
import { useState, useEffect, useContext } from "react"
import { CarsContext } from "../context/CarsContext"

const Filters = () => {

  const [localState, setLocalState] = useState('init')
  const { state, dispatch } = useContext(CarsContext)

  useEffect(() => {
    // There is my question! Why console.log executing every time i change filter select option ?
    console.log('component mounted');
  }, [])

  const filterChangeHandler = (e) => {

    //and also localState could not change, because this component every time mounts with init value
    setLocalState('filter changed')

    // this dispatch changes filter value, and items fetching from server
    dispatch({ type: 'setFilter', payload: e.target.value })
  }

  return (

      <select
        name="stockFilter"
        onChange={filterChangeHandler}
        defaultValue={state.statusFilter}
      >
        <option value="all">show all</option>
        <option value="inStock">in stock</option>
        <option value="notAvailable">not available</option>
      </select>

Filters local state is : {localState}

  )
}

export default Filters

Codesandbox link
https://codesandbox.io/s/peaceful-morse-21zj6m?file=/src/components/Filters.jsx
Tried to comment React.StrictMode line in index.js., but no effect
Is it possible to avoid this unwanted mount Filters.jsx component?
Comment: The issue is that the  component is re-rendering every time the state changes, because it is a child of the  which is re-rendering every time the state changes. As a result, the  component is re-rendering as well.

To fix this, you can use React's useMemo hook in the  component to only re-render the  component when the state of the  actually changes.
Comment: Thanks for answer! My Filters.jsx component not only rerender, its mounts again on every render.  I tried to apply memo on all components, but no result, Filtres.jsx component is unmouting any way when changed filter value. I can't imagine which value i should wrap into useMemo hook in my CarsContextProvider as you said
Comment: You can notice  useEffect with empty array dep executing every time when i change filter value in Filters.jsx
Answer: Found a problem.
Problem was in component GoodsList.jsx loading status was dismounting Filter.jsx
if (state.loading) return
loading...

fixed version of GoodsList.jsx
import { useContext, useEffect } from "react"
import { GoodsContext } from "../context/GoodsContextProvider"
import GoodsFilter from "./GoodsFilter"

const GoodsList = () => {

    const { state, fetchGoods } = useContext(GoodsContext)

    useEffect(() => {

        fetchGoods()

    }, [fetchGoods])

    return (
        <>
            <GoodsFilter />
            {state.loading ?
loading...

                :
                <>

                        {state.items.map((good =>
{good.name} - {good.quantity}
))}

                </>
            }

        </>
    )
}

export default GoodsList


Coroutine Channel- Flow collect issue

Question: I am using one activity, the multiple fragment model, in my application. I have a sharedViewModel with the coroutine Channel to send and receive data from one fragment to another fragment. Also, I have a custom Dialog fragment as a popup across the app and its user action will observe the remaining fragments. My problem here is the event send from the custom dialog is not triggering in the fragment collect part frequently(2/5 Click). I am adding the codebase for your reference.
SharedView Model Part
<code>private val _cornerDataChannel = Channel<CornerData>()
val cornerDataEvent: Flow<CornerData> = _cornerDataChannel.receiveAsFlow()

fun updateCornerDataEvent(data: CornerData) = viewModelScope.launch {
     Log.e(TAG, "Event Added")
     _cornerDataChannel.send(data)
}
</code>
Sending part in the Custom Dialog Fragment
<code> private fun myToolSelectionCallBack(tool: ToolDTO) =
        viewModel.updateCornerDataEvent(CornerData.ToolData(tool))

 private fun systemStreamSelectionCallBack(stream: StreamDTO) =
        viewModel.updateCornerDataEvent(CornerData.StreamData(stream))
</code>
Receiving Part inside fragments
<code> private fun observeCornerItemSelectionCallBack() = lifecycleScope.launchWhenStarted {
        viewModel.cornerDataEvent.collect { event ->
            when (event) {
                is StreamData -> streamSelectionCallBack(data= event.data)
                is ToolData -> toolSelectionCallBack(data = event.data)
            }
        }
    }
</code>
In the receiver part, some user clicks are missing freqently. But it's always getting the update part under the view model.
Comment: Did you find the root cause for this issue?
Comment: Yes, you can use BroadcastChannel instead.
Answer: This is not a problem with clicks, this is because you're using regular channels for multiple observers/receivers but it is supposed to be single receiver with regular channels. You have to use BroadcastChannels for multiple receivers with single sender.
Now BrodcastChannels has been deprecated it is replaced with SharedFlow()
Note: This API is obsolete since 1.5.0. It will be deprecated with warning in 1.6.0 and with error in 1.7.0. It is replaced with SharedFlow.
Check: BroadcastChannels-OfficialDocs

Coroutine Channel- Flow collect issue


Como dar submit em um form sem dar refresh?

Question: Tenho um formulário que é passado para o php via POST.
Como todo formulário, quando é acionado o submit ele dá um refresh
na página, porém meu formulário está dentro de uma modal,
usei javascript para reabrir a modal quando a página atualiza mas mesmo assim gostaria
de submeter o dado sem ter que dar refresh na página.
Estou tentando fazer isso via ajax porém o (formData) que deveria estar
retornando os dados está retornando uma array vazia.
HTML
<form method="post" action="/home.php" id="form1" class="d-flex flex-row margem-bot-2x">
<fieldset class="border p-2" id="field">
    <select id="formselect" class="form-select" aria-label="Default select example">
        <option selected>Categoria</option>
        <?php
            $options = "";
            foreach ($data[0] as $value) {
            $options .= "<option value={$value['codigo']}> {$value['nome']}</option> \n";
            }
            print_r($options);
        ?>
    </select>
    <input name="datalist" list="dados" id="formcontrol" class="form-control me-2" placeholder="Digite alguma informação..." aria-label="Search" >
    <datalist id="dados">
        <option><?php if(isset($pessoa)){ print_r($pessoa->nome); }else{ echo "-"; } ?></option>
    </datalist>
</fieldset>
<button type="submit" class="btn btn-success" onclick="carregarosdadosaqui()">Pesquisar</button>
</form>

JavaScript
function carregarosdadosaqui(){
var form = document.querySelector('#form1');
form.addEventListener('submit', function(e) {
  e.preventDefault(); // <--- isto pára o envio da form

  var url = this.action; // <--- o url que processa a form
  var formData = new FormData(this); // <--- os dados da form
  var ajax = new XMLHttpRequest();
  console.log(formData);
  console.log(form);
  ajax.open("POST", url, true);
  ajax.onload = function() {
    if (ajax.status == 200) {
      var res = JSON.parse(ajax.responseText); // a resposta do servidor
      //fazer algo com a resposta do servidor
      alert(res);
    } else {
      alert('Algo falhou...');
    }
  };
  ajax.send(formData);
});
}

Comment: Em `console.log(formData)` altere para `console.log(formData.entries())` e veja qual o resultado.
Answer: Retire a action="/home.php" da tag <form>.
O que acontece é que quando você envia o formulário, essa action faz o redirecionamento para o arquivo home.php, removendo ele deve resolver seu problema.