Find the value of $a$ by evaluating the limit $L=\lim_{n\to\infty}\frac{1^a+2^a+\cdots+n^a}{(n+1)^{a-1}[(na+1)+(na+2)+\cdots+(na+n)]}=\frac{1}{60}$

Question:
For $a\in\mathbb R-\{-1\}$
  $$L=\lim_{n\to\infty}\frac{1^a+2^a+\cdots+n^a}{(n+1)^{a-1}[(na+1)+(na+2)+\cdots+(na+n)]}=\frac{1}{60}$$
  find the value of $a$.

My attempt:
$$L=\frac{(1/n)^a+(2/n)^a+\cdots+(n/n)^a}{(\frac{n+1}{n})^{a-1}[a+1/n+a+2/n+\cdots+a+n/n]}$$
which as $\lim_{n\to\infty}$ must equal to $\frac{1}{a+a+a+\cdots}$. Now this obviously can't be implying some logical error on my part. What to do now?
Answer: We have
\begin{align}
\frac1{60} &=\lim_{n\to\infty}\frac{1^a+2^a+\cdots+n^a}{(n+1)^{a-1}[(na+1)+(na+2)+\cdots+(na+n)]}\\
&= \lim_{n\to\infty}\frac{\frac1n\sum_{i=1}^n \left(\frac{i}{n}\right)^a}{\frac1n \left(\frac{n+1}n\right)^{a-1}\left(na + \sum_{i=1}^n \frac{i}{n}\right)}\\
&= \lim_{n\to\infty}\frac{\frac1n\sum_{i=1}^n \left(\frac{i}{n}\right)^a}{\left(\frac{n+1}n\right)^{a-1}\left(a + \frac{1}{n^2}\sum_{i=1}^n i\right)}\\
&= \lim_{n\to\infty}\frac{\frac1n\sum_{i=1}^n \left(\frac{i}{n}\right)^a}{\left(\frac{n+1}n\right)^{a-1}\left(a + \frac{n(n+1)}{2n^2}\right)}\\
&= \frac{\int_0^1 x^a\,dx}{1\cdot\left(a+\frac12\right)}\\
&= \frac{1}{(a+1)\left(a+\frac12\right)}
\end{align}
so $a \in \left\{-\frac{17}2, 7\right\}$.
Answer: $L=\lim_{n\to\infty}\frac{1^a+2^a+...+n^a}{(n+1)^{a-1}[(na+1)+(na+2)+...+(na+n)]}=$
$=  \lim_{n\to\infty}\frac{1^a+2^a+...+n^a}{\frac{1}{n^a}(\frac{n+1}{n})^{a-1}\frac{1}{n}[n^2a +\frac{n(n+1)}{2}]} =$
$=  \lim_{n\to\infty}\frac{(\frac{1}{n})^a+(\frac{2}{n})^a+...+1^a}{(\frac{n+1}{n})^{a-1}[na +\frac{(n+1)}{2}]} =$
$=  \lim_{n\to\infty}\frac{\frac{1}{n}[(\frac{1}{n})^a+(\frac{2}{n})^a+...+1^a]}{(\frac{n+1}{n})^{a-1}[a +\frac{1}{2}+\frac{1}{n}]} =$
$=  \lim_{n\to\infty}\frac{\frac{1}{n}\sum_{k=1}^{n}(\frac{k}{n})^a}{(\frac{n+1}{n})^{a-1}[a +\frac{1}{2}+\frac{1}{n}]} =$
$=\frac{\int_0^1 x^a dx}{a+\frac{1}{2}}=\frac{1}{(a+1)(a+\frac{1}{2})}$
because
$1+2+...+n=\frac{n(n+1)}{2}$


AsyncTask Workflow

Question: I am currently working on an android application that has to handle a network connection using several AsyncTasks.
This is the first task that is establishing the connection and calling a new task which is handling the microphone input.
private class establishConnectionTask extends
        AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {
        try {
            // initialize connection
            initConnection();
            MicrophoneTask micTask = new MicrophoneTask();
            micTask.execute("");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Executed";
    }

    @Override
    protected void onPostExecute(String result) {
        mReadInputTask = new readInputTask();
        mReadInputTask.execute("");
        super.onPostExecute(result);
    }

Everything works fine, the connection is working and I can transfer data. Also the MicrophoneTask is doing it's job.
Here comes the problem:
In the onPostExecute method I am creating a new AsyncTask which should handle all the network input.
This is how the readInputTask looks like:
private class readInputTask extends AsyncTask<String, Integer, String>
{

    @Override
    protected void onPreExecute()
    {
        Log.d("DEBUG", "pre");
        super.onPreExecute();

    }

    @Override
    protected String doInBackground(String... params) {
        // blocking readInput method
          Log.d("DEBUG", "doInBackground");
    }

    @Override
    protected void onPostExecute(String result) {
        Log.d("DEBUG", "post");
        super.onPostExecute(result);
    }
}

The readInputTask somehow gets stuck in the onPreExecute method of the readInputTask. The only output I get is "pre", eventhough I also expect "doInBackground" and "post".
Does anyone see an error or knows a solution for this?
Any help is appreciated!
Comment: I think `doInBackground` is throwing an exception before the Log line. Did you see any errors in the Logcat ?
Comment: No exception is thrown. I only see my Log lines.
Answer: mReadInputTask.execute("");

When you use AsyncTask#execute(params), the AsyncTasks are executed serially: one after the other. To execute AsyncTasks in parallel, use AsyncTask#executeOnExecutor(...).
From the docs on executeOnExecutor (Executor exec, Params... params):

This method is typically used with THREAD_POOL_EXECUTOR to allow
  multiple tasks to run in parallel on a pool of threads managed by
  AsyncTask, however you can also use your own Executor for custom
  behavior.
Comment: @Al0x Yea, they used to be. From version 1.6 (Donut) and up until 3.0 (Honeycomb), AsyncTask were executed in parallel by default (using a ThreadPool). But, `[s]tarting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution` (taken from [AsyncTask(subheading: Order of execution)](http://developer.android.com/reference/android/os/AsyncTask.html)).
Comment: Thanks alot, got it working now! I thought AsyncTasks were parallel.

AsyncTask Workflow


Easiest way to add x-webkit-speech to the search block's input element

Question: I am creating a zen sub theme and I was wondering what't the quickest way to add the x-webkit-speech attribute to the search box so user's can search with their voice? I know there is a Drupal project that can modify the search for me but I would prefer to do it in my templates somewhere so the rendered output is something like...
<input title="Enter the terms you wish to search for." type="text" x-webkit-speech id="edit-search-block-form--2" name="search_block_form" value="" size="15" maxlength="128" class="form-text">

Answer: use hook_form_alter on the search_form and add an HTML attribute via the #attributes for x-webkit-speech.
Answer: as described in hook_form_FORM_ID_alter and @tenken said, write a simple module:
function mymodule_form_search_block_form_alter(&$form, $form_state, $form_id) {
  $form['search_block_form']['#attributes']['x-webkit-speech'] = 'x-webkit-speech';
  $form['search_block_form']['#attributes']['speech'] = 'speech';
}

also to have valid xhtml avoid valueless attribute.
Comment: I used a hybrid of your answer and tenken's. I'm marking yours as the answer because it contained most of the code I used:

function THEMENAME_form_search_block_form_alter(&$form, $form_state, $form_id) {
    $form['search_block_form']['#attributes']['x-webkit-speech'] = 'x-webkit-speech';
    $form['search_block_form']['#attributes']['speech'] = 'speech';
}
Comment: just to be clear you dont need a custom module, since you asked for a "theme" solution. the hook_form functions can be called from your custom theme's `template.php` file.


Android handling simultaneous permissions from different sources

Question: I am trying to request multiple permissions at the same time, coming from multiple sources. My problem is that only one permission is being requested.
Here's an example :
We have 2 fragments which are loaded at the same time on MainActivity such as
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication.MainActivity"
    android:orientation="vertical">

    <fragment android:name="com.example.myapplication.fragments.FragmentOne"
        android:id="@+id/fragment_one"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <fragment android:name="com.example.myapplication.fragments.FragmentTwo"
        android:id="@+id/fragment_two"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

We have FragmentOne that requests READ_CALL_LOG such as
@Override
public void onStart() {
    super.onStart();
    Log.d(TAG, "onStart: ");
    requestPermissions(new String[]{Manifest.permission.READ_CALL_LOG}, 1);
}

We also have FragmentTwo that requests READ_CONTACTS such as
@Override
public void onStart() {
    super.onStart();
    Log.d(TAG, "onStart: ");
    requestPermissions(new String[] { Manifest.permission.READ_CONTACTS }, 2);
}

What this means is that as soon as the application launches, the 2 fragments are created, then started. When that happens, both fragments request a permission at the same time. My problem is that only the first permission is ever prompted to the user.
Now to figure out my problem, I added some logs in onRequestPermissionsResult of each fragments such as
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    Log.d(TAG, "onRequestPermissionsResult: requestCode=" + requestCode + " permissions=" + permissions
            + " permissions.length=" + permissions.length + " grantResults.length=" + grantResults.length);
    for (String permission : permissions) {
        Log.d(TAG, "onRequestPermissionsResult: permission=" + permission);
    }
}

Following that I found my problem, but am left with no solution.
When I looked at the logs, as soon as I launch the app, I get these logs
2017-05-02 13:22:40:0356    + 677   05-02 13:22:38.650 27003 27003 D FragmentOne: onStart:
2017-05-02 13:22:40:0357    + 699   05-02 13:22:38.661 27003 27003 D FragmentTwo: onStart:
2017-05-02 13:22:40:0357    + 702   05-02 13:22:38.661 27003 27003 D FragmentTwo: onRequestPermissionsResult: requestCode=2 permissions=[Ljava.lang.String;@afbcb45 permissions.length=0 grantResults.length=0

At the same moment, the dialog requesting READ_CALL_LOG is displayed.
The problem here seems to be that it goes into onRequestPermissionsResult too early.
As soon as I accept the READ_CALL_LOG permission from the dialog, I get 2 new logs
2017-05-02 13:27:42:0017    + 2803  05-02 13:27:40.358 27003 27003 D FragmentOne: onRequestPermissionsResult: requestCode=1 permissions=[Ljava.lang.String;@5028ba8 permissions.length=1 grantResults.length=1
2017-05-02 13:27:42:0017    + 2804  05-02 13:27:40.358 27003 27003 D FragmentOne: onRequestPermissionsResult: permission=android.permission.READ_CALL_LOG

At that point, the second permission dialog (for READ_CONTACTS) that I was expecting is NOT displayed. No further logs are generated.
Now, I know that I could get all the permissions from the different fragments and prompt them all at the same time by passing the relevant String array. But that is not what I am trying to accomplish here. I am trying to have multiple components handle their own permissions.
Am I missing something? Am I doing something wrong?
For reference, I will put here the full code of MainActivity and of FragmentOne. FragmentTwo pretty much the same thing (Only the TAG and the permission change).
MainActivity :
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

FragmentOne :
public class FragmentOne extends Fragment {

    private static final String TAG = "FragmentOne";

    public FragmentOne() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragment_one, container, false);
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart: ");
        requestPermissions(new String[]{Manifest.permission.READ_CALL_LOG}, 1);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.d(TAG, "onRequestPermissionsResult: requestCode=" + requestCode + " permissions=" + permissions
                + " permissions.length=" + permissions.length + " grantResults.length=" + grantResults.length);
        for (String permission : permissions) {
            Log.d(TAG, "onRequestPermissionsResult: permission=" + permission);
        }
    }
}

Answer: Try to put the permission requests in the activity instead of the fragment and request both at the same time.
What seems to be the problem is that when you request the second permission the first dialog is closed so it is treated as denied.
Comment: That's what I ended up doing in the end. But it does not solve the actual problem. Which is permissions do not seem to be handled correctly in fragments. Or at least, they are, but only if there is a single fragment requiring permissions running at a single time. I find it strange that Fragment offers the requestPermissions method, if it does not handle correctly multiple fragments.


ArangoDB Graph Traversal fails inspite of increased heap size

Question: ArangoDB Version: 3.3.14
Heap Statistics for application:
 { total_heap_size: 39108608,
  total_heap_size_executable: 3670016,
  total_physical_size: 37433512,
  total_available_size: 8735662896,
  used_heap_size: 28891504,
  heap_size_limit: 8769069275,
  malloced_memory: 16384,
  peak_malloced_memory: 168484640,
  does_zap_garbage: 0 }
I have a traversal api which traverses through 3 vertices and returns around 300 document vertices.
For 200 I get the proper response but when I increase the number of vertices to 300, the traversal api throws an error invalid string length. I have increased the heap space for application to 8GB but as can be seen below the heap_used is way far too less. I am quite not sure if this issue is during serialization to JSON as there is sufficient heap memory available or are there any other options available to get the complete data.
AQL query (if applicable):
{"request":{"vertex":"start_vertex","start_vertex":"service_teams/9a2e582997494bee9066bbcf2aa52218","start_vertices":null,"opts":{"expander":"var connections = [];\n config.datasource.getOutEdges(vertex).forEach(function (e) {\n if( (e._id.indexOf(\"loc_has_parent_loc\") > -1) || (e._id.indexOf(\"loc_is_associated_with_org\") > -1) || (e._id.indexOf(\"st_is_allocated_loc\") > -1) ) {\n connections.push({ vertex: require(\"internal\").db._document(e._to), edge: e});\n }\n });\n return connections;"},"collection_name":"","edge_name":"","data":true,"path":false}},"err":{"code":500,"message":"Invalid string length"}}
Answer: The error message you're seeing here is a V8 error message, thus this is a javscript implementation limitation. V8 allows strings up to 256 MB.
The old graph traversal API is implemented in Javascript, and for processing may stringify documents inbetween and thus reach this limit.
Please prefer AQL-Traversals instead for better performance.


Collecting data from multiple sources using multiple processes/threads/tasks

Question: Let's imagine the set of several data sources, i.e. couple of thermal sensors, or video cameras. I want to collect data from those sources in slaves and pass to the master.
Efficiency is the key aspect of the operation.
Should I use multiple processes or threads/tasks?
EDIT: I forgot to mention... All data sources should be synchronously served, equally with the same priority, at the same time, regardless of the CPU and memory usage and available number of cores.
Answer: If you're passing from several slaves to a master, use threads. This will help you share your address space and perhaps make the task easier to implement. If you have very many slaves and want the utmost efficiency, use a thread pool to service slave sources.
Using multiple processes would just add process context switch overhead, which in general is slightly more than that of thread context switches. You would also have to manage interprocess communication, which in general is more complex and less efficient than interthread communication.
Comment: File mapping objects are most likely your best option for efficient interprocess communication, which you should still avoid. One of the reasons it would be less efficient than interthread communication is that you would have to use a mutex for synchronization to the file mapping object, instead of the much more efficient critical section.
Comment: In fact, the concept of multiple threads is much more easier to handle. I considered the Memory Mapped Files to exchange data. It could work with interprocess communication. I don't know if it is suitable for threads. What do you think about that?
Answer: The typical way of doing that is using a reader writer lock (ReaderWriterLockSlim in .NET). Your writers would queue for one-at-a-time write access to your shared state map, while your readers (your client application for instance) can read together at the same time, though obviously not while the state is being written by a producer.
Edit: That's using threads obviously. Inter process communication would kill any hope of decent performance you might have.
Comment: Doesn't exactly change much, you just have a set of events you fire off for every producer, and your consumer joins on all of them, then it fires another event that the producers join on when done. You still need to serialize the actual access to your object, although a simple `lock(syncobj)` might be enough with only one consumer.
Comment: Thanks for your input! Can you please see the comment: http://stackoverflow.com/questions/10402469/collecting-data-from-multiple-sources-using-multiple-processes-threads-tasks#comment13418611_10402490


Install Android APK Programmatically

Question: Now, I want to programmatically install another apk, which exists in my current apks' assets.
However, I can't copy the apk to sdcard first, because the sdcard doesn't mount.
Is there a possbile solution ? thanks.
Comment: what is ur question, how to mount the sdk or how to install the apk programmatically ?
Answer: To install app programmatically use following code, you'll need user permission.
android.permission.INSTALL_PACKAGES

Code:
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
    .setData(Uri.parse("file:///path/to/your.apk"))
    .setType("application/vnd.android.package-archive");
startActivity(promptInstall);

Install Android APK Programmatically


Table View UI error: Swift

Question: On the last question I asked about the code error in my animal table view project, now I finished the initial coding, but my UI turned really strange. It is missing the first letter of each animal name and the table view prototype cell.
For example, amel should be camel and hinoceros should be rhinoceros.
Is this a bug from the code here?
import UIKit

class AnimalTableViewController: UITableViewController {

var animalsDict = [String: [String]] ()
var animalSelectionTitles = [String] ()

let animals = ["Bear", "Black Swan", "Buffalo", "Camel", "Cockatoo", "Dog", "Donkey", "Emu", "Giraffe", "Greater Rhea", "Hippopotamus", "Horse", "Koala", "Lion", "Llama", "Manatus", "Meerkat", "Panda", "Peacock", "Pig", "Platypus", "Polar Bear", "Rhinoceros", "Seagull", "Tasmania Devil", "Whale", "Whale Shark", "Wombat"]

func createAnimalDict() {
    for animal in animals {
        let animalKey = animal.substringFromIndex(advance(animal.startIndex, 1))
        if var animalValues = animalsDict[animalKey] {
            animalValues.append(animal)
            animalsDict[animalKey] = animalValues
        } else {
            animalsDict[animalKey] = [animal]
        }
    }
    animalSelectionTitles = [String] (animalsDict.keys)
    animalSelectionTitles.sort({ $0 < $1})
    animalSelectionTitles.sort( { (s1:String, s2:String) -> Bool in
        return s1 < s2
    })
}

override func viewDidLoad() {
    super.viewDidLoad()

    createAnimalDict()
}

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

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // Return the number of sections.
    return animalSelectionTitles.count
}

override func tableView(tableView: UITableView, titleForHeaderInSection section:Int)  -> String? {
    // Return the number of rows in the section.
    return animalSelectionTitles[section]

}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

    let animalKey = animalSelectionTitles[indexPath.section]
    if let animalValues = animalsDict[animalKey] {
        cell.textLabel?.text = animalValues[indexPath.row]
        let imageFileName = animalValues[indexPath.row].lowercaseString.stringByReplacingOccurrencesOfString("", withString: "_", options: nil, range: nil)
        cell.imageView?.image = UIImage(named:imageFileName)
    }
    return cell
}

}
Comment: Have you checked that `animalsDict` contains what you expect? And shouldn't it be `substringToIndex` instead of `substringFromIndex` as already suggested in an answer to your previous question? Did you set a breakpoint in `titleForHeaderInSection ` and `cellForRowAtIndexPath` and used the **debugger** to check where the "wrong" names come from?
Answer: So far I can say the error is in your createAnimalDict() method. In the line
let animalKey = animal.substringFromIndex(advance(animal.startIndex, 1))

exchange the second parameter in advance to 0 so it be:
let animalKey = animal.substringFromIndex(advance(animal.startIndex, 0))

In fact I don't really know what you are trying to do.
Answer: In this method:
override func tableView(tableView: UITableView, titleForHeaderInSection section:Int)  -> String? {
    // Return the number of rows in the section. (THIS COMMENT IS INCORRECT)
    return animalSelectionTitles[section]
}

You are returning the title for each section. However your animalSelectionTitles[index] contains the animal name without the first letter due to its construction in createAnimalDict
Use the animal array instead for providing the full animal names:
override func tableView(tableView: UITableView, titleForHeaderInSection section:Int)  -> String? {
     return animals[section]
}

However note that due to the removal of the first letter you might have two animals mapping to the same key so if not necessary use the entire animal name as the key.

Table View UI error: Swift


VST difference between valve amp, preamp and tape saturation

Question: I've been learning how to master songs with a few tutorials and I've stumbled upon various plugin categories I'd like to be able to distinguish a bit better.
Many of those tutorials recommend to use preamp VSTs when mixing, as well as a valve amp and a tape saturator VST when mastering (sometimes, a tube amp plugin is also recommended).
What confuses me is that all those three kind of plugins seem to have the exact same purpose, which is to make the sound bolder, warmer and louder. Also, a lot of plugins seem to simulate tube and tape at the same time...
My question is, what are the different purposes of these components in real life, and how can I tell them appart when using them VSTs?
Answer: A valve and a tube are the same thing -- "tube" was originally more common in American English, while "valve" was more common in England. A "vacuum tube" is any one of a number of types of electronic component based around an arrangement of electrodes inside a sealed glass unit, from which all the air has been removed.
The kind of tube used in amplification is a triode. You give it a steady high voltage on one input, and a varying low voltage input (like the output of a guitar or a record needle) on the other. The output is the high voltage, varied according to the low voltage signal -- that's amplification.
This is the same behaviour you get in a transistor, which is smaller, less fragile and easier to manufacture in high volumes.
The interesting thing about valves is what happens when the signal input is too high.
For a theoretically perfect amp, output = c * input where c is a constant. A tube amp will approximate this for most of its range. But what happens if c * input is greater than the maximum output of the amplifier?
You might imagine that the output is either c * input or max_output, whichever is lower. If that happens, you get "hard clipping" as shown by the red lines in this graph.

Tubes, though, don't respond quite so harshly. As you approach the maximum, the amplification ratio gradually eases off, so instead of just cutting off the top of the wave, you get a gentle curve, described as "soft clipping".
When used for music, the outcome is a distortion effect that people tend to describe as "warm". By contrast, transistors tend to have a sharper curve, which people tend to describe as "harsh" -- although there are transistors made specifically for music which have a more musical sound.
Hence an amplifier made with valves is considered to add an appealing sound when pushed a little, and it also provides a safety net when mixing -- occasional peaks are handled gracefully.
A tube/valve amp VST, as you can imagine, simulates those response curves, to create a sound that's close to what a valve/tube amp would produce.
There is a certain element of familiarity here. All the classic rock/pop recordings were made with tube pre-amps, and so we have learned to love the effect.

Tape saturation is a similar effect, but with a different history.
When audio is recorded onto analogue magnetic tape, the varying electrical signal is passed to an electromagnet, which creates a varying magnetic field, which leaves its mark on a moving tape.
Again, the interesting stuff happens when the input signal is too high for accurate reproduction. Again, the way magnetic tape handles an excess signal is to flatten the peaks gently.
The effect is so well loved that there are high end studio accessories containing a short loop of tape, a write head and a read head, so that the performance being recorded gets real tape compression applied before it is digitised and recorded to hard disk.
Tape also has a non-linear frequency response, so can be compared to a certain set of EQ settings.
Again, a VST simulates these effects.

Both tube and tape, when overloaded, are kinds of compression. They reduce the difference between quiet parts and load parts -- in this case by amplifying the loud parts less, and doing so in a way that distorts the sound in a manner that we have learned to enjoy.

What do you do with this knowledge? Well, try them all and use your ears. If you like what you hear, it's good. If you don't, it's bad. If you can't tell the difference, it's pointless.
As with all mixing and mastering, it's a minefield of superstition and psychosomatic perceptions -- and you might not have the "golden ears" to tell the difference; many of us don't. If you really care, do blind A/B tests. Or, just go with what sounds good to you, psychosomatic or not.
Comment: +1 but two points. 1St 'The kind of tube used in amplification is a triode' is only true of preamps, but the question is probably about preamp simulators, so it could slide. 2 'If you can't tell the difference, it's pointless' many people have used equipment above their ability to discern just what the difference was, and have sounded better off for it.
Comment: Very useful answer, the main difference between tube and tape has been explained quite well! It also gives me a greater understanding why I am using these VSTs, thanks a lot!


Multiple grace note snare drum ornament

Question: I am looking at Sergei Prokofiev's Dance of the Knights (from the Romeo & Juliet ballet: Act I, Scene 2, No. 13) .
In mm. 9–10 (from rehearsal mark [77]) and also a few times later in the piece there is a particular grace note ornament that is played on the snare drum:

In both of these performances:

The London Symphony Orchestra, cond. Valery Gergiev
The Royal Stockholm Philharmonic Orchestra, cond. Yuri Temirkanov

it looks like this ornament is played with the sticking: lrlR.
Does this type of ornament have a name?

On a chart of standard drum rudiments there are some grace note ornaments:

a single grace note ornament called a Flam, which is played with the sticking: lR
a two grace note ornament called a Drag, played: llR

But, I don't think the ornament in question is well described as either of these because a flam has just one grace note, and a drag has two grace notes both played with the same hand rather than with alternating hands.
Some other candidates from standard drum rudiments (but that don't contain grace notes) are:

a Single Stroke Roll: RLRL
a Single Stroke Four, which contains a triplet, but is also played: RLRL

But, both of these start on the beat, and don't usually have the last note played with the right hand or given an accent.

Would/should a percussionist think of the snare drum ornament in the Dance of the Knights as some variant any of the above, or as something completely different? And is there a name for it this ornament?
Comment: Sorry: What exactly is your question?
Comment: @MS-SPO What is the name for the ornament in the image? I don't think it's a flam, or a drag, or a single stroke roll, or a single stroke four.  Does it have name?
Comment: Thanks. Quick look into "Stick control for the snare drummer" suggests flam beats, which you can perceive as a variation  of rolls. I don't think there's a specific name for it. Also, whether to play it LRLR, LRRR, RRLL or whatever is a matter of convenience for, experience of, drum tuning by the drummer. There are so many ways to create said sound (rrlR or llrLmight be a reasonable choice). E.g. you can follow Tommy Igoe, who favors soft hands and mainly finger control. Or you could even achieve it by the Muller technique.  As long, as it's clear, how it should sound …
Comment: The latter point may be worth a discussion. Taking the notation literally, suggests a slightly syncopated accent on what's written as a quarter note. If no syncopation was intended, then the flam has to start a little earlier, which may be harder to notate.
Answer: A four stroke ruff.  It sounds similar to a drag, but with an extra grace note.  There is also an alternative sticking of rllR or lrrL, which sounds basically the same (provided you don't crush the double stroke), so you can really play either sticking.  But alternating is the "proper" way.
I would not call this a "single stroke four" because that would usually refer to a metered grouping of three notes with no accent, rather than a single accent with three preceding grace notes.
Comment: I don't know that there's really a set definition here.  I believe "drag" always refers to the rrL / llR rudiment, but ruff is a bit more ambiguous- Some people consider the drag is a type of ruff, some people only use ruff to refer to non-drag and non-flam ornaments.
Comment: Ah, so a ruff *is* different to a drag.  I'm sure I've seen rudiment charts that suggest they are just two name for the same ornament, or call a drag a "drag ruff".
Comment: Would you say that `lllR`/`rrrL` could be called a four stroke drag?
Comment: I don't think I've ever seen that rudiment used, so any name you gave it would have to be clarified, and that name returns no relevant hits on google.  I guess that seems like a reasonable choice for a name, though.
Answer: 'Single stroke four' is about as close as we get to an official name from the list of rudiments. lrlR or rlrL, although the speed at which the acciaccatura 'triplet' is played may well vary. The main point is that the main note is played on the beat, rather than after it, meaning the 'triplet' is played before.
Answer: I think what confuses you is that you try to assign a name to a sticking pattern, like "LR must be called xyz". That's not a useful approach to a drummer.
Let's try to get two things straight, the roll and the flam.
A roll basically plays note after note, e.g RLRL or RRLL or RRL or RLR etc. in whatever timeframe. Right stick, left stick, right stick, left stick, done. In terms of arm/hand movements you'll observe basically arms out-of-phase: if one is up, the other one is down (or on its way), alternatingly.
A flam in contrast is hitting with both sticks at the same time ... with a nuance of a shift and lower accent in time: think of two sticks falling onto the snare, where one is just a little bit shifted, say an inch or so ... which translates into a very narrow time interval of "almost same time". If you can hear both sticks, it's not a flam. In terms of arm/hand movements:

both sticks seem to hit simultaniously,
while when starting the flam the louder stick will be held higher and arrive just a little-little-bit later

If done correctly, see video here, you'll hear a very characteristic sound, you can't create else on the drumset.
To complete, a ruff, if you look at the relevant movements of arms/hands, is much more like a roll with a taste of a flam, as you can see here at 01:15.
Though there is a logical convention for notation, one or two short notes with a slur towards the emphasized quarter note (see middle of my 2 videos), it doesn't really address the movement property, which is essential for the sound produced. So the translation from notation to action may be ambigous, depending e.g. on the composer, the drummer etc.

Now, let's return to your two videos. In both cases you'll see the characteristic movement for a roll, not for a flam, and sounds very uniform and with distinguishable strokes. So call it whatever you think is usefull AND will be understood as you wanted it.

Some final remarks on stick-techniques. As I indicated in my early comments (stick control), it depends much on the drummer.
A beginners technique is the good habit to have one beat (sound) from one hit (with any stick). So if you want to hear beat-beat-beat-beat, you play carefully hit-hit-hit-hit, or stick-stick-stick-stick.
An advanced drummer, and even a careless drummer, can create multiple beats with one hit only using rebound (backbouncing of the stick), like:

beat-beat from hit or stick
beat-beat-beat from hit or stick
etc.

Rebound is widely used, and can sound bad when not under control. I.e. the time intervals tend to become shorter, just like with a steel ball or coin falling on the floor.
So, putting both together a drummer has many options all the time to realize an intended sound, like a notated beat-beat-beat-beat, e.g.:

RLRL or LRLR (which will probably be precisely in time and sound quite uniform)
RRLL or LLRR (which may sound less uniform and more rock-n-roll-ish, like in "dada dada didi didi, bat-man!")
R L or L R (using good controlled rebound; do you see the 3 options using rebound you have per pattern R L or L R?)

So what can you do? Listen and observe:

how does it sound?
what are arms, hands and fingers doing (in order of increasing difficulty to observe)?

And as a rule of thumb: you'll hear flams almost never. So a roll is a good first assumption.
Comment: I think this answer meanders a bit and never really answers the question.  Also, I've had more than a couple instructors encourage very open flams for solo repertoire.
Comment: Calling it "open flams" may be ok by notation, but simply fails observation in your two videos, as I layed out. // My answer may seem to meander, as the question paved this path. Sometimes things become easier to understand when moving towards the limits. // To repeat, creating the intended sound impression is more important in my view than coming up with some name for it.

Multiple grace note snare drum ornament


Could you check my results for entropies?

Question: Could you please check my results to the following exericse:

Let $X,Y$ be independent RVs, each with values in $\{0, 1\}$ and probabilities $(1/2,1/2)$. Compute $I(X; Y )$, $I(X + Y ; X)$ and $I(X + Y ; X − Y )$.
Remark: $I$ stand for the mutual information of $X$ and $Y$. It holds
$$I(X;Y) = H(X)+H(Y)-H(X;Y)$$
, where $H$ denotes the entropy.

With this in mind I computed the resprective entropies as:
$$H(X) = H(Y) = 1$$
$$H(X+Y) = H(X-Y) =1.5$$
$$H(X,Y) = 2$$
$$H(X+Y, X) = H(X+Y, Y) = 2.5$$
$$H(X+Y, X-Y) = 3$$
In the end I get $I(X; Y ) = I(X + Y ; X)  =  I(X + Y ; X − Y ) = 0$.
Is this O.K.?
Comment: Well, does it make sense? For example, is it really true that if I tell you $X$, you learn nothing about $X+Y$? For example, if I told you that $X=0$, is there still the same probability of having $X+Y=2$ as before?
Comment: It seemed suspicious to me, but I can not see where I made a mistake.
Answer: Some sanity checks that we can do without getting into the full calculation:

$H(X+Y,X)$ and $H(X+Y,X-Y)$ should both be at most $2$, because $H(X,Y)$ is $2$, and the pairs $(X+Y,X)$ and $(X+Y,X-Y)$ shouldn't have more entropy than $(X,Y)$: after all, we can compute them from $(X,Y)$!
In fact, knowing $X+Y$ and $X$, we can compute $Y$, and knowing $X+Y$ and $X-Y$, we can compute $X$ and $Y$. So we should have $H(X+Y,X) = H(X+Y,X-Y) = H(X,Y) = 2$.
$I(X+Y;X)$ should be positive because some values of $X$ definitely convey information about $X+Y$.
$I(X+Y;X-Y)$ should be positive because some values of $X-Y$ definitely convey information about $X+Y$. (If $X-Y=0$, we know that $X+Y$ is either $0$ or $2$; if $X-Y=\pm1$, we know that $X+Y=1$.)

For computing $H(X+Y)$ we do have to look at the formula. ($H(X-Y)$ will be the same). $X+Y$ takes on values $0, 1, 2$ with probabilities $\frac14, \frac12, \frac14$, so the surprisal of $X+Y$ takes on values $2, 1, 2$ with probabilities $\frac14, \frac12, \frac14$, and we get $H(X+Y) = 2 \cdot \frac14 + 1 \cdot \frac12 + 2 \cdot \frac14 = 1.5$. So your computation checks out.
Now, we get $$I(X+Y;X) = H(X+Y) + H(X) - H(X+Y,X) = 1.5 + 1 - 2 = 0.5$$ and $$I(X+Y;X-Y) = H(X+Y) +  H(X-Y) - H(X+Y,X-Y) = 1.5 + 1.5 - 2 = 1.$$
Comment: Thanks a lot for your answer, it helped me a lot.


For orthogonal vectors $x$ and $y \in \mathbb{R}^3$, if $x$ has norm $4$ and $y$ has norm $4$ then what is the norm of $x+y$?

Question: For orthogonal vectors $x$ and $y \in \mathbb{R}^3$, if $x$ has norm $4$ and $y$ has norm $4$ then what is the norm of $x+y$?
Comment: x,y and x+y are all coplanar (the belong to the same plane). So you can use Pythagorean Theorem.
Answer: Since the vectors are orthogonal, they meet at a right angle, so we have
$$|| x+y || = \sqrt{||x||^2 + ||y||^2}$$
by the Pythagorean theorem.


How do you show $a_{n+1}= \sqrt{a_n +1}$ is contractive?

Question: Let $a_{n+1}= \sqrt{a_n +1}$ for all natural numbers $n$.
How do you prove $a_n$ is contractive?
Definition of contractive sequence is:
If there exists a constant $C \in (0,1)$ such that $|a_{n+2} - a_{n+1}| \leq C|a_{n+1}-a_n|$ for all natural numbers $n$, then the sequence $a_n$ is contractive.
Here is my thought process:
First, I prove $a_n$ is monotone increasing by induction.
Second, I prove it is bounded above.
Third, I compute what the limit would be.
Last, I try to get the required inequality for contrative sequence. I am stuck on this last step.
In the third step, I solved the quadratic equation $L^2 - L - 1 = 0$, which gives me L = $\frac{1+\sqrt{5}}{2}$
Then,for the fourth step,  I do  $|a_{n+2} - a_{n+1}|=|\sqrt{a_{n+1}+1} -\sqrt{a_{n}+1} | \leq L + L$. At this point I am not clear how to find the value of $C$.
Comment: Can you bound $f'(x)$ for $f(x)=\sqrt{x+1}$.
Answer: Hint: $\;\left|a_{n+2} - a_{n+1}\right|=\left|\sqrt{a_{n+1}+1} -\sqrt{a_{n}+1}\right| = \dfrac{\left|a_{n+1}-a_n\right|}{\sqrt{a_{n+1}+1} + \sqrt{a_{n}+1}} \le \dfrac{\left|a_{n+1}-a_n\right|}{1+1}\,$.
Answer: Let $f(x)=\sqrt {1+x}\;$ for $x> 0.$ Then $f'(x)=\frac {1}{2\sqrt {1+x}}.$ So $0<f'(x)< \frac {1}{2}$ when $x>0.$
If $x,y$ are positive and $x> y$ then by the MVT there exists $z \in (y,z)$  such that $\frac {f(x)-f(y)}{x-y}=f'(z).$   Since $0<f'(z)<\frac {1}{2},$ therefore  $0<f(x)-f(y)<\frac {1}{2}(x-y).$
Hence for any  positive $x,y$ we have $|f(x)-f(y)|\leq \frac {1}{2}|x-y|$, with equality iff $x=y$.
Of course proving the validity of the formula for $f'(x)$ can be done by using  the method in the Answer by dxiv.


How to calculate the next year's January hourly forward prices for an asset given the historical hourly prices?

Question: I have an exercise given to me during the recruitment process which asks to calculate the next year's January hourly forward prices for an asset given the historical hourly prices of that asset and next year's January average price (average of all hours in that period).
The exercise asks to take account of the seasonality (modelling seasonality), hence there is a 9 year hourly price dataset given.
I have studied statistics and econometrics at school but have forgotten most of the techniques that could be used for price estimation.
Any idea how this exercise can be solved? I can provide a sample dataset on request.
Comment: Sorry, but I disagree. This is a *screening question* for a job offer that means that the knowledge base of the candidate is being evaluated. If he does not know, it is dishonest to pretend that he does by just foisting off the question to other people, with *zero effort* on his part to attempt a solution. The whole point of the screening questions is to weed out people who don't know. Lots of professors don't know about this site either; that does not mean it is not unethical and a violation of student conduct if students post their assignment questions on SE without disclosing the context.
Comment: I have seen the recruiting effort actually test not only the knowledge of the prospect BUT the resourcefulness of the prospect. It is one thing not to know and not to know where the solution might be AND not to know but also to know where to get ethical help to deal with the question. I believe in attempting to help people who ethically seek help and to provide guidance as they attempt to get smarter about things. I trust you are also of this mind and emulate @whuber as he eminently pursues this goal.
Comment: Since this is a de facto homework question, it should be tagged as such.
Comment: I don't believe that this is homework at all. I Think that a challenge was laid out by an individual (the recruiter) who was unaware of this website. I would treat the question as coming from them and in this light it is definitely not homework.
Comment: http://quant.stackexchange.com/ would be a better place to ask this question
Answer: We have studied very similar problems mostly in the retail sector. One needs to recognize that the eventual hourly forecasts need to aggregate/reconcile to the monthly forecast. We have implemented a two-prong approach which uses monthly values to predict hourly values taking into account monthly patterns and hourly effects. These models also incorporate any level shifts or trends that may be found to be statistically significant. Additionally any auto-regressive structure is also incorporated ( previous prices). Care is also taken to identify anomalous data and adjusting for these effects to ensure a robust solution. Known events such as Holidays and other possible causes are also included/tested in a very sophisticated manner. The software package I have helped develop called AUTOBOX implements this solution. I would suggest that you review it ( there is a free 30 day trial ) and if you like the results either acquire it or rewrite it in any language/system that you wish.
Finally one needs to validate that the final model has an error process that has constant variance and that the model's parameters are invariant over time.
In closing the recruiter is simply trying to find that employee that can solve a problem that they can't currently solve OR is as creative/ingenious as your are to be able to reach out to subject matter experts and acquire/find an answer. If I were them I would definitely hire you !
Comment: @Erik If truly have *forgotten* the techniques, then the thing for your to do is to re-read your class/text notes. The solution suggested above does not apply to forecasting forward prices of stocks at all.
Comment: Thank you for your reply! I will definitely try the Autobox out. As for the exercise, as I stated previously, this task is not just to predict prices based on historical values, but there is also a monthly average constraint already given for the period that needs hourly data to be calculated. So I reckon one needs to use a Solver function for Excel to change the hourly prices in such a way that would solve the equation. Only question is which conditions have to be met for Solver to work properly?
Comment: It's not that I haven't made any attempts to solve it - I have, but I realize the result is not close to reality. By writing here, I was looking for some guidance which in my opinion is a normal practice. Networking is efficient after all.
The fact that I can't solve it by myself at present does not mean I don't want to learn how to do it.
Comment: @rocinante I agree that stock price forecasting is difficult BUT for you to dismiss the general approach is a bit much in my opinion as there may be changes in volatility that can be identified and/or particular days of the week/month that might be important. Don't throw out the baby with the bathwater ! Take the structure that you can identify and move forward. It is better to light a candle than curse the darkness.
Comment: @Erik The problem here is three-fold. One, you misrepresented your efforts by claiming that you "forgot", when you now just admitted that you never knew how to do it in the first place. Second, SE rules are clear that *attempts at solution should be disclosed*, along with any data/code output. Thirdly, as a job screening question, it is unethical to crowd-source a solution. You are the one being hired for the job, not SE members.
Comment: @erik It is not necessary to reach out to Solver to constrain hourly forecasts to match monthly numbers as a bottom up/top-sown procedure can do just that.
Comment: @IrishStat It is not a question of difficulty. Finance books are very clear on how this type of forecasting should be done, and have their own models - which recruiters/interviewers are expecting candidates to know.
Comment: @roci Although I sympathize with your concern, I must point out it is not our role to guess about the motivations or circumstances behind a question, except insofar as it might bear on information needed to formulate an answer. As an individual, if you believe an SE question might violate your ethical norms, then you can comment constructively--as you have done--but please resist any *ad hominem* accusations. Egregious ethical violations are obvious to everyone and typically get no answers or else answers that might be a little misleading or confusing (and nobody bothers to correct them ;-)).


Why does the row order of the sequences in TraMineR influence clustering results (Wards method)?

Question: We have a large sample (44,933 sequences each of potential length 35) with 9 states. We create a standard dissimilarity matrix:
seq <- seqdef(data, 3:37, right="DEL", left="DEL", gaps="GAP", indel=3, id=data$id, weights=data$weight)

Then create the dissimilarity matrix (We use indel=3 to place greater emphasis on length of the sequences in the clustering.):
om <- seqdist(seq, method="OM", indel=3, sm="TRATE", with.missing = TRUE)

Finally, we cluster the dissimilarity matrix:
seq.ward <- agnes(om, diss=TRUE, method="ward")

If we randomize the order of the rows in the original data:
rand1 <- sample(44933)
data.rand1 <- data[rand1,]

and then recreate the sequences and proceed as above, the cluster results differ.
Answer: This has nothing to do with the way the dissimilarities are computed by TraMineR. The solution you obtain depend on the way the clustering algorithm (agnes in your case) deals with ties. Actually dissimilarity values are most probably not unique in your matrix, and therefore there will most probably be ties at the different steps of the hierarchical clustering process. The successive chosen splits will rely on some random choice that itself depends on the initial order. Hence, the different final solutions.
Therefore, to reproduce your solution you must

Keep the same row/column order in the dissimilarity matrix.
Set a seed value.

Hope this helps
Comment: You can use the fonction `clusterboot` in package `fpc` to check the stability of your clustering.


How to avoid certain variables from being cached?

Question: I've spent days trying to figure this out and really hope you guys can help me out here.
Let's say, I've created a list field on the user entity called field_render_array with the options:

Render array 1
Render array 2

There is a controller called RenderArray which should:

Return render array 0 if field_render_array is not set.
Return render array 1 if field_render_array is equal to render_array_1.
Return render array 2 if field_render_array is equal to
render_array_2.

I've been trying to achieve this using a controller like:
<?php

namespace Drupal\example\Controller;

use Drupal\Core\Controller\ControllerBase;

class RenderArrayController extends ControllerBase {

  public function content() {
    $user = \Drupal::currentUser();
    $field_render_array = $user->get('field_render_array')->value;

    if (!isset($field_render_array)) {
      return array(
        '#markup' => 'You haven't set your preferred render array.',
      );
    }
    else if ($field_render_array == 'render_array_1' ) {
      return array(
        '#markup' => 'Your preferred render array is 1',
      );
    }
    else {
      return array(
        '#markup' => 'Your preferred render array is 2',
      );
    }
  }

}

The problem is that the value of $field_render_array is getting cached. This comes across as a bug for end-users as the render array doesn't immediately change after changing the value of field_render_array.
Is it possible to somehow avoid certain variables from being cached or is there another solution to achieve the same thing?
Comment: Google "drupal 8 lazy builder".
Answer: If the variables come from the current user, then add this cache context to the build array you return:
$build['#cache']['contexts'][] = 'user';

Comment: See https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays for lots of documentation. Note that this means that your controller will possibly have a huge amount of variations, one for each user. If it is not expensive to build, you might want to disable caching completely with #cache max-age = 0. If it is expensive and you have a lot of users, you could make your own cache contexts that doesn't vary by user ID but just by the value of that field. You just need a service, see http://drupal.stackexchange.com/questions/214144/how-to-define-a-new-cache-context-for-a-node
Answer: To solve this problem I decided to reduce the number of render array's from 3 to 1.
<?php

namespace Drupal\example\Controller;

use Drupal\Core\Controller\ControllerBase;

class RenderArrayController extends ControllerBase {

  public function content() {
    $user = \Drupal::currentUser();
    $field_render_array = $user->get('field_render_array')->value;

    if (!isset($field_render_array)) {
      $markup = 'You haven't set your preferred render array.';
    }
    else if ($field_render_array == 'render_array_1' ) {
      $markup = 'Your preferred render array is 1';
    }
    else {
      $markup = 'Your preferred render array is 2';
    }

    return array(
      '#markup' => $markup,
      '#cache' => ['max-age' => 0],
    );

  }

}

As the field_render_array can always change, I added '#cache' => ['max-age' => 0] to the render array left. See https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays for more information.


Javascript pattern behaves weird

Question: foo is a function that calls itself, and within it is a function bar which also calls itself. Then I'm exposing bar. But why does it later says 'foo' is undefined?
var foo = (function(){
    var bar = (function(t){
        console.log(t);
    })('test 1');

    return bar;
})();

console.log(foo); // output: undefined

Update:
I would like to do something like this:
var foo = (function foo(){
    (function bar(t){
        console.log(t);
    })('test 1');

    return { bar : bar };
})();

foo.bar('test 2');

only that now bar is not recognized..seems like I can't self-execute once, and yet pass it as the return value..
Comment: Because `bar` is undefined, as that inner IEFE does not return anything? What did you expect it to be?
Comment: I've voted the question to be closed. thanks guys for the quick help!
Answer: The foo function immediately invokes itself, so its return value is assigned to foo. It returns the return value of bar, since that immediately invokes itself too, and since bar returns undefined, foo returns undefined too:
// Outer function, immediately invoked
var foo = (function(){

    // Inner function, immediately invoked
    var bar = (function(t){
        console.log(t);
        // Implicitly return undefined
    })('test 1');

    // bar is now === undefined

    return bar;
})();

console.log(foo); // output: undefined

Comment: `bar` is not a function, but only a variable.
Comment: @Bergi - It's clear what I'm trying to say though. It's easier to say "bar" than "the anonymous function the return value of which is assigned to bar".
Comment: ha. how dumb of me. i need Coffey.
Comment: But if bar is a function, and we return bar… I think using correct terms is essential here to avoid any (further)confusion.
Comment: I would like to return the pointer to `bar` as a function, but have `bar` call itself
Answer:
foo is a function that calls itself

No. foo is the return value of an immediate call to an anonymous function.

But why does it later says 'foo' is undefined?

That function returns bar which is the return value of another immediate call to a different anonymous function.
The return value of that function is, since there is no return statement in it: undefined (so bar is undefined so foo is undefined.
Answer: It's not behaving wierdly at all.
   var bar = (function(t){
        console.log(t);
        // return undefined;
    })('test 1');
   return bar; // again return undefined;

It has no return statement, therefore it is returning undefined. You are then returning undefined again, so it's obvious foo will also be undefined.
Answer: foo is not a function, but the return of the anonymous function
function(){
    var bar = (function(t){
        console.log(t);
    })('test 1');

    return bar;
}

And the return is bar, that is the return of the anonymous function
function(t){
    console.log(t);
}

with t == 'test 1'. This function returns nothing, so bar is undefined, as well as foo.
Answer: The way I read this: You're not returning bar, you're returning the result of bar('test 1'); which is undefined.
Comment: indeed. (hammer on the head)
Comment: He does not call `bar` with anything.
Comment: Yes, I know that my comment is not literally correct, but he quickly got what I meant. The function I called "bar" is actually anonymous.
Answer: You have extra parenthesis around your function. This turns it into a self invoking anonymous function.
This means that foo is set to its return value!
All you need to do is remove the extra parenthesis.
http://jsfiddle.net/Xfh58/
Comment: *You have extra parenthesis around your fuction. This turns it into a self invoking anonymous function.* — No. They turn it into a function expression. It is the pair of parenthesis that *follow* it that make it self-invoking.
Comment: My bad, im sure the correct answers will get pushed to the top.
Answer: bar does not return a value, so foo doesn't as well.
Answer: tBecause the bar function does not return anything. A function that does not have a return value in javascript returns undefined.
If you change bar to this:
var bar = (function(t){
    return t;
})('test 1');

you foo will no longer be undefined.
Comment: `bar` is not a function

Javascript pattern behaves weird


Composition of everywhere discontinuous bijection with itself, limit, and continuity

Question:
Let $\phi$ be everywhere discontinuous bijection that maps $\mathbb R$ onto $\mathbb R$.
Define $\phi^n=\underbrace{\phi\circ \phi\cdots \phi}_{n\text{ times}}$ where $\circ$ is ordinary composition of functions.
Define $\psi= \lim_{n \to + \infty} \phi^n$
Can $\psi$ be everywhere continuous?

Some of my thoughts on this problem:
Since $\phi$ is a bijection so is $\phi^n$ for every $n \in \mathbb N$. Since limit should not destroy bijectivity I think that $\psi$ also is a bijection and if also everywhere continuous that means that it is everywhere strictly monotone so everywhere differentiable. And, I am not sure what to do next.
Answer: Sure.  For instance, it's possible that $\phi^n(x)\to 0$ for all $x$.  As a sketch of how to construct such a $\phi$, build its orbits one by one by a transfinite recursion of length $\mathfrak{c}$.  In each step, you just pick a $\mathbb{Z}$-indexed sequence of new points converging to $0$ to be a new orbit.  All you have to do is arrange that every point of $\mathbb{R}$ is eventually put in an orbit and you avoid continuity at any point, which is easy (for instance, you can easily arrange that the image of every interval is dense, using just the first $\omega$ steps of the construction).
Note that $\lim\phi^n(x)=\lim\phi^n(\phi(x))$ (assuming either limit exists), so $\psi$ must satisfy $\psi(\phi(x))=\psi(x)$.  So $\psi$ can actually never be injective (assuming it is defined in the first place).
Comment: I gave you +1, but I am not completely sure in your argument.
Comment: How can $\phi^n \to 0$ if $\phi^n (\mathbb R)=\mathbb R$?
Comment: Ignoring the discontinuity condition, consider the example $\phi(x)=x/2$, for instance.
Comment: Ignoring the discontinuity condition ignores the whole question.
Comment: @Clayton I am having internet connectivity problems, I do not repeat the comments, they just come in pairs. I do not know why.
Comment: @AnteP.: Ah. This has happened to me on a handful of occasions. Sorry for the confusion; I thought you were being borderline belligerent.
Comment: I don't know why you think $\phi^n\to 0$ should contradict $\phi^n(\mathbb{R})=\mathbb{R}$, but it seems unlikely that your intuition for this has anything to do with the discontinuity condition.  If you want any additional explanation you will need to explain why you think $\phi^n\to 0$ and $\phi^n(\mathbb{R})=\mathbb{R}$ are incompatible.
Comment: @EricWofsey I do not know why, I am not able now to prove that.


Conditional probability selecting a number and flipping a fair coin.

Question: One of the numbers 1, 2 or 3 is selected at random. Then a fair coin is flipped that number of times. What is the probability that the number 3 was selected given:

no heads on the coin flip(s)
1 head
2 heads
3 heads

I know for three heads, the probability is of course $1$ or $100\%$ but I can't wrap my head around finding it for the other 3 conditions.
Comment: Just define some random varibles X,Y for the number out of $\{1,2,3\}$selected and the number of heads in X coin flippings resp. Note that $Y\tilde Bin(X,0.5)$. Then you can use the definition of conditional probability.
Answer: I think I solved my own problem here:
For the first case of no heads:

There is $\frac{1}{2}$ chance to get no heads if the number picked is 1.
There is $\frac{1}{4}$ chance to get no heads if the number picked is 2.
There is $\frac{1}{8}$ chance to get no heads if the number picked is 3.

So we can set this up: $\frac{\frac{1}{8}}{\frac{1}{2}+\frac{1}{4}+\frac{1}{8}}=\frac{1}{7}$
For the second case of one head:

There is $\frac{1}{2}$ chance to get 1 head if the number picked is 1.
There is $\frac{1}{2}$ chance to get 1 head if the number picked is 2.
There is $\frac{3}{8}$ chance to get 1 head if the number picked is 3.

So we can set this up: $\frac{\frac{3}{8}}{\frac{1}{2}+\frac{1}{2}+\frac{3}{8}}=\frac{3}{11}$
For the third case of two heads:

There is $\frac{0}{2}$ chance to get 2 heads if the number picked is 1.
There is $\frac{1}{4}$ chance to get 2 heads if the number picked is 2.
There is $\frac{3}{8}$ chance to get 2 heads if the number picked is 3.

So we can set this up: $\frac{\frac{3}{8}}{\frac{0}{2}+\frac{1}{4}+\frac{3}{8}}=\frac{3}{5}$
For the last case, its clear that the probability is 1.
Answer: There 14 possibilities of tosses. Suppose you are given that there is 1 head flipped. Out of the 14 possibilities, there are only 6 that have 1 head exactly. Out of those 6, 3 come from having 3 flips. Thus the probability is 1/2.
P(A|B) = $\frac{P(A \bigcap B)}{P(B)}$ = $\frac{\frac{3}{14}}{\frac{6}{14}}$ = $\frac{3}{6}$.
The rest are done similarly.


Add DNS record to zone that I don't administer

Question: TL;DR - I want to add a DNS service record to a zone that our parent company manages in our local DNS server since parent company won't help but don't want to maintain an entire copy of their primary zone in order to do it.
Full story
I manage a small remote office (our company was just acquired by a large company) with 20 people and lots of local servers for engineering and testing purposes.  I have a Windows Server 2008 machine setup with DNS running that resolves all of our local names and then forwards all other unknown names up to megacorp's internal DNS server via server-level forwarding.  So far this works great.
However, we here at minicorp were recently switched to megacorp's Exchange server.  When we configure our Outlook clients to connect to the Exchange server we can connect up, but we get the infamous "the name on the security certificate is invalid or does not match" warning.  This is because the domain name in the certificate that megacorp uses doesn't match the domain name for use in Outlook auto discovery mechanism.  For the most of megacorp's users this isn't an issue since they're on the active directory which pushes out the proper autodiscovery URL via SCP.  Since we here in minicorp won't be joining the AD for a while we're stuck with this issue.
Microsoft describes some ways to fix it here:
https://support.microsoft.com/en-us/kb/2772058
Megacorp's IT folks are overwhelmed with higher priority issues (nice way of saying they're of no help to minicorp for this problem) so I need to figure out a way to solve this without requiring them to make changes.
According to that Microsoft article, the 'proper' way to handle this is via SCP but since AD isn't an option we can't go that route.  So Outlook falls down to the #3 option which tries the autodiscover.megacorp.com URL which works but results in the certificate warning.  Also, in order to even make that work I've had to add a autodiscover.megacorp.com zone to my local DNS server since that name doesn't resolve in megacorp's DNS server for some reason.
The next option according to that article is to use a DNS service record to provide the proper autodiscover URL that matches the name in the SSL certificate.  The problem is that I don't administer the primary zone for megacorp's domain which finally leads me to my question...  Can I create a service DNS record for a zone that I don't manage?  Similar to how I created a 'autodiscover.megacorp.com' zone which contains just the proper IP address for that name but all other name requests under megacorp.com domain get forwarded up to megacorp's DNS server, could I do something like that but with a service record?  It's as though I want to 'subclass' megacorp's DNS so I can extend it to provide my own records.
Does such a thing exist or am I going in the wrong direction?  Maybe there is a different way to solve this certificate error?  I realize the proper way to handle this is for megacorp IT to implement this properly but... yeah...
Thanks for bearing with me through this question; it got a lot wordier than I intended.
Answer: Your idea will work. So long as you control the DNS servers used by the clients that you need to manipulate, there is nothing stopping you from intercepting the queries and replying however you like.
This answer comes with three caveats:

Clearly, this is an option of last resort. Make sure you have a good idea of how the DNS admins of Megacorp are going to respond when they learn that you're intercepting DNS records that they manage.
Don't Be A Dick. If Megacorp fixes the problem, you should make it a priority to stop doing this and relinquish control of their DNS data back to them.
Interception should be as specific as possible. If you take control of blah.example.com, you are intercepting all queries to the left of blah, not just blah. You're taking control of an entire subdomain, not just a specific name + record type combination.

Lastly, there's a Windows specific caveat here: the DNS snap-in can't be used to create an apex SRV record. You can use it to create the zone, but the record itself will  have to be populated using the commandline.
With that in mind:

Create a forward lookup zone with the exact name of the record you are intercepting. If you're trying to intercept a SRV record named _service._proto.example.com, you would create a zone named _service._proto.example.com. Following rule #3, avoid _proto.example.com and example.com. Doing so would end up intercepting much more than the traffic that you're trying to catch.
Define the SRV record at the top level of the zone using the commandline:

dnscmd /recordadd _autodiscover._tcp.example.com @ SRV 0 0 443 mail.example.com.
Comment: Ah hah!  That was it.  The command line allowed me to specify `@` as the node name which created the service record at the root of the zone which is where I want.  Thanks for all your help.
Comment: I need to create a SRV record at the top level (megacorp.com).  According to the Microsoft article it should be \_autodiscover.\_tcp.megacorp.com.  I wouldn't create a zone with that name because then a SRV record created within it would look like \_autodiscover.\_tcp.\_autodiscover.\_tcp.megacorp.com.  Instead I _think_ I need to create a megacorp.com top level zone and create the SRV record there.  However, when I do that I intercept ALL requests for megacorp which is not what I want...
Comment: You're confused, I think. The zone would in fact be called `_autodiscover._tcp.example.com`. If you use *Other New Records* in the DNS snap-in to add the record in this domain, the SRV record dialog will already be populated with `_autodiscover._tcp.example.com` at this point. If you're ever worried about whether or not a name you're entering will be treated as fully qualified, just append a `.` to the end. In this particular case, it's not necessary. I'd make sure that the trailing dot is present in the *Host offering this service* field, though.
Comment: OK, I've created the `_autodiscover._tcp.megacorp.com` zone.  I then add a New Resource Record to this zone (using the DNS snap-in).  The domain field is filled in with `_autodiscover._tcp.megacorp.com`, but the other fields are blank.  I tried leaving everything but the _Host offering this service_ field blank but it wouldn't let me.  So I fill in the fields as described by the Microsoft article but leave me in a situation I described in my previous email.  I think I'm still missing something.  Sorry for being slow...
Comment: Hmm. Might be a limitation imposed by the snap-in. Unfortunately, I only have read-only access to our Windows environment and can't lab this out for you. I can say that this is completely legal from a DNS standpoint, so I suggest trying to do this using [the command line](https://technet.microsoft.com/en-us/library/cc730624.aspx#BKMK_cmd). (link updated, the last one had some bad syntax)
Comment: Cool. I've updated the answer to reflect that. :)
Answer: I think if this were possible it would be a massive security vulnerability with DNS - you could put some static entries on host files if it's a small office or suppress the warning.
https://support.microsoft.com/en-us/kb/2783881
Method 4: Configure Outlook to allow the connection to the mismatched domain name
ImportantThis section, method, or task contains steps that tell you how to modify the registry. However, serious problems might occur if you modify the registry incorrectly. Therefore, make sure that you follow these steps carefully. For added protection, back up the registry before you modify it. Then, you can restore the registry if a problem occurs. For more information about how to back up and restore the registry, click the following article number to view the article in the Microsoft Knowledge Base:
322756 How to back up and restore the registry in Windows
To configure Outlook to ignore the name mismatch and connect to a specific HTTP endpoint, you can set or deploy a registry value. To do this, follow these steps:
Close Outlook.
Start Registry Editor. To do this, use one of the following procedures, as appropriate for your version of Windows.
Windows 10 and Windows 8: Press Windows Key + R to open a Run dialog box. Type regedit.exe and then press OK.
Windows 7: Click Start, type regedit.exe in the search box, and then press Enter.
Locate and then click to select the following registry subkey:
HKEY_CURRENT_USER\Software\Microsoft\Office\xx.0\Outlook\AutoDiscover\RedirectServers
Note You can also use the following registry subkey:
HKEY_CURRENT_USER\Software\Policies\Microsoft\Office\xx.0\Outlook\AutoDiscover\RedirectServers
Where xx is 12.0 for Outlook 2007, 14.0 for Outlook 2010, 15.0 for Outlook 2013, and 16.0 for Outlook 2016
Click the Edit menu, point to New, and then click String Value.
Type the name of the HTTPS server to which AutoDiscover can be connect without warning for the user, and then press ENTER. For example, to allow a connection to https://contoso.com, the first String Value (REG_SZ) name would be as follows:
contoso.com
You do not have to add text to the Value data box. The Data column should remain empty for the string values that you create.
To add more HTTPS servers to which AutoDiscover can connect without displaying a warning, repeat steps 4 and 5 for each server.
On the File menu, click Exit to exit Registry Editor.
Comment: DNS *is* a massive security vulnerability unless something like DNSSEC is in play. :) It's very possible.
Comment: yes but in the context it would be man in the middle against your own domain
Comment: Out of curiosity, I actually tried that method previously and it doesn't actually work.  I think the AutoDiscover\RedirectServers registry key is actually to suppress the warning about using the autodiscover URL to begin with (I also received that prompt but I checked don't ask me again).  This doesn't effect the certificate name mismatch like the KB article title suggests.  This is probably for the best given the security implications.
Comment: what are the security implications?
Comment: The MITM attack you mentioned. Someone could redirect the traffic from your Outlook client attempting to connect to the autodiscover URL and the Outlook client wouldn't warn the user of this.  The MITM could do all sorts of bad stuff like this.  Regardless, Microsoft should probably update that KB article since it isn't accurate.


Question about the use of the word "standard error" in several situations

Question: I'm now reading the book Computer Age Statistical Inference and I'm not sure what the standard error actually refers to in several cases.
In Page 9, the author defines for two data sets AML and ALL (they are chosen randomly from two large data sets) the two-sample t-statistic $t=\frac{\overline{\mathrm{AML}}-\overline{\mathrm{A} \mathrm{LL}}}{\widehat{\mathrm{Sd}}}$ and use this too find out whether their exists difference between the two original data sets. He says that "sd is an estimate of the numerator's standard deviation", but I cannot understand which standard deviation and what estimation he refers to.
Another one is that, say, we obtain a fitting curve (for example $y = ax + b$,etc) from a set of observed data $(x_i,y_i)$, then what does it mean by discussing the standard deviation of a point on the curve(this is mentioned in the Bootstrap Chapter)?
Comment: Efron and Hastie's book is a graduate level text intended for PhD students in mathematical statistics. You should not view it as an introductory statistics text! It reads as if it is introductory, but it actually is very subtle. If you're having trouble with the simplified two-sample t-statistic formula on page 9, then this book is not appropriate for you!
Comment: "Which standard deviation"? The standard deviation of the numerator (which is the difference between two means)! "Which estimation?" The point of the text is that you don't need to know. You only need to know that there exists some formula for the estimated standard deviation.
Comment: The S.E. of the *t* test can also be expressed as "the standard *deviation* of sample means of size *n*" & analogously "the standard *deviation* of differences in sample means of size *n*". But "standard error" makes for shorthand. It is also worth pointing out that in common nomenclature the sample standard deviation $s$ (alternately $\hat{\sigma}$) leaves implicit the "standard deviation *of what*" part, e.g., $s_{x}$ (or $\hat{\sigma}_{x}$ is explicit about being the standard deviation of $x$. Contrast with $s_{\bar{x}}$ (or $\hat{\sigma}_{\bar{x}}$): the sample SD of sample means size *n*.
Comment: @Gordon Smyth Thank you very much for your comment! Actually I have only learned about some basic statistics (about point estimation,hypothesis testing,confidence intervals, etc).  Which book would you recommend if I want to have a solid basis in statistics(if I am interested in machine learning)?
Answer: Variance/standard deviation is a concept associated to a random variable. In your case,

If we assume that one data point from AML comes from an independent sampling of a probability distribution, then the sampled mean $\overline{AML}$ is also a random variable, thus it (theoretically) has a standard deviation. Same goes for sampled mean $\overline{ALL}$ of ALL, and same goes for their difference $\overline{AML} - \overline{ALL}$. The text refers to this literal numerator.
As an observer however, we don't know exactly which probability distributions we are drawing from, and we only have observations. The best we can do is make estimations, and that's what the denominator intends to do.
I can't find what you are referring to in the text, so here's a guess: maybe you are talking about linear regression. Again you need randomness somewhere for standard deviation to make sense. Let's assume the points $(x,y)$ are drawn based on the assumption that
$$y = ax + b + \epsilon$$
where $a,b$ are fixed, and $\epsilon$ is a random error (for example, a Gaussian). Due to this random error, your "best-fit" straight line (whatever that means) $y \sim \hat{a} x + \hat{b}$ would likely not recover exactly $a,b$, but hopefully something close, as long as the error is "small".
In other words, the "randomness" of the error would cause "randomness" in $\hat{a}, \hat{b}$ of your best-fit straight line, which then allows us to again talk about standard deviation.
Comment: Thanks so much for your explanation! Now I completely understand these concepts.


Why the positional embeddings for different positions are not confined

Question: for this formulas PE(pos,2i)=sin(pos/(10000^(2i/modelDimension))) and PE(pos,2i+1)=cos(pos/(10000^(2i/modelDimension)))
we know PE for position i follows: [sin(i/denominator[0]),cos(i/denominator[0]), sin(i/denominator[1]),cos(i/denominator[1]), sin(i/denominator[2]),cos(i/denominator[2]),...]. note each element here is a proposed positional embedding element for an embedding element.
let's assume our embedding size is 1. so positional embedding for position i is sin(i/denominator[0]). also assume denominator[0] value is 0.2. so
PE(0,0)=sin(0)=0,
PE(1,0)=sin(5)=sin(1.59*Pi)=-.958,
PE(2,0)=sin(10)=sin(3.184*Pi)=-.544,
PE(3,0)=sin(15)=sin(4.777*Pi)=.6502
...

this just circulates the 2Pi. so in the sense of trying to assign a meaningful values for positional embeddings I dont realize how does it make sense. its not confined to sth like (i/max_sequence_length*pi/denominator[0]), that way if we used only cosine, the last words were assigned to -1 and first words assigned to 1. I mean some more understandable shifting embedding values into the space. if its not confined the positional embeddings dont obey a pattern the positional embeddings seem to be just random. how can not confining it makes sense?
Answer: That's the point of embeddings!
Using the time-series example from my answer to your other question, say that you want to create a weekly Fourier feature using the $\sin$ function as $\sin\big(\tfrac{2\pi t}{7}\big)$ where $t$ is the time index for days. The feature when plotted looks like below.

As you can see, I marked every 7th day with a red triangle and each of them has the same value of the "embedding" feature. That is the point, the feature represents 7th day with some numerical value. This enables us to use the feature in a regression model, where the numerical value would represent the day of the week.
The same in positional embeddings in the transformer model, the embeddings map the position of the word in the sentence to the embeddings space. Assuming that we are interested in "every seventh word" in a sentence (as in the time-series example above), we can use the embeddings to record the information. This enables you to model periodic trends in the data.

this just circulates the 2Pi. so in the sense of trying to assign a meaningful values for positional embeddings I dont realize how does it make sense. its not confined to sth like (i/max_sequence_length*pi/denominator[0]), that way if we used only cosine, the last words were assigned to -1 and first words assigned to 1.

If you did it like this, your model would be able to only work with texts of length smaller or equal to max_sequence_length, while we want it to work with texts of arbitrary length. Also, how would it differ from just using i as a feature? The point of positional embeddings is to encode cycles in the data.
Comment: @FarhangAmaji you are not altering anything, it's `sin((2 * pi * i) / m)` where `m` is taken from a different value in `denominator` per each embedding (feature).
Comment: ur answer about the similarity of this type of embeddings make sense for this question and not the other one. because this fourier method apparently captures the seasonality (along sequence dimension relations) (I dont fully get it now but I suppose it does). I had guessed it right, to separate the question, because ur answer seemed to target this one.
Comment: about `while we want it to work with texts of arbitrary length`, now we also pass the `max_sequence_length` to create embeddings. ofc I get that each row can be created independently this way (I mean rows of positional embeddings can be added to positional embeddings matrix this way) but in the way I suggest I cant.
Comment: at least I know now I should study how fourier captures seasonality, to understand the answer to this question. thank u
Comment: but one further question!! the fourier along the sequence dimension is for 1st data `sin(2*pi*1)`, for 2nd `cos(2*pi*2)`, for 3rd `sin(2*pi*3)` but here I have formula for `i position`  is equal to `sin(i/denominator[0])`. note I mean the Alternating sin and cosine in fourier is along the sequence dimension but in my formula 1st thing: is Alternating in embedding dimension, 2nd thing: is not Alternating in sequence dimension. did I get the formula wrong or its the same as the original paper of `attention is all u need`?
Comment: https://otexts.com/fpp3/useful-predictors.html#fourier-series
`Fourier terms are given by`. yes in my case I am not alternating it but the fourier does it.
Comment: dont we in fourier check different `m`s to check the which `m` works better? but here the denominator is fixed!! I think I should restudy that fourier seasonality thing better. if u have sources I apprecitate it


Using Riemann-Lebesgue lemma

Question: I am reading a paper by VAALER. He is using Riemann-Lebesgue lemma and saying that below function tends to $0$ as $N \to \infty$
$$\int_{-2}^{2} \frac{\pi t}{\sin \pi t}(\cos \pi(2N+1)t)e^{2 \pi i t z} dt$$
Before this he has not written anything.
I am not able to understand why we can use that theorem. If you can give any hint.
Thanks
Comment: @Mattos Aren't you confusing $t\to\infty$ and $N\to \infty$ here? the $\cos(\pi(2N+1))$ is the part with the parameter going to $\infty$.
Comment: Could you please state the proposition or theorem you are using.If you can share a link please share . Thanks for help.
Comment: @HitendraKumar A relevant question here is: do you know the statement of the Riemann-Lebesgue lemma? If so, which of the assumptions is unclear to you here?
Comment: I know which says fourier coefficient goes to $0$ an N goes to infinity.
Comment: @HitendraKumar I cannot really parse what you just wrote. The R-L gives a conclusion (the limit of the integral is zero) under some assumptions. You say you are "not able to understand why we can use that theorem." **Why?** Which of the assumptions are you unclear about in order to apply the theorem?
Comment: @ClementC. Yes, I gave the wrong $f$.
Answer: Suppose $f$ is absolutely integrable on some finite interval $[a,b]$ of $\mathbb{R}$. Then one form of the Riemann-Lebesgue Lemma states that
$$
          \lim_{r\rightarrow\infty}\int_{a}^{b}f(t)\sin(rt+\phi)dt =0, \;\;\;\forall \phi\in\mathbb{R}.
$$
You can use this version to get what you want. The above holds for $\sin$ if $\phi=0$ and it holds for $\cos$ if $\phi=-\pi/2$. Then $2\pi(N+1)$ becomes $r$.

Using Riemann-Lebesgue lemma


Why is S.D. of the sample mean getting smaller as I increase the sample size?

Question: My guess is that if a take a sample with $n$ observations ($n$ = sample size), average them and plot it and repeating the same thing for a lot of times then I am getting "dupplicates along the way", meaning that observations which occured in the sample nr 1 could also occur in the sample nr $x$. So I don't always get new data, therefore my SD gets smaller.
It's a little bit strange/counter intuitive for me that repeating the same process of taking the average of a sample and plot it , again and again will get the sample mean closer and closer to the true pop. mean. But S.D. of the sample mean keeps varrying with the sample size as opposed to the mean of the sample.
Answer: The standard deviation of the sample mean is given by $$\sigma_{\bar x}=\frac{\sigma}{\sqrt{n}},$$ where $\sigma$ is the population standard deviation. Notice that it is not a function of the mean (let's call the mean $\mu.$) Since $\sigma$ is constant, $\sigma_{\bar x}$ is really just a function of the sample size, and as you can see from the formula, a larger sample size means a smaller standard deviation of the sample mean. This is intuitive - don't you expect that collecting more data will in general produce a less variable result for your sample mean?
Comment: I can understand the confusion though since the most common definition for the sample standard deviation $$s=\sqrt{\frac{\sum \left( x_i-\bar{x} \right )^2}{n-1}}$$ includes the sample mean.  Like your example, a computationally equivalent sample standard deviation (though less common form),  $$s=\sqrt{\frac{\sum x^2 - \frac{\left( \sum x \right )^2}{n}}{n-1}}$$ does not include the mean.


Contour integral with a logarithm squared: $\int_0^\infty \frac{\log^2 x \, dx}{(1+x)^2}$

Question: The integral I'd like to evaluate is $\int_0^\infty \frac{\log^2 x \, dx}{(1+x)^2}$. I consider the function $f(z) = \frac{\text{Log}^2 z}{(1+z)^2}$, which has a pole of order 2 at $z=-1$ and has a branch point at $z=0$. I set up the integral $\oint_C f(z) dz$ along the contour $C = C_1 + C_2 + C_3 + C_4 + C_5 + C_6$, which consists of $C_1$ going just above the branch cut from $0$ to infinity, $C_2$, which is a big half-circle, $C_3$, which is a piece along the real axis from infinity to a point infinitesimally close to $z=-1$, $C_4$, which is a small half-circle going around $z=-1$ clockwise, $C_5$, which is another small piece on the real axis, and, finally, $C_6$, which is a quarter-circle around the origin to close the contour.
Now, I take the branch with $\text{Log}(z) = \log(r) + i \theta$, $0 \le\theta<2\pi$. Then the piece along $C_1$ is the integral $I$ I want to calculate. The pieces along $C_2$ and $C_6$ are zero when we take appropriate limits, but I'm not sure what to do with all the other pieces, since we can't really (can we?) write them in a way "$\text{something} \cdot I$", because of the singularity at $z=-1$. I know what I would do in the case of $1+z^2$ in the denominator, but not in this one. Suggestions?
Comment: The way you are sketching out the solution gives you, as the contour integral $$-PV \int_0^{\infty} dx \frac{(\log{x}+i \pi)^2}{(1-x)^2} + i \epsilon \int_{\pi}^0 d\phi \, e^{i \phi} \frac{\log^2{(e^{i \pi}+\epsilon e^{i \phi})}}{(\epsilon e^{i \phi})^2} \\ + \int_0^{\infty} dx \frac{\log^2{x}}{(1+x)^2}$$  This forces you to evaluate a wholly different principal value integral and is sort of leading you astray.  I prefer the way I outline using a keyhole contour which, while it requires using a log cubed, gets us there.
Answer: We have
$$\int_1^{\infty} \dfrac{\log^2(x)}{(1+x)^2}dx = \int_1^0 \dfrac{\log^2(1/x)}{(1+1/x)^2} \left(-\dfrac{dx}{x^2}\right) = \int_0^1 \dfrac{\log^2(x)}{(1+x)^2}dx$$
Hence, our integral becomes
\begin{align}
I & = \int_0^{\infty}\dfrac{\log^2(x)}{(1+x)^2}dx = 2\int_0^1\dfrac{\log^2(x)}{(1+x)^2}dx = 2\int_0^1 \sum_{k=0}^{\infty}(-1)^k (k+1)x^k \log^2(x)dx\\
& = 2\sum_{k=0}^{\infty}(-1)^k(k+1) \int_0^1 x^k\log^2(x)dx = 2\sum_{k=0}^{\infty}(-1)^k(k+1)  \cdot \dfrac2{(k+1)^3}\\
& = 4 \sum_{k=0}^{\infty} \dfrac{(-1)^k}{(k+1)^2} = 4\left(\dfrac1{1^2} - \dfrac1{2^2} + \dfrac1{3^2} - \dfrac1{4^2} \pm \cdots\right) = \dfrac{\pi^2}3
\end{align}
Comment: I'm aware of this derivation, but I'd like to use complex analysis.
Answer: I would consider the integral
$$\oint_C dz \frac{\log^3{z}}{(1+z)^2} $$
where $C$ is a keyhole contour about the real axis of radius $R$.  Then as $R \to \infty$ the integral is equal to
$$-i 6 \pi \int_0^{\infty} dx \frac{\log^2{x}}{(1+x)^2} + 12 \pi^2 \int_0^{\infty} dx \frac{\log{x}}{(1+x)^2} +i 8 \pi^3 \int_0^{\infty} dx \frac{1}{(1+x)^2} = i 2 \pi \operatorname*{Res}_{z=e^{i \pi}} \frac{\log^3{z}}{(1+z)^2}$$
Note that the definition of the keyhole contour implies that the pole at $z=-1$ is necessarily represented as $z=e^{i \pi}$, as $\arg{z} \in [0,2 \pi]$.
To evaluate the other integrals we consider similar contour integrals:
$$\oint_C dz \frac{\log^2{z}}{(1+z)^2} = -i 4 \pi \int_0^{\infty} dx \frac{\log{x}}{(1+x)^2} + 4 \pi^2 \int_0^{\infty} dx \frac{1}{(1+x)^2} = i 2 \pi \operatorname*{Res}_{z=e^{i \pi}} \frac{\log^2{z}}{(1+z)^2}$$
$$\oint_C dz \frac{\log{z}}{(1+z)^2} = -i 2 \pi \int_0^{\infty} dx \frac{1}{(1+x)^2} = i 2 \pi \operatorname*{Res}_{z=e^{i \pi}} \frac{\log{z}}{(1+z)^2}$$
Back substituting the other integral expressions into the first one, we find that
$$-i 6 \pi \int_0^{\infty} dx \frac{\log^2{x}}{(1+x)^2} + 12 \pi^2 \left [ i \pi \operatorname*{Res}_{z=e^{i \pi}} \frac{\log{z}}{(1+z)^2}-\frac12 \operatorname*{Res}_{z=e^{i \pi}} \frac{\log^2{z}}{(1+z)^2}\right ] \\ -i 8 \pi^3 \operatorname*{Res}_{z=e^{i \pi}} \frac{\log{z}}{(1+z)^2} = i 2 \pi \operatorname*{Res}_{z=e^{i \pi}} \frac{\log^3{z}}{(1+z)^2} $$
or
$$\begin{align}\int_0^{\infty} dx \frac{\log^2{x}}{(1+x)^2} &= \operatorname*{Res}_{z=e^{i \pi}} \frac{(2 \pi^2/3 )\log{z}+ i \pi \log^2{z} - (1/3) \log^3{z}}{(1+z)^2}\\ &= \left (\frac{2 \pi^2}{3} \right )\frac1{e^{i \pi}} + (i \pi) 2 \frac{i \pi}{e^{i \pi}} -\frac13 \frac{3 (i \pi)^2}{e^{i \pi}}\end{align}$$
Thus,

$$\int_0^{\infty} dx \frac{\log^2{x}}{(1+x)^2} = \frac{\pi^2}{3} $$
Comment: Thanks! I remembered vaguely that this "adding power" technique should work in case of a log, but it's nice to see exactly how. I'll up-vote once I get 15 points.
Comment: @some1: No problem.  Please note here how I did not need to evaluate the lower-order integrals directly, but rather expressed them in terms of their residues.  The result is a nice, nontrivial expression of the integral of a function times log squared in terms of the residue of the function times a cubic polynomial in log.  This works in general and not just for your integral here.
Comment: yeah, I know. By the way, what if we consider an equivalent integral (up to changing the variables): $\int_{-\infty}^{+\infty} \frac{dx x^2 e^x}{(1+e^x)^2}$, so that now we have an infinite number of singularities along the imaginary axis. The usual rectangular contour doesn't work here (you get the identity $4\pi^2 = 4\pi^2$). Is there any reasonable contour we can choose to calculate this integral without changing variables?
Comment: @some1: for a rectangular contour I would use a similar trick: consider the contour integral of $z^3$ rather than $z^2$.
Comment: OK, so "adding power" technique works here too. Great, thanks!


How to combat/prevent repeated unauthorized attempts to login to my postfix server?

Question: I recently setup my first postfix server and am loving life. :)
But, today I logged into the server to debug some connectivity issues that ended up being on my end, and noticed in the mail log that there was one IP that kept hammering the SASL login, and failing obviously. I banned the IP with ufw, but that's not a very efficient solution. What I'm left wondering is why this sort of behavior is allowed by default, and what I can do to mitigate against these types of attacks.

Why was this IP allowed to repeatedly fail to autheticate, and not blacklisted? What do I change to make that happen?
Is there some way I can setup notifications or alerts to this sort of failure pattern if I can't automatically handle the situation, and need to manually block the IP with ufw?
Is there any real harm in just letting these poop birds try to break into my system willy nilly? Should I be worried about this?
Comment: Look up fail2ban. It's designed for this.
Answer: Regarding point 1
For Debian based systems you could use fail2ban.
You can install it with sudo apt install fail2ban (or running it as root user, when you don't have sudo rights.)
If you are running a limited VM you can try denyhosts
To install this, you have to sudo apt install denyhosts
Both do the same, prevent intruders to bruteforce your Server, however fail2ban has the ability to check on a periode of time to prevent the same IP checking your server again
For point 2
You can setup Action on fail2ban and denyhosts to get notifications about the executed Actions.
And regarding point 3
If they gain access, they either make this device to a Zombie or Spam Sender or both, so dont use a generic password. My Servers are also checked daily from random IPs.
Comment: Regarding point 3: To stop the attackers, and harden your server, check out the [CIS Benchmarks](https://www.cisecurity.org/cis-benchmarks/) for your Server OS and apply the recommended settings.
Answer: ConfigServer Security & Firewall (CSF + LFD) does the job perfectly.
It ships with the Login Failure Daemon (lfd), which acts as a quasi real-time log parser. What it does is generate a rule on the fly to block the offending IP address in your firewall (iptables) after a predetermined number of failed attempts, and it can also send an alert by E-mail. A typical server exposed on the Internet is going to be probed by hundreds, thousands of attackers on a daily basis. So, expect to receive a lot of notifications.
Note that the block is not permanent, the IP address will be unbanned after a period of time.
LFD covers most common services such as SSH, SMTP, POP etc out of the box, but you can add custom rules if needed (some understanding of regular expressions may be required since LFD does log parsing).
Even if your server is well protected, it doesn't have to allow that hammering to take place - it's still a lot of wasted resources. Better to block them right away.
Comment: but thats nothing else as a administrative panel which would lead to a oos situation on serverfault.com


Complex View Involving Separate Entities / Taxonomy Vocabulary / Content - Distinct

Question: Given the following Content Type: Smartphone
Taxonomy Vocabulary: OS: Android / iOS / Windows / Blackberry
Taxonomy Vocabulary: Color: Red / Blue / White / Black / Yellow
OS and Color is a Taxonomy Vocabulary which is term referenced in the content type smartphone.
Now the question is:
How do you setup a view to display only the COLORS that are available for the Android OS? I do not care about what phone it is. Example of this contextual path would be: example.com/android-colors
That in effect would just give me a list of all available colors that androids are in. Since OS and color has no direct relation, you would have to create a view of smartphones then GROUP THEM BY color while the contextual filter grabs the %android% arguement via the path.
The problem with this is that there will be thousands of records since each result is unique since your querying the smartphone table. Distinct setting in the query dialog box does not apply since each result is technically not distinct.
Comment: Couldn't you do example.com/%OS/%COLOR? The first taxonomy ID argument for OS and the second for color?
Comment: no you cannot because you don't know which colors there are since OS and COLOR are not linked at all. The only thing matching these 2 taxonomy vocabularies is the content type "smartphone", but when you create a view to display the smartphones, you will get hundreds of results of smartphone colors.
Comment: If you have example.com/android, that will show all phones that are using Android. If you have example.com/android/blue, it wil show you all phones that are running Android and that are colored blue. That is how the terms are linked. Isn't that what you're looking for?
Comment: no but i am looking for a list of colors that are available for android. how do you know there was a blue android in the first place when there isn't one!? just imagine a page with a list of colors that the android phones are available in and thats it... a list of colors. not a specific color.
Comment: I get it now, I think my answer will help.
Answer: You can cheat a little and use Views Limit Grouping to help do this.
I created a view of smart phones with the path being smart-phones/%/colors. The only argument I need is for the OS. Add a contextual filter for the mobile OS using "Content: Has taxonomy term ID", filter by the term name. Under your fields to be shown, just select the color.
Using the Group Field (with Limit) formatter, we'll group by the color and show 0 items. Now if there are smart phones that have a color selected, it should show up in this list. In my screenshot you can see that I am only showing Blue and Orange, but in my taxonomy I actually have Blue, Green, Orange, and Red available - but I have no phones that are Red or Green.
From here, all you need to do is rewrite the color url to go to whatever other view you would like, such as smart-phones/%OS/%Color


Force of interest

Question: Suppose the force of interest over the time interval $[1,3]$ is given by $\delta (t) =\alpha +\beta t^{-1}$. If $100$ invested at $t=1$ grows to $120.74$ at $t=2$ and $100$ invested at $t=2$accumulates to $114.00$ at $t=3$. Find $\alpha$ and $\beta$.
$A(2)=e^{\int^2_1 (\alpha+\frac{\beta}{t})dt=\frac{120.74}{100}}$
$A(3)=e^{\int^3_2 (\alpha+\frac{\beta}{t})dt=\frac{114}{100}}$
$\rightarrow \alpha+\ln {2^\beta}=\ln{\frac{120.74}{100}}$ and
$\alpha + \ln{\frac{3}{2}^\beta}=\ln{\frac{114}{100}}$
Eliminating $\alpha$
$\beta=\frac{\ln{\frac{114}{100}}}{\ln{\frac{4}{3}}}$
But this does not yield the answer.
Comment: Can you clean up the problem statement - something seems wrong as written?
Answer: The expressions
$$A(2)=e^{\int^2_1 (\alpha+\frac{\beta}{t})dt=\frac{120.74}{100}}$$
$$A(3)=e^{\int^3_2 (\alpha+\frac{\beta}{t})dt=\frac{114}{100}}$$
are  meaningless.
I think you wanted to write
$$A(2)=e^{\int^2_1 (\alpha+\frac{\beta}{t})dt}=\frac{120.74}{100}$$
$$A(3)=e^{\int^3_2 (\alpha+\frac{\beta}{t})dt}=\frac{114}{100}$$
From this we get (by taking logarithms)
$$\int^2_1 (\alpha+\frac{\beta}{t})dt =\log{\frac{120.74}{100}}$$
$$\int^3_2 (\alpha+\frac{\beta}{t})dt=\log{\frac{114}{100}}$$
and further
$$\alpha+ \beta  \ln2 =\log{\frac{120.74}{100}} $$
$$\alpha+ \beta  \ln\frac{3}{2} =\log{\frac{114}{100}} $$
This results in
$$\beta=\frac{\log 120.74-\log{114}}{\log4-\log3}=\frac{\log\frac{120.74}{114}}{\log\frac{4}{3}}$$
Answer: You did the main , stating A(2) and A(3) and computing the integrals ...
$A(2)={e^{\int^2_1 (\alpha+\frac{\beta}{t})dt}= e^{{\alpha} + {\beta} \cdot \ln(2)} = \frac{120.74}{100}}$
$A(3)={e^{\int^3_2 (\alpha+\frac{\beta}{t})dt}= e^{{\alpha} + {\beta} \cdot \ln(3/2)}=\frac{114}{100}}$
Then we have merely a system of 2 linear equations with 2 unknowns ${\alpha}$ and ${\beta}$ :

${\alpha}+ {\beta} \cdot \ln(2) = \ln(1.2074)$
${\alpha} + {\beta} \cdot \ln(\frac{3}{2}) = \ln(1.14)$

and the solutions are ${\alpha} \approx 0.0500697$ and ${\beta} \approx 0.199668$
I'm looking for the error, not understanding well what you did after Eliminating $\alpha$ , but miracle173 had found them both in your calculus and the mine. Now it is fixed.
Comment: @miracle173 : I don't understand what you mean. The purpose is not to detail how to solve the linear system, the OP knows the integrals ... My last sentence is just friendly politeness :)
Comment: so $$\beta = \frac{1.2074-1.14}{\ln(2)-\ln(\frac{3}{2})}$$
Comment: I wanted to point at the fact that your $\beta$ and th OP's $\beta$ have a different numerator. But as far as I can see your $\beta$ is wrong, too. I posted the correct $\beta$  in an answer.
Comment: @miracle173 : I computed something similar to your expression using a determinant resolver and the decimal values are the same. What did you find different ? [wolfram to compute the expression](http://www.wolframalpha.com/input/?i=X+%3D+%7B1.2074-1.14%7D%2F%7Blog+2+-log+1.5+%7D) while the mine with a decimal less is *0.23429*
Comment: check the numerators of $\beta$. yours is $1.2074−1.14$ mine is $\log 1.2074− \log 1.14$
Comment: @miracle173 yes ! you are true ! it is fixed , TY !
Comment: I think you should also fix the wrong format of the equations. I assume this format led to your wrong solution.

Force of interest