Is there such a thing as a minor blues scale?

Question: I have learned the Blues scale as 1, b3, 4, b5, 5, b7.
I'm looking at a chart "Stolen Moments" (in the RealBook) and it says to solo on C Minor Blues.
Is the minor blues the same as the Blues as I've described above?
So the notes would be:
C, Eb, F, Gb, G, Bb, C
Or is there a minor version of this scale?
Comment: That's the common minor blues scale. For reference, the major blues would be 1, 2, b3, 3, 5, 6.
Comment: That IS the minor version!
Answer: Officially, yes. It gets credence as it features in some music exams. Cm blues scale contains the notes C E♭ F G♭ G and B♭
That ♭5 is better known in jazz circles as ♯4, but for all intents and purposes it sounds like the same note.
I think the problem arises because the Blues often gets to be played with other notes - notably those of the major Blues scale. And, of course, several micro notes which appear mainly on guitar or sax that cannot be defined using 12tet.
So, to pigeon-hole it, we can say it contains only the notes first quoted.
Comment: In a run up the scale, I'd much prefer it notated as F♯ rather than G♭ to avoid writing G♮ for the 5th degree. Depends on context, obviously.
Comment: @user45266 - 99% of the time, that note is played in real music, rather than as part of a scale. It's only the academic side that somehow needs to pigeon-hole it. More often than not, when I play the note, I don't even give it a consideration as far as what it might be called! And if it's blues or jazz, I feel the players will think likewise.
Comment: Doesn't #4 make more sense functionally?
Comment: @MCMastery - not particularly. There's a b3, b5 and b7. Although jazzers seem to prefer #4.
Answer: The problem is that the term "Blues Scale" is used in more than one context.
Some sources quote the "Blues scale" as the Major pentatonic with a b3 added while other simply equate Blues with the scale you have given above, minor pentatonic with a #4.
In the context you have provided I think the scale you have described is the minor Blues scale.
Answer: When musicians talk about the "blues scale", they could mean either the major blues scale or the minor blues scale. Starting on C, C D D♯(E♭) E G A is the major blues scale, and C E♭ F F♯(G♭) G B♭ is the minor blues scale. Note that both are modifications of their respective pentatonic scales, with one note added in.
As for why the minor blues scale sometimes gets called "the blues scale", that's probably because it can be played over both major and minor blues songs, whereas playing the major blues scale over a minor blues song sounds unidiomatic to the blues genre.
Comment: I wish I could mark two answers as correct, as I also like this answer.  Thank you!


Sharing system to my remote friend via Internet

Question: I have my system created by using PHP, MySQLi, HTML, CSS and JavaScript and  installed it in a localhost XAMPP sever.
I need to share my system via the Internet to my friends. I have no domain name or other online server.
What can I do for free to complete sharing of my system?
Comment: You're going to have a hard time routing anything to a device on your home network without a static IP address, which is not something that is typically included for household internet packages.
Answer: You can use ngrok ( https://ngrok.com/ ) to create a tunnel to your localhost. After you install the package You can run ./ngrok http port, like, ./ngrok http 8080 and you would get a url which you can share with the world.
like this:

http://ec13044d.ngrok.io -> localhost:8080

However, you need to create an account at Ngrok [and select Free plan].


AnguarJS Routing Not Working As Expected

Question: I have a listing of blog posts and I want to be able to click on the title and have it dynamically redirect to the proper posting.
So far it works except when I click on the anchor tagged title it redirects to:
blog/#/post/:post

rather than
blog#/post/:post

I've tried to change the href to data-ng-href,
using target="_self"
and tried changing the href="#/post/{{post}}" and href="/post/{{post}}"
Routes:
(function(){

    'use strict';

    angular.module('ghpg')
    .config(Config);

    Config.$inject = ['$routeProvider'];

    function Config($routeProvider){

        $routeProvider
            .when('/listing', {
                templateUrl: '/angular/views/listing.client.view.html'
            }).otherwise({
                redirectTo:'/'
            }).when('/post/:title',{
                templateUrl: '/angular/views/post.client.view.html',
                controller: 'postController',
                controllerAs: 'post'
            }).otherwise({
                redirectTo:'/listing'
            });

    }

})();

Listing View:
    (function(){

    'use strict';

    angular
    .module('ghpg')
    .controller('listingController', listingController);

    listingController.$inject = ['$scope', 'blogContent'];//,'blogContent'] //, 'blogContent'];

    ////

    function listingController($scope,  blogContent){
        var vm = this;
        vm.articles = [];
        grabData();

        function grabData(){
            return blogContent.getContent().then(function(data){
                    console.log(data.articles);
                    vm.articles = data.articles;
                    return vm.articles;
                    },function(err){
                console.log(err);
                vm.data = [];

                });
        }

    }

})();

App.js:
(function(){

    'use strict';

    var dependencies = [
        'ghpg',
        'ngRoute'

    ];

    angular.module('blogger', dependencies)
    .config(Config);

    Config.$inject = ['$locationProvider']

    function Config($locationProvider){

        $locationProvider.hashPrefix('!');

    }

    if (window.location.hash === '#_=_'){
        window.location.hash = '#!';

    }

    //bootstrap angular

    angular.element(document).ready(function(){

        angular.bootstrap(document, ['ghpg']);

    });

})();

LISTING VIEW:

 Listings

 {{ post.title  }}

{{ post.date }}

"> {{ post.content }}

Having trouble where I went wrong. I strongly suspect that it's some small typo or something with my SPA location/locationProvider in app.js but it looks the same in my other apps, unless my eyes are fooling me (which could be totally happening!)
Answer: What I did for a fix was simply this:
changed the listing view's anchor:

 {{ post.title  }}

to include the /blog# portion in the href so that I have:

 {{ post.title  }}

Simple fix, cause only the blog portion or webpage of my website is the angularJS, everything else is not so the routing was not being called to route it until it saw /blog# as part of the app.


Nginx rewrite issue

Question: I would like a particular configuration for one of my virtual servers but I have a problem explaining that to Nginx :)
Its quite simple. If the URI looks like
example.com/whatever_1/whatever_2/.../whatever_n

I would like to rewrite it as
example.com/index.php?request=whatever_1/whatever_2/.../whatever_n

The second is if the URI begins with /administration/ like
example.com/administration/whatever_1/.../whatever_n

I would like it to be rewritten as
example.com/administration/index.php?request=whatever_1/.../whatever_n

I was tinkering arround and tried:
server
{
#   listen 80;
    server_name example.com;
    index index.html index.php;
    root /srv/example/;

    location ~ /administration/(.*)$
    {
        if (!-e $request_filename)
        {
            rewrite ^/(.*)$ /administration/index.php?request=$1 last;
        }
        break; #tried with and without it
    }

    location / #tried with and without this location block
    {
        if (!-e $request_filename)
        {
            #rewrite ^/(.*)$ /index.php?/$1 last;
            rewrite ^/(.*)$ /index.php?request=$1 last;
        }
    }

    location ~ \.php$ #boilerplate
        {
                # Filter out arbitrary code execution
                fastcgi_index index.php;
                include fastcgi_params;
                fastcgi_pass  unix:/var/run/php5-fpm.sock;
        }
}

But this does not work. Im quite new to Nginx so any help would be appreciated.
Thanks, Jan.
Comment: http://nginx.org/r/try_files
Answer: This is nginx, not apache. You should avoid rewrites when possible (and it often is possible).
Use try_files instead. For example:
location /administration/ {
    try_files $uri $uri/ /administration/index.php?request=$request_uri;
}

location / {
    try_files $uri $uri/ /index.php?request=$request_uri;
}

Comment: Thank you. May I ask why should I avoid rewrites?
Comment: Rewrites are slow, and there's usually a faster alternative (such as `return` or `try_files`). And rewrites are often combined with `if` which, while it's valid to do so, can lead to problems (since [`if` is evil](http://wiki.nginx.org/IfIsEvil)).

Nginx rewrite issue


The trace-determinant plane, classification of equilibria of differential equations

Question: What are some easy ways to remember each of the different behaviors of general solutions of ordinary differential equations in the trace-determinant plane? For differential equations of the form $\frac{dY}{dt} = AY$ where $A$ is a $2 \times 2$-matrix and $Y$ is the column vector $(x\ y)$.
Comment: Just think first about whether the roots are real or complex (to do this, think about the discriminant of the characteristic polynomial, using the trace and determinant), and then think about the signs of the real parts.
Answer: Stable solutions only occur when the trace $\tau \leq 0$ and the determinant $\Delta>0$.
So saddles occur when $\Delta<0$, and the non-isolated fixed points whenever $\Delta=0$ (the borderline).
When $\Delta>0$ the centers (these should seem interesting) occur at $\tau=0$.
After that, for $\Delta>0$, just try to recognize the symmetry of stability reversal on either side of the $\tau=0$ line. For example as you go away from the centers, you get spirals, then the borderline stars and degenerate nodes on the $\tau^2-4\Delta=0$ curve, and then the nodes.
I think I accidentally memorized this plane by solving examples of every type of equation that could possibly happen. Very useful for stability analysis by eye!
Comment: If you have access to *Mathematica*, I made a really cool manipulator that is fun to play with. You can see all (including eigenvalues) as you drag the 4 matrix values. I would only add it to this post if you wanted and could actually use it. Sometimes playing helps too eh.
Answer: There are a few concepts to consider:
First of all you need to rebember that these such systems can be solved by writing down the eigenvalues (and theirs eingenvectors) to the plane, the eingenvectors show the diretion of expansion (or retraction) of the system, while the signal of the eingenvalues decide if it is a retraction or a expansion.
I usually reccor to these materials every time I need to remember these concepts in a quick way:
Youtube ODE ovewview
Trace-determinant plane
PS.: Without time to go deeper in this issue, I should came back to review in a feew weeks years.
Answer: I find the below caption for the trace-determinant plane a good reminder (this is taken from Hirsch, Smale and Devaney's Differential Equations, Dynamical Systems, and an Introduction to Chaos (3e, p.64)):


No such property: variantConfiguration for class:

Question: After upgrading gradle 4.0.0 app build failed with error message:
No such property: variantConfiguration for class: com.android.build.gradle.internal.variant.ApplicationVariantData
is there any way to migrate gradle ?
android.applicationVariants.all { variant ->
        variant.outputs.all {
            def buildType = variant.variantData.variantConfiguration.buildType.name
            ...

        }
    }

app level gradle file
dependencies {
        classpath 'com.android.tools.build:gradle:4.0.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }

Answer: In the last gradle Relase ApplicationVariant implement BaseVariant
Instead of
def buildType = variant.variantData.variantConfiguration.buildType.name

Should be
def buildType = variant.buildType.name

Comment: Updating this property signed APK signature mismatched. Did anyone encounter this problem?


How can I test whether one empirical CDF is to the left or right of another?

Question: I am currently working with a box plot (shown below) that consists of two boxes per value of one of the independent variables (call it $x$). The other independent variable is indicated by the two boxes (call it $y$). The blue box represents the dependent variable (call it $z$) under the condition $y = 1$, while the red box represents $z$ under the condition $y = 2$. The bottom and top whiskers represent the 10th and 90th percentiles respectively, while the bottom and top edges of a box represent the 25th and 75th percentiles respectively. The median is marked in black.
My hypothesis is that, when $y = 1$ (blue box), the empirical CDF of $z$ is to the right of the empirical CDF of $z$ when $y = 2$ (red box) "in general" (on average or otherwise) for every value of $x$. This relationship (although not particularly strong) can be seen in the plot below. However, I am not sure how to phrase this precisely in terms of a statistical test.
One possibility that I thought of was to use a two-sample Kolmogorov-Smirnov test for each value of $x$, but I am not sure how helpful this would be. Another possibility, is that, because the data was generated in pairs, i.e., one specific value of $z$ when $y = 1$ can be matched to another specific value of $z$ when $y = 2$, then I should subtract the value of $z$ when $y = 2$ from the corresponding value of $z$ when $y = 1$, and then check that the values are always (or mostly) positive. Any suggestions would be appreciated.
Answer: Maybe you're interested in whether sample y
stochastically dominates sample x. If so,
you might want to look directly at ECDF plots, and do some formal tests.
Here are summaries and ECDF plots of two samples.
summary(x); length(x);  sd(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  5.067  14.628  21.012  21.807  28.297  53.943
[1] 30        # sample size
[1] 10.56207  # sample SD

summary(y); length(y);  sd(y)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  12.81   25.30   29.27   29.25   32.56   45.47
[1] 30
[1] 8.098928

plot(ecdf(x), col="blue", main="ECDFs", xlab="values")
lines(ecdf(y), col="brown")

Because the ECDF of y (brown) plots to the right of
the ECDF of x (blue), and therefore below, it seems
the values of y are generally larger than
values of x
A two-sample Kolmogorov-Smirnov test confirms this
with a P-value below 5%. The test statistic $D$
is the maximum vertical distance between the two
ECDF plots.
ks.test(x,y)

        Two-sample Kolmogorov-Smirnov test

data:  x and y
D = 0.43333, p-value = 0.006548
alternative hypothesis: two-sided

When two samples are not of the same shape (including the same variability), a two-sample
Wilcoxon Rank Sum test, is said to be a test
of stochastic dominance (rather than of different
medians).
boxplot(x, y, horizontal=T, col=c("skyblue2", "wheat"))

wilcox.test(x,y)

        Wilcoxon rank sum test

data:  x and y
W = 236, p-value = 0.001292
alternative hypothesis:
 true location shift is not equal to 0

Notes: (1) Technically speaking, there are several
different types of 'stochastic dominance' with
somewhat different definitions. You may be interested in googling that. Perhaps start here.
(2) The fictitious samples used in the above
discussion were sampled in R as follows:
set.seed(2022)
x = rgamma(30, 4, 1/5)
y = rgamma(30, 5, 1/5) + 7


how to change the javascript version in firefox browser

Question: help -> about firefox shows firefox version 63.0(32 bit)
but my javascript version shows 1.5
http://jsfiddle.net/Ac6CT/

I want to use the latest javascript version.
Comment: the `language` attribute on a script element is deprecated - so your code is flawed - javascript on Mozilla supports 98% of ES6, 100% of ES2016, most of ES2017 and 2018
Answer: I assume you read one of the answers over here: stackoverflow.com/questions/4271566, since it matches your code exactly. That answer is 8 years old and out of date. Seeing "1.5" is the expected behavior in the latest version of Firefox.
You can prove this by using a newer feature. For example,
const x = 5
x --> 5

The const feature was added since "Javascript 1.5," so this serves as evidence for my above claim.
Comment: You should not rely on the version number, and instead try to determine whether a specific feature is available. This is because browsers don't always implement every feature, even if they implement most.
Comment: yes i can use let also, but want to know the version


JFreechart com valores Dinâmicos

Question: Venho enfrentando dificuldades na criação de um gráfico em linha que seja dinâmico, obtive algum "progresso" porém agora ele me acusa um erro: Exception in thread "main" org.jfree.data.UnknownKeyException: Unrecognised columnKey: 10/17. A ideia do gráfico é, ele pega todos os valores de uma lista e soma separando-os por mês no formato MM/yy. Pelo que li a respeito o JFreechar já realiza essa soma e a separação no estilo de gráfico que estou montando, contudo posso estar enganado.
Exemplo minimo verificável
import java.awt.Color;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.LineBorder;
import javax.swing.table.AbstractTableModel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

public class ExemploMinimo
{
    public class Request implements Serializable
    {
        /**
         *
         */
        private static final long serialVersionUID = 1L;
        private Date registrationDate;
        private String noteTotal;

        public Date getRegistrationDate()
        {
            return registrationDate;
        }

        public void setRegistrationDate(Date registrationDate)
        {
            this.registrationDate = registrationDate;
        }

        public String getNoteTotal()
        {
            return noteTotal;
        }

        public void setNoteTotal(String noteTotal)
        {
            this.noteTotal = noteTotal;
        }
    }

    // ----------------------------------------------------------------------------------------
    public interface Dao<R>
    {
        public List<R> searchAll() throws Exception;
    }

    // ----------------------------------------------------------------------------------------
    public class ModelTableRequestRoute extends AbstractTableModel
    {
        /**
         *
         */
        private static final long serialVersionUID = 1L;
        private List<Request> request = new ArrayList<>();
        private SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

        public ModelTableRequestRoute(List<Request> list)
        {
            request = list;
        }

        @Override
        public String getColumnName(int column)
        {
            switch (column)
            {
                case 0:
                    return "data";
                case 1:
                    return "valor";
            }
            return super.getColumnName(column);
        }

        @Override
        public int getColumnCount()
        {
            return 2;
        }

        @Override
        public int getRowCount()
        {
            return request.size();
        }

        @Override
        public Object getValueAt(int row, int column)
        {
            Request r = request.get(row);
            switch (column)
            {
                case 0:
                    return dateFormat.format(r.getRegistrationDate());
                case 1:
                    return r.getNoteTotal();
                default:
                    return null;
            }
        }

    }

    // ----------------------------------------------------------------------------------------

    public class FrameMinimo extends JFrame
    {
        /**
         *
         */
        private static final long serialVersionUID = 4320341978109746731L;

        private List<Request> requestList = new ArrayList<>();

        private JPanel tablePanel;
        private JPanel graphicPanel;

        private Date currentDate = new Date();

        private JTable table;
        private JScrollPane scroll;

        public FrameMinimo()
        {
            inicializarComponentes();
            inicializarEventos();

            Request r = new Request();
            r.registrationDate = currentDate;
            r.noteTotal = "3000.00";
            requestList.add(r);

            ContruirTabela();
            construirGraficos();
        }

        private void inicializarComponentes()
        {
            setTitle("Exemplo Minimo");
            setSize(1150, 637);
            setLocationRelativeTo(null);
            setResizable(false);
            setLayout(null);
            setDefaultCloseOperation(EXIT_ON_CLOSE);

            // Table panel
            tablePanel = new JPanel();
            tablePanel.setSize(400, 402);
            tablePanel.setLocation(3, 3);
            tablePanel.setLayout(null);
            tablePanel.setBackground(Color.WHITE);
            tablePanel.setBorder(new LineBorder(Color.BLACK));
            add(tablePanel);

            // Table
            table = new JTable();
            scroll = new JScrollPane(table);
            scroll.setFont(getFont());
            scroll.setBorder(new LineBorder(Color.BLACK));
            scroll.setLocation(3, 3);
            scroll.setSize(394, 395);
            scroll.getViewport().setBackground(Color.WHITE);
            tablePanel.add(scroll);

            // Graphic panel
            graphicPanel = new JPanel();
            graphicPanel.setSize(737, 603);
            graphicPanel.setLocation(tablePanel.getX() + tablePanel.getWidth() + 1, 3);
            graphicPanel.setLayout(null);
            graphicPanel.setBackground(Color.WHITE);
            graphicPanel.setBorder(new LineBorder(Color.BLACK));
            add(graphicPanel);
        }

        private void ContruirTabela()
        {
            ModelTableRequestRoute modelTableRequestRoute = new ModelTableRequestRoute(requestList);
            table.setModel(modelTableRequestRoute);
        }

        private void construirGraficos()
        {
            // FIXME Create data set with list values
            DefaultCategoryDataset ds = new DefaultCategoryDataset();
            for (Request request : requestList)
            {
                ds.getValue(new Double(request.getNoteTotal().replace(".", "").replace(",", ".")),
                        new SimpleDateFormat("MM/yy").format(request.getRegistrationDate()));
            }

            // Create chart
            JFreeChart chart = ChartFactory.createLineChart("Vendas por Rota", "Mês", "Valor", ds, PlotOrientation.VERTICAL, true, true,
                    false);

            // Chart properties
            CategoryPlot plot = chart.getCategoryPlot();
            plot.setBackgroundPaint(Color.WHITE);
            plot.setRangeGridlinePaint(Color.GRAY);

            ChartPanel cp = new ChartPanel(chart);
            cp.setSize(730, 550);
            cp.setLocation(3, 3);
            cp.setVisible(true);
            graphicPanel.add(cp);
            graphicPanel.repaint();
        }

        private void inicializarEventos()
        {

        }
    }

    public static void main(String[] args)
    {
        ExemploMinimo e = new ExemploMinimo();
        FrameMinimo fm = e.new FrameMinimo();
        fm.setVisible(true);
    }
}

Comment: Você já não fez essa pergunta? https://pt.stackoverflow.com/questions/244292/jfreechart-jtable
Comment: Não, ela está diferente, agora é outro problema. Eu achei um lógica para atribuir os valores dentro do gráfico, mas agora ele me informa um erro
Comment: Pra mim parece ser o mesmo problema.
Comment: Não, pois agora é esse erro: Exception in thread "main" org.jfree.data.UnknownKeyException: Unrecognised columnKey: 10/17. Achei melhor abrir outra questão, pois aquele post era sobre uma duvida de lógica, este já é um problema concreto com um erro
Answer: Depois de muito pesquisar encontrei a solução adequada para meu problema. Ainda estou estudando mais o código, mas por hora foi o que me gerou o resultado esperado
 DefaultCategoryDataset ds = new DefaultCategoryDataset();
            Map<String, Double> map = new HashMap<>();

            for (Request request : requestListForClient)
            {
                Double total = new Double(request.getNoteTotal().replaceAll(",", "."));
                String month = new SimpleDateFormat("MM/yy").format(request.getRegistrationDate());

                if (map.containsKey(month))
                {
                    Double totalMonth = map.get(month);
                    map.put(month, (totalMonth + total));
                }
                else
                {
                    map.put(month, total);
                }
            }

            for (Map.Entry<String, Double> entry : map.entrySet())
            {
                String month = entry.getKey();
                Double total = entry.getValue();

                ds.addValue(total, "Valor do Mês/Ano", month);
            }

            // Create chart
            JFreeChart chart = ChartFactory.createLineChart("Vendas por Cliente", "Mês/Ano", "Valor (R$)", ds, PlotOrientation.VERTICAL,
                    true, true, false);

            // Chart properties
            CategoryPlot plot = chart.getCategoryPlot();
            plot.setBackgroundPaint(Color.WHITE);
            plot.setRangeGridlinePaint(Color.GRAY);

            LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
            renderer.setBaseShapesVisible(true);
            renderer.setSeriesPaint(0, Color.RED);

            ChartPanel cp = new ChartPanel(chart);
            cp.setSize(730, 550);
            cp.setLocation(3, 3);
            cp.setVisible(true);
            chartPanel.add(cp);
            chartPanel.repaint();

JFreechart com valores Dinâmicos


Are the following statements true or false?

Question: Let $S$ be the set of vectors $\left\{ \left( 3,1,0\right), \left( -1,0,0\right) \right\}$ in $\mathbb{R}^{3}$. Let $T$ be the set of vectors which are orthogonal to some vectors in $S$, and $U$ be the set of vectors which are orthogonal to all vectors in $S$. Which are true or false ?
(a) $S$ is a subspace of $\mathbb{R}^{3}$
(b) $T$ is a subspace of $\mathbb{R}^{3}$
(c) $U$ is a subspace of $\mathbb{R}^{3}$
(d) $T$ is spanning set for $\mathbb{R}^{3}$
I understand the definitions of spanning, orthogonal and subspace, but I am having difficulty applying it to these True or False questions.
Answer: For (a): does $S$ contain $(0,0,0)$? All subspaces must contain this vector.
For (b): Note that $(1,-3,1)$ and $(0,3,0)$ are both elements of $T$. Is their sum $(1,0,1)\in T$?
For (c): Clearly, $(0,0,0)\in U$. Suppose $(a,b,c),(x,y,z)\in U$. Then,
$$
(a+x,b+y,c+z)\cdot (3,1,0)=(a,b,c)\cdot(3,1,0)+(x,y,z)\cdot(3,1,0)=0+0=0.
$$
Similarly, $(a+x,b+y,c+z)\cdot(-1,0,0)=0$. Thus, $(a,b,c)+(x,y,z)$. See if you can show that $\lambda(a,b,c)\in U$ for all $\lambda\in \mathbb{R}$ as well.
For (d): Note that $\{(1,0,0),(0,1,0),(0,0,1)\}\subset T$. What does this tell you?
Comment: The set S does not contain the zero vector, but surely we can make zero from a linear combination of the vectors in S meaning that it is apart of SpanS ?
Comment: In your question, you said that $S=\{(3,1,0),(-1,0,0)\}$. Therefore, $S$ does not contain the zero vector. span $S$ is a different set altogether.
Comment: For (d) will it span $\mathbb{R}^{3}$, since surely there will not be enough elements to span the whole of $\mathbb{R}^{3}$ ?
Comment: Yes. The vectors I mentioned for a basis for $\mathbb{R}^3$


Relação entre structs em C

Question: Tenho o seguinte cenário:
typedef struct Unidade{
    int cod;
} und;

typedef struct Produto{
    int cod;
    char nome[100];
    und unidade;
} prod;

Como podem ver tenho uma variável do tipo unidade dentro de produto. Como gravo nessa variável e como acesso ela?
Em unidade gravo assim: u
nidade.cod = 10;

Em produto ficaria como na hora de gravar nessa variável unidade? E como eu leria essa variável mais tarde?
Comment: Como está seu código que cria uma instância dessa estrutura?
Comment: no main esta assim  prod produtos[100]; //lista de produtos
 und unidades[20]; // lista de unidades
Comment: Edita a pergunta, coloca direitinho como tá.
Answer: Basicamente é
produto.unidade.cod = 10;

onde produto é a variável da instância.
A leitura seria feita assim:
produto.unidade.cod

Coloquei no GitHub para referência futura.
Se o objeto for criado como ponteiro aí teria que usar o operador -> no lugar de ..

Relação entre structs em C


Smooth function which is not continuous

Question: I have seen it mentioned that in certain infinite dimensional topological vector spaces it is possible to have a smooth curve which is not continuous, but I've never seen an explicit example. Can anybody point me towards a reference for this?
Comment: Isn't continuous included in the defintion of smooth?
Comment: This seems to be an oxymoron: smooth function is waaaay more than merely continuous, but undoubtedly *it is* continuous.
Comment: Smooth implies continuous is true in finite dimensions, but apparently not necessarily in infinite dimensions.
Answer: The mentioner might have been thinking of discontinuous linear maps on infinite-dimensional topological vector spaces.  You can read about the construction of such functions at Wikipedia.  The construction relies on the axiom of choice.
I am not an expert on notions of differentiability in infinite-dimensional spaces, but any linear function is well-approximated by a linear function (itself!).  So I believe that a discontinuous linear function has a Fréchet derivative.
Edit: Christopher Wong explains below that the function will be Gateaux differentiable but not Fréchet differentiable.
Comment: It will be Gateaux differentiable, but since the function itself is not continuous, it cannot have a Frechet derivative, which is required to be continuous.
Comment: Yes, I think that in the context where I've seen this they've been using the Gateaux derivative (but not using that name). Thanks!
Comment: @Christopher Thank you!  I've added a correction.

Smooth function which is not continuous


Is it possible to calculate weights of a portfolio with negative values?

Question: Sorry in advance if this question is either too basic or really dumb, but I've been researching this and am a bit confused.  I'm trying to help my niece with a question she has and the gist of it is she has the following portfolio:
Name     Shares    Price
a        50        50
b        85        20
c        10        -30
Total Value = $3900

I might be missing something obvious but I tried to take each value and divide it from the total, which gives me:
a 50 * 50 = 0.641%
b 85 * 20 = 0.436%
c 10 * -30 = -0.077%

Which equals 100% but is not correct because of the negative weight(I also tried to make the negative number positive but it didn't seem right). I understand the negative value is causing the weight to be negative but somehow I need to account for the 10 shares(I also want to account for it based on the value and not number of shares). How can I use this information and create  a weight that doesn't have a negative value?
I don't really need the answer, just the logic(or what kind of math I need to learn to solve this).
Answer: Usually you can abandon an asset that has a negative value, so you can ignore c and just consider a and b.  The sense is that the weighting gives you and idea how sensitive your portfolio is to changes in the value of the asset.  If you are stuck with c (say it is your house and you won't walk away) you could take the absolute value-in a sense a 5% change in the value of c will be properly reflected that way.
Then you need to normalize.  The fractions of the portfolio need to add to 100%, so divide by the sum of the percentages.  Then a=25/45, b=17/45, c=3/45.
This is the impact on your portfolio of a change in the value of one asset, but it ignores that the various assets could have much different volatilities.  Suppose a is cash, deposited in a bank account, while b is shares in Facebook.  The value of your portfolio is much more sensitive to Facebook than cash as the value will change much more.
Comment: Thank you so much for taking the time to help, Ross.  I'm still a bit confused.  I thought about the way you normalized the number(in fact I tried that before by using absolute numbers) but isn't the problem that the value of the portfolio is now $4500 using those numbers? Also doing a (.50 * 50)/39 + (.85 * 20)/39 + (.10 * 30)/39 equals 115%.  I might be missing something, sorry.
Comment: @learningJava:  yes, the assets are worth 4500 this way.  The point is that reductions of the negative one are worth as much as improvements in the positive ones.  But if the negative one improves \$100 it is as good as a positive one improving by the same \$100.  And you are right, the denominator should be 45 as 25+17+3=45.  Fixed.
Comment: Thank you for explaining it more clear.  I do see your logic, but I'm not sure if it fits my problem.  You see, I know the value is $3900 and although setting it to $4500 seems to solve my problem, I'm not sure if it reflects the correct valuation.  I think its the interday performance evolution of a fund, so overall it can never be negative but if you look at one days performance, then negative values happen. I get your logic but if your bank account says your portfolio is worth $3900, I'm not sure if its accurate to change that.
Comment: okay, I think I need to think about this logic more..but I think I took my eye off the prize and lost track of what your were saying.  The more I think about it, am I correct in your not saying to value the portfolio at $4500, but use it to figure the weights? So in the overall portfolio I own 6.67% of C? Basically if I want to recreate the above portfolio($3900) without any negative weights would it look like this: a= 55.5%, b= 37.7% and c= 6.67%? Is that correct?
Comment: Yes, that is what I was getting at.  It gives you a flavor of how much each will contribute if it improves by 10% of its value.  For the negative one, an improvement is a reduction in the absolute value, but it still indicates how important it is.
Comment: I understand what your saying but I don't know, it doesn't feel right(although logically it makes sense).  Let me present you with an example, say I was going to buy assets with these values(50,20,-30), what quantities would I need to buy to get to the 39 value I have over there.  Do I need a different way to get that to or can I rearrange the above results to get it? (25/45.0)*50 + (17/45.0)*20 + (3/45.0)*-30 = 33.33 and making it positive makes it 37.33 but not 39.  Sorry for being a pain, I just don't understand.
Comment: @learningJava: If your target is a specific value, that gives one equation in three unknowns:  a shares at 50, b shares at 20, c shares at -30 gives a total of 50a+20b-30c.  If you want this to equal 3900, you still have two degrees of freedom left.  You could have a=78, b=0, c=0; or a=0,b=300, c=70; or ???
Comment: Thanks Ross. I am trying to figure out how to do it while maintaining the same structure.  I am starting to suspect it may not be possible to maintain a similar structure and convert it for the same results.  I'll play around a bit and think about this and might ask if I have a different question.  Thank you so much for your help, and I'll accept your answer(and upvote).  Thank you!
Answer: I understand that this answer is late but I just see it. A short answer to your question is yes. Let me explain this. Suppose that you buy today stocks (a) 50*$30, (b) 85*$15 (c) 10*$45. The market value of this portfolio is $3225. Three months later you could have the next values (a) 50*$50, (b) 85*$20 (c) 10*-$30, with a market value of $3900. In the real world negative dollars do not exist, in the accounting and financial world it means losses. Thus, you have from the first portfolio value ($3225) the next weights:46.5%, 39.5%, 14%. From your second portfolio value ($3900), 64.1%, 43,6%, -7.7%. Then your gain/loss in 3 months is: gain of 17.6% from stock a, gain 4.1% from stock b, and losses 21.7%(-7.7-14) from stock c.


How to use WHERE condition with the LEFT JOIN?

Question: How to implement WHERE conditions in LEFT_JOIN. My query is:
SELECT t1.company_short_name, COUNT(t2.user_ip_address) as chart_accessed
FROM tblcompanymaster t1
LEFT JOIN tblhistorymaster t2 ON t1.row_id = t2.company_id
WHERE t2.user_last_request_time BETWEEN 1603775329 AND 1606280929
GROUP BY t1.company_short_name

Where I need to found all the company_short_name with the count of access, and if there is no access or the count is 0 then it should come COUNT(t2.user_ip_address) is 0. When I am not using where condition its working perfectly but after the use of where condition its giving only the result where the count is greater then 1. I have tried a lot but I am not able to modify the code. Any suggestions will be of great help
Answer: Put your where clause condition to ON clause
SELECT t1.company_short_name, COUNT(t2.user_ip_address) as chart_accessed
FROM tblcompanymaster t1
LEFT JOIN tblhistorymaster t2 ON t1.row_id = t2.company_id
and t2.user_last_request_time BETWEEN 1603775329 AND 1606280929
GROUP BY t1.company_short_name

Answer: You can add the filtering (where) component to the join instead - only taking the values if they exist in t2.
SELECT t1.company_short_name, COUNT(t2.user_ip_address) as chart_accessed
FROM tblcompanymaster t1
LEFT JOIN tblhistorymaster t2 ON t1.row_id = t2.company_id AND t2.user_last_request_time BETWEEN 1603775329 AND 1606280929
GROUP BY t1.company_short_name


When the tones in a chord are packed together, is it in "Close position" or "Closed position"?

Question: When a chord is written such that the chord tones are as close together as possible, like this...
<code>X:1
K:C
M:4/4
L:1/1
[CEG] | [EGc] | [Gce] |
</code>
...what is the correct term: "Close position" or "Closed position"?
Comment: While we're at it, is "close" in this case pronounced /kloz/ (like "close the door") or /klos/ (like "close to you")?  If it's /kloz/, then in my dialect at least, "closed position" and "close position" are nearly homophones due to the elision of /d/ before /p/.
Comment: I think the inflexible premise that there is only one correct answer is deeply misguided, biased, and not at all how language works. The types of evidence and "authority" you seek emphasize these points.
Comment: The myth and ideal of a one and only true correct meaning and perspective for basically everything is one of the worst things in today's world, in my opinion. The design of this very site supports the same misguided geek/engineer philosophy, trying to come up with one "correct" truth and world-view, calculating numbers that put everything in "scientific" order. :/ And the most tragic thing is, we're talking about _music_ which should be one of the best things in life, free-for-all, area of self-expression, communication, social experiences, celebrating life. Not about being correct. Sheesh!
Comment: @Theodore as in "the pitches as close together".
Comment: Correct in what context, for what purpose? There are many questions about correctness on this site, and from what I can see the problem behind many of the questions is not solving a problem or getting something done, but social legitimacy and respectability. Someone wants to "be right" as opposed to "being wrong", among peers or the general population or something. Being publicly proclaimed as being honourable and good, in contrast to others who are therefore dishonourable, bad, naughty. Being "wrong" is of course a frightening scenario, because it implies a threat of losing social status.
Answer: Both are correct.

Both are very widely used.
Both convey clear and well-understood meaning.
Both terms convey the intended meaning.
Both appear in authoritative sources.

Is "close position" more formally used [in Western classical music institutions]? Probably, but that's a very long way from making "closed position" incorrect.
First, it's important to point out that this is not analogous to confusing "intents and purposes" as being "intensive purposes." The term "closed" is descriptively accurate and conveys the intended meaning.
The reality of language is that there are often two alternative usages that are both accepted. This phenomenon is common in language, and is even documented in dictionaries. But dictionaries don't define language; new words are added to dictionaries each year because dictionaries lag behind trends. This lag is greater in niche areas like musical terminology, which are not exhaustively covered in general dictionaries and for which universally accepted authorities do not exist. Different genres, regions, and groups have different usages.
We must be cautious about using "authority" in these circumstances and telling a large group that the term they use, intend, and understanding is incorrect because it doesn't appear in a book written by a very narrow cultural/historical subset. Before going down that road, a relevant question to ask is: what defines authority in the domain of language, and how closely is that authority linked to institutions that historically represent white, male, Western classical traditions? (A quick search of the authors/editors you cited shows there might be something here.) You've acknowledged the ubiquity of "closed position." Where does the authority come from to deem this legitimate use of language incorrect. In what sense is the usage "closed position" not legitimate?
It's really not necessary, but here are some examples of the use of "closed position":
Suzanne Davis, associate professor of piano at Berklee College of Music:

If you can learn closed position and spread voicings with tension in your jazz voicings, you can pretty much apply them to any style of music. (Source)

thejazzresource.com:

Bill Evans pioneered a technique of using rootless 4-note voicings in his jazz piano playing. Also called closed-position voicings or Mehegen voicings, they consist of two guide tones (3rd and 7th) as well as two other notes (5th/6th and root/9th) and are usually voiced with a guide tone as the bottom note... (Source)

Here are two texts (1 and 2) that refer to "closed position voicings."
Here's an academic paper and a PhD dissertation that refers to "closed voicings" and "closed position voicings," respectively.
There are also many sites online, including these examples: 1, 2, and 3.
IMO the most reasonable position is that both terms are accepted, well-defined, descriptively accurate, and well-understood. In other words, they are both correct.
Comment: @Edward, the level of pedantry associated with this question is so high that it almost seems like an attempt to remind those who are not white, male classical musicians that they are wrong despite their widespread use of a term.
Comment: @Aaron, tell that to Suzanne Davis. But I think you're missing the bigger point. "Closed position" is extremely ubiquitous; that alone should give someone pause when deeming it incorrect. Its meaning is intentional and well-understood. It's an accepted alternative of "close position," which makes it correct. This is not analogous to confusing "intents and purposes" as being "intensive purposes." The term "closed" is intentional and conveys the intended meaning.
Comment: @Aaron, the point I'm making about language (and I can make this more explicit in my answer if it's not clear) is that you're not going to find "the true authoritative source" that gives us "the one true answer." The reality of having a second, accepted alternative is that they both are used widely with clear, well-understood meaning. Is "close position" more formally used? Probably. But that is a long way from making "closed position" an *incorrect* term.
Comment: @Aaron, I updated the answer to address your point about authoritative sources. I recommend caution there. Just based on some quick searching, all the authors/ editors you cited appear to be white males born in the mid 1900s trained in Western classical tradition. (Is that correct? I didn't dig too deeply.) A question to consider is: where does the authority come from to tell a group of people that a term is *incorrect* that (a) they use widely, (b) is descriptively accurate, (c) is very clear and well-understood, and (d) is used intentionally?
Comment: The sources cited are not convincing. It is easy to find many, many uses of "closed", but none in sources widely regarded as definitive.
Comment: You won't find a good enough musical dictionary that, when you look up "closed position," it says "alternative of close position." But despite not being as well-documented in this particular instance, this type of phenomenon is very common in language. The omission in a dictionary of one particular instance from the domain of musical terminology (which is not heavily featured in dictionaries) does not make the term "closed position" *incorrect*. Dictionaries doesn't define language, and in this case, the sheer ubiquity (combined with its clear meaning & intentional use) is highly relevant.
Comment: Clearly this is written as a rebuttal to the other answer, but I think too much of this answer is spent arguing against authority and dictionaries and language prescriptivism.
Comment: I also think examples of people using a phrase is generally poor support for "correctness" (whatever that means) of the phrase; I'd like to use a google ngram as support, but I can't think of a good pair of terms that doesn't also show up in other contexts.  There must be a better way, though.
Comment: @Edward, you don't find it at all concerning that (from what I can tell) all "authorities" cited in the other answer are white, they are all trained in classical music, almost all are male, and most were born before 1950? Do you expect black jazz artists to possess the same level of written authority given their history in the US? The other answer relies on a narrow set of opinions and claims they are correct by virtue of their historical power within musical circles. All of this is emphasized by the pettiness of the question and of arguing that "close" is correct and "closed" is incorrect.
Answer: Close position is the correct term.1

See, for example, Wikipedia: Voicing (music): Vertical placement.

Also, from "The Complete Musician" by Steven Laitz:

The third and the fifth of each triad are arranged directly above the root. This tight spacing ... of chordal members is called close position.2

From The Oxford Companion to Music:

position. ... (2). Chords may be described as being in 'close' or 'open' position, depending on their layout.3

In a variation, The Norton/Grove Concise Encyclopedia of Music combines "close position" and "close harmony":

Close position [close harmony] The spacing of a chord in such a way that the upper voices lie as close together as possible or the interval between the highest and lowest is relatively small.4

And from Aldwell and Schachter's Harmony and Voice Leading:

Of the many [possible chord voicings], two general types are commonly distinguished: open position and close position.5

From Harmony, by Walter Piston

When the three upper voices are as close together as possible, the spacing is described as close position.6

Finally, one source (and the only one cited here) that mentions "closed" position:

People often mishear [close position] as "closed" position because the meaning seems somehow logical, and you may by now even see it written that way in some sources.

The term is also used by Elaine Gould in her book Behind Bars. For example, the section title "options for close-position intervals" (p. 633).

Stemmed beams are often the best notation for close-position chords and also for sustained durations that overlap.

**Notes**
1 One possible source of confusion is that "close" and "closed" sound very similar, and "closed" makes intuitive sense, being the opposite of "open". It can be helpful to think of "open" in its meaning as "spacious" (the open prairie).
2 Steven G. Laitz, "The Complete Musician: An Integrated Approach to Tonal Theory, Analysis, and Listening", 2nd ed. (2008, Oxford University Press), p. 117.
3 The Oxford Companion to Music, ed. Alison Latham (Oxford University Press, 2003), p. 986.
4 The Norton/Grove Concise Encyclopedia of Music, ed. Stanley Sadie (Macmillan Press Ltd., 1994), p. 172.
5 Edward Aldwell and Carl Schachter, Harmony and Voice Leading, 2nd ed. (Harcourt Brace Jovanovich, 1989), p. 67.
6 Walter Piston, Harmony, 5th ed., rev. Mark DeVoto (W. W. Norton & Co., 1987), p. 18.
Comment: I think it's misguided to think that this question is best answered by looking at the sources where each term is used, evaluating which sources are "more definitive," and then picking *only one* answer based on the foregoing analysis. This opens the door to bias and doesn't reflect how language works. The right way to approach the question is to evaluate both terms' usage, ubiquity, meaning, and descriptive accuracy. You appear to reject at the onset the possibility that both are correct, which leaves no room for the reality of the situation.
Comment: It's probably pronunciation. In English English, close is pronounced 'cloce', whereas closed is pronounced 'clozed'. Close being the adjective *not* the verb (it's 'cloze' then).  So, not sounding dissimilar, but but easy to tell apart.
Comment: @Aaron, how many of your sources are white males trained in classical music and born before 1950? Do you expect Black jazz musicians to have the same level of "authoritative sources" you demand as evidence? You've defined "authority" in a way that excludes many of the voices you disagree with--which are the same voices that have been historically excluded from the positions of power you believe give credibility. Both terms are widely used, both are well-understood and convey accurate and intended meaning, and both appear in written text. Why do you insist they cannot possibly both be right?
Comment: You can add the [Dolmetsch Dictionary](https://www.dolmetsch.com/defsc1a.htm), which lists "closed position" but as a dance term.


Is $\text{Trace}(e^{XA+A^TX})$ a convex function of $X$?

Question: Is $\text{Trace}(e^{XA+A^TX})$ a convex function of $X$?
$X$ is diagonal and positive definite, $A$ is symmetric negative definite definite.
And by the way, what is the best way to solve a problem of the form:
$\text{min}.$ $\text{Trace}(e^{XA+A^TX})$
s.t. $X$ diagonal, $X_{ii}>0$ and $1^T X 1<x$
where $X$ is the variable and $A$ is symmetric negative definite, $x>0$, $x \in R$
Comment: A minor thing: since  $A$ is symmetric, why didn't you drop the transpose?
Answer: Let $D$ (resp. $D^+$) be the set of diagonal matrices (resp. diagonal positive matrices).
Let $f:X\in D^+\rightarrow tr(e^{XA+AX})$. We seek $\min_X f(X)$ under the condition $tr(X)=\sum_i x_{i,i}=x$.
Fortunately the first derivative of $f$ is easy to calculate. For every $H\in D$, $f'_X(H)=tr(e^{XA+AX}(HA+AH))$ ; the Lagrange condition of our problem can be written: there is $\lambda\in\mathbb{R}$ s.t., for every $H\in D$,$f'_X(H)+\lambda tr(H)=0$ or $tr((Ae^{XA+AX}+e^{XA+AX}A+\lambda I)H)=0$. That is equivalent to the following $n$ equalities:
(*) for every $i$, $(Ae^{XA+AX}+e^{XA+AX}A+\lambda I)_{i,i}=0$.
Remark 1. If $tr(X)<x$, then put $\lambda=0$ in the previous formula.
Remark 2. Unfortunately the second derivative of $f$ is difficult to calculate.
EDIT 1: @ questioner ,  Tim Notke (a highschool basketball coach) said
« Hard work beats talent when talent fails to work hard ».
If we search the critical points, then necessarily $tr(X)=x$ and even $\lambda >0$. Indeed $XA+AX$ symmetric implies that $e^{XA+AX}$ is symmetric $>0$. Thus $spectrum(Ae^{XA+AX})\subset \mathbb{R}^{*-}$ and $tr(Ae^{XA+AX})<0$. Finally, the relations (*) imply that $\lambda>0$ and therefore $tr(X)=x$.
EDIT 2. Let $S_n$ be the set of real symmetric matrices. $X\in S_n\rightarrow e^X$ is not a matrix convex function. Yet $X\in S_n\rightarrow \log(tr(e^X))$ is a spectral matrix function and is convex. cf. convexity of matrix "soft-max" (log trace of matrix exponential)
Thus $g:X\in S_n\rightarrow tr(e^X)$ is also convex. Here we consider $f:X\in S_n\rightarrow g(XA+AX)$ and for every symmetric $H$, $f''_X(H,H)=g''_{XA+AX}(HA+AH,HA+AH)\geq 0$. Finally, for every symmetric $A$, $f$ is convex over $S_n$.
Comment: So, what about convexity?! What can be used with the sole first derivate of f?!
Comment: Careful there. He offers a partial solution. That sounds a bit ungrateful.
Comment: @loup: this sounds a bit vague. What do you mean exactly by $f'_X(H)$? why does X is still appearing in it?  (thank you for the quote anyway.)
Furthermore, the constraint is inequality not equality, which is why, I think that you have to KKT instead of Lagrange Condition.
Comment: @ questioner , 1. the derivative $f'_X$ is a linear function over $D$ (see a book about differential calculus). Note that (star) is equivalent to $\nabla (f+\lambda tr)(X)=0$. 2. Since $f$ and $tr(X)$ are convex, the required minimum -if it exists- is reached on the edge, that is for $tr(X)=x$. 3. The necessary part of KKT condition is a direct consequence of Lagrange's theory (one line proof). 4. (star) is difficult to solve numerically. Perhaps it is better to use the convexity of $f$. You can ask Michael Grant ; he is a specialist in the subject.


Subgraphs of maximal planar graph

Question: Does a maximal planar graph with $n$ vertices (and $3n - 6$ edges respectively, please correct me if I am wrong) contain, as a proper subgraph, any planar graph (up to isomorphism) with at most $n$ vertices? Otherwise, what is a counterexample? I define a maximum planar graph as a planar graph that, when a new edge is added to it, is impossible to draw on a plane without intersections.
Comment: Welcome to MSE. Please read this text about [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question).
Comment: There is no such thing as "the" maximal planar graph on $n$ vertices.
Answer: A star graph on $n-1$ vertices (one in the middle, $n-2$ on the outside) is planar. But it is usually not contained within a maximal planar graph having $n$ vertices. For example, the Fritsch graph is a maximal planar graph on 9 vertices, and there is no 8-star to be found (as can be seen by inspecting the degrees of the nodes: the maximal degree here is 5, so there cannot be a proper subgraph where one of the nodes has degree 7). It also does not contain the 8-star as a minor, which is less immediate to see, but the basic observation is that there's no edge which you could contract, such that the two vertices on either end are between them connected to all of the remaining vertices.
This situation is generally applicable because maximal planar graphs (triangulated graphs) are under no obligation to have one of their vertices connected to $n-2$ of the others.

(image from https://commons.wikimedia.org/wiki/File:Fritsch_graph.svg)

Subgraphs of maximal planar graph


Help with view styling - template/css/whatever

Question: Our client saw the schedule view of DrupalCon Denver's site and wants one of their conference schedule views to look like that:

Obviously we're styling things differently, but what they really want is the track icons to display in the exposed filter and alongside the individual sessions.
Individual Sessions
We have a content type called session, and a taxonomy called track. The taxonomy has an image field called track icon (field_track_icon), and there's a term reference field on the session that holds the selected track.
I managed to get the icons to display in the view with the sessions:
View setup -

Preview -

But I need to do some conditional processing - if the field "field_hide_track" on the individual session is true, then don't display track icons (or the value of field_hide_track, obviously.) We have a certain session type that needs to contain all of the choices from the taxonomy (i.e. be associated with all tracks) but do not want it to have a visual indicator. Right now, because they have all the choices, the view displays all of the icons from the taxonomy. It also displays the icon twice if there are multiple speakers, but I think that's because of the way we have things grouped. Basically we want the icon to display before the session number/title line for all sessions that don't have field_hide_track checked.
I've tried custom templates (views-view-fields--at-a-glance-test--page.tpl.php and views-view-field--at-a-glance-test--page.tpl.php, where the view's machine name is at_a_glance_test), but can't figure out how to get the information I need to do the conditional processing. Can someone point me in the right direction?
Exposed filter
I have no idea where to start with this one. We're using Better Exposed Filters module to allow checkboxes instead of dropdowns, etc. I already have a views-exposed-form template to handle the background color and font choices, etc. but aside from some kind of horrible hard-coding, I don't know how to get the icons from the taxonomy to display next to the checkboxes. I think I could probably move the css for this into the template file and generate a background property for each taxonomy term that would include the image, but I don't know how to get the image from the taxonomy term field in the context of the views-exposed-form template.
EDIT to add Views PHP code that worked
<?php
if(isset($data->field_field_hide_track[0]['raw']['value'])) {
    if($data->field_field_hide_track[0]['raw']['value'] == '0') {

    $image_vars = array(
        'path' => file_create_url($data->field_field_track_icon[0]["rendered"]["#item"]["uri"]),
        'alt' => $data->field_field_track_icon[0]["rendered"]["#item"]["alt"],
        'attributes' => array(
          'class' => array('session_list_track_logo')
        )
      );

    $track_logo = theme('image', $image_vars);
    print "
" . $track_logo . " " . $data->field_field_session_number[0]['raw']['value'] . " | " . $row->title . "
";
    }
    else {
      print "
" . $data->field_field_session_number[0]['raw']['value'] . " | " . $row->title . "
";
    }
}

?>

Answer:
To show fields you have to use views_php where you can check
if ($row->field_hide_track) {
    print $row->field_track_icon;
}
For filters you are on the right track you are showing terms as checkboxes you just have to style labels of the field just like DrupalCon Denver's site something like this.
views-exposed-form-schedule-page .form-item-edit-track-1 label, #views-exposed-form-schedule-page-1 .form-item-edit-track-1 label, #views-exposed-form-schedule-page-2 .form-item-edit-track-1 label {
background: url(/sites/all/themes/denver2012/images/track-1.png) 0 0 no-repeat;
}
Comment: Thanks, I'll look at views_php. As for the exposed filter, I don't think I was clear on what I need to do. I know I can create a style like that; the issue is that I need to get the url of the graphic from the taxonomy term field.
Comment: If you want to show `field_track_icon` you have to write html in labels for this you have to override `theme_select_as_checkboxes` function from better_exposed_filters.theme in your theme and when `bef_checkbox` is called in `theme_select_as_checkboxes` it removes label html so you have to also write new function `your_bef_checkbox` where you can load term using `taxonomy_term_load($value);` and insert `field_track_icon` in your label
Comment: OK, I've looked at views_php, and based on the issue queue and all the comments, there are way too many bugs and issues to be useful in D7. Any other ideas?
Comment: I have never faced any issue using views_php and so are 11,415 other sites. Just try to use it. It works fine. If you don't want to use it then you have to overwrite fields level template in views `views-view-fields--at-a-glance-test--page.tpl.php` and put some php code there. But I strongly suggest to use views_php.
Comment: I've already tried. I spent 3 hours this afternoon trying. There are issues, big ones, with 7. The $rows>whatever variables only display node ids, not actual values, and there's no easy way to get an image field.
Comment: `if ($row->field_hide_track) { print drupal_render($data->field_track_icon); }` Is it not working?
Comment: No, it doesn't. That doesn't display anything.
Comment: Have you added `field_hide_track` and `field_track_icon` before `views_php` field? If you can share some screenshot then I'll be able to help you.
Comment: Yes. I did get it to work to a certain degree based on some comments from the [module's issue log](http://drupal.org/node/1140896). I've added the code to the OP. It's not pretty, and certainly not the way the module intended for things to work, but it's the only way it does work (for me and a whole lot of other people, apparently.)
Comment: so views_php is working fine now for you view?
Comment: I wouldn't say it's working fine; it's very buggy and needs to be hacked to get anything to work. But it does work. Yes, I'll give you the answer credit, since it's not your fault that it doesn't work as designed.


DLQueryExample could not load ontology

Question: DLQueryExample given worked . but when i changed the code to try for a new ontology , i could build the file without errors.i created the ontology using the ontology IRI http://www.semanticweb.org/name/ontologies/2013/8/insurance
 but when i tried to run it , the following problem occured.
--------------------Configuration: Samples - JDK version 1.7.0_40  - --------------------
Could not load ontology: Problem parsing string:ontology1
Could not parse ontology.  Either a suitable parser could not be found, or parsing failed.  See parser logs below for explanation.
The following parsers were tried:
1) RDFXMLParser
2) OWLXMLParser
3) OWLFunctionalSyntaxOWLParser
4) TurtleOntologyParser
5) OWLOBOParser
6) KRSS2OWLParser
7) ManchesterOWLSyntaxOntologyParser
Detailed logs:
Parser: RDFXMLParser
org.xml.sax.SAXParseException; systemId: string:ontology1; lineNumber: 3; columnNumber: 40; Element type "rdf:about" must be followed by either attribute specifications, ">" or "/>".

Parser: OWLXMLParser
Attribute not found: IRI (Line 3)

Parser: OWLFunctionalSyntaxOWLParser
Encountered "  "< "" at line 1, column 1.
Was expecting:
    "Ontology" ...
     (Line 0)

Parser: TurtleOntologyParser
uk.ac.manchester.cs.owl.owlapi.turtle.parser.ParseException: Encountered "" at line 1, column 1.
Was expecting one of:

Parser: OWLOBOParser
org.coode.owlapi.obo.parser.TokenMgrError: Lexical error at line 1, column 22.  Encountered: "\n" (10), after : ""

Parser: KRSS2OWLParser
de.uulm.ecs.ai.owlapi.krssparser.ParseException: Encountered " ">" " "" at line 1, column 1.
Was expecting:

Parser: ManchesterOWLSyntaxOntologyParser
Encountered '' at line 1 column 1.  Expected either 'Ontology:' or 'Prefix:' (Line 1)
Process completed.
how could i resolve this ?
Answer: Trying to access the ontology that you linked gave me a 404 error. If that was the case at the time you ran your experiment, that would explain the issue - the HTML returned in the 404 is not a parseable ontology, hence the failure.
The error message from the API could be clearer, though.

DLQueryExample could not load ontology


Trying to assign each letter the user inputs with an expression, then print the word and the added total of that word

Question: I'm looking for a quick solution to calculating multiple variables with expressions and then adding the totals of those expressions together. I know Adding if cases to every possible combination is not the way to go.
h = 8 * 6
e = 5 * 6
l = 12 * 6
o = 15 * 6

example: type in any word: hello
>>> hello: 312

Assign each alphabet letter variable its own alphabet string equivalent. E.g. a = 'a'
While True, ask the user to enter any word.
If a letter is in the word, assign each letter with an expression. E.g. a = 1 * 6

After that I'm not sure how I can easily handle any combination of letters the user inputs to add the totals afterward.
Comment: use a `dict`...
Comment: Unspecified in your question, but it looks like you might be interested in using `ord()`.
Answer: If your letters and values are in a dictionary you can easily lookup the value as you loop over the letters.
For example:
letter_values = {
  'h': 8 * 6,
  'e': 5 * 6,
  'l': 12 * 6,
  'o': 15 * 6
}

letter_values['h'] # 48

# use get() to return zero if not found

letter_values.get('h', 0) # 48
letter_values.get('&', 0) # 0

With this you can make a comprehension to loop over the letters in you word and take the sum of the result:
# for each letter get the value (or 0) and sum them:
sum(letter_values.get(letter, 0) for letter in str)

# result 312

Comment: Get does not return zero unless you tell it to. If returns None.
Comment: Thanks @MadPhysicist – had it in the second example just forgot it in the first.


AWS::S3::SignatureDoesNotMatch exception when copying/renaming a non-latin named file in S3

Question: I got this exception only for files with Hebrew characters:

AWS::S3::SignatureDoesNotMatch (The
  request signature we calculated does
  not match the signature you provided.
  Check your key and signing method.)

The code, after establishing the connection to S3, is:
AWS::S3::S3Object.rename(
  resource_file_name,
  new_resource_file_name,
  bucket,
  {:content_type => resource_content_type} )

Answer: Encoding only the first file name fixed the problem:
AWS::S3::S3Object.rename(
  URI.encode(resource_file_name),
  new_resource_file_name,
  bucket,
  {:content_type => resource_content_type} )

Comment: I'd love if someone could explain what is the logic behind this, and whether it's a bug...


upload multiple files which shows attributes say file size,file Name, and also remove option and cancel etc

Question: I came across this requirement, in which I need to upload multiple file with showing other attributes like showing file names , file size and also when someone click on remove option that particular file should be removed as well.
I thought to post this question as a reference for other, just to purpose of help someone
Answer: To achieve this just proceed as bellow
<code> var app=angular.module("MyApp",[]);
            app.directive('fileUpload', function () {
                return {
                    scope: true,        //create a new scope
                    link: function (scope, el, attrs) {
                        el.bind('change', function (event) {
                            var files = event.target.files;
                            //iterate files since 'multiple' may be specified on the element
                            for (var i = 0;i<files.length;i++) {
                                //emit event upward
                                scope.$emit("fileSelected", { file: files[i] });
                            }
                        });
                    }
                };
            });

            app.controller("MyCtrl",function($scope, $http) {

                //a simple model to bind to and send to the server
                $scope.model = {
                    name: "",
                    comments: ""
                };

                //an array of files selected
                $scope.files = [];

                //listen for the file selected event
                $scope.$on("fileSelected", function (event, args) {
                    $scope.$apply(function () {
                        //add the file object to the scope's files collection
                        $scope.files.push(args.file);
                    });
                });

                $scope.remove=function(file,files){
                console.log("size: "+($scope.files).length);
                if(files.indexOf(file)!=-1){
            files.splice(files.indexOf(file),1);
                }
                }

                $scope.validate=function(size,file,files){
                var status=false;
                console.log("size @@: "+($scope.files).length);
                if(size >2048){

            if(files.indexOf(file)!=-1){
            files.splice(files.indexOf(file),1);
            return true;
                }
                }

                if(files.length>5){

                if(files.indexOf(file)!=-1){
            files.splice(files.indexOf(file),1);
            return false;
                }
                }

                }

                $scope.cancel=function(files){
                console.log("Cancelled");
                files.length=0;
                }
            });
</code>


Likelihood ratio test for comparing two exponential distributions

Question: I am trying to use a likelihood ratio test to compare the parameters of two exponential distributions.
by this thread
Likelihood Ratio for two-sample Exponential distribution
I found that I can use
$$
\frac {L_{H_1}(\hat \theta_1,\,\hat \theta_2)}{L_{H_0}(\hat \theta_0)} = \frac {(\hat \theta_0)^{n_1+n_2}}{(\hat \theta_1)^{n_1}(\hat \theta_2)^{n_2}}=\left(\frac {\hat \theta_0}{\hat \theta_1}\right)^{n_1} \cdot \left(\frac {\hat \theta_0}{\hat \theta_2}\right)^{n_2}
$$
to calculate the likelihood ratio statistic.
(with mn1/mn2 being the means of the two datasets)
However, something doesn't seem right to me...I keep getting the statistic = 1 when i plug it into r.
Is this accurite? or does anyone know a likelihood ratio function to compare two distributions in r?
Comment: Could you show your derivation? It might help identify the problem.
Comment: alright, im using the equation on the right
Comment: In general, I don't get 1 on sample data when I use that formula.
Answer: The answer from the link provides a formula of ratio of likelihoods of the null and the alternative hypotheses with detailed derivation, and the R code below is my implementation for it with $\theta_1 = 1$, $\theta_2 = 2$, $n_1 = 70$, and $n_2 = 100$.
To generate samples, get cdf for exponential distribution first. If $f(x) = \frac{1}{\theta}e^{-\frac{x}{\theta}}$, F(x) = $\int_{0}^{x} \frac{1}{\theta}e^{-\frac{t}{\theta}} dt = 1 - e^{-\frac{x}{\theta}}$. If $u = 1 - e^{-\frac{x}{\theta}},$ then $x = -\theta*ln(1-u)$. So get $n_1$ samples $u \in [0, 1)$ and compute $x_i$ values with $\theta = \theta_1$ and $n_2$ samples $\in [0, 1)$ and compute $y_i$ values with $\theta = \theta_2$, and then follow the likelihood ratio formula to compute the ratio. The computed ratio is not always 1 using the formula after testing a few times.
<code>
theta_ln_1Minusu <- function(theta, vec){
  size = length(vec);
  for(i in 1:size){
    vec[i] = -theta*log(1-vec[i]);
  }
  return (vec);
}
</code>
<code>>theta1 = 1; theta2 = 2; n1 = 70; n2 = 100;
>u1vals = runif(n1); u2vals = runif(n2);
> xvals = theta_ln_1Minusu(theta1, u1vals);
> yvals = theta_ln_1Minusu(theta2, u2vals);
> x_avg = sum(xvals) / n1; y_avg = sum(yvals) / n2;
> x_avg
[1] 1.041831
> y_avg
[1] 1.733426
> w1 = n1/(n1+n2);w2 = n2/(n1+n2);
> likelihoodRatio = (w1+w2*y_avg/x_avg)^n1*(w1*x_avg/y_avg+w2)^n2;
> likelihoodRatio
[1] 168.8613
</code>
On the comment below:
In addition, regarding EngrStudent's comment, I spent a while to compute and found that the ratio is close to 1 only when x_avg is close to y_avg; in other words, $\theta_1$ is close to $\theta_2$. Denote $\frac{yavg}{xavg}$ as $x$, $x > 0$, divide the last term by $(n_1+n_2)$, and then compute the log of the last term in the link:
$w_1*ln(w_1+w_2x) + w_2*ln(w_1/x+w_2) = (w_1+w_2)*ln(w_1+w_2x) - w_2*ln(x) =ln(w_1+w_2x) -ln(x^{w_2})$
If this log value is 0, then $w_1+w_2x=x^{w_2}$. It is known that this equality holds when x = 1. The both sides are continuous. Now check the derivatives of both sides. The left side's is $w_2$, and the right side's is $w_2*x^{w_2-1}$. The increment rate of the left side is fixed to $w_2$, and $ w_2< 1$. If $x < 1$, $x^{w_2-1} > 1$, the increment rate of the right side is always larger than that of the left, $w_2$, and the left is larger than the right when x>0 close to 0. And if $x > 1$, the increment rate of the right side is always smaller than $w_2$. Thus, the equality holds only when $x = 1$.
Comment: Can you find the case or cases where the distributions would be fundamentally different, but the LLR test result might be close to one?
Comment: Check the formula, and you can see that if $\theta_1$ is close to $\theta_2$, x_avg is close to y_avg, the two terms are close to one and result must be close to one.


How to covert byte array b'2\x000\x006\x000\x000\x000\x00\x04\x04\x04\x04' to Readable character string "20600" using Python?

Question: I am getting b'2\x000\x006\x000\x000\x000\x00\x04\x04\x04\x04' byte array and I am trying to convert it to 206000 but when I use decode("utf8") it's printing 206000 and while returning it returns same byte array 2\x000\x006\x000\x000\x000\x00\x04\x04\x04\x04 in string format i.e. 2\x000\x006\x000\x000\x000\x00\x04\x04\x04\x04
I am doing decryption using AES of given encrypted string.
a = b'2\x000\x006\x000\x000\x000\x00\x04\x04\x04\x04'
b = ""
for aa in a:
    print(chr(aa))

print(b)

I expect the output of b'2\x000\x006\x000\x000\x000\x00\x04\x04\x04\x04' to be 206000, but the actual output is 2\x000\x006\x000\x000\x000\x00\x04\x04\x04\x04.
Comment: That's not UTF-8 encoding, it's UTF-16LE.  You first need to remove the padding bytes (the four 4's) that were added to make the message a multiple of the AES block size.
Answer: It seems your string is of type utf16. I did a.decode('utf16') and it gave me '206000ЄЄ' as the result. Not sure why these euro came but thought this might aid you to finally reach the goal. I think there is some problem with your utf16 encoding, but I am pretty sure it is utf-16 and this would be the solution. All the best. :)
Comment: The euro signs are from the `0x04` repeated 4 times at the end. I think that is probably padding. And it looks like PKCS padding for a 12 byte message (which this is) will use 4 x 0x04. https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.1.0/com.ibm.zos.v2r1.csfb400/pkcspad.htm
Answer: Thank you guys for your responses. I temporary solution for this. Because of some extra padding, it was not working. But after removing extra padding it is successfully running now.
data= b'2\x000\x006\x000\x000\x000\x00\x04\x04\x04\x04'.decode("utf8")
data= data.replace("\x00","")
data= data.replace("\x04","")
print(data)

I know it is the wrong way to solve the problem. But I promise you I will come back with a proper solution.
Thank You,
Hemant Hatankar
Answer: you need to remove the padding bytes first at the end of the byte array. and then you can use this to convert it into human readable string.
although \x00 represents null so this might help
a = b'2\x000\x006\x000\x000\x000\x00\x04\x04\x04\x04'
print("".join( chr(x) for x in a if x != 0x04))

Answer: You need to decode the byte array into a string first:
a = b'2\x000\x006\x000\x000\x000\x00\x04\x04\x04\x04'
b = a.decode('utf-8')
for aa in b:
    print(aa)

print(b)

Comment: This ain't a 'utf-8' string.


Como converter uma view para string no controller?

Question: Gostaria de converter essa view para string e ter o valor em string em meu controller
O problema é que eu gostaria que ela executasse um trecho de script que está nessa view
O método atual que tenho, apenas converte, sem executar o script que está nessa view
Atualmente está assim:
  public static string PartialViewToString(this Controller controller, string viewName, object model)
    {
      if (string.IsNullOrEmpty(viewName))
      {
        viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
      }

      controller.ViewData.Model = model;

      using (StringWriter stringWriter = new StringWriter())
      {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
        ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, stringWriter);
        viewResult.View.Render(viewContext, stringWriter);
        return stringWriter.GetStringBuilder().ToString();
      }
    }

Em meu controller chamo:
var htmlString = helper.PartialViewToString(this,"NomeView",model);

Comment: O que seria esses "scripts"? JavaScripts?
Comment: Porque é que precisas da view em string no controller? Isso é um requisito muuiito estranho... Tenho quase a certeza que existe uma maneira melhor de resolver o teu problema.
Comment: Olá, sim "scripts" são os javascripts
Comment: @dcastro, você já viu a lib "rotativa" que rendeniza a view em pdf ? então, a ideia é a mesma, entretanto eu quero armazenar o byte[]
Comment: Ok, parece-me um caso de uso valido. E o que é que os scripts fariam que fosse relevante para a geração do PDF?
Comment: @dcastro é montado usando template engine em js, usando dados que vem via json
Comment: Ou seja, a view que é inicialmente enviada para o cliente não contém dados, e estes dados são mais tarde obtidos via AJAX? Nesse caso, acho que vais precisar de uma view diferente para gerar o PDF, uma view criada na hora com todos os dados necessários .
Comment: sim, foi por esse motivo que eu quero captura-la no controller
Comment: É, acho que o melhor mesmo é criar uma view sem javascript para o PDF :/ coloquei na resposta
Answer: Os scripts na view só são executados do lado do cliente - no browser - depois do HTML ter sido gerado e enviado para o cliente.
Vais precisar de outra view sem javascript para gerar o PDF. Até existem javascript engines para correr do lado do servidor, mas acho que isso seria desnecessário, seria considerado um "hack", e sem duvida iria afectar a performance do servidor.


Porque o arquivo app.component.css não funciona no Angular?

Question: Quando executamos no Angular o comando ng g c page --spec=false ele cria um componente composto por quatro arquivos, um arquivo HTML, um arquivo de modulo,  um arquivo de CSS e um arquivo TS como mostra na figurar abaixo, no meu caso abaixo não precisei executar o comando porque veio nativamente do Framworks;

O arquivo CSS não funciona apesar de estarei interligados como mostra no código abaixo;
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

Essa são as configurações que coloquei no meu arquivo css que está com o nome de app.component.css
body{
    background: #098778;
}

Por favor, esse arquivo CSS está no projeto só de enfeite ou é porque estou fazendo algo errado?
Se estou fazendo algo errado o que devo fazer para ele funcionar?
Eu já sei que existe um arquivo padrão na raiz do projeto com o style.css, ele serve de configuração global do projeto, o que eu preciso é que o arquivo app.component.css funcione!
Comment: Nao existe a tag body dentro desse seu componente.
Comment: É isso mesmo, pode colocar sua resposta.
Answer: O app css e especifico do app component, o body esta acima dele no dom logo nao ira funcionar. Para mudar o estilo global você tem que mudar o arquivo style.css
o que vc pode tentar no app.css e algo assim:
:host{
    width:100vw;
    hight:100vh;
    background: blue;
}


Is it possible to serve a theme from outside the web root?

Question: We have a need to keep a proprietary theme in a directory that isn't readable or writable by a client.
At the same time, the client needs to be able to do standard Drupal updates (ie, they will have full control of the web root of the Drupal installation, but nothing above that).
What's the easiest/best way to accomplish this, assuming it's possible?
Answer: If you have
Options +FollowSymLinks

set for the DocumentRoot for your Drupal site, you can put the proprietary theme anywhere you want as long as you create a symlink to it somewhere Drupal searches for themes (eg, sites/all/themes).
Just keep in mind that Apache needs to be able to read it.  Whether the client can read it directly is a permission issue, but if Apache can read it a savy client can get it via custom PHP.
Comment: Also keep in mind that you can never completely keep the CSS, JavaScript, images and HTML output to yourself, because it is sent to the browser.
Comment: Thanks, MPD. A symlink seems sensible. Appreciate the warning about the accessing via PHP as well. I'll let you know what way we go on this.
Comment: @marcvangend, that's a good point and something we're willing to live with. The theme itself we do need to keep as protected as possible.


Is the Church-Kleene Ordinal describable with Kleene's $O$?

Question: Kleene's $O$ is an ordinal notation system that uses certain natural numbers to represent transfinite ordinals.  It is a recursive notation system (although it's not decidable whether a number represents an ordinal whether two numbers represent the same ordinal), so naturally we can only represent recursive ordinals, i.e. order types of recursive well-orderings.  The smallest ordinal we cannot represent in Kleene's $O$ is the Church-Kleene ordinal $\omega_1^{\mathrm{CK}}$, the smallest non-recursive ordinal, so it is the order type of the recursive ordinals, i.e. the order type of the ordinals that can be represented in Kleene's $O$.  (This leads to the result that the set of natural numbers in Kleene's $O$ is not recursive, or even recursively enumerable.)  Since $\omega_1^{\mathrm{CK}}$ is non-recursive, it follows that you can't have a recursive well-ordering in Kleene's $O$ that has order-type $\omega_1^{\mathrm{CK}}$.
Yet this Wikipedia article mentions a remarkable fact:
"Within the scheme of notations of Kleene some represent ordinals and some do not. One can define a recursive total ordering that is a subset of the Kleene notations and has an initial segment which is well-ordered with order-type $\omega_1^{\mathrm{CK}}$. Every recursively enumerable (or even hyperarithmetic) nonempty subset of this total ordering has a least element. So it resembles a well-ordering in some respects. For example, one can define the arithmetic operations on it. Yet it is not possible to effectively determine exactly where the initial well-ordered part ends and the part lacking a least element begins."
First of all, does anyone know the details of how this recursive subset is defined?  I'm more interested in the last part: "it is not possible to effectively determine exactly where the initial well-ordered part ends and the part lacking a least element begins."  I assume that if you partitioned a recursive totally ordered set $X$ into two parts $A$ and $B$, such that every element of $A$ is less than every element of $B$, then both $A$ and $B$ are recursive totally ordered sets.  Am I wrong about that?  If I'm right, then is the article saying that a partition of the recursive subset into the well-ordered part and the non-well-ordered part CAN be done recursively, but we can't tell recursively which partition is the one we want?
Any help would be greatly appreciated.
Thank You in Advance.
Answer: This is a bit too long to fully describe here. I can give you references.
Sacks's Higer Recursion Theory is a good source for learning about the ordinal notations and Kleene's $\mathcal{O}$.
I believe wikipedia above is describing the $\Pi_1^1$ set of unique notations in Kleene $\mathcal{O}$. This is constructed using the Harrison Ordering, which is a recursive linear ordering which is not a well-ordering but has no hyperarithmetic decreasing sequence. It also has an initial sequence of order type $\omega_1^\text{CK}$. In fact the order type of the Harrison Ordering is $\omega_1^{CK}(1 + \eta) + \gamma$ where $\eta$ is the order type of $\mathbb{Q}$ and $\gamma$ is some computable ordinal.
The relevant section to learn about the set of unique notations and the Harrison Ordering is page 55-58 in Sacks's Book. I believe the book is available online.
Comment: @KeshavSrinivasan The Harrison Linear ordering is recursive in the sense that it is isomorphic to a computable linear ordering of $\omega$. This does not mean that the Harrison Linear Ordering sitting inside of $\mathcal{O}$ is a computable subset of $\mathcal{O}$. Also the Harrison Ordering is constructed by using a arbitrary recursive linear ordering with no hyperarithmetic descreasing sequence. So the $\gamma$ will probably depend on which one you choose.
Comment: @KeshavSrinivasan It is not true. Another example: by an easy finite injury argument, we can come up with a computable total order of ordertype $\omega+\omega^*$, such that neither the $\omega$ nor $\omega^*$ part is a computable subset.
Comment: Indeed it is: [Projet Euclid link](http://projecteuclid.org/euclid.pl/1235422631).
Comment: @William Thanks for this.  Does Sacks discuss my question about whether the well-ordered initial segment of the Harrison Ordering is a recursive set?  Also, is anything known about what specific ordinal this mysterious $\gamma$ is?
Comment: @William So is the Harrison Ordering NOT a computable subset of $O$?
Comment: Wikipedia and Sacks does not say that the Harrison Ordering is computable as it sits inside of $\mathcal{O}$. However, the well-ordering ititial segment is definitely not recursive. If it was, then the initial is isomorphic to an computable ordinal. But we know the initial segment is $\omega_1^{CK}$ which is not computable. Although I suspect the Harrison Order is not recursive inside $\mathcal{O}$, even if it was, the initial segment is a limit ordinal so I do not see any way this would imply the initial segment is computable.
Comment: @William If $X$ is a totally ordered recursive set and you partition $X$ into two parts $A$ and $B$ such that every element of $A$ is less than every element of $B$, then don't $A$ and $B$ have to be recursive?
Comment: If the $<$ relation is recursive, then for any fixed $z$, $\{x : x < z\}$ is recursive. But there is no element in the Harrison Order such that the well ordered initial segment is exactly the set of things less than this element.
Comment: @William So is my general statement about $A$, $B$, and $X$ not true?


Self used before self.init called in custom UIGestureRecognizer class

Question: What would be the proper way to subclass UITapGestureRecognizer and initialize a variable passed to my convenience constructor before I call the constructor that needs to get passed a reference to itself for later use?
Here is my code that doesn't compile yet:
import Foundation
import UIKit
import UIKit.UIGestureRecognizerSubclass

typealias ActionBlock = (BlockTapGestureRecognizer) -> Void

class BlockTapGestureRecognizer : UITapGestureRecognizer {

    private var handler: ActionBlock?

    convenience init?(handler block: @escaping ActionBlock) {
        self.init(target:self, action:#selector(self.performAction(_:)))
        self.handler = block
    }

    func performAction(_ recognizer: BlockTapGestureRecognizer) {
        if let block = self.handler {
            block(self)
        }
    }

}

Answer: The problem is that self and self.performAction(_:) are both being referenced before the call to self.init can be made. This violates the order of initialization requirements in Swift.
One solution would be to delay the setting of the target and action.
convenience init?(handler block: @escaping ActionBlock) {
    super.init()
    addTarget(self, action:#selector(performAction))
    self.handler = block
}

Note that if your BlockTapGestureRecognizer doesn't actually have any other init method that it explicitly declares, then this init method can't be a convenience and it shouldn't be optional because it can't fail:
init(handler block: @escaping ActionBlock) {
    super.init()
    addTarget(self, action:#selector(performAction))
    self.handler = block
}

Comment: @LeoDabus The joy of copy and paste :) Thanks


Rails form_for multiple different class objects?

Question: Is there a way to have multiple and different models in one form_for in rails 4?
maybe something like
# gives error
<%= form_for ([@user, @pet]), url: some_path do |u, p| %>

Comment: What are your routes?
Answer: Typically something like this is done with associations of the two models. In which case, I will take a few assumptions here. I assume that you have two models user and pet. I assume that a pet belongs to a user and a user can have many pets. With this kind of association, a pet model would have a user_id attribute that would association the user to that pet.
User Model
attr_accessible :name, :pets_attributes
has_many :pets
accepts_nested_attributes_for :pets

Pet Model
attr_accesible :user_id, :name
belongs_to :user

Personally, I am a big fan of using simple_form as it has a cool association feature.
View
<% simple_form_for @user do |f| %>
  <%= f.input :name %>
  <%= f.simple_fields_for :pets do |p| %>
    <% p.input :name %>
  <% end %>
<% end %>

Controller
Within your controller, (going to assume that this is a new action). This will create a line for the user and build three spots for the pets.
def new
  @user = User.new
  3.times do
    @user.pets.build
  end
end

Routes
One thing that you may want to consider with the routes is to set them up similar to this. This would create your routes to be a bit prettier as a Pet show action would also be referenced to the user /users/:user_id/pets/:pet_id
resources :users do
  resources :pets
end

Answer: It is not possible with form_for helper because it takes only one record. Syntax with [@user, @pet] is for building right routes for associated records. Only last element of passed array will be used as record. Other will be used to create right routes. So, in your example, assuming user has one or many pets and @user is persisted, result route will look like one of the following:
"user/#{@user[:id]}/pet/#{@pet[:id]}" # when @pet is persisted
"user/#{@user[:id]}/pet/new" # if @pet = Pet.new

You can define your own helper and form builder or just write custom template view to accept multiple records.


Most performant way to update a single document in Elasticsearch via an alias

Question: I have an Elasticsearch setup with an alias that points to many indices. I need to update a single document, but I don't know which index it resides in.
There are two ways I can accomplish this as far as I can see:

_update_by_query:

POST my-alias/_update_by_query
{
  "query": {
    "terms": {
      "_id": ["my-id-to-update"]
    }
  },
  "script": {
    "source": "ctx._source['Field'] = 'new value'"
  }
}

read (which returns the specific index) then write:

GET my-alias/_search
{
  "query": {
    "terms": {
      "_id": ["my-id-to-update"]
    }
  }
}

POST my-index-returned-from-the-get/_update/my-id-to-update
{
  "doc": {
    "Field": "new value"
  }
}

Which method is more performant?
Which method is preferred?
Is there a better way than either of these two?
Answer: The performance of both approach will be the same with one difference that your first approach only need to send one request compare to second one with two request, so it would be better to use first approach as you will reduce the API calls by half.
Also in my opinion the first approach is much cleaner and fits more in concept of aliases of Elasticsearch because you are encapsulating exact index name from your application, as application doesn't need to have any clue about exact index-name your documents are in.
An important note about updating a document in Elasticsearch is documents in Elasticsearch don't get updated, it means the document will be flagged as deleted and new document will be created (this is due to Lucene implementation), then during process of Lucene segment merging the document will be actually deleted.
you can find a good blog post about segment merging here.