In a raffle with two prizes, what's the probability of winning at least a prize, if I buy more than one ticket?

Question: Let's say there's a raffle with two prizes. The total number of tickets sold is of 15 (meaning that the probability of winning at least  prize, if I buy one ticket, would be $p = 2/15$).
My question would be, what happens if I buy more tickets, for the same raffle? I read some answers for a similar question, and people were calculating the probability of winning the raffle, based on the probability of not winning it.
The formula applied there was:
$p = 1 - (1-x)^{2}$
, if someone buys two tickets. The logic behind it was: what was the probability of actually missing the prize $n$ (or 2, for this example) times in a row. Then subtract that value from 1.
I wanted to know, how can we calculate this probability without actually calculating the failure probability first. For example, if the probability of buying one ticket and winning one of the two prizes is $p=2/15$, why isn't the probability of winning a prize, in case of buying 2 tickets $p = 2 * 2/15$?
I know my assumption is wrong, because if someone would buy 10 tickets, the probability would already be $p=\frac{2 * 10}{15}$, which is already greater than 1.
Why is my logic wrong, in this case?
Comment: It's wrong because you double count the scenarios in which you win two prizes.  In general, $P(A\cup B)=P(A)+P(B)-P(A\cap B)$ but you neglected that last term.
Comment: $A$ is the event "the first ticket wins a prize" and $B$ is the event "the second ticket wins a prize".  You could only sum those probabilities if the events were mutually exclusive, which they are not.
Comment: @lulu Would $P(A)$ be the probability of winning the first prize only, and $P(B)$ the probability of winning the second prize only? If so, how can $P(A∩B)$ be explained? Probability of winning both of the prizes simultaneously?
Answer: This is in essence the hypergeometric distribution; from a box with $N$ balls (15 tickets), where $m$ are white (2 winning tickets) and $N-m$ are black (13 non-winning tickets), we pick $n$ balls at random (we buy $n$ tickets). If we denote "$X$" the number of white balls (winning tickets) we pick, the probability that $X=i$ is;
$$P(X=i)=\frac{\binom{m}{i}\cdot \binom{N-m}{n-i}}{\binom{N}{n}}$$
So in your case it would be $P(X=1)+P(X=2)$, with substituting $n$ in the formula accordingly to the number of tickets you buy.
Answer: I will try to instead dive into an explanation that relies more on intuition than on the necessary math behind what is happening, which should be a combination of the following:

You buying more tickets dilutes the individual chance of each of your tickets winning. A second ticket purchased means you would have your first ticket have to be drawn from amongst a pool of not 15 but 16 tickets instead, which lowers the individual chance of each ticket winning. Thus, you cannot simply multiply the probability of winning by the number of tickets purchsed without accounting for the fact your tickets increase the ticket total.

If you win the first prize with 1 ticket, all your other tickets
become worthless for the consideration of meeting the condition on
the 2nd raffle. The probability of winning 1 prize with 1 ticket is
split as between winning the 1st available prize and the 2nd one.
If on the 1st raffle you already win a prize, each of the individual
chances of winning on the 2nd try for all the other tickets
effectively do not matter. They are instead as if the 2nd half of
the raffle contributes nothing to your chance of winning.
Another way you can think of this is that the condition needs you to
win at least 1 prize, but 2 tickets both winning means they were
seperately counted twice towards meeting the condition despite the
fact we only need to count this as 1 win towards our computation (if
hypothetically every time you played you won both prizes, it
wouldn't make sense you had a probability of 2 of winning at least 1
prize), so you would have to remove that extra probability of 2 tickets winning.
This effectively again reduces the additional probability
contribution of each of your tickets.

To summarize, each ticket loses value as you buy more because 1) it has more competition against all your other tickets and 2) because two of your tickets winning is no different than 1 of your tickets winning, so you have to account for that in the computation since it would instead count it as 2 wins.
Sidenote: The logic provided is closer to the concept of expected value. If you had 10 tickets purchased in a 2 prize raffle with 15 entries (including yours), you would in fact have $E= \frac{2 \cdot 10}{15}$ prizes won on average.


Views filter (contextual?) by Taxonomy id

Question: Have a question.
I have a D8 website for our company. This website contains service pages and now I would like to add a block with reviews on every service page. But the reviews should match the service.
The website has taxonomy vocabulary with all the services. So when I create a service page I have to choose a service from taxonomy (basically, one service page represents one term id from taxonomy vocabulary). And when I create a new review I also have to choose a service from the same taxonomy vocabulary.
So now I would like to add a block with the reviews on the service page. But I have no idea how to make the reviews match with the service page where they are embedded.
Is there some kind of filter what match term IDs from different fields?
Regular filter, contextual filter? Tokens? Unfortunately, nothing worked for me :(
I could create different blocks for every single service ... but there would be a more universal solution.
Would be happy to get any help with that.
Answer: Add Term ID as contextual filter.
When filter value is not available, select Provide Default value
For Type, select Term ID from URL
This is automatically pickup the term from your node, your view preview will go blank, because the actual view edit page does not have a term. It will show up when you look at the node.
Comment: Thank you :)

Unfortunately, I do not have "Term ID from route context" for some reasons.
Comment: @user126902 turns out they recently renamed it to from URL.


Way to compare array key & replace value if found (PHP)

Question: Hello i am trying to make an php application, but i am having some trouble with arrays
Actually,
I m trying to compare array key & if found replace its value & merge whole array into one.
For example
Array ONE-
Array
    (
        [0] => Array
               (
                [label] => July 20 2020
                [y] => 3
               )
        [1] => Array
               (
                [label] => July 18 2020
                [y] => 1
               )
    )

Array TWO-
  Array
        (
            [0] => Array
                   (
                    [label] => July 18 2020
                    [y] => 0
                   )
            [1] => Array
                   (
                    [label] => July 19 2020
                    [y] => 0
                   )
            [2] => Array
                   (
                    [label] => July 20 2020
                    [y] => 0
                   )
            [3] => Array
                   (
                    [label] => July 21 2020
                    [y] => 0
                   )
        )

To
desired output array
Array
            (
                [0] => Array
                       (
                        [label] => July 18 2020
                        [y] => 1
                       )
                [1] => Array
                       (
                        [label] => July 19 2020
                        [y] => 0
                       )
                [2] => Array
                       (
                        [label] => July 20 2020
                        [y] => 3
                       )
                [3] => Array
                       (
                        [label] => July 21 2020
                        [y] => 0
                       )
            )

I have tried
array_merge($arrayone, $arraytwo);
but it doesn't work.
Is it possible to get the desired output ?
This is how array looks like - https://i.stack.imgur.com/RT0TW.jpg
Please share your thoughts on this.
Thankyou
Answer: With your arrays, I do not think there is a smart way to do it, but this should work :
    <?php
$datesArray = [
    [
        'label' => 'July 18 2020',
        'y'     => 0,
    ],
    [
        'label' => 'July 19 2020',
        'y'     => 0,
    ],
    [
        'label' => 'July 20 2020',
        'y'     => 0,
    ],
    [
        'label' => 'July 21 2020',
        'y'     => 0,
    ],
];

$valuesArray = [
    [
        'label' => 'July 20 2020',
        'y'     => 3,
    ],
    [
        'label' => 'July 18 2020',
        'y'     => 1,
    ],
];

foreach($datesArray as &$dateArray) {
    foreach($valuesArray as $valueArray) {
        // use ?? if php version allows it, else do isset($valueArray['label']) ? $valueArray['label'] : null;
        $currentLabel = $valueArray['label'] ?? null;
        if ($currentLabel === $dateArray['label']) {
            $dateArray['y'] = $valueArray['y'] ?? 0;
        }
    }
}

print_r($datesArray);
return $datesArray;

Result :
Array
(
    [0] => Array
        (
            [label] => July 18 2020
            [y] => 1
        )

    [1] => Array
        (
            [label] => July 19 2020
            [y] => 0
        )

    [2] => Array
        (
            [label] => July 20 2020
            [y] => 3
        )

    [3] => Array
        (
            [label] => July 21 2020
            [y] => 0
        )

)

This will take quadratic time, if you need something faster you will have to change the indices of your arrays to make a faster lookup.
snippet
Comment: Hello, you mean there is no return ? I have added return to the end of the script, but the `print_r($datesArray);` actually outputs the desired result
Comment: Yes their was no return
Comment: I had figured out the same functionality with another way so its ok, but this is interesting to find that code example you've added seems to be working but in actual integration it does not print anything i mean just blank (print_r).
Comment: Well it should be working, can you show the code that is not working ?


Can't crack the "java.sql.SQLException: No suitable driver" in my JUnit test

Question: I'm using Hibernate 4.1.5.SP1, Hibernate Validator 4.3.0.Final and JUnit 4.8.1.  When I run my JUnit tests, I'm getting the exception "java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/myproject" when trying to setup my transaction.
@Before
public void setUpDAOTest() {
    final Configuration configuration = new Configuration();
    configuration.configure("junit_hibernate.cfg.xml")
        .setProperty("javax.persistence.validation.mode", "none")
        .setProperty("hibernate.show_sql", "false");
    final ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    session = sessionFactory.openSession();
    ThreadLocalSessionContext.bind(session);
    tx = session.beginTransaction();    // exception thrown here

The exception suggests my URL is malformed, but it seems right to me.  Also, I have verified the database is running and I can connect to it on a command line.  My Hibernate config file is
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myproject</property>
        <property name="hibernate.connection.username">myproject</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.pool_size">10</property>
        <property name="show_sql">true</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="javax.persistence.validation.mode">none</property>

        <property name="current_session_context_class">thread</property>

        <mapping class="com.follett.fdr.myproject.model.UserRole" />
        <mapping class="com.follett.fdr.myproject.model.Organization" />
        <mapping class="com.follett.fdr.myproject.model.Product" />
        <mapping class="com.follett.fdr.myproject.model.State" />
        <mapping class="com.follett.fdr.myproject.model.Country" />
        <mapping class="com.follett.fdr.myproject.model.AccessCode" />
        <mapping class="com.follett.fdr.myproject.model.Contract" />
        <mapping class="com.follett.fdr.myproject.model.TrainingLink" />

    </session-factory>
</hibernate-configuration>

So I'm stumped.  What else could I be doing wrong?  Here is the full stack trace …
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/myproject
    at java.sql.DriverManager.getConnection(DriverManager.java:602)
    at java.sql.DriverManager.getConnection(DriverManager.java:154)
    at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:193)
    at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:281)
    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:297)
    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:169)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160)
    at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1396)
    at org.mainco.subco.orgsclient.dao.AbstractDaoTest.setUpDAOTest(AbstractDaoTest.java:40)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)

Answer: you should have the mysql driver jar in your classpath, so download it and include it in your classpath
if you are using maven to build take the definition from here
Comment: Ah, yes I'm using Maven.  Turned out upgrading the dependency version I was using from 5.0.5 to 5.1.15 healed the pain.  Btw, that link you posted wasn't working for me.


Como se utilizar propriedade expandida no C#

Question: Estou com um problema, criei uma classe contendo a seguinte propriedade:
public class MinhaClasse
{
public int Idade {get; set;}
}

Porém, quando eu faço isso:
public class MinhaClasse
{
   public int Idade {
      get{
         return Idade;
      }
      set{
         if (value < 18)
            throw new Exception("Proibido para menores!");
         else
            Idade = value;
      }
   }
}

O código acima não funciona e sou obrigado a criar um atributo private para armazenar o valor idade, ou pelo menos tenho feito assim. Isso está correto? Por que não posso usar Idade = value?
public class MinhaClasse
    {
       private int _idade;
       public int Idade {
          get{
             return _idade;
          }
          set{
             if (value < 18)
                throw new Exception("Proibido para menores!");
             else
                _idade = value;
          }
       }
    }

Comment: tenta public int idade(int idade)
Answer: Tem que criar o campo privado para funcionar, você está criando um loop infinito, porque está usado a propriedade Idade para manipular a propriedade Idade, o que então forçará manipular Idade e assim vai.
using System;

public class Program {
    public static void Main() {
        var obj = new MinhaClasse();
        obj.Idade = 20;
        Console.WriteLine(obj.Idade);
        obj.Idade = 10;

    }
}

public class MinhaClasse {
    private int idade;
    public int Idade {
        get => idade;
        set => idade = value < 18 ? throw new Exception("Proibido para menores!") : value;
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Sempre que lança uma Exception está fazendo algo errado. Até consideram que esta classe deveria ser abstrata para ninguém poder usar. Muitas pessoas consideram ruim lançar exceção em uma propriedade, pelo menos em boa parte dos casos. Isto é controlar fluxo com exceção.
Comment: Sim............
Comment: @gato Depende de várias cosias, tem usos que não serve pra nada, porque precisa de um *framework*  que faça a validação, tem casos que ela não resolve, tem casos que não faz sentido usá-la, afinal é uma forma declarativa, e boa parte dos código precisam ser imperativos, o declarativo é bom quando vai usar em algum outro lugar e o *framework* específico precisa entender a semântica daquilo. De forma geral não sou muito fã
Comment: Por que no primeiro exemplo que dei o código funciona e não cai no loop?
Comment: Porque você não está manipulando a própria propriedade, em algum lugar daquele código mostra que está fazendo isso?
Comment: Por causa do Set.
Comment: Não entendi....
Comment: Me ajude a compreender uma coisa, no primeiro exemplo, ele cria um atributo para a classe com o mesmo nome da propriedade?
Comment: Não, ele cria um campo com o nome que ele quiser.
Comment: Daí, a partir do segundo exemplo, ele já não cria mais esse campo e a propriedade se comporta como um método, por isso eu tenho que criar um campo eu mesmo. É isso?
Comment: Sim, sempre é um método, ou dois se fizer as duas operações. https://pt.stackoverflow.com/q/133924/101
Comment: Para situações como a do segundo exemplo, poderia existir algo como um "return value" (ou algo assim) dentro do set. Deste modo ele não cairia em loop e saberia que era para definir o valor da propriedade. Assim eu não precisaria criar um campo chamado idade só para isso e código ficaria mais limpo. Por isso fiz a pergunta, achei que o C# tinha algo desse tipo para resolver o problema.
Comment: Não, o `set` é `void`. Ambos caem em *loop* se você usar o próprio nome, e nada que não seja usar outro nome pode resolver isso, menos ainda um `return`.
Comment: Mas quando faço uso apenas do `public int Idade {get; set;}` ele entende sozinho que é para retornar o valor da propriedade e "setá-la". Quando digo `Idade=value` ele poderia entender que não quero um loop infinito e sim fazer o set da propriedade.
Comment: Quem viu algum problema na resposta favor informar para eu arrumar. Ou tirar o negativo sem motivo.
Comment: Não fui eu, eu dei até um positivo para equilibrar novamente. A resposta me foi muito útil.
Comment: @Maniero o uso de Dataannotations não seria mais apropriado para validar a lógica do modelo?
Comment: @Maniero hum entendi. Lembrei me [desta resposta](https://pt.stackoverflow.com/a/105684/27190), acho que o AP pode dar uma olhada e aprender um pouco sobre validação ;D
Comment: É, ali foi criado um *framework* :) Não gosto pra tudo.


Exercício Linguagem PHP

Question: Alguém pode me ajudar:
Em PHP:
Crie uma classe que tenha dois métodos;
O método 1 calcula o módulo da divisão do número de matrícula (número qualquer) por um número inteiro (você decide qual número inteiro utilizar);
O método 2 irá imprimir na tela o resultado obtido pelo cálculo realizado no método 1.
Comment: Qual sua dúvida? O que você tentou fazer?
Answer: Não é o objetivo do site resolver questão e sim tirar dúvidas. Mas ao que parece você é novata então vou responder sua pergunta. Podemos definir essa classe de muitas formas, mas escolhi fazer da forma mais fácil possível. Segue o código:
<?php
    class Modulo{

        private $resto;

        public function restoDivisao($matricula, $denominador) {
            $this->resto = $matricula%$denominador;
        }

        public function imprimeResto() {
            echo $this->resto;
        }
    }
?>

Aqui definimos a classe que tem apenas um parâmetro, que é o resto da divisão. Ele é um parâmetro privado, ou seja, só pode ser acessado pelos próprios métodos da classe. Para usar essa classe você pode fazer da seguinte forma:
$resto = new Modulo;
$resto->restoDivisao(9,4);
$resto->imprimeResto();

Primeiro instanciamos a classe, criando um objeto e guardando na variável $resto. Depois chamamos  métido restoDivisao(), passando como parâmetros o número da matricula (um número qualquer) e o divisor. Esse método faz o cálculo do resto e guarda no atributo privado. Depois chamamos o método imprimeResto() que pega o atributo que setamos no método anterior e imprime na tela.

Exercício Linguagem PHP


What phrase pasted in vim's normal mode would create havoc in the text?

Question: If pasting a text in vim I forget to switch to insert mode and the text streams in normal mode, usually what happens is that the "command" is getting executed until the first insert-mode character (i I a A o O s S c C) and the rest text then gets pasted, leaving some degree of a mess.
Are there words (or code snippets) which would create a lot of mess if pasted in normal mode?
e.g. use would undo the last change and overwrite the undo history, which can cost some nerves.
I guess as an aside, maybe there is a way to work around that kind of human error?
Comment: "overwrite the undo history" - no such thing in Vim, since Vim has undo *tree*. All you need to do is `:earlier 30s`. Or use one of the nice plugins that lets you visualise the undo tree (undotree, gundo, vim-mundo...) There's no reason for nerves.
Comment: Thank you for the answers to the second question, the paste function works well in the insert mode. However I'm still interested in the dangers of *inadvertent* pasting into the normal mode.
Answer: Type :set paste before pasting code, and :set nopaste after. See :help paste for more.
GUI versions of Vim, like MacVim or GVim, have much better OS integration than terminal Vim, and do not have problems like this.
Comment: paste is acting in insert mode only, and is great to keep the formatting, however it does not help in normal mode. GUI versions are handy, but very often inaccessible for me while working on embedded devices and/or over SSH
Answer: If you are working with terminal vim, then :set paste will put vim in paste mode and allows you paste in verbatim. This will avoid unexpected effects. More details at :help paste.
Also, you might like to :set nopaste after the pasting.
If typing :set paste/nopaste now and then bothers you, then you might like to have(in your vimrc)
set pastetoggle=<F11>
source ~/.vimrc

Now pressing F11will toggle "paste/nopaste" option alternately.
Comment: thank you for the pastetoggle hint, I have solved the toggle with the following mapping: `noremap  :set nonumber:set norelativenumber:set nopaste` and `noremap  :set number!:set relativenumber!:set paste!` .
this way i can also e.g. copy without line numbers


Clustering: Variance or Squared deviation from the mean?

Question: I'm studying performance analysis and in the summarizing data methods there's the clustering. I understood what clustering is and the various algorithms to clusterize data, however in my book (The art of computer systems performance analysis, Raj Jain) there's written (according to clustering techniques) the following:

What I really don't understand is that statistic formula about variance underlined in red. How can we talk about intragroup and intergroup variance in clustering? My professor said that this formula is correct just for SDM(squared deviation from the mean) but not variances since you can't divide by n-1 each cluster as they are not populated of n elements. So we should talk about intragroup SDM and intergroup SDM. Furthermore let's suppose I computed a PCA before clustering and that I selected just 2 principal components that explains the 93% of variance (here it's clear we can talk about variances). Then I compute clustering (Ward method), and dendogram shows me the intragroup distance according to the number of the cluster I choose. How do I extimate the total variance lost after doing PCA+ clustering? How could it be done if I have to extimate SDM and not variance after clustering? Why on my book that formula refers to variances? Thanks
P.S. I used jmp tool
Comment: [In statistics](https://en.wikipedia.org/wiki/Deviance_(statistics)) be deviance we rather understand the -2 times log-likelihood, are you *sure* you mean deviance..? How do you define it?
Comment: oh sorry you are right. That was a translation error. It's the squared deviation from the mean not deviance
Comment: just to be clear it's the variance multiplied by (n-1)
Comment: You are right with the terminology grievance. The book probably meant to say variability, or scatter, not variance, where "Sum of squares [of deviations]" stand for variability. In clustering, as in ANOVA or MANOVA, there is true that SStotal=SSwithin+SSbetween. Note that this [is related](http://stats.stackexchange.com/q/158210/3277) to the combined distance between clusters (their centroids).
Comment: As in ANOVA/MANOVA, variance or Mean square (MS) = SS/df. Df for "total" is N-1, for "between" is k-1, k being the number of classes (clusters). And pooled (i.e. weighted averaged) "within" variance has df=N-k.
Answer: Forget of PCA for now. You don't need PCA here.
k-means clustering (and Ward) are based on the idea of minimizing the sum-of-squares; and that value is related to variance.
There are different kinds of variance. Here you need the simple one, although it supposedly is biased. For large data, the difference doesn't matter. To understand that statement, assume variance is the simple $$1/N \sum_{x_i\in S} ||x_i - \mu_S||^2$$
And not N-1.
But now when looking at clusters, you want a cluster with many objects to have more influence. So for N objects, you take N times the variance. I.e., you take simply the sum of squares.
The proper version of the equation is
total-SSQ = within-cluster-SSQ + inbetween-clusters-SSQ = constant
It says that minimizing the SSQ (and equivalent, minimizing variance of a cluster) increases the separation of clusters; and conversely.
Answer: Intragroup variance is determining the variance within each cluster and combining them.  Intergroup variance is determined by the distance between the cluster centers. I think something similar to Cochran's theorem applies to allow these variance estimates to be summed.


How can I estimate the volume of a solid object, knowing only it's longitudinal corss-sectional area?

Question: Let's say the shape is too complex to split it into simpler parts and solve it analytically.
I can obtain it's longitudinal cross-sectional area by loading the image into an image editor, scaling it appropriately to the point where 1px$^{2}$ = 1mm$^{2}$, then by measuring the number of pixels inside the shape, I can get the approximate area.
Here is a simple example of what I mean
Since I know that this value is the result of evaluating this definite integral here:
$ A=\int_{a}^{b}r(x)dx$
And that the volume of a solid of revolution obtained by rotating the same shape around the x axis:
$V=\pi\int_{a}^{b}\left[r(x)\right]^2dx$
I'm wondering if by some method I can get from one to another?
Thank you in advance.
Comment: I had an intuitive feeling this was the case, but I was hoping to be proven wrong. :( Thank you for confirming my suspicions.
Comment: Is it known that the object has rotational symmetry?
Comment: Yes, it definitely does.
Comment: The thing is, you can't really go from $A$ to $V$ in a general case because different parts of the area are "weighted" differently - an area $dA$ twice as far from the symmetry axis than the same $dA$ closer to the axis will contribute twice the volume.
Answer: No, you need more information. For example, consider a semicircle of radius $1$. Then the area is $\frac{\pi}{2}$ and the resulting volume is $\frac{4\pi}{3}$. Now consider a rectangle of height $1$ and width $\frac{\pi}{2}$. Then the area is again $\frac{\pi}{2}$, but the resulting volume is now $\frac{\pi^2}{2}$.


How to throw an expectation_failure from a function in Boost Spirit?

Question: In Boost::Spirit, how can I trigger an expectation_failure from a function bound with Boost::Bind?
Background: I parse a large file that contains complex entries. When an entry is inconsistent with a previous entry I want to fail and throw an expectation_failure (containing proper parse position information). When I parse an entry I bind a function that decides if the entry is inconsistent with something seen before.
I made up a little toy example that shows the point. Here I simply want to throw an expectation_failure when the int is not divisible by 10:
#include <iostream>
#include <iomanip>
#include <boost/spirit/include/qi.hpp>
#include <boost/bind.hpp>
#include <boost/spirit/include/classic_position_iterator.hpp>
namespace qi = boost::spirit::qi;
namespace classic = boost::spirit::classic;

void checkNum(int const& i) {
  if (i % 10 != 0) // >> How to throw proper expectation_failure? <<
    std::cerr << "ERROR: Number check failed" << std::endl;
}

template <typename Iterator, typename Skipper>
struct MyGrammar : qi::grammar<Iterator, int(), Skipper> {
  MyGrammar() : MyGrammar::base_type(start) {
    start %= qi::eps > qi::int_[boost::bind(&checkNum, _1)];
  }
  qi::rule<Iterator, int(), Skipper> start;
};

template<class PosIter>
std::string errorMsg(PosIter const& iter) {
  const classic::file_position_base<std::string>& pos = iter.get_position();
  std::stringstream msg;
  msg << "parse error at file " << pos.file
      << " line " << pos.line << " column " << pos.column << std::endl
      << "'" << iter.get_currentline() << "'" << std::endl
      << std::setw(pos.column) << " " << "^- here";
  return msg.str();
}

int main() {
  std::string in = "11";
  typedef std::string::const_iterator Iter;
  typedef classic::position_iterator2<Iter> PosIter;
  MyGrammar<PosIter, qi::space_type> grm;
  int i;
  PosIter it(in.begin(), in.end(), "<string>");
  PosIter end;
  try {
    qi::phrase_parse(it, end, grm, qi::space, i);
    if (it != end)
      throw std::runtime_error(errorMsg(it));
  } catch(const qi::expectation_failure<PosIter>& e) {
    throw std::runtime_error(errorMsg(e.first));
  }
  return 0;
}

Throwing an expectation_failure would mean that I get an error message like this on an int that is not divisible by 10:
parse error at file <string> line 1 column 2
'11'
  ^- here

Comment: Can you create another rule instead of int_, which would match integer only when your condition is satisfied? I don't know Spirit well, but I would assume there is a rule similar to r_bool in AXE which wraps a predicate, it's quite common situation.
Comment: I think I'll need something like this, unfortunately: http://boost-spirit.com/home/articles/qi-example/creating-your-own-parser-component-for-spirit-qi/
Comment: Sorry to see that, it's very user unfriendly. That's why you need AXE :-)
Answer: You can use the _pass placeholder in phoenix to enforce a parse fail. Something like this should work.
bool myfunc(int i) {return i%10 == 0;}

...
_int [ _pass = phoenix::bind(myfunc,_1)]

Comment: @Frank please note, that setting _pass to false will only stop the current rule but not the parser as a whole with all the other rules (aka your grammar).
Answer: Years late but anyway:
If you absolutely want to throw an exception and want the on_error to catch it, you have to throw the expectation_exception from the qi namespace because the error handler on_error does catch nothing else.
This might apply to a semantic action or a custom parser implementation.
Would look like:
boost::throw_exception(Exception(first, last, component.what(context)));

where Exception is a qi::expactation_exception and nothing else.
If you do not have a component at hand like in a semantic action you must provide your own qi::info object instead of component.what(..).
You can throw from everywhere inside a context guarded by on_error.


Time Series Modelling[Issue with modelling the residuals]

Question: I am doing the sales forecast. I found the trend and seasonality manually for my time series data. Regressed time series data against the trend and seasonality and found the residuals. The residuals doesnt have autocorrelation(is this expected?). Verified the ACF and PACF plots and found no significant variables. What model to fit for the such residual data? It is normally distributed(confirmed using shapiro test) Any kind of guidance to move forward will be really helpful. I am new to the time series modelling
Please advice.
Thanks!
Answer: Post your data. It is ok to have a mean model and flat forecast.  If there are no patterns in the ACF/PACF and no outliers and no changes in seasonality/level/trend/parameters/variance you are ok!
See Rob Hyndman's words on flat forecasts
http://robjhyndman.com/hyndsight/flat-forecasts/
Comment: Apologies..I cant share data.. it is restricted..both my ACF and PACF have their first lag variable insignificant.. but 2nd, 3rd is significant..can i do time series modelling with such data? if yes, how many lag variables to consider?
Comment: It sounds like you might need an AR2, but what about outliers...are you looking for them??  You can scale your data by multiplying it by .23080744 for example and you won't be violating anything.
Comment: there are no outliers..i ve verified it.. why would you recommend only AR model? in my ACF plot, 2nd and 3rd lag variables significant variables as well..


Purely geometric derivation of the circle surface

Question: There are ways to get the surface or circumference of the circle by considering the areas and lengths of inscribed or Inscribing polygons. However this relies on using trig functions.
This is ok at first but ultimately trig functions when unpacked rely on coordinate definitions.
If one could define trig functions without introducing any kind of coordinate system or basis that would be fine too.
Purely geometric in this case means  completely clear of any coordinates or  any kind of ortho normal basis.
Essentially what it means to geometrically calculate the surface of a circle is to geometrically exactly calculate pi,
that is given some infinite series that converges to pi,or some recursive relation, show on purely geometric bases that that series in fact calculates the surface or circumference.
Archimedes used exhaustion to get an approximate value. Is there a way to get an exact value using similar axioms but no coordinates in any way.
Is this even possible, is it provably impossible?
Comment: What searching have you done and what has not satisfied you about the sources you have found? Archimedes, for example, used "areas and lengths of inscribed or inscribing polygons" long before anyone had the coordinate plane or named trig functions.
Comment: What reading have you done of the description?
Comment: I put the thing about archimedes just before I saw the comment I'll give you that.
Comment: To address your edit: Archimedes didn't just get an approximate value, The word "exhaustion" essentially refers to the error converging to zero.
Comment: I would appreciate reading and understanding what exactly the question is about.
Comment: No, he got only the approximate value, don't write nonsense here
Comment: This is a high level question
Answer: Archimedes' Work
I believe that Archimedes did what the question is asking for. While it's true that he famously put bounds on $\pi$, he also

showed that the area of a circle should be exactly $\pi r^2$ (phrased in terms of a right triangle with the same area as the circle) by demonstrating that errors in polygonal approximations approach zero
had a method for obtaining approximations to pi that could be continued in a recursive way (though it would require better and better approximations of square roots along the way).

The first point is summarized here on Wikipedia and elaborated on in these notes from Bill Casselman's History of Mathematics course.
The second point is discussed at these notes for Chuck Lindsey's History of Mathematics course, which provide a translation of Archimedes' work for his approximation (how he did the trig stuff without the language of trig functions, essentially) and provide a recursive procedure that could be continued assuming arbitrary precision square roots.
Explicit Recurrence
While algebraic formulas did not exist in the time of Archimedes, an algebraic recurrence based on inscribed polygons and the Pythagoran Theorem is discussed in places such as this page of Nick Craig-Wood. At that page, they mention that a square inscribed in a circle of radius $1$ has side length $\sqrt{2}$ by the Pythagorean Theorem. They also mention that using the Pythagoran Theorem twice gives the following recurrence for the side length $d_n$ of an inscribed regular polygon with $n$ sides:
$$d_{2n}=\sqrt{2-2\sqrt{1-\dfrac{d_{n}^{2}}{4}}}$$
We can turn this into a recurrence for a sequence of approximations of $\pi$. Let $p_n$ be the approximation corresponding to a polygon with $n$ sides. Since the circumference of this circle is $2\pi$, we have $d_n=2p_n/n$. Then we have
$$p_{2n}*\dfrac{2}{2n}=\sqrt{2-2\sqrt{1-\dfrac{\left(2p_{n}/n\right)^{2}}{4}}}$$
which reduces algebraically to $$p_{2n}=\sqrt{2n^{2}-2n\sqrt{n^{2}-p_{n}^{2}}}\text{.}$$
Starting with $p_4=2\sqrt{2}$, the first $10$ approximations to $\pi$ given by this recurrence are approximately $2.82843, 3.06147, 3.12145, 3.13655, 3.14033, 3.14128, 3.14151, 3.14157, 3.14159$.
Comment: But did he get a formula, a series that converges to pi? Do you have that formula, and can you prove geometrically that such a formula corresponds to geometry of the circle and area or circumference?
Comment: @Matko Algebraic formulas did not exist at the time he did his work. But you can take the geometry of doubling the numbers of sides of inscribed polygons to make a recurrence formula by using the Pythagorean Theorem. This is done at many places online, including https://www.craig-wood.com/nick/articles/pi-archimedes/
Comment: If you could get that reccurence formula in the answer I'll accept it as answering the question.
Comment: @Matko I translated that recurrence into one explicitly for approximating $\pi$ and edited it in.
Comment: That's exactly what I wanted to know


Como configurar Bootstrap 4 com Angular 8.3.6 utilizando angular.json

Question: Estou tentando configurar o Bootstrap 4 no Angular 8.3.6, estou seguindo os seguintes passos:

ng new novaAplicação (criar o projeto)
npm install bootstrap jquery popper.js --save (instalar bibliotecas)
setar arquivos CSS e JS no angular.json nos arrays de style e script conforme abaixo:
"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.css",
  "src/styles.scss"
],

"scripts": [
  "node_modules/jquery/dist/jquery.js",
  "node_modules/popper.js/dist/umd/popper.js",
  "node_modules/bootstrap/dist/js/bootstrap.js"
]

Inserir componentes bootstrap para teste no app.component.html. No caso coloquei um alert.

  A simple primary alert—check it out!

Quando rodo o servidor (ng serve) aparece somente o texto, sem a formatação do estilo, quando uso um componente que tenha algum tipo de movimento (dropdowns por exemplo), este movimento também não funciona. É como se não estivesse reconhecendo os arquivos (css, js) setados no angular.json.
A alternativa parece ser colocar os links(css e js) do bootstrap diretos no index.html, ou, copiar os arquivos para a pasta assets, porém não vejo como boa prática visto o manual mostrar da forma que detalhei inicialmente.
Abaixo a configuração:
Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.803.6
@angular-devkit/build-angular     0.803.6
@angular-devkit/build-optimizer   0.803.6
@angular-devkit/build-webpack     0.803.6
@angular-devkit/core              8.3.6
@angular-devkit/schematics        8.3.6
@angular/cli                      8.3.6
@ngtools/webpack                  8.3.6
@schematics/angular               8.3.6
@schematics/update                0.803.6
rxjs                              6.4.0
typescript                        3.5.3
webpack                           4.39.2

Comment: Mas vc viu se dá algum erro no console do navegador, se deu qual erro foi? Não sei se percebeu mas o caminho do arquivo Js do bootstrap no **angular.json** está com uma extensão inválida!
Comment: Olá LeAndrade! Não há erros no console quando executo o servidor, nem no console do browser e nem no terminal. Corrigi aqui a extensão do arquivo, vou corrigir aqui no post, mas continua com o mesmo problema, parece que as informações dos arrays (scripts, styles) não migram ao rodar o servidor.
Comment: É José, em tese era pra funcionar, parece que está tudo configurado corretamente, só não posso afirmar 100% pq nunca trabalhei com Angular na versão 8, pode ser que tenha mudado alguma configuração pra utilizar Bootstrap, pq até a versão 7, o que vc fez já bastava para poder utilizar.
Comment: Encontrei alguns alguns posts no forum do Angular relatando este problema na versão8 mas foram encerrados sem terem sido tratados, vou reabrir lá.
Comment: Você tentou usar o scss? Eu fiz um projeto recentemente com ele, mas ao invés de colocar no angular.json, eu coloco um import no meu style.scss.
Comment: Sim, é possivel funcionar se linkar os arquivos js e css no index.html, ou no caso do css inserir um import no style.css. Porém é uma forma de contornar o problema, e não uma solução conforme a proposta da ferramenta, acho que se trata de um bug, reportei no forum do Angular, estão checando, tendo a solução, colocarei aqui.
Answer: De fato adicionando no arquivo angular.json o bootstrap não carrega os estilos. Para resolver o problema, é necessário:

Adicione no seu index.html os scripts do bootstrap depois do app-root, dentro do body:

Importe o css do boostrap no seu arquivo styles.css:
@import '../../node_modules/bootstrap/dist/css/bootstrap.css';

Dessa forma, você aponta diretamente para o CSS do boostrap no seu index.html. Essa seria uma solução de contorno para funcionar o bootstrap com o Angular.
Comment: Sim, estou fazendo isso de forma paliativa. Valeu Giuliana.


Tools to improve sight-reading of rhythms

Question: So, there are a number of tools and strategies to learn to sight-read pitch.
I mean, you just make flashcards and in a while you should be able to read comfortably all notes on all staves, right?
But rhythm is a different beast, isn't it?
If you make flashcards of rhythms, I suppose, you'll memorize those specific rhythms you have made flashcards for.
What is your strategy?
Thank you!
Answer: I would recommend getting a copy of Hindemith's book:
Elementary Training for Musicians
In the early chapters he has masses of exercises in sight-reading rhythmic patterns, both as single-line rhythms, and also more complex ones where you have to tap one rhythm while playing another rhythm (very useful for pianists).
The book is also extremely useful for lots of other aspects of musicianship. I have been delving into the book for years - and still not mastered all it contains (maybe I am just a slow learner!)
Answer: For jazz guitar there is a standard book by William G. Leavitt called Melodic Rhythms for Guitar. It has lots of examples of so-called "rhythm groups" of increasing complexity. Playing through this book greatly improves sight-reading of rhythms. And this is also the clue: there's no shortcut. You have to sight-read in order to learn it. In my opinion you shouldn't waste time on looking for some magic tools, just sit down with a piece of music and play. Of course, it's important to use material that is not beyond your level, but that should be easy to find.
Comment: Isn't a book with "rhythm groups" a magic tool in itself? :-)
I'll look for it, thanks - but, I'm no guitarist, I hope it's still a valid suggestion.
Comment: @SomeDudeOnTheInterwebs: Yeah, you're right. I was more referring to flash cards etc., because I think they're not really to the point. [This link](http://bbamusic.wikispaces.com/file/view/Melodic+Rhythms+for+Guitar+-William+Leavitt.pdf) might be helpful.
Comment: I agree the best approach is to find a method book that focuses on progressively complex rhythms.  The real 'trick' to learn is how to subdivide and to keep a consistent '2-Dimensional' internal metronome that operates in a cyclic motion (i.e. 1 2 3 4 1 2 3 4 . . . . round and round).  Subdivision will allow you to calculate syncopation and some polyrithms, while the circular metronome will grant you awareness of where the downbeat is and how it lines up with the downbeat of musicians you're playing with.
Answer: It will depend a little on the instrument. For example, rhythm guitar with lots of strumming will be slightly different from picking out a melody on, say, a clarinet. Yes, the rhythmic pattern will be the same, but its execution is different, as is reading chord symbols as opposed to dots.
Tapping a foot is always good, as is internalizing the basic beat with a part of your body. My violin teacher used to sniff in place of rests, to keep them in time and place. (Christine Perfect's (McVee)  dad, namedropping!) It worked well, but didn't sound too good.
Metronome will get a mention - sometimes it can be set for twice or thrice the speed to keep more accurate time.And of course, counting out loud. 1e&a 2e&a et al.
Put the radio etc on and tap along using different patterns, there are literally thousands to choose from, and visualise them as you tap. 'This is 4 quavers, a crotchet, 4 quavers and a crotchet' sort of approach.The good thing about this is you don't need an instrument - it could even happen as you drive along. Explaining to the law may be tricky!
Comment: The idea of taking rhythmic dictation from the radio never occurred to me - thanks. +1'ed
Answer: A good idea is to start with the note that is the shortest and make that one beat and count the other notes in relation to the smallest notes.
So for instance if you are in 4/4 time and the shortest notes in the piece is quavers you make the quavers one beat, the crotchets 2, minims 4 and semi breves 8.
It is not a perfect method. You run the risk of either having to count to 8 really fast if the tempo of the piece is brisk or playing the piece much too slow but for a means to teach the basics of rhythm to new players it has merit. When you get the rhythm down you can much easier learn to play the piece in time and faster later.
Answer: Just a different sort of flashcard. Get some blank postcards and a black marker pen and in your best musical handwriting, notate a rhythmic pattern lasting one crotchet on each card. Each single card could contain for instance (a non-exhaustive list):

crotchet
quaver quaver
crotchet rest
dotted quaver semiquaver
semiquaver semiquaver quaver rest
Triplet quavers
etc.

Create duplicates of each card.
Then shuffle and deal four cards in a row. Set your metronome and try to read the rhythm, looping around so you're playing the same bar over and over again.
Pick up the left-hand card and move it to the right hand end, or exchange two cards. Or replace a card with one from the pack. You get the idea.
Comment: This is a awesome idea I didn't think of (although needs devising a sorting algorithm, since existing ones work with one card a time).


JQuery in JSF get element by id

Question: I created a web page that print some text using JSF
I've added spaces using tag

between each word
I want to decrease the width value to 12 when browser window size getting smaller
I know it's possible to do this using Jquery.
Can someone please guide me?
Answer: You can use

and use jquery to change the width using
$('.spacer').attr('width','12px');

To detect the browser resize you can use
$(window).resize(function() {
   // put here a check if window is smaller than what you want
   // and set your spacer size accordingly
});

But wondering, why don't you just use a percentage for the width? then it will scale automatically

JQuery in JSF get element by id


My jazz guitar doesnt sound like jazz

Question: I mainly learned the major scale and minor pentatonic. I have a fairly good grasp of music theory, but I guess my harmony area is lacking when it comes to chord naming etc. I understand most intervals like a dominant 7th chord is simply the chord constructed from the 5th mode of the major scale or Mixolydian and includes the 7th.
So I try noodling around and at first it just sounds like major scale. So then I practice some arpeggios and basically hitting through 3,5,7 intervals through the modes. It helps a little, specially with a little sliding and I think the 4th and 5th and 7th sound somewhat interesting.
I also just tried playing all over the place like minor pentatonic up then slide up 4 frets and go down in new key with minor pentatonic with passing notes and this sounds a little better or more like jazz.
So I'm wondering if maybe I need to frequently change keys? Learn chords better and change like every measure? More passing tones into the major scales? Basically if anyone has felt they had thos kinda of issue and solved it, maybe they can give me suggestions.
Comment: Have you started with blues before moving into jazz? With the more static harmony, it is easier to come up with pleasing improvisations in a blues setting. There you can start developing motifs, which in my mind is what makes improvisations coherent. If you want to get the most out of pentatonic scales the book Pentatonic Khancepts by Steve Khan is recommended. It shows how to apply pentatonics in about all kinds of harmonic settings, for common jazz progressions etc.
Answer: Though your question is vague, I think I get the problem by reading between the lines. You know some scales and theory but when you try to play over changes it sounds like you're still doing exercises rather than "playing jazz"? If so, that's a common problem and just another hump to get over.
You're definitely on to something with arpeggios. Scales are good to know in general and they're helpful to have under your fingers at times when playing lines. But if you simply play scales your lines won't sound very melodic; they'll sound like scales.
It's usually better to think about the chord tones. Make sure you know your diatonic 7th arpeggios really well. Practice the song for a bit by playing only the arpeggios over the given chords.
Then practice patterns using the 3, 5, 7, and 9 of the chord. Another way to look at this is superimposing the diatonic arpeggio that's a 3rd above the given chord (ex. Dm7 -> Fmaj7). By shifting up a diatonic 3rd like that you're adding the 9 while omitting the root. Get used to playing those notes in various patterns (up, down, pivoting up and down octaves, etc).
Or another simple approach is to combine triad pairs. For instance if you take any 2 adjacent diatonic triad pairs in a given key (ex. F, G in the key of C) you'll get a 6 note scale that contains that entire key minus a note. So then by alternating back and forth between playing an F triad arpeggio and then a G triad arpeggio in various inversions you'll be covering a lot of ground and playing most of the notes in the key of C. But the triads will sound more melodic than simple scale steps.
Those will get you sounding more melodic within a single chord, but then you need to sound like you're playing over changes as opposed to single chords. Look into using target notes (hitting essential chord tones on the down beat when changing to a new chord) and more specifically into guide tones (using the 3rd and 7th degrees to connect chords via a half step).
For instance, given a ii-V-I in C you have Dm7 | G7 | Cmaj7. The 7th of the Dm7 (C) at end of one measure can move a half step down to the 3rd of the G7 (B) on the first beat of the chord change. Then you can do the same thing with the G7 by moving from the 7th (F) down to the 3rd (E) of the Cmaj7. Using these guide tones will get you those lines that flow through chords and sound never-ending instead of sounding like you're playing individual phrases over each chord.
And of course, there are plenty of other things to think about like quoting and altering the original melody, stealing idiomatic licks from records (if want it to you it to sound like "jazz", then steal and analyze some licks from jazz records that you like), etc. But thinking in chord tones and how they connect between changes will get you a good part of the way there.
Answer: Forget scales and chords for now.  The algorithm you want:

Find some jazz you like.  Pick a tune with a solo you love that isn't too complicated.  Ideally something you know so well that it's almost memorized.
Try to sing the solo (or just part of it, to start).
Try to play the solo on your instrument, or part of it.
Try singing your own solo along with the song.  (Or if you have some sort of play-along version of the same tune, that could be ideal.  Band-in-a-box or iReal Pro or Aebersold play-alongs.)
Try to play something like the solo you just sang.
Go back to step 1.

In fact, if you get stuck at any point along the way, you can always go back to step 1, it's an important step.
The idea is to get the basic language drilled into your brain, and to develop your listening and playing-by-ear skills along the way.
OK, and actually don't really forget scales and chords.  You'll find they give you some framework that helps you identify what you're hearing.  But it's probably best if you learn to sing them and how to recognize them when you hear them, and not just how to play them.
Disclaimer: I play terrible attempts at jazz solos.  But to the extent they sound like attempts at jazz solos, and not just random noodling, I credit some listening and transcribing.
Answer: While noodling has its place, it is not a good strategy for learning jazz guitar. Listen to tons of jazz. Identify phrases that interest you and try to play them; try to figure out what keys the phrases are in, and play them everywhere on the neck, in every key.
I would suggest learning the triads everywhere on the neck of the guitar (major, minor, augmented, diminished). These can be a base for chord-building, but also can be used to construct solos that outline the harmonies of a song. Apply this new knowledge to some Standards, creating solos from only chord-tones; try to work in some of the phrases you have lifted from your favorite tunes. Once you gain some facility with triads, you can add some color with flatted fifths, sixths, ninths, elevenths, etc. Or you can do some chord substitutions with the triads. You can get a lot of mileage out of triads, and then use scales to build on this base.
But, the best thing you could do is find a good teacher to guide you through the beginning of this lifelong process.
Answer: Focus on Rhythm, Not Harmony
I would suggest that the root of your issue is not harmonic, but rhythmic. Your post suggests that you're already in very good shape harmonically. It also seems like you probably have good technical control too. You've made good scale choices, you're already emphasizing the 1, 3, 5, and 7 of each chord, and you're using some passing tones (chromatic leading tones go a long way to make lines sound jazz-y). You're using pentatonic scales too, which can sound really nice when played immediately after/before scalars lines with chromatic passing tones.
So you're already doing things right, harmonically speaking. We can probably rule that out as the main problem, which leaves rhythm as a likely area to focus on. In fact, the issue you've described is extremely common among players who are technically proficient but new to jazz.
Rhythmic Phrasing
On guitar and piano, the challenge to play something rhythmically interesting is greater because nothing forces us to break up our phrases. By contrast, horn instruments have to think about phrasing, because they must stop playing every now and then to take a breath. But piano and guitar can play eighth notes ad nauseum with no pauses or rhythmic variations. It doesn't take long for this to stop sounding like jazz. Phrasing is really important in improvisation.
There are a lot of ways to introduce more rhythmic diversity into our playing. David Berkman told me once to choose a player who excels in this (he mentioned Kenny Kirkland) and transcribe & learn to play many their solos. One of the all-time greatest masters of this was Charlie Parker. And in general, you'll find a lot of interesting rhythmic variation in bebop music. The dotted quarter is a cornerstone of those rhythms. Transcribing full lines and phrases is ideal, but you can also try simply adding dotted quarter spacing between two notes. For example, if you play four eighth notes and end the phrase on the upbeat of 2, then you can start your next string of eighth notes on the downbeat of 3. Another technique--which is somewhat similar to the dotted quarter--is the use of a repeating 3-beat cross-rhythmic pattern. For example, here's four bars of bebop-style improvisation in F major:

The very first phrase is played first starting on beat 1, and then a second time starting on beat 4. We could repeat this lick a third time, starting on beat 2 of measure 2. This is a 3-beat lick, and repeating it a few times creates a nice cross rhythm to the 4/4 time. This rhythmic tension catches the ear. At the end of measure 3, we also see the dotted quarter spacing, which interrupts the eighth-note lick. The C on beat 3 is followed by a B♭ on the "and" of 4. This adds rhythmic variety, which makes the line rhythmically interesting and gives it a jazz-y/bebop-y feel.
Eighth Note Groupings & Accentings
As described above, we often hear bebop musicians achieving rhythmic variation through rests and/or variations in note duration. The dotted quarter is a quintessential note spacing. But there are other ways to create this rhythmic grouping, structure, diversity. Even if you're playing a long run of eighth notes, you can still create rhythmic emphasis by grouping notes a specific rhythmic pattern:

This is a Charlie Parker-esque lick, and you can hear something similar on his 1942 version of Cherokee at ~1:41. Every note has the same duration and there are no rests. But despite this, we still see a 3-beat, 3-beat, 2-beat rhythmic pattern. I've highlighted the first note in each grouping. The 3-3-2 pattern appears in the first two bars and again in the last two bars. The 3-beat group contains 6 quarter notes, and it effectively creates the same 3-beat cross rhythm discussed above. The accents contribute to this rhythmic pattern, emphasizing the first note in each group (among other things).
Feel
Beyond rhythm, there is one last element to the playing that can make your lines sound like jazz: the feel. We want the lines to swing. This doesn't necessary mean playing swung eighth notes. In a lesson, Gary Smulyan once told me that modern swing means playing straight eighths slightly behind the beat with a small accent on upbeats. Finding a good swing feel can go a long way to improving the sound of lines that are already harmonically interesting.
Comment: Thank you for great answer. Its hard to pick one over the others but I think your on to something.  I have always enjoyed rush type of abrupt rhythm change to I am at least aware of rhythm, but I probably do every thing in 3/4 time and 3 notes per string due to my neglect for rhythm. Probably needs more of my attention.

My jazz guitar doesnt sound like jazz


How can I display GUI while testing PyQt5 app with pytest-qt?

Question: I am new to PyQt, but I am going to use pytest with pytest-qt plugin to test my PyQt5 application. I had some GUI testing experience in Java with SWTBot and RCPTT, where I could see what happens with controls and whole GUI during the test in real-time. I'd like to have such behavior with my new python tools, but it seems that pytest-qt tests GUI in some background way. All code works as I expect, but during testing I can't see the GUI. The code is simple as in tutorials:
from tests.test import MyApp
from time import sleep
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

def test_myapp(qtbot):
    app = QApplication([])
    window = MyApp()
    # window.show()
    # app.exec_()
    qtbot.addWidget(window)
    qtbot.mouseClick(window.buttonBox.buttons()[0], Qt.LeftButton)
    sleep(5)
    assert window.label.text() == 'accept'

If I uncomment the window.show() line (they do so in the tutorial), I can see a strange window, that contains frozen background:

I suppose that it is theoretically possible to show the interface because I know that PyQt5 works from the python shell (more):

you can, for example, create widgets from the Python shell prompt, interact with them, and still being able to enter other Python commands

But I don't know how to achieve it with pytest-qt
Answer: This code works as I asked, it shows the interface properly. The key thing is qtbot.waitForWindowShown(window) line.
from tests.test import MyApp
from time import sleep
from PyQt5.QtCore import *

def test_myapp(qtbot):
    window = MyApp()
    qtbot.addWidget(window)
    window.show()
    qtbot.waitForWindowShown(window)
    sleep(3)
    qtbot.mouseClick(window.buttonBox.buttons()[0], Qt.LeftButton)
    assert window.label.text() == 'accept'
    qtbot.stopForInteraction()

Comment: This answer led me to the right place (thank you!), so I'll make a note that as of 2022 `waitForWindowShown` is deprecated ("underlying method was obsoleted in Qt 5 and removed in Qt6"), in favor of `waitExposed`.  The latter should be used as a context manager so the format is a bit different, but it works just as well (at least for me).


Estimate the cumulative baseline hazard function from a Cox model coefficients

Question: CoxPh model described as $h(t|X)=h_{0}(t)e^{\beta X}$ where $h_{0}(t)$ is the baseline hazard function and is non-parametric. If you have the following model,
require(survival)
surv_object <- Surv(time = ovarian$futime, event = ovarian$fustat)
fit.coxph <- coxph(surv_object ~ rx + resid.ds + age_group + ecog.ps,
                   data = ovarian)
(fit.coxph)
The cumulative hazard function of the above model $H_{0}(t)$ can be obtained in this manner cumulativeHazard<- basehaz(fit.coxph) and the smooth baseline hazard function can also be obtained using the method described by Royston
But, assuming you neither have the access to the fitted model (in this case fit.coxph) nor the data used in modeling (in this case ovarian), instead you have access to the model's exponentiated coefficients $\beta$ (hazard ratios), sample size $n$ (in this case n=26), and the number of events $\delta$ (in this case $\delta$=12). Typically, this is what is found in the results of the most published papers(data is never published)
To my question, how can one estimate/approximate the cumulative hazard function $H_{0}(t)$ or even baseline hazard function $h_{0}(t)$ from the available information.
Many thanks
Comment: The baseline hazard function and the cumulative baseline hazard function are functions in time $t$. Do you have any information about the mean censoring times and/or mean event times?
Comment: Do you have information about the estimated survival probabilities? The cumulative hazard is the negative log of the survival probabilities, i.e. $H(t)=-log(S(t))$. Thus, if you have $\hat{S}(t)$, you can get the estimate $\hat{H}(t)=-log(\hat{S}(t))$.
Comment: @Nussig Yes, mean censoring time is provided sometimes. For example, using the ovarian data, the mean event time is  351.3 from `mean(ovarian$futime[ovarian$fustat==1])`
Comment: I was thinking along that lines that if you have no covariates, or maybe just two groups, you can estimate the baseline hazard function under the assumption of an exponential model by dividing the number of events by the total exposure time.
Comment: @Nussig could you kindly elaborate this comment in the answer section. It is a useful thought
Answer: The Cox proportional hazards model does not estimate the baseline hazard. This was originally the aim of being semi-parametric (i.e., in a proportional hazards model distributional assumptions for the event times are "hidden" in the baseline hazard).
To get an estimate of the cumulative hazard function (and then also of survival probabilities) typically the Breslow estimator is used. This a non-parametric estimator that similarly to the Kaplan-Meier estimator is calculated based on when the true events occurred and the number of subjects at risk at these time points. There are also many other alternatives proposed in the literature, such as the smooth baseline hazard function of Royston that you mentioned.
Coming back to your question, and based on what was described above, it is not possible to estimate non-parametrically/flexibly the cumulative baseline hazard without having access to the time points at which the events occurred. As Nussig suggested, one possibility to get something would be to assume an exponential distribution under which the baseline hazard is constant. However, this is a very restrictive parametric assumption that is often not realistic.


Why does compression seem to improve the fidelity of recording?

Question: I understand the basic idea of compression: increase low amplitude, decrease high amplitude to some 'normalized' middle range.
I especially understand how the effect enhances electric guitar to turn the normally fast decay into a slower decay and good sustain.
But when compression is applied to a vocal signal - one where a notes are held and sung in the mid-range of dynamics - what is happening to the signal? If it's already sustained an mid-dynamic range, it would seem the compression doesn't have anything to change.
Yet when I have recorded myself singing (in the privacy of my home to save others the misery hearing me!) the uncompressed sound was 'thin' while the compressed sound was fuller. It's hard to describe the difference. Certainly just turning up the level on the uncompressed track did not sound like the compressed one. Even singing with a full, resonant voice, the uncompressed track had no 'presence', poor fidelity to what could be heard in the room. Compression made the track sound much more like what I could hear in the room.
I also noticed the same thing when recording acoustic guitar with a microphone. Even close miked, with playback level up the sound was thin and dead. Adding compression didn't really change the sustain of the acoustic guitar, but the sound brightened up and had presence. It sounded like what I heard in the room when playing.
Somehow compression made the miked tracks sound much more like the room sound, but I don't know why. It's like the dry recording just lost lots audio detail and compression magically restored it. That seems different that just compressing amplitudes to some ideal middle range.
In case it helps my mic is something like a Shure PGA48. I don't remember the exact brand and model, but it's shaped like that and the price was entry level.
The compressor was a plugin that came with PreSonus Studio One. I don't have the gear set up now (I didn't have space to keep it set up and so packed it away.) I'm not absolutely certain, but the interface image below is what I remember. I don't remember how I set it, but changing the 'knobs' changed the graph line, and I didn't know how to read the graph, so I probably left it at presets which may not be what is pictured. I wish I could be more specific, but I don't remember exactly what I did. More importantly to me, I mostly remember that just adding the effect did the job. I didn't need to mess about with the settings.
Comment: "Higher Fidelity" Is rather a psychological effect caused because you are hearing a Louder (Not Intensity, Loudness as in LUFS/Mean Intensity of a Recording) Version. What is happening is Loud Parts of the Spectrum are kept Unchanged/Slightly Reduces and The Softer parts are kicked up, making the spectrum fuller as Overtones are now Louder than Before. This as said in a below answer will not always increase quality but rather decrease quality. It's your brain that's thinking that it's of higher quality just because it is louder.
Answer: They don't always improve the quality or fidelity of audio. With the right parameters (or in many contexts, wrong parameters) compressors can:

Completely change the dynamics of a performance, aka a good chunk of the performer's vision (and often the composer's and producer's and everyone else's but you vision too).
Induce tremolo-like artifacts.
Induce distortion.
Kill the attack.
Alter the timbre, not always in an expected way.

Maybe some distortion is fine in rock, but in a classical music context it might be considered "bad fidelity" or "bad quality". Context here includes your subjective personal tastes, and the specific traditions or conventions each genre and listening setting has and expects. Same for the other stuff. The right parameters in the right context can make it sound more professional, or with "more fidelity", but wrong parameters can make things sound awful just as easily.
If you are not using presets, or a compressor designed for laymen, it's not easy to make a compressor add to the performance. What's actually easy is to make the effect unnoticeable, or affect the audio in a negative way performance-wise and context-wise.
If everything you throw into a compressor comes out sounding with more "fidelity", one of two things is happening:

Pure luck, coincidence that the initial parameters happened to shape that specific audio track into something you liked better than the dry version.
You are using a compressor or preset designed from the start for your usecase.

what is happening to the signal? If it's already sustained an mid-dynamic range, it would seem the compression doesn't have anything to change

If the threshold isn't reached, nothing is happening to the signal. Not all compressors behave this linearly, so what's exactly happening depends on the compressor. If the signal is dancing around the threshold, and specially the voice where compression ratios are traditionally low (assuming a good singer, and some styles do highly compress vocals even if the singer is awesome), what you are hearing is just a little bit of compression, that can turn good dynamic control from the singer into awesome-out-of-this-world dynamic control, but this requires a mixing engineer that knows the tools.

Yet when I have recorded myself singing (in the privacy of my home to save others the misery hearing me!) the uncompressed sound was 'thin' while the compressed sound was fuller. It's hard to describe the difference.

What compressor did you use? Some compressors do not act linearly over frequency, so they compress some frequencies more than others (without the control of a multi-band compressor). Or perhaps you used a compressor with multi-band functionality. Even more linear compressors can sound different on different frequencies because of psychoacoustics.
The point is, maybe you equalized the audio without knowing, perhaps making the lows more noticeable (equalization or psychoacoustics can do this), making the sound less "thin", but it's hard to know and analyze without knowing:

The compressor you used
The settings
It's behavior
The actual details of the audio you used (sustained stuff, transient stuff, etc)
Exactly what you mean by "thin"

That's on the frequency side of things. On the amplitude side of things, unless you are a trained musician, your dynamic control is not on point. A compressor can mask that, making the voice more controlled.

Why does it sound better / more professional?

Coincidence, probably. Did you use a preset? Maybe the preset was tailored for guitar and voices. Did you not use a preset? Then maybe it was your knowledge on compressors! If you didn't use a preset and don't know much about compressors, then it most likely the initial patch of your compressor is not initialized to 0, but to something tailored for voice and guitar (which are very common things in music in general).
But compressors can also make things sound awful. It's not just a box that you can connect stuff to and make things sound better.
They tend to make things sound better because that's what they are designed to do. Performers with no control over dynamics sound amateur. Performers with high control over dynamics sound professional (assuming they have control over everything else). The compressor controls dynamics, so can take some care of that for you.
It can also alter our perception of tone (again, even in single-band compressors, but maybe you did use a multi-band compressor), making things sound "brighter", "darker", "more mellow", "thinner", etc.
Comment: the compressor was bundled vst plugin that came with Presonus, I don't have the gear set up so I can't get the exact software name, I took the preset and probablt tweaked it a bit but I didn't really understand the controls, sorry, that's still probably too vague to help much.
Comment: Added an image of the plugin, don't know if that provides any helpful detail.
Comment: This answer is really a bit too pessimistic. –Yes, good singers don't really need compression – but even for them, it can actually make sense because it has other advantages besides _controlling dynamics_. –Yes, a badly set up compressor can make things sound bad (as can any effect), and to set it up perfectly you need a good ear and experience... but many compressors are in fact easy to set up in such a way that it's musically benefitial. A good-quality 3:1 soft-knee compressor with 10ms attack, 50ms release works out-of-the-box for lots of signals, only requires tweaking the threshold.
Comment: @leftaroundabout You say the answer is too pessimistic, but then go on to repeat and copy every single thing i already said in your comment and your answer, so I'm not sure what your point is. 1: Physics and audio processes don't really care how pessimistic or optimistic you are. 2. I was just accentuating the notion of OP that compressors just make stuff sound better no matter what. As I see it, you completely missed the point, we'll have to agree to disgree on this one. No matter how hard you are smiling, you need to tune a compressor for the particularities of any given input.
Comment: @MichaelCurtis  Some compressors ('character' compressors)  significantly alter the signal in various ways. Perhaps yours is one of them. .
Comment: I didn't say "compressors just make stuff sound better no matter what". I don't remember the settings, assume it was close to a preset, like the in the picture I added. As @leftaroundabout said, any effect can be made to sound bad, but I didn't change it much from preset. My perception was a change of _tone_ not _dynamics_, but don't understand why.
Answer: Most of the reason a compressor makes a given signal sound better is indeed simply that it allows you to turn up the gain – much more than would be possible without compression, because then it would either run you into headroom limitations or drown out some other instruments in the mix because the peaks are too loud.
But yes, compression also has a bunch of other results. One you have noticed is that it makes mic recordings "roomier". The reason is that whenever there is no direct sound, the compressor opens up, amplifying any remaining reverberations. Whereas when there is signal, the compressor pushes it down. So the overall dry/reverb ratio is decreased, which is what you would also get with more reverb. However, compressor-boosted reverb has the advantage that it doesn't mingle as much with the dry signal, and therefore can in practice come out as less "muddy". Of course you may or may not want this; for a silky smoothening reverb, compression isn't really useful.
Another consequence of such "level-ratio changing" is what you probably mean by "sound fuller". What makes a voice sound full are the actual tonal parts, vocals and voiced consonants. But except for classically trained singers, those are actually not the loudest bits of a vocal track. If instead hard unvoiced consonants, particularly plosives and s-sounds, stick out as the loudest, then this makes the whole track appear thinner. A compressor can reduce the level of those sounds while boosting the soft tonal components. It can make sense to use a high-pass filter in a sidechain to make the compressor focus on consonants even more. A compressor with very high sidechain highpass is called de-esser.
For guitar this also works similarly: the compressor masks away some of the thin-sounding transients, leaving in relation more of the actual notes.
Then there is the fact that real-world compressors, especially analogue ones based on tubes and/or optoelectronics, introduce quite a lot of distortion – but a smooth kind distortion, which is not very overtly notable yet works out to be pretty useful musically. This is something you also get without a designated compressor, by simply running the mic through a tube preamp. The resulting distortion is itself a kind of compression: it clips away some of the higher-peak components and allows boosting the softer elements. Furthermore, distortion forces the wave shape during voiced consonant to more follow the coherent voice component – that too helps with "full sound". And finally, the distortion introduces some extra harmonic overtones. This first of all makes the signal more present or "transparent", something which is often desired in vocals. Engineers often put a treble boost on vocals, but boosting high frequencies has the obvious downside of making it sound thinner too. Distortion from a tube or compressor helps making treble boost less necessary, so in the end you'll have fuller-sounding vocals in the mix.
Comment: Would close miking exacerbate the ratio of hard consonance (and I suppose miked acoustic guitar sharp attack sounds) to voiced sounds. I imagine it would. That kind of triggers my memory that I could hold the mic away - sing more to the room instead of the mic - after the compressor was added. Sorry for the vagueness. I did the recording a long time ago, but the compression part of what I tried has always nagged me.
Comment: Mic distance again has a whole bunch of different effect. I wouldn't say close miking exacerbates consonant problem _in general_, but it might do so in specific situations.
Answer: There are actually two types of compression:

Normal "in line" compression, where the signal goes into the compressor and out again. This has the effect of making the loud bits of the signal quieter - but extra gain is then usually applied to bring up the overall level. This is basically "squashing the peaks".
Parallel compression. This is where the original signal is compressed as above (often quite heavily) and then mixed in at a lower level with the original. This was standard practice on vocals on Motown recordings. The overall effect is to make the quieter parts louder. This is often great on vocals as it tends to make them sound more "present" without actually sounding as if they are compressed - because the peaks are pretty much unaffected.

Unless it is done badly, compression should not introduce appreciable distortion or alter the overall frequency content significantly.
It could well be that the compressor configuration you are using is actually making the room reverb in the original louder. Without seeing how it is configured, it's not possible to say for sure.
Comment: Parallel compression per se isn't really any different from in-line compression with lower ratio. The reason sounds different in practice is that analogue (or modelled) compressors _do_ introduce significant amounts of extra distortion.
Comment: It's a subtle argument. Analogue VCA's exist since at least the 90's which are practically distortion free - but you can't vary the gain of a circuit over a few ms and *not* introduce distortion, so even an "ideal" compressor *will* introduce artefacts. In series compression you gain reduce peaks by not much, but you do it to *all* of the signal. In parallel compression you only treat (say) 20% of the signal, and you hammer the hell out of it. But you still have 80% of it untreated, which seems to sound more natural. What you say is in essence true. Anyway, there is a big audible difference.
Answer: The other answers seem to be addressing ways to alter (and ideally enhance) the original audio waveform.  Here's an alternative.
Way back in the vinyl days,  the RIAA curve was developed as a way to reduce background noise related to the physics of turntables and contact with the vinyl. Quoting bits from Wikipedia,

The purposes of the equalization are to permit greater recording
  times (by decreasing the mean width of each groove), to improve sound
  quality, and to reduce the groove damage that would otherwise arise
  during playback. RIAA equalization is a form of pre-emphasis on
  recording and de-emphasis on playback. A recording is made with the
  low frequencies reduced and the high frequencies boosted, and on
  playback the opposite occurs. The net result is a flat frequency
  response, but with attenuation of high frequency noise such as hiss
  and clicks that arise from the recording medium. Reducing the low
  frequencies also limits the excursions the cutter needs to make when
  cutting a groove. Groove width is thus reduced, allowing more grooves
  to fit into a given surface area, permitting longer recording times.
  This also reduces physical stresses on the stylus which might
  otherwise cause distortion or groove damage during playback.
A potential drawback of the system is that rumble from the playback
  turntable's drive mechanism is amplified by the low frequency boost
  that occurs on playback. Players must therefore be designed to limit
  rumble, more so than if RIAA equalization did not occur.
RIAA playback equalization is not a simple low-pass filter. It defines
  transition points in three places: 75 μs, 318 μs and 3180 μs, which
  correspond to 2122 Hz, 500 Hz and 50 Hz (rounded values)

Prior to this standard,  each record company had a slightly different compression scheme, which of course raised hell because a record player only had one playback filter curve.
Fast-forward a couple decades, and Dolby comes out with curves to handle tapes (primarily hiss) and to match acoustics in movie theatres.
Well after that comes the start of digital companding techniques.
The point is that all those early methods were primarily aimed at eliminating noise for analog recording and playback systems.  These were essentially "lossless" except where the original SNR was poor enough that filtering couldn't separate noise from signal.
For that matter, the knobs on your stereo preamp let you tweak the compression to your personal taste.
Comment: @CarlWitthoft Dynamic compression / expansion is *completely* different from equalization. Maybe you can see a multi-band compressor as a smart equalizer, or use an equalizer and a compressor to make a dynamic equalizer, but they are both very different tools, used to do very different things. Can you explain why you think they are "not really different"? Very interesting assertion!
Comment: I sort of follow this, but to me - who is not a sound engineer - it seems like the text jumps from EQ to compression. I surmise from this and parts of the other answers that compression and EQ are linked. I updated my answer with an image of the compressor interface. I'm not sure what in that compressor would be effecting EQ.
Comment: The RIAA curve is not compression, but an EQ curve. It did not change the dynamic range of the end result, it merely encoded the audio in a format that was more suitable for cutting/reading grooves in plastic than the orginal signal. RIAA, unlike compression, was supposed to be transparent.
Comment: @Hobbes  point taken, although dynamic compression/expansion is not really different from equalization.
Comment: EQ boosts/cuts certain frequencies, regardless of their original level. Compression changes the signal dependent on its level. Seems a pretty big difference to me.
Comment: "the knobs on your stereo preamp let you tweak the compression to your personal taste". No, this is plain wrong. Stereo preamps don't contain compressors. And RIAA equalisaaion is just a filter, not in any way a dynamics processor. It's a different beast.


How to open Bootstrap Photo Gallery on page load?

Question: I am using Bootstrap Photo Gallery, and would like to open the slideshow when the page loads.
Answer: Add your gallery into model window then used #modelid in then then gallery is automatically load when your page is loaded.
<code><script type="text/javascript">
    $(window).load(function(){
        $('#myModal').modal('show');
    });
</script>
</code>
Comment: It would be  jQuery('#bootstrap-gallery').show(); but it doesn't work. Doesn't create an error either but blocks off access to the gallery. Additional complication - borderless gallery option' which says it doesn't use modal. Closest I got was with >  window.bootstrap.Gallery(jQuery('.view-photographer-of-the-year  a'), jQuery('#blueimp-gallery').data()); FInding an unminified version of the drupal code is hard.


Passing context to a block field of a display suite node

Question: I have a view that displays results of nodes.  In these nodes, I have a block field via Display Suite (a table view from Commerce Add To Cart Extras).  The block View renders fine in a full node display, since I can easily pass the contextual filter, but I need this block field to also render in the node when it's a teaser as a result of a View.
I tried looking at the Views default from context module, but I can't seem to get it.  How can I get my views in my teaser to just know what the context is within its particular node?
I hope this makes sense.
Comment: When I look in devel, for each node, I see the correct product ids in my product ref field.  So, it looks like the context is getting passed.  So I guess it is a rendering issue.
Answer: The way to do it:

Enable Views content pane (views_content, part of ctools I think)
Create a Views display using content pane instead of block display type.
Configure a contextual filter, but don't give it a default value.
Configure the content pane "argument settings" to take a node id from url.
In Display Suite, create a "Dynamic field". Move it into one of the layout regions.
Click the cog-wheel icon in the dynamic field, choose content to display, you find your newly created Views display under "Views panes".

Good luck!
Comment: I didn't see an option for argument settings, or where to take a node id from URL.
Comment: There are some settings at the top of the second column of the Views UI. One of that should be "Argument mode" i think
Comment: @vintorg: You can improve the answer if you want.
Comment: Not sure I can - it worked just as you said it would.
Answer: Just want to add that if even after enabling Views Content Panes + creating the Content Pane display in Views, well the Views Panes section still does not appear in the Display Suite's Dynamic Field's settings, this might be because your content pane's "Argument input" setting is not properly configured.
In my case I had selected "From context" -> "URL" when I actually needed to select "From context" -> "Term ID".


Como converter os campos em uma linha com string?

Question: Segue o código:
Model:
public class Usuario
{
   public string Campo1 { get; set; }
   public string Campo2 { get; set; }
   public string Campo3 { get; set; }
   public string Campo4 { get; set; }
   public string Campo5 { get; set; }
   public string Campo6 { get; set; }
   public string Campo7 { get; set; }
   public string Campo8 { get; set; }
   public string Campo9 { get; set; }
   public string Campo10 { get; set; }
}

Controller:
var teste = new Usuario();
string texto = ""+teste.Campo1+ teste.Campo2+ etc"";

Como pode ver o código acima, existe maneira mais fácil sem ficar digitado teste? Ou seja, só digitar teste que já preenche todos os campos com seu valor. Porque amanhã posso ter mais de 100 campos.
Alguma solução?
Answer: Você pode usar um método ou propriedade no Model. Por exemplo:
public class Usuario
{
    public string Campo1{ get; set; }
    public string Campo2{ get; set; }
    public string Campo3{ get; set; }
    public string Campo4{ get; set; }
    //etc.

    public override string ToString()
    {
        return Campo1 + Campo2 + Campo3 + Campo4; // +etc.
    }
}

E no controller:
var teste = new Usuario();
string texto = teste.ToString();

Eu sobrecarreguei o método ToString do tipo, mas você também pode criar um método novo ao invés disso.
Answer: Dá pra fazer com reflection. Você precisa tomar cuidado porque, geralmente, reflection deixa a execução bem mais demorada.
Veja um exemplo:
using System;
using System.Linq;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        var obj = new Usuario { Campo1 = "teste", Campo2 = "teste 2" };

        Type type = obj .GetType();

        var texto = "";
        foreach(var prop in obj.GetType().GetProperties())
        {
            Console.WriteLine($"{prop.Name}={prop.GetValue(obj, null)}");
            texto += prop.GetValue(obj, null) + " ";
        }
    }
}

public class Usuario
{
    public string Campo1 { get; set; }
    public string Campo2 { get; set; }
    public string Campo3 { get; set; }
    public string Campo4 { get; set; }
    public string Campo5 { get; set; }
    public string Campo6 { get; set; }
    public string Campo7 { get; set; }
    public string Campo8 { get; set; }
    public string Campo9 { get; set; }
    public string Campo10 { get; set; }
}

Veja funcionando no .NET Fiddle.
Comment: Interessante a sua resposta, obrigado jbueno.
Answer: Considerando que o número de campos vai aumentar, use Reflection:
public override string ToString()
{
    string retorno = "";
    foreach (var campo in this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public |
                           BindingFlags.NonPublic | BindingFlags.FlattenHierarchy))
    {
        retorno += " " + campo.GetValue(this, null);
    }

   return retorno;
}

O que eu faria é definir uma classe ancestral com o método:
public abstract class Basica
{
   public override string ToString()
   {
        string retorno = "";
        foreach (var campo in this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public |
                               BindingFlags.NonPublic | BindingFlags.FlattenHierarchy))
        {
            retorno += " " + campo.GetValue(this, null);
        }

       return retorno;
   }
}

Usuario herdar:
public class Usuario : Basica
{
   public string Campo1 { get; set; }
   public string Campo2 { get; set; }
   public string Campo3 { get; set; }
   public string Campo4 { get; set; }
   public string Campo5 { get; set; }
   public string Campo6 { get; set; }
   public string Campo7 { get; set; }
   public string Campo8 { get; set; }
   public string Campo9 { get; set; }
   public string Campo10 { get; set; }
}

E um teste:
public class Program
{
    public static void Main()
    {
        var usuario = new Usuario
        {
            Campo1 = "Teste1",
            Campo2 = "Teste2",
            Campo3 = "Teste3",
            Campo4 = "Teste4"
        };
        Console.WriteLine(usuario.ToString());
    }
}

Fiz um Fiddle.
Comment: Resolveu problema aqui, obrigado Cigano Morrisson Mendez
Answer: usa o System.Reflection.PropertyInfo
sobrecarrega o ToString() como Renan postou, mas dessa forma:
public override string ToString()
{
    string retorno = "";
    foreach (System.Reflection.PropertyInfo pr in this.GetType().GetProperties())
    {
        if (pr.CanRead)
        {
           object valor = pr.GetValue(this, null);
           retorno += pr.Name +": "+ (valor == null ? "" : valor.ToString()) + ", ";
        }
    }
    return retorno;
}

aí o resultado será:
var teste = new Usuario();
string texto = teste.ToString();
//Campo1: Valor, Campo2: Valor, Campo3: Valor, ...


Problemas com **UL inline**

Question: Boas,
Eu tenho um problema em fazer um ul inline assim pois sempre que tento por hr e vertical-align sai sempre do sitio.
Este é o resultado que me dá:

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

li {
    display: inline;
    padding-left: 20px;
}

a {
text-decoration:none;
color:#000000;
}

a:hover{
 color:#3ba09e;
}
   hr{
width:20px;
display:inline-block;
vertical-align:middle;
}

Arquivo

Escritórios

Escolas

Outros

Answer: Você digitou errado os atributos do hr.
hr{
    with:20px;
    display:inline block;
    vertical-align:middle;
}

Está errado o with e inline block, correto é:
hr{
    width:20px;
    display:inline-block;
    vertical-align:middle;
}

E troque o h4 por span e atribua o seletor da sua preferência.

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

li {
    display: inline;
    padding-left: 20px;
}

a {
text-decoration:none;
color:#000000;
}

a:hover{
 color:#3ba09e;
}
   hr{
     width:20px;
     display:inline-block;
     vertical-align:middle;
     border: 1px solid red;
}

.textoMaior {
     font-size: 18px;
     font-weight: bold;
}

Arquivo

Escritórios

Escolas

Outros

Comment: @BrunoGibellino Atualizei minha resposta com sua necessidade.
Comment: @BrunoGibellino Utilizei `border-color` ao invés de `color`
Comment: Verifica se não tem outro elemento ou seletor dando conflito
Comment: Mesmo assim não sei como é que dá aquele espaçamento todo entre o **** e a imagem.
Comment: obrigado, mesmo isso que precisava. Mas com o background-color e com o color não dá para mudar a cor do hr. Será que estou a fazer bem?
Comment: Eu precisava mesmo de utilizar o **h4** e quando mudei o **span** para **h4** aquilo desformatou tudo. Não existe nenhuma maneira de utilizar **h4** com **ul**?
Comment: desformatou como?
Comment: Ao invés de ficar inline ficou tudo em linhas separadas

Problemas com **UL inline**


How to show $\lvert e^{i2t\sin\theta}\rvert= e^{-2\Im(t\sin(\theta))}$

Question: First, I say sorry if this might looks obvious for you. I just confused since I can't found something related about this.
Here's the problem :

All I know about modulus is
$$\lvert x+iy\rvert = \sqrt{x^2+y^2}$$. And even if I apply this on
$\lvert e^{i2t\sin\theta}\rvert$, this gives me $1$ as the result.
So, where does $\Im(t\sin(\theta))$ come from? Please explain the step with detail. Thanks. Your little help means a lot to me. Thanks in advance.
And btw, $t>0, t\in \Bbb R$ and $0\leq \theta \leq 2\pi$
Answer: If $t$ is any real number then indeed $|e^{it}|=1$, you are right. It follows that if $z=x+iy$ is a complex number then:
$|e^{iz}|=|e^{i(x+iy)}|=|e^{ix}e^{-y}|=e^{-y}=e^{-Im(z)}$
Now, when you checked the result in Wolfram you obviously didn't write that $2t\sin(\theta)$ is a real number, so you got an answer in the general case, where it might be any complex number. After all, if $2t\sin(\theta)$ is real then its imaginary part equals $0$, so the answer still remains the same.


Creating Visualisations of Random Graphs

Question: I've got some code in C that produces a whole load of random geometric graphs and finds the proportion that percolate in order to estimate the full connection probability.
However I need to produce some kind of visualisation i.e. images of the graphs (not all of them, essentially just one example). Moreover I need to check (not essential) that the graphs produced look right (according to my domain).
Does anyone know of a good way of taking an adjacency matrix and a position matrix (the nodes have positions in Euclidean space) and producing some kind of visualisation?
Sorry to post this here, I thought someone from maths may have done this before.
Cheers.
Comment: If you want to do it in Matlab have a look here: http://www.mathworks.nl/help/symbolic/mupad_ref/graph-createrandomgraph.html
Answer: If you have access to Mathematica, then you just need to perform
$$
\verb bAdjacencyGraph[A,VertexCoordinates->Coordinates]b
$$
where $A$ is your adjacency matrix, and $\verb bCoordinatesb$    is a list of the form
$$
\{\{x_1,y_1\},\{x_2,y_2\},\ldots,\{x_n,y_n\}\}
$$
Comment: I need to have the nodes live inside a circle with a circular obstacle at its centre - is this easy enough to add to the graph visualisation?
Comment: Yes, it is (probably) easy, you should read the help for Graph, e.g. However, I understood from you question that you need to draw the graph with your own coordinates.
Answer: If you simply need to visualize an adjacency matrix, you can use a tool like Gephi. You can write a simple MATLAB script that would write your adjacency matrix and position matrix into a gdf file and then use Gephi to visualize. Alternatively, you can even import your data from an Excel sheet or specify internally.
Hope this helps!