How do I programmatically fix local menus to be shown only for a content type?

Question: I am using the following lines in a links.task.yml file.
x.nodename_updates:
  route_name: view.great_view_name1.page_1
  base_route: entity.node.canonical
  title: 'Updates'
  weight: 50

x.nodename_subscriptions:
  route_name: view.great_view_name2.page_1
  base_route: entity.node.canonical
  title: 'Subscriptions'
  weight: 50

The submenus are shown on all nodes. I would like to show them for a single content type, but when I use the entity name in the base_route such as entity.TYPE.canonical, it doesn't work. It works for other entities that are defined in classes with annotations.
I know it is possible to fix it through hook_menu_local_task_alter(), but this is something I believe can be fixed within the links.task.yml file.
Answer: I don't konw if there's a better way to do it now but few years ago I did it using a custom access: https://stackoverflow.com/questions/36496998/drupal-8-how-to-add-task-and-contextual-links-for-specific-node-type/36636263#36636263
In my case it was easier because I was creating the routes in my module.
Since your routes are created by views you would need to implement a RouteSubscriber to alter the route, add the _custom_access and _node_types requirements.
/!\ Warning: I am not sure since I never tried it on views routes but it might conflicts or breaks the rules you've set from the views UI to access this view. It should be compatible with a _permission rule, maybe not with an _entity_access rule.
yourmodule/yourmodule.services.yml
services:
  yourmodule.route_subscriber:
    class: Drupal\yourmodule\Routing\RouteSubscriber
    tags:
    - { name: event_subscriber }

yourmodule/src/Routing/RouteSubscriber.php
<?php

namespace Drupal\yourmodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('view.great_view_name1.page_1')) {
      $requirements = $route->getRequirements();
      $requirements['_custom_access'] = '\Drupal\yourmodule\Access\ByNodeTypeAccessCheck::access';
      // Replace 'my_node_type' with the name of the node type you want.
      // Since it's an array, you can add more than one node type.
      $requirements['_node_types'] = ['my_node_type'];
      $requirements['node'] = '\d+';
      $route->setRequirements($requirements);

      $options = $route->getOptions();
      $options['parameters'] = $options['parameters'] ?? [];
      $options['parameters']['node'] = [
        'type' => [
          'entity:node',
        ],
      ];
      $route->setOptions($options);
    }
  }

}

yourmdule/src/Access/ByNodeTypeAccessCheck.php
namespace Drupal\yourmdule\Access;

use Drupal\Core\Access\AccessCheckInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\node\NodeInterface;
use Symfony\Component\Routing\Route;

/**
 * Check the access to a node task based on the node type.
 */
class ByNodeTypeAccessCheck implements AccessCheckInterface {

  /**
   * {@inheritdoc}
   */
  public function applies(Route $route) {
    return NULL;
  }

  /**
   * A custom access check.
   *
   * @param \Drupal\node\NodeInterface $node
   *   Run access checks for this node.
   */
  public function access(Route $route, NodeInterface $node) {
    if ($route->hasRequirement('_node_types')) {
      $allowed_node_types = $route->getRequirement('_node_types');
      if (in_array($node->getType(), $allowed_node_types)) {
        return AccessResult::allowed();
      }
    }
    return AccessResult::forbidden();
  }

}

Answer: There's no way to do that entirely within links.task.yml.
If you see the documentation, you'll see that the only possible keys are:

route_name: The machine name of the local task route - this also
determines where it's displayed.
title: The title of the local action. By default, it will be passed through t() and localized. Strings with spaces should use single quotes.
title_context (optional): context for t()
base_route: The route where the "root" tab (generally the top,
leftmost one) is displayed and which serves to group a set of tabs.
parent_id (optional): The plugin ID of the tab that is the parent -
only relevant for 2nd level tabs. If this is set, base_route should be
omitted and will be supplied from the parent
weight: (optional) The
integer weight (lower weight tabs are further left, default is 0).

None of these keys will help you with what you're trying to do.
Your options are to use hook_menu_local_task_alter(), as you've noted, or create a deriver class to Dynamically Generate Local Tasks.
From that same documentation page, your yaml would look something like:
example.local_tasks:
  deriver: 'Drupal\example\Plugin\Derivative\DynamicLocalTasks'
  weight: 100

And a deriver class something like:
namespace Drupal\example\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;

/**
 * Defines dynamic local tasks.
 */
class DynamicLocalTasks extends DeriverBase {

  /**
   * {@inheritdoc}
   */
  public function getDerivativeDefinitions($base_plugin_definition) {
    // Implement dynamic logic to provide values for the same keys as in example.links.task.yml.

    // Here you would check for your node canonical route and node bundle
    // to generate the task definition only if appropriate.
    $this->derivatives['example.task_id'] = $base_plugin_definition;
    $this->derivatives['example.task_id']['title'] = "I'm a tab";
    $this->derivatives['example.task_id']['route_name'] = 'example.route';

    return parent::getDerivativeDefinitions($base_plugin_definition);
  }

}

Comment: In the case asked by the OP, there aren't properties that can be changed only for a bundle. For example, the base route is the same for all the nodes (*entity.node.canonical*).
Comment: Thanks for the detailed and speedy response!


Variance of maximum of Gaussian random variables

Question: Given random variables $X_1,X_2, \cdots, X_n$ sampled iid from $\sim \mathcal{N}(0, \sigma^2)$, define
$$Z = \max_{i \in \{1,2,\cdots, n \}} X_i$$
We have that $\mathbb{E}[Z] \le \sigma \sqrt{2 \log n}$. I was wondering if there are any upper/lower bounds on $\text{Var}(Z)$?
Comment: Both answers to http://stats.stackexchange.com/questions/105745 provide approximations to the standard deviation (and therefore to the variance), using analyses that might produce upper or lower bounds.
Comment: Just to get you started, i think you will find that $Var(Z) \le \sigma^2$ (equality is achieved at n = 1), and Var(Z) decreases as n increases. I leave it to you to provide that tighter bound as a function of n.
Comment: The sample max minus the sample min is known as the [studentized range](https://en.wikipedia.org/wiki/Studentized_range) and follows the studentized range distribution if the underlying random variables are IID normal. That's at least vaguely related to what you're asking... (could give a starting point for reading). Back on your specific question, I'm sure you could write a Monte-Carlo simulation rather easily to find a practical answer.
Comment: Related:  http://stats.stackexchange.com/questions/77110/mathbbe-and-variance-of-the-maximum-of-independent-mathcaln-mu-i-sig
Answer: You can obtain upper bound by applying Talagrand inequality : look at Chatterjee's book (Superconcentration phenomenon for instance) .
It tells you that ${\rm Var}(f)\leq C\sum_{i=1}^n\frac{\|\partial_if\|_2^2}{1+\log( \|\partial_i f||_2/\|\partial_i f\|_1)}$.
For the maximum, you get $\partial_if=1_{X_i=max}$, then by integrating with respect to the Gaussian measure on $\mathbb{R}^n$ you get
$\|\partial_if\|_2^2=\|\partial_if\|_1=\frac{1}{n}$ by symmetry. (Here I choose all my rv iid with variance one).
This the true order of the variance : since you have some upper bound on the expectation of the maximum, this article of Eldan-Ding Zhai (On Multiple peaks  and moderate deviation of Gaussian supremum) tells you that
${\rm Var}(\max X_i)\geq C/(1+\mathbb{E}[\max X_i])^2$
It is also possible to obtain sharp concentration inequality reflecting these bound on the variance : you can look at http://www.wisdom.weizmann.ac.il/mathusers/gideon/papers/ranDv.pdf
or, for more general gaussian process, at my paper
https://perso.math.univ-toulouse.fr/ktanguy/files/2012/04/Article-3-brouillon.pdf
In full generality it is rather hard to find the right order of magnitude of the variance of a Gaussien supremum since the tools from concentration theory are always suboptimal for the maximum function.
Why do you need these kinds of estimates  if I may ask ?
Comment: Thanks a lot. This helps a lot.

I was dealing with the problem where I was trying to bound probability of errors in estimating the length of runs of 0 in a bit stream from observations through a deletion channel. After a Gaussian approximation, the max seemed to be a natural estimator, and I found bounding its performance quite non-trivial. In my particular problem, I could find a way round it by reducing it to a Gaussian MMSE estimation problem.
Comment: Note that the Talagrand inequality, is an improvement of the Poincaré inequality satisfied by the standard Gaussian measure. There is more about this in Cordero-Ledoux's article "Hypercontractive measures, Talagrand's inequality and influences".
Comment: @TanguyKevin what's C in the lower bound?
Answer: More generally, the expectation and variance of the range depends on how fat the tail of your distribution is. For the variance, it is $O(n^{-B})$ where $B$ depends on your distribution ($B = 2$ for uniform, $B = 1$ for Gaussian, and $B = 0$ for exponential.) See here. The table below shows the order of magnitude for the range.


What does a double bass string eliminator do?

Question: On some double basses, I've seen the players with this on their strings:

I found out that it was an eliminator.
But what does a double bass eliminator do?
Answer: It's called, at least in cello-land, a "wolf-eliminator."  The intent is to dampen or stifle off-pitch frequencies.
Comment: viola/violin too.
Answer: Because the string is quite long between the bridge and the tailpiece, it has a life of its own. It can, and will, produce notes, often using sympathetic vibration, which are audible. Particularly when an instrument is amplified. These sounds are sometimes called 'wolf tones'. Anything which will dampen vibrations that are not wanted, as here, will be effective. The eliminator is used to stop unwanted vibrations being heard, especially when a pick up/mic is used to make the instrument heard better, as in stage work.Cheap and cheerful, less than $10 from Jazzazart. Anything would do, a sponge, etc., but it doesn't look pro.
Comment: A sponge will probably dampen (sorry for the pun) frequencies you wanted to keep as well.
Comment: Ha ha.The frequencies produced from behind the bridge, I'd have thought would not be useful to a player anyway.


Picking the point on a sphere furthest from all points?

Question: 2D Version of the problem (With tentative solution)
You are given a set of vectors $V = \{v_i\}$ And you are guaranteed that they are all unit length.
You want to find a vector $x$ such that $x$ is as far away on the surface of the circle from all other points.
In 2D you can pick a random $v_0$ then pick an orientation for your space. Sort all $v_i$ relative to the angle they form with $v_0$. Then for every pair of consecutive points, pick the largest oriented angle (i.e. angles > $\pi$ are allowed). Add a new point at the bisectrice of this angle.
So for example in this case, the point F is added in between points E and B because they form the largest angle.

3D version of the problem
I am looking for solving the same problem in 3D, i.e. finding a point such that it maximizes it's geodesic distance/angle with its closest point in the original set. More formally.
Given $v_i$ s.t $\|v_i\| = 1$ find $x$ such that $\|x|\ = 1$ and for all $v in \mathbb{R}$ with $\|v\| = 1$, $x \cdot v_\alpha <= v \cdot v_\beta$ where $v_\alpha$ is the closest point to $x$ and $v_beta$ is the closest pint to $v$.
I am struggling finding a solution because you cannot sort points in 3D by angle the way you can in 2D. And in 2D you can easily define where to add the point based on a triangle, but the equivalent terahedron in the 3D problem is trickier to define.
Answer: In 2D, we are motivated to bisect the angle because the point furthest from all given points has to be at the same distance from two of them. If the maximizer were, theoretically, closer to one point than all the others, then you could move it away from that point by a tiny bit and improve the minimum distance.
Similarly, in 3D, we can start there: given the points $v_1, v_2, \dots, v_n$ on the sphere, the optimal point $x$ minimizing $\max\{x \cdot v_1, \dots, x \cdot v_n\}$) cannot have one single point $v_i$ such that $x \cdot v_i > x \cdot v_j$ for all $j \ne i$. If that were so, we would just move $x$ by a tiny amount away from $v_i$, decreasing $x \cdot v_i$ while possibly increasing all other angles, and possibly improving the minimum angle.
What's more, if we reach a point where $x \cdot v_i = x \cdot v_j$, we are still not done. In this case, $x$ lies on the great circle of all points on the sphere equidistant from $v_i$ and $v_j$: the intersection of the sphere with the plane perpendicular to $v_i - v_j$. There is (usually, see caveat later) some direction to go in on the great circle that decreases both $x \cdot v_i$ and $x \cdot v_j$. So in fact, we know that the best point $x$ must satisfy $x \cdot v_i = x \cdot v_j = x \cdot v_k$ for three points $v_i, v_j, v_k$.
At this point, we can solve the problem by a finite search: for each triple $\{v_i, v_j, v_k\}$, find the two points on the circle such that $x \cdot v_i = x \cdot v_j = x \cdot v_k$, and then see which of the $2\binom n3$ points we found is best.
There is, finally, a caveat that some very unbalanced point configurations might defy the analysis above. Suppose that $v_i$ and $v_j$ are the two points closest to $x$, $x \cdot v_i = x\cdot v_j > x \cdot v_k$ for all other points $k$, and the reason we cannot move $x$ along the great circle of points equidistant from $v_i$ and $v_j$ is that $x$ is already the point on that circle furthest from $v_i$ and $v_j$. (It is really weird that $v_i$ and $v_j$ are the two points closest to $x$, and yet $x$ cannot get any further away from them, but it can happen when all the other points are contained in a spherical cap between $v_i$ and $v_j$.)
There are $\binom n2$ more points of this type: they satisfy $x \cdot v_i = x \cdot v_j$ as well as $x \cdot (v_i \times v_j) = 0$, so once again we can find such a point for each pair $\{v_i, v_j\}$ and check them as well. Actually, for each pair $\{v_i, v_j\}$, this system of equations gives us two points on the sphere; we might as well check them both, even though one of them is just the midpoint of the chord joining $v_i$ to $v_j$ and definitely isn't optimal.
Comment: Actually, with cross products, very concretely. We have $x \cdot (v_i - v_j) = x \cdot (v_i - v_k) = 0$, so $x$ is perpendicular to $v_i - v_j$ and $v_i - v_k$. Take $(v_i - v_j) \times (v_i - v_k)$, normalize it, and take both signs. (But also we can just solve it as a system of linear equations.)
Comment: I am a little confused when you say we can solve the 2 systems you described. How do you find the two solutions for the first case for example?
Comment: I see, and then we do the same for the degenerate case by treating the output of the cross product as a new point.
Comment: I am not sure if this is correct or I am just confused.

Consider a set of 3 points such that they lie in a great circle of the sphere and such that 2 lie on the diamteter and the third forms an isoceles triangle.

In the first case, the cross product yields points perpendicular to this triangle, neither of the 2 directions actually maximizes the distance. So the first construction fails>

in the second construction we produce  3 points through the cross product, one will produce nonsense as the 2 vectors are colinear.
Comment: The other 2 will lie orthogonally to this triangle, by construction. However neither these points nor their antipodes maximize the angle I think.
Comment: I don't see the first construction failing. We can say that the 3 points are $(1,0,0)$, $(-1,0,0)$, and $(0,1,0)$. Then the first case will tell us that $(x,y,z) \cdot (1,0,0) = (x,y,z) \cdot (-1,0,0) = (x,y,z) \cdot (0,1,0)$, or $x = -x = y$, which tells us that we're looking for a point $(x,y,z)$ with $x=y=0$. This gives us the points $(0,0,1)$ and $(0,0,-1)$ which really are equidistant from the 3 given points, and in fact both of the are valid candidates for being as far as possible from all 3 points.
Comment: (The case where two points $v_i, v_j$ lie on a diameter is actually an even more unusual case of the degenerate case; here, all points equidistant from $v_i$ and $v_j$ are at the same distance from them. But I do not think we ever need to worry about that degenerate case, unless they are the only two points.)
Comment: @Misa Lavrov the reason I caught it is percisely because I ran into it in the wild lol.
Answer: Take two points $A$ and $B$ on the circle's circumference, If $O$ is the center then, there are two angles formed viz. $\angle AOB = X$ and $\angle (360 - \angle AOB) = Y$
$X + Y = 360$
Both $X$ and $Y$ are (angular) distances and you want $X$ and $Y$ to be as large as possible.
Suppose there's an upper limit to the values $X$ and $Y$ can take on, say U. Then for both $X$ and $Y$ to be as large as possible, $X = Y = U$ i.e $X - Y = 0$
i) $X + Y = 360$
ii) $X - Y = 0$
Ergo,
$X = Y = 180$ degrees.
For a point to be as far away as possible from all other points on a circle, it must, cogito, satisfy this condition.
Comment: You are not really addressing the problem at all. The question is, given a point distribution on the sphere, find a new point that is the furthest possible from all other points.

Your answer does not provide any insight into that problem and seems to be out of subject.


Swift - performSegueWithIdentifier in thread

Question: i've got this type of problem :
With my app i'm able to connect my iPhone with a BLE device so when i connect their together i'm transported into an another view.
Into this view i've to check always if i'm connected yet in a thread func.
If my connection is lost i've to call the performSegueWithIdentifier method.
But... When i do it, xCode give me back a bad report that says :

This application is modifying the autolayout engine from a background
  thread, which can lead to engine corruption and weird crashes. This
  will cause an exception in a future release.

This is my short code :
override func viewDidLoad(){
  super.ViewDidLoad()
  let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
  dispatch_async(dispatch_get_global_queue(priority, 0)) {
    while(true){
      if(serial.connectedPeripheral == nil){
        self.GoBackToBLE()
      }
    }
  }
}

I want to precise that i can't use the method dispatch_get_main_queue because if i use that i can't do anything else into the view for example if i have a button I want to be able to press it and if i use dispatch_get_main_queue method i can't.
any suggestions? thanks a lot
Answer: You shouldn't do anything related to UI in dispatch_get_global_queue
you can split the things to run into 2 parts, 1 is related to UI other one is doing network calls/calculations etc.
override func viewDidLoad(){
  super.ViewDidLoad()
  let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
  dispatch_async(dispatch_get_main_queue(), { () -> Void in
    // do the ui stuff here
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in
      // do everything which is not ui
    })
  })
}

Comment: So if I have to change the view using the perform segue I have to put that method into the main_queue right?
Comment: yes, but what is in GoBackToBLE? you can split this function into 2 different functions.
Comment: Gobacktoble is only the function that I've tried to use for change view into this function there is only the prepare for segue method!
Comment: So than it should move to main_queue.
Comment: Thanks. This evening when I turn back to home I'll tell you if it works or not


Call jquery function from MVC Action method

Question: function AddScheduledCandidate() {

if (ValidateScheduledCandidate()) {
    InsertGoogleEvent($('#comment').val(), $('#SchDateTime').val() );

    $.post(WebsiteURL + 'VideoRepository/AddScheduledCandidate', { id: $('#hdnId').val() }, "json")
                            .done(function (response) {

                                    window.location.href = response.Url;
                            })
    }
}

The problem in above code is that my page is redirected before google calender info is inserted. It is because I know jquery code doesn't execute line by line and before completing google calendar event, redirect code is fired and google calendar record is not inserted.
Any Help will be highly appreciated.
Thank you
Comment: Can u post code for insertgoogleevent?
Comment: Title and question seems to be contradictory:)
Comment: I wrote that title because if I can call javascript from mvc action, the page redirect would not have been happened until the script execution is completed.
Answer: It seems insertgoogle event is async server call so try something like below to sync call .
function AddScheduledCandidate() {

if (ValidateScheduledCandidate()) {

$.post(WebsiteURL + 'VideoRepository/AddScheduledCandidate', { id: $('#hdnId').val() }, "json")
                        .done(function (response) {

 InsertGoogleEvent($('#comment').val(), $('#SchDateTime').val() );
                           window.location.href = response.Url;
                        })
}
}

Comment: You also need to put window.location.href in call back of insertgoogleevent function
Comment: I can't do so because I am using the same script in another pages as well.
Comment: @NadeemShaikh then you need to add some flag to function parameter to identify who is caller and make if condition based bahaviour there.


cannot find the symbol class NativeContentProvider

Question: When i compiled the program it's showing error
cannot find the class NativeContentProvider
The given below is the code i was trying to use but not working
    private void displayContacts() {

        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                if (Integer.parseInt(cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    Cursor pCur = cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
                            new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        Toast.makeText(NativeContentProvider.this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
                    }
                    pCur.close();
                }
            }
        }
    }

    public void clickFunction(View view){
        displayContacts();
    }

Where clickFunction is the onClick method of the button
Comment: what is name of the class you put this code ?
Comment: Post your logcat please.
Comment: looks like you've copied some code from the internet that contains a class name reference, just replace `NativeContentProvider.this` with `this`, and see if that works
Comment: I'm using that code in MainActivity class directly to access all the contacts.
Comment: @ARDANISH You should pass `CONTEXT`
Answer: Toast.makeText(NativeContentProvider.this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();

Here NativeContentProvider.this this should be activity or context !!
Comment: what's name of your Class in which you are using this. can you show me full class code.
Answer: Basic Syntax of Toast .
Toast.makeText(context, text, duration).show();

Try with
Toast.makeText(YourActivity.this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();

Or
  Toast.makeText(getApplicationContext(), "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();

Comment: tried both one but when i clicked the button it shows app has stopped. Open it again
Comment: error: cannot find symbol class NativeContentProvider, execution failed for task ':app:compileDebugJavaWithJavac'.


Why does flute fingering have to be so complicated?

Question: So, I have progressed on my flute. I'm now getting the notes that I am supposed to be getting. Here is what I noticed during my last flute practice as far as fingerings:
All open: C#
1 key down(counting that set of 2 keys at the very top of the flute as 1 key): C
2 keys down: B
2 keys down + thumb key: Bb
I'm only doing left hand fingerings for the moment so all my fingerings so far are second octave fingerings. No first octave fingerings yet.
But why does flute fingering have to be so complicated? I mean, there are 20 keys on the flute. That is twice as many keys as I have fingers. Not only that but the Bb in my list according to Second Octave Basic Fingerings has 3 different possible fingerings. I guess now that I found yet another fingering for that same Bb, that makes 4 fingerings. Why so many fingerings for a single note? And why 20 keys? Isn't 10 keys + harmonics(in other words overblowing) sufficient to get all the notes of the 3 octave range?
Comment: If you think the flute is complicated — check a bassoon. I have ten (10) keys for the left thumb.
Comment: Have you seen a piano recently?   Or try talking with a violinist.
Comment: If you think *that's* complicated, wait till you get to the third octave :)
Comment: OK, guys, you asked for it.  https://en.wikipedia.org/wiki/Wanamaker_Organ
Answer: This answer is slightly modified from a forum post I once wrote elsewhere to explain in detail why the flute's "complicated" design is the way it is.  It's long as anything, but it does answer the question, so why not?  TL;DR included at the bottom.
Let's start with the question about the B flat, and other alternate fingerings.  There are some notes with more than one fingering, but in those cases the secondary fingering is there to make certain quick combinations of notes easier to finger.  The "thumb B flat" key is there so that if you want to play a scale with a B flat, you don't have to bother using your right hand.  Imagine trying to quickly play an A flat to B flat trill without the thumb key... it's a pain; you have to keep flicking your right hand fingers in the opposite way to your left hand fingers.  On the other hand, if the B flat was always played with the thumb key, then moving between B and B flat would be really awkward.

Isn't 10 keys + harmonics (in other words overblowing) sufficient to get all the notes of the 3 octave range?

Actually 11, but yes, theoretically.  However there are "extra" keys that extend the range in either direction.  For example, after C, you are usually expected to then go across the register (overblow), and put all your fingers down.  However, in fast passages, this isn't practical, so the trill keys extend the register up a bit further and give you an "extra" D and D# at the top so that it's possible to trill these notes from C and C# (which is essentially impossible for a human to do using the normal fingering).
And, on the bottom end, we have 2 extra keys to extend the register of the flute downwards.  This isn't strictly necessary of course, but it's nice to have a couple of extra notes in the bass end without compromising the high end, and composers have seen fit to write music for this full range,  (with B and B flat foot joins, this is extended a bit further).
But let's ignore the B flat and the trill keys for a second (which after all, are just alternate fingerings for quick passages, you don't need to use them that often at all).  Why are the fingerings the way they are?  And why aren't they the same in every octave?

Let's imagine we're designing the flute from scratch. So, how do flutes work?  Let's look at the simple, diatonic flute first.  Instruments like this are found all over the world, independently invented by different cultures (with some variation but perhaps not as much as you'd expect), except not with keys, but with holes.
For example, for a typical 6 holed flute (could be in any key but in keeping with western tradition I'll write it in D) is fingered like this:
●●● ●●●   D
●●● ●●○   E
●●● ●○○   F#
●●● ○○○   G
●●○ ○○○   A
●○○ ○○○   B
○○○ ○○○   C#
●●● ●●●   D (overblown, often vented)

(the above could be for example a cheap "Irish flute", a pennywhistle (with a fipple), or indeed an Indian Bansuri.  Other similar flutes have more or less holes, the Japanese Shakuhachi has only 5, the carnatic bansuri 7, but the basic principle is the same.)
Over time, in Western Europe, people wanted to be able to play more chromatic notes, but they ran out of fingers to drill more holes.  Half holing is always an option (it's what bansuri players do), but it's difficult and imprecise in fast passages.  Some "forked" or "veiled" fingerings will sometimes work on these flutes. What this means that instead of just changing the length of the tube, you flatten that note by covering some holes lower down the tube.  With an instrument like the french horn, this is comparable to putting your hand in the bell to lower the pitch a little, the tube becoming slightly obstructed.
So if C# is ○○○ ○○○,
You can flatten it to C by covering more holes, so:
○●○ ○○○ , ○●● ○○○, or even ○●● ●○○ (depending on the flute one of these will be pretty much in tune)
Over time flute makers began to understand more and more how to position these 6 holes so these forked/veiled fingerings were in tune.  The baroque flute (as seen here

) still only had 6 holes (and 1 key, for E flat), but these holes were tactically placed (and sized) to allow a lot of options for various fingerings.
Note: this is still pretty much just a stick with 6 holes in it (and 1 key at the end to open a 7th hole, but that was it). The specific placement of these holes was perfected to be manipulated (incredibly skillfully) to play all the extra chromatic notes though, by using these "cross-fingerings". This resulted in a flute with many many alternative fingerings for the same notes, with different ones being slightly flatter/sharper (pitch) darker/brighter (timbre).  (Note that while to a modern musician this "inconsistency" of tone and pitch may seem like a defect, this was not actually not necessarily undesirable  for the music of the time. But going into more detail on that would make this answer even longer...)
e.g.
●●● ●●●   D
●●● ●●● □ D#
●●● ●●○   E
●●● ●○●   F
●●● ●○○   F#/Gb
●●● ●○○ □ F#/Gb option 2
●●● ○●●   F#/Gb option 3
●●● ○○○   G
●●○ ●●●   G#
●●○ ○○○   A
●○● ●●○   Bb
●○● ●○●   option 2
●○● ●●● □ option 3
●○○ ○○○   B

etc.
The above is for the first octave, but as you get higher, the vented fingerings become more and more complicated, with more and more alternative options that are slightly sharper/flatter darker/brighter louder/quieter.  This essentially meant that the further away from the "home key" (D) you got, the more of a pain it was to play.  There were no "sonata for flute in Ab"s in the baroque days...
This flute gradually evolved, with more and more keys being added to open extra holes here and there, finally ending up with the concert flute as used at the beginning of the 19th century (now usually called the "simple system" or "old system" flute).   So now rather than being a stick with 6 holes on it, it's stick with 6 holes on it and a bunch of other holes covered by metal keys that you can open with a bunch of levers and stuff. (This incidentally is the flute that is still used by Irish flute players to this day, albeit with a different technique than the classical players used to use, and generally the keys are mostly ignored, or even removed).
If you look at the fingering and mechanism of this flute, with all the additional holes and keys here and there, and alternate fingerings for each note, it most certainly does not follow a simple "logical" system.  But, it evolved over time, kept all the familiar fingerings for the more simple notes, and allowed the flute to be "more or less, with a lot of finesse", chromatic.
EXAMPLE HERE
The modern flute

So with that out of the way, how would we design a "perfect" chromatic instrument.  We want it to play equally as well in all keys, with a strong and even tone that doesn't change throughout the chromatic scale.  So that means no veiled fingerings: with the same principle as a diatonic flute, open 1 hole,move up one note, except this time we do it for the chromatic scale not just the diatonic one.  Take a big tube, and drill (at least) 11 holes in it (for all 12 notes).  And the fingering would be something like this:
●●●●●●●●●●●  D
●●●●●●●●●●○  D#
●●●●●●●●●○○  E
●●●●●●●●○○○  F
●●●●●●●○○○○  F#
●●●●●●○○○○○  G
●●●●●○○○○○○  G#
●●●●○○○○○○○  A
●●●○○○○○○○○  A#
●●○○○○○○○○○  B
●○○○○○○○○○○  C
○○○○○○○○○○○  C#

Of course, the biggest problem here is the most obvious one: more notes than fingers.
The modern flute we play now is the Boehm flute, and in fact its whole purpose is to achieve more or less what is shown above, in the simplest way possible: a fully vented flute with 1 large hole for each semitone, each of which is progressively uncovered as you go up each semitone, (effectively shortening the length of the pipe).
Us not having enough fingers though, the genius of Boehm was 1) coming up with this concept itself for a "fully vented" chromatic flute (not just a flute that starts with the assumption of the diatonic flute and then tries to "fix it" to make it chromatic) and 2) coming up with a system of keywork that allows us to control it in a manageable way without needing essentially another hand...
The Principle of the the Boehm system flute's is a "fully vented" system: large, always open tone holes that are opened one by one throughout to go up the chromatic scale, with no veiled or "forked" fingerings. This marked the biggest change the the design of the flute in hundreds of years.  Up to this point, changes to the western flute had been incremental: this was a complete step change.  Up until this point, the keys added to the flute were closed when not in use.  Essentially, when not being used to get the "extra notes", the flute still only had 6 small holes open.  The Boehm flute completely scrapped the "6 finger holes in a wooden tube plus some keys" model that had existed for literally hundreds and hundreds of years, and went with a metal tube, with many (far more than fingers on our hands) very large (far bigger than our fingertips) holes on it. This resulted in not only a fully chromatic instrument, but a LOUD one.
The much increased volume, and consistent tone throughout the flutes range and ease of playing ALL keys resulted in its fast adoption through most of Europe (with very minimal modifications) and it has remained almost unchanged for over 150 years at this point (whereas the "old system" flute gradually changed and evolved throughout its life, and always had many competing variations at any given time).
If you look at the fingerings on your flute going chromatically upwards from low C, you will notice that, with the exception of B flat and F sharp, the holes open 1 by one going up the tube, like this
●  ●●●●●●●●● ● ● ●  C
●  ●●●●●●●●● ● ● ○  C#
●  ●●●●●●●●● ● ○ ○  D
●  ●●●●●●●●● ○ ○ ○  Eb (pinky opens hole at the back)

●  ●●●●●●●●○ ○ ○ ○  E
●  ●●●●●●●○○ ○ ○ ○  F
●  ●●●●●●○○● ○ ○ ○  F# *
●  ●●●●●○○○○ ○ ○ ○  G
●  ●●●●○○○○○ ○ ○    G#
●  ●●●○○○○○○ ○ ○ ○  A
●  ●●○○○○●○○ ○ ○ ○  Bb *
●  ●○○○○○○○○ ○ ○ ○  B
●  ○○○○○○○○○ ○ ○ ○  C
○  ○○○○○○○○○ ○ ○ ○  C#

○  ●●●●●●●●● ● ○ ○  d

If you had an extra hand you wouldn't need the complicated mechanism, and you could just play the flute directly as it is above, but without that, you need a fingering system that triggers these keys.
In fact the earliest (and now pretty much omnipresent) modification to the original Boehm system flute, the closed G#, was a step away from  the most "logical" way of triggering these holes.  As you can see above: G has one more hole covered than G#, but we finger it the opposite way (using the left hand little finger to open a hole not close it). Originally the "G# key" was just a normal key, pressed down by the little finger of the left hand.  Although this was more "logical" chromatically speaking, people disliked having to constantly use the little finger on the left hand to play a G and every single note below it, and so the closed G# became more popular.  While this may seem illogical, imagine having to keep the left hand pinkie constantly depressed down to play G, F, F# E, Eb and D.  It's a pain...  (Note that this is still the situation with the right hand, and the right hand pinkie is to this day one of the more tricky parts of the Boehm flute, causing many students problems).
If you look above this is very nearly a perfect key system: the starred fingerings are the only compromises, and it's easy to see why they were done.  Yes, it causes ever so slightly veiled notes, but without these mechanisms for a later hole to close an earlier one, you simply wouldn't have enough fingers to play all the notes!
And how bad are these compromises?  Well, with the Bb, it's so far down the tube that it makes almost no difference, and it's possible to play a "perfect" B flat with the thumb key or Bb shake if you want to compare (and I can't hear the difference on my flute at all).  With the F sharp it does make a (very small but admittedly audible) difference, and you can tell if you manually close the hole to the left of RH1 and then compare by using RH4 to close the F#, you can hear that a "true" F# is ever so slightly brighter.  Also note that the "saxophone" or trill fingering of F# (LH T123 RH 2 4 instead of LH T123 RH 3 4) results in  ●  ●●●●●●○●○ ○ ○ ○  * instead of * ●  ●●●●●●○○● ○ ○ ○  (and is even more veiled).  But as a compromise to be able to finger that extra note we need easily, I'd say it's worth it (and you really can barely hear it).

This still leaves another question, why not have all the same fingerings in all octaves?
The answer is "venting".  The physics of it is pretty complicated, but basically, yes, if you work hard enough, you CAN use the first octave's "logical" fingering to play up and up in higher octaves. Theoretically of course you could keep going up and up infinitely, playing more and harmonics (like on brass instruments), but the real world physics of overblowing an imperfect pipe starts to get in the way of this, and it becomes pretty much impossible at about B. A "perfect" (physically speaking) flute would be an unobstructed tube, 100% open at both ends, this could play up and up the harmonic series.  What a flute actually is is a tube with someone's face at 1 end and holes being opened up at the other end; and while these holes are very large on the Boehm flute, they're not infinitely large.
Luckily, physics also has an answer to this problem: venting: when overblowing (playing upper harmonics of a note) on a flute, you get a clearer, brighter tone by opening up the pipe in certain tactical places. On baroque flutes in order to play the higher octaves, a lot of half holing, minute venting and skill was needed, but the Boehm flute has so many options for holes to open and close independently through the complex key system that it's possible to use these "vented" fingerings to play much higher than would be possible otherwise:
Look at all those holes above: pretty much every one can be opened and closed independently (plus trill keys).  This means that you can coax our metal tube to play  clearly and in tune up to top C and beyond, by opening up the right holes in the right places to force certain harmonics to resonate properly.  Compare a top G with and without the thumb: it's possible to overblow a bottom G up to the 3rd octave, but opening the thumb key to "vent" the note makes it just "pop" into place, and sound much clearer.
TL;DR
The modern flute is more or less logical: keys are opened up 1 by 1 to shorten the length of the pipe.  The Boehm flute is designed to follow this principle as close as possible, opening up 1 more key for each semitone, gradually shortening the length of the pipe,  with 3 exceptions**
1) There are more notes than we have fingers, so a couple of tricks are needed to allow us to control all the keys.  This means that the system of uncovering holes 1 by one going up the flute isn't quite followed for F# (or for one of the B flat fingerings) due to a workaround to let us use the same finger on the same key for multiple functions.  However these imperfect "veiled" fingerings on the modern flute are very rare, and barely audible in their difference from a "perfect" note.
2) For high notes, the system of simply opening holes 1 by 1 isn't actually what we want.  The non ideal physics of a real flute in the real world means we actually need to open up other (apparently random but not) keys in the middle of the tube to get the highest notes to play clearly and in tune (and to get the very highest notes to even play at all), which is why the fingerings appear to become "illogical" in the highest register.  This is called "venting", and is a way of extending the range of a woodwind instrument beyond what can be achieved by simply overblowing the harmonic series.
3) Extra keys are added to allow easier fingering workarounds for certain fast passages.  These aren't acoustically necessary, but they give a few extra options to work around our imperfect hands.  Oh and there are a couple of keys on the bottom to give a few extra low notes, why not eh?

links:
http://www.oldflutes.com/hybrid.htm
http://robertbigio.com/cleverandrich.htm
http://www.kingmaflutes.com/mySite/ksback.html
http://www.oldflutes.com/articles/reform.htm
Answer: If we were to invent the flute from scratch today using modern technology and knowledge, we could probably make it simpler.  However, it has evolved over many years.  Extending it to be chromatic happened gradually and added much of the complexity.
As with so many things, even if we recognise that it could be improved with some changes, it would be at the expense of those who have learned the current standard.
For example, the QWERTY keyboard is probably not the most efficient but many of us have learned it and it would be hard to introduce a new system.  (In that case, it has been tried but QWERTY still dominates.)
Comment: this actually isn't true, it would be true for the simple system flute, but the boehm flute is exactly the opposite of this.  The old flute got gradually more and more convoluted and awkwardly designed for centuries, and then Boehm came along and redesigned the flute as a chromatic instrument from the ground up.  The flute we play today is a barely modified version of this design, which was implemented from the ground up as a chromatic instrument
Comment: I'm not sure how easy it would be to substantially simplify flute fingering.  In C major or F major, the fundamental tones are produced so one finger equals one scale step- hard to improve upon that.  The more complicated fingerings for the higher harmonics are constrained by acoustical considerations. And the QWERTY comparison is not really apt, because the keys on the flute cannot be assigned to random tones.
Comment: Yes, "much simpler" was probably excessive.  I'll drop the much.  However, there is some scope for simplification if we don't require compatibility with the past.  An old unkeyed flute necessarily has the holes where the notes require.  For a modern flute, the keys need not be near the holes.  We could have an almost piano like layout if we wished.  Even more extreme, we could use electronics between the keys and the pads; a fly by wire approach as in some modern planes.  Anything would be possible if we went to that.  (I am not seriously proposing that.)
Comment: Of course, if we had electronic control of the keys, we could simply use a keyboard, as you suggest.  But in that case, why not dispense with the tube altogether and just have sensors connected to a mouthpiece with no flute attached?  Or maybe just keys and a tube to blow in?  Or forget the tube?  At some point, we don't really have a flute any more.
Comment: Remember that I am not actually suggesting this but the electronic route may be able to combine the sound a standard flute with easier controls.  However, even with mechanical  levers and pads, the key layout does not need to match the location of the holes.
Comment: True.  But do you play the flute?  the layout is pretty well optimized.
Comment: No.  I am extrapolating from the OP's comments and my experience of the clarinet and saxophone.  Note that I am not proposing any change, just trying to explain why we are where we are.
Comment: I can't really fault you for assuming this would be the case, and usually that would be the story, but, in the case of the modern concert flute, it actually happens to be not true at all
Answer: Part of the answer is that you need to produce 12 different notes per octave with just 9 fingers (the right hand thumb doesn't have any keys, because it's needed to support the instrument).  Thus, there will have to be more fingerings than just taking off one finger at a time, which (on the modern flute) means more holes than fingers.  This makes some complication necessary.
The other reason is for ease of playing.  For fast passages and trills, it's important to make transitions between fingerings as easy as possible, which is why you have more than one fingering for many notes, as well as the associated keywork.
The modern flute is perhaps the most acoustically rationalized of all woodwinds and has the simplest fingering patterns of all.  While it's a bit confusing in the beginning, if you persevere, you'll find the fingerings soon become second nature.
Comment: I have to quibble about the "simplest fingering patterns" assertion and not just because it highly subjective.  I play flute, saxophone and clarinet, and of the three, the saxophone is far easier to understand.
Comment: @Duston - okay, that's reasonable.  I also play flute, saxophone, and clarinet, and oboe and a little bassoon as well.  While saxophone fingerings are about the same level of simplicity as flute fingernings overall, the saxophone has the additional complication of an octave key, which the modern flute does not have.
Answer: Mostly it has to do with the mathematic of perturbation of a vibrating air column. The major scale (any major or minor or makam or whatnot, except for bugles) isn't a simple overtone series of an open air column. The trick is to induce vibrations by breaking the column irregularly.
Comment: I'm not sure this will be understood by the OP. It summarizes what someone who understands acoustics already knows. Maybe more detail would be helpful. (I don't know the science enough to post an answer.)
Comment: Even that isn't an answer -- you can get a keyless fife, for example.  A lot of keys on woodwinds are added not only to perfect the pitches but to allow for alternate fingerings in support of various tunes.
Answer: Humans have been making and playing flutes for at least 40k years, probably far longer than we have had what we would recognize today as mathematics.
The fingerings we have today are a result of people figuring out fingerings that work, with various evolutions due to materials and mechanics advances over the years.
As others have suggested, we could do a clean sheet redesign today that would be simpler. Dr. Carlene Hutchins did this for the violin family, though her work was focused more on building a coherent string family than simplifying the ergonomics of playing violins. Despite the slightly different goal, she worked with physicists to understand the fundamentals of the instrument and extend it in a way she thought was appropriate.
I learned to play flute early in grade school. Many years later, I still remember the fingerings. I suspect the illogical nature actually helps. There was no algorithm to remember, just plain memorization. My muscles will always know approximately how to play the flute, even though they have long since forgotten keyboards (and I have a room full of synths with keyboards I still play!). So it seems there are open questions about what is really easier.


Windows Server 2008 r2 security permissions

Question: I hope I've selected the correct StackExchange for this question. I have searched google and StackExchange but haven't been able to find an answer to my question with the search queries used.
I setup a home server as a little project to learn the basics of the Windows Server environment in October 2015. It has worked well and served the purposes I set it up for since.
However, I made a mistake a couple of weeks ago....
Imagine for a second that someone could be stupid enough (or just had a complete lapse in concentration!) to remove 'Full control' for the Administrators on the primary data HDD.
Data drive permissions
Is there any way to revert this permission change short of reinstalling the OS?
Thanks
Comment: See the accepted answer on this question: https://serverfault.com/questions/53325/resetting-ntfs-permissions-disk-wide
Answer: You can boot the system with a live Windows CD/DVD/USB and use "TAKEOWN" and "ICACLS":
TAKEOWN /f "X:\" /r /d y
ICACLS "X:\" /reset /T
If you do not have a live Windows, extract the HDD's and connect them another windows machine and reset them from there.
Comment: Thank you joeqwerty and Oniceag George. I have done as suggested which has given permission to my user. Hasn't completely resolved the problem but answers the question I raised perfectly :)


Monotonicity of $L^p$ norms

Question: Let $(X, \mathscr{A})$ be a measurable space, and let $\mu$ be a measure on $(X, \mathscr{A})$ such tat $\mu(X) = 1$  suppose that $1\leq p_1 < p_2 < +\infty$.
Show that if $f$ belongs to $\mathscr{L} ^{p_2}(X,\mathscr{A}, \mu) $ then $f$ belongs to $\mathscr{L} ^{p_1}(X,\mathscr{A}, \mu) $ and satisfies $\| f\| _{p_1} \leq \| f\| _{p_2}$
Is there a typo in my exercise?
For $\ell_p$ spaces it seems to be the other way around:
http://en.wikipedia.org/wiki/Lp_space
Thankful for help
Comment: No typo. What did you try?
Comment: Exactly, it IS the other way around!
Comment: Hint: Jensen's inequality.
Answer: The assumption $\mu(X)=1$ is crucial. It's not satisfied by the set of natural numbers, hence it's not surprising it doesn't work in this case.
One case use Jensen's inequality with the convex function $x\mapsto |x|^{p_2/p_1}$.

Monotonicity of $L^p$ norms


confirmDeveiceCredentialIntent from non-activity/application context

Question: As we know, we have an api in KeyguardManager for authenticatng the user through his device lock. The api is : confirmDeviceCredentialIntent.
The doc for this api says :

Get an intent to prompt the user to confirm credentials (pin, pattern or password) for the current user of the device. The caller is expected to launch this activity using startActivityForResult(Intent, int) and check for RESULT_OK if the user successfully completes the challenge.

Now, my problem is, I want to invoke this flow in a non-activity context. I am using a kv store in my app whose contents would be encrypted by the key that I am storing in android keystore. So when I want to get any value fro that store, I first need to authenticate user so that I get my key and decrypt the content before returning.
Second thing is, I, as a consumer of that kv store, don't want to be aware about how the encryption of the store is done and therefore I shouldn't invoke confirm credentials myself. I just want my value from the store and it's store's (which is non-ui component) responsibility to invoke the authentication flow if it's required.
So mostly, I'd be using the global application context. And this context doesn't provide startActivityForResult api.
Is there any other way by which I can get result of confirm credentials action from user?
Answer: I ended up using a Dummy Activity. This activity itself is launched by application context and then it handles invoking confirmCredentials intent for result.


WHERE em campo bigint[]

Question: Tenho que realizar uma consulta para saber se o código de um grupo esta nas permissões para ver o campo.
SELECT *
  FROM callcenter.pausa
    WHERE habilitado = 1
     AND permissao_ver::varchar ilike '%1%'
    ORDER BY pausa ASC

Resultado:
{26,9,10,7,19,2,21,11,17,14,15,6,8,25,24,32,27,28,22,23,13,12,16}

Esse array não tem o numero 1 mas o mesmo me retorna dados pois exitem outros numero com o digito 1, preciso que ele verifique certinho que realmente tem o numero 1.
Comment: Se você que quer ele te retorne apenas os dados que sejam o numero um por que esta usando o `like`?
Answer: Rafael,
Você pode utilizar o operador &&, ele compara dois array e se qualquer elemento existir nos dois ele retorna true (como se fosse um "OR").
Assumindo que esse campo permissao_ver seja um bigint[], você pode fazer o comando conforme exemplo:
SELECT *
FROM callcenter.pausa
WHERE habilitado = 1
AND permissao_ver && '{1}'::bigint[]
ORDER BY pausa ASC

Você pode consultar mais detalhes na documentação do postgres: https://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-OPERATORS-TABLE

WHERE em campo bigint[]


Why is MIDI gain based on a factor of 40?

Question: Many documents state that the MIDI standard gain is 40 * log10(CC7/127).
I've found only one person asking why, with no replies. This document says that voltage (amplitude) gain is a factor of 20, not 40.
So why a factor of 40? What is the theory behind it? What is the nature of gain being addressed in the MIDI standard?
The answer will be important for me, because I am trying to match the volume of MIDI to an OPL4 device which has a logarithmic scale, and using the MIDI formula clearly gives an incorrect volume level for quiet notes. By comparing output produced by the MIDI formula, I clearly hear that Windows Media Player has higher volumes for quieter notes.
Linear volume boost does not help here, making the sound even uglier: making loud notes louder and not much affecting quiet notes.
Update:
thank you very much for the answers. It was somewhat hard to choose the best one. Therefore our conclusions are: simplicity in implementation (V * V * sample), covering broader dynamic range (96 dB instead of 48 dB).
My suspicion was actually about breaking the human perception of 20 * log having 40 * log, which has steeper curve. I replaced volume table 20 * log, and it now sounds very similar to other players I tried (including WMP).
Regarding questions asked: OPL4 is my own implementation, designed basing on YMF278B datasheet, therefore I have full access to its internals - here's the outcome of my work heavily using hardware acceleration playing more or less properly on the 3.58 MHz machine.
I suspect that at TL=127 chip must mute the output, however it is not declared in the datasheet, and my implementation does not make this assumption.
If total silence is required immediately, panpot=8 can be used until envelope reaches max 1023 under key off condition with appropriate RR=15.
OPL4 (YMF278B) contains OPL3 implementation, however slightly different than in OPL3 and earlier chips because of running at 49.515 instead of 49.715 kHz.
Comment: The terms "theory" and "MIDI" don't go well together. MIDI is just a heap of hacks upon hacks that were created to get the devices of the time to kinda work together, within their respective technical limitations. The whole standard should have been burnt a long time ago and replaced with something properly designed, but for some reason that has never happened.
Comment: @leftaroundabout: You mean MIDI 2.0? (ducks and runs)
Comment: @leftaroundabout I personally love Midi because of the way it can hacked and bend from its original design, but maybe it's just me :D
Comment: @leftaroundabout I suppose you'd also like sheet music notation to be burnt and properly designed? ;) How about music _discourse_? It's like dancing about architecture, man, a big historical mush of misunderstandings. :/ Actually, the whole music culture in its entirety is _unbearably_ non-designed! It's such a big mess, it's almost as if _humans_ were involved. * shrug *
Comment: @piiperiReinstateMonica standard notation is one of the most remarkable things that have happened in human history, because it somehow managed to evolve naturally into a form that does its job _amazingly well_ – I could hardly think of any way that a plan-designed system could possibly be better for common practice music. Now, perhaps you'll say that MIDI also does "its job" just fine, of linking the digital synthesizers of its time together. Only, that's not what most people use it for, nor was its original ambition so limited. It's at this point a as if Beethoven had used mensural notation.
Comment: @leftaroundabout Looking around, I see no reason to believe that anything substantially more useful could have been created in the actual non-fantasy world. MIDI is precise enough and vague enough to offer a lot of uses, and it is already there, for decades already, which is a totally killer feature. A lot of excellent things have come by using technical things for something they were not intended for. The world is full of failed "better" technologies. MIDI is a great success in my books. :)
Comment: To OP: not saying anything to the MIDI question, but for your OPL4 player, it might be a doable solution to experimentally build an exhaustive volume mapping look-up table and adjust all values until it sounds like you want across the range. I mean, if you're able to measure the levels and find values that sound right in practice, do you need a theoretical function anymore at that point? A mapping LUT might be a reasonably quick option, if you just want to get it done. What OPL4 device is this by the way, a Moonsound or something?
Comment: "MIDI is just a heap of hacks upon hacks that were created to get the devices of the time to kinda work together" - that isn't exclusive to MIDI lol
Comment: This could be interesting https://www.cs.cmu.edu/~rbd/papers/velocity-icmc2006.pdf Roger B. Dannenberg, "The Interpretation of MIDI Velocity" ...  _This study aims to determine empirically how hardware and software MIDI synthesizers translate velocity to peak RMS amplitude. ... Surprisingly, computed values of dynamic range for commercial synthesizers vary by more than 60dB._ Analyzed synths: Microsoft GS soft synth, Yamaha DX7 and SY22, Roland U220, Kurzweil K2000R with Kurzweil orch samples, and GPO Finale Edition. Though I disagree with his using non-overlapping windows for RMS calculation.
Answer: I don't know the reason but a bit of math gives a reason.
First, a note: how a sound generator responds to a CC value is entirely up to the manufacturer or developer of the generator. What I found about CC7 is that the 40*log(CC7/127) formula is a suggestion. Also, this is not gain, it's "volume". What does volume mean in this context? Whatever the manufacturer or developer of the sound generator wants it to mean.
One good reason to use a factor of 40 instead of 20 or 10 is that the possible output values of that function range from -84 to 0 (ignoring the input value of zero for the moment). With a factor of 20, the output only ranges from -42 to 0, and for a factor of 10 it's only 21 to 0.
Of course the relationship inside the sound generator between the output value of the function and the gain (or attenuation) of the output amp can be made in any way. Also the characteristics of the amplifier are up in the air. That said, if the output of the function is used to set dB of attenuation, then a range of 84 dB is much more useful than 42 or less.
A factor could be chosen such that the output is -127 to 0, but in dB that is actually an overly broad range for output amp attenuation.

Why are we ignoring the input value of 0? Because the mathematical log of 0 is -infinity, which obviously will have to be handled specially in some way in and computer system applying this scaling function.
One way to handle it is to change the function to 40*log((CC7+1)/128), which outputs -84 to 0. Another way is to insert an if CC7==0 statement that catches the invalid input and can just set the output to 0. Other solutions exist.
Comment: Interestingly, according to page 18 of the Yamaha OPL4 aka YMF278B's Application Manual (link on Wikipedia), the maximum attenuation that can be set for a voice (there are 24 simultaneous voices) by setting all 7 bits of the TOTAL LEVEL register is only -(24+12+6+3+1.5+0.75+0.375) = -47.625 dB. And complete silence is not possible at all, except by stopping the voice, AFAIK. So even though the OPL4 is from Yamaha and the manual says that with an external sample ROM module it "complies with GM System Level 1", apparently Yamaha didn't think -84 dB of attenuation is needed, let alone -infinity.
Answer: This definition of MIDI volume appears in the General MIDI Level 2 specification, on the bottom of PDF page 10 and top of PDF page 11 (printed pages 6 and 7):

Regarding the curve of volume change messages, the square of the value is proportional to the volume.
Example

CC#7
amplitude
proportional to

127
0 dB
127 × 127 = 16129

96
-4.9 dB
96 × 96 = 9216

64
-11.9 dB
64 × 64 = 4096

32
-23.9 dB
32 × 32 = 1024

16
-36.0 dB
16 × 16 = 256

0
-∞
0 × 0 = 0

The formula used is: gain in dB = 40 * log10(cc7/127)

To simplify the math in my descriptions, I will use a relative MIDI volume from 0 to 1.
V is the relative MIDI volume from 0 to 1.
V = (MIDI volume value) / 127
L is the relative sound pressure level in decibels from -∞ to 0.
L = 40 log10 V
A is relative sound wave amplitude from 0 to 1.
L = 20 log10 A
20 log10 A = 40 log10 V
log10 A = 2 log10 V
log10 A = log10 V2
A = V2
My guess as to why this definition for MIDI volume was chosen is that it is possibly supposed to roughly represent perceptual loudness: The MIDI volume value halfway between the minimum and maximum roughly represents a sound "half as loud" as the sound represented by the maximum MIDI volume value.
As a rough approximation of a relative "perceptual loudness" measure, I looked at the definition of a sone. In a grossly simplified terms:

doubling the perceived loudness doubles the sone value.
an increase in sound pressure level of 10 dB corresponds to a doubling of the loudness in sones.

I used these simplified definitions to create a "relative sones" value like this:
N is the relative perceptual loudness in "relative sones" from 0 to 1.

L
N

0
1

-10
1/2

-20
1/4

-30
1/8

-40
1/16

N = 2(L / 10)
log2 N = L / 10
10 log2 N = L
To see how relative MIDI volume V compares to relative perceptual loudness N, I plugged in the earlier definition of L in terms of V and solved for N:
10 log2 N = 40 log10 V
log2 N = 4 log10 V
(log10 N) / (log10 2) = 4 log10 V
log10 N = (4 log10 2) (log10 V)
log10 N = (log10 24) (log10 V)
log10 N = log10 V(log10 24)
N = V(log10 16)
N = V1.204...

That seems like relative MIDI volume V is pretty close to relative perceptual loudness N, and I guess it's convenient that relative MIDI volume squared gets the relative sound wave amplitude (A = V2). So that's my wild guess why this definition for the MIDI volume was chosen.
Comment: Is this new for General MIDI Level 2? For their GM System Level 1 compliant OPL4 chip, Yamaha chose to have only 47.625 dB of attenuation range for values 0-127, which is why the OP has this question. Or are "General MIDI Level" and "GM _System_ Level" different concepts. Downloading the spec requires registration, so I'm not interested.
Comment: This should be the accepted answer!
Comment: @piiperiReinstateMonica There is no difference in meaning between "GM System" and "General MIDI". For example, the download page for the [GM1 spec](https://www.midi.org/specifications/midi1-specifications/general-midi-specifications/general-midi-1) calls it the "'General MIDI System Level 1' specification -- also known as 'GM', 'General MIDI 1' and 'GM 1'". The GM1 spec's title page says "General MIDI System Level 1" so I guess that's the official name of it. The GM2 spec's title page says "General MIDI 2".
Comment: @piiperiReinstateMonica The GM1 spec doesn't mention this volume defintion. I looked again and the ["General MIDI System Level 1 Developer Guidelines"](https://www.midi.org/specifications/developer-white-papers/general-midi-level-1-developer-guidelines-2) does mention this definition. It also says it "follows the standard 'A' and 'K' potentiometer tapers" and it came from Yamaha: *"The recommended volume response curves [...] were provided [...] by Yamaha Corporation. Roland uses the same response curve, and other Japanese manufacturers who are members of the AMEI have agreed to do the same."*
Comment: Maybe the OPL4 designers had a technical reason to do the voice level control the way they did, or maybe it's because for some other reason, cultural, communicational, ... arbitrary preference? Who knows. But with that implementation, even though it's advertised as being compliant, it's not possible to cover the 84 dB range, and it's not possible to mute a voice and bring it back up without stopping and re-starting the sample. Go figure.
Comment: @piiperiReinstateMonica This volume spec isn't in GM1 (GM1 Developer Guidelines are later recommendations) so OPL4 could be GM1 compliant. OPL4 volume appears compatible with OPL1 which uses [6 bits](http://www.shipbrook.net/jeff/sb.html#40-55) instead of 7, but otherwise same meaning (highest bit is 24 dB, each following bit is half of previous bit). Wikipedia's [Yamaha OPL](https://en.wikipedia.org/wiki/Yamaha_OPL#Internal_operation) says "volume would normally be done by multiplication, but [OPL1 uses] log-transformed signals [for] cheaper additions."
Comment: Don't look at the FM synth stuff. OPL4 does include an OPL3 compatible FM synth, but the main new thing that makes it OPL4 is a separate 24-voice PCM sample player which uses 7 bit volume. That's what the OP is trying to use, not the FM synth. Link to a scanned PDF of the YMF278B's Application Manual is available on the Wikipedia page https://en.wikipedia.org/wiki/Yamaha_YMF278 The 7-bit per-voice TOTAL LEVEL register is described on page 18. There other volume-related registers, but they're not per-voice.
Comment: @piiperiReinstateMonica The OPL4 wavetable registers for Total Level (7 bits) (printed page 18 / PDF page 21) appear similar to the OPL4 FM registers for Total Level (6 bits) (printed page 45 / PDF page 48). The highest bit of each Total Level register is 24 dB attenuation, and each following bit is half of the previous bit.
Comment: Indeed, and by setting all 7 bits you get a maximum of (24+12+6+3+1.5+0.75+0.375) = 47.625 dB of attenuation. The lowest bit 0.375 dB feels kind of weird - does anyone really need to set level that precisely.
Comment: Very nice answer - happy with that! Plus if your mixing down at -30db it's time to turn it up notch! Important to be able to nearly silence matters down at -84 db or whatever.
Answer: The standard states

Regarding the curve of volume change messages, the square of the value is proportional to the volume.

The squaring means that you get 40dB as the proportionality factor rather than 20dB.
Answer: MIDI volume is interpreted by multiplying sample values with the square of the controller value after normalisation.  This is a 7-bit controller, and synthesis is typically done using 16-bit D/A converters.  Squaring the value makes the multiplier 14 bits, covering the possible dynamic range pretty much completely while making for a simple implementation.
The formula is what results in terms of dB values and does not really reflect the simplicity of what actually happens in terms of implementation.  That is somewhat similar to how a logarithmic potentiometer for volume control actually is done in practice, with "logarithmic" being not much more than a euphemism for "non-linear" inspired by the logarithmicity of loudness scales.
Comment: Also, logarithmic is not a euphemism for non-linear. There are many non-linear curves, functions, etc that are also not logarithmic. Geometric functions are an example. In terms of audio electronics, the concept of linearity is further complicated by the fact that "linear" means something a bit different in electronics from what it means in mathematics.
Comment: @ToddWilcox: While "logarithmic" is not *generally* a euphemism for non-linear, the term "logarithmic pot" is often used to refer to a wide range of potentiometers.
Comment: This answer confuses me in many ways. Right off the bat, what about midi volume for synths that have no samples and no D/A converters?
Comment: Also, if you multiply a sample with a volume value of 14bits, this sample cannot be bigger than 2 bits to fit in the 16 bits output. That's very low quality! You can of course reduce it afterward but squaring does not improve the midi information actually.


F# Sql Type Provider and .NET Framework v4.0/4.5 on Windows 10

Question: I'm trying write an application using F# and I need to access a Sql database.  I am trying to use the Sql type provider but when I do:
type schema = SqlDataConnection<ConnectionString="...">

I get the following design time error:
The type provider 'Microsoft.FSharp.Data.TypeProviders.DesignTime.DataProviders' reported an error: The .NET SDK 4.0 or 4.5 tools could not be found

A lot of people seem to get this but the only solution I've seen is to download and install the Windows Software Development Kit for Windows 8.1.  I have done this, selected all the options (including .NET SDK 4.5) and it appears to have installed without error.  However this hasn't fixed the issue and when I look in Programs and Features I can see 4.5.1 SDK and 4.6 SDK installed but not 4.5 SDK.  I am using Windows 10 and Visual Studio 2015 Community Edition.  Has anyone else had this problem and got a solution?
Alternatively is there any good alternative type provider or solution for connecting to and querying (note I only need to read data, not write) from a sql database in F#?
EDIT: Registry keys were missing so I added [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.1A\WinSDK-NetFx40Tools] with an InstallationFolder value pointing to the correct directory with all the utilities required in it.  As far as I can tell from: https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Data.TypeProviders/Util.fs this is all that is required.  However this didn't have any effect.  I looked back at an older version of Util.fs and it seemed to only look for v8.0A, not v8.1A so I also created a key for that, again pointing at the correct folder but still no luck.  At this stage from looking at the code I believe everything necessary is in place for it to work but it's just not.  I'm not sure if the type provider needs to re-installed but I can't find any options to do something like that.
Answer: It looks like you might be hitting this issue here: https://github.com/Microsoft/visualfsharp/issues/637 , the fix for which was in the pull request here https://github.com/Microsoft/visualfsharp/pull/638 .  Looking at the changes in the pull request, it looks like the current version is looking for the following registry keys:
HKLM\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.0A\WinSDK-NetFx40Tools
HKLM\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A\WinSDK-NetFx40Tools

On my machine, I have SDK versions v7.0A, v7.1, v7.1A, v8.0A, and v8.1A, and SQL type providers work fine.
Can you check your registry, and try downloading and installing one of the above SDKs if you are indeed missing either of them?
Comment: Yes I dug around in the code and discovered this.  I added the keys and pointed them at the correct place but still failing for same reason
Comment: I've never had to explicitly install the SDKs, I've only ever installed Visual Studio with F# and things have worked, and I'm running VS2015 on Windows 10.  However, the thread on github mentioned above indicates that it's only an issue for a clean Windows 10 install, while I have had previous versions of both VS and Windows on the machine.
Comment: Ironically the reason I my windows install is fresh is because I had all kinds of issues installing vs typescript integration because of previous versions of .net/visual studio.  It feels like every Microsoft SDK and toolkit has (un)installation issues these days.
Answer: For me it was enough to install this: https://developer.microsoft.com/en-us/windows/downloads/windows-8-sdk


DELETE row from different tables using SQL

Question:
I'm trying to delete all the rows in tblProInfo,tblOrderAA where tblProInfo.proInfoScienceName='shalosh'
Here is the command I wrote. I get a message that it couldn't generate my query.
DELETE tblOrderAA.*,  tblProInfo.*
FROM tblProInfo INNER JOIN tblOrderAA ON tblProInfo.proInfoSerialNum = tblOrderAA.orderAASerialPro
WHERE (((tblProInfo.proInfoScienceName)='shalosh'

Answer: DELETE a1,  a2
FROM tblProInfo as a1 INNER JOIN tblOrderAA as  a2
ON a1.proInfoSerialNum = a2.orderAASerialPro
WHERE a1.proInfoScienceName='shalosh'

The syntax is correct as per msaccess but doesn't delete records. Access delete queries cannot delete from more than one table at a time. This is an Access limitation.
Refer here to know about deleting records from multiple tables in MS-Access
If both tables are connected and referential integrity set such that deletes are cascaded then you can cause records to be deleted from both tables at the same time by simply deleting the record on the One side of the link.
In Sql Server:
The concept of deleting rows from multiple tables in a single delete statement cannot be done in sql server. There is the concept of triggers on the tables that do deletes in a cascading style.
Comment: Then simply remove the extra parenthesisin where clause and enjoy. The syntax is perfect that you posted except extra parenthesis.
Comment: I'm doing it via c#, and oleDB.now I get this error. the Record has been deleted.
Answer: On this line you have 3 opening brackets and 1 closing bracket:
WHERE (((tblProInfo.proInfoScienceName)='shalosh'

Answer: You have to separate the statements. You can not delete from two tables with one query
DELETE FROM tblOrderAA
WHERE tblOrderAA.orderAASerialPro IN
(
    SELECT orderAASerialPro
    FROM tblProInfo WHERE tblProInfo
    tblProInfo.proInfoScienceName='shalosh'
)

DELETE FROM orderAASerialPro
WHERE tblProInfo.proInfoScienceName='shalosh'


how to alter exposed form values before submit for filters in drupal7 view

Question: I want to do left and right trim when end user enters data in textbox for filter list of rows in drupal 7 views
Answer: <code>function example_form_alter(&$form, &$form_state, $form_id) {
 array_unshift($form['#validate'], 'example_request_validate');
}

function example_request_validate(&$form, &$form_state) {
  if (isset($form_state['values']['text_field']) && !empty($form_state['values']['text_field'])) {
    $request_id = $form_state['values']['field_request_id_value'];
    if (strchr($request_id,''))) {
      $request_id = ltrim(strchr($request_id,''), '');
    }
    form_set_value($form['text_field'], $request_id, $form_state);
  }
}
</code>


maximum tree depth vs number of training data in random forest regression

Question: I want to tune the parameters of random forest regression. If I have $n$ rows of training data, is there a bound on the maximum depth in terms of n, to avoid overfitting problem? Is $2^d < n$ the correct bound, where $d$ is the maximum depth of a tree?
Answer: Overfitting is best evaluated by k-fold cross validation, looking at how it performs on your validation set with chosen metric (like accuracy). It is data specific and not easy to predict using rules of thumb.
In Random Forest the more important hyperparameter is usually the number of trees used, as the averaging across many trees reduces overfitting. Often the max_depth is left at infinite. Use gridsearch with cross validation on your problem and find out how it works for your particular problem.
Comment: Tuning the number of trees wrt accuracy is ill-advised. https://stats.stackexchange.com/questions/348245/do-we-have-to-tune-the-number-of-trees-in-a-random-forest/348246#348246
Comment: Yes, tuning like a regularization parameter etc is wrong. But one still needs to ensure that there are enough trees, and that has some interaction with other parameters like tree depth. Though one could say just always leave it very high, like 100-500 and take the perf hit.
Comment: Even so, grid search is not an efficient way to do that.  It would be better to fit a single forest at the maximum number of trees, then plot a loss curve by the number of trees in the forest by truncating, then simply truncate the forest to a sensible number.


PostgreSQL COPY FROM csv with different date format

Question: I am trying to upload CSV data to a PostgreSQL database in Python using the COPY FROM STDIN function.
In the CSV file my Date field is DD-MM-YYYY HH:MI and this gives me an error:

psycopg2.errors.DatetimeFieldOverflow: date/time field value out of
range: "31-12-2020 08:09"

Is there a way I can define the Date/Time format when using COPY FROM?
DB column is type TIMESTAMP if relevant.
I only know how to do this with a line-by-line INSERT statement.
Comment: It is indeed much more efficient to parse and transform data once they are inside of the database. And you're right: using INSERT statements would be terribly inefficient with large files.
Comment: @S-Man apologies that was just me typing off the top of my head.  I am just copying from CSV with no Date format specified, I'll update for correctness. Thanks.
Comment: Could it be that your database is expecting `2020-12-31` instead of `31-12-2020`? You could always import it to a text column and cast it to timestamp afterwards ;-) Would it be an option? Although postgres would cast it withnout any problems: `SELECT '31-12-2020 08:09'::timestamp` ;-)
Comment: @JimJones yes I believe PostgreSQL is expecting 2020-12-31 format but I don't know if this can be manipulated with the COPY FROM function. I assume using a temporary text column will still be considerable more efficient than having Python do a line-by-line file read & insert
Answer: Just before the COPY command do:
set datestyle = euro;

show datestyle;
 DateStyle
-----------
 ISO, DMY

Then this works:
SELECT '31-12-2020 08:09'::timestamp;
      timestamp
---------------------
 2020-12-31 08:09:00

Otherwise with my default datestyle:
show datestyle;
 DateStyle
-----------
 ISO, MDY

SELECT '31-12-2020 08:09'::timestamp;
ERROR:  date/time field value out of range: "31-12-2020 08:09"
LINE 1: SELECT '31-12-2020 08:09'::timestamp;

For more information see here Date input Table 8.15. Date Order Conventions
Comment: Thanks. I created temporary text columns to get the data loaded then in pgAdmin I used "UPDATE public.my_table SET actual_datetime_col=(SELECT str_datetime_col::timestamp)" to update.
Comment: You could save a step by just temporarily changing the `datestyle` setting in the session before you do the `COPY`.


The Dual problem of a non constraints problem?

Question: The primal problem is
$min_{w\in R^d}: P(w)$ where $P(w)=\frac{1}{n}\sum_{i=1}^n\phi_i(w^Tx_i)+\frac{\lambda}{2}||w||^2$.
The dual problem is
$max_{\alpha\in R^n}: D(\alpha)$ where $D(\alpha)=\frac{1}{n}\sum_{i=1}^n-\phi_i^*(-\alpha_i)+\frac{\lambda}{2}\left \|\frac{1}{\lambda n}\sum_{i=1}^n \alpha_ix_i\right \|^2$, where $\phi_i^*$ is the convex conjugate of $\phi_i$.
I spent almost two days, but still cannot figure it out why these two are primal-dual problem. Because the primal problem has no constrains, is the dual problem means its conjugate problem? I know if the primal problem has constraints, then I can use Lagrange form to find its dual. But this problem has no constraint, I kind of don't know what to do.
Answer: As you rightly point out, because this doesn't have any constraints, it can't possibly have any dual variables. So the dual offered by the author is not the true dual. I'm not exactly sure where you got this from, but its author has done a poor job of explaining what they're doing.
What the author likely has done here is create some sort of equivalent problem by introducing some additional variables into the primal problem. Here's my guess: given $y\in\mathbb{R}^n$, they created this equivalent problem:
$$\begin{array}{ll}
\text{minimize} & \tfrac{1}{n}\sum_{i=1}^n \phi_i(y_i) + \tfrac{\lambda}{2}\|w\|^2 \\
\text{subject to} & w^Tx_i = y_i, ~ i=1,2,\dots,n
\end{array}$$
I believe that $\alpha_i$ above are Lagrange multipliers for these equality constraints. I might be off by a sign change, though for equality constraints that doesn't matter much.
Why don't you try deriving the dual of this modified problem and see if that matches up with  $D(\alpha)$. If so, you can go chastise the author of the claimed primal/dual pair.
Comment: Thanks for your suggestion. Let me try to derivate it from your equivalent problem. It seems to be the correct direction. I will let you know the result. Thanks again!
Comment: If set the constraint to $w^Tx_i+y_i=0$, then the dual problem is exactly as what they give. Thanks for your hint:)
Comment: Excellent! I am glad I could help. And I am glad you could finish the job.
Answer: Here is my solution that can be used to obtain dual of ERM without forming constrained problem as shown by Michael above.
From Fenchel conjugacy one has:
\begin{equation}
\phi(w^Tx) = \sup_z \langle w^Tx,z \rangle - \phi^*(z)
\end{equation}
from where we conclude that
\begin{equation}
\phi(w^Tx) \geq  \langle w^Tx,z \rangle - \phi^*(z)
\end{equation}
Using the above trick, we can lower bound the given objective function as:
\begin{equation}
F(w,\alpha) = \lambda r(w) -\frac{1}{n}\sum_i(w^tx_i\alpha_i + \phi^*_i(-\alpha_i) ) \leq P(w)
\end{equation}
where I have taken ${any}$ regularizer $r(w)$ and $z$ replaced by $-\alpha_i$.
Next, we minimize the lower bound as:
\begin{aligned}
D(\alpha)&=\inf_w F(w,\alpha)\\
&=\inf_w \left( \lambda r(w) -\frac{1}{n}\sum_i(w^tx_i\alpha_i + \phi^*_i(-\alpha_i) )\right)\\
&=-\sup_w \langle w,\frac{1}{n}\sum_i x_i\alpha_i \rangle -\lambda r(w)-\frac{1}{n}\sum_i\phi^*_i(-\alpha_i)\\
&=-\lambda r^*(\frac{1}{\lambda n}\sum_i x_i\alpha_i)-\frac{1}{n}\sum_i\phi^*_i(-\alpha_i)
\end{aligned}
where in step 3, we used the linear algebra fact $\sum_i <.,.>=<.,\sum_i .>$; inf-sup equality and in the last step, the definition of conjugate and one property of conjuagtes (conjugate of $ah(x)$ is $ah^*(y/a)$).
Comment: [see here](https://proofwiki.org/wiki/Negative_of_Infimum_is_Supremum_of_Negatives) for equality used in 3rd step. Fenchel conjugacy is used in the last step.
Comment: Can you explain more about the inf-sup equality in the last step. what do you mean by "inf-sup equality"?  I think you use Fenchel conjugacy in the last step.
Comment: But what you provide is a lower bound.
Comment: Exactly. Since your primal problem is minimization problem, minimizing the lower bound makes sense.  As an exercise, you can check if strong duality holds?


How to copy data from txt file and paste to XLSX as value with Python?

Question: How to copy data from txt file and paste to XLSX as value with Python?
(txt)File: simple.txt which contains date,name,qty,order id
I need the data from txt and copy paste to xlsx as VALUE.
How it's possible it? Which package could handle this process with Python?
openpyxl?Panda? Could you please give an example code?
My code which not suitable for the paste and save as values:
import csv
import openpyxl
input_file = 'C:\Users\mike\Documents\rep\LX02.txt'
output_file = 'C:\Users\mike\Documents\rep\LX02.xlsx'
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
with open(input_file, 'r') as data:
reader = csv.reader(data, delimiter='\t')

for row in reader:

    ws.append(row)

wb.save(output_file)

Comment: Please show us how your data looks: what is inside the txt file and what structure is?
Comment: And moreover, please tell us what you did already and what you encountered. I could find 2 relevant packages with 1 simple google search.
Comment: Why don't you take a look at [comma-separated values](https://docs.python.org/3/library/csv.html) (CSV) which is what most spreadsheets are. Python supports CSV out of the box. Plenty of examples there, too…
Comment: Ladies and Gents, I need a code which suitable for the next : copy txt.value , open excel application, paste as value  and save workbook.
Answer: In pandas, with pandas.read_csv and pandas.DataFrame.to_excel combined, you can store the content of a comma delimited .txt file in an .xlsx spreedsheet by running the code below :
#pip install pandas
import pandas as pd

input_file = r'C:\Users\mbalog\Documents\FGI\LX02.txt'
output_file = r'C:\Users\mbalog\Documents\FGI\LX02.xlsx'

pd.read_csv(input_file).to_excel(output_file, index=False)

Comment: It's not work because the mentioned txt contains empty columns and rows.
Comment: That's not what is said in your question. You said *(txt)File: simple.txt which contains date,name,qty,order id)*. Can you share a sample of your `.txt` file ?
Comment: This txt came from SAP transaction (LX02)


Is there a mandolin-like instrument with guitar-like tone and range?

Question: I need to play low guitar accompaniment parts (simple bass-note-plus-chord style) but I prefer the narrow neck and short scale length of the mandolin.
Is there an instrument (acoustic, not electric) that has a narrow mandolin-style neck (and preferably a short scale length, although I realise that's perhaps unlikely) but that can reach the low guitar range and has something of the rich and powerful low-end that a guitar has?
I've looked at a few mandolas (tuned a 5th below mandolin) but so far nothing I've found has had anything like the guitar's power or sustain in that range. Is this a fool's errand?
Comment: Power and sustain might be difficult, because the sound characteristics is mainly made by the size and form of the instrument for accousting string instruments.
Comment: Hmm, perhaps a miniature child's guitar would be close?
Answer: Yes, you are on a fool's errand, but you might learn some new ideas while you are on it.
Why not consider a 4-string tenor guitar? Those are tuned in 5ths like a banjo. The lowest pitch on the tenor guitar is the C above the E on the regular guitar. But there is an alternate tuning for the tenor guitar where the lowest pitch is the G above the low E on the guitar, or a minor third higher. In the G tuning, the tenor guitar is tuned like a violin, but one octave lower.
You are aware of course of the issue that the mandolin is tuned in 5ths and the guitar is tuned in 4ths--I hope you are taking that into account.
There are a number of "baby" acoustic guitars on the market now which have the shortest possible scale length that can still accommodate standard guitar tuning.

A mandolin has a scale length of 356mm or 14 inches.
A standard acoustic guitar has a scale length of 648mm or 25.5 inches.
A "baby" guitar has a scale length of 584mm (23 inches) or 559mm (22 inches).

Any shorter than 559mm and you can't adequately produce the low "E" of a guitar.
Some "Baby" guitars of good quality:

Little Martin
Baby Taylor
Fender Squier Mini electric guitar

Be sure to check out specialty instruments by Gold Tone. They make some freaky cross-over hybrids between mandolins, guitars, basses, banjos--you'll just have to see the site and view the demos!
Gold Tone has a new mandolin with a 6-string guitar neck on it, tuned in 4ths, but of course it plays the range of the conventional mandolin. It does not go down to the lower octave of a real guitar. I played one of these at the Summer NAMM convention in Nashville last month. It's an impressive instrument, but it's not quite what you are looking for.
Then there are the octave mandolin, the Greek bouzouki, and the banjo, all of which do in fact go down close to the range of the guitar (and lower than the mandola), yet are tuned in 5ths, not 4ths.
Finally, as a left-field choice, if you want a real acoustic guitar, tuned like one, but you want the thinnest, narrowest neck, you might want to consider the Daisy Rock Girl Guitar brand. They are quite hideous in aspect but they are designed to be played by, well, girls, with small adolescent hands. Nothing wrong with that, mind you, but a sparkly pink guitar may not be your thing.
Comment: It's worth note that the "octave mandolin" Wheat mentions (i.e. the mandola tuned an octave below the mandolin) is also called the [octave mandola](http://www.hobgoblin.com/local/products/GR3216/Ashbury-Style-E-Octave-Mandola/) or (perhaps more correctly) the [tenor mandola](http://www.banjolin.co.uk/banjolin12/index.php?content=index&section=instruments&subsection=mandola).
Comment: Nice answer and welcome to the site!
Comment: Also worth checking out the Irish Bouzouki, which is generally bassier than it's Greek forefather.
Answer: You won't find anything with a short neck that plays guitar notes, because the range of available notes is a function of the length of the neck.
I would suggest a mandola, a mandocello or a bouzouki but they are not necessarily designed to offer as much sustain as a guitar- if you listen to music designed for those instruments it tends to be based on very rapid picking rather than individual sustained notes. You could perhaps adapt your playing style to accomodate this.
Or I guess you could try the viola, which is a very different type of instrument, but could offer the sustain and tonal characteristics you want.
Comment: I'd just add that for bouzouki and mandola, I've often heard them  played strumming-style on the folk scene.
Comment: "You won't find anything with a short neck that plays guitar notes" UBass, an ukulele bass with a ridiculously short scale length and the low notes of a bass guitar (!!!).
Comment: But... why???? Also from my experience of acoustic bass you would need a ridiculously huge body for that to be audible more than three feet away, which would make for a shonky-looking instrument.
Answer: Have you tried a ukulele? I don't know any other instruments that your looking for other then a ukulele
Comment: A baritone ukulele might fit the bill.
Answer: Here is a new instrument designed by Pono and Kilin Reece
Answer: What you want is a guitar bodied octave mandolin. That's a guitar sound with a neck tuned GDAE or GDAD. The sound is much deeper and fuller than a mandolin.
Answer: a tenor or bass ruan, perhaps?
Comment: That is an interesting suggestion, but a ruan sounds nothing like a guitar or a mandolin!
Comment: 'nothing like'? subjective evaluation of similarity in tone can be affected by context too. please try listening to some works played by the Singapore Ruan Xian Chamber Ensemble on youtube e.g. http://www.youtube.com/watch?v=xvn3PCatV7g http://www.youtube.com/watch?v=yZkUzL94_4o etc.
Answer: please search for:

Liuto cantabile /Liuto moderno    (for example: Calace or

http://www.musikalia.it/en/catalogue/instruments_list.asp?cat=4)
(there are not a lot of such instrumentmakers)

Mandocello (in some music-houses like thomann, Europe)

And ofcourse: Going to a luthier and ask for constructing a individual one.
But the luthier has to live too - it cant be so "cheap" like anindustrial one. (btw: in comparison with the lot of work, whats in a such instrument, its really "cheap" from the luthier too ...)
Answer: Frank with Republic Guitars here, I just shipped one of our Highway 49 tenor guitar's tuned to Octave Mando tuning to a customer and it sounds and plays great. I had to put different string gauges on it but I keep enough gauges on hand to accommodate. I used something close to the medium gauge example on http://rycooder.nl/pages/tenor_gauges.htm
Answer: Available in several Latin American countries are various instruments going under the name "tiple." These usually sound pretty good and come in various sizes. They should be available from Latin American instrument sources. Another possibility is the requito guitar which is popular in Mexico. (I'm not sure which is more important to you, the tuning in fifths or the short neck length.) All of these will sound a bit higher than a guitar. (As an aside, the guitarron. The Mexican one is like a big guitar; the Argentine has six strings and the Chilean one has 25 strings so seems more like lute. These are low but big.
Answer: A baritone guitar would also work in terms of range, though it will be lower than the guitar and might not have the scale length you want. Baritone ukulele would be similar, being the highest-pitched strings of a guitar on a shorter scale length.