Is there a reason instructors teach chords before arpeggios?

Question: Some friends of mine have started picking up my spare guitars and practicing while I play bass. They don't play guitar and have been asking me for tips.
Like me, they struggle with chords because they have to move multiple fingers to multiple strings all while playing. I found playing arpeggios to be easier and a good way to learn the chords, so I've been getting them to play arpeggios while I follow with a bass line.
I'm by no means a fantastic guitarists and not an instructor. Am I leading them down a bad path by telling them to play arpeggios first instead of pushing chords? Is there a reason instructors teach chords before arpeggios?
Chords always seemed harder to me.
Comment: As a guitar teacher, I've never started with just teaching random chords. I have always taught all my students *songs*. If those songs have chords, they learn those chords. If they have arpeggios, then they learn the arpeggios. I ask them for a list of songs they like and then we pick ones that are within reach based on their level and/or edit the difficulty of exactly how they play it so it's not frustrating. I'm not sure what other teachers do, but there isn't one right way to learn or teach guitar.
Comment: @ToddWilcox  I thought I was the only guitar teacher that believed students should learn to play guitar by learning to play simplified arrangements of songs they actually wanted to play instead of "The Saint's Go Marching In" or "Twinkle Twinkle Little Star".
Comment: @RockinCowboy I actually hate simplified arrangments unless there is no other option that will help with motivation, be instructive, and also not frustrate the student. More often any simplification will be temporary. Like "let's play it this way until you get it down, then we will add in these elements" until the student is playing the exact same part as on the recording or as written.
Comment: @ToddWilcox Agreed.  I prefer to teach various techniques by incorporating them into arrangements of songs they might have already learned a simplified arrangement for.  Gives them a more powerful "why".
Comment: @ToddWilcox - Whilst agreeing that chord playing is the backbone of being a guitarist, I taught chords that went with songs. Maybe subtly different from your approach, not sure. But my objective was not to actually learn a raft of songs, rather to teach how a set of chords worked together. The songs were merely vehicles. Often, I didn't necessarily  expect to hear a completed song - that was the choice of the student, but if they understood how chords fit together to work in songs, that was mission accomplished.On a different level, I've worked with many players who obviously did just  (cont).
Comment: learn songs, verbatim, and that's what they end up having to do, with each and every song. They seem incapable of listening, and being able to hear/understand the chord structure, thus playing it straight away. So, for my method, capbility of playing chords and knowing how they fit together - and realising that patterns are prevalent - seems to be more productive in the long run than learning a song for the song's sake, then another...   Yes, some wanted to do particular songs, and that wasn't denied, and simplified versions in playable keys did the job, but so many teachers seem hell (cont)
Comment: on teaching just songs. What I'm trying to say is "Now you know those 4 chords, let's try to fit them into a few songs" instead of "You'll need to learn those 4 chords in order to play that one song", if any of this makes sense. And if a song comes along that needs an extra chord, it's a good time to find out why it's needed, and how it fits in the group of chords, and indeed, an incentive to learn that new chord, and its changes from and to the others already known. Answers on a postcard...
Comment: @Tim My students generally like riff-based music. I.e., there's virtually no song I've taught that one could play by just knowing 4, 5, or even 20 chords. See, for examples, Led Zeppelin *Heartbreaker*, System of a Down *Hypnotize*, Muse *Time is Running Out*, AC/DC *Thunderstruck*, The Jonas Brothers *SOS*, Metric *Black Sheep*, Tool *The Grudge*  etc.
Comment: @ToddWilcox - thanks for the response. Very different stuff (hate the word genre) from what most of my students play. With me at least!! They probably do it out of my earshot! I guess each song does need to be addressed individually - this one uses E blues scale, etc.,but what about middle of the road stuff?
Answer: Actually you might be on to something.  I know from teaching beginning guitarist (and from my own personal experience) that learning to contort your fingers and hands into the correct position to instantly finger a given chord is very difficult.  Nothing in the natural everyday world provides any advance training for those type hand formations and movements - they are completely foreign and unnatural.
Because it is so difficult to contort into the strange positions needed to play a chord and requires a great deal of dedication and intentional practice resulting in massive amounts of frustration, MOST aspiring guitar students give up their dream before they can play their first song!
But eventually an aspiring guitarist should learn to play chords because almost all guitar music is based on or around chord formations.  Obviously rhythm guitar (which is easier for most students to master than lead guitar or classical fingerstyle) is almost all chord based.  Learn to play three chords and you can strum your way through literally thousands of songs.
Even when a guitar student advances to playing lead guitar, knowing the scales that are centered around basic chord shapes will help them find the notes they need easier than just randomly attempting to memorize where every note is on all 20 plus frets on all 6 strings.
But - (and here is where your idea has merit) a great way to learn to play chords - might in fact be to play arpeggios based on the chords.  By playing the chord tones as individual notes, it would not be mandatory to get your fingers to simultaneously land on each string at the correct fret (as would be required if you were strumming the chords).
So if your friends can play arpeggios while placing their fingers in the correct position for an underlying chord one string at a time - instead of having to try to land all the fingers in the exact right place all at once, then they might actually be more inspired to continue playing.  Eventually they will get closer to being able to get all their fingers in the right place at once.
They would not even have to play a true arpeggio, but rather just some melodic sounding picking of individual notes out of a chord one string at a time so that it sounds musical and pleasing to the ear.
So I would say, that as long as your friends learn how to form the chords, if they want to learn to play the chords by placing their fingers one at a time while playing individual chord tones in a melodic sounding way (that resembles an arpeggio) then they need not listen to "conventional wisdom".  They may have a better chance of developing the requisite passion for guitar that inspires them to put in the needed hard work IF - they start by doing what gives them more immediate gratification and positive reinforcement.
So you might actually be leading them down the path of least resistance at first, but that path could very well lead to them becoming a capable guitarist.
Comment: My favorite for practicing the change between G and C is this little melody (all 8th except the last note - I hope the notation is understandable) ef||:gg'b'g''bg'd'g'|e'g'c''e''c'g'e'g'|e'g'c''e''c'g'e'g'|d'g'b'g''b'g'ef:||g - you start out on the lowest string, bring the first finger for the G-chord into position and then have two 8th time to get the finger on the highest string into place before you need to play it. Then the b and you have another three 8th of open strings while you get ready for the C-cord shape. And the transition from C to G also gives you three 8th of open strings.
Answer: Arpeggios generally start on the root, then sequentially play 3,5,8 and so on. Guitars can be used to play these, but they don't always relate exactly to chord shapes. Take a simple E maj. chord, and you find that it leaves out the major 3rd note that you'd play in the arpeggio on the 6th string 4th fret. O.k. the rest of the notes follow well, but the two are not exact copies.
Not many instruments are chordal, so playing chords is something a guitarist ought to be good at. Arps not so important. Probably more important to bass players, but they dont often ( someone will argue that point!!) play chords in a normal bass playing situation.
Yes, it's tricky in the beginning using more than one finger in order to play a chord, but that's the nature of the beast. It's far more useful that a guitarist knows chords than can play arps.
Comment: Sometimes if I pick out the notes of a chord one string at a time in order, I call it an "arpeggio" even though it technically may not be a true arpeggio the way you would play it on keys.  But your point is valid.  Agreed that knowing chords is an essential part of learning to play guitar.
Answer: First, there's tradition ... from your Uncle Joe who played bluegrass with the boys for barn dances every Saturday night (or maybe his name was Bill and he covered CCR tunes in the local bars with his buddies) to popular teachers such as Mel Bay and the like.  For years guitar method books would teach G, C, and D7 and then tell you that "anybody can play rhythm guitar" ... right? (And thanks to Bill Haley, Elvis, and Buddy Holly it was pretty much true!)
Perhaps worth considering also --- you state "I found playing arpeggios to be easier" (than chords).  In keyboard playing it's the other way round; playing 3 notes at once requires less motion and cognitive (read: over a time span) reasoning that playing them as an arpeggio.  And an arpeggio is often defined as a "broken chord", too (even on Wikipedia).
So it might be worth finding out if a guitar teacher who teaches chords first has been influenced by keyboard study or a keyboard teacher, or a theory teacher who is "keyboard-centric" (in my experience that's most of them).
Comment: Good point about the difference it playing chords on keys vs. strings.
Answer: One big reason is that playing arpeggios requires single note playing, often across strings. This is quite advanced compared to strumming all (or most) strings together, assuming you play with a pick. I am surprised your friends find it easier.
Also, playing single notes requires greater coordination between the hands. I would also argue your point that chords are harder because you "have to move multiple fingers to multiple strings, since once you've put them in the right place you can leave them there and bang away with the strumming hand (as long as the chord don't change).
I would also argue that arpeggios are of little value compared to chords, but of course that depends on the situation and musical genre.
Answer: It speaks to why people play guitar. If you want to go to Julliard then just strumming your chords for several hours a day is not going to get you to there.
To get a person who has that ambition is rather rare. What most people get into guitar for is just to play some popular songs with friends and family.
There is of course nothing wrong with such an ambition. Just like not everyone who takes up jogging does it to become an Olympic marathon athlete so does not everyone take up the guitar to become the next John Williams.
Getting people to strum and learn chords is the easiest way to get them to play the songs they like so this is what teachers, teach.
After all teacher just like most other people have to give the people who employ them what they want.


What is the meaning of the term "stable" in relation to predictions?

Question: In section 2.3 of Elements of Statistical Learning  when the text introduces the linear model and k-nearest-neighbour it states:

The linear model makes huge assumptions about structure and yields stable
  but possibly inaccurate predictions. The method of k-nearest neighbors
  makes very mild structural assumptions: its predictions are often accurate
  but can be unstable.

What is the meaning of stability in this context? Please elaborate in relation to the aforementioned methods.
Answer: The book Elements of Statistical Learning does not seem to give a formal definition of the concept of "stability" as it is used in this context. The words stable or stability do not occur in the index. However, the following quote seems to indicate the intended meaning (page 16 of second edition):

The linear decision boundary from least squares is very smooth, and
  apparently stable to fit. It does appear to rely heavily on the
  assumption that a linear decision boundary is appropriate. In language
  we will develop shortly, it has low variance and potentially high
  bias. On the other hand, the $k$-nearest-neighbor procedures do not
  appear to rely on any stringent assumptions about the underlying data,
  and can adapt to any situation. However, any particular subregion of
  the decision boundary depends on a handful of input points and their
  particular positions, and is thus wiggly and unstable-high variance
  and low bias.

With the linear model all of the data contributes to the predictions for any particular $x$.  This gives low variance, hence its predictions can be stable — but high bias if the linear model is not a good approximation.
With the $k$-nearest neighbors method, for any particular $x$ only the $k$-nearest neighbors contribute to the prediction. As a result the variance is higher, hence its predictions can be unstable — this is especially so if $k$ is much smaller than $n$.The gain is that by only using close points, the approximation could be better, so potentially lower bias. One problem is that if the ambient space of the $x$ is high-dimensional, there might be no really close neighbors anyhow.
Furthermore, for defining neighbors we need a distance measure, a metric.  The results of $k$-nearest neighbors depends critically on the definition of the metric, while the linear model does not use such information.  The book elements of statistical learning do assume an euclidean metric, bit other choices are of course possible. For the euclidean metric to be meaningful, the different variables must be on comparable scales. If, for instance, you multiply one of the variables by 1000 (changing unit from km to m, for instance) that will change, maybe drastically, the $k$-nearest neighbors solution, while it has no impact on the linear model at all.

Below is the original answer — as historical documentation:
In this context it probably means that when the input data $x$ changes a little, then the predicted value also changes only a little bit, in an easily understood manner, while with $k$-means, this need not be true, some little change in $x$ could cause a surprisingly large change in the prediction.
Comment: A basic problem with the linear model is that its results are sensitive to any data that are "influential" or have high "leverage." Both of these are technical terms that refer to quantitative assessments of how the regression estimates or fitted values change when an individual response is varied. This shows that according you your answer, linear regression is "unstable." A better answer would therefore either have to be altogether different or else it would show us *quantitatively* how points in a k-means fit tend to have *greater* leverage than comparable points in an OLS fit.
Comment: @whuber & kjetil b halvorsen: Is there a consensus on a correct answer? Also, is there a reason you have been discussing k-means instead of k-NN?
Comment: I agree the newer answer is probably more in line with ESL, but I get where the earlier one was coming from: For k-NN vs. linmod the difference is more than just [condition number](https://en.wikipedia.org/wiki/Condition_number), as the nearest neighbor mapping is **discontinuous** as a function of the inputs.
Comment: According to this definition, the linear model is "unstable" too.
Answer: I'd like to illustrate these two using the following comparison.

As you can see the higher the variance the more unstable the prediction will be and the higher the bias the mean of the prediction will be more far away from the target. The linear regresson would be stable but its bias sometimes is high(overfitting); while the KNN might be accurate(low bias) but might be unstable(high variance).
Comment: "The linear regresson would be stable but its bias sometimes is high" Shouldn't this be "underfitting"?


styleClass genérico na tabela

Question: estou montando uma tabela e queria saber o seguinte: Quero colocar um estilo css nos cabeçalhos das colunas, é preciso usar um styleClass em cada cabeçalho ou consigo declarar um genérico pra todos os cabeçalhos?

Answer: se o "cabeçalho" for uma  você pode colocar no seu estilo assim:
table th { ... }

styleClass genérico na tabela


Line Integral: why does it require |r'(t)|?

Question: I'm a confused by the following definition of the line integral from Wiki:
For some scalar field $f : U \subset R^n \to R$ the line integral
along some piecewise curve $C \subset U$ is defined as:   $\int_C f(r) \ ds = \int_a^b f(r(t)) | r'(t) | dt$
where $r : [a,b] \to C$ is an arbitrary bijective parametrization
of the curve $C$ such that $r(a)$ and $r(b)$ give endpoints of $C$.
QUESTIONS
On the LHS $r$ is used.  Is it still defined as a bijective parametrization?
On the RHS why is the Euclidean norm $|r'(t)|$ required in the equation?  Intuitively, it seems the line integral could just be calculated $\int_a^b f(r(t)) dt$?
Comment: You have wrong symbols all over here. Why a $>$ in the middle of the line integral? For a mapping, you use $\to$, not $\implies$. The $r$ should not be on the left; it should be a neutral letter like $x$. $s$ represents arclength on the curve; do you think that if you change $t$ a little, then $r(t)$ moves a distance of $\Delta t$? When you drive your car, is your distance given by the time you drive, independent of your speed?
Comment: Fixed. Quoting caused it.
Comment: In the same wiki, if you scroll a little down, they tell you why you have to multiply by $|r'|.$ What is unclear there?
Answer: A stupid example of why you need the $|r'(t)|$ factor.
Suppose you have your parametrization of $x$ and $y$ in terms of some parameter t.  We could replace $t$ with $2t$ and it would still describe the same curve.  You would be moving along the curve at twice the speed, but it is the same curve.  As a result of moving along that curve at twice the speed, the interval of integration will be cut in half though.  The $|r'(t)|$ will correct for such shenanigans.
$\int_a^b f(r(t))|r'(t)|\ dt = \int_{\frac {a}{2}}^{\frac {b}{2}} f(r(2t))|r'(2t)|\ dt$
We want to analyze the integrand such that ever piece of the curve of equal length has equal contribution regardless of the "speed" we are moving across those lengths.
The $|r'(t)|$ factor gives us a consistent integral for a path regardless of the parameterization of that path.
Answer: The factor makes the integral well-defined, meaning that it doesn't depend on the choice of parametrization of the curve.
See the below answer of @Doug M for an example.

Suppose you have your parametrization of $x$ and $y$ in terms of some parameter t.  We could replace $t$ with $2t$ and it would still describe the same curve.  You would be moving along the curve at twice the speed, but it is the same curve.  As a result of moving along that curve at twice the speed, the interval of integration will be cut in half though.  The $|r'(t)|$ will correct for such shenanigans.
$\int_a^b f(r(t))|r'(t)|\ dt = \int_{\frac {a}{2}}^{\frac {b}{2}}
> f(r(2t))|r'(2t)|\ dt$
We want to analyze the integrand such that ever piece of the curve of
equal length has equal contribution regardless of the "speed" we are
moving across those lengths.
The $|r'(t)|$ factor gives us a consistent integral for a path
regardless of the parameterization of that path.
Comment: Your answer shouldn't rely on the presence of a comment (which can vanish without a trace); if you need to refer to the comment, you probably should quote it.


Stop Lilypond from generating multiple files

Question: I am not sure if this is the right place to ask, but it seems like a lot of people are using Lilypond here.
Every time I compile a .ly file using lilypond for Windows10 it generates too many files. It outputs a pdf for the whole piece (which is what I need), and a separate pdf for each line of the piece + a .eps file for each one of those pdfs + some additional .count and .tex files.
I have tried compiling both using cmd and double clicking on the .ly file. On command line, I have tried adding --pdf, --loglevel=NONE, --output=FILE, -fpdf, -dno-print-pages and -dprint-pages, but nothing seems to help.
Comment: Possible duplicate of [Is there a way in Lilypond to omit entire staffs from the pdf layout but listen to them in MIDI?](https://music.stackexchange.com/questions/67472/is-there-a-way-in-lilypond-to-omit-entire-staffs-from-the-pdf-layout-but-listen)
Comment: Also probably helpful:   http://lilypond.org/doc/v2.19/Documentation/learning/string-quartet-parts    But in any case, the PDFs can't come into existence without the .count, .tex,. .eps as those are byproducts of the applications "behind the scenes"
Comment: You sure there's nothing in the user manual about "print full score only" argument?
Comment: That doesn't happen by default. Did you use something like `lilypond-book-preamble.ly`?
Comment: Re "But in any case, the PDFs can't come into existence without the .count, .tex,. .eps as those are byproducts of the applications behind the scenes": sorry, this is just wrong. LilyPond does not create such files by default.
Answer: If the -o option is generating multiple files, you can try the following command to explicitly specify the format of the output file:
<code>lilypond -dbackend=pdf -o outputfile.pdf inputfile.ly
</code>
This will generate a single PDF file named outputfile.pdf from the input file inputfile.ly. The -dbackend=pdf option sets the backend format to PDF.


How to print count table query of bigquery in python?

Question: I am trying to print count of rows available in table of bigquery in python,I have written below code:
from google.cloud import bigquery def main():
    myquery = "select count(*) from `myproject.mydataset.mytable`"
    client = bigquery.Client()
    job = client.query(myquery)
    result = job.result()
    print("Total rows available: ",result)

When I execute above code it gives me output as

"Total rows available: google.cloud.bigquery.table.RowIterator object
  at 0x00000247B65F29E8>".

It means I am getting object value as my output.
But I want to print actual count of rows available in my table(query result).
Comment: It'd probably be better if you used the [Table](https://googleapis.dev/python/bigquery/latest/usage/tables.html) object to do so. See the example for connecting with your table then just print [`table.num_rows`](https://github.com/googleapis/google-cloud-python/blob/master/bigquery/google/cloud/bigquery/table.py#L530); this operation would be free of charge and much faster.
Answer: RowIterator has an attribute called total_rows.
Simply change your last statement to
 print("Total rows available: ", result.total_rows)

Comment: In any case, expected result with this change only should be 1. As count returns one row.
Comment: I just tried this way but it gives me "Total rows available:  None" as output. But in actual I have 634700 rows in that respective BQ table (output if i run same query from BQ console).
Comment: No. `result.total_rows` and `result.num_results` only report how many results have been iterated and show None or 0 before you start to iterate over the RowIterator
Comment: `results.total_rows` is perfect. https://cloud.google.com/bigquery/docs/samples/bigquery-query-total-rows
Answer: Try changing your query to
myquery = "select count(*) size from `myproject.mydataset.mytable`"
client = bigquery.Client()
job = client.query(myquery)
result = job.result()
for row in results:
    print("Total rows available: ",row.size)

Answer: BigQuery first returns a query object and from there you can get the result using .result().  But that is an Iterator object so you have to iterate to get the values.  In a count (*) you know that there is only one row to iterate on so you can use "next".  And that returns a row with one value in it and thus the [0].
    myquery = "select count(*) from `myproject.mydataset.mytable`"
    iterator = client.query(myquery).result()
    first_row = next(iterator)
    print("Total rows available: ",first_row[0])

Comment: Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it'd be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren't as familiar with the syntax or struggling to understand the concepts. **Would you kindly [edit] your answer to include additional details for the benefit of the community?**


BeautifulSoup scraper downloaded images are corrupt

Question: I greatly need help for my code. I was attempting to do an exercise from a book and I followed it exactly. The code worked and it downloaded the images. However, all the images that was downloaded were corrupted. I have no idea whats causing it or what I missed.
Thanks.
<code>#! python3
# downloadXkcd.py - Downloads every single XKCD comic.
import requests, os, bs4

url = 'http://xkcd.com'
os.makedirs('xkcd', exist_ok=True)

while not url.endswith('#'):
    # Download the page.
    print('Downloading page %s...' % url)
    res = requests.get(url)
    res.raise_for_status()

    soup = bs4.BeautifulSoup(res.text,'html.parser')

    # Find the URL of the comic image.
    comicElem = soup.select('#comic img')
    if comicElem == []:
        print('Could not find comic image')
    else:
        comicUrl = comicElem[0].get('src')
        # Download the image.
        print('Downloading image %s' %(comicUrl))
        res.raise_for_status()

    # Save the image to ./xkcd.
    imagefile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
    for chunk in res.iter_content(100000):
        imagefile.write(chunk)
    imagefile.close()

    # Get the prev button's url
    prevlink = soup.select('a[rel="prev"]')[0]
    url = 'http://xkcd.com' + prevlink.get('href')

print('Done')
</code>
Answer: You are writing wrong data to the file:

for chunk in res.iter_content(100000)

res is the data of the webpage. You should be getting the data of the image with the url comicUrl instead. I think you forgot this line:
<code>print('Downloading image %s' %(comicUrl))
res = requests.get('http:' + comicUrl)
</code>
Note: I added http: before the url because the image urls you are extracting lack this. You should define a function to check whether it is necessary to add this schema.
Comment: Oh wow thanks alot! I cant believe I missed a line. This code was really making me go crazy.
Appreciate your help.


PHP Standard author header comments

Question: What is the format I should use for PHP header comments?
Is this the same for PEAR as found here http://pear.php.net/manual/en/standards.header.php?
What should be contained?
<?php

/**
 * database.php
 *
 * Database access
 *
 * @category   CategoryName
 * @package    PackageName
 * @author     Mike
 * @copyright  2013 Mike
 * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
 * @version    CVS: $Id:$
 * @link       http://pear.php.net/package/PackageName
 * @see        NetOther, Net_Sample::Net_Sample()
 * @since      File available since Release 1.2.0
 * @deprecated File deprecated in Release 2.0.0
 */

?>

Could someone please explain what each of these actually mean other than the author and copyright.
Does entering the version number here do anything other than show the programmer? Can it be used by the system itself?
@package and @category What do these two do? And again, are they used by the system or is it purely for the programmer?
Comment: See [phpdoc](http://phpdoc.org/). It's used to compile documentation in a readable form and can also be parsed by most ide's.
Comment: Can I install this locally on my Mac and use it in conjunction with SUblimeText?
Comment: Probably but I'm not really familiar with sublime. I use vim ;)
Answer: Check out the PHPDoc documentation. It contains explanations of all of the tags.
phpDocumentor 3.0
https://docs.phpdoc.org/3.0/guide/references/phpdoc/tags/index.html
Answer: Check out the PHPDoc.org @author tag.
Syntax
@author [name] [<email address>]

Examples
 /**
  * @author My Name
  * @author My Name <email@example.com>
  */

Answer: Since PEAR head was made for PHP4 code with small updates to work with PHP5 I'd look as something more in line with current standards. @package and @category were something that PEAR used to split up code before PHP had namespaces. All new code should not use them except if you are planning to use PEAR to distro your code. As someone else already give link for PhpDoc it's the best place to learn about the available tags. I'd also take a look at the tags other major projects that you find on GitHub and other sites use as most use similar but more updated styles with the most common tags.
Answer: I used this comment style for function

/**
* @author     Azxster
* @datetime   04 March 2020
* @perpose    Standard commenting way
* @input      Get comment requirement
* @output     Show comment represent the way
*/
Comment: maybe spell @purpose correctly though =)

PHP Standard author header comments


My string set using UserDefaults coming up as nil when I try to access it

Question:
As my code below shows...
When I press the save button, it saves textfield input to user defaults so I can display it in a label. That works fine, as the label is displayed immediately when I save the input.
I've added a swipe gesture to flip the UIView containing the label and display another image. But when I want to flip it back with the swipe, it shows an error saying the label is now nil??
I am new to this, spare me if it is an easy silly error easily fixed.
Thnx for any help.
ViewController.swift FILE
  import UIKit

class ViewController: UIViewController {

var back: UIImageView!

@IBOutlet weak var plateView: UIView!
@IBOutlet weak var text: UITextField!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var saveBtn: UIButton!

var showingFront = true

let defaults = UserDefaults.standard

override func viewDidLoad() {
    super.viewDidLoad()

    back = UIImageView(image: UIImage(named: "back.png"))

    let swipe = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.swiped))
    swipe.direction = UISwipeGestureRecognizerDirection.left
    plateView.addGestureRecognizer(swipe)

    label.backgroundColor = UIColor(patternImage: UIImage(named: "blank.png")!)

    saveBtn.isHidden = true

}

func swiped() {

    if (showingFront) {

        UIView.transition(from: label, to: back, duration: 1, options: UIViewAnimationOptions.transitionFlipFromRight, completion: nil)

        showingFront = false

    } else {

        UIView.transition(from: back, to: label, duration: 1, options: UIViewAnimationOptions.transitionFlipFromLeft, completion: nil)

        showingFront = true

    }
}

@IBAction func editingDidBegin(_ sender: Any) {

    saveBtn.isHidden = false
    label.isHidden = true
    text.isHidden = false
}

@IBAction func save(_ sender: Any) {

    defaults.set(text.text, forKey: "number")
    defaults.synchronize()
    let num = defaults.string(forKey: "number")
    label.text = num

    label.isHidden = false
    saveBtn.isHidden = true

    view.endEditing(true)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

Comment: Can you please share the image of your Storyboard/xib to get more clarity.
Comment: done. also updated code so its cleaner and makes more sense
Answer: I assume your code is just a test for now.
Try to synchronize the userDefaults so they get written by the system:
defaults.set(text.text, forKey: "number")
defaults.synchronize()

...

Furthermore, defaults.string(forKey: ...) returns an optional because it may fail for several reasons.
if let num = defaults.string(forKey: "number") {
    lab.text = num
}

Comment: It works when I press save, because it must if it is displayed in the label. But when I swipe to flip it, and then attempt to swipe again to flip back to the label, it says its nil.


Exponential Family with Dispersion Parameter Distributions

Question: Defining the exponential dispersion family by
$exp\left(\frac{x_{i}\theta - b(\theta_{i})}{\phi} + c(x_{i}, \phi, w_{i})\right)$
I'd like to change the usual Inverse-Gaussian density below to the form above.
$\left( \frac{\lambda}{2\pi x^{3}} \right)^{1/2}exp\left( \frac{-\lambda(x-\mu)^{2}}{2\mu^{2}x} \right)$
My book (Fahrmeir & Tutz, Springer) says that
Canonical parameter ($\theta$): $\frac{1}{\mu^{2}}$
Dispersion parameter ($\phi$): $\lambda^{2}$
However my results are a little different from those presented by the author.
$exp\left( \frac{-x/\mu^{2}+2/\mu}{2/\lambda} -\frac{\lambda}{2x}+\frac{ln(\lambda)}{2} - \frac{ln(2\pi x^{3})}{2}\right)$
Canonical parameter ($\theta$): $-\frac{1}{\mu^{2}}$
Dispersion parameter ($\phi$): $2/\lambda$
Comment: I don't think the $\lambda/2x$ term is ancillary. Is it?
Comment: Hi @AdamO, What do you mean by ancillary?
As for my new findings, I found out that Fahrmeir uses another parametrization, one that he does not provide, would you know another common way to parametrize the IG distribution? It would help me.
Answer: \begin{align*}
\left(\frac{\lambda}{2\pi x^3}\right)^{\frac{1}{2}} \exp{\left(-\lambda \frac{(x-\mu)^2}{2\mu^2x}\right)} &= \exp{\left(\ln{\left(\frac{\lambda}{2\pi x^3}\right)^{\frac{1}{2}}}\right)} \exp{\left(-\lambda \frac{(x-\mu)^2}{2\mu^2x}\right)} \\
&= \exp{\left( -\lambda \frac{x^2-2x\mu +\mu^2}{2\,\mu^2x} - \frac{\ln{2\pi x^3}-\ln{\lambda}}{2} \right)}\\
&= \exp{\left( -\frac{\lambda x}{2\mu^2} + \frac{\lambda}{\mu} - \frac{\lambda}{2x} -  \frac{\ln{2\pi x^3}-\ln{\lambda}}{2} \right)}\\
&= \exp{\left( \frac{x(-1/\mu^2)+2/\mu}{2/\lambda} - \frac{\lambda}{2x} -  \frac{\ln{2\pi x^3}-\ln{\lambda}}{2} \right)}
\end{align*}
Thus canonical parameter : $-\frac{1}{\mu^2}$
Dispersion: $\frac{2}{\lambda}$
Comment: At the last step, is it not canonically $-1/(2\mu^2)$ and $1/\lambda$ instead?


Unit testing OverflowException : Maximum retries of 10000 reached without finding a unique value

Question: So I am working on some unit testing before I implement a new feature. I run my test and it fails with OverflowException : Maximum retries of 10000 reached without finding a unique value This is the test I'm running.
    public function test_job_factory()
    {
        $client = Client::factory()->create();
        $accountHandler = AccountHandler::factory()->create();
        $user = User::factory()->create();

        $this->post('/login', [
            'email' => $user->email,
            'password' => 'password',
        ]);

        $user->givePermissionTo( 'manage jobs' );
        $clientContact = ClientContact::factory()->create();
        $job = Job::factory()->create();

        $this->assertTrue($job->id > 0);
    }

The error seems to happen while creating the job itself. Tests above this test the other factories and are working.
Heres the JobFactory.php file:
<?php

namespace Database\Factories;

use App\Models\AccountHandler;
use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Job;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Job>
 */
class JobFactory extends Factory
{
    protected $model = Job::class;

    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            'title'              => $this->faker->company(),
            'is_active'          => 1,
            'is_draft'           => 0,
            'client_id'          => $this->faker->unique()->numberBetween(1, Client::count()),
            'account_handler_id' => $this->faker->unique()->numberBetween(1, AccountHandler::count()),
            'eclipse_contact_id' => $this->faker->unique()->numberBetween(1, User::count()),
            'client_contact_id'  => $this->faker->unique()->numberBetween(1, ClientContact::count()),
            'description'        => $this->faker->paragraphs(1),
        ];
    }
}

and the migration for this (create_jobs_table.php):
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('jobs', function (Blueprint $table) {
            $table->id('number');
            $table->boolean( 'is_active' )->default(true);
            $table->boolean( 'is_complete' )->default(true);
            $table->string('title', 64)->nullable();
            $table->timestamps();
            $table->foreignId('author')->nullable()->constrained()->references('id')->on('users');
            $table->text('description')->nullable();
            $table->foreignId('client_id')->nullable()->constrained()->references('id')->on('clients');
            $table->foreignId('client_contact_id')->nullable()->constrained()->references('id')->on('client_contacts');
            $table->foreignId('account_handler_id')->nullable()->constrained()->references('id')->on('account_handlers');
            $table->date('expiry_date')->nullable();
            $table->date('artwork_deadline')->nullable();
            $table->date('proof_deadline')->nullable();
            $table->integer('redirect')->nullable();
            $table->boolean( 'is_draft' )->default(true);
            $table->foreignId('eclipse_contact_id')->nullable()->constrained()->references('id')->on('users');
            $table->foreignId('subscription_id')->nullable()->constrained()->references('id')->on('subscriptions');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('jobs');
    }
};

So what is wrong and why this loop here? I have added the minimum data that is needed to create a job so no idea what I've missed.
thanks
*** EDIT ***
I was asked to give a link to where I found the bad practice of using unique and numberBetween here is an example Laravel factory error "Maximum retries of 10000 reached without finding a unique value" when I use unique Faker method this will not work as you expect!
Comment: What's the reason behind using `$this->faker->unique()->numberBetween(1, Client::count())` instead of just creating a new `Client` i.e. `Client::factory()`? The same question for the other relationships.
Comment: Why do you need `->unique()`? Also, instead of `numberBetween(1, N)`, why not `-> randomElement(Client::pluck('id'))`? That's _safer_ than relying on `1-to-count()` to represent available ids... (or using `Model::factory()` as suggested above)
Comment: Thanks guys. That has now got it!. Reason for the numberBetween is I'd looked on a few posts on here and that was one suggestion. In my scenario it made sense (I thought) as the id would always start at one. I do however see it as being a bad idea now. Say i created 2 clients and deleted one and then added a new one then count would be 2 but id's would be 1 and 3 and if instead removed the first client then id's would be 2 and 3. plenty of scope for the kind of errors which are hard to trace. using randomElement gets around that perfectly.
Comment: Please link those posts so that the answers can be marked as not helpful if appropriate.
Comment: updated question with reference example of bad practise
Answer: I will recommend to follow documentation approach for this problem.
https://laravel.com/docs/9.x/database-testing#factory-relationships
Looking at your migration table, there is a big chance that your factory will not work, since you indicating the relation on SQL level, which basically will force you to have records in related table, otherwise SQL will throw you with an error..
Comment: Oh thats interesting. I will try this way on my next tests. as up until now I've only been adding a single factory model, I have plenty of tests that do need multiple elements. As is always with the docs how on earth did I not see that section! I ended up using suggestion above by Tim Lewis to use $this->faker->randomElement(Model::pluck('id')) which allowed this test to pass.
Answer: The problem is that when you try and get 5 values between 1 and 5
(including) and you can only fetch 4. The 5th number will never pass the
unique() validation.
its because when you run the first instance of unique, for instance
$faker->unique()->numberBetween(1, 20)

then run it in another factory, laravel usually extends the previous instance(i guess), if that makes sense.
But when you pass true like below
$faker->unique(true)->numberBetween(1, 20)

it starts searching from 1 to 20 again
this solved the problem for me.
so always pass true in the unique() instace


How to calculate inner product between vector $xx^T$ and matrix $A^TA$?

Question: If $\langle A,B\rangle=\sum_{i=1}^n\sum_{j=1}^n a_{ij}b_{ij}$, how do I solve
$$\langle xx^T,A^TA\rangle$$?
Is there a shortcut for doing this? or should I expand each entry and do the inner product?
I got $\|Ax\|^2_2$, but wondering if there is any other ways to do it.
Comment: I changed $=\sum_{i=1}^n\sum_{j=1}^n a_{ij}b_{ij}$ to $\langle A,B\rangle=\sum_{i=1}^n\sum_{j=1}^n a_{ij}b_{ij}.$ That is standard and proper MathJax (and LaTeX) usage. $$\begin{align} \text{wrong: } & =\sum_{i=1}^n\sum_{j=1}^n a_{ij}b_{ij} \\ {} \\ \text{right: } & \langle A,B\rangle=\sum_{i=1}^n\sum_{j=1}^n a_{ij}b_{ij} \end{align}$$
Answer: You're not going to find a cleaner formula than $\|Ax\|_2^2.$
You can derive it in a coordinate-free manner by using the formula for Frobenius product in terms of trace:
$$A:B = \operatorname{tr}(A^TB).$$
So then
$$xx^T : A^TA = \operatorname{tr}(xx^TA^TA) = \operatorname{tr}(x^TA^TAx) = (Ax) : (Ax) = \|Ax\|^2_2$$
where the key second step uses invariance of trace under cyclic permutations.
Comment: Does it apply to inner product between two vectors, i.e., for $$, $xx^T : yy^T = tr(xx^Tyy^T) = tr(x^Tyy^Tx) =(y^Tx):(y^Tx) = (y^Tx)^2 $?
Comment: @JaydenRice Sure, that works.


Methods for improvisation practice (beginner)

Question: Suppose we start with an idea, a three note motive. We want to practice improvisation skills by playing this motive over the form. That is, all phrases must be constructed with specific relation of the motive.
What are most basic devices that can be used by beginner improvisers for motive development starting from most basic ones?
My take:

just play the motive while keeping the form, move motive notes in line chord root changes
play the motive while keeping the form but alter notes to match harmony using halfsteps
gradually start applying new rhythmic values for the motive. Keep rhythm for the whole form until mastered.
add second rythm, change every 4,2,1 bars depending on form and comfort

This form of practice intends to help systematically build basic time and form confidence by taking one step at a time. This is actually very boring and tiring method, but it sometimes necessary in my opinion to let beginner notice where are roots of his problems.
Apart from widely known Jamey Aebersolds HOW TO PLAY JAZZ & IMPROVISE series, what other resources are there that have exercises with similar approach?
Answer: I suggest you to follow a similar dynamic to what Gary Burton suggests in his Inroduction to Jazz Improvisation course:
https://www.coursera.org/course/improvisation
It's not for complete beginners, but you can follow a similar methodology from the very start.
Get familiar with scales and chords. Start simple. Add new chords and scales as you progress.
Start without chord progressions. Practice improvising over one chord, let's say C major triad. The most basic scales you can play over it are C major and C Lydian.

C major  = C D E F G A B

C Lydian = C D E F# G A B

Improvise using those notes over C major. You don't have to be too rigid, you can play other notes if you feel like it. Just use these as base so you get to know them and how they feel. If you feel like two modes is too much to start with, learn the major first, then the Lydian.
When you feel comfortable with the major triad and the major and Lydian modes, add new chord qualities and modes. What about C minor triad now? The minor and Dorian modes get well with minor quality, so improvise using C minor and C Dorian over it. Again, if you feel it's too much, practice the minor mode first, then the dorian.

C minor  = C D Eb F G Ab Bb

C Dorian = C D Eb F G A Bb

And just like that you are ready for your first progression. Now that you know how to play over major and minor triads, you can mix them up and play over them. Make up progressions of minor and major triads and see what you can play over them.
Your very first goal should be to know the 7 modes derived from the major mode, and which quality they are friendly with. For triads, it goes like this:
Modes for major triads: major, Lydian, Mixolydian.
Modes for minor triads: minor, Dorian, Phrygian.
Mode for diminished triads: Locrian.
The modes, in relation with the major mode, are:

Lydian:     1  2  3  4# 5  6  7

Major:      1  2  3  4  5  6  7

Mixolydian: 1  2  3  4  5  6  7b

Dorian:     1  2  3b 4  5  6  7b

Minor:      1  2  3b 4  5  6b 7b

Phrygian:   1  2b 3b 4  5  6b 7b

Locrian:    1  2b 3b 4  5b 6b 7b

Notice how as you go down, only one grade changes, this is a useful order to memorize them easily. Not only that, they are also ordered in relation of their chord friends! The first 3 for major triads, the next 3 for minor triads, and the last one for diminished triads.
For completion and reference, here is C in those modes:

C Lydian:     C  D  E  F# G  A  B

C major:      C  D  E  F  G  A  B

C Mixolydian: C  D  E  F  G  A  Bb

C Dorian:     C  D  Eb F  G  A  Bb

C minor:      C  D  Eb F  G  Ab Bb

C Phrygian:   C  Db Eb F  G  Ab Bb

C Locrian:    C  Db Eb F  Gb Ab Bb

Just add one modes to your repertoire at your own pace, as you feel comfortable.
You then want to learn how these modes interact with 7th chords, other scales (like pentatonic, blues, diminished scales, etc) and the modes derived from the melodic and harmonic minor, but that's beyond the scope of this question.
Comment: I followed this course briefly. To me, it is focused on learning to play correct notes on ten or so scales in many keys (by "rambling around") instead getting your timing, rhythm and phrasing first while playing simpler harmonies.
Comment: @Rumca That's why I'm not suggesting the course itself, but a similar methodology for your level. You can't get a simpler harmony than playing over one triad! Practice over one chord, then over different chord qualities (minor, diminished, and so on), aiming to eventually play over chord progressions. I understand that the course is not for complete beginners, that's why I built my post based on it, not quoting it.
Comment: @Rumca Phrasing, theme, variation (etc) are all based on these basic foundations.


Mediawiki - only a certain user group can read / access

Question: I'm setting up a wiki at the moment and I want it to be completely private and only be accessible for a specific user group.
My first step was:
$wgGroupPermissions['*']['read']    = false;

that way no one (but admins I guess) should be able to read any content of the Wiki.
After that I created some groups to allow read only, read edit and creating allowance etc.
Sadly I tried to register a new test account and I could still read the main wiki page even though I changed the permission that no one should be able to read it except the user groups I created.
Do I miss something?
Comment: How about just requiring users to log in to the server? Restricted access is [not really what MediaWiki was built for](https://www.mediawiki.org/wiki/Security_issues_with_authorization_extensions).
Comment: Did you manage this? I'd like to achieve the same thing.
Answer: You need to add $wgGroupPermissions['user']['read'] = false; as * still allows visitors in the users group to read.
Answer: That method specifically allows Users that have created accounts to view the wiki.  See this manual page: https://www.mediawiki.org/wiki/Manual:Preventing_access#Restrict_viewing_of_all_pages, it's the second Warning.  So you may want to also restrict account creation.


On whether or not $\sum na_n$ converges.

Question: If $a_n$ is absolutely convergent, then does $\sum na_n$ also converge? I have an objection with $a_n = \frac{(-1)^n}{n^2}$, where it is absolutely convergent, but $\sum na_n=\frac{(-1)^n}{n}$, which is conditionally convergent. Can I have another example that also has that property?
Another question naturally arises is whether given a random conditionally convergent sum, $\sum a_n$, then is $\sum (-1)^n a_n$absolutely convergent? I feel that this is a yes. Different opinions?
Comment: I think the phrasing "Different opinions?" is quite... unfortunate. There is no "opinion" to have here.
Comment: @ClementC. lol yeah there are no opinions in math
Answer:
No. Take $a_n = \frac{1}{n^2}$ for all $n\geq 1$. $\sum_{n=1}^\infty a_n < \infty$ (absolute convergence, since all terms are positive), but $$\sum_{n=1}^\infty na_n = \sum_{n=1}^\infty\frac{1}{n} = \infty$$

For your second question, also no. Take $a_n = \frac{(-1)^n}{n}$. Then $\sum_{n=1}^\infty a_n$ is conditionally convergent; but $$\sum_{n=1}^\infty (-1)^n a_n = \sum_{n=1}^\infty\frac{1}{n} = \infty$$

For your second question, even more generally, what you are asking is exactly

If $\sum_n a_n$ is conditionally convergent, then is it also absolutely convergent?

which is clearly false. Why is it equivalent to your question? Well, because $|(-1)^n a_n|=|a_n|$, so $\sum_n (-1)^n a_n$ is absolutely convergent iff $\sum_n a_n$ is.


Is this a valid proof for the divergence of $E\left( \frac{1}{\bar{X}} \right)$ for a Normal distribution?

Question: I have come across this proof and I was wondering if it is valid. What troubles me is the inequality $e^{-\frac{n}{2} \theta^2} > \frac{1}{2}$ as it's not obvious to me how one gets there. I know that $e^{-x} \geq 1-x$ but other than that I am stuck.

All help would be greatly appreciated, thank you.
Comment: $E(\frac 1 X)$ diverges for any $X$ that has positive density at in the neighborhood of $0$.
Comment: For each $n$ you need a different $ε$, otherwise I does not seem to work. In other words $ε$ is $ε(n)$.
Comment: @JimmyR. I believe $n$ is kept fixed so this is not a problem.
Answer: Hint: What is $$\lim\limits_{\theta \to 0} e^{-\frac{n}{2}\theta^2}?$$
What does this tell us about when $\theta$ is sufficiently small?
Comment: @JohnK By definition, this means that if I choose $\epsilon$ small enough, then for all  $|\theta| < \epsilon, |e^{-(n/2)\theta^2} - 1| < 1/2$ i.e. $e^{-(n/2)\theta^2 } > 1/2$.
Comment: It tells us that this will be very close to $1$ but where does the $1/2$ come from?
Comment: That's great, thank you.
Answer: So, since $e^{-x}\ge 1-x$ (as you pointed), for fixed $n$ and $0<θ<ε$ you know that $$e^{-\frac{n}{2}θ^2}>e^{-\frac{n}{2}ε^2}\ge 1-\frac{n}{2}ε^2$$ where the first inequality is due to the monotonicity of the exponential function. So, if you could show that $1-\frac{n}{2}ε^2\ge \frac12$ the proof would be valid. You have that $$1-\frac{n}{2}ε^2\overset{?}\ge \frac12 \iff nε^2\overset{?}\le 1$$ but since $n$ is fixed and $0<ε$ is arbitrarily small (or "sufficiently small" as the author of the proof indicates) then this holds for any $ε\le \frac{1}{\sqrt{n}}$.
Comment: Usually a downvote comes with an explanation of the mistake, so I (and perhaps also the OP) am waiting.
Comment: Oh I see it now. The $1/2$ is arbitrary, we could have chosen $1/3$ or anything else.
Comment: @JohnK Yes, exactly. I guess he only chooses $1/2$ for simplicity in his proof.


Should I enable KeepAlive on Apache backend with Varnish as frontend?

Question: I'm using Varnish as a frontend with Apache 2 as backend on my web server. What are the pros and cons of Apache's KeepAlive in this setting?
Apache and Varnish run on the same server now, but I could put them on different servers in the future.
Answer: Pro:

TCP handshake between Varnish and Apache not needed for every single request, reducing overhead.

Con:

If your Varnish service wanted to DoS your Apache service with connection exhaustion, it's easier for it to do so..?

Can you clarify what's prompting this question?  HTTP connection keep-alive is implied in HTTP 1.1 and on by default in every major web server for a good reason; it's a performance improvement (though it will be a very small one with no latency between services), with a couple of denial-of-service-related caveats that aren't applicable when Apache's only client is Varnish.
I'd even recommend increasing Apache's KeepAliveTimeout higher than the default of 5 seconds, to let Varnish continue to re-use the same pool of connections.
Comment: That document is incredibly misleading and outdated, and should be stricken from the internet. It's assuming that the only limiting factor for "performance" is the number of spare available worker threads - which is rarely the case, and especially won't be the case when the only client is the Varnish server.  They're also making that recommendation on the assumption that a given client will only be making one request at a time to the mod_perl server.  And ignore the part about a client only using one connection, and taking longer because of it; that hasn't been the case for years.
Comment: When using Apache as a regular frontend server, it is sometimes recommended to disable KeepAlive: "If your mod_perl server's httpd.conf includes the following directives: ... KeepAlive On ... you have a real performance penalty, since after completing the processing for each request, the process will wait for KeepAliveTimeout seconds before closing the connection and will therefore not be serving other requests during this time. With this configuration you will need many more concurrent processes on a server with high traffic." http://perl.apache.org/docs/1.0/guide/performance.html#KeepAlive


dynamically choose filters/fields in an aggregation table on a View

Question: I need users to customize which kind of aggregation to apply to a table (view).
Example: let´s choose counts of species X and Y in an area. This means apply two filters.
          I also want to give the option to choose fields 'species', 'area' and 'place'. The table resulting of applying these 3 filters would give a completely different table than before.
Insert all the (3) filters into the same view creates allways the same result. I don't think there is some way of let user choose 'disabling' one of the filters.
Should I create two different views (each one with its corresponding filters) inserted into a panel or there is some better way to solve that?
To make more clear, here are two screenshots:
1) Without 'Place' field (and filter): for especie Cuniculus paca, number of counts is 60.

2) With'Place' field: as for each especie we have different places names, the results are completely different.

In fact I think the question should not be exclusively about filters but also about Views.
There is a chance to avoid a Field to be 'executed' (applied to the resulting View) allways? 'Exclude from Display' with Aggregation options YES doesn't do any effect, the results are grouped by this new field also, changing completely all the results.
Answer: You can expose the filters (and for markup and additional functionality, there is a nice module Better exposed filters). You can find it when adding a filter "Expose this filter to visitors, allow tthem to change it", under the advanced sction on the right (by default collapsed) you can group them into a block and then add them to your site whereever you need them.
Hope I understood the question the right way.


iOS UIWebView Event when opening new window

Question:
I try to create an iOS application that display a webview but the website I want to display open sometime a new window. ( window.open ) I had no problem on other device to add a listener and do something when the application is trying to open a new window but on iOS I have no idea how to create this type of listener.
Is there a way to add a listener and do something when the app try to open a new window ?
For the moment, when I click on a link with a window.open, the app open a new webview on top and there is no way to go back to the old view.
- (BOOL)webView:(UIApplication*)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *url = request.URL.absoluteString;
    if (navigationType == UIWebViewNavigationTypeLinkClicked && [url rangeOfString:@"........].location==NSNotFound){
        [[UIApplication sharedApplication] openURL:[request URL]];
        NSLog(@"opening link on default browser");
        return NO;
    }
    return YES;
}

- (void) webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"webViewDidFinishLoad\n");
}

Answer: What you should do is determine whether the URL will be opened externally or not.
You can do this using the following:
- (BOOL)isExternal:(NSURL*)url {
    BOOL isExternal = NO;
    if (![url.scheme isEqual:@"http"] && ![url.scheme isEqual:@"https"]) {
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            isExternal = YES;
        }
    }
    return isExternal;
}

Then from the UIWebViewDelegate, use this method to decide wether or not to allow loading of the URL:
-(BOOL)webView:(UIApplication*)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    BOOL allowToLoad = ([self isExternal:request.URL] == NO);
    return allowToLoad;
}

Comment: Thank you for your answer. I tried this on my code and it seems not to work. My application still open a new window for some links and isExternal return 1. The url.scheme is a https
Answer: Please, see UIWebViewDelegate and its method webView:shouldStartLoadWithRequest:navigationType: and webViewDidFinishLoad:.
Comment: have you tried this : http://longweekendmobile.com/2010/09/14/making-target-_blank-links-work-in-a-uiwebview/ ?
Comment: Yes that is what i have done. But I don't know how to add a delegate to check if the application will open a new window
Comment: Actually I think it is not the same problem. I made a mistake in my explanation. I thought it was a target blank but it is a javascript code window.open


How can I re-install a module?

Question: I am creating on Drupal 8 module. I have used a custom table to store the data collected from forms.
Somehow during installation, tables are not created due to an issue in the install file. Now I have fixed the issue, and I want to install the module again.
How can I re-install a module?
From this and this discussions, I know the Disable module functionality has been removed.
Is there any other way to re-install a module so that its database tables are created?
Answer: The Devel module can also help here.
It makes a "Reinstall modules" page available at /devel/reinstall, which lets you re-install modules in bulk.
It's also worth mentioning Drush; dis (obviously) doesn't work any more, but pm-uninstall and en still do. And if you have Devel installed, you can invoke a reinstall with
drush dre module1 module2

Comment: I've started an issue to fix that https://www.drupal.org/node/2292425
Comment: Note that devel doesn't yet support Drupal 8's uninstall-only changes http://cgit.drupalcode.org/devel/tree/drush/devel.drush.inc#n115
Comment: I think all the answers posted here are incorrect. The original question is how to "re-install". This is not the same as how to uninstall and then install. All the scenarios here, sadly, do an uninstall which is a major step backwards for D8 as this will wipe the configuration for that module. I'm still looking for the correct answer of how to "re-load" the install config for a module (without uninstall).
Answer: As you said "Disable functionality is removed from Drupal 8" ..
The short answer is - you probably are looking for the "Uninstall" tab found on the "Extend" (Modules) page /admin/modules/uninstall
There is no longer any grey area between a module being on and active vs off and "purged". "Disabled" is no longer a thing. Uninstalling a module means removing all traces of it.
Go to admin/modules/uninstall and uninstall module... Then enabled the module from modules list page. That should install the module again.
For Example ....
Before Installing Ban Module in Drupal 8 ... ban_ip module doesn't exist in database..

After Installing Ban Module in Drupal 8... ban_ip table is created and module cannot be disabled but can be uninstalled in admin/modules/uninstall

Now if you uninstall module.. Table will be removed from database and module can be installed again which will create tables in the database..
Comment: Thanks a lot for such awesome explanation. I checked the list of modules in *uninstall* tab, but couldn't found my module. If you want to check code here https://github.com/mohit-rocks/messaging . Currently you can install module and settings related forms are coming.
Answer: Solution 1: Uninstall and Install again manually
Using the Drupal UI:

Go to the Extend page from the admin menu
Go to the uninstall module page
Uninstall the module you wish to
Go to the Extend page again (where you have a list of modules)
Install the module you just uninstalled

Using Drush (you should try it if you don't use it):

drush pm-uninstall MODULE -y && drush pm-enable MODULE -y
OR in short drush pmu MODULE -y && drush en MODULE -y

Replace MODULE with the name of your module.
Solution 2: Reinstall using Devel module
Assuming you have the devel module installed.
Using Drupal UI:

Visit the path /devel/reinstall
Re-install the modules you wish to

Using Drush:

drush devel-reinstall MODULE -y
OR in short drush dre MODULE -y

Replace MODULE with the name of your module.
Answer: If you want to re-install (reload) the install config for a specific module you can use this drush command:
drush cim --partial --source=modules/custom/MY_MODULE/config/install

Comment: This got me excited but it doesn't work for me, I keep getting errors about the source dir not existing.
Comment: What is the your source dir? And i guess it would require that the module has a config/install dir. If it doesn't; then likely there is nothing to re-install for that module.
Comment: I tried relative and absolute paths to the dir, on my local machine and my VM. Module has config dir with yml files. Ended up using drupal console and config:import:single. Thanks
Answer: If nothing else works you can try the below for Drupal 8.

Remove the problematic module files and it's folder

rm -rf modules/your_problematic_module

Remove the cached twig templates

rm -rf sites/default/files/php

Clear the Drupal cache

NOTE: Make sure to backup the code and Database before doing this

How can I re-install a module?


Do un-earned runs affect win, loss for pitchers

Question: Here is the scenario. A pitcher leaves the game after 7 innings with a 4-4 tie, but only 3 of the runs against were earned. The relief pitcher completes the game for a 6-4 win. Who gets the win?
Answer: Unearned runs have nothing to do with wins and losses.
The answer to your question depends on when the 5th run was scored.
If the pitcher finishes the 7th inning, and his team scores a run before the relief pitcher enters the game, he gets the win.
If the relief pitcher enters the game before the 5th run is scored, the relief pitcher gets the win.  This is the case regadless of how the relief pitcher enters the game.  It might be by starting the 8th inning, pinch-hitting in the 7th, or even through a double-switch.
It's all about the "pitcher of record" when the last lead-change takes place.

The win is given to the "pitcher of record" when the winning team takes the lead for the last time.
As wax eagle has pointed out, a starting pitcher cannot get a win unless he pitches 5 complete innings.
Interesting example:

Pitcher A enters the game in the top of the 7th inning with his team winning by 3
Pitcher A gives up 5 earned runs, but completes the 7th inning (he blows the lead)
Pitcher A's team scores 4 runs in the bottom of the 7th inning (his team makes a comeback)
Pitcher B relieves pitcher A by entering the game to start the 8th inning (Pitcher A is done)
Pitcher A's team holds the lead and wins the game
Pitcher A gets the win after pitching less than 1 inning and blowing a 3 run lead
Answer: Wins and losses are based on the score, not on whether or not the runs are earned or not. If the pitcher's team loses the game they cannot get a win, even if they gave up fewer earned runs than their team scored.
The pitcher at the time the winning team gains a lead they keep through the rest of the game is the winning pitcher. There is only one exception to this rule. If the starting pitchers does not pitch 5 innings and his team gets the lead while he is still in the game the official scorer is to award the win to the "most effective pitcher for the winning team"
Answer: The fact that a run is "unearned" does not affect win-loss tallies. In this context, "a a run is a run is a run."
If he leaves at the end of an inning, the starting pitcher is the "pitcher of record" in the half inning after he leaves, when his team is batting. If his team scored the fifth run during this half inning, he gets the win; otherwise the relief pitcher does.
What the fact that the runs are "unearned" do affect, is the pitcher's earned run average (ERA). Such runs do NOT counted toward his ERA.
So a pitcher could give up, say, one unearned run, lose the game 1-0, and have a 0.00 ERA for the game.


Copiar TAG específica de arquivo XML e mesclar com outro arquivo XML

Question: Situação:
- Preciso de um único arquivo XML que contenha os dados de todos os outros arquivos existentes e os que estão por vir. Mas não posso simplesmente juntar um arquivo com o outro sendo que preciso de apenas uma tag específica.
Existe algum jeito de fazer isso em C# ou em Java?
Help
Comment: Sim, é possível tanto em Java quanto em C#. Só não é possível conter os dados dos arquivos que ainda estão por vir... Apresente o código de como você está tentando realizar essa mesclagem.
Answer: Consegui fazer de forma simples usando XPathNavigator no C#. Neste caso estou colocando a nf junto com um arquivo notasGeral.xml onde fica todas as notas fiscais.
<code>private void button2_Click(object sender, EventArgs e)
        {
            XmlDocument document = new XmlDocument();
            document.Load("nf1.xml");
            XPathNavigator navigator = document.CreateNavigator();
            navigator.MoveToChild("nfeProc", "http://www.portalfiscal.inf.br/nfe");

            XPathDocument newBooks = new XPathDocument("C:\\Program Files\\VertrigoServ\\www\\Prototipo\\notasGeral.xml");
            XPathNavigator newBooksNavigator = newBooks.CreateNavigator();
            newBooksNavigator.MoveToChild("nfeProc", "");

            foreach (XPathNavigator nav in newBooksNavigator.SelectDescendants("NFe", "http://www.portalfiscal.inf.br/nfe", false))
            {
                navigator.AppendChild(nav);
            }

            document.Save("C:\\Program Files\\VertrigoServ\\www\\Prototipo\\notasGeral.xml");
            label1.Text = ("Concluído!");
            textBox1.Clear();
        }
</code>


Argument of #selector cannot refer to a property

Question: The goal is to update the below condition to Swift 2.2 syntax, which advises using #selector or explicitly constructing a Selector.
if activityViewController.respondsToSelector("popoverPresentationController") {

}

However, using the below as a replacement fails and generates an error saying Argument of #selector cannot refer to a property
if activityViewController.respondsToSelector(#selector(popoverPresentationController)) {

}

What's the right way to implement this check with #selector?
Comment: popOverPresentationController is a property not a func. Right?
Answer: You can use the following:
if activityViewController.respondsToSelector(Selector("popoverPresentationController")) {

}

Or if you target iOS only
if #available(iOS 8.0, *) {
    // You can use the property like this
    activityViewController.popoverPresentationController?.sourceView = sourceView
} else {

}

Or if your code is not limited to iOS
#if os(iOS)
    if #available(iOS 8.0, *) {
        activityViewController.popoverPresentationController?.sourceView = sourceView
    } else {

    }
#endif


Distance between a point on the edge of a circle to a point on a equilateral triangle

Question: Equilateral triangle $ABC$ has side length 6. Let $D$ be the point on segment $BC$ such that $BD=4$. The circle passing through points $A, B, C$ intersects line $AD$ at $A$ and at another point $E$. The length of $DE$ can be expressed in simplest radical form as $\frac{A\sqrt B}C$, where $A$, $B$ and $C$ are positive integers. What is $A+B+C$?
I keep on getting $15$, but the answer key says the answer is $18$.

I don't know if the link to the image will work, but what I have tried so far is $R-r$ $\left(\frac{6\sqrt3}3-\frac{6\sqrt3}6\right)$. However, I realize that $R$ is calculated assuming that you are going from the center of the circle inscribed in the equilateral triangle to a point on the outside circle, and in this problem the line going through points $AD$ doesn't go through the middle of an inscribed circle. My question is what other methods should I try to find the length of $DE$ where the answer can be expressed in terms of $\frac{A\sqrt B}C$.
Comment: Welcome to MSE. It would be helpful if you could show your efforts so far - this would make it easier for answerers to point out any errors that might have happened or confirm your solution. Please do this by making an [edit] to your post.
Answer: Applying Stewart's Theorem in $\triangle ABC$:
$$AD^2=6^2-4\cdot2=28 \implies AD=2\sqrt{7}$$
Considering the power of a point at $D$:
$$4\cdot2=2\sqrt{7}\cdot DE \implies DE=\frac{4\sqrt{7}}{7}$$


Offline logout with JWT auth on mobile

Question: Does anyone have a particular technique for offline logout on a mobile application that has a jwt token based authentication ? Or do you have any advice ?
Comment: Can't you simply discard the token?
Comment: @Paulw11by "discard" you mean deleting it from the device ? Because the backend doesn't know when a user goes offline.
Comment: But the device is offline, so it can't tell the backend anything. Normally the client side just discards the token, so that next time it tries to access the backend (when it is back online) the user is required to authenticate as the client doesn't have a valid token.  Being "logged in" and being "online" are different things. If the backend needs to know if a user is online then you need some sort of persistent connection.
Comment: Yes i got your point. Discarding the token on the device seems to be right thing to do. But if the app supports push notifications, the backend will keep sending push notification to that logged out user. I think it can require a bit more logic from there.
Comment: So that is a slightly different question. It helps us if you put all of the details in your question to start with. If the device is offline then it isn't going to receive notifications until it comes back online. You could send silent notifications that your app turns into local notifications. Include the target userid in the notification so that the client can ignore it if the user has logged out/changed.
Comment: Yes. Thats what i call "a bit more logic". Thank you for answer. Very Helpful I found this post that tries to solve the problem. https://android.jlelse.eu/solving-offline-logout-problem-f3b50da49e7e
Answer: Found a pretty good solution following  this post. And combined to what @Paulw11 said you must be able to solve this.

Offline logout with JWT auth on mobile


Image upload broken when editing content

Question: Sorry if I'm using incorrect terms here. What's going on is, when I edit any content, as the the types of content under 'Content Management > Content Type', there's the Image: field, which I think is provided by the CCK Imagefield module or Imagecache. (I'm on 6.x-3.10 of Imagefield)
When I choose a file and click upload, I get a thumbnail image (http:/mysite.com/sites/mysite.com/files/imagefield_thumbs/image.jpg?1357151034). When I click 'Preview', I get a preview with the image I uploaded (http://mysite.com/sites/mysite.com/files/imagecache/product/image.jpg). When I save, the image is gone, and going back to the edit form, it doesn't show up as an attached image. One possible clue; this content type isn't 'product', but it's in sites/mysite.com/files/imagecache/product/.
This all worked until a couple of weeks ago, when I updated a bunch of modules. I did a whole site backup before I ran the updates, and a development version of the site on my local computer doesn't have this problem on up to date modules. The only way I can replicate it on my local machine is to use a backup of the database from after this error occurred.
Comment: Are there any File System errors on the Status Report page (admin/reports/status)? What about on the File System Page (admin/settings/file-system)? My guess is that the File System Path is not writeable by the web user, but the Temporary Directory is - and that's why the preview and initial thumbnail work.
Answer: Make sure the file directory exists at sites/default/files and make sure it is writeable by the web server. For this you need to go to the file directory if you are familiar with terminal and type chmod -R 775 files when in the directory that contains the file directory. otherwise in an FTP client like Filezilla right click the file and click file permissions and change the permissions there.  You may also need to check that this folder files/imagecache/product exists and is writeable.


Batch Script to get latest folder

Question: I have to determine the latest release version from a release location containing release artifacts. Here is how the folder looks like:-
1.4
1.4.1
1.5
1.5.1
1.5.2
latest

In the above example my script should return 1.5.2. The release engineer creates a folder called latest and puts the latest release artifacts (1.5.2's contents  in the above case) inside it - so I have a easy way to copy the latest release. But my problem is I want to print the version as well. here's my attempt:-
@echo off

SET Remote="\\path to release location"
SET newest=""

for /f %%a in ('dir %Remote% /b /od') do (if NOT %%a=="latest" SET newest=%%a)

echo %newest%

This works fine with the above example. But the release engineer sometimes creates a tmp or some other folder there (basically he forgets to clean up) and that screws up my naive assumption of filtering out just "latest". Is there a easy way to sort the folders that start with a number declare the newest release version.
Also pls suggest if there are any better idea of solving this
Comment: Pipe the output of the dir command to FINDSTR and give it a regular expression to find just directory names with numbers. Something like this for the findstr: `findstr /r "^[0-9][0-9]*\.[0-9][0-9]*"`
Comment: Just ask the release engineer to place a marker with the release version in the `latest` directory too!
Comment: Thanks @Squashman - Here's what I came up with: `for /f %%a in ('dir %cd% /b /od  ^| findstr /r "^[0-9][0-9]*\.[0-9][0-9]*"') do (SET newest=%%a)`
@Compo: Thanks for your tip !
Answer: Posting the solution here as per @Squashman's suggestion:-
@echo off

SET Remote="//Path to release loc"
SET newest=not set

for /f %%a in ('dir %Remote% /b /on  ^| findstr /r "^[0-9][0-9]*\.[0-9][0-9]*"') do (SET newest=%%a)

echo %newest%

Note:- The sort order /od vs /on is something I have to work with the release engineer to agree upon to protect against situations like: patching an older release does not over-write the latest release
Thanks everyone!!
Comment: I know this is a repeated comment but the easiest method involves the engineer, who you're collaborating with, including a file. The file could either have a known size or extension with the release as it's name or a have a known name with the release as it's single line content.
Comment: Why not break up the directory name into variables and test which one is the newest with some if statements?
Answer: This does not rely on the newest modified date actually being the greatest release number.
@echo off
setlocal enabledelayedexpansion
set newest=000000000
PUSHD \\servername\share\directory
for /f "delims=" %%G in ('dir /b /ad ^| findstr /r "^[0-9][0-9]*\.[0-9][0-9]*"') do (
    FOR /F "tokens=1-3 delims=." %%H IN ("%%~G") DO (
        SET "node1=000%%H"
        SET "node1=!node1:~-3!"
        SET "node2=000%%I"
        SET "node2=!node2:~-3!"
        SET "node3=000%%J"
        SET "node3=!node3:~-3!"
        IF 1!node1!!node2!!node3! GTR 1!newest! (
            set newest=!node1!!node2!!node3!
            set newrelease=%%G
        )
    )
)
echo %newrelease%
POPD
pause

Comment: Thanks for the ans - wondering where exactly will the results be different vs the  `dir /on` option
Comment: @Zakir, make three directories from the cmd prompt. Name them 1.1, 11.1 and 2.1.  Then use your DIR command.  Do you think 11.1 will be last using `DIR /ON`?

Batch Script to get latest folder


Does the subdominant prepare the dominant : a general rule?

Question: Can we say that iv prepares the V in a minor key? Because iv is a subdominant chord and V is the dominant?
Comment: You're getting a few different answers because people are interpreting your question differently. Can you explain a little more by what do you mean by  "does the subdominant prepare the dominant"? e.g. are you asking if people generally expect V after hearing iv? or if V is acceptable after iv? Or if *only* iv is likely to come before V? These are all different questions with different answers...
Answer: Your question is a little bit unclear, but yes: generally speaking, the subdominant chord (IV or iv) prepares the dominant (V).
(In the answer below, the Roman numerals should be understood in both major or minor. When I say IV, I mean IV in major or iv in minor. The only exception is V, which must be major [V, not v] to create dominant function.)
To generalize this a bit more, we say that the IV chord has "predominant" function. This is exactly what it sounds like: by "predominant," we're literally saying it comes before ("pre") the dominant.
The ii chord also has very clear predominant function. Less often, the vi can function as predominant, and in rare cases so can the iii chord.
Lastly, the IV chord doesn't have to be a predominant. It can resolve back to tonic, and in popular music, it's very common for it to come after the dominant!
Comment: Did you mean iv rather than IV, given OP is in minor? (in answer, not comment). And is iii meant to be III, since i is minor?
Comment: So is it like, if you have C -  G - Am - F, the G comes too soon? "What a surprise - I wasn't _prepared_ for this!" ;)
Comment: Interesting almost opposite view! How does your answer cope with plagal cadences?!  I thought it was called 'predominant because it was the one before the dominant.
Comment: The opposite answers may be because we made different assumptions about the question. And as for plagal cadences, see my last paragraph, where I mention it can resolve back to tonic.
Comment: sorry I was meaning iv prepares V and not iv prepares v
Comment: so if I have a chord progression i - iv - V in Dm,  I can say that iv prepares V ?
Comment: @Dicordi Yep! The iv here would be a predominant, which prepares the dominant V.
Comment: I'm unclear as to whether you're saying 'subdominant' is similar/the same as pre-dominant.
Comment: @Tim "Subdominant" is specifically the IV or iv chord ("subdominant" meaning a dominant, or fifth, below tonic). That chord is often a predominant, but it's not the only predominant chord. So the subdominant can be a predominant, but it doesn't have to be. And "predominant" can mean the subdominant, but it's not necessarily the same.
Answer: I would say that it's a bit the other around. At least classical or more accurately CPP composers tend to establish three main harmonic areas. The "tonic" is the harmonic area of rest or finality or even beginning. The "dominant" harmonic area tends to signal the approach of the tonic area (though event may be evaded for artistic reasons.) The "predominant" harmonic area tends to suggest harmonic movement towards dominant harmony. The boundaries between these areas are not necessarily sharp. A 4-bar phrase with the chords I-I-ii6-V has clearly marked boundaries. However even something like I-vi-ii6-V the vi chord can be seen as an extension of the tonic or the beginning of the predominant area (or as I think of it, a "passing" chord.) In I-ii6-I64-V7-I. I I64 can be considered a predominant harmony leading smoothly to V7 (especially in concertos where everyone pauses on the I64 and the soloist plays a bunch of showy stuff) or just a decoration to the V7.
In cases like I-IV6-I6 or I6-IV6-I, the IV6 really is a passing chord (or neighbor chord, it has no "function" as in functional analysis.) Similarly  in the Folia progression, i-V-i-VII-III-VII-i-V-i the first i-V-i isn't a cadence (or rarely; one could lengthen the time of the second i, i-V-i-i, and make the V-i into a cadence.) The final V-i is often treated cadentialy even appearing as i-V-i-VII-III-i-V-I.
Music is generally recursive in that one could (somewhat like Schenker or the generative music guys) take a pattern like I-V-I expand each part. One can always repeat a chord or insert that chord's dominant chord (like I-V-I becomming I-I-V/V-V-I) where V/V is the "analysis name" for II. In the "large" one can insert a ii-V belonging to a chord before  the chord. Expanding this pattern usually leads to a predominant pattern followed by a dominant leading to the tonic (at a higher level, this may only be a phrase). Any I digress and risk turning the idea of harmonic regions into a durchkomperniert ramble (perhaps I should uses Omani musical patterns and create a Muscat Ramble).
Comment: +1 for the 'Muscat Ramble'. It all could have been less confusing had theorists used the term 'ante dominant' back in the day.
Answer: In the major/minor system chord I, IV, and V are the primary chords. (In minor you can generally use symbols i, iv, V.) These are the primary chords. In very loose terms you can play these chords in any order and produce a clear sense of tonality. IV is one of the tonal pillars.
In functional harmony there is a sort of norm for harmonic flow moving pre-dominant to dominant to tonic. Roughly speaking that would be ? V I where ? is any chord not a dominant or tonic. Lots of chords can fill that pre-dominant role and IV is one of the most common.
However, that doesn't mean that IV always goes to V or that V must be preceded by a pre-dominant. Pre-dominant to dominant to tonic is just a norm, not the only option.
One way that IV is found in a different functional role is in prolongation of some chord. I IV I is a tonic prolongation and V IV V just prolongs the dominant.

does the subdominant prepare the dominant : a general rule?

Not as an exclusive rule.
It is one of the most common roles of IV, but not the only role.
Answer: First thing - if we're talking in terms of functional harmony, dominants, subdominants and tonics, it's likely to be V (major) not v (minor) even in a minor key.
(OK, I see you've edited that in your question.)
Yes, iv fits nicely before V.    We can explain this by noticing that iv is closely related to ii7.  And ii7, V, i is a standard 'cycle of 5ths' progression.
Let's shift over to an actual instance.  I'm not sure SE can cope with the symbols I need to make this clear usind functional chord names.
In D minor I'm talking about Em7♭5 going to A7 going to Dm.   Em7♭5 is E, G, B♭, G.  The root notes E, A, D are 'cycle of 5ths'.   Gm - that's G, B♭, D contains most of the notes of Em7♭5 and therefore can do the same job.
Answer: 'v is the dominant'. Not necessarily. V can be and is more often the dominant.
But that's not the point. It's called subdominant because it's under the dominant. It has no particular role with relation to the dominant. Sometimes it precedes the dominant, sometimes it doesn't, and other chords do instead.
So, basically, no. In fact, if the 'dominant' is v, it's considerably weaker than if it was V, and as such, probably has no more role to play than iv itself.
Chords that do precede the dominant are likely to be iii, V/V or i itself.
Comment: @MichaelCurtis - so, after  a subdominant, we expect a dominant to follow? It may - or it may not. There is no compunction for that to happen, and it doesn't in so many pieces. It may commonly happen - so what? That doesn't put it as the harbinger. Even in the common 12 bar blues I follows IV, and towards the end, it's V, IV, I V. so like I say, IV does not mean V will follow.
Comment: this is so wrong, IV very commonly precedes V, https://www.semanticscholar.org/paper/A-corpus-analysis-of-rock-harmony-Clercq-Temperley/5db8f90ab0d15bb2d1d5acc9d5c494df337f3a6f and http://davidtemperley.com/kp-stats/ provide nice corpus studies of _both_ rock and classical styles
Comment: sorry I meant iv prepares V and not iv prepares v
Comment: IV is one of the most common chord to precede a V, your answer is worded to suggest that is not the case. It's very misleading. the role of IV as a _common_ pre-dominant in no way precludes other things from happening. When IV - or another non-tonic chord - precedes V functional harmony will call it a _pre-dominant_, the OP uses the descrption "prepare the dominant." Not the common terminology, but Richard clarified that in his answer.


Dynamic input text (ngModel) and variables for Angular. Lagging input?

Question: I'm trying to add multiple input text fields for a description that is being assigned to an array, but I'm having trouble using ngModel here. In the code below, when typing into the textbox it loses focus and I can only type one character at a time -- almost like its lagging. It seems to work when outputting the array to the console, however, when I add another text field element instead of the third element being blank it will return the previous value.
component.html

          Description #{{ i + 1 }}
          <textarea class="form-control text-wrap" placeholder="Posts will use this description." [(ngModel)]="descriptionPool[i]" name="somename"></textarea>
          <button class="btn btn-primary text-light" (click)="addDescriptionField(descriptionPool[i])"> + </button>
          <button class="btn btn-primary text-light" (click)="delDescriptionField(i)"></button>

component.ts
descriptionPool: Array<string> = [];

ngOnInit(): void {

      this.descriptionPool.push('');

  }

addDescriptionField(description: string) {
    console.log('descriptions? ' + JSON.stringify(this.descriptionPool));
    this.descriptionPool.push(description);
  }

  delDescriptionField(index: any) {
    this.descriptionPool.splice(index, 1);
    console.log('after deleting: ' + JSON.stringify(this.descriptionPool));
  }

The delete function works as expected. :)
Comment: problem seems to be in ngmodel
Answer: When you input some text the angular ngOnChange listener will run, so the ngFor indexes will rerendered and the focus will be lost. For avoid this issue a trackFn can be added to the ngFor. See https://angular.io/api/core/TrackByFunction for more details on the topic. Below the code solution for your issue:
In you html code define the ngFor a trackFn function that will be corrispond to the trackByFn function declared in the .ts file.

      Description #{{ i + 1 }}
      <textarea class="form-control text-wrap" placeholder="Posts will use this description." [(ngModel)]="descriptionPool[i]" name="somename"></textarea>
      <button class="btn btn-primary text-light" (click)="addDescriptionField(descriptionPool[i])"> + </button>
      <button class="btn btn-primary text-light" (click)="delDescriptionField(i)"></button>

And in the ts file declare the abowe mentioned trackByFn function:
trackByFn(i: number, items: any) {
return i //returning the index itself for avoiding ngFor to change focus after ngModelChange
}