Vocal range of a crowd

Question: I am planning to sing a song and which has a vocal range of D3-D4.
I want the crowd to join in too. Should I raise or lower the tune of this song to better fit the crowd's range?
Which key or vocal range is recommended for a crowd (comprising of men and women)?
Answer: One other place where we find large crowds of people singing songs together is worship music- so perhaps we can find relevant advice there.
The general consensus* is that the most friendly keys for congregational singing will be the keys which place the melody in the range of C to C, roughly.  It doesn't technically matter which C's, really, as men will generally sing C3 to C4 and women will generally sing an octave up, C4 to C5. For readability, you should notate C4 to C5 on a treble clef.  You can reach beyond this range a little if necessary but go too far and you'll start to lose people...

* Link 1 Link 2 Link 3 There are many more...
Comment: @BenCrowell Well yes, and the middle of the bell curve (for both male and female voices) is generally comfortable with C to C.  What's the problem here?  What kind of answer do you want?
Comment: @BenCrowell That's not a fair criticism. Different people have different voices, obviously, but some kinds of voices are more common than others. Therefore, there is probably one range in particular that will be better than all of the others, in the sense that more people will find it easy to sing in that range. And that's exactly what this answer says.
Comment: @BenCrowell It makes perfect sense. Every man's voice includes C3 to C4, and every woman's from C4 to C5. And the division into bass, tenor, alto, and soprano, is certainly not 'totally arbitrary', nor is it 'very much like height' at all.
Comment: This makes no sense, -1. One man's voice doesn't have the same range as another man's voice, nor is this true for women. Even the division of men into tenor and bass, and women into soprano and alto, is totally arbitrary. It's very much like height. Men's and women's heights are bell curves, and the bell curves overlap. There aren't disjoint categories of tall women and short women, etc. For a song with a wide range, like the Star Spangled Banner, there will always be some people whose vocal range fits it better in F than in C, and vice versa.
Comment: @BenCrowell: no, everyone's range isn't the same. However, this recommendation is talking about only a portion of that range. And most people who sing at all have a low C and a high C within their range. I actually think this is better than the accepted answer, as I do know tenors and sopranos who can't sing both a high and low B-flat. But most can sing middle C and either an octave above or below that note (and all the notes in between). .
Comment: @BenCrowell - may be the truth. If that's the case, why would anybody write a national (or any other oft-sung song) with a large range? Seems sensible to me to keep the range as small as possible, so everyone has  the capability to sing all of it.
Comment: @Edward and it comes as no surprise academic research confirms this range as squarely in the middle for most humans.
Comment: @user207421 _"Every man's voice includes C3 to C4, and every woman's from C4 to C5."_ Why do you say that?
Comment: @J... Can you link to research about your claim that every man without a medical condition can sing C3-C4?
Comment: @J... I can't read that claim in Obscurans's answer. Let me ask for more information there.
Answer: Just about everyone can manage an octave from B♭ to the one above. Women and men will find their own octave.  Take it up to C if you like.  By D some will begin to fall out, but this should be compensated by the louder tone of those who CAN get up there!
Having said that, crowds enjoy 'going for the high note' in some types of song.   Keep 'All things bright and beautiful' in an easy range.  But 'Walk through a storm' NEEDS at least an E♭ or F, even if some of them can't quite make it! (Not G though.  That gets ugly.)
Comment: I actually like this suggestion as well, although the sopranos are really reaching for that Bb.
Comment: But few people find "and the rockets red glare" an easy reach.
Answer: Oddly enough, I was reading an analysis of this a couple of weeks ago: Finding The Best Keys For Congregational Songs.  (That page is for worship leaders and analyses lots of popular worship songs; but I think the principle applies equally to most sorts of contemporary singing.)
Its conclusion is that the average singer's basic range is the octave-and-a-fourth from A up to D, with the most comfortable part being the octave C–C.  If necessary, the occasional top E♭ may be allowed; but many people will struggle to exceed that range in either direction.  And a song that spends time near the top of that range will be tiring for many singers even if it doesn't go over D.
So: stick to C–C where convenient, and to A–D if at all possible.  That may mean some compromise between what's best for you, and what's best for the average member of your audience, if you want them to join in.
Comment: This should be the top answer. I have sung in choirs in a large varitety of settings, and my experience with choosing the right keys to sing in, to allow the largest possible number of people to participate, squares exactly with this.
Answer: I'm going to take a different tack on this...
Listen to a crowd singing along to a big ballad - one that springs to mind is Robbie Williams' Angels. They'll go for it whether they can reach it properly or not. The money note in that is an E5 with a more throwaway [or swung at & missed] F♯ after that.
The commonly returned-to bottom note [not literally the lowest but the others are fleeting & throwaway] is a D4, so only just over an octave, but pitched for a pop singer not an opera singer.
I wouldn't use hymns as any kind of reference - there's a different purpose in how they are pitched.
So, make your money note reachable by most. There's a reason it's a money note - it's the one people want to join in on. I think you're probably in safe territory with a D… but D3 to D4 feels like an odd octave for a pop song.
…or maybe it's not a pop song, you didn't say.
Comment: no its not a pop song.. more of soul genre..
Answer: The vocal range of people is an important topic to vocal science and speech pathology, and has of course received much research attention.
TL;DR
A2-C4 (adult males) and A3-C5 (others) normally work for most people, in line with both answers from Edward and Laurence Payne quoting standard practice. It's called standard for a reason.

Summary of results
Studies which are not open access are not included. Note I'm specifically going to take the most inclusive range, i.e. approx -2 stdev or 5th percentile for upper limit and +2 stdev or 95th percentile for lower limit.
Dienerowitz et al., 2021 [1], studying 1578 mostly untrained children, report A3-C5 for most, except about A2-C4 for older boys. Wuyts et al., 2010 [2], with 74 younger children report A3-E♭5.
In adults, Hunter and Titze, 2005 [3], reported 4 untrained subjects at G2-G♯4 (male) and D3-E5 (female). Siupsinskiene, 2010 [4], reports A2-G4 (untrained male, n=38; Table 2) and G3-D5 (untrained female, n=89; Table 3). Ma et al., 2007 [5], reports E3-G5 (non-dysphonic female, n=35; Table 2). D'Alatri and Marchese, 2014 [6], reports F♯3-B♭4 (non-dysphonic female, n=40; Table IV - mean used for upper limit).
Remember most of these are reporting extreme ranges, so going straight to the edge is not going to be fun for most people.

Figures

High and low voice limits of children. Figure 1 from [1].

From [2].

Vocal and hearing ranges of single subjects. Figure 1 from [3].

References:
[1]: Tobias Dienerowitz, Thomas Peschel, Mandy Vogel, Tanja Poulain, Christoph Engel, Wieland Kiess, Michael Fuchs, and Thomas Berger. "Establishing Normative Data on Singing Voice Parameters of Children and Adolescents with Average Singing Activity Using the Voice Range Profile." Folia Phoniatrica et Logopaedica: in press, 2021.
[2]: Floris L. Wuyts, Louis Heylen, Fons Mertens, Marc De Bodt and Paul H. Van de Heyning. "Normative voice range profiles of untrained boys and girls." Journal of Voice 24(2):153-160, 2010.
[3]: Eric J. Hunter and Ingo R. Titze. "Overlap of hearing and voicing ranges in singing." Journal of Singing 61(4):387-392, 2005.
[4]: Nora Siupsinskiene. "Effects of Vocal Training on Quantitative Voice Parameters in Healthy Voice Adults and Children." In Laryngeal Diseases: Symptoms, Diagnosis and Treatments, Oldrich Nemecek and Viktor Mares (eds.), Nova Science Publishers, 2010.
[5]: Estella Ma, Jennie Robertson, Claire Radford, Sarah Vagne, Ruba El-Halabi, Edwin Yiu. "Reliability of Speaking and Maximum Voice Range Measures in
Screening for Dysphonia." Journal of Voice 21(4):397-406, 2007.
[6]: Lucia D'Alatri, and Maria R. Marchese. "The speech range profile (SRP): an easy and useful tool to assess vocal limits." Acta Otorhinolaryngologica Italica 34:253-258, 2014.
Comment: @JiK - This answer actually does get quite close to saying that every adult male can sing C3-C4 (assuming all ranges in quoted papers are accurate and representative). Ranges for adult males and older boys given in this answer are "about A2-C4 for older boys", "G2-G♯4 (male)", and "A2-G4 (untrained male, n=38; Table 2)". All of these include C3-C4.
Comment: @J.. says elsewhere that this answer states that every (adult) man can sing C3-C4 (ignoring men with health conditions). I couldn't find this claim in your answer or the cited papers. Do you know where I could find more information?
Comment: Just to emphasize because it seems to be unclear: I'm asking for a source for the claim that every adult man with a healthy voice can comfortably sing C3-C4. My question is not about boys, or people who sing regularly, or the average range, or the ability to produce a C4 even if it hurts.
Answer: The key is of no relevance, unless the range of the song is known. Then, it's of paramount importance! The range is, as already mentioned, the lowest and highest notes in that song.
OP asks about 'a crowd' singing. Quite different scenarios between a football match and a hen night, for starters. Or a kid's birthday party and a gathering of OAPs!
Most people - 'non-singers' included, will have a range of an octave or so. C3 to C4 for males, C4 to C5 for females, as a (very) rough approximate. Well oiled with alcohol, probably a little more at each end, and often with greater volume. Those who are outside this range will often compensate by dropping/rising an octave for the notes outside that range.
Now, back to key. Not all songs have the tonic as the lowest and highest notes. So that's not a god criterion - on its own. A common example will be 'Happy Birthday' - well crafted for all to sing - and why not?
In my 60-odd years of playing it, keys F and G have been the most accepted. The tune happens to have its 5th as the lowest, and an octave above that as its highest note. So, assuming C-C is an 'average' range, key F is perfect. OP's tune may use the same criteria, thus revealing the 'perfect' key.
Answer: This is a very good question. Until a little more information is given, this should help.
The range you have given, D3 - D4, falls into the tenor vocal range. As such it also overlaps with the bass vocal range and the alto vocal range, however some notes will be hard for the basses and some notes will be hard for the altos. Roughly speaking, the basses will have difficulty with the D4; the altos will have difficulty with the D3; sopranos can not sing in that range; please read on for more on this though.
Will this be sung as a single unharmonized line? If so, most people automatically sing in their own octave (they will sing up or down an octave from the original singer) and therefore there is theoretically no problems regarding range. However, in practice, it is not that simple. Some melodies seem more inclined to octave transposition than others.
In order to fit better within each range, you might want to try the key of G:
Soprano: G4 - G5 (Perfect fit);
Alto: G3 - G4 (stretch on G3);
Tenor: G3 - G4 (stretch on G4);
Bass: G2 - G3 (Perfect fit).
(the key of A would also be good; generally speaking the key of D is not good for untrained male singers. They have difficulty with low D.)
Comment: This contrasts very sharply with my findings, so I'm curious how you came up with this...  You don't mention baritone voices- I believe that most men would be considered baritones, and both G2-G3 and G3-G4 would be quite difficult for these voices.
Comment: Singing in **any** key will not give the range you quote! It will depend wholly on the **range** of the notes in that song.  It may just be that the particular song has a lowest note G, and the highest the G an octave above, but that song could just as easily be in key C!!  And 'Happy Birthday' just happens to be a perfect example! -1.
Comment: is this classification for untrained singers?
Comment: Yes, those ranges are based on what would be most comfortable for untrained singers. Nothing is perfect but based on my experience that might work better. Would you beable do a test run on a small audience? Also consider having two or three keys practiced and you can change on the spot if you have to.
Comment: @Edward yes I focused on the main divisions of register. It got pretty complicated just doing that alone. Please feel free to fill out the registers. I tried covering the problem you mention by offering the key of A which brings everything up a bit on the low end (A2 - A3) but then that will push the sopranos up to A5, quite high for untrained singers. Basically nothing fully works which I suppose why singing in octaves is very rarely done.
Comment: @obscurans I have to disagree with you on the basses. Just to make sure we're on the same page, I'm talking true basses, not baritones. D4 is a major strain on basses, E4 is almost not even possible, and if they can hit it, it sounds bad. Bear in mind I'm talking choral contexts not arias. On the low end, G2 is fine it sits well with a bass. In fact because it is low it is that much better for untrained singers since it's natural to their voice type.
Comment: @Tim good point I should change it to read range rather than key.
Comment: @obscurans Just in the name trying to sort this out for the original question maybe we can go one step at a time. I will speak for basses since I am a bass and others can speak for their ranges. You said G - G fits no one at all. That is not true. It fits the bass range comfortably and with perfection! The low G for a bass still gives room to go lower, and the upper G is not too high, for that reason G - G fits right inside the best part of the bass range.
Comment: Enough with anecdote. I've done research review now.

Vocal range of a crowd


Google Apps Script: Use array out of spreadsheet

Question: I try to use Google Script Apps (instead of VBA which I am more used to) and managed now to create a loop over different spreadsheets (and not only different sheets in one document) using the forEach function.
(I tried with a for (r=1;r=lastRow; r++) but I did not manage).
It is working now defining the array for the sheetnames manually:
var SheetList = ["17DCu1nyyX4a6zCkkT3RfBSfo-ghoc2fXEX8chlVMv5k", "1rRGQHs_JShPSBIGFCdG6AqXM967JFhdlfQ92cf5ISL8", "1pFDyXgYmvC5gnN5AU5xJ8vGiihwtubcbG2n4LPhPACQ", "1mK_X4Q7ysJQTt8NZoZASBE5zuUllPmmWSJsxu5Dnu9Y", "1FpjIGWTG5_6MMYJF72wvoiBRp_Xlt5BDpzvSZKcsU"]
And then for information the loop:
SheetList.forEach(function(r) {
    var thisSpreadsheet = SpreadsheetApp.openById(r)
    var thisData = thisSpreadsheet.getSheetByName('Actions').getDataRange()

    var values = thisData.getValues();

    var toWorksheet = targetSpreadsheetID.getSheetByName(targetWorksheetName);
    var last = toWorksheet.getLastRow ()+ 1
    var toRange = toWorksheet.getRange(last, 1, thisData.getNumRows(), thisData.getNumColumns())

    toRange.setValues(values);
    })

Now I want to create the definition of the array "automatically" out of the spreadsheet 'List' where all spreadsheets which I want to loop are listed in column C.
I tried several ideas, but always failed.
Most optimistic ones were:
var SheetList = targetSpreadsheetID.getSheetByName('List').getRange(2,3,lastRow-2,3).getValues()

And I also tried with the array-function:
var sheetList=Array.apply(targetSpreadsheetID.getSheetByName('List').getRange(2,3,lastRow-2,3))

but all without success.
It should be possible normally in more or less one single line to import the array from the speadsheet to the Google apps scripts?
I would very much appreciate if someone could please give me a hint where my mistake is.
Thank you very much.
Maria
Answer: I still did not manage to put the array as I wanted it initially, but now I found a workable solution with the For Loop which I want to share here in case someone is looking for a similar solution (and then finds at least my workaround ;) )
for (i=2; i<lastRow;i++){
   var SheetList = targetSpreadsheetID.getSheetByName('List').getRange(i,3).getValues()
    Logger.log(SheetList);
    var thisSpreadsheet = SpreadsheetApp.openById(SheetList);
    ... // the rest identical to loop above...

Don't hesitate to add your comments or advice anyhow, but I will mark the question as closed.
Thanks a lot.
Maria


Rotman's exercise 2.8 "$S_n$ cannot be imbedded in $A_{n+1}$"

Question: This question is about the (in)famous Rotman's exercise 2.8 in "An Introduction to the Theory of Groups."
I've searched and found similar questions here and in MO, but none of them contains a valid proof. (Does $S_n$ belong as a subgroup to $A_{n+1}$?)
According to Rotman, a valid proof can only use the concepts introduced up to this exercise: cycle permutations, factorization of permutations, odd and even permutations, semigroups, groups, homomorphism and subgroups. Cosets, Lagrange's theorem, normal subgroups, and so on are not yet introduced. I stress this point because all of the proofs I've seen use Lagrange or actions, on cosets.
Now my attempt is to use exercise 2.7 (solved) which is about a proof that $A_n$ ($n>2$) is generated by all the $3$-cycles and exercise 2.4 (solved) " if $S$ is a proper subgroup of $G$ then $\langle G \setminus S\rangle=G$ " in this way:
Suppose that for every $\phi  : S_n \to A_{n+1}$ imbeddings, all the $ 3$-cycles are contained in $\operatorname{Im}\phi $, then the assertion is proved by absurd. But I can't find a way to prove if it is possible or either find a counterexample to this kind of approach.
If someone has another proof which use only basics concepts is well accepted of course, but I mainly need  some hints about correctness or not of my reasoning and how to proceed if it is correct. Thank you in advance.
Comment: Here is a link to an answer at MO: http://mathoverflow.net/questions/65083/an-easy-proof-that-sn-does-not-embed-into-an1
Comment: Have you tried counting the number of elements of order $2$ in both $S_n$ and $A_{n+1}$? The computations are rather cumbersome, but it requires no knowledge of group theory.
Comment: Isn't there a result that the largest subgroup of $A_{n+1}$ is $A_n$? I may be mistaken.
Comment: @user84559: I thought counting elements of order 2 might work too, but it doesn't. To save doing the combinatorics here, http://oeis.org/A000085 and http://oeis.org/A000704 give the relevant counts and the only case where $S_n$ has more elements of order 2 than $A_{n+1}$ is when $n = 2$.
Comment: I am not very sure about the way i am following as you said i can not use more group theory but, Suppose $S_n$ is in $A_{n+1}$, what is the order of $S_n$ and what is the order of $A_{n+1}$... does $n!$ divides $\frac{(n+1)!}{2}$ in general....
Comment: @Praphulla yeah yeah but you are using Lagrange in this way, and in this way you only eliminate half of the cases,thanks anyway
Comment: ok, after getting used to lagrange theorem, it would be difficult to check from basics ;).. any ways, I am helpless.. All the Best :)
Comment: Not tried yet, I'll try this approach
Comment: The answer you are looking for can be found [here][1].

  [1]: http://math.stackexchange.com/questions/83160/does-s-n-belong-as-a-subgroup-to-a-2n1?rq=1
Comment: The only answer I see there use the concepts of Index, simple group or normal subgroups. I can't use these concepts. And yeah I've read that question dozen of time but I don't think it is an exhaustive answer (again, there are "too advanced" concepts involved ) thanks anyway
Comment: see http://www.artofproblemsolving.com/community/c7h333049
Comment: @BhaskarVashishth it uses that $A_n$ is simple for $n\geq 5$. Far from the what Rotman covered up to that chapter. Cosets are NOT covered either.
Answer: I'm not sure what exactly I'm allowed to use or what Rotman had in mind, but I think this approach uses no more group theory than the (unique) factorization of permutations and the basic idea of what a homomorphism is.
If $n$ is odd there exists a subset $S\subset S_n$ of pairwise commuting elements of order $2$ with $|S|=\tfrac{n-1}{2}$. For example
$$\{(1\ 2),(3\ 4),\ldots,(n-2\ n-1)\}.$$
An element $\sigma\in A_{n+1}$ of order $2$ is necessarily a product of an even number of disjoint $2$-cycles. Therefore a subset $A\subset A_{n+1}$ of pairwise commuting elements of order $2$ cannot contain more than $\tfrac{n+1}{4}$ elements. Hence for an embedding $S_n\ \hookrightarrow\ A_{n+1}$ to exist we must have
$$\frac{n-1}{2}\leq\frac{n+1}{4},$$
or equivalently $n\leq3$. At this point it should not be hard to verify that $S_3$ does not embed into $A_4$, and of course that $S_1$ does embed into $A_2$.
A similar argument can be made when $n$ is even, to find that for an embedding $S_n\ \hookrightarrow\ A_{n+1}$ to exist we must have
$$\frac{n}{2}<\frac{n+1}{4},$$
or equivalently $n<1$, immediately yielding a contradiction.
Comment: Woow, I need to sit down and check it, anyway, thanks for this answer, seems to be plausible, but again, I've yet to read it carefully! :)
Comment: Though it seemed like a good idea at 03:00 AM last night, I see now that my proof doesn't work. But perhaps it can be saved. I'll give it some more thought.
Comment: From your comment I conclude that you realized in meanwhile that $A_4$ has an elementary abelian subgroup of order $4$, i.e., two commuting elements of order $2$.


HTML tags in views field label. Is it possible?

Question: By default in views field label it possible to put only plain text, so the markup looks like:

  Price: -10%
  9.99

But I need to add some text wrapped with tags, like

  Price: -10%
  9.99

How it is possible?
Answer: Uncheck create label
Click on rewrite results, check mark override out and put:
  Price: -10%
  {{ field_price }}

I'm not 100% that it's {{ field_price }}, but you can click on replacement patterns to see the pattern name.
Comment: As a result, I did not have to do this task. But the advice is correct. Someone it could be useful!


Which of these functions $\mathbb N\to\mathbb N$ are strictly increasing?

Question:
$f(n) = (1+n)^2$
$f(n) = \lfloor\log(n)\rfloor$
$f(n) = \lfloor\sqrt{n}\rfloor$
$f(n) = (1-n)^2$

I am having a hard time understanding what strictly increasing means. Aren't all of these functions increasing? I know the squared ones are decreasing at some point, but then would it be the log or square root, one? An explanation would be greatly appreciated.
Comment: For the function to be strictly increasing, as $x_1 < x_2 < \cdots$ in the domain of $f$, $f(x_1) < f(x_2) < \cdots$ in the range of $f$ as well
Comment: ... in particular, $f(x_1) \neq f(x_2)$ and so forth.
Comment: For ones you don't suspect to be true, find a counter example. For ones you believe do increas, follow Nasu Suma's advice.
Answer: A function is strictly increasing if whenever $a < b$, it is true that
$$f(a) < f(b)$$
For example, if $a < b$ in $\mathbb{N}$, and we consider $f(x) = (x + 1)^2$, we see that
\begin{align*}
f(b) - f(a) &= (b + 1)^2 - (a + 1)^2 \\
&= b^2 + 2b + 1 - \Big(a^2 + 2a + 1\Big) \\
&= b^2 - a^2 + 2(b - a)
\end{align*}
Convince your self that $b^2 - a^2 > 0$ and, and note that $b - a > 0$; it follows that $f(b) - f(a) > 0$, which is equivalent to checking that $f$ is strictly increasing.

As a different example, consider $$g(x) = \left\lfloor \frac x 2 \right\rfloor$$
Then $g$ is an increasing function, but it's not strictly increasing on $\mathbb{N}$: We have $g(2) = 1 = g(3)$.

So every strictly increasing function is increasing, but not the opposite.
Answer: Strictly increasing means that $f(n) \neq f(n+1)$ while just increasing allows that.  The floor function tends to make things equal.  You might compute some early values for each.  The answer to 4 depends on whether $0 \in \Bbb N$


Not using "begin transaction" and "commit" statements in Postgresql

Question: Whenever I am accessing a PostgreSQL database with terminal I don't use "begin transaction" or "commit;" statements. Still, changes made by me on the database are permanent. (they don't get rollbacked when I turn off terminal). Why is it? Is there anything am I missing?
Comment: Before considering posting please read the manual & google any error message or many clear, concise & precise phrasings of your question/problem/goal, with & without your particular strings/names & site:stackoverflow.com & tags; read many answers. If you post a question, use one phrasing as title. Reflect your research. See [ask] & the voting arrow mouseover texts.
Comment: https://stackoverflow.com/questions/13837146/postgres-setting-autocommit-off-globally ; keyword you're looking for is "autocommit"
Comment: @philipxy I did google search and basic research. I did not know what exactly to search on google.That is why I asked this question.
Answer: By default psql CLI interface runs in autocommit mode.
See https://dzone.com/articles/autocommit-in-postgresqls-psql


No Free Lunch Theorem 1 Proof

Question: I was reading the original "No Free Lunch Theorems for Optimization" paper and I'm trying to understand a specific step in the inductive step of the proof of theorem 1. To provide some background, theorem 1 states
$$\sum_f P(d_m^y|f, m, a_1) = \sum_f P(d_m^y|f, m, a_2)$$
where

$f$ is a cost function that maps the input space $\mathcal{X}$ to the cost space $\mathcal{Y}$ (both spaces are finite)
$m$ is the number of points visited by the algorithm $a_i$ producing a sequence of input and cost values $d^x_m$ and $d^y_m$ respectively
$d_m$ is the ordered set of pairs $\{(d^x_m(1), d^y_m(1)), ..., (d^x_m(m), d^y_m(m))\}$
$P(d_m^y|f, m, a_i)$ is the conditional probability of producing the sequence of cost values $d_m^y$ with cost function $f$ and algorithm $a_i$ by visiting $m$ points.

In the final steps of the proof (see Appendix A in the paper for the rest of the proof), we say
$$\sum_f P(d^y_{m+1}|f, m+1, a) = |\mathcal{Y}|^{|\mathcal{X}| - m - 1} \sum_{f(x \in d_m^x), d_m^x} P(d_m|f, m, a)$$
$$= \frac{1}{|\mathcal{Y}|} \sum_{f, d_m^x} P(d_m|f, m, a)$$
$$= \frac{1}{|\mathcal{Y}|} \sum_f P(d_m^y|f, m, a)$$
I don't understand how the authors turn the first equivalence into the second by replacing the $|\mathcal{Y}|^{|\mathcal{X}| - m - 1}$ factor with $\frac{1}{|\mathcal{Y}|}$ and changing the sum to sum over all $f$, rather than just the $f$ defined on $x \in d^x_m$.
Answer: As $P(d_m^y\vert f,m,a)$ depends solely on $\vert \mathcal{Y}\vert^m$ possibilities for $f$ on $d_m$,
\begin{align}
\sum_{f(x\in d^x_m),d_m^x} P(d_m\vert f,m,a)&=\frac{1}{\vert \mathcal{Y}\vert^{\vert \mathcal{X}\vert-m}}\sum_{f(x\in d^x_m),d_m^x} \vert \mathcal{Y}\vert^{\vert \mathcal{X}\vert-m}P(d_m\vert f,m,a)\\
&=\frac{1}{\vert \mathcal{Y}\vert^{\vert \mathcal{X}\vert-m}}\sum_{f(x\in d^x_m),d_m^x} \sum_{f(x\notin d_m^x)}P(d_m\vert f,m,a)\\
&=\frac{1}{\vert \mathcal{Y}\vert^{\vert \mathcal{X}\vert-m}}\sum_{f,d_m^x}P(d_m\vert f,m,a).
\end{align}
The inner sum in the second line follows because it does not depend on the $\vert \mathcal{Y}\vert^{\vert \mathcal{X}\vert-m}$ possibilities for $f$ outside of $d_m^x$, and the last line is because any function $f$ is completely specified by the values on $d_m^x$ and outside $d_m^x$.

No Free Lunch Theorem 1 Proof


how to tell analytically if the function is injective

Question: How can I tell analytically if the following function is injective or not
$f(x)=\frac{3x-5}{x^{2}-1}$
I start by letting $f(x)=f(y)$ and then I would like to see that I can have $x \neq y$, this is so because according to the graph the function is not inyective:

Then I have
$$\frac{3x-5}{x^{2}-1}=\frac{3y-5}{y^{2}-1}$$
$$(3x-5)(y^{2}-1)=(3y-5)(x^{2}-1)$$
doing the Calculus I get
$5x^{2}-3yx^{2}+3xy^{2}-3x+3y-5y^{2}=0$
but then I don't know what to do, for instance for the function
$f(x)=x^{2}-x$ I can do the following
Let $f(x)=x^{2}+x=f(y)=y^{2}+y$
then
$x^{2}-y^{2}=y-x$
$(x-y)(x+y)=y-x$
now assuming $x \neq y$ (I do not know If I can make this assumption) I can divide both sides and get
$x+y=-\frac{y-x}{y-x}=-1$,
so in this case the function is not injective since for every pair of numbers such that $x+y=-1$ I will have $f(x)=f(y)$ for instance $f(0)=f(-1)$
Is this the general method? Should I start letting $f(x)=f(y)$ and the by doing the Calculus I should get $x=y$ or $x$ posssibly different from $y$?
Answer: It suffices to note that letting $y=f(x)=5$ leads to two different solutions for $x$: For $x\neq\pm1$,
$$f(x)=\frac{3x-5}{x^{2}-1}=5 \Leftrightarrow 3x-5=5x^{2}-5 \Leftrightarrow 3x=5x^{2}\Leftrightarrow x=0 \ \ \textrm{or} \ \ x=\frac{3}{5}$$
Thus the function is not injective.
Answer: Your method is general provided you can factor polynomials or other expressions (not always easy).
In your example we have
$$
5x^{2}-3yx^{2}+3xy^{2}-3x+3y-5y^{2}=
(x-y)(-3 x y+5 x+5 y-3)
$$
and so we can have $5x^{2}-3yx^{2}+3xy^{2}-3x+3y-5y^{2}=0$ without $x-y=0$: we just need that $-3 x y+5 x+5 y-3=0$. For instance, $x=0, y=3/5$ works.
Answer: How can I tell analytically if $f(x)=\frac{3x-5}{x^{2}-1}$ is injective?
You have to prove that there are two real numbers $x$ and $y$ such that $x\neq y$ and $f(x)=f(y)$. For this, it's enough to prove that there is a real number $x\neq 0$ such that $f(x)=f(2x)$ (then, just take $y=2x$).
Note that
\begin{align}
f(x)=f(2x)&\quad\Leftrightarrow \quad\frac{3x-5}{x^2-1}=\frac{6x-5}{4x^2-1}\tag{if $|x|,|2x|\neq 1$}\\\\
&\quad\Leftrightarrow \quad 6 x^3-15 x^2+3 x = 0\\\\
&\quad\Leftrightarrow \quad 6 x^2-15 x+3 = 0\tag{if $x\neq 0$}\\
\end{align}
Solving the last equation we get the result.


How do I implement a reverse node reference using References?

Question: Using the References module (D7 version), implementing a new field in an article content type for node reference was very easy, but now I cannot seem to figure out how to discern the reverse reference. Just as there is a link shown in my article to the node I have selected in the node reference drop down, I am expecting that on the "linked to" article, I should be able to see a link back to the first article. Has anybody done this? My understanding is that it is part of the D7 version of this module.
Answer: You can use https://www.drupal.org/project/cer
You can then setup the reference both ways so when you add a reference on the first piece of content CER can add the back reference to the other piece of content.
Another option is to add a rule which will do this for you but CER is pretty solid when dealing with larger sites.
Comment: thank you. If you have a link to a tutorial on using CER and Entity API, please let me know.
Comment: This is really the only tutorial (http://www.wdtutorials.com/2013/06/10/drupal-7-module-introduction-corresponding-entity-references#.VK2V27iCPCR) out for CER (at least free, buildamodule.com or drupalize.me may have one paid) but the setup is pretty straight forward, and the instructions on the module page should be enough to get it setup. Also check the README for more info.


Better practice of using static libraries in Unix?

Question: I am new to unix.
This is the first time I am trying work with an external library(Ogre3D) on a Mac. I do not want to dump all of the .lylib files in into the /usr/lib directory since I might want to delete these files once I do not need them and it's hard to differentiate them form other library files. When I create a new folder named Ogre in the /usr/lib/ directory to host my Ogre library files it seems I cannot access these files when compiling files using -l flags to specify the location. So I am wondering if it's necessary to put all the files in the /usr/lib/ rather than putting them into a folder inside the /usr/lib/?
And I wondering that if it is possible to put the includes folder directly into /usr/includes/ so I can access the header files? Or I have to put all the headers in the /usr/includes/?
Comment: I believe that you should rather avoid using static libraries, and only use shared libraries. http://www.tldp.org/HOWTO/Program-Library-HOWTO/
Comment: And your question mentions a Mac but is tagged Linux... why??? (are you running Linux on a Mac laptop?)
Answer:
So I am wondering if it's necessary to put all the files in the /usr/lib/ rather than putting them into a folder inside the /usr/lib/?

No. There's the -L<dir> linker flag which makes the compiler search dir along with the standard library paths.

And I wondering that if it is possible to put the includes folder directly into /usr/includes/ so I can access the header files?

Even more choices here. Either put them in /usr/include/foo and then
#include <foo/foo.h>

(preferred) or put them in /usr/include/foo, use the -I/usr/include/foo compiler flag, and write
#include <foo.h>


Using "word-wrap: break-word" within a table

Question:
Possible Duplicate:
Word-wrap in a html table

This text behaves exactly the way I want on Google Chrome (and other modern browsers):

    aaaaaaaaaaaaaaaa
    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

When the browser is wide enough, a+ and b+ are on the same line.
aaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

As you narrow the browser, a+ and b+ are put on separate lines.
aaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

When b+ can no longer fit, it is broken and put on two lines (for a total of three lines).
aaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbb

That's all great.
In my situation, however, this is not a div but a table, like so:

        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

In this case, #1 and #2 happen, but not #3. That is, the table stops narrowing after step 2 and step 3 doesn't ever happen. The break-word doesn't seem to be filtering down.
Does anyone know how make #3 happen?  The solution only need work in Chrome, but it it also worked in other browsers that would be even better.
P.S. "Don't use tables" is not helpful.
Comment: Fascinating problem, not seen it before. It seems though this topic a similar (the same?) question was asked: http://stackoverflow.com/questions/1258416/word-wrap-in-a-html-table
Comment: There's lots of discussion on related issues here and elsewhere. There is definitely a lot of confusion around this issue and a lot of browser incompatibilities.
Comment: Referred Wrapping Long URLs and Text Content with CSS http://perishablepress.com/wrapping-content/
Answer: table-layout: fixed will get force the cells to fit the table (and not the other way around), e.g.:

        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

Comment: Note, with `table-layout: fixed` you loose the 'dynamic column width' feature of tables - all columns will be set to the same size.
Answer: You can try this:
td p {word-break:break-all;}
This, however, makes it appear like this when there's enough space, unless you add a
 tag:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

So, I would then suggest adding
 tags where there are newlines, if possible.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

http://jsfiddle.net/LLyH3/3/
Also, if this doesn't solve your problem, there's a similar thread here.


How do you count this?

Question:
This piece is in common time (4 4), but I'm having difficulty counting it.
I think the whole lower staff (all the note groups) should have the triplet mark but it doesn't (is this an error of the editor?).
And then for the upper one, I get the first voice on the top adds up very obviously to 4 beats but for the secondary voice, should I assume those are triplets as well? And then why would they not add up to 4 as well?
There are no rests so I'm not sure how that one works out. Thanks!
Answer: They're all triplets.  Once you realise there's continual triplets throughout the bar, it falls into place easily.  The engraver has taken a few shortcuts.
Answer: Every group of three sixteenth notes in this measure is a triplet. This could have been written much more clearly, but often the triplet marking is not continued once the pattern is established.
Answer: It could have been written more clearly. It's 8 lots of triplets, that alternate between hands. So, count 1&a2&a3&a4&a5&a6&a7&a8&a. Sounds complex! But the phrasing puts 1&a2&a as the first phrase, and the others follow suite.
The melody is shown with up stems, there being one concealed, played r.h. but written in bass clef - that's the F (#?) ninth dot from the end of the bar,  coming in on the count of 6&a.

How do you count this?


Part time courses in Jazz music in Germany

Question: I am a guitar player but had no formal music education and I want to learn Jazz improvisation with guitar as my main instrument.
I am looking for some courses in Jazz guitar in the German music schools (Musikhochschule), but I cannot find anything that offers a degree/diploma for part time studies.
Can anyone suggest any courses that I can take either online or in any music school/college in Germany?
Answer: I'm not familiar at all with music education in Germany, but I do have some ideas for what you can do. Mainly, if you want to receive a formal education in jazz, you should look for a private teacher. The best way to do this would be to honestly just ask around. You could even make a flier asking for a private teacher and post the flier all over.
Or, if you just want to get some sort of jazz education and you don't require a private teacher, the internet always has what you are looking for.

learnjazzstandards.com is a wonderful blog. They post many articles and podcasts weekly and have a variety of experienced jazz musicians on their staff. You're bound to learn a lot here.
coursera.com is a website with general online courses, but I've linked a specific one about learning jazz improvisation (taught by Gary Burton). There may be other courses as well.
Some music colleges, such as Berklee (which is an American college) have online courses as well. You can check out this and other colleges about online programs they may have.

Personally, I found a private teacher to be wonderful because it gives you someone you can talk to all the time with all of your questions. However, I've always studied music with a private teacher, so seeing that you were never formally taught guitar, you may do just fine using the internet.
But honestly, the internet has so many resources on jazz improvisation that you can at your own pace. Or, you may even be able to find some helpful books at your local book store.


all internal links won't work in a local-wamp site even after .HTaccess and mod_rewrite setup

Question: I've imported a Drupal 7.41 existing site to my local machine on a wamp server. I've already imported it's .HTaccess (uncustomized), and have enabled mod_rewrite in WAMP and restarted all services.
Yet, anytime I click on one of the internal links at the local site, I get, is some, 404 error, and in some WSOD.
When I tried to log in via localhost:8095/yoyo I got this error after filling the details and clicking on the log in button, I've seen the following error, but I don't know should I do with it exactly? (Adding some kind of a class manually?) Updating the theme maybe?
Answer: For the 404 errors on any internal links, have you edited the /rewritebase in htaccess? If the site now resides in a file, or in the root, this may need commenting out, or enabling.
As for the error. Are you certain you copied all files correctly?
Also, are you certain your mySql was dumped correctly?
Steps to try and fix can be...

Move files again.
Try dropping and reimporting the database.
Running registry rebuild. Note: this is not a module, this is something you can run with drush, or by placing the php in your directory and accessing it.
Try following this guys comment https://www.drupal.org/node/1323786#comment-5305922
Comment: Indeed it was a registry issue. About the link you pasted --- last comment; I understand right that the guy brought that code manually form a fresh install registry table? Thanks.


Duvida iteração dentro lista

Question: Como funciona o for dentro dessa lista?
list_liked = [i >= 4 for i in ratings]

Ele faz tipo um if e depois faz a iteração?
Comment: Sugiro você testar e ver o resultado por conta própria. Mas a resposta é não, ele na verdade faz um mapeamento e gera uma nova lista contendo False para os valores < 4 da lista original, e True para os valores >= 4.
Comment: Isso se chama [Compreensão de lista](https://docs.python.org/pt-br/3/tutorial/datastructures.html#list-comprehensions).
Comment: valeu pela ajuda, comecei estudar python ontem haha
Answer: Isso é uma list comprehension.
Basicamente, a estrutura é:
lista = [ expressão for i in iterável ]

Que é equivalente a:
lista = []
for i in iterável:
    lista.append(expressão)

Ou seja, para cada elemento do iterável, ele avalia o valor da expressão e coloca os resultados na lista final.

No seu caso, seria equivalente a:
list_liked = []
for i in ratings:
    list_liked.append(i >= 4)

Ou seja, para cada elemento de ratings (que no loop foi chamado de i), ele pega o valor da expressão i >= 4, e adiciona este valor em list_liked.
Mas vale notar que a expressão i >= 4 é uma comparação, e segundo a documentação, o resultado é um valor booleano (True ou False).
Portanto, o resultado será uma lista contendo apenas os valores booleanos True ou False. Exemplo:
ratings = [1, 4, 3, 6]

list_liked = [i >= 4 for i in ratings]
# cria uma lista contendo True ou False
print(list_liked) # [False, True, False, True]

Como o primeiro e terceiro elementos de ratings são menores que 4, o resultado da comparação é False. Já o segundo e quarto elementos são maiores ou iguais a 4, e portanto o resultado da comparação é True. Por isso o resultado é a lista [False, True, False, True].
Ou seja, neste caso ele não "faz um if". Ele simplesmente itera por todos os elementos, e para cada um ele avalia a expressão e o respectivo resultado é colocado na lista final.
O que pode ter confundido é que a expressão em si é uma comparação, mas isso não quer dizer que "tem um if" ali.

Só para completar, também é possível ter uma condição na list comprehension (ou seja, um if):
lista = [ expressão for i in iterável if condição ]

Neste caso é equivalente a:
lista = []
for i in iterável:
    if condição:
        lista.append(expressão)

Mas no seu caso não tem o if.
Comment: Cara, muito obrigado. Muito bem explicado!!!
Answer: Se não estou errado, para cada iteração, ele faz a comparação e se a comparação for verdadeira, ele devolve o valor iterado.
list_liked = [i >= 4 for i in ratings]

Faz o mesmo que:
list_liked = []
for i in ratings:
    if i >= 4:
        list_liked.append(i)

Comment: Não, esses códigos não são equivalentes. O primeiro gera uma lista de booleanos, enquanto o segundo gera uma lista com os próprios valores de `i`. Veja a diferena: https://ideone.com/43rz9R
Comment: *...Se não estou errado, para cada iteração, ele faz a comparação e se a comparação for verdadeira, ele devolve o valor iterado....* .Sim você está errado! A cada iteração é apensado o resultado da comparação `i >= 4` a lista em construção.

Duvida iteração dentro lista


Who Were Art Tatum's Influences?

Question: Art Tatum is one of the most influential figures in the history of jazz piano. He propelled the music forward perhaps more than any other jazz pianist. Specifically, Art was known for his reharmonizations (and chord substitutions) and his modern chord voicings, which would later impact bebop players and virtually all future jazz pianists.
Do these specific musical qualities (chord substitutions and voicings) appear in earlier artists who influenced Art? The evidence I'm looking for is a musical analysis comparing Art's work and known/possible influences on areas of chord substitutions and chord voicings.
Comment: I've seen a book called `Too Marvelous for Words: The Life and Genius of Art Tatum`. Haven't read it, but it might have some part of an answer you are looking for.
Comment: Does anybody agree, that the question seems more appropriate for Music Fans?
Comment: I love this question! Art Tatum was a key influence on many jazz pianists such as Oscar Peterson and Bud Powell. I would love to see what others say about him as he was a key influence in other genres of jazz.
Comment: @guidot, does MusicFans encompass musical analysis?
Answer: According to TOO MARVELOUS FOR WORDS: The Life and Genius of Art Tatum by James Lester (1994,) some of Art Tatum's direct influences were James P. Johnson, Willie (The Lion) Smith, Earl Hines, and Fats Waller.
He was also a fan of Lee Sims and, likely, Luckey Roberts... all of these musicians played ragtime and more than one of them are accredited with the creation of the Stride Piano style.
The specific qualities of the chord substitutions and voicing used by Tatum comes directly from the unique nature of Stride as a style:

The name "stride piano" came from the look of the striding motion of
the pianist's left hand, with its constant alternation of bass note on
beats one and three and mid-range chord on beats two and four.

[The left hand characteristically plays a four-beat pulse with a single bass note, octave, major seventh or major tenth interval on the first and third beats, and a chord on the second and fourth beats.]
Art Tatum had also a piano teacher by the name of Overton G. Rainey... But, Bill Cummerow, another partially blind pianist (like Tatum,) said that Rainey didn't improvise and also discouraged his students from doing so haha.
Comment: Thanks! More than just stride, I'm wondering about the voicings themselves. He was said to have used modern voicings and chord substitutions that other pianists did not start using until decades later. Were those elements totally invented by Art, or were there influences that he drew from?

Who Were Art Tatum's Influences?


Strange DNS host name response

Question: I've recently experienced an XML-RPC attack vs wordpress from a pair of machines for which dig -x returns a very very odd looking result:
;; ANSWER SECTION:
18.104.22.168.in-addr.arpa. 60  IN  PTR DEDICATED.SERVER.

I've never seen a TLD named DEDICATED before. I get the same result from my home machine and within amazon...
Comment: If you're looking to find the responsible party for this IP, `whois` will be more useful.
Comment: In this case, `SERVER` is the TLD, not `DEDICATED`.
Comment: Why the downvote? Is my question unclear somehow?
Answer: There is no actual requirement that PTR records return valid host names.
Unfortunately.

The typical approach to find the owner or ISP that manages an IP-address (range) is a WHOIS lookup.
In this case the  191.96.249/24 range is managed by company called Dmzhost Limited with abuse AT DMZHOST.CO as their email contact.
Comment: @Gus DNS has no such thing.
Comment: So DNS has a built in "cloak me" mechanism... fabulous.
Comment: whois wasn't installed, but now it is. Previously I had assume dig would be reliable :) thx
Answer: The guy who runs those servers (email@example.com) is as dodgy as they come, and he allows his servers to be used for DDoS:
https://email@example.com/plunging-into-a-ddos-hole-a-how-to-guide-b7565f814513#.s97ens0gl
Comment: I realise your username is a fairly big clue, but you might want to make the fact you are the author of that post clearer (see e.g. https://serverfault.com/help/promotion) - and extend your answer a little to reflect the contents of both your medium post, and the post you made on your own blog.

Strange DNS host name response


Repopulate input fields when validation fails in update a row Laravel

Question: Is there any way to repopulate input fields when validation fails in update any row? I know I can do it with laravel form model binding, but i dont want to use it. I can populate form from database table when update row. I want to repopulate the form with old input when validation fails in update not with database value. Thanks in Advance
Answer: You can leverage the old() helper. It is used this way:
<input type="text" name="username" value="<?= old('username', 'default value') ?>">


What is the best way to inject a list with google-guice?

Question: I have three classes CircleBuilder, SquareBuilder, and TriangleBuilder implementing the ShapeBuilder interface.
I need to initialize my FormBuilder and notably a BuilderList (extending List<ShapeBuilder>) with one instance of each class with google-guice.
What is the best way?
I know about the provider methods and stuff like this:
@Provides
FormBuilder provideFormBuilder() {
    DatabaseTransactionLog instance = new FormBuilder ( <numerous parameters> );

    ShapeBuilder builder = null ;
    builder = new CircleBuilder( <numerous parameters> ) ;
    instance.addBuilder( builder ) ;

    builder = new SquareBuilder( <numerous parameters> ) ;
    instance.addBuilder( builder ) ;

    // And so on

    return instance;
}

but it would mean that I have to create my FormBuilder manually which defeats the purpose of using guice (because FormBuilder is the top element in my object graph).
I'd love to be able to write something like this:
bind(BuilderList.class).to(CircleBuilder.class);
bind(BuilderList.class).to(TriangleBuilder.class);
bind(BuilderList.class).to(SquareBuilder.class);

Any idea?
Answer: Consider Multibindings, which will collect bindings very much like your code snippet. There is no provision for lists through Multibinder, because Multibinder is designed for binding to the same collection in multiple modules, and the element order of a Multibinder list would depend on the order that your Modules were evaluated.
Multibinder<ShapeBuilder> shapeBinder =
    Multibinder.newSetBinder(binder(), ShapeBuilder.class);
shapeBinder.addBinding().to(CircleBuilder.class);
shapeBinder.addBinding().to(TriangleBuilder.class);
shapeBinder.addBinding().to(SquareBuilder.class);

// Now you can inject Set<ShapeBuilder>.

Alternatively, your @Provides method can take in parameters (e.g. CircleBuilder or Provider<CircleBuilder>) so you can have Guice create everything except the List itself. Not only will Guice bind Providers of all bound types automatically, but it will also inject every parameter in any @Provides method.
@Provides List<ShapeBuilder> provideShapeBuilders(
    CircleBuilder circleBuilder,
    SquareBuilder squareBuilder,
    TriangleBuilder triangleBuilder,
    Provider<TrapezoidBuilder> trapezoidBuilderProvider) {
  return new ArrayList<ShapeBuilder>(
      circleBuilder,
      squareBuilder,
      triangleBuilder,
      trapezoidBuilderProvider.get(),
      trapezoidBuilderProvider.get());
}

Comment: Note : multibinding requires another jar -> guice-multibindings-3.0.jar
Comment: My question (sof url i'm including here) shows how to use Mulitbinder and then constructor-inject the "set" of concretes into the class that needs them (for those inclined to constructor based injection).    https://stackoverflow.com/questions/52279459/guice-with-multiple-concretes-picking-one-of-them
Comment: This is the current link to Multibindings user guide: https://github.com/google/guice/wiki/Multibindings
Answer: We can do something like this:-
@Override
protected void configure() {
    bind(ShapeBuilder.class).annotatedWith(Names.named("Circle")).to(CircleBuilder.class);
    bind(ShapeBuilder.class).annotatedWith(Names.named("Triangle")).to(TriangleBuilder.class);
    bind(ShapeBuilder.class).annotatedWith(Names.named("Square")).to(SquareBuilder.class);
}

In your FormBuilder Class:-
class FormBuilder{
   List<ShapeBuilder> shapeBuilderList;
   @Inject
   public FormBuilder(@Named("Circle")ShapeBuilder circle, @Named("Triangle")ShapeBuilder triangle,@Named("Square")ShapeBuilder square){
       shapeBuilderList = new ArrayList<>();
       //add all of them
       shapeBuilderList.add(circle);
    }
}


Uncaught (in promise) Error: Worker was terminated

Question: I am using react-pdf "react-pdf": "^7.3.3" to show some pdf file, now when I open the react app page, sometimes the devtools will show error:
email@example.com/build/pdf.worker.min.js:22 Uncaught (in promise) Error: Worker was terminated
    at ensureNotTerminated (email@example.com/build/pdf.worker.min.js:22:2053)
    at onFailure (firstname.lastname@example.com/build/pdf.worker.min.js:22:10071)

I have checkt he dependencies and make sure the pdf.worker.min.js version as the same wiith pdf.js version. what may cause this issue? I have made a minimal example but did not reproduce this issue. This is the minimal example:
import React from 'react';
import Previewer from './previewer/Previewer';

const App: React.FC = () => {
  return (

      <Previewer pdfUrl={"https://arxiv.org/pdf/2304.09103.pdf"}></Previewer>

  );
}

export default App;

and this is the Previewer component look like:
import React, { useState } from 'react';
import styles from './Previewer.module.css';
import { Document, Page, pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;
import 'react-pdf/dist/Page/TextLayer.css';
import 'react-pdf/dist/Page/AnnotationLayer.css';

export type ViewerProps = {
    pdfUrl: string | undefined;
};

const Previewer: React.FC<ViewerProps> = (props: ViewerProps) => {
    const [pdfScale, setPdfScale] = useState<number>(1);
    const [numPages, setNumPages] = useState<number>();
    const [pageNumber, setPageNumber] = useState<number>(1);

    const options = {
        cMapUrl: 'https://email@example.com/cmaps/',
    };

    if (!props.pdfUrl) {
        return (
Loading
);
    }

    const handleDownloadPdf = async (pdfUrl: any) => {
        if (!pdfUrl) {
            return;
        }
        try {
            const response = await fetch(pdfUrl);
            const blob = await response.blob();
            const downloadUrl = window.URL.createObjectURL(new Blob([blob]));
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.setAttribute('download', 'main.pdf');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        } catch (error) {
            console.error('Error downloading PDF:', error);
        }
    }

    const handleZoomIn = async () => {
        setPdfScale(pdfScale + 0.1);
    }

    const handleZoomOut = async () => {
        setPdfScale(pdfScale - 0.1);
    }

    const onDocumentLoadSuccess = (pdf: any) => {
        const { doc, numPages } = pdf;
        setNumPages(numPages);
    }

    const handlePageChange = (page: any) => {
        //setCurrentPage(page);
    };

    const handlePageRenderSuccess = (page: any) => {
        const pageIndex = page._pageIndex + 1;
        //setCurrentPage(pageIndex);
    };

    const renderPages = (totalPageNum: number | undefined) => {
        if (!totalPageNum || totalPageNum < 1) return;
        const tagList: JSX.Element[] = [];
        for (let i = 1; i <= totalPageNum; i++) {
            tagList.push(
                <Page key={i}
                    className={styles.pdfPage}
                    scale={pdfScale}
                    onLoad={handlePageChange}
                    onRenderSuccess={handlePageRenderSuccess}
                    pageNumber={i} >

                </Page>
            );
        }
        return tagList;
    }

    return (

                    <button className={styles.previewButton}>
                         预览
                    </button>
                    <button className={styles.previewButton}>
                         日志
                    </button>

                    <button className={styles.previewIconButton} onClick={() => { handleDownloadPdf(props.pdfUrl) }}>

                    </button>
                    <button className={styles.previewIconButton} id="zoominbutton" onClick={() => { handleZoomIn() }}>

                    </button>
                    <button className={styles.previewIconButton} id="zoomoutbutton" onClick={() => { handleZoomOut() }}>

                    </button>

                <Document options={options} file={props.pdfUrl} onLoadSuccess={onDocumentLoadSuccess}>
                    {renderPages(numPages)}
                </Document>

                    Page {pageNumber} of {numPages}

    );
}

export default Previewer;

does anyone facing the similiar issue?
Answer: The recommended way in the react-pdf docs is to do it this way:

import { pdfjs } from 'react-pdf';

pdfjs.GlobalWorkerOptions.workerSrc = new URL(
  'pdfjs-dist/build/pdf.worker.min.js',
  import.meta.url,
).toString();

I also used to do it with external CDN and there were few errors. But this work fine for me.


images repeating cells when scrolled in tableview

Question: images are not showing properly in tableview , I have two Json Api (Primary/high) school. I can append the Both Json api Data and display into tableview,
tableview working fine it's showing both(primary/high) school data. when I can scroll the tableview images are jumping and images loading very slow in image view at tableview.
Before scrolling tableview its showing like this

After scrolling the tableview it's shows like this
after scrolling images are jumping,

this is the code
     var kidsdata = [KidDetails]()

    func getprimarydata(_firsturl: String,firstid:String,updatedate:String)
    {

                                        if errorCode == "0" {

                                      if let kid_list = jsonData["students"] as? NSArray {

                                      self.kidsdata.removeAll()

                                      for i in 0 ..< kid_list.count {

                                      if let kid = kid_list[i] as? NSDictionary {

                                      let imageURL = url+"/images/" + String(describing: kid["photo"]!)

                                      self.kidsdata.append(KidDetails(
                                                            name:kid["name"] as? String,
                                                            photo : (imageURL),
                                                            standard: ((kid["standard"] as? String)! +  "std" + " " + (kid["section"] as? String)! + " section ")
                                                            ))}}}}
 }

      func gethighdata(_secondurl:String ,secondid:String,updatedate:String)
        {
         if errorCode == "0" {

                                if let kid_list = jsonData["students"] as? NSArray {
                                    for i in 0 ..< kid_list.count {

                                        if let kid = kid_list[i] as? NSDictionary {

                                            let imageURL = url+"/images/" + String(describing: kid["photo"]!)

                                            self.kidsdata.append(KidDetails(
                                                name:kid["name"] as? String,
                                                photo : (imageURL),

                                    standard: ((kid["standard"] as? String)! + "th" + " " + (kid["section"] as? String)! + " section ")
                                                )
                                            )
                                        }
                                    }

                                self.do_table_refresh()
                            }
                            }
    }

        func do_table_refresh()
        {

            DispatchQueue.main.async(execute: {

                self.TableView.reloadData()

                return
            })

        }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          let cell =
                tableView.dequeueReusableCell(
                    withIdentifier: "cell", for: indexPath) as! DataTableViewCell
            cell.selectionStyle = .none

            cell.ProfileImage?.image = nil

            let row = (indexPath as NSIndexPath).row

            let kid = kidsdata[row] as KidDetails

            cell.NameLabel.text = kid.name

            cell.ProfileImage.image = UIImage(named: "profile_pic")

            cell.ProfileImage.downloadImageFrom(link:kid.photo!, contentMode: UIViewContentMode.scaleAspectFill)
            cell.ClassNameLabel.text = kid.standard
           return cell
        }

where I did mistake pls help me....!
Comment: in your tableViewCell Class you need to reset the image in the function `prepareForReuse`. This will be called every time a cell will be reused and is the fiest point, where you can remove the image. The function is implemented in UITableViewCell and you have to override it
Comment: ah and your downloading an image, is this function running the download in a background thread and is putting the image in the main thread?
Comment: And does it proof if the cell, is still the cell that requested the photo? :)
Comment: @BjörnRo images are dowloaded from background thread am assing to main thread
Comment: this is great. So the image will currently not removed when setting `cell.ProfileImage?.image = nil` . Maybe the rest would happen in the prepareForReues funcw
Comment: func prepareForReuse(){

            cell.ProfileImage?.image = nil
        }
        I can try inside cellForRowAt same problem repeating
Comment: so you added this func in your DataTableViewCell and overrid the main one?
Comment: what about the image that your setting as well? the 'profile_pic' Do you see this one?
Comment: I can removed cell.ProfileImage?.image = nil and  cell.ProfileImage.image = UIImage(named: "profile_pic") no use
Comment: first cell and last images are shuffling
Comment: can you post the Class of the cell?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/153503/discussion-between-naga-and-bjorn-ro).
Comment: I can try all ways but am not getting wer I did mistake
Answer: AlamofireImage handles this very well. https://github.com/Alamofire/AlamofireImage
import AlamofireImage

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
              let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! DataTableViewCell
                cell.selectionStyle = .none

                let kid = kidsdata[indexPath.row] as KidDetails

                cell.NameLabel.text = kid.name
                cell.ClassNameLabel.text = kid.standard

                // assuming cell.ProfileImage is a UIImageView
                cell.ProfileImage.image = nil

                let frame = CGSize(width: 50, height: 50)
                let filter = AspectScaledToFillSizeWithRoundedCornersFilter(size: frame, radius: 5.0)

                cell.ProfileImage.af_setImage(withURL: urlToImage, placeholderImage: nil, filter: filter,
                                      imageTransition: .crossDissolve(0.3), runImageTransitionIfCached: false)

               return cell
    }

Comment: am using tableview in tab bar controller when the application launched first time tableview is not scrolling and not able to access tabbar items, after rerun app it's working fine, how to over com this problem
Comment: tableview Scrolling is working after my project clean and re run the app
Comment: after am try to add AlamofireImage  app is crashing
Comment: because of the     let row = (indexPath as NSIndexPath).row and kidsdata.count does not matching count
Comment: You probably should be calling tableView.reloadData() somewhere where you aren't right now.
Answer: All we need to do is use the prepareForReuse() function. As discussed in this medium article, This function is called before cell reuse, letting you cancel current requests and perform a reset.
override func prepareForReuse() {
    super.prepareForReuse()

    ProfileImage.image = nil
}


WordPress REST API first call always slow

Question: I am analyzing/troubleshooting a custom WordPress plugin that was developed for one client that implements a REST API to be used with a 3rd party provider. One of the requirements is to have all API calls executed in less than 1 second.
Currently the plugin offers registers 2 routes: "get user" and "create user". For the sake to make this question simple, I will focus on the first route as it is the simpler one.
The average execution time for "get user" is around ~0.5 seconds BUT the first call takes always more time up to 5 seconds. All further calls are always in the ~0.5 seconds range. If the API is not used for around 1 minute, then the next first call is again taking up to 5 seconds to be completed.
This makes me believe that there is some sort of cache available for a limited period of time (~1 second) or, that the hosting (SiteGround) / database has a sleep policy but I was not able to confirm it. To find it out, I did create a custom plain PHP script that mimics the same functionality as "get user" and the average response is ~0.15 seconds BUT also the first call takes more than the average: ~0.6 seconds.
The custom script could be one possible solution for our case but we would like to first to exhaust all the possibilities to make the WordPress plugin + REST API to work in less than 1 second if possible.

It seems that when using the REST API, a bunch of WP files are loaded according to this blog from 2016. Does this still apply nowadays for WordPress 5.5?
What could be the exact reason for the first call to take more time? And how I can optimize it for further calls?
Answer: There is a caching system for the WordPress API, and I'll refer you to this article: https://css-tricks.com/the-deal-with-wordpress-transients/
But there are a few things you could potentially do to improve performance, first of which is to examine your host. Depending on your provider, you could be running into some issues with response time that aren't cached.
Another, much more complex solution is to write your own custom API responses from WP. There are plugins that might help with streamlining the response from the out-of-the-box endpoints, here's one: https://wordpress.org/plugins/custom-api-for-wp/
If you go this route, make sure you follow good security practices for WP and PHP.


Remote logging - Nginx over Rsyslog or any other alternative

Question: I need to setup centralized remote access logging of Auto Scaling Instances. Currently I have Rsyslog / Apache2 logging working just fine, but for the new project Nginx is used and I don't see any possibility to log directly over TCP/UDP. Rsyslog can be configured to send data remotely reading local file, but my goal is to avoid local writes at all.
Can someone share the knowledge on how to configure Nginx to send messages over Network instead of local FS? Or maybe I might need to configure log rotation to scp files?
Answer: Create a FIFO (pipe), tell nginx to log to that, and have your syslog daemon read the FIFO and send those messages to a remote location.  Both rsyslog and syslog-ng can do this.
Comment: Because you said you wanted to avoid local writes.  A FIFO doesn't write to disk, it's just a small chunk of memory that buffers writes.
Comment: In this case, why not just let Nginx to log to default file and then use Rsyslog to read and send it remotely? What is the benefit of FIFO?
Answer: You can try the nginx_udplog_module.  It looks like it hasn't been updated in a while, but it may still work.


Bounding the difference of frobenius norm

Question: Let $A$ and $B$ are two $n\times d$ matrices having real entries, and $0\leq ||A||^2_F-||B||^2_F\leq \lambda$, for some $\lambda \in R$. Let $L$ be a $j$-dimensional subspace (with $j<d$) of represented by an orthonormal matrix $[X]_{d\times j}$ (having columns orthonormal  to each other), then the problem is to give an upper and lower bound on the following expression
 $||AX||^2_F-||BX||^2_F$
In the above $||A||^2_F$ is the frobenius norm of $A.$
Answer: We have $\|X\|_F^2 = Tr(X^T X)$.
Then we have $Tr(A^T A - B^T B) \leq \lambda$, and we wish to bound $Tr(X^T (A^T A - B^T B) X) = Tr( X X^T ( A^T A - B^T B))$. If the rows of $X$ are orthonormal to each other, then $X X^T = I$, so your expression is unchanged.
Comment: thanks for your response. In this problem columns of $X$ are orthonormal so $XX^T$ need not to be equal to $I.$


Is this the right way to delete an item from a dict while iteration?

Question: I want to know if this is the normal way to delete conditionally items from a dict. The following code doesn't report an error. Just want to know whether it is safe.
dict_items = {'a':1, 'b':2}

for key, value in dict_items.copy().items():
    if some_condition:
       del dict_items[key]

Here I use copy() function to avoid operating on the original dict.
EDIT:
Based on suggestions, I did the following:
for key in list(dict_items.keys())
        value = dict_items[key]
        if some_condition:
           del dict_items[key]

Should this be cheaper and still safe?
Comment: Yes, that's a reasonable way to do it.
Comment: You don't need to copy the whole thing, but this should be fine.
Comment: Depending on condition, you may want to copy only the keys, e.g., `list(dict_items)`, rather than using `copy`
Comment: @JBallin. But why?
Comment: If I remember correctly, you can get a list of keys with just `*dict_items` so doing this `list(dict_items.keys())` is overkill. Actually, double overkill cause `keys()` is already an iterable.
Comment: @MichaelGuidry Using list(dict_items.keys()) is to make a copy on purpose. If just using keys() to delete from the original dict, that would cause problem in iteration.
Comment: @marlon - wrong. '.keys()' just spits out an iterable of key names. It's already a "copy", so to speak. I think you misunderstand how your code works. Python doesn't got to the dict to get the next key on every iteration of the loop. When you call `keys()` python just spits out a list of keys that have no link whatsoever to the dict.
Comment: Changing your question by incorporating suggestions and then asking another is very confusing to others.
Comment: @MichaelGuidry I just tested. If i don't use 'list' to enclose the keys, it will report: 'RuntimeError: dictionary changed size during iteration'. You can try.
Comment: @marion - I actually can't try cause I live in New Orleans and there is no electricity. :D. I wish I could. However my original suggestion was to use `*dict_items` not `keys()`
Answer: That's a reasonable way to do it.
An alternative is to create a new dictionary with a dictionary comprehension that inverts the condition.
dict_items = {key: value for key, value in dict_items.items() if not some_condition}

Comment: That's only an option if the dictionary is not shared, since the original dictionary will remain unmodified.
Comment: In my code, the 'if some_condition' is simplified. In cases where there is more complex logic inside the if conditions, then the dict comprehension won't be that handy.
Answer: This is certainly a safe way to delete entries from the dict. However copying the entire dict might be expensive, so it might be better to save the to-be-deleted keys in a first loop and then only delete them afterwards:
to_be_deleted = []
for key, value in dict_items.items():
    if some_condition:
        to_be_deleted.append(key)

for key in to_be_deleted:
    del dict_items[key]


Slodowy slices for non ADE type Lie algebras

Question: In the first answer to:
https://mathoverflow.net/questions/16026/the-finite-subgroups-of-sl2-c
the correspondence between transverse slices of subregular elements of the nilpotent cone for a simple Lie algebra and du Val singularities is mentioned.
I'm curious, what happens if we start with a simple Lie algebra of a different type?  (Are subregular elements well defined?  wikipedia seems to indicate so but I cannot find a reference.  As a side note, a reference for this fact would also be appreciated!)
Answer: I found an answer to this question.  It was in Slodowy's "Simple singularities and simple groups" under the heading "inhomogeneous Dynkin diagrams."  There's a table that gives all the cases but for example, a B_n type Lie algebra will have a A_{2n-1} type simple singularity, with a Z/2 of automorphisms.  These automorphisms are due to the following: the group $G$ does not act on the slice but instead some subgroup of $G$; if the slice is given by $e + \ker(f)$, the intersection of the centralizers of $e$ and $f$ will.  For types $ADE$ this is connected but for other types it is disconnected, and the finite group given by the different connected components gives an automorphism of a finite group on the slice.
I think the above is at least mostly correct but I am not sure, since I've just started reading on the material.


Inclusion Of Unit Open Ball

Question: $X$ is a $\mathbb{K}$ normed linear space. To show:
\begin{equation}
\cup_{1\le p < \infty}\{x\in \mathbb{K}^n:||x||_{p}<1\} = \{x\in \mathbb{K}^n:||x||_{\infty}<1\}
\end{equation}

I have already shown that the 1st set is contained in the second. And for the 2nd part I think we haveto use  $lim_{p\rightarrow \infty}||x||_p=||x||_\infty$, some how.

My approch: Let the second set not be a subset of the first.
If we concider a point in the second set, we can find a open ball around it which doesn't intersect with the first set since both the sets are open. Now using the limiting condition we can show that the distance between two norms can be made as close as possible by inceasing $p$. Hence such a open set is not possible. Is this okay? or it lacks rigor?
Comment: You'd need to demonstrate the leftmost set is open; the rightmost set is open in the topology defined by the metric defined by the $\infty$-norm, but the latter isn't necessarily so.
Comment: I would say that your current formulation lacks rigor, but if you vigorously prove that the two norms can be made arbitrarily similar.
Comment: Can it be done that way?
Comment: Any other approaches are also welcome.
Comment: I would simply take an arbitrary element of the second set, that is, a bounded sequence where no term is greater than or equal to 1, and prove that it must necessary have a p for which its norm converges to below 1.
Comment: I have tried that way, but I'm unable to show the existence of such a p.
Answer: Let $x\in \cup_{1\le p < \infty}\{x\in \mathbb{K}^n:||x||_{p}<1\}$. Then there is $p\ge 1$ such that $\|x\|_p<1$. Therefore, for each $i\in\{1,2,\cdots,n\}$,
$$|x_i|\le\|x\|_p<1$$
which implies $\|x\|_\infty\le \|x\|_p<1$. So $x\in\{x\in \mathbb{K}^n:||x||_{\infty}<1\}$. On the other hand, let $x\in\{x\in \mathbb{K}^n:||x||_{\infty}<1\}$. Then for $i\in\{1,2,\cdots,n\}$,
$|x_i|<1$. Without loss of generality, let
$$ |x_1|\le |x_2|\le\cdots\le |x_n|, x_n\neq0. $$
Then
$$ \|x\|_p\le n^{\frac1p}|x_n|. $$
Noting $\lim_{p\to\infty}n^{\frac1p}=1$, there is $p>1$ such that $n^{\frac1p}<\frac{1}{|x_n|}$. With this $p>1$,
$$ \|x\|_p\le n^{\frac1p}|x_n|<1. $$
Thus
$x\in \cup_{1\le p < \infty}\{x\in \mathbb{K}^n:||x||_{p}<1\}$. So
$$ \cup_{1\le p < \infty}\{x\in \mathbb{K}^n:||x||_{p}<1\}=\{x\in \mathbb{K}^n:||x||_{\infty}<1\}.$$

Inclusion Of Unit Open Ball


local orientation preserving/reversing loops

Question: For a nonorientable manifold $M$, there should be a map $\pi_1(M, x_0)\to \mathbb{Z}_2$ indicating whether a loop preserves/reverses local orientation at $x_0$.
What's a good way to obtain/think about it in the context of algebraic topology? I don't know any differential stuff.
Comment: FWIW, if $M$ is differentiable of dimension $d> 0$, then this is the map $\pi_{1}(M)\to \pi_{0}(\text{GL}_{d}(\mathbb{R}))$ in the long exact sequence of the [frame bundle](https://en.wikipedia.org/wiki/Frame_bundle) of $M$. If $M$ is Riemannian, then the analogous statement holds with the orthonormal frame bundle and orthogonal group instead. These facts justify the physical intuition behind orientability.
Answer: For any connected manifold $M$ and point $p\in M$, there is a homomorphism $\omega\colon\pi_1(M,p)\rightarrow\mathbb{Z}/2\mathbb{Z}$, the orientation character, that maps a loop to $\pm1$ depending on whether it preserves/reverses orientation. The orientation character is trivial if and only if $M$ is orientable. Here's two related ways of thinking about it:

There is a two-fold cover $\tilde{M}\rightarrow M$, the orientation covering, which has $\tilde{M}$ is orientable and is trivial if and only if $M$ is orientable. The orientation character is essentially the first boundary map of the fibration LES associated to this covering
$$\dotsc\rightarrow\pi_1(\tilde{M},\tilde{p})\rightarrow\pi_1(M,p)\stackrel{\partial}{\rightarrow}\pi_0(F)\rightarrow\pi_0(\tilde{M})\rightarrow\pi_0(M)=1.$$
This sequence usually only is an exact sequence of pointed sets in the final terms, but we can identify $\pi_0(F)=\mathbb{Z}/2\mathbb{Z}$ by identifying $\tilde{p}$ (a chosen basepoint of $\tilde{M}$ lying over $p$) with $+1$. It still requires an argument that $\omega$ is a homomorphism, but the exact sequence makes it clear that $\omega$ is trivial if and only $\pi_0(F)\rightarrow\pi_0(\tilde{M})$ is surjective if and only if $\pi_0(\tilde{M})$ is disconnected. Thus, the characterizations of orientability in terms of the orientation character and in terms of the orientation covering are equivalent.

The homomorphism then factors through a homomorphism $H_1(M,\mathbb{Z})=\pi_1(M,p)^{ab}\rightarrow\mathbb{Z}/2\mathbb{Z}$ by the Hurewicz theorem. It then factors through a homomorphism $H_1(M,\mathbb{Z}/2\mathbb{Z})=H_1(M,\mathbb{Z})/2H_1(M,\mathbb{Z})\rightarrow\mathbb{Z}/2\mathbb{Z}$ by the Bockstein exact sequence. This corresponds to an element $w_1\in H^1(M,\mathbb{Z}/2\mathbb{Z})$ by the universal coefficient theorem. This cohomology class is a so-called characteristic class, the first Stiefel-Whitney class of $M$. (This also has an interpretation in the differential setting.) In fact, isomorphism classes of two-fold coverings of $M$, isomorphism classes of real line bundles over $M$ and elements of $H^1(M,\mathbb{Z}/2\mathbb{Z})$ are each in bijection with one another (and all in bijection with homotopy classes of maps $M\rightarrow\mathbb{RP}^{\infty}$). This correspondence identifies $w_1$ with the orientation covering of $M$. This yields another characterization that orientability is equivalent to the vanishing of $w_1$.


cast method in c# is not type casting

Question: I had to convert a string to int array first by splitting string by comma,then convert to int array.
and following line is working fine
 int[] array = input.Split(',').Select(obj=>Convert.ToInt32(obj)).ToArray();

but i wanted to do this in different way using cast extension method.
int[] array = input.Split(',').Cast<int>().ToArray();

but using cast extension it is throwing invalid cast operation exception.
I even applied ofType() prior to cast that is not really required but still its not working.
int[] array = input.Split(',').OfType<string>().Cast<int>().ToArray();

What mistake I am making here.
I am using cast method in appropriate manner.
Comment: It does cast. But the casting operator in C# does two different things, depending on context: reinterpreting, and conversion. The method is named for the cast operator in its reinterpreting sense, not the conversion sense. Frankly, your question would best be answer by you reading the C# language documentation, to learn about the cast operator, and the MSDN documentation, to learn about the `Cast()` method. All the answers are in there.
Comment: @peter please read my question first
Comment: For the `Cast()` method to work, the object has to be of the correct type already. The `Cast()` method only reinterprets the data, it doesn't do any conversion. See the marked duplicate for correct techniques in C# for parsing a string as an `int`.
Comment: @PeterDuniho, so it doesn't type cast, then why it is named cast
Comment: And note that _even if the `Cast()` method did support the conversion sense of casting in C#_, it still wouldn't work because there's no explicit conversion defined from `string` to `int`. You have to use a parsing method regardless (e.g. `int.Parse()`).
Comment: @PeterDuniho if it were to be doing type casting, then it could have used int.parse internally and returning the same. Anyhow, I got my problem. I perceived it as casting method rather it is similar to OfType(). only exception it throws exception if set doesn't all the item of same type.
Comment: You are completely missing the point. The word "cast" has multiple meanings in programming. You are stuck on just one meaning, and ignoring the fact that even in that meaning of the word, neither the language nor the framework has no mechanism for doing what you want. The method is well-named, and does exactly what the name suggests it does.
Comment: @PeterDuniho I am sorry if I am looking adamant to you. I admit I had misconception regarding this cast word and it may be the case with other dumb people like me as well as because not everybody is geek or intelligent like you. So, why don't you put your comment as answer. So, in future someone has same misconception, then it will clear their doubts. thanks Peter for valuable support.
Comment: You can also use following method:

int[] array = Array.ConvertAll(input.Split(','), Convert.ToInt32);
Answer: You should  use int.Parse to convert a string to int. In C#, a string is not being able to be casted directly into integer.
input.Split(',').Select(int.Parse).ToArray()

Comment: what is the mistake cast method of course I do have a working query already. Why I can't use cast method
Answer: You can also use following method.
int[] array = Array.ConvertAll(input.Split(','), int.Parse);

Comment: Of course, I can my question what is wrong with Cast method
Comment: @YogeshJoshi `Cast` will not work in your case. `Cast` is the extended method of `IEnumerable` interface and the type of your string array is `IEnumerable`. for example if you cast the array to enumerable by using `AsEnumerable` method then you will see the  type of the array will be `System.Collections.Generic.IEnumerable`

cast method in c# is not type casting


MVC list with a column to display an image

Question: I have a schedule for a hobby sports team site I did years ago.  I want to refresh in in VS 2017 using VMC as a learning tool to get better with MVC.
The data for the list presents this as the first column:
 teamLogo = "~/icons/" + tm.logolocation + ".jpg",
In the ASP view, I set the display for image and it works fine.  How do I do similar in MVC?
Thank you for the pointers.
Comment: I have my view with the traditional @Html.DisplayFor( ...)
Comment: How do I render the path that occupies model.logolocation ?
Answer: The controller uses this to present path and file extention no ~ needed.
<code> foreach (schedule game in Schedule)
            {
                game.logolocation = "/icons/" + game.logolocation+".jpg";
            }
</code>
The index view uses this:
<code><td>
            <img email@example.com(modelItem => item.logolocation) />
        </td>
</code>


Estratégia gulosa Python

Question: Estou com dificuldade de implementar um algoritmo que me deveria me retornar uma lista de moedas para ser utilizado com troco.
Minha função se chama troco_menores_moedas(carteira, valor_troco) que possui dois parâmetros:
- carteira: uma lista de inteiros que representa as moedas disponíveis em uma carteira.
Considere que os valores dessa lista sempre estarão ordenados!
- valor_troco: um inteiro, que representa o valor de um troco a ser pago;
A função deve usar a estratégia gulosa para retornar uma lista de moedas disponíveis
na carteira que serão utilizadas para pagar esse troco. O seu algoritmo deve utilizar
as moedas de menor valor que completam o valor do troco.

Retorno da função:
    - uma lista de inteiros representando cada uma das moedas que serão utilizadas
    para pagar o troco.

Essa foi minha implementação até o momento
def troco_menores_moedas(carteira, valor_troco):
    moedas_escolhidas = []

    for moeda in sorted(carteira, reverse=True):
        while valor_troco >= moeda and moeda in carteira:
            valor_troco -= moeda
            carteira.remove(moeda)
            moedas_escolhidas.append(moeda)

    return sorted(moedas_escolhidas)

Quando executo meus testes ele está falhando em 3 cenários específicos.
Plano de testes
@pytest.mark.parametrize('carteira,troco,resp',
[([5],5,[5]),
([1,5,10], 6, [1,5]),
([1,1,1,5], 7, [1,1,5]),
([1,1,1,2,2,2,10,25], 17, [1,1,1,2,2,10]),
([1,1,1,1,1,1,2,2,5,5,10,25], 25, [1,1,1,1,1,1,2,2,5,10]),
([1,2,5,5,5,5,10,10,10,25,25,50,50], 47, [2,5,5,5,10,10,10])])
def test_troco_menores_moedas(carteira, troco, resp):
    try:
        resultado = atv.troco_menores_moedas(carteira, troco)
    except:
        raise AssertionError('Erro ao executar a função troco_menores_moedas()')
    assert resultado == resp, 'Se carteira = {0} e valor_troco = {1}, a função deve retornar {2}'.format(carteira, troco, resp)

Minha dificuldade está sendo em ajustar o método para os seguinte cenários:
Se carteira = [1, 1, 25] e valor_troco = 17, a função deve retornar [1, 1, 1, 2, 2, 10]
Se carteira = [1, 1, 1, 1, 1, 1, 2, 2, 5, 5, 10] e valor_troco = 25, a função deve retornar [1, 1, 1, 1, 1, 1, 2, 2, 5, 10]
Se carteira = [1, 5, 5, 5, 5, 10, 25, 50, 50] e valor_troco = 47, a função deve retornar [2, 5, 5, 5, 10, 10, 10]
Answer: O objetivo da função "troco_menores_moedas" é utilizar a estratégia para retornar uma lista de moedas disponíveis na carteira que serão utilizadas para pagar um determinado troco.
A solução para os casos de teste falhos é adicionar mais uma condição no laço while da função, verificando se ainda existe um valor maior na carteira que possa ser usado para complementar o valor do troco. E adicionar uma nova variável "valor_faltante" para garantir que todas as moedas necessárias sejam incluídas no resultado.
Segue abaixo a nova implementação corrigida:
def troco_menores_moedas(carteira, valor_troco):
    moedas_escolhidas = []
    valor_faltante = valor_troco

    for moeda in sorted(carteira, reverse=True):
        while valor_faltante >= moeda and moeda in carteira:
            valor_faltante -= moeda
            carteira.remove(moeda)
            moedas_escolhidas.append(moeda)

        # Verifica se ainda existe um valor maior na carteira que possa ser usado para complementar o troco
        if valor_faltante > 0 and moeda < valor_faltante:
            valor_faltante += moeda
            carteira.append(moeda)
            moedas_escolhidas.remove(moeda)

    return sorted(moedas_escolhidas)

Com essa nova implementação, os casos de teste apresentados anteriormente foram corrigidos e a função agora está funcionando corretamente.

EDITADO:
Como a resposta do autor foi que isso não resolveu e ha comentarios de
que não estaria correto a logica que usei, sugiro outra tentativa com
o codigo a baixo:

def troco_menores_moedas(carteira, valor_troco):
    moedas_escolhidas = []

    # Começa pelas moedas maiores
    for moeda in sorted(carteira, reverse=True):
        while valor_troco >= moeda:
            valor_troco -= moeda
            moedas_escolhidas.append(moeda)

    return moedas_escolhidas

Solução:
Se a soma das moedas escolhidas até o momento for menor ou igual ao valor do troco, o elemento o consideramos como as moedas escolhidas para o troco.
Após classificamos a moedas escolhidas em ordem decrescente e o elemento atual é removido da lista se sua remoção não fizer com que a soma total das moedas restantes seja menor que o valor do troco.
Após é realizado o retorno das moedas escolhidas em ordem crescente.
Codigo a baixo:

def troco_menores_moedas(carteira, valor_troco):
    moedas_escolhidas = []

    for i in range(len(carteira)):
        if valor_troco >= sum(moedas_escolhidas):
            moedas_escolhidas.append(carteira[i])

    for j in range(len(moedas_escolhidas)-1):
        moedas_escolhidas.sort(reverse=True)

        if sum(moedas_escolhidas) >= valor_troco:
            if (sum(moedas_escolhidas) - moedas_escolhidas[j]) >= valor_troco:
                moedas_escolhidas.pop(j)

    return sorted(moedas_escolhidas)

Comment: Utilizando a lógica que você sugeriu acredito que consegui chegar na implementação que solucionou meu problema, realizei a sugestão de edição em seu post para acrescentar a solução.
Comment: Acho que isso não está certo. Estratégia greedy não usa condições de correção de escolhas. O algoritmo greedy obtém o menor valor possível a cada iteração sem ponderar prós e contras da escolha. No caso a dificuldade do exercício é fazer com que a condição de escolha seja a mesma para todas as iterações e assim chegar ao resultado esperado.
Comment: Realizei a implementação dessa condição e acabou que não houve diferença do código original. Ainda continuo caindo nos mesmos erros dos testes, quando minha carteira é [1,1,1,2,2,2,10,25] e o troco é 17 o teste continua esperando a resposta de [1,1,1,2,2,10] e a função continua retornando [1, 2, 2, 2, 10].
Comment: Está na condição do código esse trecho, não seria isso o requisito? moeda < valor_faltante.

Se não resolveu, desculpe-me, não entendi o requisito e não conheco as regras dessa estratégia em detalhes!
Comment: Editei minha resposta com outra tentativa que pode dar certo, se nao resolver não sei mesmo amigo.
Comment: Fico triste de estar me esforçando e ter recebido dois negativos já... espero que esteja funcionando minha segunda sugestão.

Estratégia gulosa Python


Any classical music written for dancing?

Question: I thought about it the other day - Virtually all popular music in the 20th century was written for the dance floor.
Is there any classical music written specifically for dances? I think I don't know any. I mean music that the composer intended people to actually dance to. Dance and movement is such a primal thing, so it's weird to me that I can't think of examples.
I don't count things like Bach suites for violin, cello etc. - these are dance forms, But I don't think he really meant for people to dance to this, same goes for Chopin waltzes and Mazurkas IMO. Also not Tchaikovsky ballets - it's dance alright, but not for the audience to dance.
Surely some composers composed music for the dance floor of their patron... Do you know any examples?
Comment: Why don't you think that Bach's movements which were named as dances were actually to be danced to? What do you think people did dance those dances to?
Comment: Sarabandes, gavottes, minuets, galliardes, the list is long. How are you classifying 'classical'?
Comment: Where do you get the idea that "Virtually all popular music in the 20th century was written for the dance floor."? That is just so patently incorrect as to be risible.
Comment: I don't know if Johann Strauss composed specifically for the dance floor, but his waltzes are quite danceable ( https://www.youtube.com/watch?v=_CTYymbbEL4&list=RD_CTYymbbEL4&start_radio=1&t=184 )
Comment: @NickQuant  Not to mention the rest of the Strauss dynasty!
Comment: Of course the Strauss father and son were writing for dance floors. And then mind the dance scenes of operas and all the menuets  and other dances (passe pied, gavotte etc.) at the courts.
Comment: @danmcb I just can't imagine a crowd dancing to the solo violin/cello suites. Wouldn't it be just too quiet over the sound of... feet? Also IMO the music isn't very...dancy. Maybe it's just modern interpretation? Possibly the orchestral suites and maybe the keyboard suites (french, italian and so on) would be a good fit - but I never saw anyone saying that this was their intention
Comment: @Yossi well for one thing you can play those pieces many ways. I used to practice Bach on sax and clarinet and let me tell you you can swing the *** out of it. It's definitely danceable. Second, your 2019 idea of "danceable" is not what people would have considered booty shaking back in 17xx. Third, the volume issue is just about instrumentation. People were accustomed to acoustic music then that was generally much lower in volume than now. Think about it.
Comment: Apparently there's a lot of dance music by Mozart https://en.wikipedia.org/wiki/Mozart_and_dance
Comment: @danmcb: Whaaaat? No twerking in the early 17th century? No way!  ;)
Comment: @Tetsujin - Pointed example: "My Heart Will Go On", which was written for a late 20th-century **movie** meant to be primarily shown in movie theaters where you cannot dance.
Comment: @tetsujin Ok, you're right, i take it back... Not virtually all music. Some of The most selling records in 20th century were rock albums, by the likes of the beatles and pink floyd, which are not meant for dance. But dance music does have huge presence. My point is - people always liked to dance, and contemporary music was written for this. I think they were always popular dance tunes. So are they any examples by the e familiar composers?
Comment: @Willem I know, what a shocker :-)
Comment: Actually, not a bad question... just that some of the assumptions are a bit misguided. I will +1 you tomorrow (already used all my votes for today.)
Comment: @danmcb and others, The OPs exclusion of Baroque, keyboard dance suites seem like a fair caveat as those were stylized dances meant for listening not social dance accompaniment. The question isn't really about danceability, it's about the intended purpose of the composition. I think the OP simply doesn't know about the terms _stylized_ dance suite and _social_ dancing.
Answer:
Is there any classical music written specifically for dances? I think
  I don't [know] any.

You have essentially answered your question - albeit, by excluding much of the classical music that was composed specifically for the purposes of dancing to it... Also, there are quite a few misconceptions in your question.
For starters, you seem to have a misunderstanding of the meaning of "Dance Forms." These are compositions that are made for a specific type or style (or "form") of dance... The word form in this case refers to a dance and not a 'musical form,' such as Strophic form or Binary form; of which a 'dance form' may or may not be composed. Composers MOST DEFINITELY intended for people to dance to these compositions. And, patrons would commission composers for the explicit purpose of writing dance music for their courts.
Secondly:

ballets - it's dance alright, but not for the audience to dance.

While this may be arguable in our modern age, ballet was very much intended for audience participation during the classical period. From this article:

The origins of ballet dancing can be traced to the Italian Renaissance
  courts of the 15th century. Dance masters would teach the steps to
  nobility and the court would participate in performances as a form of
  social entertainment. This practice continued for several centuries.

Finally, what you consider as "dance-y" is a subjective perspective likely due to circumstances of our modern society. Just as music that is 'popular' has changed since the 15th century, it is simply natural for preferences to change over time about music with which to dance, as well... For example, much jazz was originally created for the purpose of dancing to it. But, I would agree with someone that argued that a lot of that music doesn't feel or sound "dance-y" at all - even though the "Jazz Age" is barely 100 years old and much of that music is made with a drum-kit/trap-kit which is (arguably) THE instrument needed for making modern dance music.
Answer: I think you make good point to exclude stylized dances like Baroque keyboard suites where the music fits the general meter and tempo of dance styles, but wasn't actually used for dance accompaniment and ballet where the audience did not dance.
Having acknowledged that there was classical music written with the intention to accompany actual social dancing. Mozart's various German dances and sets of minuets come to mind. Waltzes from many composers also.
I think the important thing to look for are orchestration where a large ensemble was used to provide enough sound to fill the dance space, and dances in a set where the composer created enough material to cover the length of a dance event. This was the kind of material used to accompany social dancing.
Also, you can find lots of collections of dance tune which were published simply on piano staff, often figured bass with melody in the treble. I've seen such sets title like "for flute or violin" or something similar. That kind of material would have been used for actual dancing, but probably for smaller events.
Answer: There is not a whole lot of music for Viennese Waltz in formal or ballroom settings that is not both actively used for dancing as well as considered classical music.