Best approximation (infinity norm) of even functions

Question: Let $f\in C([-1,1])$ be an even function, i.e., $f(-x)=f(x)$ for all $x$. In fact, I've shown that its best approximation $p^{*}_{n}$ is even as well (Here the best approximation is in the sense of infinity norm, i.e., $\lVert f-p^{*}_{n}\rVert$). I want to show that for any $n\geq 0$, $p^{*}_{2n}=p^{*}_{2n+1}$ and if $f$ is not even, then for sufficiently large value of $n$, its best approximation $p^{*}_{n}$ is not even.
Comment: Is this homework?
Comment: @copper.hat It's an exercise in Approximation theory and approximation practice by L.N. Trefethen.
Answer: Note that the best approximating polynomial is unique.
Let $(Rf)(x) = f(-x)$ and let $p$ be the best approximation to $f$.
We have $\|f -p\| = \|Rf -Rp\| = \|f-Rp\|$. In particular, since the norm is convex, $p^*={1 \over 2} (p + Rp)$ satisfies $\|f-p^*\| \le \|f-p\|$ and so $p^* = p$.
Since $p^*$ is even, we obtain the desired result.
Suppose that $f$ is not even. Then there is some $x^*$ such that $f(x^*) \neq f(-x^*)$.Choose $\epsilon < {1 \over 4} |f(x^*)-f(-x^*)|$ and $p$ such that $\|f-p\| < \epsilon$.
Then $|p(x^*)-p(-x^*)| \ge   |f(x^*)-f(-x^*)| -  | p(-x^*)-f(-x^*)| -|p(x^*)-f(x^*)| > {1 \over 2} |f(x^*)-f(-x^*)|$ and so $p$ is not even.
Comment: Yes, I've shown this. But what if $f$ is not even? I guess a similar argument can show that if $f$ is odd, so is its best approximation.
Comment: Ah, I missed that part (to be fair, you did say that you wanted to show that $p^{*}_{2n}=p^{*}_{2n+1}$). Give me a moment.
Comment: I wonder how come $p^{*}_{2n}=p^{*}_{2n+1}$ given that they even have different degrees?
Comment: Note that in the even $f$ case, the optimal $p$ can only have non zero coefficients for even powers of $x$. Note that the odd powers cancel in $p + Rp$.


Enqueue and TryDequeue in ConcurrentQueue

Question: There is a ConcurrentQueue instance and two threads that access it concurrently. One thread enqueues items continuesly (may be enqueue few items in 100 micro seconds) and other thread TryDequeue item by item and do some processing. There is a ManualResetEvent to signal the processing thread after any item enqueue (this is not quite related to this question)
In this case, is there any possibility of adding items in wrong order to the ConcurrentQueue.  I know it's thread safe but just want to make sure whether it does not mess with the order of items when enqueue and dequeue quite faster.
Comment: It's a queue!  If it could reorder entries, they would have called it ConcurrentBingoMachine, ConcurrentLottery, ConcurrentShoppingTrolley or something.  The only way things get out-of-order on producer-consumer queue pipelines is if there is more than one consumer thread.
Comment: 'There is a ManualResetEvent to signal the processing thread after any item enqueue' :(
Comment: Aparrently, there is a 'ConcurrentBag' class, so, not ConcurrentBingoMachine :((
Comment: Agree with Martin. Perhaps you can post your actual issue with relevant code!
Comment: @MartinJames : Thanks for naming suggestions for unordered queues. BTW, could you explain "The only way things get out-of-order on producer-consumer queue pipelines is if there is more than one consumer thread." ?
Comment: @Harsha - if a pipeline of producer-consumer queues, one task may require much more processing than the others, eg. there is some special processing on a video frame.  It is therefore tempting, on a multicore box, to use more than one thread, (A and B, say), at that stage of the pipeline in order to make best use of the CPUs available and reduce overall latency.  The snag is then that thread A might get a frame first but thread B might finish first, so enqueueing its frame to the next stage before A and resulting in out-of-order video.
Comment: @Harsha - another 'classic' example is IOCP servers.  'IOCP' is M$-speak for an event queue with benefits.  Typically, a pool of user threads waits on an IOCP queue for socket-completion events.  It can happen that more than one thread can process read event buffers for the same socket and so assemble files and other data 'out-of-order', despite TCP guarantees:(  Typically, each socket object will maintain a sequence-number that is copied into each buffer and incremented biefore processing, so allowing buffers to be resequenced at a later stage if found out-of-order.
Comment: @MartinJames: Thanks, post this as the answer.
Answer: There is absolutely no way that the items can be out of order.
First of all, a queue by definition enforces a FIFO order: you put elements at one end and take them out at the other end. And since this is done by a single-producer-single-consumer model, it's absolutely safe.
Answer: It's a queue! If it could reorder entries, they would have called it ConcurrentBag or something. The only way things get out-of-order on producer-consumer queue pipelines is if there is more than one consumer thread.
Comment: I think ConcurrentShoppingTrolly is a better name


jquery scrolltop from Hash url

Question: i want to the page to smooth scroll to an anchor based on the hash URL when the page loads.
ie
www.domain.com/pagename/#matches
I have this, but it's not working
var elem = $('#_' + window.location.hash.replace('#', ''));
if(elem) {
     $('html,body').animate({
          scrollTop: $('#' + elem).offset().top-65
        }, 1000);
        return false;
}

Console error is
Syntax error, unrecognized expression: #[object Object]
Update
I got it working with
if(window.location.hash) {
     var elem = window.location.hash;
     $('html,body').animate({
          scrollTop: $(elem).offset().top-65
        }, 1000);
        return false;
}

However when the animation finishes, the default anchor action kicks in and thus jumps the page and ignores the offset im trying to achieve
Comment: share yur full code what you do
Answer: If I understood your question correctly then check if hash is found then extract it from url and pass it to scrollTop.
if(window.location.hash) {
      var hash = window.location.hash.substring(1);
      $(document.body).animate({
          'scrollTop':   $('#' + hash).offset().top
      }, 2000);
}

Comment: thank you, i actually got it working with

if(window.location.hash) {
   var elem = window.location.hash;
   $('html,body').animate({
     scrollTop: $(elem).offset().top-65
   }, 1000);
   return false;
    }

trouble is, after the animation scroll it still does the normal anchor jump and thus removes the offset im trying to achieve

jquery scrolltop from Hash url


How to determine whether song is 16 bar blues or 32 bar form?

Question: I'm analyzing blues in the Mississippi Delta tradition and the hardest/most subjective aspect I am running into has to do with songs with measure numbers divisible by 8. For example, we can use "Death Don't Have No Mercy," by Reverend Gary Davis. Depending on how I define the measure and the time signature, each verse either fits the AA'BA pattern of the 32-bar form or a 16-bar blues.
I will briefly write out the chord progression for reference:
<code>|Em -|Am    B|Em -|Em -|
|G  -|A7   D7|G  -|B7 -|
|Em -|Em    -|Am -|C7 -|
|Em -|C7B7 Em|Em -|Em -|

|i   -|iv     V|i   -|i   -|
|III -|IV7 VII7|III -|V7  -|
|i   -|i      -|iv  -|VI7 -|
|i   -|VI7V7  i|i   -|i   -|
</code>
As you can see, the way I have defined the measure and time signature, this verse fits as a 16-bar blues. But in that 14th bar, there's a chord change within a single beat. That one measure kinda makes me want to subdivide the whole thing again and call it a 32-bar blues. Each line would therefore become 8 measures, that C7 and B7 would get their own beats, and the verse would fit the AABA melodic pattern characteristic of a 32-bar sequence. So, how do I resolve the subjectivity of time measures? How do I classify this song in a way that will be consistent with other analysts?
Answer: I'd like to point out that the timing of your chords on the last line is not quite right. He also plays a B in the bass of the first chord of the last line. This is what it actually is, based on this version:

Em/B C7 |B7    |Em   |Em    ||
The song is 16 bars, it sounds and feels like it so there is no reason to write it as 32. 32 bars would make for an unnatural fast count.
Many songs have a chord on a single beat. That is no reason to interpret the song differently but in this case all the chords are at least 2 beats each.
It is also not an AABA form. The AABA form can be any number of bars, 32 or 16 or 64, but the reason it is not AABA is that in AABA The A sections are all either identical or very similar. In this song every group of 4 bars is unique. That makes it a 16 bar blues as you labeled it initially.
Comment: Thanks for the right transcription there.  Writing it that way takes away any reason to further subdivide!
Comment: @DuncanOcel A tip for the future, when transcribing go with the count that sounds most natural. For example, if there's a feeling of a backbeat make that 2 and 4. You did it in your transcription.
Answer: If the overall harmonic rhythm of this piece was consistently more than 2 chords per bar, your question would make more sense.   But there's only one instance here.
If the structure was:
|Em -|Am - B7 - |Em - - - |Em - - -|
|G - - -|A7 - D7 - |G - - - - |B7 - - -|
|Em - - -|G - C7 B7 |Em - - - |Em - - -|
you would have no hesitation in labelling it a 12-bar blues. I don't think adding another phrase makes it a 32-bar one.
Also:
If we're counting in 4/4 - and I hear 4 bars of 4 beats each in each line here -  most chords get two beats, in that one bar it's one beat each.  Not half a beat.
Check bars 13 and 14 of your chord transcription.  I don't think you've got it quite right.
If you call C7 VI7 in E minor, what would you call the equally likely C♯7?
Comment: Got it. I guess C7 in the key of Em is really bVI7. Thanks for the tip!


Android - DatePicker em um editText

Question: Seguinte, gostaria que aparecesse um seletor de data assim que clica no editText que tenho, mas oq eu achei ta colocando automaticamente a data atual, quero que possa ser escolhido...
Segue o código que eu tentei até agora:
public class AtividadePrincipal extends AppCompatActivity {
ListView lvLista;
List<String> nomes;
EditText data1;
Calendar dateSelected = Calendar.getInstance();
private DatePickerDialog datePickerDialog;
String myFormat = "dd-MM-yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat);

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_atividade_principal);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
 data1.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            setDateTimeField();
           // showDialog(DATE_DIALOG_ID);
            return false;
        }
    });

private void setDateTimeField() {
    Calendar newCalendar = dateSelected;
    datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            dateSelected.set(year, monthOfYear, dayOfMonth, 0, 0);
            data1.setText(sdf.format(dateSelected.getTime()));
        }

    }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
    data1.setText(sdf.format(dateSelected.getTime()));
}
}

segue o xml do editText data1:
<EditText
                android:id="@+id/data1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="15dp"
                android:layout_marginTop="15dp"
                android:background="@drawable/cantos_arredondados"
                android:drawableRight="@drawable/icone_cor_diferente"
                android:hint="Data1"
                android:inputType="date"
                android:paddingTop="8dp"
                android:textColor="@color/colorAccent" />

Answer: Tente dessa maneira:
Calendar myCalendar = Calendar.getInstance();

DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        myCalendar.set(Calendar.YEAR, year);
        myCalendar.set(Calendar.MONTH, monthOfYear);
        myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        updateLabel();
    }

    };

   edittext.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
      new DatePickerDialog(classname.this, date, myCalendar
               .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                myCalendar.get(Calendar.DAY_OF_MONTH)).show();
        }
    });

    private void updateLabel() {

        String myFormat = "dd/MM/yyyy"; //In which you need put here
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, new Locale("pt","BR"));

        edittext.setText(sdf.format(myCalendar.getTime()));
    }

Comment: Obrigado, me ajudou bastante. Só recomendo usar `OnFocusChangeListener` ao invés de `OnClickListener`, assim como fiz na minha aplicação.
Comment: deu super certo! obrigado

Android - DatePicker em um editText


How do I convert hook_menu()?

Question: I am having site built in Drupal 7 and in future I want to migrate my site to Drupal 8.
How can I write hook_menu() and hook_menu_alter() to routing.yml files?
Answer: Here is an example taken from All functionality of hook_menu() is replaced by new systems for routing, menu links, local tasks, actions and contextual links:
Drupal 7
in modules/book/book.module:
function book_menu() {
   $items['book/export/%/%'] = array(
    'page callback' => 'book_export',
    'page arguments' => array(2, 3),
    'access arguments' => array('access printer-friendly version'),
    'type' => MENU_CALLBACK,
    'file' => 'book.pages.inc',
  );
    $items['node/%node/outline'] = array(
    'title' => 'Outline',
    'page callback' => 'book_outline',
    'page arguments' => array(1),
    'access callback' => '_book_outline_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
    'file' => 'book.pages.inc',
  );
...
  return $items;
}

Drupal 8
in modules/book/book.routing.yml:
book_export:
  pattern: '/book/export/{type}/{node}'
  defaults:
    # What's being returned is the entire response (not HTML, or even if HTML, we don't want additional blocks around it), so use _controller instead of _content.
    _controller: '\Drupal\book\BookController::export'
  requirements:
    _permission: 'access printer-friendly version'
book_node_outline:
  pattern: '/node/{node}/outline'
  defaults:
    _controller: '\Drupal\book\BookController::outline'
  requirements:
    # Indicates that the book outline access access system should be invoked.
    _book_outline_access: TRUE

Answer: Here is the link of blog to convert your hook_menu to routing.yml file.
Well to understand a simple routing.yml  :
route.name:
  path: '/path/of/page'
  defaults:
    _title: 'Title of Page'
    _controller: '\Drupal\modulename\Controller\ClassName::methodName'
  requirements:
    _permission: 'permission name'

This is an example of simple routing.yml file.
route.name : Name of route which should start with your module name.
path :  Path of the page.
_title : Title of page
_controller : Class that returns the content of page.
_permission : Permission of page.
To set the access_callback, parameter upcasting there are various different ways. To set the menu link and menu tab two more files that you have to write.
webform.links.menu.yml and webform.links.task.yml.

How do I convert hook_menu()?


Getting column name ambigous

Question: I have query in which i am getting column 'month' ambigious . I am trying with following query. Please check nd help me.
SELECT SC.name as sc,
       B.name as brand,
       COUNT(T.id) as tc,
       SUM(IF(is_category_present = 1, 1, 0)) as BASE
FROM outlet_categories OC
     INNER JOIN transactions T ON OC.outlet_id = T.outlet_id
     inner join outlets O on O.id = T.outlet_id
     inner join brands B on T.brand_id = B.id
     inner join sale_channels SC on SC.id =  O.sale_channel_id
WHERE T.month = month

Comment: Possible duplicate of [Ambiguous column name error](http://stackoverflow.com/questions/318066/ambiguous-column-name-error)
Comment: need to define the table aliase in where cluase WHERE T.month = month
Comment: Since that column name exists in at least two tables, you have to qualify it each time it's referenced, just like `T.month`.
Comment: Did you search for your problem? This question has been asked many many many times before.
Comment: You need to use the table alias for your final month in the WHERE clause.
Answer: Qualify all your column names.  It is not clear what the right names are, but these need table aliases:
SELECT SC.name as sc, B.name as brand,
       COUNT(T.id) as tc,
-------^ Looks like an aggregation query, but there is no `GROUP BY`.
       SUM(IF(is_category_present = 1, 1, 0)) as BASE
--------------^
FROM outlet_categories OC INNER JOIN
     transactions T
     ON OC.outlet_id = T.outlet_id INNER JOIN
     outlets O
     ON O.id = T.outlet_id INNER JOIN
     brands B
     ON T.brand_id = B.id INNER JOIN
     sale_channels SC
     ON SC.id =  O.sale_channel_id
WHERE T.month = month;
----------------^

Three notes about MySQL:

Your IF() is not necessary.
I am guessing that month is a variable.  If so, name it something else.
Presumably, you want a GROUP BY.

A better version of the query:
SELECT SC.name as sc, B.name as brand, COUNT(T.id) as tc,
       SUM(??.is_category_present) as BASE
FROM outlet_categories OC INNER JOIN
     transactions T
     ON OC.outlet_id = T.outlet_id INNER JOIN
     outlets O
     ON O.id = T.outlet_id INNER JOIN
     brands B
     ON T.brand_id = B.id INNER JOIN
     sale_channels SC
     ON SC.id =  O.sale_channel_id
WHERE T.month = v_month
GROUP BY SC.name, B.name;

The variable month has been renamed v_month, so it is no confused with a column name.  MySQL will interpret T.month = month as T.month = T.month -- assuming that month is only in the T table.  And, I'm guessing that T.month = T.month is not your intention.
Answer: If you have a column named month in more than one table then you have to specify the table it comes from, otherwise the database doesn't know which of the columns named month you refer to.
Comment: yes month field is iin Outlet_category and transactions T. can you please tell me, how you are saying?
Answer: SELECT SC.name as sc,
       B.name as brand,
       COUNT(T.id) as tc,
       SUM(IF(is_category_present = 1, 1, 0)) as BASE /* <-- from with table this column? add alias*/
FROM outlet_categories OC
     INNER JOIN transactions T ON OC.outlet_id = T.outlet_id
     inner join outlets O on O.id = T.outlet_id
     inner join brands B on T.brand_id = B.id
     inner join sale_channels SC on SC.id =  O.sale_channel_id
WHERE T.month = month /* <-- from with table this column month? add alias*/

This error means than you have, for example, column test in several tables and SQL doesn't know where take this column - from table1 or table2, for example.

Getting column name ambigous


sankey highchart - Pulando colunas

Question: Estou implementando um Sankey Diagram usando o Highcharts JS e estou tentando colocar uma linha que acessa a primeira coluna para a terceira coluna. Isso é possível?
Por exemplo: http://jsfiddle.net/morn2e4g/18/
Nesse caso, estou tentando colocar uma linha do Brasil para a Alemanha, mas não mova a Alemanha para a segunda coluna.
Answer: Simplesmente adicionar <code>['Brazil', 'Germany', 2 ],</code> não resolve? (http://jsfiddle.net/morn2e4g/91/)
Foi criada uma linha do Brasil para Alemanha e a mesma continua na terceira coluna.

sankey highchart - Pulando colunas


Show that a set of logical connectives given with W(p, q, r) is complete

Question: I just stuck upon a discrete maths-related problem with proving that a set of logical connectives is complete. I already know how to prove that ("basic") sets are full (examples like show that the given set of connectives is complete: $\{\lnot, \Rightarrow\}$), but I got stuck upon the following example...
Three-figure logical connective $W(p,q,r)$ is defined as $W(p,q,r) \equiv (p \lor q) \Rightarrow \lnot r$. Proove that set $\{W\}$ is a complete set of connectives.
What should I do here? I know that a known complete set is $\{\lnot, \land, \lor\}$ and that I should "derive" each one of those connectives with $(p \lor q) \Rightarrow \lnot r$, but how should I even start?
P.S.: I'm sorry if the translation of the assignment isn't 100% accurate, because English is not my first language and this assignment is given in my native language :)
Comment: $p \lor q \Rightarrow \lnot r$ is equivalent to $(\lnot p \land \lnot q)\lor \lnot r$
Answer: W(p,p,p) is equivalent to $p \implies \neg p$
which is equivalent to $\neg p \lor \neg p.$
$ W(p,p,\neg q)$
is equivalent to $p \implies q.$
Exercise.  Show {$p \implies \neg q$}
is a complete set of connectives.
Answer: Hint: see what happens when you use only one or two distinct arguments.  For example, what does $W(p, p, p)$ yield?


Have these (extremely simple) classes of algebraic structures been considered in the literature? If so, what are they called?

Question:
Questions. Have the following kinds algebraic structures been considered in the abstract algebra literature etc.? If so, what are they really called? (I have used made-up terminology for the sake of the question.)

A woodland is a set equipped with an $n$-ary operation $f_n$ for each integer $n \geq 0$. (Observe that every woodland has a distinguished element corresponding to the case $n=0$).
A jungle is a woodland such that we can permute the arguments of $f_n$ willy-nilly. In particular, $(X,f_*)$ is a jungle iff for all integers $n \geq 0$ and all permutations $\pi$ of $\{0,\ldots,n-1\},$ it holds that $f_n(x_0,\ldots,x_{n-1}) = f_n(x_{\pi(0)},\ldots,x_{\pi(n-1)}).$

Motivation. The rooted trees of graph theory form a jungle in an obvious way, and this is (isomorphic to) the initial jungle. Similarly, the ordered rooted trees form a woodland in an obvious way; and, this is the initial woodland.
Comment: Basically, if there are multiple operators and no relations between them, we really can only study one operator at a time - they do not interact. Imagine a ring without the distributive law.
Comment: I don't think it makes sense to study objects with multiple operations unless there is a relationship between the various operations.  Otherwise you would just study each operation independently.  There is something called an Operad, which is much more complicated, but bears some similarity to the kind of objects you are talking about.
Comment: @amcalde But we could really choose, for each $n$, any function  $f_n:X^n/S_n\to X$. Lacking any logical relationship between the operators, this is just a random collection of functions.
Comment: @goblin, Just say that $1$ wins on ties. Then this modified MAJ function is a woodland. Actually it's a jungle since it's all symmetric. Another jungle I can immediately think of is the popcount function mod 2. (Add up the number of ones mod 2 for any Boolean input).
Comment: This seems like a generalization of Boolean funcitons for a woodland. And symmetric Boolean functions for the second? No?
Comment: @amcalde, I'm not really seeing the connection. Can you elaborate?
Comment: Well a Boolean function takes $n$ arguments from the set $X = \{0,1\}$ and returns either $1$ or $0$ so from what I understand, it's like your woodland. $f: X^n \rightarrow X$. Except that your woodland seems to have some particular Boolean function picked out for each $n$.
Comment: So, for example the majority vote function on $X$ is a woodland because for any $n$ inputs the function $f_n$ is given as the majority vote on $n$ bits. (Of course you'd have to define what happens when $n$ is even and there is a tie.)
Comment: @amcalde, true. Nice observation. **Edit** actually I'm not quite sure how to make majority vote into a woodland. We have a majority vote function $B^n \rightarrow B$ for $n$ odd only, I think...
Comment: Well, there is supposed to be only one $f_n:X^n\to X$ in this structure. But I think the real problem is that there really isn't any conditions on these functions (except symmetry in the jungle) which means that it probably covers *too* many algebras. For example, any algebra with a unary and binary operation can be made into a woodland, with commutativity and associativity implying it would be a jungle.
Comment: @ThomasAndrews, you're right, of course. I guess such structures aren't very interesting beyond the free algebra monad they define.
Comment: That free algebra has an interesting additional unary function which maps a rooted tree to the merger of the child trees (so it takes the tree, and identifies the root node with all of its children, yielding a new rooted tree.) Then the algebra has some interesting relationships.
Comment: @ThomasAndrews, I think I understand what you mean. Syntactically, we're flattening things. So $((x,y),(x,x,y))$ becomes $(x,y,x,x,y)$. Is this right?
Comment: Yes. If that unary function is $T$ (for truncate) then $Tf_1$ is the identity, $Tf_n(u_1,\dots,u_n)=Tf_2(u_1,Tf_{n-1}(u_2,\dots,u_n))$. Lots more relationships. Basically $Tf_n$ could be defined in terms of $Tf_2$ ultimately, and $Tf_2$ would be associative.
Comment: Even more interesting: $f_{m+n}(u_1,\dots,u_m,v_1,\dots,v_n)=T(f_2(f_m(u_1,\dots,u_m),f_n(v_1,\dots,v_n)))$. This would mean every $f_n$ can be defined in terms of $f_1,f_2,$ and $T$.
Answer: A "woodland" would be an algebra over the free nonsymmetric operad $W$ with one generating operation in each arity $n \ge 0$ and no relations. Similarly a "jungle" would be an algebra over the free symmetric operad $J$ with one generating operation in each arity $n \ge 0$ and $\Sigma_n$ acts trivially on the $n$th generating operation. Trees appear naturally because this is what operads are built on. It seems to me that the set of (resp. ordered) rooted trees is in fact the free $W$-algebra (resp. $J$-algebra) over the empty set (the initial set), which explains why they're initial in their category of algebras.
I don't believe these things have been studied on their own, as they have very little structure; consider that a magma is a woodland where all the $f_n$ are trivial for $n \neq 2$, and magmas aren't particularly studied. They're more of an intermediary technical tool.
One (rather silly) thing I can say is that if you consider a linear version of this and remove the operations in arity $0$ and $1$, then the first one is the ungraded underlying operad of the dg-operad $A_\infty$ controlling homotopy associative algebras (it would have $\operatorname{deg} f_n = n - 2$ and a differential $\partial(f_n)$ that I don't want to write down). I guess you can relate the second one to some shifted version of $L_\infty$. I doubt this is what you had in mind though.
Comment: If you decide that $f_n(x_1, \dots, x_{n-1}, f_0) = f_{n-1}(x_1, \dots, x_{n-1})$ (as suggested in the comments, I didn't read them all), then the operad starts looking quite different.


What's the term for rapidly blending two pitches a single time in a beat?

Question: Here's some examples of what I mean:
A chiptune song's lead synth (@ 0:31)
A song from Touhou (@ 0:51)
Is there a general term for this? Is the term for the vocals version different to the term for the lead synth version?
Thanks
Comment: Sorry, I am afraid I don't understand what you are referring to specifically.  Could you try and explain it in some different words?
Comment: This question could be improved by including a written description, as best you can, of what the aural effect you're asking about is.
Comment: Do you mean rapidly "sliding" from one pitch to another or having two different pitches playing at the same time?
Answer: In terms of electronic music, the term "pitch bend" is probably the most common, easily understood, and appropriate term for both cases.
In a more classical/formal context, the musical term for this kind of continuous variation in pitch is portamento, which applies whether it is fast (as in your examples) or slow.  This term applies to all musical instruments that allow continuous pitch variation, including voice.  Sometimes the term glissando is used though this latter term usually indicated that you hit a set of closely-spaced discrete notes. The usual example of this is sweeping your hand along a piano keyboard.
As an illustration of the difference between these general music terms in terms of synths, portamento is what you get if you mess with a pitch bend wheel, and glissando is what you get when you drag your finger across the keyboard.
Note that glissando and portamento usually involve going in only one direction (up or down).  Your second, vocal, example returns to the original pitch,
so these terms might not be the best to use (pitch bend should work fine though).  The term melisma is particularly appropriate for this kind decoration in vocals.
Comment: I could hear portamento in the synth example and that was going to be my answer... but then I couldn't spot it in the vocal one (in which I could hear something more like the auto-tune pitch jumping effect)
Comment: Most synths have both a mod wheel for controlling modulation depth (LFO amount, etc) and pitch bend controller which is a separate controller with different physical behavior. As there is usually a dedicated pitch controller, the mod wheel is very rarely used to change pitch. Topo is spot on regarding the glide function, Which is separate from pitch bend in midi terms but both affect the same voltage in vintage CV/modular terms.
Comment: "Bending" is another word used for this, especially for some instruments and genres like harmonica and guitar in blues and rock. "Slide" and "glide" are sometimes used, again depending on the situation.
Comment: *portamento is what you get if you mess with a mod-wheel* - in synth-jargon specifically, portamento tends to be used more specifically to describe a setting of the synth voice that causes the pitch to glide *without* the player needing to touch the  pitch bend or mod wheel (sometimes this can be set to only happen with legato playing)
Comment: @ToddWilcox on some synths the control wheels are re-assignable, on some synths one is dedicated to pitch bend.  I thought that the term "mod-wheel" was an appropriate generic term for this kind of wheel controller, whatever function they are assigned to.


How to draw connection between drawitems?

Question: I want to develop a workflow Tool with smartgwt. My problem is to draw relationships between drawitems. I tried libary gwt-connectors, but its not working on canvas,only on AbsolutePanels. Can anybody help me? Thanks! :)
Answer: Since AbsolutePanel implements the interface IsWidget it should be no Problem to embedd a AbsolutePanel into a SmartGWT Canvas.
For Example:
<code>AbsolutePanel boundaryPanel = new AbsolutePanel();
//draw diagram into baundaryPanel...
Canvas wrapper = new HLayout();
wrapper.addChild(boundaryPanel.asWidget());
</code>
Comment: that is also not working...i found out,, that i only can connect HTML, Image or Label-Widgets with gwt-connectors :(
Comment: Ok, than I would recommend you to use another library. For instance I used gwt-links which is a very impressive library for such a usecase. Espacially for your workflow tool this library could be a good match.
Comment: Ok thanks! Are there any showcases? Or do you have an example how to draw connection with this libary?
Comment: Unhappily the showcase seems to be broken.
But there is a [video](http://www.youtube.com/watch?v=sd9Hw83x5lg) that  shows a single example of the showcase. When you want to get started with that library you could use the [gwt-links-wiki](https://code.google.com/archive/p/gwt-links/wikis/GettingStarted.wiki).
Comment: thats exactly what i need! i will try that :)
Comment: Which widgets do you want to resize?
Comment: Ich want to resize images:)
Comment: For example you could wrap the image into a Layout and [let a user resize this HLayout](http://www.smartclient.com/smartgwt/showcase/#layout_user_sizing).
Comment: that works now, thank you! one last question...how can the user draw connection between two hlayouts?
Comment: A user could connect widgets after they are added to the DiagramController
Comment: hmm...i can resize and drag the images (hlayout with image as background) around, but there are no knobs shown to connect them, like in the video. what could be wrong?
Comment: Preferably you could compare your solution with the [source code of the examples](https://github.com/prenaudin/gwt-links/tree/master/gwt-links-parent/gwt-links-demo/src/main/java/com/orange/links/demo/client/example)


How do I get the type of a blessed ref? (ARRAY|HASH|SCALAR)

Question: I'm passed a reference, and I want to know its type. For this purpose,
"ref" works on unblessed references, but on blessed references it returns
the package name it was blessed with.
<code>     $a=[];
     print ref $a;
</code>

ARRAY

<code>     bless $a, 'mytype';
     print ref $a;
</code>

mytype

How can I get the type?
Comment: Duplicate of http://stackoverflow.com/questions/11085/how-can-i-determine-the-type-of-a-blessed-reference-in-perl
Answer: <code>use Scalar::Util 'reftype';
print reftype bless {}; # HASH
</code>
Comment: pedantically, use Scalar::Util 1.01 'reftype';   since reftype was added less than 10 years ago, some poor souls may be lacking it.
Answer: You can use Scalar::Util::reftype for this, but in general it isn't something that you need to do.  Usually people asking this question indicates they are doing something else in a less than ideal way.  So, why do you think you need to know?
Comment: It's true.  Once you bless something, you shouldn't access the underlying data directly.  (Sometimes it's useful to do anyway, though, if you are Data::Dumper or Data::Visitor or something.)
Comment: You should implement a dump() method on the object that you can call, which will do Data::Dumper-like activities and keep the type-aware code locked inside the module.
Comment: I know what I'm doing; namely, implementing something akin to Data::Dumper but into a specific format.
Comment: No, he should use Data::Visitor.
Answer: As stated in a comment above.. you are incorrect if you think that external code needs to be aware of the implementation details of a blessed object.  If you need to do something like Data::Dumper on the object, create a dump() method on the module which contains the implementation logic.  You could add some code into the UNIVERSAL class's autoloader so that it just calls Data::Dumper if you attempt to call dump() on an object that doesn't define it.


Unable to access query

Question: I get db cannot be resloved error in this class. At the displayListView() function. Can anyone please help me solve it. Thanks
got code from here http://kdehairy.com/2012/08/19/using-a-preloaded-sqlite-database-with-sqliteopenhelper/
public class PrepopSqliteDbActivity extends Activity {
// private static final String DB_NAME = "hymnals";

//A good practice is to define database field names as constants

 private SimpleCursorAdapter dataAdapter;
 private Context context;

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

    //Our key helper
    ExternalDbOpenHelper repo = ExternalDbOpenHelper.getInstance( context );

    SQLiteDatabase  db = repo.getWritableDatabase();

    displayListView();

}

 private void displayListView() {

 //all hymns are fetched
  *final Cursor cursor = db.fetchAllHymns();*

  // The desired columns to be bound
  String[] columns = new String[] {

          ExternalDbOpenHelper.HYMN_ID,
          ExternalDbOpenHelper.HYMN_NAME,

  };

  // the XML defined views which the data will be bound to
  int[] to = new int[] {
    R.id.tVid,
    R.id.name,

  };

 // create the adapter using the cursor pointing to the desired data
 //as well as the layout information
     dataAdapter = new SimpleCursorAdapter(
    this, R.layout.activity_main,
    cursor,
    columns,
    to,
    0);

  ListView listView = (ListView) findViewById(R.id.list);
 // Assign adapter to ListView
  listView.setAdapter(dataAdapter);

  listView.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> listView, View view,

     int position, long id) {

// Get the cursor, positioned to the corresponding row in the result set

   Cursor cursor = (Cursor) listView.getItemAtPosition(position);

// Get the state's capital from this row in the database.

   }

  });

 }

  }

Answer: The variable db is a local variable within the onCreate method. Use an instance variable instead:
class /* ... */ {
    private SQLiteDatabase db;
    /* ... */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        /* ... */
        db = repo.getWritableDatabase();
        /* ... */
    }
    /* ... */
}

Comment: But now fetchAllHymns() is undefined for type SQLIteDatabase
Comment: @Azeem `fetchAllHymns` is your creation. The method `fetchAllHymns` is not part of the Android framework, so I'd really wonder if it were available. From another question of yours I'd guess that you want `repo` as instance variable and that it supports that method.

Unable to access query


How is OLS estimator converging in quadratic mean equivalent to its variance matrix converging to $0$?

Question: $\newcommand{\E}{\mathbb{E}}$ $\newcommand{\Var}{\text{Var}}$ $\newcommand{\b}{\beta}$
Sorry that my title is not clear (if there is any better suggestions, I will edit it as soon as I can)
I want to show that under some conditions, $\hat{\b}\overset{q.m.}{\to}\b$, i.e. $\E[|\hat{\b} - \b|^2]\to 0$ is equivalent to $\Var(\hat{\b})\to 0$, where $\hat{\b}, \b$ are vectors.
($\hat{\b}$ is OLS estimator)
And I found the relation as follows: $$
\begin{align*}
 \E|\hat{\b} - \b|^2 &= \E [\hat{\b}^2 - 2\hat{\b}\b + \b^2] \\
   &= \E[\hat{\b}^2] - 2\b\cdot \E\hat{\b} + \b^2 \\
   &= \E[\hat{\b}^2] - (\E\hat{\b})^2 \;\;\text{since $\E\hat{\b} = \b$} \\
   &= \Var(\hat{\b})
\end{align*}$$
However, it only does make sense if all variables are univariate, i.e. $\hat{\b}, \b\in\mathbb{R}$ (or $\mathbb{C}$) since $\Var(\hat{\b})$ is a matrix.
How can I improve this and show that $\hat{\b}\overset{q.m.}{\to}\b$ is equivalent to $\Var(\hat{\b})\to 0$ in multivariate case?
Any help will be appreciated!
Comment: I think the following would be useful but doesn't directly answer your question if I understand correctly: http://personal.psu.edu/drh20/asymp/lectures/asymp.pdf
Comment: @gunes Right, but $E |\hat{\beta} - \beta|^2 = E[(\hat{\beta} - \beta)^{T}(\hat{\beta} - \beta)]$ (if I am correct) and I don't know how to relate $E |\hat{\beta} - \beta|^2$ and $\text{Var}(\hat{\beta})$ further
Comment: @gunes Or you mean the first expression is $E[(\hat{\beta} - \beta)(\hat{\beta} - \beta)^{T}]$? If it is, my question has been solved
Comment: No, it's as yours, the L2-norm. Is the last expression $Var(\hat \beta)$ or $Var(|\hat\beta|)$?
Comment: @gunes It's just $\text{Var}(\hat{\beta})$
Answer: Couple facts:

In general, if $v$ is a random vector, where each entry has finite second moments, then
$$
E[ \|v\|_2^2] = E[v'v] = E[\mbox{trace}(vv')] = \mbox{trace} (E[vv'])
$$
If $v$ has mean zero, then $E[vv']$ is the variance-covariance matrix.

Suppose $Q_n$ is a sequence of positive semidefinite matrices. Then $Q_n \rightarrow 0$ (in any one of the equivalent matrix norms), if and only if $\mbox{trace}\, Q_n \rightarrow 0$.

Then your calculation in the single variable case extends essentially verbatim, after replacing $v $ by $\hat{\beta} - \beta \,(= \hat{\beta} - E[\hat{\beta}]$): By Fact 1, the quadratic-mean (squared) distance between $\hat{\beta}$ and $\beta$ is
\begin{align*}
E[\|\hat{\beta} - \beta\|^2_2] = \mbox{trace} (E[(\hat{\beta} - \beta)(\hat{\beta} - \beta)']).
\end{align*}
Since it's assumed that
$$
E[(\hat{\beta} - \beta)(\hat{\beta} - \beta)'] \rightarrow 0,
$$
Fact 2 implies
$$
\mbox{trace} (E[(\hat{\beta} - \beta)(\hat{\beta} - \beta)']) \rightarrow 0.
$$
Notice we have made the assumption (as you did) that $\hat{\beta}$ is unbiased, $E[\hat{\beta}] = \beta$. (This is true, for example, under the Gauss-Markov type assumption $E[\epsilon|X] = 0$.) In general, vanishing variance-covariance matrix just means
$$
E[\|\hat{\beta} - \beta\|^2_2] - \| E[\hat{\beta}] - \beta \|_2^2 \rightarrow 0.
$$
Comment: Does the following also make sense then? trace$(E[Q_nQ_n'])\to 0$ iff $E[Q_nQ_n'] \to 0$? Or is it one side (like if trace$(E[Q_nQ_n'])\to 0$, then $E[Q_nQ_n'] \to 0$)?
Comment: $trace(E[v v']) \rightarrow 0$ if and only if $E[vv'] \rightarrow 0$ (in operator norm, to the zero matrix). "$E[vv'] \rightarrow 0$" is the multivariate generalization of $Var(v) \rightarrow 0$, for mean zero random vectors.
Answer: The problem here is that it is not (entirely) clear how you want to generalise the squared error to the multivariate case.  There are two obvious ways you can do this depending on what is of interest to you.  One generalisation is to use the inner product, leading to the squared norm of the estimation error.  The other generalisation is to use the outer product, leading to the variance matrix.
I will illustrate each of these generalisations below.  To start with, we note that in either case the OLS estimator in the multiple linear regression model leads to the form:
$$\begin{equation} \begin{aligned}
\hat{\boldsymbol{\beta}}
&= (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} \mathbf{Y} \\[6pt]
&= (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} (\mathbf{X} \boldsymbol{\beta} + \mathbf{\epsilon}) \\[6pt]
&= \boldsymbol{\beta} + (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} \mathbf{\epsilon}. \\[6pt]
\end{aligned} \end{equation}$$
From this equation we see that the estimation error is the vector:
$$\hat{\boldsymbol{\beta}} - \boldsymbol{\beta} = (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} \mathbf{\epsilon}.$$

Generalising to the squared norm (using the inner product): Using the above form for the OLS estimator you can write the squared norm of the estimator error by the inner product of the estimation error:
$$\begin{align}
||\hat{\boldsymbol{\beta}} - \boldsymbol{\beta}||^2
&= (\hat{\boldsymbol{\beta}} - \boldsymbol{\beta})^\text{T} (\hat{\boldsymbol{\beta}} - \boldsymbol{\beta}) \\[6pt]
&= ((\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} \mathbf{\epsilon})^\text{T} ((\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} \mathbf{\epsilon}) \\[6pt]
&= \mathbf{\epsilon}^\text{T} \mathbf{x} (\mathbf{x}^\text{T} \mathbf{x})^{-1} (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} \mathbf{\epsilon} \\[6pt]
&= \mathbf{\epsilon}^\text{T} \mathbf{x} (\mathbf{x}^\text{T} \mathbf{x})^{-2} \mathbf{x}^\text{T} \mathbf{\epsilon}, \\[6pt]
\end{align}$$
which is a quadratic form of the error vector $\mathbf{\epsilon}$.  Using the standard rule for expectation of a quadratic form you then have:
$$\begin{align}
\mathbb{E}(||\hat{\boldsymbol{\beta}} - \boldsymbol{\beta}||^2)
&= \sigma^2 \text{tr}(\mathbf{x} (\mathbf{x}^\text{T} \mathbf{x})^{-2} \mathbf{x}^\text{T}). \\[6pt]
\end{align}$$
Obviously this is just a scalar value, and it does not correspond to the variance matrix of the estimator.  Nevertheless, there are various sufficient conditions you can impose on the limit of the design matrix to ensure that this value converges to zero.

Generalising to the variance matrix (using the outer product): Using the above form for the OLS estimator you can write the variance of the estimator by the outer product of the estimation error:
$$\begin{align}
(\hat{\boldsymbol{\beta}} - \boldsymbol{\beta}) (\hat{\boldsymbol{\beta}} - \boldsymbol{\beta})^\text{T}
&= ((\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} \mathbf{\epsilon}) ((\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} \mathbf{\epsilon})^\text{T}  \\[6pt]
&= (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} (\mathbf{\epsilon} \mathbf{\epsilon}^\text{T}) \mathbf{x} (\mathbf{x}^\text{T} \mathbf{x})^{-1}.  \\[6pt]
\end{align}$$
Using standard moment rules you then have:
$$\begin{align}
\mathbb{V}(\hat{\boldsymbol{\beta}})
&= \mathbb{E}((\hat{\boldsymbol{\beta}} - \boldsymbol{\beta}) (\hat{\boldsymbol{\beta}} - \boldsymbol{\beta})^\text{T}) \\[6pt]
&= (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} (\mathbf{\epsilon} \mathbf{\epsilon}^\text{T}) \mathbf{x} (\mathbf{x}^\text{T} \mathbf{x})^{-1} \\[6pt]
&= \sigma^2 (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} \boldsymbol{I} \mathbf{x} (\mathbf{x}^\text{T} \mathbf{x})^{-1} \\[6pt]
&= \sigma^2 (\mathbf{x}^\text{T} \mathbf{x})^{-1} (\mathbf{x}^\text{T} \mathbf{x}) (\mathbf{x}^\text{T} \mathbf{x})^{-1} \\[6pt]
&= \sigma^2 (\mathbf{x}^\text{T} \mathbf{x})^{-1}. \\[6pt]
\end{align}$$
If your regression model has $m$ terms (so that the design matrix $\mathbf{x}$ is an $n \times m$ matrix) then this variance matrix is an $m \times m$ matrix.  It is possible to impose conditions on the limit of this matrix form so that the variance "converges to zero" in an appropriate sense.


How to read Bach's Prelude C#?

Question: The Prelude in C# major (BWV 848) with 7 sharps looks quite difficult for reading. Is there an easier way to decipher and analyse this piece and understand what's happening, especially the secondary dominants.
How could this be explained to a beginner who is not so skilled with reading and has no great idea of secondary dominants.
Let's assume she/he knows: The dominant chord of C is G, and as the dominant of G is D7 this dominant of G is a secondary dominant, while C can become as C7 a secondary dominant of F (the subdominant of C).
Comment: Why is the key signature done like that, it is the first time I saw that.
Comment: @Neil Meyer: and as we  know ... Bach notated it in C-clef ... I don't know that a modern editor would publish it this way. Notating an F# in the lower octave is less "rewriting" than editing  in treble-clef, don'r you think?
Comment: This question is related and referring to https://music.stackexchange.com/questions/95223/enharmonic-key-signatures-in-bachs-well-tempered-clavier, and answers are meant to help  reading a tricky  composition full of sharps and  to help and understand the wired functions of secondary dominant (like ii-V7/ V or V7/ii and V7/V etc.) I have a waste one in preparation. Others - shorter - are welcome.
Comment: I think I've seen something similar by Bartok. This edition is of Franz Kroll
 - Bach-Gesellschaft Ausgabe, Band 14 (pp.10-13)
Leipzig: Breitkopf und Härtel, 1866. Plate B.W. XIV. Btw. I didn't think about the signature like that might make it easier for reading. ;)  But there's also an edition by Franz Kroll in Db  which I mean to poste.
Comment: Publisher should not have the right to rewrite a piece. If it is written in C# exactly what is the publishers qualifications to say it should be in DB?
Comment: you can publish what you like after 70 years of  the  composer's dead. I don't know whether there has been in 1866 a copyright like we have today. And Bach has used (transcription and adaption) the works by Vivald and others. And also this Prelude seems to have already existed before in C- major.
Comment: The relations between notes are the same as any major key, and they're on the same position on the stave as the note one semitone lower. C - G is the same relation as C# to G#. So it's relatively easy compared to, say, Ebm.
Comment: @NeilMeyer, so someone can publish a transcription or arrangement which could include key changes, but it's not OK to publish with a key change for keyboard?!? What's your qualification to imposing that on others? And from checking IMSLP autographs, Albrecht is right, it uses C clef, and also repeats sharps at the octaves in the key signature.
Answer: If you find it easier to visualise in C major, you could ignore the key signature and read accidental double sharps as sharps, naturals as flats.
But why choose this piece to teach secondary dominants? PLAY this one, if it's at a suitable technical level for this student. I agree, the harmony might be clearer in C major.  But this piece ISN'T in C major! Surely the aim is to play THIS piece?
Comment: Laurence, I agree! I want to show that this piece is much easier to read  if you analyse the secondary dominants. (Of course many others would be suitable too, but I wtc 848 or the Prelude in D major are most useful in a special way!)
or putting the cart before the horse: I mean understanding this function V7/  is most useful to read this piece. Btw. this question should help OP of the other question (s. link above) to better understand the problem ...
Comment: I can't see that it's going to sound much different in C to C#. The big difference will be fingering. But merely using it as an exercise for theorising, your solution is what I would have done.
Comment: @ Tim: sometimes I think the it is easier to play in C# than in C  (may be just because the fingerings of the two different keys don't fit together)  while it is much more difficult to "read"  it in C# (regarding the double sharps). By reading I mean *analyzing the chords and understanding the functions*.
Answer: When I tried to play this prelude some decades ago there was no internet and no way to google and I also had access to music libraries. So I came to same conclusion as Laurence and Tim are advising: I've read  it in C, ignoring the 7 sharps.
But what could I read the other day?
Bach recycled some of the preludes and fugues from earlier sources: the 1720 Klavierbüchlein für Wilhelm Friedemann Bach, for instance, contains versions of eleven of the preludes of the first book of the Well-Tempered Clavier.
The C♯ major prelude and fugue in book one was originally in C major – Bach added a key signature of seven sharps and adjusted some accidentals to convert it to the required key.
That's what we are going to do now and writing the harmony (secondary fifths!)
I didn't add  the the Roman Numbers of the 4 bars in  line 1-4 (it is obvious that it is 1,2,3,4,3,2,1 in the degrees tonic, dominant, supertonic, relative key).
This transcription in C:

In bar 32 he starts with a chain of secondary dominants
B7 -> Em, A7 -> Dm, E7 -> Am, D7 -> G, A7 -> Dm, G7 -> C, D7 - Gm, D7 -> F
we can even extend this secondary chord progressions considering always 2 chords together as "secondary" of the next degree: (iv-V7/) or (ii-V7)
mind that the chords are in 1st (or 3rd) inversion: the 3rd in bass respectively the 7th).
The role and function of secondary dominants is explained here:
What is a secondary dominant chord?
Now it's quite easier to read and understand the progression in C# major:

And if we look at the transcription of Franz Kroll  in Db we will understand even better the functions of the secondary dominants. That's why I believe it is easier to read it in Db major: look at the 1st chord of the V7/X (secondary dominants)! We read C7 -> F ... etc. this is much easier to read and analyse than B double sharp -> E#

How to read Bach's Prelude C#?


How to convert DB2 set option to oracle?

Question: I try to covert DB2 SET option to Oracle, it's so hard. Couldn't found anyone had the same problem like I do. Really need some help.
<code>SET OPTION
ALWCPYDTA = *OPTIMIZE,
COMMIT = *NONE,
DECRESULT = (30, 30, 00),
DFTRDBCOL = *NONO,
DYNDFTCOL = *NO,
DYNUSRPRF = *USER,
SRTSEQ = *HEX
</code>
Answer: There is no option possible for what you are asking for. IBM DB2 is very different to Oracle, although both are RDBMS and support SQL and a lot of different features, the options of each one don't match.
If you want equivalences between your options in SET for DB2 against let say Oracle parameters, there are not. Most of the options are specific of the product itself and not transportable to the other database engine. For some, perhaps you can find a kind of equivalence, but you need to be careful about the meaning of the option itself in order to translate such meaning to another database engine.
Here a link to the IBM SHOW
https://www.ibm.com/docs/en/rdfi/9.6.0?topic=statements-set-option
Example
ALWCPYDTA
Specifies whether a copy of the data can be used in a SELECT statement. This option will be ignored in REXX.
There is no translation to Oracle for this option, as there is neither copy of data as part of any select statement in Oracle, neither REXX. Those are exclusive of IBM DB2.
Comment: Thank u for the answer. I had a feeling that I might get this kind of answers , but it's good to know that. I think I'm getting a headache now.


Definition of friend class and accessor sections

Question: When defining a class as a friend class, does it matter in which accessor section the definitions is placed, and if so does that change the members the friend has access to?
class aclass
{
private:
   // friend bclass;

public:
   // friend bclass;

protected:
   // friend bclass;
};

class bclass
{};

Answer: Access specifiers do not apply to friend function/Class
You can declare the Friend Function or Class under any Access Specifier and the Function/Class will still have access to all the member variables(Public,Protected & Private) of that Class.
Answer: Once you place friend class/function inside a given class (say 'aclass') anywhere. It will have access to all defined members of the class (irrespective of public/private/protected); for example:
class aClass
{
public: int pub;  void fun1() {}
protected: int pro; void fun2() {}
private: int pri;  aClass(const aClass& o);
  friend void outsider ();
};

Friend function outsider() can access pub, pro, pri, fun1, fun2; but not aClass copy constructor in this case (if it's not defined anywhere).
Answer: Friend functions aren't placed inside any accessors by convention, because by definition they aren't part of the class. You might do something like this:
class Elephants
{
 //friend void notAMemberFuncion(argument 123);

public:
// member functions;

protected:
// data members;
};

Comment: read the question, not talking about friend functions but rather friend classes.
Answer: The friend class/function can access all the private/protected/public members of class, which access section the friend class/function is placed doesn't make any difference.
It's suggested to put friend class/function in the public section, because friends is part of the class interface.


Finite, simple group with $p+1$ Sylow $p$-subgroups has order dividing $p(p^2-1)$

Question: I'm reviewing for my final, and the following is a (non-homework) question that I'm stuck on:

Let $G$ be a finite and simple group, and suppose $|\mathrm{Syl}_p(G)| = p+1$.
(a) Prove that $G$ can be embedded into $S_{p+1}$
(b) Prove that $p^2 \nmid |G|$
(c) Prove that $C_G(P) = P$
(d) Prove that $|G|$ divides $p(p^2 - 1)$

I used (a) to prove (b), and (b) implies that $P\in \mathrm{Syl}_p(G)$ has order $p$.  I used that to prove (c), but I'm not seeing how any of this implies (d).  Any hints to show (d)?
Answer: Hint: Consider that we are given that $|G: N_G(P)| = p+1$ and we have shown in part (c) that $|C_G(P)| = p$.  What can we say about $|N_G(P): C_G(P)|$?
Comment: @MöbiusDickus that's what you need to do
Comment: So $[N_G(P) : C_G(P)] = [N_G(P):P]$, and $[G:P] = [G:N_G(P)][N_G(P):C_G(P)]$, so $|G| = p(p+1)[N_G(P):C_G(P)]$.  I need to show then that $[N_G(P):C_G(P)]$ divides $p-1$.


General results on the change of the parity of a number by repeatedly dividing by 2

Question: I know this question may seem open, but I'm a bit interested in figuring out, getting some ideas, or at least getting some sources on how the parity of a number is affected by repeatedly diving it by 2. My question specifically is

How many times can an even number $n$ be divided by 2 before reaching an odd number?

I guess this is in a way related to the Collatz Conjecture and I'm not sure if this question is ground-breaking in anyway but I did some research and could not find anything significant. I guess it could also be rephrased to given the prime decomposition of a number, how many $2$s will there be?
Comment: Collatz conjecture... You write without knowing.
Answer: This nowhere groundbreaking: Any even number is of the form $2^md$ with $m \geq 1$ and $d$ odd. You can repeatedly divide it by $2$ precisley $m$ times.
Answer: All even numbers are clearly divisible by 2, i.e. divisible by 2 once.
50% of those will be divisible by 4, i.e. divisible by 2 twice.
50% of those, i.e. 25% of all even numbers, will be divisible by 8, i.e. divisible by 2 thrice.
50% of those, i.e. 12.5% of all even numbers will be divisible by 16, i.e. divisible by 2 four times.
etc...
Comment: How can you speak of percentage among the natural numbers? There is no Uniform distribution on a countable set.
Comment: [Natural density?](https://en.wikipedia.org/wiki/Natural_density)


I have data on income for two groups, but the income is in deciles - how can I compare them?

Question: The income data is in interval format.
The data does not have individual income measurements. But is in {1,2...10}, that is in deciles, where 1 is the lowest income range and 10 is the highest.
What are the common ways I can compare the income distributions of two groups using this decile interval income data?
Comment: You are given the points of a [QQ plot](https://en.wikipedia.org/wiki/Q%E2%80%93Q_plot), so why not at least graph it?
Comment: If you want to use some particular parametric model, you can calculate maximum likelihood estimators based on the deciles.
Answer: It depends on what you mean by "compare". Two possibilities come to mind.

Your data is fully described by two histograms, where the bins are defined by income deciles. There are ways to define distances between histograms. One I personally like is the earth mover's distance or Wasserstein metric. This would allow you to say, e.g., that distributions A and B were closer together than C and D. (Which would of course depend on the specific distance measure you choose.)
You could similarly compare both distributions to a reference distribution, like the uniform one. This naturally leads to the Gini coefficient.
These are purely descriptive measures.
If you want to do inferential statistics or similar on your data, then you can do different things. You first notice that your data is ordinal-data - we don't know the specific income of two individuals, but if they are in different deciles, then we know which individual has a higher income. So I'd recommend you read up on ways to analyze ordinal-data, e.g., by looking through our earlier questions carrying that tag. The Wikipedia page on ordinal regression may also be helpful and has a few references.


Why LBW is given not when ball is not pitched in Stump line while bowling around the wicket

Question: When bowler is bowling over the wicket and ball pitches out side off and is hitting the stumps, the LBW is given.
But when bowler is bowling around the wicket and ball pitches out side of leg but hitting the stumps then why LBW is not given.
Can any body tell me logic behind this rule.
Comment: In the second scenario, does the ball pitch outside off, or outside leg?
Comment: LBW is only not given if the ball pitches outside the line of the leg stump.
Answer: Because it is in the rules.... LAW 36 (LEG BEFORE WICKET)

The striker is out LBW in the circumstances set out below.
and (b) the ball, if it is not intercepted full pitch, pitches in line between wicket and wicket or on the off side of the striker's wicket,

It is irrelevant as to whether the bowler delivers over or around the wicket. It has to do with whether the batsmen has the ball delivered on their off side or on (leg) side. If it pitches outside of leg it does not matter if the ball will hit the wickets or not, it will be given not out.
However if the ball pitches on the off side and is in line with the wickets it should be given out
As to why there is the difference, it may be hard to determine, but if it was allowed to be given out with a pitch outside leg then I would say most deliveries would be going there since it is harder to hit (and defend) a ball coming from that direction.


Why is the last semiquaver outside the last triplet of the measure?

Question: The following measure is from "Clair De Lune ~ Adagio Sostenuto de la Sonata Op. 27 N. 2 De Beethoven", guitar sheet music .

Correct me if I'm wrong but the last semiquaver isn't going to be played, right?
Lets say each quaver is getting one foot tap. Foot tap for F and dotted A, a second on D and the final foot tap for F. Correct?
Why did the notation software add the last semiquaver after the "vertical axis" of F note? why it is not aligned under the F ?
[Update]
Time signature: 4/4
Comment: @Luke: I believe the minim/half note should have been dotted.
Comment: Hmm. It doesn't look like proper notation to me. There should be a crochet rest after the minim. My hunch is that it is just phrasing because the dotted quaver and the semiquaver are not in the triplet.
Comment: There is a Debussy piece called Clair de Lune. It would be clear if you call this Moonlight Sonata.
Comment: @Luke Time signature is 4/4
Answer: Even though this question has already long been answered, I thought I would show a picture of the note durations in case it helps someone. The time of a single quarter note can be filled many ways:

|___________| : One quarter note
|_____|_____| : Two eighth notes
|___|___|___| : Three triplets
|__|__|__|__| : Four sixteenth notes

So the rhythm Beethoven uses here is:

|___|___|___|
|________|__|

You can see how the notes are staggered.
Comment: I managed to fix it eventually... per [this meta note](http://meta.music.stackexchange.com/questions/554/can-we-have-a-formatting-sandbox), use `` (and *no* indent) to prevent jTab taking control; also the `<` brackets needed to go, not 100% sure what was unhappy with them!
Comment: Help! Preformatted block of ASCII art isn't coming through correctly.
Answer: Why is the last semiquaver outside the last triplet of the measure?
Because it should be!
You can think of the last quarter beat of the measure as being divided into three voices:
a) An eighth rest and two eighth notes (D51 and F5)
b) A dotted eighth note and a sixteenth note (A4 and A4)
c) A quarter note (F3)
The last eighth note of voice a) should be placed approximately one third from the end of an imagined full quarter note length, while the sixteenth note of voice b) should be placed one quarter from the end of this imagined length.
The last semiquaver isn't going to be played, right?
Wrong! Voice b) is the melody! The other notes are (mainly) accompaniment.2
Listen to this recording and you will understand how it should be played. The sheet music or notation used for that recording might not be identical to yours, but you should get the idea.
The music, "Piano Sonata No. 14" (in C sharp) by Ludwig van Beethoven, is a piano sonata that in your sheet music has been adapted for the guitar. It is nicknamed the Moonlight Sonata, (or in French Sonate au clair de lune).
1The notes sounding on the guitar is actually one octave down, but I chose here to write the octave numberings generally associated with the lines of the staff.
2This is a slight overstatement in order to emphasize the importance of voice b).
Comment: I'm not the one who down voted it. It is always annoying me that someone down vote without leaving a comment.
Comment: I need to think about this. Excellent answer (+1) I need to be able to play it. Lets say each quaver is getting one foot tap. How to play it? This will help me to visualize it
Comment: It would be interesting to learn what the down vote was for. Is anything incorrect or does the answer not answer the question? How can I improve it? :-)
Comment: @Chiron: I know you didn't. I'm happy for your upvote since it likely means that you were helped by my answer.
Comment: @Chiron If each triplet quaver (each triplet eighth note) is one foot tap, imagine sub-dividing each foot tap into four equal parts. The last semiquaver (the last sixteenth note) starts on the second sub-division of the last foot tap: `_---_---_=--`
Comment: @Chiron: Do as Bavi_H says, or you can practice clapping, tapping and playing [four against three](http://www.youtube.com/watch?v=wQWQUc8CCa0) which you need to know in order to play the last beat exactly as written. Or you could just wing it, but loose out on a good exercise. :-)
Answer: First of all, this has nothing to do with "solfege".
Secondly, Clair de Lune is composed by Debussy and isn't played (or named) "Adagio sostenuto". This is a bar from Beethoven's Sonata #14, usually just called Moonlight Sonata (this shows it in d minor instead of 'c# minor` which is the original key).
Regarding the music: the passage is mostly fine. It's not what was originally written, but the result would be close. What may be throwing you off is that if this passage were really written with the last quarter note (crotchet) on beat 4 the preceding half note (minim) would either have a quarter beat (crotchet) rest after it or it would have a dot added so it was 3 beats.
The top two voices are correct. The bottom voice should be a whole note (I guess what you would call a "semibreve").
Check the links and compare. Good luck!
Comment: Clair de Lune = Moonlight = Chiaro di Luna = Luz de la Luna = Mondschein.  Would it surprise you to find out that they call it "Mondschein" in Germany and "Clair de Lune" in France?
Comment: No. That's what I'm saying. It is NOT Claire de Lune. What you have is Moonlight Sonata. If my response answers your question please be sure to mark it as answered.
Comment: `http://imslp.org/wiki/Piano_Sonata_No.14,_Op.27_No.2_(Beethoven,_Ludwig_van)`
Comment: What is this link for?
Comment: @tptcat The original paper that I have is named as I mentioned, interpreted by Josefina Robledo. Good to know it is a Debussy music. Thanks!
Comment: @tptcat I only to make sure that the last semiquaver isn't going to be played. right?
Comment: @Chiron I don't understand. Of course it's played. That's where it falls in the beat. Right after the last triplet; the last sixteenth note of that bar.


Menu links not working in IE

Question: When I click on certain links in menu in IE a page with error message "Internet Explorer cannot display this page" appears. Other browsers are OK.
Problem is with these two links
"http://localhost/?q=calendar"
"http://localhost/?q=user/login"
Do you know what is wrong?
thank you
Answer: To give any meaningful answer you need to describe your problem better. I did notice that your urls seem to lack your site name
http://localhost/?q=calendar vs http://localhost/drupal?q=calendar
This can happen if you don't create the urls with the l/url function regardless of browser being used.
Comment: Thank you, that's it. I tested IE in virtual machine so I couldn't use localhost and those links were "hardwired" in the menu. Is there some variable I can use that will create the right link?

Menu links not working in IE


A strange warning from proc phreg (Survival Analysis) in SAS

Question: I am been trying to fit a Cox regression on a small dataset but I have come across a strange problem. Although the model runs well, I am unable to get an ouput from it. Instead in the log one reads
WARNING: The OUTPUT data set has no observations due to the presence of time-dependent explanatory
         variables.

It's true that I have a time dependent variable on the RHS but this shouldn't be a problem, I think. Many analyses use this kind of variables. Could you please help me understand why that happens and how I can get past it? There is plenty of information to be got from this statement and it would be really helpful to me. Here is my dataset and the code I have been using so far.
data surv;
input time event fin;
cards;
2 0 1
3 1 1
4 1 1
1 1 0
5 1 0
6 0 1
7 0 0
8 1 1
9 0 0
10 1 0
;
proc phreg data=surv;
model time*event(0)=fin ft;
ft=fin*log(time);
output out=b;
run;

Wasn't sure whether I should post it here or in stats stack.exchange but in any case, I would really appreciate some help. Thank you.
Answer: SAS is just telling you that you have a time dependent variable (it doesn't impede the code from running). You are violating the proportional hazards assumption for the Cox PH test, but the test is robust enough to handle it.  There is really no "correct" answer here.  You can perform some transformations and run the model after each transformation.  Whichever model returns the lowest AIC would be your best model.  Check out this presentation. Also, this lecture has some good information as well. IF however the PH assumption is not important, you should switch to a parametric model.  I hope this is what (or somewhat) close to what you were looking for.
Comment: Thank you for your input. This is just a toy dataset, my real one is huuuuge. My problem is that I have to perform diagnostics with these time dependent variables in the model.


Pacemaker: dynamic location constraints

Question: I have a corosync cluster involving several machines that have different roles within the cluster.
I have some clone resources grouped together and I set up everything to behave as an opt-in cluster:
<code>node dir01
node dir02
node ms01
node ms02
node ms03
primitive pri_clvmd lsb:clvm \
    op monitor interval="120" timeout="20" \
    op start interval="0" timeout="30" \
    op stop interval="0" timeout="30"
primitive pri_dlm ocf:pacemaker:controld \
    op monitor interval="120" timeout="30" \
    op start interval="0" timeout="90" \
    op stop interval="0" timeout="100"
group grp_cluster_storage pri_dlm pri_clvmd
clone cln_cluster_storage grp_cluster_storage \
    meta ordered="true" interleave="true" target-role="Started"
location LOC_CLUSTER-STORAGE1 cln_cluster_storage inf: ms01
location LOC_CLUSTER-STORAGE2 cln_cluster_storage inf: ms02
location LOC_CLUSTER-STORAGE3 cln_cluster_storage inf: ms03
property $id="cib-bootstrap-options" \
    dc-version="1.1.7-ee0730e13d124c3d58f00016c3376a1de5323cff" \
    cluster-infrastructure="openais" \
    expected-quorum-votes="3" \
    stonith-enabled="false" \
    last-lrm-refresh="1390076650" \
    no-quorum-policy="ignore" \
    symmetric-cluster="false"
</code>
So far, so good, everything seems to work just fine at that stage however one of the thing I want to acheive is to be able to add hosts in the cluster without having to modify the cib configuration.
With the above config, whenver I need a new host (let's say ms04), I would have to add a new location constraint.
Is there any way around that?
Comment: Why do you create location constraints? Why not let the cluster determine by itself where to host which resources?
Comment: because it is an asymetric cluster and machines have different hardware specs based on what they are supposed to do. For instance all of them doesn't have an HBA to access the SAN, or they have different CPU and RAM sizing.
Answer: kind of an answer to my own question:
what I am trying to do is probably not painless at the moment. however, forthcoming pacemaker should show that by implementing support for region x in location constraints:
Quoted from http://blog.clusterlabs.org/blog/2013/announcing-1-dot-1-11-beta-testing/
"PE: Allow location constraints to take a regex pattern to match against resource IDs"

Pacemaker: dynamic location constraints


how to make a dynamic grid view using marionette.js

Question: I am new to marionette and I wanted to create a dynamic grid-like structure with two columns and multiple rows. I am really stuck on how to create exactly two columns, and have a grid-like structure.
Thanks in advance
Comment: Could you share your tries?
Answer: The better way - use CompositeView
<code>// A Grid Row
var GridRow = Backbone.Marionette.ItemView.extend({
    template: "#row-template",
    tagName: "tr"
});

// The grid view
var GridView = Backbone.Marionette.CompositeView.extend({
    tagName: "table",
    template: "#grid-template",
    itemView: GridRow,
});
</code>
Look this example http://jsfiddle.net/derickbailey/me4NK/
Comment: Thanks @Vasil Vanchuk i tried this method and it worked .. :)


What is the one point compactification of the reals?

Question: In several of my questions this theorem has come up. What is the one-point compactification of the reals? Does it have to do with limits and dividing by $0$? I vaguely remember something about a circular number line. Does it apply to complex numbers too? And do numbers such as aleph-null or ordinal infinities mess up this theorem?
Comment: You are overthinking the problem.  Add one point, whose neighborhoods are that point together with complements of compact sets in the real line.  You will indeed get "a circular number line".
Comment: This might be one of the most confused questions I've seen in a while.
Comment: It might be easier to think about if you replace the reals with the open interval $(0,1)$, which is homeomorphic to the reals, and so has a homeomorphic one-point compactification.
Comment: Keyword: "real projective line"
Answer: Problem: Can we write one to one, onto and continious from the circle $S_1$ to $\mathbb R$ ?
The answer is no and it can be shown that if we extract one point from $S_1$, it is possible.
Now the idea is that instead of extractinting one point from $S_1$, let's add one point to $\mathbb R$ so that we can write the map from $S_1$ to $\mathbb R \cup {a} $. As $S_1$ is compact then $\mathbb R\cup {a}$ is compact.
One point compactification is the generelezation of this idea. In general, if you add one point to $\mathbb R^n$ in a appropriate way you will get $S_n$.
Comment: @tox123: yes exactly, but think $\infty$ as a symbol.
Comment: So is it that the reals don't fit a circular number line, but if you add infinity they will?
Comment: does $\infty$ encompasses all infinities?
Comment: $\infty$ is just the symbol used to mean 'a new point'. You could call it $\bullet$ if that makes it less ambiguous for you.
Comment: @tox123: Cardinal and ordinal numbers have nothing to do with this topic. Regarding the extended real numbers $\pm \infty$, you could envision taking the two endpoints of the line and looping them around so that they are the same point: in that sense, $\infty$ encompasses both $\pm \infty$.
Answer: The one point compactification of the reals is the circumference. Indeed, stereographic projection from the north pole gives a homeo from the circumference without that pole onto the real line, and the inverse is the embedding of the reals into a compact space consisting of just one single additional point. In full generality, for non-compact locally compact Haussdorf space $X$, the one point (or Alexandroff) compactification is just a compact Haussdorf space $X^*$ obtained adding a point to the given one, and all such $X^*$'s are homeomorphic. For complex numbers, which topologically are the real plane, the one point compactification is the sphere, and stereographic projection works the same.


Qual o problema dessa paginação não responsiva usando boostrap 4 no Laravel?

Question: Estou utilizando Laravel para fazer um sistema, junto com o framework Bootstrap. E estou utilizando o recurso de paginação. Porém estou com problemas para deixar responsivo os numeros da paginação. Ambos estão desconfigurados referente a tabela, e estão ultrapassando os cantos. Abaixo está o exemplo.

Estou tentando centralizar ou deixar alguns números de paginação justapostos. Porém toda a vez que redimensiono para o modo Celular (mobile), ocorre a sua desconfiguração. Abaixo está o codigo do que estou utilizando no Laravel.

                    {{ $prospect->appends($data)->links() }}

Também adicionei o código aqui, junto a tabela que estou utilizando. Logo olhando o meu código do bootply, percebe-se que não há problema nenhum, mas utilizando a paginação do Laravel, acontece diferente no front-end.
Estou com dúvidas se a paginação do Laravel pode mesmo interferir no front-end ou é apenas um erro básico de mal uso do boostrap 4.
Como posso estar consertando esse problema?
Answer: Vc colocou as classes de flex no lugar errado! Elas tem que estar na ul e não na div

                {{ $prospect->appends($data)->links() }}

Segue um exemplo, repare que as classes de flex estão na ul, não na div:

<link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />

1

1

1

1

1

1

1

1

1

1

1

1

1

1

Comment: Não sei o que pode diferenciar, mas seria preciso postar o resto do código com a tabela junto? Aqui comigo não funcionou dessa maneira. Tipo, ele não fica justo ao centro, somente se colocar o justify-content-center no nav. E ainda passa do tamanho da tabela.
Comment: @ArthurAbitante como o código que vc postou na pergunta o máximo que da para te ajudar é isso... Se vc puder atualizar a pergunta e colocar a tabela como ela é renderizada no browser, tipo abre no navegador, da um Ctrl+U e pega a tabela já renderiza. Ai testa para ver como ela fica de forma insolada em uma página em branco. Isso vai te ajudar a ver se o erro é nela ou se é outra coisa que está na pagina que está atrapalhando. Mas só com o seu código da pergunta não da para ajudar mais que isso :/
Comment: Acabei de editar a questao, o código se encontra aqui, https://www.bootply.com/Ne9SYj0yN7. parece que terei que extender a pergunta para o Laravel. Pois alguma coisa na paginação do Laravel está interferindo também.
Comment: @ArthurAbitante então deve ser isso pq mesmo na ambiente que vc montou funciona certinho http://prntscr.com/peigfv Confere se o Laravel está colocando estilos inline na sua tag HTML, da uma inspecionada nos elemento depois de renderizado para ver se identifica algo


mcNemar's Test how to compare two proportions in dependent sample

Question: I would like to compare the false positive rates (1 - specificity) from two different tests within the same sample. The false positive rate is calculated by comparing the test values against the actual prevalence of disease.
Test 1 has a false positive = 17.1%
Test 2 has a false positive = 15.5%
I believe I am supposed to use the McNemar's test but I can't figure out how to set up the two by two table.
Thank you!
Comment: Did I answer your question?
Answer: The false-positive rate is
$$\small \text{FPR}=\frac{\text{FP}}{\text{FP + TN}}$$
This would be some simulated data set of $187$ participants with the same percentages as in the OP:
<code>> mat = as.table(rbind(c(23, 9), c(6, 149) ))
> colnames(mat) <- rownames(mat) <- c("False Positive", "True Negative")
> names(dimnames(mat)) = c("Test A", "Test B")
> mat
                Test B
Test A           False Positive True Negative
  False Positive             23             9
  True Negative               6           149
> addmargins(mat)
                Test B
Test A           False Positive True Negative Sum
  False Positive             23             9  32
  True Negative               6           149 155
  Sum                        29           158 187
> pr.mat = prop.table(mat)
> round(addmargins(pr.mat),3)
                Test B
Test A           False Positive True Negative   Sum
  False Positive          0.123         0.048 0.171
  True Negative           0.032         0.797 0.829
  Sum                     0.155         0.845 1.000
> mcnemar.test(mat)

    McNemar's Chi-squared test with continuity correction

data:  mat
McNemar's chi-squared = 0.26667, df = 1, p-value = 0.6056
</code>
So you are really testing for the off-diagonal differences: the proportions of healthy individuals in which there was discrepancy with one of the tests being false positive, while the other was true negative. The idea is for the $2\times2$ contingency table to be populated with count data.
Comment: I think you did answer the question +1, also similar Q/A elsewhere https://stats.stackexchange.com/a/274882/99274


Why it does not create the table and add data?

Question: DatabaseHelper.java:
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String TAG = "DatabaseHelper";
    public static final String DATABASE_NAME = "daysDATABASE.db";
    public static final String TABLE_NAME = "daysDATABASE";
    private static final String COL1 = "datez";
    private static final String COL2 = "json";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, datez TEXT, json TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    public boolean addData(String date, String json) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("datez", date);
        contentValues.put("json", json);
        db.insert(TABLE_NAME, null, contentValues);
        return true;
    }

MainActivity.java:
public class MainActivity extends AppCompatActivity {
DatabaseHelper mydb;

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

        mydb = new DatabaseHelper(this);
        mydb.addData("02164987", "adsdsadsadsadsadsadsa");
    }

If I open the database, there is no table in it, nor data ofc.. since the table is not created.
..........................................................................................................................................................
I would tell more informations but I do not think you need more than this 2 java class. I copy pasted and changed some stuff from tutorialspoint tutorial but seems like it does not work for some reason.
Comment: The application throws some exception?
Comment: Do not think any of these related to this problem: https://www.pastiebin.com/5bd85bbcbf43a
Answer: Even if your table was created, you could not add data in it with the addData() method because you don't supply a value for the id column.
The CREATE statement creates the column id as PRIMARY KEY but not AUTOINCREMENT so you must supply its value. But I don't think that this is what you want.
So change the CREATE statement to this:
db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, datez TEXT, json TEXT)");

then uninstall the app from the emulator/device so the db is deleted and run again.
This way the onCreate() method will be executed and the table will be created.
Edit1: remember to close the database object after you're done with it:
mydb.close()

Edit2: the insert() method, if successful, returns the id of the new added row or -1 if there was a problem, so I suggest you make this change in addData() method:
int id = db.insert(TABLE_NAME, null, contentValues);
return (id >= 0);

Answer: Adding to forpas answer which solves the root cause of the problem, i will suggest you use
db.insertOrThrow(TABLE_NAME, null, contentValues);
instead of db.insert(TABLE_NAME, null, contentValues); so you can get a clue of what the problem might be.


settings.php not in expected location(s)

Question: We are trying to change the database settings for a long-standing drupal 6 site, but are having trouble finding the correct settings.php file:
$ cd /var/www/vhosts/mysite
$ find sites/ -name "settings.php*"
sites/default/settings.php.save
sites/default/settings.php.mod2
sites/mobile.mysite.com/settings.php
sites/mysite.com/settings.php
sites/mysite.com/settings.php.pre_handoff_unedited
sites/mysite.com/settings.php~
sites/mysite.com/settings.php.20131022

We renamed the two most likely suspects, but the sites continues to run smoothly:
sites/mobile.mysite.com/settings.php_hold
sites/mysite.com/settings.php_hold

I also looked for a sites.php that might be overriding settings.php, but we don't seem to have one of those either:
$ find sites/ -name "*sites.php*"
$

Which means I can't find a sites.php or settings.php anywhere in the web directory that seems to control drupal.
We have nginx set up to receive http requests and mysite.com requests are forwarded to apache.  Could that be relevant?  Where else I might look for the drupal config settings?
Comment: Based on what you posted, `settings.php` should be in `/sites/mysite.com/settings.php`. Did you try clearing caches after editing that file?
Answer: You should search for setting file as:
find sites/ -name settings.php

as the file won't have any other name than settings.php (unless included from settings.php).
So you're down with these 2 valid entries:
sites/mobile.mysite.com/settings.php
sites/mysite.com/settings.php

Normally when you have settings.php in sites/default it applies to all sites, unless overridden by the site specific file (which is the case).
So:

sites/mobile.mysite.com will work on sites like mobile.mysite.com
sites/mysite.com/settings.php works on sites like mysite.com

Here is example from default.settings.php documentation page:
For example, for a fictitious site installed at http://www.drupal.org/mysite/test/, the settings.php file is searched in the following directories:

sites/www.drupal.org.mysite.test
sites/drupal.org.mysite.test
sites/org.mysite.test
sites/www.drupal.org.mysite
sites/drupal.org.mysite
sites/org.mysite
sites/www.drupal.org
sites/drupal.org
sites/org
sites/default

The configuration directory will be discovered by stripping the website's hostname from left to right and pathname from right to left. The first configuration file found will be used and any others will be ignored. If no other configuration file is found then the default configuration file at sites/default will be used.

If you're still confused, please run drush status command to find the right settings file, e.g.
$ drush status | grep settings
 Drupal Settings File            :  sites/default/settings.php

or for specific site:
$ drush -l http://mobile.mysite.com status | grep settings

Answer: Domain Wise settings.php file
1) sites/mobile.mysite.com/settings.php --> This is the original file for
2) mobile.mysite.com domain
3) sites/mysite.com/settings.php        --> This is the original file for mysite.com Domain
4) sites/mysite.com/settings.php~       --> This file is last edited and it has the recent changes. But due to unexpected closing of editing application(like vi or emac editor) the file changes are saved in this file
Also you can use  below commands to check the last file modification time for all above three files.
e.g.
file sites/mobile.mysite.com/settings.php
stat sites/mobile.mysite.com/settings.php


How run mahout in action example ReutersToSparseVectors?

Question: I want run "ReutersToSparseVectors.java". I can compile and created JAR file without problem.
I compiled this file by below command:
javac -classpath hadoop-core-0.20.205.0.jar:lucene-core-3.6.0.jar:mahout-core-0.7.jar:mahout-math-0.7.jar ReutersToSparseVectors.java
created JAR file with below command:
jar cvf ReutersToSparseVectors.jar ReutersToSparseVectors.class
When I write java -jar ReutersToSparseVectors.jar to run, give me below error:

Failed to load Main-Class manifest attribute from
ReutersToSparseVectors.jar

Do you can help me to solve this problem?
IF this example can run with hadoop, please me that how i can run this with hadoop.
Answer: instead of using -jar option, then it's better to to run:
 java -cp mahout-core.jar:... mia.clustering.ch09.ReutersToSparseVectors

or you can use mvn exec:java command, as described in README for examples...
 mvn exec:java -Dexec.mainClass="mia.clustering.ch09.ReutersToSparseVectors"

Or you can run this file directly from your IDE (assuming, that you correctly imported Maven project).
P.S. your command isn't working, because to run with -jar switch, the .jar file should have special entry in manifest that describes that class should be started by default...
P.P.S. It's better to use book's examples with Mahout 0.7, as they were tested for it.  You can use it with version 0.7 if you need, by then you need to take source code from mahout-0.7 branch of repository with examples (link is above)
Comment: I can't get answer via your method. Please more explain. IF you can run JAVA file in CH09 in "Mahout in action", please tell me method that you use for run this files. Thnx
Comment: run eclipse, import project into it, and then use 'Run As...' command when right-click on the corresponding source file
Comment: I do this work, but not answer. This error is "Could not find or load main class ReutersToSparseVectors". Of course, i config "Run Configuration" and set main class to  "ReutersToSparseVectors" but give me this error.
Comment: `mvn exec:java` works for me without any problem - I updated my answer with precise command line
Comment: I do this with `mvn exec:java` but give me error: `BUILD FAILURE`
Comment: you never mentioned that you have build error... Did you took source code from `mahout-0.7` branch of examples? Because examples from books will not build with Mahout 0.7!
Comment: Note is here. I use code from "Mahout in action" book. Now, how i can run this code. If you can please help me. Thanks
Comment: If you want to check examples from Mahout in Action, then you need to use Mahout version 0.5! This book was written and tested for this version. Source code for examples is at https://github.com/tdunning/MiA, please, clone this version and run as per instructions in README file and my answer here. But you should use 0.5!
Comment: I need run program in ch09 in "Mahout in action" book. But [here](https://github.com/tdunning/MiA) not explain about this. If you Know this please tell me.Thanks for your answers.
Comment: I wrote in my answer how to run it with maven using `mvn exec:java` command... It works on my machine, but on your, you need to prepare data as specified in the books and only then run this example
Comment: Excuse me. Do you can run ReutersToSparseVectors in "ch09"? How set the input and output address and what type file build into addresses? I do any work for this but don't work.
Comment: You need to prepare data as described in book. name of input directory is stored in variable `inputDir`, name of output directory in `outputDir` variable.
Comment: Is `inputDir` a document file or sequence file? I understand this!
Comment: inputDir is directory with files, produced in previous steps
Comment: Hi. I wrote detailed post on how to use examples from book: http://alexott.blogspot.de/2012/07/getting-started-with-examples-from.html
Comment: You solved it using my instructions, or figured solution yourself?
Comment: If `ReutersToSparsVectors` only work on `Reuters files` or work on any of documents with different subject?


'undefined reference to `shogun::SGRefObject::unref()' when compiling with .so object

Question: I'm getting this error when I try to compile the gaussian kernel test given on the shogun developer page at
https://github.com/shogun-toolbox/shogun/wiki/README_developer.
I followed the instructions given in order to produce the .so shogun library at https://github.com/shogun-toolbox/shogun/wiki/INSTALL.
I then went to the directory above that containing the shared object library and issued the order "g++ GTest.cpp shogun/libshogun.so -o a.out" and was given the error that is the topic of this post.
I ran through a thread linked on the net (2 link restriction), but I couldn't find a given  solution.
Anybody have any idea how to solve this?
Answer: you shouldn't try to link directly the shared library with your example.
Say you created a shogun based example file, let's call it shogun_example.cpp, in order to compile this you should run:
g++ shogun_example.cpp -o shogun_example -lshogun

this is in case the libshogun.so is in the search path of the linker.
If the compiled libshogun.so is not in the search path then you should provide the location of the shared library to the compiler with -L, for example:
g++ shogun_example.cpp -o shogun_example -L<path to the shogun shard lib> -lshogun

Comment: Unfortunately, this didnt work. I am using the instruction "g++ -std=c++11 -DHAVE_EIGEN3 classifier_gaussian_process_binary_classification.cpp -o classgp -lshogun" in an attempt to compile the example within the examples folder and am getting a laundry left of undefined references. I set each of the g++ include search variables to the /usr/local/include folder within which shogun stored its include folder after installation. I also set up the LD_LIBRARY_PATH variable so that shogun would be able to find the shared library. I can compile other examples and I have installed eigen 3 with apt-get
Comment: Solved the problem. Turns out OpenCL is a dependancy and it's something I overlooked because I didn't read the text as I was installing the shared library's with cmake. Lesson here is to read cmake instructions while installing, regardless of how simple instructions on a site make installation out to be lol. Thanks for putting up with me.


Can't take input in a string

Question: In this program, I'm not able to get input in string c[] (in add_diary() ) by using fgets() or gets(), the program just skips the input process, please tell me what am I doing wrong. I just can't get it started. In a diary the most important thing is to write and the thing is 'you can't write, cuz fgets() isn't working'.
<code>    #include <stdio.h>
#include <stdlib.h>

void access();
void diary_main(char user[],char pass[]);
void diary_login();
void add_diary(unsigned dd, unsigned mm, unsigned yy);
void add_entry(unsigned choice);
void del_entry(unsigned dd, unsigned mm, unsigned yy);
void update_entry(unsigned dd, unsigned mm, unsigned yy);
void logout();

void main() {
    access();
}

void access() {
    char password[10],username[20], ch;
    int i;
    printf("Enter User name: ");
    gets(username);
    printf("Enter the password (8 characters):");
    for(i=0;i<8;i++) {
            ch = getch();
            password[i] = ch;
            ch = '*' ;
            printf("%c", ch);
     }
     password[i] = '\0';
     /*printf("\nYour password is :");
     for(i=0;i<8;i++) {
    printf("%c", password[i]);*/
    diary_main(username, password);
}

void diary_main(char user[],char pass[]) {
    /*FILE *fptr;
    //char file_name[10];
    //sprintf(file_name, "user%s.txt", user);
    fptr = fopen("login.txt", "w");
    fprintf(fptr,"\n%s",user);
    fclose(fptr);*/
    diary_login();
}

void diary_login() {
    unsigned choice;
    printf("\nEnter your choice\n");
    printf("1. Add Diary Entry\n");
    printf("2. Delete Diary Entry\n");
    printf("3. Update Diary Entry\n");
    printf("4. Logout\n");
    printf("5. Exit\n");
    scanf("%d", &choice);
    if (choice == 1) {
        add_entry(choice);
    }
    else if (choice == 2) {
        add_entry(choice);
    }
    else if (choice == 3) {
        add_entry(choice);
    }
    else if (choice == 4) {
        logout();
    }
    else if (choice == 5) {
        exit(1);
    }
    else {
        //printf("%d", choice);
        printf("Enter correct choice");
        diary_login();
    }
}

void add_entry(unsigned choice) {
    unsigned dd, mm, yy;
    printf("Enter date (DD/MM/YY):");
    scanf("%u/%u/%u", &dd, &mm, &yy);
    //printf("%u/%u/%u", dd, mm, yy);
    if ((dd>31 || mm>12) || (dd>29 && mm == 2) || (yy!=17)) {
        printf("\nEnter correct date\n");
        add_entry(choice);
    }
    else {
        //printf("else");
        switch(choice) {
            case 1: add_diary(dd, mm, yy);
                    break;
            case 2: del_entry(dd, mm, yy);
                    break;
            case 3: update_entry(dd, mm, yy);
                    break;
        }
    }
}

void add_diary(unsigned dd, unsigned mm, unsigned yy) {
    //printf("add_diary");
    long file_extra;
    char file_name[50], c[5000];
    FILE *fptr;
    file_extra = (((dd*100)+mm)*100)+yy;
    sprintf(file_name, "diary%ld.txt", file_extra);
    fptr = fopen(file_name, "w");
    /*if(fptr == NULL){
       printf("Error");
       exit(1);
    }*/
    printf("\nStart writing diary..\n");
    scanf("%s", c);
    //fgets(c, sizeof(c), stdin);
    //gets(c);
    fprintf(fptr,"%s",c);
    fclose(fptr);
}

void del_entry(unsigned dd, unsigned mm, unsigned yy) {
     long file_extra;
     char file_name[50];
     file_extra = (((dd*100)+mm)*100)+yy;
     sprintf(file_name, "diary%ld.txt", file_extra);
     int status;
     status = remove(file_name);
     if( status == 0 ) {
        printf("Entry deleted successfully.\n");
     }
     else {
        printf("Unable to delete the file\n");
    }
}
void update_entry(unsigned dd, unsigned mm, unsigned yy) {
    long file_extra;
    char file_name[50], c[5000];
    file_extra = (((dd*100)+mm)*100)+yy;
    sprintf(file_name, "diary%ld.txt", file_extra);
    FILE *fptr;
    fptr = fopen(file_name, "w");
    printf("\nStart editing diary..\n");
    scanf("%s", c);
    //fgets(c, sizeof(c), stdin);
    //gets(c);
    fprintf(fptr,"%s",c);
    fclose(fptr);
}
void logout(){

}
</code>
Comment: what do you mean by new line and where's that new line coming from?
Comment: and only scanf() is working in add_diary()
Answer: From my understanding this is how scanf works:
Let's say you have them input "Hello World", what is actually brought in is "Hello World\n". You can work around this by selecting n-1 in the array ('\n') and replace it with a terminating ('\o').

Can't take input in a string