Cocoa Scripting: Returning the cloned objects from a "duplicate" command

Question: The AppleScript duplicate command is supposed to return the copied objects.
And while apps using the original AE-based functions seem to do that, apps based on the Cocoa Scripting framework seem to never return anything but missing value.
It appears that the command handler of NSCloneCommand is responsible for not returning the specifiers for the cloned objects.
I was attempting to fix this in my scriptable app by subclassing the command,  collecting the cloned object specifiers and then returning them.
This works well if only one item is duplicated.
It also works if multiple items are cloned along with using the to parameter with the command (as in duplicate every widget to end): Then I can return a specifier of type NSRangeSpecifier that designates the first and last of those cloned items.
However, if one uses the duplicate command on multiple items without the to parameter, then the items get sorted into the array in a non-consecutive manner. For instance, if there are initially 2 "x" elements, with id 1 and 2, duplicate every x will insert a copy of each element right after its original, so that we'll have them in this order: 1, 3, 2, 4.
Now, how would one return a specifier for this, i.e. a specifier for items 3 and 4?
There is no "list" specifier in the sub classes of NSScriptObjectSpecifier, and I cannot return an NSArray for each individual NSScriptObjectSpecifier either, it seems. And while NSAppleEventDescriptor supports creation of lists, I cannot figure out how I'd convert the object specifiers into NSAppleEventDescriptors.
How can I solve this other than enforcing a consecutive order of the cloned objects (which would require me to re-implement the NSCloneCommand's operation entirely, I'm afraid).
BTW, Mark Aldritt, author of Script Debugger, confirms the issue that duplicate (also: move, open) do not return values as they're supposed to.
Comment: In the subclass you could get a list of the current items, then call `super.performDefaultImplementation()` to perform the duplication, get the list again and filter the items from the first list.
Comment: That was not the question, though. I wrote what works, and that includes what you suggest (though I did it in a different manner, so your answer is still useful). The real question is: What do you do when they're not in consecutive order, because then you need to create a list of specifiers, and I don't know how to do that. Although, if you think that's smarter, I could split this into its own question and take this one as answered, pending solution of the other one. I just didn't want to ask the other one alone because then I'd probably get questions like "why do you need this"? :)
Answer: Mark Aldritt helped me a little further, telling me about some private API methods:
@interface NSScriptObjectSpecifier (NSPrivate)
+ (id) _scriptingSpecifierWithDescriptor:(NSAppleEventDescriptor*) descriptor;
+ (id) _objectSpecifierFromDescriptor:(NSAppleEventDescriptor*) descriptor inCommandConstructionContext:(id) context;
- (NSAppleEventDescriptor*) _asDescriptor;
@end

The _asDescriptor was what I was looking for - a way to turn an object specifier into a NSAppleEventDescriptor so that I can add that to a list object. The code for that would look like this:
- (NSAppleEventDescriptor*) objectSpecifiersAsList:(NSArray*) objectSpecifiers {
    NSAppleEventDescriptor* result = [NSAppleEventDescriptor listDescriptor];
    for (NSScriptObjectSpecifier* specifier in objectSpecifiersArray) {
        [result insertDescriptor:specifier._asDescriptor atIndex:0];
    }
    return  result;
}

When I tried this to return the non-consecutive items, I found, however, that this doesn't work. In fact, it has the same effect as returning an NSArray of the same NSScriptObjectSpecifiers. Here's an example:
set x to duplicate widgets 1 thru 2

With the custom duplicate command handler returning a list of specifiers for the copied items 3 and 4, AppleScript ends up calling the same command handler a second time and after that it gives the error -10006 with the message:
Can't set widgets 1 thru 2 to widgets 1 thru 2

Mind you - it does not say "widgets 3 thru 4" or "{widget 3, widget 4}". No, it always reports the items that were given at the first parameter to the duplicate command.
As soon as I change my code to returning a single specifiers or a range specifier, the command behaves normally again.
So it seems like this is a hidden bug in Cocoa Scripting (or AppleScript?) wherein it cannot handle returned object specifiers in a list.
Update & Solution
After more trial-and-error I figured out a way that works:
The type for the result has to be changed from "descriptor", and there are two possibilities:

To use the code above that returns a listDescriptor, the result type needs to be "any", i.e.:
<result>
    <type type="any"/>
</result>

Alternatively, if the result type is changed to "list of any", then one can return an NSArray containing the NSAppleEventDescriptor values:
<result>
    <type type="any" list="yes"/>
</result>

Both solutions require the use of the private _asDescriptor method, however, as there is no other known way to turn a scriptable object into a NSAppleEventDescriptor.
(Of course, if your app supports the duplicate command for only one type of element, then you can change the type to "list of yourtype" and return simply an NSArray of your objects, without the need for the private method - that's only needed for returning results of type any.)
Mark says this about using the private method:

If you are concerned about Mac App store issues, these private methods were give to me by Apple as there is no alternative API.  I'm pretty sure you can get permission to use them.

I hope to submit my own app implementing this solution to the App Store soon. I shall then update this answer with the outcome of using the private function.
Answer: Thomas, I'm not sure if it was a typo, but I'm not seeing an "at" parameter for the duplicate command in the Standard Suite:
<command name="duplicate" code="coreclon" description="Copy an object.">
    <cocoa class="NSCloneCommand"/>
    <direct-parameter type="specifier" .../>
    <parameter name="to" ...</parameter>
    <parameter name="with properties" ...</parameter>
</command>

There is also no <result ...> element, so the command should not return any value or values, by definition. Am I missing something?
Comment: Right - that's a conundrum with the various default Sdefs I found, including the ones offered by the Sdef Editor. If you have a look around at other apps,  some will include the result, while others do not. I assume that those that include it are usually older ones, while those that do not include the result type are those where developers have learned that the `NSCloneCommand` does not work right and thus have removed it to avoid confusion.
Comment: Also, I have to correct myself on the `at` parameter - I meant the `to` parameter. I'll correct the question accordingly (at only is used with make, which I looked at a lot as well, hence I got confused).
Comment: The SDEF I use is installed by Apple on the Mac at /System/Library/ScriptingDefinitions/CocoaStandard.sdef, so I take it to be the sanctioned suite definition.
Comment: I guess Apple went the easy way out after realizing that their NSCloneCommand is not working right and simply removed the result from the command in the sdef. That's pretty bad, IMO. And plenty of apps still contain it. And it's needed by scripters, same as with open and make. See the last line I added to my question.


PHP nome de variável dinâmico, de acordo com valor de outra variável

Question: Imaginem que eu tenha o código  abaixo:
<?php

$linha1 = 0;
$linha2 = 0;
$linha3 = 0;
$linha4 = 0;
$linha5 = 0;

// Array com 5 numeros
$cincoNumeros = [1, 2, 3, 4, 5];

for($i=0;$i<50;$i++) {

    // Misturo aleatoriamente o array acima
    shuffle($cincoNumeros);
    // Seleciono um array unitário (um número) no array que foi misturado.
    $umNumero = array_slice($cincoNumeros, 0, 1);
    // Pego o valor do index do array $umNumero
    $valor = $umNumero[0];

    // Agora, de acordo com esse número sorteado, incremendo a variavel correspondente:

    switch ($valor) {
        case 1:
        $linha1 += 1;
        break;
        case 2:
        $linha2 += 1;
        break;
        case 3:
        $linha3 += 1;
        break;
        case 4:
        $linha4 += 1;
        break;
        case 5:
        $linha5 += 1;
        break;
    }

}

?>

Deste jeito funciona, mas imaginem o tamanho que ficaria se estivessemos falando de 100, 500, 1000 variáveis linhasX.
Há alguma forma de mudar o nome da váriavel dinamicamente,  usando apenas um FOR sem SWITCH, como sugiro abaixo?
<?php

// crio um laço com 50 loops, por exemplo
for($i=1;$i<=50;$i++) {

    // Misturo aleatoriamente o array $umNumero
    shuffle($cincoNumeros);
    // Seleciono um array unitário (um número) no array que foi misturado.
    $umNumero = array_slice($cincoNumeros, 0, 1);
    // Pego o valor do index do array $umNumero
    $valor = $umNumero[0];
    $linha.$valor += 1; // Incremento de uma variavel linhaX qualquer, de acordo com valor sorteado. Digamos que o valor sorteado seja 3 então, a variável a ser incrementada seria $linha3.
}

?>

Sei que o nome da variavel $linha.$valor está errado. Estaria apenas concatenando, mas dá erro porque não existe essa variável "linha".
Pergunto: Há como fazer que o nome da variável possa variar de acordo com o valor sorteado?
O código ficaria mais enxuto que com o uso de switch.
Comment: talvez trocar a variável linha por um array e cada posição do array seria uma linha
Comment: Pode ser @igorhenrique vou testar. Mas de qualquer forma não terminaria tendo que usar um switch enorme? Códigos enxutos (clean) melhoram o desempenho da aplicação web, a página carrega mais rápido, facilita compreensão e manutenção do código né? Sempre que que possível procuro otimizar.
Comment: Não. Como cada posição do array representa um linha, não é necessário fazer a checagem pelo switch para somar, você acaba fazendo a soma de forma mas genérica.
Answer: $linha = array();

//crio um laço com 50 loops, por exemplo
for($i=1;$i<=50;$i++) {

   shuffle($cincoNumeros);
   $umNumero = array_slice($cincoNumeros, 0, 1);
   $valor = $umNumero[0];
   //cada linha corresponde a uma posição do array
   $linha[$valor] += 1;
}

Comment: Sua sugestão é uma boa solução. Até porque, pesquisei e não encontrei nada que se aproxime do que imaginei. Talvez não seja possível.


Find the name of a file except its directory

Question: I used the following code to read all files in a folder:
files_path = [os.path.abspath(x) for x in os.listdir()]
fnames_transfer = [x for x in files_path if x.endswith(".mkv")]

Now I need to extract the name of the file except its directory. For example fnames_transfer is E:\pythoncode\feature\1.mkv. I need to extract 1.mkv from this string. What should I do for this?
Comment: Why are you using `os.path.abspath()` in the first place?
Answer: I used this os.path.basename(fnames_transfer[i] )and it works for me.


How to convert a list made up of one tuple into a two item list?

Question: I have a function that returns a one item list, like so:
list = [('array_1','array_2')]

I want to change this so that the list is instead a two item one, without the parentheses or single quotes:
list = [array_1,array_2]

What would be the best way to go about doing this?
Comment: `list([('array_1','array_2')][0])`, that would translate the tuple into a list containing both of the entries.
Comment: The first is a tuple of strings, the second is a list containing two variables, where do these come from? There is insufficient information to answer your question.
Answer: Try this
 lists = [('array_1','array_2')]
print([y for x in lists for y in x])

output
['array_1', 'array_2']

Answer: Use chain.from_iterable
from itertools import chain

list(chain.from_iterable([('array_1','array_2')]))

['array_1', 'array_2']

Answer: You can try this:
lst_tuple = [('array_1', 'array_2')]
lst = []
for i in lst_tuple[0]:
    lst.append(i)

By iteratating over the list that contains the tuple and appending each item to a new list, you can get this result:
['array_1', 'array_2']

Answer: You could just typecast like this.
list = list([('array_1','array_2')][0])


optimization Determine the coordinates of point

Question: Determine the coordinates of point P of the line passing through points (a; 0) and (0; b), where
a and b are positive, which maximize the area of the rectangle shown in the diagram.
diagram
if someone can give me some explanation it would be appreciated.
Answer: You can solve the problem in many different ways.
The equation of the straight line is $\frac{x}{a} + \frac{y}{b} = 1$
Let the co-ordinates of $P$ be $(t, b(1-\frac{t}{a}))$
Area of the rectangle $f(t) = bt(1-\frac{t}{a})$
You need to find the value of $t$ that maximizes $f(t)$
Method 1: Algebra
Since $f(t) = \frac{b}{a} \left(\frac{a^2}{4} - (t-\frac{a}{2})^2 \right)$
it is maximum when $t = \frac{a}{2}$, i.e., the co-ordinates of $P$ are $(\frac{a}{2}, \frac{b}{2})$
Method 2: Calculus
Set $f'(t) = 0 \implies t = \frac{a}{2}$ and $f''(t) < 0$ means this is indeed a maxima
Method 3: Lagrange multiplier
Let the co-ordinates of $P$ be $(x, y)$
Consider $L = xy + \lambda (\frac{x}{a} + \frac{y}{b} - 1)$
Set $\frac{\partial L}{\partial x} = 0$, $\frac{\partial L}{\partial y} = 0$, $\frac{\partial L}{\partial \lambda} = 0$ and solve to obtain $x = \frac{a}{2}$ and $y = \frac{b}{2}$


Floating Action Button won't stay on top of SnackBar

Question: I've been dealing with this problem for days. I simply can't make the FloatingActionButton to go on top of the SnackBar.
I've seen a lot of tutorials .. Tried everything.
I hope that someone can help me here:
My layout is:
<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/coordinatorLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:layout_collapseMode="pin"/>
        </android.support.design.widget.AppBarLayout>

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|right"
            android:layout_marginBottom="20dp"
            android:layout_marginRight="20dp"
            android:src="@drawable/ic_start"
            app:fabSize="normal"/>

    </android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.DrawerLayout>

My activity code is:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends AppCompatActivity implements OnClickListener {

    DrawerLayout drawerLayout;
    Toolbar toolbar;
    FloatingActionButton fab;

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

        setupToolbar();
        setupFab();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                if(drawerLayout != null)
                    drawerLayout.openDrawer(GravityCompat.START);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setupNavigationView(){

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    }

    private void setupFab(){
        fab = (FloatingActionButton) findViewById(R.id.fab);
        if(fab != null)
            fab.setOnClickListener(this);
    }
    private void setupToolbar(){
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        if(toolbar != null)
            setSupportActionBar(toolbar);

        // Show menu icon
        final ActionBar ab = getSupportActionBar();
        ab.setHomeAsUpIndicator(R.drawable.ic_menu);
        ab.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public void onClick(View view) {

        if(view.getId() == R.id.fab){

            Snackbar
              .make(findViewById(R.id.coordinatorLayout), "This is Snackbar", Snackbar.LENGTH_LONG)
              .setAction("Action", this)
              .show(); // Don�t forget to show!
        }
    }
}

The result is this one:
Comment: May i know what scrollable view you are using?
Comment: Follow this guide: http://inthecheesefactory.com/blog/android-design-support-library-codelab/en
Comment: It is a ViewPager @Sree14. And each of the fragments have a recyclerView
Comment: @FábioCarballo Have you found an answer? I'm having the same issue when I try to click the button multiple times.
Comment: @SrikarReddy hey, to me the problem was with proguard.
Answer: Instead of using the coordinatorLayout, but actually you need the FloatingActionButton's view :
@Override
public void onClick(View view) {
    if(view.getId() == R.id.fab) {
        Snackbar .make(view, "This is Snackbar", Snackbar.LENGTH_LONG) .setAction("Action", this) .show();
    }
 }

Answer: Put this attribute in your FloatingActionButton(FAB):
app:layout_anchor="@id/coordinatorLayout"

This should associate the FAB with your CoordinatorLayout.
Comment: ```java.lang.IllegalStateException: View can not be anchored to the the parent CoordinatorLayout```


Question about a DNS and subdomain on a different server

Question: I want to know if and how I can do the following:
server A is the main server for www.aserver.com
server B is a server that gives webservices, and one of the services is for activator (an internal webservice. it gives the service via  xx.xx.xx.xx/activator/service.aspx
I want that when someone goes to ws.aserver.com/activator/service.aspx that it will actually pull the page at from xx.xx.xx.xx/activator/service.aspx (bserver) but it will look like ws.aserver.com/activator/service.aspx
ws.aserver.com's A record cannot point to bserver, because some requests for this host must be served by aserver. And for legacy reasons, the URL cannot change.

bserver only have an IP - it is not DNS managed
what should I write for the ws on aserver?  ANAME?  CNAME?  subdomain?  redirect?  dns routing?
So many names....
Comment: If you're not able/willing to have DNS for ws point to server B, then the only option is to have it point to some other machine (possibly A) that acts as a proxy. But that's far less efficient. Why not just have DNS point to B? And all of your possible answers, with the exception of 'redirect', are DNS terms... which suggests that you _do_ intend to make bserver "DNS managed"
Comment: I am not sure what I said really. saying DNS managed, I mean that I will not have a DNS on the server. however, what do you mean: "just have DNS point to B"?  I can't and don't want to have: ws.aserver.com  go blindly to bserver.com .   ws.aserver.com gives other services, as well as IIS7.5 websites.
Comment: So the 'ws' hostname is handled by multiple servers? Why not use two different hostnames, then? Maybe call bserver 'ws2'?
Comment: If by "handled" you mean, some services are onaserver and some are on bserver - than yes.  The reason I can't do "ws2" is that for 2 years now, the released version of the software, have ws.aserver.com/activator/service.aspx  hardcoded in them. that's the main reason.
Answer: It sounds like what you need is a reverse proxy server.  This would be a machine that sits in front of your two HTTP servers, and based on the URL path, it directs the requests to the appropriate place.
This wouldn't have to be a physically separate box--you could potentially run that service on aserver or bserver, if you have sufficient resources there.
You could also accomplish this with simple HTTP redirects (which you seemed to elude to in your question) on aserver, but that's far less efficient, as it means the requesting client actually ends up making two requests.
Squid is a popular HTTP proxy that can be set up as a reverse proxy. I've never tried it, though.  I believe Apache (probably with additional modules) can also do this itself, but again, I've never tried.
Comment: Apache's [mod_proxy](http://httpd.apache.org/docs/2.2/mod/mod_proxy.html) is a good way to do it as well, especially if you're already running apache on one of your two servers.


How to plot trees with introgression using ggtree or Python's ETE toolkit?

Question: I'm migrating a question I asked some days ago in ggtree's google forum. Since SO community is larger and, more importantly, since I have to move on with my project, I'm giving a shot that someone here might have an answer. I'm plotting a phylogenetic tree in which the colour of the branches corresponds to the species. My tree has introgression. That means: All the individuals of the same species may not be connected to a unique node in the tree, but are scattered all around it. To reflect this discrepancy, I want to colour branches grouping a set of individuals that belong to the same species (so call operational taxonomic units or OTUs) until a conflict is found.
For instance, in the following plot (without introgression), t3, t4 and t10 belong to "green" OTU, while t1, t2, t7 and t8 to "red" OTU. Once these differing OTUs hit the same node in the tree, the remaining branches are coloured black.
library(ggtree)
set.seed(123)
tree <- rtree(10)

cls <- list(c1=c("t1", "t2","t8","t7"),
        c2=c("t3", "t4", "t10"),
        c3=c( "t9","t6","t5"))

tree <- groupOTU(tree, cls)
ggtree(tree, aes(color=group)) + geom_text(aes(label=label)) +
 scale_color_manual(values=c("black", "red","green","blue")) +
  theme(legend.position="right")

This is the behaviour I want for well defined OTUs, unfortunately, once introgression is added to the equation, and individuals of different species are spread throughout the tree, ggtree seems to assign colours to conflicting branches based on some sort of majority consensus (plot to the left). In the following plot, f1, part of species "green", has introgressed with individuals in species "red". Since the node connecting t1 and t2 marks a discrepancy in the phylogeny, I would like colour black the remaining edges until the origin (plot to the right).
library(ggtree)
set.seed(123)
tree <- rtree(10)

cls <- list(c1=c( "t2","t8","t7"),
        c2=c("t3", "t4", "t10","t1"),
        c3=c( "t9","t6","t5"))

tree <- groupOTU(tree, cls)
ggtree(tree, aes(color=group)) + geom_text(aes(label=label)) +
 scale_color_manual(values=c("black", "red","green","blue")) +
  theme(legend.position="right")

Having the edges after the conflict coloured black is not only awful. Is misleading from a scientific point of view. Is there a way to fix this problem and get the plot on the right?
EDIT -------
If you can do this using Python ETE Toolkit, I'm open to hear from you...
Answer: you should tag your post with #ggtree.
already answered in https://groups.google.com/forum/#!topic/bioc-ggtree/Q4LnwoTf1DM.


Nome de autor em meta property

Question: Opa,
Preciso adicionar o nome de um autor do artigo, igual a essa imagem:

Meus códigos são:
<meta xmlns="" property="og:url" content="http://www.meusite.com.br/noticia/19/l-wander/emprego/testando-noticia">
<link rel="canonical" href="http://www.meusite.com.br/noticia/19/l-wander/emprego/testando-noticia">

<meta itemprop="name" content="Testando noticia, porL. Wander em 09/09/2016 09:54">
<meta itemprop="description" content="asf sfsdf as">
<meta itemprop="image" content="http://meusite.com.br/images/noticias/3979f3543ba1b09e54b55578cbb506fd.jpg">

<meta property="og:type" content="article">
<meta property="og:title" content="Testando noticia, por L. Wander em 09/09/2016 09:54">
<meta property="og:description" content="asf sfsdf as">
<meta property="og:image" content="http://meusite.com.br/images/noticias/3979f3543ba1b09e54b55578cbb506fd.jpg">
<meta property="og:image:type" content="image/jpeg">
<meta property="og:url" content="http://www.meusite.com.br">
<meta property="og:site_name" content="meusite Brasil">
<meta property="og:see_also" content="http://www.meusite.com.br/noticia/19/l-wander/emprego/testando-noticia">
<meta property="og:locale" content="pt_BR">
<meta property="article:author" content="L. Wander">
<meta property="article:publisher" content="L. Wander">

<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="meusite Brasil">
<meta name="twitter:title" content="Testando noticia, porL. Wander em 09/09/2016 09:54">
<meta name="twitter:description" content="Testando noticia, por L. Wander em 09/09/2016 09:54">
<meta name="twitter:creator" content="Testando noticia">
<meta name="twitter:image:src" content="http://meusite.com.br/images/noticias/3979f3543ba1b09e54b55578cbb506fd.jpg">
<meta name="twitter:domain" content="meusite.com.br">

Está normal, mas, preciso que o nome da pessoa apareça ao lado no link do site.
Answer: Resolvi faz um tempo, lembrei de postar a solução agora:
<meta property="article:author" content="URL do Facebook do Autor">

Nome de autor em meta property


How to create a page to custom display of particular node type and add it to node context menu?

Question:
I created custom node type, let's say "My Node".
I created custom node display type (at /admin/structure/display-modes/view), let's say "Specialized Display".
Configured the "Specialized Display" for "My Node" - configured some fields, their order, etc.
How can I create a page on path "node/*/specialized-display" for "My Node" nodes using "Specialized Display"? (I.e. reject "node/123/specialized-display" if "node/123" is not "My Node", but e.g. "story".)
How can I make a tab appear in node context menu (the one which contains "View", "Edit", "Delete" tabs)?
Bonus question: how can I make URL automatic alias(es) "[alias of node/%]/specialized-display"?

What I tried
Created view page, path "node/%/specialized-display", use contextual filter (to reject different node types, use argument for node selection and to alter page title).
Problems:

Couldn't find out how to add it to the node context menu.
It creates redundant node title on the page (one for whole page and one for item in view). Couldn't find out how to remove it, but it's not that big problem, I'll remove is using CSS (although accessibility is going to be damaged).

My system: Drupal version: 8.8.3
Answer: First question:
First you are going to want to set your views path to: node/%node/specialized-display. Then, in the contextual filter, under "WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED" check off: Specify validation criteria. Finally, select "Content" from the dropdown and select your node type.
Second Question:
This guide explains how to add contextual links, all you are going to need a basic custom module with a routing.yml file. You can set the route to the view. Hint, Drupal console's drupal debug:router is a great way to find the route to your view. https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-contextual-links#s-rendering-contextual-links
Third question:
I've had my best luck with the sub-pathauto module to make the aliased routes. https://www.drupal.org/project/subpathauto
Thoughts...
I am using this setup on two sites so far and this works pretty well. Sub-Pathauto seems to behave fairly well. I do have one tip though, when initially building my views, I disable it, so that I can ensure everything works before I add the extra layer.
Other thoughts...
This could be done through traditional custom views processing. If you have a big site, it may be the way to go. I haven't tested Sub-Pathauto at large scale, this is currently something I am experimenting with.
Comment: I'll check this later - I can work on this project mostly only during weekends. But at first look, it looks great. (Point is: I'm not ignoring this answer.)
Comment: I missed your last bullet, just saw it on this pass. You must be rendering your page title in the blocks and on the node. You can choose to render different view modes. Personally I use display suite, select "reset", go to full content and remove the title. WHat I'm saying is this comes down to how your site is setup somewhat. Maybe ask a new question with those extra details added once you have this working. Glad your not ignoring my answer! Good luck!


Positive series for use the Ratio test or the Root test

Question: I have a question:
for use the Ratio test or the Root test I need the series will be positive or non negative (zero can belong to series? why?)
Comment: Can you clarify your question? Your question seems to be asking two things: 1) Is it true that to use the ratio test or root test the series must be non-negative? and 2) Can $0$ be in the series? Am I correct?
Comment: Its same.. non-negative say that can 0 be in the series
Answer: No. The root and ratio test are defined in absolute values, so you dont need that the series will be non-negative to use them. But the ratio test requires that the series will be eventually non-zero.
Take a look, by example, here.
Comment: of course. Why you think you cant use them in this case?
Comment: @Master the ratio test its a limit, then it is enough that exists some $N\in\Bbb N$ such that $a_n\neq0$ for all $n\ge N$. This is the meaning of "eventually non-zero".
Comment: Can i use these tests for series that for example: $a_0 = 0$ ?
Comment: Because that for example, in the ratio test i divide in $a_n$, and what will be if it's $0$?
Comment: Thank you about your complete answer!!


Importance of McNemar test in caret::confusionMatrix

Question: There are many metrics to evaluate the performance of predictive model.  Many of these appear relatively straightforward to me (e.g. Accuracy, Kappa, AUC-ROC, etc.) but I am uncertain regarding the McNemar test.  Could someone kindly help me understand the interpretation of the McNemar Test on a predictive model contingency table?  This is applied and the P-Value returned from the R function caret::confusionMatrix.  Everything I read about McNemar talks about comparing between before and after a 'treatment'.  In this case, I would be comparing predicted classes vs. the known test classes.  Am I correct to interpret a significant McNemar test to mean that the proportion of classes is different between the testing classes and the predicted classes?
A second, but more general, followup question would be how should this factor in to interpreting the performance of a predictive model?  For example, as reflected in the 1st example below, in some circumstances 75% accuracy may be considered great but the proportion of predicted classes may be different (assuming my understanding of a significant McNemar test is accurate).  How would one approach such a circumstance?
Lastly, does this interpretation change if more classes or involved?  For example a contingency matrix of 3x3 or larger.
Providing some reproducible examples mirrored from here:
#significant p-value
mat <- matrix(c(661,36,246,207), nrow=2)

caret::confusionMatrix(as.table(mat))
> caret::confusionMatrix(as.table(mat))
Confusion Matrix and Statistics

    A   B
A 661 246
B  36 207

               Accuracy : 0.7548
                 95% CI : (0.7289, 0.7794)
    No Information Rate : 0.6061
    P-Value [Acc > NIR] : < 2.2e-16

                  Kappa : 0.4411
 Mcnemar's Test P-Value : < 2.2e-16
... truncated

# non-significant p-value
mat <- matrix(c(663,46,34,407), nrow=2)

caret::confusionMatrix(as.table(mat))
Confusion Matrix and Statistics

    A   B
A 663  34
B  46 407

               Accuracy : 0.9304
                 95% CI : (0.9142, 0.9445)
    No Information Rate : 0.6165
    P-Value [Acc > NIR] : <2e-16

                  Kappa : 0.8536
 Mcnemar's Test P-Value : 0.2188
... truncated

Answer: Interpret the McNemar's Test for Classifiers
McNemar's Test captures the errors made by both models. Specifically, the No/Yes and Yes/No (A/B and B/A in your case) cells in the confusion matrix. The test checks if there is a significant difference between the counts in these two cells. That is all.
If these cells have counts that are similar, it shows us that both models make errors in much the same proportion, just on different instances of the test set. In this case, the result of the test would not be significant and the null hypothesis would not be rejected.

Fail to Reject Null Hypothesis: Classifiers have a similar proportion
  of errors on the test set.
Reject Null Hypothesis: Classifiers have a different proportion of
  errors on the test set.

More information can be found out here:
https://machinelearningmastery.com/mcnemars-test-for-machine-learning/
Answer: This is an interesting question that has different answers according to the context. I agree with what
have answered you before, so here I will focus more on the context.
It is normal that you have been confused when looking for McNemar's test interpretation on the Internet. The main reason is that both the historical origin of the test (Genetics), as well as its common use in the medical and social science fields, make its interpretation difficult in the context of machine learning. Here I explain what I have learned so far.
First of all, it is important to know that there are two different scenarios in the context of machine learning. The first one is that you are evaluating the quality of your model vs. the reference data (test data or possibly training data). The second scenario is when you are comparing two classification models (algorithms).
In the first scenario you would normally look for the p-value of the test to be greater than 0.05. That is, do not reject the null hypothesis that assumes homogeneity of the proportion of misclassified cases for the two class labels. In your confusion matrix above, these proportions are calculated from cells AB and BA. A significant value here would indicate that your algorithm misclassifies one label more than another.
In the second scenario you would probably look for the opposite. That is, that the p-value of the test is less than 0.05. This would indicate that the classifiers have different error rates. This is evidence that you can use in conjunction with other indicators such as individual model accuracy to conclude that one is better than another.
On your second question, you may have already seen that the accuracy provided by the caret package has nothing to do with McNemar's test. This is because the accuracy measures other information from the confusion matrix (cells AA and BB).
Finally, on the third question I agree with what Alexis suggested.
In summary: what McNemar's theoretically calls marginal homogeneity is, in the first scenario, the homogeneity of the rate of misclassifying the two class labels. In the second scenario, it refers to the homogeneity of the error rates of the classifiers.
I hope that these ideas will give you a better understanding of the results that caret provides.
Answer: McNemar's test is specifically a test of paired proportions. Pre-post is one structure defining pairing, but cross-sectional measurement of two separate dichotomous variables is also an allowable pairing structure in the data, the quasi-longitudinal nature of case-control data is yet another pairing structure appropriate to this test.
The null hypothesis is more or less that the proportions of one variable are equal across both values of the other other variable. A significant test result means that you have rejected this null hypothesis, and decided that your two variables are associated (i.e. that knowing something about one, gives you information about the other), and therefore that the proportion of one variable changes depending on the values of the other variable.
Blunt accuracy does not account for the accuracy due to chance, which is dependent on the size of the proportions in each group.
McNemar's test can only be applied to a 2x2 table, so no 3x3. However, there is Cochran's Q test which is like a generalization of McNemar's test to the repeated measures scenario for binary data—that is, it is analogous to a repeated measures ANOVA for binary measures—(Cochran's Q for a 2x2 gives the same results as for McNemar's test... caveat: take care regarding continuity corrections).
Comment: +1, but there is a mistake in the last paragraph. Cochran's Q test is for 2x2x2x... table situation with the same 2 categories, not for kxk table with the same k categories. As `McNemar-test` tag info states, it is McNemar-Bowker that is for such situation. Classic McNemar (for dichotomous case) is equivalent to Sign test applied to dichotomous data.
Comment: Thank you Alexis but could you put it in context for a predictive model?  Please correct me if wrong here, the 1st model rejects the null so therefore the proportion between the test data (known classes) is different from the predicted proportion.
Comment: My confusion comes in cases where both accuracy and Kappa (which I have read does account for chance) are high and yet the mcnemar p-value is very low.  Such an example is shown in [this pdf](http://static.squarespace.com/static/51156277e4b0b8b2ffe11c00/t/5310d223e4b0d21c529a0814/1393611299730/webinar.pdf).  How should that be interpreted?  This seems on the face of it to be a bad thing (when trying to create a predictive model).
Comment: @ttnphns Thanks for pointing out my mistake. However, Cochran's *Q* is for more than *paired* data, and generalizes to fully *repeated measures* structures. See my edits.


Automatically fix sonar rule

Question: I'm looking for automaticaly fix this rule :
checkstyle:javadoc.SummaryJavadocCheck

I have over 1000 javadoc that don't have point at the end of the first line. I don't want to edit file one by one but perhaps in bash i can do a replace of the first line after  /** that don't have point at the end?
Can someone help me for this or another idea?
EDIT1:
Invalid javadoc :
/**
 * Javadoc comment
 *
 * @return object an object
 */

Correct javadoc
/**
 * Javadoc comment.
 *
 * @return object an object
 */

Sonar want a point at the end of the line. It's not critical, just want to know if it's possible.
thanks
Comment: I don't know javadoc, but my guess is that you mean you want a `.` at the end of all lines following a line containing `/**`, right ?
Comment: yes but if the line has more than 100 characters, the line is automatically wrap to new line, so possibly, the `.` is not just at the end of the following line containing `/**`but it represent 90% and i can do all the other line manually ;)
Answer: You may use awk or sed, or pure bash : match exactly /** then add a dot on next line when that line does not have one. sed and bash versions below :
sed version:
sed -i.bak '/^\/\*\*$/{n;s/\([^\.]\)$/\1./;}' file1 file2 ...

Explanation :
-i.bak edit files inline, and create a backup (.bak).
/^\/\*\*$/ matches only lines which contain exactly /**.
{...} sed command block
n append next line in pattern space.
s/\([^\.]\)$/\1./ replace non "." (\([^\.]\)$) last character with itself and a dot (\1.).
Pure bash solution:
#!/bin/bash

while read -r line; do
    if [[ $line =~ ^/\*\*$ ]]; then
        read -r line2
        [[ $line2 =~ \.$ ]] || line2="$line2."
        printf -v line "%s\n%s" "$line" "$line2"
    fi
    printf "%s\n" "$line"
done

To do the same as the sed's -i.bak, you can use the bash version with something like:
for file in *.java; do
   cp -p "$file" "$file.bak"
   ./script.bash < "$file.bak" > "$file"
done

Comment: Good. To match exactly zero or more spaces before `/**`, you could also have changed `^` with `^ *` (with a space between the `^` and the `*`).
Comment: hello, i have try the sed command, all work fine but only for the first occurence, i have try to add g option to find all occurence but i think i miss something, thanks for you help ;)
Comment: @MançauxPierre-Alexandre, are you sure the matching `/**` lines contain only those 3 characters plus `\n` (no space, etc...), that the input file is in Unix format (only `\n` at the end of lines) ?
Comment: in fact you are right, it work for first occurence because the first javadoc is on the class and they are no space before `/**` but the javadoc for class methods contains indentation with one or more space before. So i can have space before `/**` so i just need to remove `^` at the beginning of the regexp, and all work fine ;)

Automatically fix sonar rule


USB wlan1 Hotspot stops working when eth0 cable is plugged in

Question: I setup successfully an USB wlan1 as AP via hostapd, and isc-dhcpd (it listens only to wlan1-interface) on a Raspberry 4 (using Raspbian). Regardless if wlan0 (the onboard WIFI) is connected to a WAN hotspot, wlan1 Clients can ping that wlan1 interface. IP Forwarding/masquerade works, and if wlan0 is connected to WAN AP, wlan1 clients also have internet access. Perfect!
But in the moment i plug-in eth0, wlan1 clients can still connect to that AP (Status connected), but can NOT PING that wlan1 interface anymore (and no WAN access anymore).
That's weird! The DHCP Server pushed the same valid IP's to the client as before, and static IP of wlan1 also stays the same (eth0 and wlan1 have static IP). wlan1 can be pinged locally from the rapsberry (but not from an external client).
When i un-plug eth0, it work's again.
What's going wrong and why i canot even ping that interface anymore?
sysctl IPv4 forwarding is enabled.
...
$ ip link
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
3: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
4: wlan1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
...

$ ip addr
...
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether e4:5f:01:84:db:34 brd ff:ff:ff:ff:ff:ff
    inet 10.8.0.2/8 brd 10.255.255.255 scope global noprefixroute eth0
       valid_lft forever preferred_lft forever
...
3: wlan0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast state DOWN group default qlen 1000
    link/ether e4:5f:01:84:db:37 brd ff:ff:ff:ff:ff:ff
4: wlan1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether a0:f3:c1:23:2d:62 brd ff:ff:ff:ff:ff:ff
    inet 10.8.5.1/8 brd 10.255.255.255 scope global noprefixroute wlan1
       valid_lft forever preferred_lft forever
...

$nft list ruleset
...
table ip nat {
        chain postrouting {
                type nat hook postrouting priority srcnat; policy accept;
                masquerade
        }
}
...

$ cat /etc/hostapd/hostapd.conf
interface=wlan1
#If this fails, try rt1871xdrv a
#driver=nl80211
# Name of the new network: best use the hostname
ssid=xxx

# Pick a channel not already in use
channel=1
# Change to b for older devices?
hw_mode=g
macaddr_acl=0
auth_algs=3
# Disable this to insure the AP is visible:
ignore_broadcast_ssid=0

wpa=2
wpa_passphrase=xxx
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP

#bridge=br0 # no bridge! We're using routing
country_code=JP

cat /etc/dhcpcd.conf
...
interface eth0
static ip_address=10.8.0.2/8
static routers=10.8.0.1
static domain_name_servers=127.0.0.1

interface wlan1
static ip_address=10.8.5.1/8
nohook wpa_supplicant
static domain_name_servers=127.0.0.1

interface wlan0
static domain_name_servers=127.0.0.1

cat /etc/dhcp/dhcpd.conf
...
authoritative;

subnet 10.8.5.0 netmask 255.255.255.0 {
  range 10.8.5.201 10.8.5.250;
  option broadcast-address 10.8.5.255;
  option routers 10.8.5.1;
  default-lease-time 600;
  max-lease-time 7200;
  option domain-name "local";
  option domain-name-servers 10.8.5.1;
}

host ares {
  hardware ethernet 04:ea:56:ae:58:03;
  fixed-address 10.8.5.20;
}

$ ipconfig # on Windows 11 Client
...
Wireless LAN adapter Wi-Fi:

   Connection-specific DNS Suffix  . : local
   Description . . . . . . . . . . . : Intel(R) Dual Band Wireless-AC 8265
   Physical Address. . . . . . . . . : 04-EA-56-AE-58-03
   DHCP Enabled. . . . . . . . . . . : Yes
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::9300:7ccf:3e03:eaf9%17(Preferred)
   IPv4 Address. . . . . . . . . . . : 10.8.5.20(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Lease Obtained. . . . . . . . . . : Friday, 16 December 2022 22:56:38
   Lease Expires . . . . . . . . . . : Friday, 16 December 2022 23:06:37
   Default Gateway . . . . . . . . . : 10.8.5.1
   DHCP Server . . . . . . . . . . . : 10.8.5.1
   DHCPv6 IAID . . . . . . . . . . . : 168094294
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-26-1E-05-25-48-2A-E3-3A-C9-F0
   DNS Servers . . . . . . . . . . . : 10.8.5.1
   NetBIOS over Tcpip. . . . . . . . : Enabled
...

Answer: Your IP addresses are:

10.8.0.2/8 for wlan1
10.8.5.1/8 for eth0

Those are in the same subnet. 10.0.0.0/8 covers everything from 10.0.0.0 to 10.255.255.255.
Yet, on your DHCP scope, the netmask is suddenly /24.
The general rule is that if you want to send traffic within a subnet, you need a switch (bridge), while you need a router to send traffic between subnets. When your machine gets a packet from one of your connected clients - which believe 10.8.5.0/24 is a subnet, it doesn't understand what to do with it, as it's addressed to a host in the same subnet as the originator.
You probably want /24 defined everywhere, so replace the netmask for eth0 and wlan1 with /24, not /8.
As to observed behavior: routes carry a weight. Faster interfaces float to the top. Your machine believes wlan1 and eth0 both point to the same destination. Thus, it sends the packet over the best interface (lowest weight in the routing table), which is the wired Ethernet interface. If it was properly configured with separate subnets, it'll work just fine.
Comment: That's it! Yea, i accidentally mixed-up `/8` with `/24`. After changing to `/24`, the AP is pingable. But now I have another problem: The Clients do not have WAN access anymore (but the server has)
Comment: Your wan router doesn't have a valid route to your clients behind the pi. And you should probably accept the answer so we avoid having the question popping up every few months...


Char buffer input more than than 256 characters

Question: I'm creating a program on DOS using the FreeRTOS kernel which allows me to render multiple windows onto the screen that contains its own text user interface. The issue is that I've encountered an overflow error which was caused by feeding more than 256 characters into the buffer. Is there a way to work around this?
A portion of my code:
int default_background=0;
int default_foreground=15;

struct window {                        /* Window structure */
    int special_id;
    int cursor_x,cursor_y;
    int width,height;
    long *background,*foreground;
    char *buffer;
};

long window_index_count=0;
struct window current_windows[10];

long create_window(int width,int height) {
    int i;
    long t;
    struct window new_window;
    new_window.special_id=window_index_count;
    window_index_count=window_index_count+1;
    new_window.cursor_x=0;
    new_window.cursor_y=0;
    new_window.width=width;
    new_window.height=height;
    for (t=0; t<width*height; t++) {
        new_window.background[t]=default_background;
        new_window.foreground[t]=default_foreground;
        new_window.buffer[t]=' ';      /* This is where the error occurs */
    }
    for (i=0; i<10; i++) {
        if (current_windows[i].special_id<=0) {
            current_windows[i]=new_window;
            break;
        }
    }
    return new_window.special_id;
}

Comment: You haven't allocated any memory for arrays, which are pointed by `background`, `foreground` and `buffer` pointers.
Comment: I just realized my mistake there. I never realized it wasn't allocated.
Comment: Wow, it got fixed. Thanks!
Answer: You don't actually allocate memory for the buffer. Since local non-static variables are by default uninitialized, their values are indeterminate. So when you use the pointer new_window.buffer you have no idea where it points to, leading to undefined behavior.
It's the same with the other pointers in the structure as well.
The solution is to actually allocate memory for the pointers to point to.


Python Authentication Issue When Modularizing Tableau API

Question: I have the following Python code that successfully authenticates and retrieves data using the Tableau API:
# Original Code
def get_all_client_users(client):
    client_users = []
    tableau_auth = TSC.TableauAuth(
        os.getenv('tableau_username'), os.getenv('tableau_pass'), client)
    server = TSC.Server(os.getenv('tableau_server_url'),
                        use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        site_users, pagination_item = server.users.get()
        for user in site_users:
            client_users.append(user)
        return client_users

To make the code more modular, I decided to split the authentication process into a separate function as follows:
def get_all_client_users(client):
    client_users = []
    server = utils.get_tableau_server_controller(client)
    site_users, pagination_item = server.users.get()
    for user in site_users:
        client_users.append(user)
    return client_users

And in the utils.py module.
def get_tableau_server_controller(client):
    tableau_auth = TSC.TableauAuth(os.getenv('tableau_username'), os.getenv('tableau_pass'), client)
    server = TSC.Server(os.getenv('tableau_server_url'), use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        return server

Issue:
After modularizing the code, the authentication process no longer works as expected.
Getting an exception: Missing site ID. You must sign in first.
I am not able to understand what can be different for the object when trying to use in the same block and accepting the object from a different function and using the same.
Feels like I am missing out on an important Python concept because of which I am not able to understand the issue.
Can someone guide me in identifying the issue, please?
Answer: Run the with statement in get_all_client_users function.
def get_tableau_server_controller(client):
        tableau_auth = TSC.TableauAuth(os.getenv('tableau_username'), os.getenv('tableau_pass'), client)
        server = TSC.Server(os.getenv('tableau_server_url'), use_server_version=True)
        return server

My understanding of the with statments is that it closes the resources right after processing them. the return statement ended the with statement.
def get_all_client_users(client):
    client_users = []
    server = utils.get_tableau_server_controller(client)
    with server.auth.sign_in(tableau_auth):
        site_users, pagination_item = server.users.get()
        for user in site_users:
            client_users.append(user)
    return client_users

Comment: Thanks. This makes sense. Will try this
Answer: It possibly an issue with you .env file. try specifying the path of the env file.
from dotenv import load_dotenv
from pathlib import Path

dotenv_path = Path('path/to/.env')
load_dotenv(dotenv_path=dotenv_path)

so in the get_tableau_server_controller function.
def get_tableau_server_controller(client):
    tableau_auth = TSC.TableauAuth(os.getenv('path/to/tableau_username.env'),
    os.getenv('/path/to/tableau_pass.env'), client)
    server = TSC.Server(os.getenv('/path/to/tableau_server_url.env'),
    use_server_version=True)
    with server.auth.sign_in(tableau_auth):
        return server

Comment: I checked via debuggers. The value i get is same in both the modules
Comment: The other issue could be  how you used with.


Proof that strong convexity implies Polyak-Lojasiewicz inequality is satisfied

Question: I am attempting to find a proof of strong-convexity implying the Polyak- Lojasiewicz (PL) inequality is satisfied. As I understand it, strong convexity means that:
$$ \textbf{H} f \succcurlyeq \mu I$$
for some $\mu>0$, where $\textbf{H}f$ is the Hessian matrix of $f$ and $I$ is the identity matrix.
The PL inequality states that:
$$\frac{1}{2}\|\nabla f(x)\|^2 \geq \mu(f(x) - f(x^*))$$
where $x^*$ is the value of $x$ for which $f(x)$ is minimized.
This paper http://www.optimization-online.org/DB_FILE/2016/08/5590.pdf states that if a function is strongly convex with constant $\mu$, then it must satisfy the PL inequality with the same constant (page 4, section 2.3, first sentence).
I found a source that says this can be done by minimizing the following inequality:
$$f(y)\ge f(x)+\nabla f(x)^T(y-x)+\frac{\mu}{2}\lVert y-x \rVert^2 \tag{1}$$
in terms of $y$ to get $$f(x^*) \ge f(x)-\frac{1}{2\mu}\|\nabla f(x)\|^2.$$
I don't understand this. How exactly is the inequality being minimized in terms of $y$ here? How do I go from strong convexity to equation (1) to this result?
Comment: A lot of books actually use (1) as the definition of strong convexity, since it does not require $f$ to be twice differentiable. The two notions are equivalent for functions whose Hessian is well-defined. A hint to get from (1) to your desired inequality: $x^*$ minimizes a convex function $f$ if and only if $\nabla f(x^*)=0$.
Comment: Thank you @Zim! I understand how to get (1) now. I am still a little confused about reaching the inequality. How would $\nabla f(x^*) = 0$ fit into the equation? Am I allowed to substitute in $x = x^*$ (in addition to $y = x^*$)?
Answer: Wow, this was a very confusing statement they gave there, but eventually I was able to get to it. Since $f$ is $\mu$-strongly convex, then we have $$f(y)\geq f(x)+\nabla f(x)^T(y-x)+\frac{\mu}{2}\|y-x\|^2$$
Now, minimize the inequity with respect to $y$. Minimization maintains the inequality relation, therefore we will focus on each side separately. LHS is straightforward and we have:
$$\min_y \{f(y)\} = f(x^*)$$
To solve the RHS we will differentiate with respect to $y$ to obtain
$$\frac{\partial RHS}{\partial y}=\nabla f(x)+\mu(y-x)=0\iff y=x-\frac{1}{\mu}\nabla f(x)$$
Plug back the optimal $y$ we found to the RHS and we get $$f(x)-\frac{1}{\mu}\|\nabla f(x)\|^2 + \frac{1}{2\mu}\|\nabla f(x)\|^2$$ and overall we have
$$f(x^*)\geq f(x)-\frac{1}{2\mu}\|\nabla f(x)\|^2$$
Comment: Hi! Thank you so much, your answer clarifies a lot of things. Just one question, I just wanted to check how you got the $-\nabla f(x) $ term in your derivative. Should it not be positive? I tried it myself and I got the same end result with a positive sign on this term. Could be an error on my part, so I just wanted to clarify? Thank you so much for your response!
Comment: @Aryan you're absolutely right, it's a typo. I edited the answer
Comment: You also need to show that $f(x)$is convex or it may not be a global minimum. But by computing the Hessian, it is immediate.


Graphiti / Graphite using Apache with Proxy and BasicAuth requests auth for every URL / request

Question: We have a server with apache set up as an authentication front end for a backend web service running on the same box.
The setup seemed to work at first, but we soon realised that apache was asking for authentication every time we clicked a link, went back or reloaded a page. We're now at a loss to resolve this.
Our apache2 virtual hosts file:
<VirtualHost *:80>

  ServerName app.ourdomain.com
  ErrorLog /var/log/apache2/graphiti-error.log
  CustomLog /var/log/apache2/graphiti-access.log common

  <Location "/">
          require valid-user
          order allow,deny
          Allow from all
          AuthType Basic
          AuthName "Stats"
          AuthBasicProvider file
          AuthUserFile /etc/passwd_lp
  </Location>

  ProxyRequests off
  ProxyPreserveHost on
  ProxyPass / http://localhost:8080/
  ProxyPassReverse / http://localhost:8080/

  <Proxy *>
          Order allow,deny
          Allow from all
  </Proxy>

</VirtualHost>

We're using Apache2 v2.2.22 on Ubuntu EC2 12.04
We have already tried; moving the Auth declarations into the <Proxy> block; setting ProxyRequests on; setting ProxyPreserveHost off.
Thanks
Comment: That sounds like it might be a client browser issue.. Is the browser not re-sending the authorization header with subsequent requests? Or is the hostname the client's accessing changing?
Comment: Hi, we thought this too at first but it's happening with all browsers (FF, Chrome & Safari tested) and the hostnames are consistent.What we suspect to be happening is that Apache forwards the session to the proxy'd backend which does nothing with it. Therefore, every click or reload causes Apache to start a new session and ask for authentication.
Comment: Basic authentication doesn't have any concept of 'sessions' - the client browser is responsible for sending the `Authorization` header with every request.  Can you check if that's happening using Chrome's developer tools or Firebug?
Comment: Thanks for the suggestions. Turns out this one has been a bit of a red herring. See my answer.
Answer: I have now solved this problem. It was nothing to do with Apache in the end (per se). Graphiti uses a JavaScript function to make HTTP requests to the Graphite service, which we had set up as a separate vhost, which also had Auth setup (some users prefer to use it directly).
So basically, no user/password were in the URL that graphite was using, and so every one triggered an Auth prompt. To fix it, we just needed to update our templates so that the URL generates with the http://<user>:<password>@<host> syntax.


field_info_instance returns empty in hook_uninstall

Question: In a custom module, I'm creating a new field and instance for a custom entity type like this:
function mymodule_install() {
  if (!field_info_field('mymodule_field')) {
    $field = array( .... );
    field_create_field($field);
  }
  if (!field_info_instance('mymodule_entity','mymodule_field', 'bundle1')) {
    $instance = array( .... );
    field_create_instance($instance);
  }
}

function mymodule_uninstall() {
  if ($instance = field_info_instance('mymodule_entity','mymodule_field', 'bundle1')) {
    field_delete_instance($instance);
  }
  if (field_info_field('mymodule_field')) {
    field_delete_field('mymodule_field');
  }
  field_purge_batch(100);
}

...and the field and instance gets created properly. However upon uninstalling the module, only the field tables are being deleted while the field instance is still there in the field_config_instance table still having deleted = 0.
Debugging the uninstall process reveals that field_info_instance (and field_read_instances) is returning NULL...
Anyone knows what I'm doing wrong? I'm on a fresh Drupal 7.23 install...
Answer: You don't need field_delete_instance separately, because field_delete_field has it inside.
According to deleted column in field_config (you can skip this value in field_config_instance if you're deleting whole field) debug field_delete_field function.
Comment: `field_delete_field()` still doesn't delete the entry in the `field_config_instance` table...
Comment: `field_config_instance` entry will be removed only after all `field_data_` and `field_revision_` entries are deleted. May be your batch size in purge is not big enough. Check the `deleted` column in field_config, field_config_instance and names of deleted field tables to be sure that field_delete_field was completed successful.
Comment: The field tables are deleted successfully and also their entry in `field_config` is completely removed. The purging function is doing well.. However `field_config_instance`still contains the instance entries with `deleted = 0`..
Comment: Try to run drush cron manually now, it should get cleared otherwise you have a trouble somewhere :)
Comment: Unfortunately no luck. Well, I guess my OP still remains unsolved. Quite odd since it's on a fresh 7.23 install.
Comment: Were fields added correctly? May be some exotic contrib modules? :) Because I have almost the same code in one of my module and it works fine on 7.23.


Gatsby fails after using Sass files with '@use 'sass:color'

Question: I'm setting up a Gatsby Project with gatsby-plugin-sass.
my gatsby-config.js file:
module.exports = {
  plugins: [
    'gatsby-plugin-resolve-src',
    'gatsby-plugin-sass',
    'gatsby-plugin-react-helmet',
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/assets/images`,
      },
    },
  ],
}

I have the following styles file structure:
|
|src
|-styles
|--base
|--- _variables.scss
|--components
|--- _Buttons.scss
|--- ...
|--main.scss

Im my _Buttons.scss file I'm importing like this:
@import '../base/variables';
@use 'sass:color as *;

When I'm trying to use the sass color functions like this (as specified on https://sass-lang.com/documentation/modules)
%buttons-focus {
  background-color: color.adjust($primary-color, $alpha: -0.5);
}

I get the following Error:
Invalid CSS after "...nd-color: color": expected expression (e.g. 1px, bold), was ".adjust($primary-co"

In my main.scss I'm importing styles like this:
@import './components/Buttons';

Am I overseeing something?
I've tried changing up @use with @import, with no luck. For me it seems like the gatsby-sass-plugin is not aware of sass modules.
Answer: gatsby-plugin-sass uses node-sass under the hood.  But in order to support built-in modules with @use, you need to configure gatsby-plugin-sass to use dart-sass instead. See below.
Built-In Modules - sass-lang

Only Dart Sass currently supports loading built-in modules with @use. Users of other implementations must call functions using their global names instead.

Alternative Sass Implementations - gatsby-plugin-sass

By default the node implementation of Sass (node-sass) is used. To use the implementation written in Dart (dart-sass), you can install sass instead of node-sass and pass it into the options as the implementation:

npm install --save-dev sass

gatsby-config.js
plugins: [
  {
    resolve: `gatsby-plugin-sass`,
    options: {
      implementation: require("sass"),
    },
  },
]

Comment: Likewise - I spent some time before I found this, so I've filled a request to add some docs/errors which help identify the problem: https://github.com/sass/node-sass/issues/2991


Headless fragment with arguments, how to use Fragment.newInstance?

Question: I've been working through 3 different tutorials to get a headless fragment to open sockets and stay open through lifecycle changes. I think I'm really close but there is one final element that escapes me. The guts of the fragment for opening the sockets and threads is based on a class that works fairly well so I'm not too concerned with that part, at least for now. Here is the relevant parts of the fragment, the rest left out to make it less torturous to read. What I'm trying to do is pass in a p2p Group Owner's IP and port. (no problems with that)
public class ConnectionFragment extends Fragment {

    private InetAddress mGoAddress;
    private int mGoPort;
    private Client mClient;
    private static final String TAG = "Connection";
    private static final String CLIENT_TAG = "Client";
    private Server mServer;
    private Socket mSocket;
    private ConnectionFragmentListener mListener;

    public static ConnectionFragment newInstance(InetAddress address, int port){
        Bundle bundle = new Bundle();
        bundle.putSerializable("GoAddress", address);
        bundle.putInt("GoPort", port);
        ConnectionFragment fragment = new ConnectionFragment();
        fragment.setArguments(bundle);

        return fragment;
    }

    private void readBundle(Bundle bundle){
        if (bundle != null){
            mGoAddress = (InetAddress)bundle.getSerializable("GoAddress");
            mGoPort = bundle.getInt("GoPort");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        readBundle(getArguments());
        mGoAddress = (InetAddress) getArguments().getSerializable("GoAddress");
        mGoPort = getArguments().getInt("GoPort");

        mServer = new Server();

    }

Then in my activity I do this, giving it the Group Owner IP and port.
mConnection = ConnectionFragment.newInstance(goInetAddress, prefixedPort);

My question is, what do I do next to run mConnection?
Thank you.
Comment: Why are you using Fragments for this, and not a Service?
Answer: You've got to add the fragment after creating it. Since it's headless, you won't need a container id:
getSupportFragmentManager()
    .beginTransaction()
    .add(mConnection, TAG)
    .commit();


Derivative of Bernoulli random variable with respect to $p$

Question: Question: Let $B\sim$ Bernoulli$(p)$ be a random variable drawn from a Bernoulli distribution with parameter $p$. What is the derivative $$\frac{d}{dp}B\:?$$
Background: I encountered this term while deriving the log-likelihood function of a specific distribution with the objective of finding the maximum likelihood estimate for $p$. There are many other terms in the original equation, but I am unsure about the derivative of this one.
What I tried so far: Since the cumulative distribution function is $$F_B(\omega)=\begin{cases}0\quad&\omega < 0\\1-p \quad& 0\le\omega< 1\\1 \quad &\omega \ge 1 \end{cases}$$ I would expect that the derivative is $$\frac{d}{dp}B = \begin{cases}-1 \quad& 0\le\omega< 1\\0 \quad &\text{else}\end{cases}$$ but I am not sure if this is correct because I don't know if I am allowed to simply plug in the CDF. Does this make sense?
Comment: Unless you have an explicit definition of $B$ as  a r.v. depending on $p$ you cannot differentiate it w.r.t. $p$.
Comment: @geetha290krm Thank you for your comment. I was not sure if $B$ being drawn from Bernoulli$(p)$ counts as $B$ is a function of $p$. So if $B$ is not a function of $p$ is then its derivative $0$, not defined or not solvable?
Answer: If we think of $B$ as a function from some sample space $\Omega$ to $\{0,1\}$, then $B_p(\omega)$ is the value of $B$ with parameter $p$ at sample space point $\omega$.
Let's pick $\Omega = [0,1]$ and $B_p(\omega)=1_{>p}(\omega),;\ p \in [0,1]$ with probability measure being the 1-Lebesgue measure $\mu_1$ and the $\sigma-$field being $\mathcal{B}([0,1])$ so we get the probability space $S_0:=([0,1],\mathcal{B}([0,1]),\mu_1)$
With this, we see that $B_p(\omega)$ is a step function as a function of $p$, where $B_p(\omega)=1$ for $p<\omega$ and $0$ otherwise.
$$\frac{d}{dp}B_p(\omega) = \delta_p(\omega) $$
Where $\delta_p$ is the dirac delta function at $p$.
Comment: Thank you for your answer. So the derivative of $B$ with respect to $p$ depends on how we define the probability space $S_0$?
Comment: @mto_19 no, I think you can leave it general $\Omega$ but it does depend on how you define $B(\omega)$ as mentioned in the comments. The sample space of random variable is often left unspecified in and we often just work with the case where sample space is the range of the random variable and the probability measure is the distribution of the random variable. I just wanted to make $B_p(x)$ a concrete function for clarity -- I'm not as comfortable with trying to do this in full generality.


What are easy steps of finding cutpoint in continuous variable with Time to event outcome, in Stata?

Question: I find it painful to manually guess a dichotomized cutpoint predictor (continuous) for an time to event outcome in Simple Cox proportional hazard model.
Currently I was trying to find the cutpoint that make the smallest p-value in the model.
If I can find it, Do I have to use ROC curve to fine-tune it? if so, how to do it?
Comment: Don't dichotomize a continuous variable. In addition, looking for a data manipulation to minimize your p-values is data dredging.
Comment: Thank you for your reply. In my case, the cut-point is needed to find the proper criteria to make a diagnosis of a particular disease.
Comment: See [this page](http://stats.stackexchange.com/questions/68834/what-is-the-benefit-of-breaking-up-a-continuous-predictor-variable/68839#68839) and many others on this site why you should not try to break up your continuous predictor this way, for this or for any type of regression/classification scheme. Much better to learn about the actual relation between your continuous predictor and outcome when standard clinical variables are taken into account in your Cox model.
Answer: Partially answered in comments:
Don't dichotomize a continuous variable. In addition, looking for a data manipulation to minimize your p-values is data dredging. – gung
See this page and many others on this site why you should not try to break up your continuous predictor this way, for this or for any type of regression/classification scheme. Much better to learn about the actual relation between your continuous predictor and outcome when standard clinical variables are taken into account in your Cox model. – EdM
To which OP responded:  In my case, the cut-point is needed to find the proper criteria to make a diagnosis of a particular disease.  Answer to that is: If the goal is to find a decision cut-point to make diagnosis for a particular disease, then do that after model construction and estimation, estimation and decision is different problems. In particular, decision tresholds could vary with patient caracteristics.  See for instance the F Harrell quote in Calculating F-Score, which is the "positive" class, the majority or minority class?


Reduced row-echelon form, and $A^{-1}B$.

Question: I have to prove the following
Let $A$ be a nonsingular $n \times n$ matrix and let $B$ be an $n \times r$ matrix. Show that the reduced row echelon form of $(A|B)$ is $(I|C)$, where $C=A^{-1} B$
Since $A$ is nonsingular $A*A^{-1} = I $
And if you multiply $A^{-1}$ with $B$ you get $A^{-1} B$, which is $C$
But I'm not sure if you're allowed to say $(A|B)*A^{-1} = (I|C)$
All in all, I'm quite sure this is not the right/a good proof. (I didn't incorporate that this is all about reduced row echelon forms)
If anyone can help me I'd appreciate it a lot :)
Answer: Since $A$ is nonsingular, Gaussian elimination will find a pivot in each column. Backwards elimination will get the reduced row echelon form, which is the identity.
Thus, the elementary matrices that give the RREF multiply to yield $A^{-1}$.
If $b$ is any column vector, the same Gaussian elimination steps as before on the matrix $[A\mid b]$ will produce the matrix $[I\mid c]$, where $c=A^{-1}b$, because we're essentially solving the linear system $Ax=b$.
So, if $B=[b_1\;b_2\;\dots\;b_r]$, Gaussian elimination will produce
$$
[A\mid B]=[A\mid b_1\;b_2\;\dots\;b_r]\to
[I\mid A^{-1}b_1\;A^{-1}b_2\;\dots\;A^{-1}b_r]=
[I\mid A^{-1}B]
$$


What is the most effective way to clean the rosin off the strings?

Question: When I use my bow to play double bass, there is always rosin stuck on the strings afterwards. If I leave that on the string for some time, it gets really hard to clean and the bow sticks to the strings; thus I cannot play well.
What is the most effective way to clean the rosin off the strings?
Answer: Source: I work in a music store and this is how we clean our instruments.
Getting Rosin Off

The most effective way to take rosin off of strings is to soak a cheese cloth in a little bit of nail polish remover. Afterwards, take the cloth and rub it against the string. The rosin should come off momentarily.
Get a new cheese cloth when you see that the used one has become dirty or is ripping.

Warnings

DO NOT let the cheese cloth or the nail polish remover ever touch the wood finish. It completely deteriorates it and all the lacquer comes off.
Do not inhale the nail polish remover.
Always wash your hands afterwards.
Answer: If you've got a lot of build-up, you can use an old wine bottle cork or a (not too scratchy) scouring pad to try to dislodge some of the caked-up residue. If that doesn't work, use some denatured alcohol, but carefully - don't let it drip on the varnished surfaces of the instrument.
Once it's gone, remember to give the strings a firm wipe with a soft cloth or chamois leather after each time you play - that should be enough to prevent the build-up in the first place.
Answer: What i usually use to clean the strings, is almond oil. I buy some at a pharmacy (it's pretty cheap), apply it to a cloth and then clean the strings. Afterwards, I need another cloth (or napkin) to clean the oil off the string.
This doesn't really work if the rosin is left for a long period of time on the strings. It will need much scrubbing to get it off.
Answer: Grab a guitar pick and go outside. Tighten the bow and "strum" the hair with the guitar pick. You'll see excess rosin blowing away on the wind.


Como converter uma cadeia de caracteres de apenas numerais em data?

Question: Como faço pra converter uma cadeia de caracteres de apenas numerais em data? Por exemplo, tenho uma variável com o seguinte valor "31012000" que seria referente a data 31/01/2000, porém não estou conseguindo converter esses número para data e poder trabalhar com ele como data, não como string.
Já tentei o seguinte e não deu certo:
Dim stringData as string = "31012000"

Dim dataConvertida as Date = stringData.format("dd/MM/yyyy)

Ou
Dim dataConvertida as Date = Date.Parse(stringData)

Ou
Dim dataConvertida as Date = Convert.Date(stringData)

Nenhuma dessas alternativas funcionaram.
Answer: Consegui resolver aqui, quebrei um pouco a cabeça e o que fiz foi inserir manualmente "/" para que assim a string pudesse ser atribuída a variável data sem precisar converter:
    Dim stringData As String = "31012000"
    Dim novaString As String = ""
    For Each c As String In stringData
       novaString += c
       If novaString.Length = 2 Or novaString.Length = 5 Then
       novaString += "/"
       End If
    Next
    Dim novaData as Date = novaString


Migrating database content to a new server

Question: I am moving a Drupal site onto a new server. I am using putty to scp the database onto this new server; I have not done this before, so there are things I am not sure.
There is a database called 'website' in the mysql on the server already, while my original database name is actually 'mydrupalsite'. If I just import the file mydrupalsite.sql into database 'website', and change the database name in setting.php, will that be ok?
Answer: It will be sufficient most of the time, but it is a good idea to open mydrupalsite.sql in text editor and scan it for old configurations. Especially if domain name also changes. Even if not, some modules needs may save things like local network addresses to data import sources et cetera.
And of course don't forget to truncate all cache tables and session table before data export. Best would be to disable cache and css/js aggregation on site before export, truncate tables, and re-enable these performance options on new site.
Alternatively, simply omit data from these tables when exporting with Backup and Migrate module or your favourite SQL client you use for export (for example, phpMyAdmin can do that, too). Of course disabling aggregation to have proper variables exported still needs to be done.
Safety note:
Truncating cache and session tables is only safe if you have put your site in maintenance mode. If you want to avoid it, you can't really truncate them, as they will be instantly re-populated and only effect will be performance hit and users logged out. In that case you need to omit that data, and make sure no one will change anything in the time of server switching, for the sake of consistency. Read only mode can help with that.
When talking about migration security - more modules equals more risk. My experience tells me that if your site is complicated one, you need to assume something will go wrong. So plan for it. Make sure you have time and manpower to fix it, no matter what exactly it is. Make sure you have enough old server paid for at least month after planned migration, so you can postpone and retry it. And make sure hosting company you are migrating away from will keep backups for you for at least 3 months.
Comment: @Beebee Integrated your comments into my answer
Comment: @Mołot Is it ok to truncate all the cache tables and session table before data export on production website ? will it affect anything on live site ? and also disable "cache and css/js aggregation on site before export" what is the advantage ? I'm not done like this before, Your reply will help :)
Comment: Alternatively, you could use the backup_migrate module to dump the structure for certain tables (*_cache, sessions etc) but not the data. These configurations can be saved into a backup profile and can be used again in the future to quickly dump SQL without all the junk.
Comment: @Beebee no matter the method, the point is not to have that data imported, as it can cause problems.
Comment: I get the point, that's why I'm providing an alternative method to speed this process up :)
Comment: @Bala if you are migrating, you will have a downtime, no way around it. And it is safe to do that during that downtime. I'll add some precautions to my answer.


How many 5-character passwords can be made from 5 characters with joins?

Question: Suppose a standard combination lock on a door has 5 distinct buttons (labelled e.g. 1, 2, 3, 4, 5).
A passcode is defined by 5 button presses.
Buttons can be repeated, so e.g. (5,5,5,5,5), (4,4,4,5,4), (1,2,4,3,5) are all valid passcodes.
The deluxe version of the lock allows "joins".  A join is when two distinct buttons are pressed at the same time, so for example the four following codes are all valid and distinct:

(1, 2, 3, 4+5),
(1, 2+3, 4+5),
(1, 2+3, 4, 5), and
(1, 2, 3, 4, 5).

How many passcodes are possible in the standard and deluxe locks?
My attempt:
Standard lock: You can choose any character 5 times, so there are $5^5 = 3125$ standard passcodes.
Deluxe lock: Deluxe lock codes have either 0, 1, or 2 joins.
The 0-join codes are the 3125 for the standard lock.
The 1-join codes can have a join in one of four positions (between characters 1&2, 2&3, 3&4, 4&5).  Having one join only constrains one of the characters (it has to be different to the character preceeding it).  So for each of the four 1-join-positions, there are $5^4 \times 4$ choices of codes, so there are $5^4 \times 4^2 = 10000$ 1-join codes.
The 2-join codes must either be between characters 1&2 and 3&4, or 1&2 and 4&5, or 2&3 and 3&4. Having 2 joins constrains each of two of the characters to be different to the character preceeding it.  So for each of the three 2-join-positions, there are $5^3 \times 4^2$ choices of codes, so there are $5^3 \times 4^2 \times 3= 6000$ 2-join codes.
So, all in all there are $3125 + 10000 + 6000 = 19125$ codes in the deluxe lock.
Comment: Your answer is correct
Answer: If $1-2$ is the same as $2-1$, there are only $5^3*10*4=5000$ 1-join codes.
Comment: Thanks.  Is the total therefore 3125 + 5000 + 6000/4 = 9625?
Comment: I think so, yes.


Zero conditional mean assumption

Question: How can I check the zero conditional mean assumption for a multiple linear regression? I read that when the assumption is violated, your model is misspecified. And your estimators are biased. So we need to check for it, but I'm completely oblivious as to how this is done.
Answer: Edit: I assume you mean the conditional mean of the errors is zero.
Imagine if the errors had a common nonzero mean - $\mu_\varepsilon$, say, and you fitted a least square model. What would happen? It would be absorbed by the constant, and the residuals would on average be zero. So you can't test whether the residuals have a common mean that's not zero.
What you can check is whether the residuals (and by implication the errors that they estimate) have constant mean; on average they're still zero, but conditionally they may have means some distance from zero.
The usual way to check that is a plot of residuals against the predictor(s), or if there are more than a couple of predictors, at least against fitted values. Here's the first diagnostic plot of the ones R will give by default when you plot the result of a regression:
<code>plot(lm(dist~speed,data=cars))
</code>

It has a loess smooth superimposed, but without the curve you can still discern that the points tend to sit above the zero line at each end and perhaps below it in the middle.
You can immediately see that the linearity assumption is somewhat suspect, and that perhaps some curved relationship is present.
Comment: If common non-zero mean $\mu_{\epsilon}$ is absorbed by the constant , then why would residuals on an average zero ?
Comment: @abc the sum of the residuals is always 0 in OLS with an intercept, hence so is the mean
Comment: and without an intercept, you can just calculate the residual mean to see how large it is?
Answer: In addition to what @glen_b said, there is a test for missspecifications (in fact there are many) one well known is the Ramsey RESET test.
Run the original model, and obtain the fitted values. Add them along with fitted values squared and cubed to original model and test for joint significance (f-test). If you reject it implies you have neglected no linearity (specification problem).
No test can tell you what to do, and even if you do not reject the null there are no guarantees.
Also another important problem is omitted variables, in fact this is even more of a problem since there is no test (you cannot test what you do not observe). Basiaclly it comes down intuition. Unless you have data from an experiment, it will almost always be the case that you have omitted variable bias, and that you model is biased since the mean independence assumption hinges of this.
Answer: Test the model without constant. If the resulted equation has beta, r-squared and adjusted r-squared similar to those from the initially chosen model (i.e. model with constant) this means that the model has 0 mean error. If not, means not. (Brooks, Introductory Econometrics, page 131)

Zero conditional mean assumption


How to prove inequality with stricly increasing concave function?

Question: I have following inequality I need to prove: $$\frac{x_i +x_j}{x_i}>\frac{u(R)}{u(R\frac{x_i}{x_i +x_j})}$$We have that $x_i,x_j,R>0$ as well as $u$ being an strictly increasing concave function in the respective interval.
Answer: If $u\colon [0,+\infty) \to \mathbb{R}$ is a concave function, with $u(0) \geq 0$, then, setting $\mu := x_i/(x_i+x_j) \in (0,1)$,
$$
u(\mu R) = u ((1-\mu) 0 + \mu R) \geq
(1-\mu) u(0) + \mu u(R) \geq \mu \, u(R).
$$
If $u$ is strictly concave, the inequality is strict, i.e. $u(\mu R) > \mu u(R)$.
In addition, if $u$ is positive, then the above inequality gives the required one.


2D array of pointers or heap objects

Question: I've got a game that has a grid, which is a 2D array. This array is filled with a struct of information.
struct GridCell
{
    uint mCellID;
    Vector2 mPosition;
    uint mLevel;
    int mCellType;
};

class Grid
{
public:
    Grid();
    ~Grid()

protected:
    // Heap
    GridCell[][] mGridCells;

    // Dynamic
    GridCell*[][] mGridCells;
};

Keeping in mind that there can be many Grids in memory at once, and that those gridcell can range from very small to very large:
Is this better suited to be a heap of gridcells or dynamic (pointer) gridcells?
From what I understand:
Heap cells will take up a large chunk of memory
Dynamic cells still will, but it will be of pointers, not the entire struct. However, this could lead to fragmented memory?
I'm not sure of which one is the best for this scenario, and I probably don't fully understand the differences between the two either. Help?
Answer: Types in C++ have a fixed size. It's not true that your GridCells will range from very small to very large. They'll be one or the other. sizeof(GridCell) is fixed. They might each point to objects of different sizes, but those objects are not part of the size of the GridCell.
Either way, both methods you propose will have exactly the same amount of GridCells in memory, so you save nothing by using pointers. In fact, the dynamically allocated approach will use more memory because you're also storing pointers to each cell. The only way the pointer approach could be more memory efficient is if you used single GridCell objects to represent more than one cell in the Grid. That is, some of the pointers would be the same.
What this really comes down to is which one is more manageable and the answer is always "the method without the pointers". It means your Grid objects will automatically manage the construction and destruction of the GridCells without you having to care about it, helping you avoid memory leaks. If you use the pointer method, you will have to loop through your arrays in the constructor of Grid, doing new GridCell() for each element. You'll also need to do the same in the destructor, doing delete on each cell you dynamically allocated. This is a pain, especially when it's unnecessary.
In the cases where pointers are required, smart pointers are much more preferable.
Furthermore, you may even be better off using a std::array<std::array<GridCell, N> M> for your fixed sized arrays. It encapsulates the array for you, allowing you to use it as you would any other Container from the standard library.
Answer: It would be better to use neither and use std::vector. Make your 2d arrays 1d and store the values straight into a vector. Or if you really must have 2 dimensional you can create a vector of vectors.
Comment: It may not be a concern here, but it is useful to note that a vector of vectors can lead to horrible performance if they grow large enough and need to be iterated relatively frequented.  Locality of data is likely to be horrible.  A better alternative then would be a large vector and manually calculating the offset to sub "arrays".

2D array of pointers or heap objects


Automatically finding starting values for a sigmoid curve

Question: I have ~10.000 of vectors and I want to fit a sigmoid curve to each of them; in each case, I need to define starting parameters for fitting, so I want to find these parameters automatically. On stackexchange, there are discussed strategies of automatically finding starting values for non-linear models (one,two), but these discussions consider some specific cases such as fitting a gaussian. Are there general stratagies which can be applied to sigmoid curve too?
Comment: You've left some useful information out, e.g., is there a unit of time or frame associated with these ~10,000 vectors? Next, there are lots of ways to fit a sigmoid or diffusion curve to this information. Regrettably, most of the extant models assume a univariate time series for the underlying process. Are these vectors iid? Or can they be related to one another in some sort of panel data structure? If the latter, then there are options beyond fitting ~10,000 univariate "models."
Answer: First I will say that it can be dangerous to assume a large number of unseen data sets have some particular parametric form (e.g. logistic), unless there are very particular constraints on the data (i.e. inherent to the data generation process).
That said, assuming you have a set of 2D points that are "approximately logistic"
$$y\approx A+B\frac{1}{1+\exp\left[-\left(ax+b\right)\right]}\equiv f[x]$$
then to estimate the 4 parameters $a,b,A,B$ a simple approach might be a two-step process like the following. (For simplicity I will assume all parameters are positive.)
The idea is that the logistic curve has a middle "linear" section connecting left and right "flat" sections. A robust procedure would really need to consider which of these are present in the data ... but for simplicity let's say all 3 are always present.
First you must estimate the asymptotes, which can be done as
$$f[-\infty]=A\approx{y_\min} \text{ , } f[\infty]=A+B\approx{y_\max}$$
(again ignoring robustness here ... really the $y$ data could fluctuate around the asymptotes, even if both are present).
Second, compute the "normalized data"
$$z\equiv\frac{y-A}{B}$$
where $z\in[0,1]$ if using the estimates above. Then subsample all points with $z\in(0,1)$, i.e. exclude the endpoints (for robustness a tolerance could be used here perhaps). For these points you can estimate $a,b$ with a simply linear fit
$$\mathrm{logit}[z]\approx ax+b$$
where logit is the inverse logistic function.
This would give rough estimates for $a,b,A,B$ that could be used to initialize your nonlinear optimization.

Update: I would add that it seems likely that your 10,000 curves are somewhat related. If this is the case, then it would be better to estimate initial parameters in "batch" if possible.
For example, if the asymptotic limits are roughly constant between different curves, then you could estimate $A$ and $B$ more robustly. I would probably try something like using the mean of the upper and lower 5% of the combined $y$ data.
This would allow you to account for instances where some curves do not contain both asymptotes. Then for each curve you can estimate the initial $a,b$ as above, using a logit-linear fit to points between the asymptotes.


Exibir texto vindo consulta a banco em @Html.Actionlink()

Question: Bem, tenho o seguinte cenário:
Faço uma consulta no banco de dados e trago um IEnumerable<> para a View:

        @foreach (var item in Model)
        {

@Html.ActionLink(item.Titulo, "MostraPublicacao", "Publicacao", new { id = item.PublicacaoId })

                        @Html.DisplayFor(model => item.Resumo);

        }

Sendo assim, o meu TITTULO é recebido por esta linha
@Html.DisplayFor(model => item.Resumo);

Preciso exibir o texto do resumo em um @Html.ActionLink() para ser um link afim de redirecionar para uma outra View, que receberá o ID deste Objeto como parâmetro
Uma imagem para tentar ilustrar melhor o problema:

Como resolvo este problema ?
Answer: No lugar do @Html.DisplayFor(model => item.Resumo) apenas altere para algo como:
@Html.ActionLin(item.resumo, "ACTION", "CONTROLLER", new{id = item.PUBLICACAOID})
Desta forma, o texto será o resumo, mas o HTML gerado será algo como:
 @item.titulo


How much is the probability of $\cos x \cos(4-x)<0$ for $0<x<4$?

Question: I have this function
$$f(x)=g(x)h(x)=\cos x \cos(4-x)$$
How much is the probability of $f(x)<0$ for $0<x<4$?
Comment: You mean $x$ is chosen uniformly over the interval?
Comment: @ParclyTaxel YES
Answer: The rest of the answer assumes that $x$ is chosen uniformly over $[0,4]$.
$$\cos x\cos (4-x) > 0$$ for $$x\in \left(\frac{\pi}{2}, 4-\frac{\pi}{2}\right)$$
on $[0,4]$.
So the probability you require is $$1 - \frac{4-\pi}{4} = \frac{\pi}{4}\approx 0.785$$
For reference, here is the graph on $[0,4]$ -
Comment: Nope! The function you mention is always positive. In fact after a little simplification you'll see that it is $\sin ^2(\frac{3x}{2})$. The required probability is thus, zero.
Comment: @ strawberry-sunshine Thank you very much.


Simple integration

Question: I'm currently learning calc 2 and feel I'm making a very silly, obvious mistake with solving the integral $\int\frac{-5\sqrt[3]{x^2}}3 dx$
I guess I'm making an algebraic mistake somewhere, this is how I went about solving it:
$$\int\frac{-5x^\frac{7}3}3 dx$$
$$\int-5x^\frac{-2}3 dx$$
$$\frac{-5x^\frac{1}3}{\frac13} = -15x^\frac{1}3 + C$$
But the actual answer is $-x^\frac{5}3$ + C
Comment: $\root 3\of {x^2}=(x^2)^{1/3}=x^{2\cdot {1\over 3}}=x^{2/3}$.
Comment: Also, you can move constants to the outside of the integral e.g. $\int-\frac{5}{3}x\,\mathrm{d}x=-\frac{5}{3}\int x \,\mathrm{d}x$
Answer: $$\int \frac{-5x^{\frac{2}{3}}}{3}dx=-\frac{5}{3} \int x^{\frac{2}{3}} dx=-\frac{5}{3} \cdot \frac{3}{5} x^{\frac{5}{3}}+c=-x^{\frac{5}{3}}+c$$
Answer: $$\int\frac{-5\sqrt[3]{x^2}}3 dx=\frac{-5}3\int{\sqrt[3]{x^2}} dx=\frac{-5}3 \int{x^\color{red}{\frac23}}=\frac{-5}3\cdot \frac35 x^\frac53+C=-x^\frac53+C$$
You incorrectly evaluated $\sqrt[3]{x^2}$, the correct one is in $\color{red}{red}$.

Simple integration


Is A Simplex Method Appropriate for Solving Nash Equilibria?

Question: I've been attempting to teach myself some game theory and in the process, some linear programming.
While muddling through this, I've been attempting to use a variety of simplex methods to attempt to find mixed-strategy Nash equilibria in zero-sum games.
Unfortunately, most of my computations end up with incomplete, or seemingly wrong answers.
Is the simplex method (or two-phase, or dual simplex) appropriate for attempting to find mixed-strategy Nash equilibria, and if so, what is the proper way to set up the starting tableaux?
I've attempting starting with something like this (example is RPS):
\begin{bmatrix}0 & 0 & 0 & -1 & -1 & 0\\1 & 1 & 1 & 0 & 1 & 1\\0.5 & 0 & 1 & 1 & 0 & 0.5\\1 & 0.5 & 0 & 1 & 0 & 0.5\\0 & 1 & 0.5 & 1 & 0 & 0.5\end{bmatrix}
or
\begin{bmatrix}0 & 0 & 0 & -1 & -1 & -1 & -1 & 0\\1 & 1 & 1 & 1 & 0 & 0 & 0 & 1\\0.5 & 0 & 1 & 0 & 1 & 0 &0 & 0.5\\1 & 0.5 & 0 & 0 & 0 & 1 & 0 & 0.5\\0 & 1 & 0.5 & 0 & 0 & 0 & 1 & 0.5\end{bmatrix}
or
\begin{bmatrix}0 & 0 & 0 & 0 & -1 & -1 & -1 & 0\\0 & 0 & 0 & -1 & 0 & 0 & 0 & 0\\1 & 1 & 1 & 1 & 0 & 0 & 0 & 1\\0.5 & 0 & 1 & 0 & 1 & 0 &0 & 0.5\\1 & 0.5 & 0 & 0 & 0 & 1 & 0 & 0.5\\0 & 1 & 0.5 & 0 & 0 & 0 & 1 & 0.5\end{bmatrix}
And this seems simple enough to solve, but anything more complex, or examples with dominated strategies often seem to be unsolveable.
Answer: Do you mean in finite games? If so, since otherwise it is hopeless, as far as I understand computing all equilibria is a hard problem. There is couple of good surveys here and here, recent handbook chapter and you might be interested in Gambit..
Comment: As I understand it, yes I am solely looking at finite games. Simple selection strategies like RPS or fighting game character selections based on matchup win rates.
Comment: I've seen a couple of those linked articles before. Most mention the Lemke-Howson algorithm. That seems to be the standard, however I approached this with the simplex algorithm first as it seemed simpler to learn and apply.

To the point of my question - is there a way to apply the simplex method to these sorts of problems (if so, what?), or should I just move on and begin learning Lemke-Howson?
Comment: I never thought about using simplex method in this context. To derive what, the best response? Then I guess you probably can. But I am not an expert here. On the other hand if some method is recurring in the literature, there is probably a reason for it.
Comment: I recommend looking at Dorfman, Samuelson and Solow, Linear Programming and Economic Analysis (also known as DOSSO). Chapter 16 is Interrelations between Linear Programming and Game Theory and tells how to convert games into linear programming problems, and vice versa.
Comment: This book? https://www.amazon.com/Programming-Economic-Analysis-Computer-Science/dp/0486654915
Comment: One word of caution: linear programming (LP) works a charm for zero-sum games. In the 50s, most literature connecting LP and games was based on the special case of (finite) zero-sum games.
Comment: That is the main use-case I'm looking at right now, However, if I wanted to do something with non-zero-sum games, or non-finite games, what would I look towards?