nullpointer exception caused with queue

Question: i believe the error is caused by incorrect adding to the queue and there might be other errors but i think it is something here
public void add(E data)
    {
        if(size == 0)
        {
                      size++;
            front = new ListNode(data,null);
        }
        else
        {
                    size++;
            ListNode <E> temp = end;
            temp.setNext(null);
            temp = temp.getNext();
            temp.setData(data);
            end = temp;
        }
    }

if you need the rest of the code to find the error here is the full class
import java.util.*;

public class Queue<E>
{
        private ListNode <E> front;
        private ListNode <E> end;
        private int size;

    public Queue()
    {
        front = null;
        end = null;
        size = 0;
    }

    public E peek()
    {
        return front.getData();
    }

    public E remove()
    {
        if(size == 0){return null;}
        else
        {
        ListNode <E> temp = front;
        front = temp.getNext();
        size--;
        return temp.getData();
        }

    }

    public void add(E data)
    {
        if(size == 0)
        {
                     size++;
            front = new ListNode(data,null);
        }
        else
        {
                    size++;
            ListNode <E> temp = end;
            temp.setNext(null);
            temp = temp.getNext();
            temp.setData(data);
            end = temp;
        }
    }

    public boolean isEmpty()
    {
        if (size == 0)
            return true;
        else
            return false;

    }

    // [data, data, data, data]
    public String toString()
    {
        String s ="";
        ListNode <E> temp = front;
        while(temp.getNext()!= null)
        {
            s+=temp.getData() + ", ";
        }

        return s;
    }

    public int size()
    {
        return size;
    }
}

and here is the node i'm using
public class ListNode<E>
{
    private E data;
    private ListNode<E> next;

    /**
     * Constructs a ListNode with a specified data and next
     * @param d the data for the node
     * @param n the next reference
     */
    public ListNode(E d, ListNode<E> n)
    {
        data = d;
        n = next;
    }

    /**
     * returns the data from the node
     * @return the data field
     */
    public E getData() {return data;}

    /**
     * sets the data for the node
     * @param d the new data field
     */
    public void setData(E d) {data = d;}

    /**
     * gets the next reference of the node
     * @return the next reference
     */
    public ListNode<E> getNext() { return next; }

    /**
     * sets the next reference for the node
     * @param n the new next reference
     */
    public void setNext(ListNode<E> n) { next = n;}
}

and this is what i am using to test it
public class QueueTester
{
    public static void main (String args[])
    {
        Queue<Integer> queue = new Queue<Integer>();

        for (int k = 1; k <= 100; k++) // add 1 to 100
            queue.add(k);

        System.out.println ("Size: " + queue.size());
        System.out.println(queue + "\n");

        for (int k = 1; k <= 50; k++) // remove 1 to 50, contents 51 to 100
        {
            int number = queue.remove();
        }

        System.out.println ("Size: " + queue.size());
        System.out.println(queue + "\n");

        for (int k = 200; k <= 500; k+=10) // add tens 200 to 500 (after 51 to 100)
            queue.add(k);

        System.out.println ("Size: " + queue.size());
        System.out.println(queue + "\n");

        while (!queue.isEmpty()) // prints contents (should be 51 to 100, then 200 to 500 tens)
        {
            System.out.print(queue.remove() + "  ");
        }
        System.out.println("\n");

        System.out.println ("Size: " + queue.size());
        System.out.println(queue); // empty
        System.out.println ("Remove from empty queue: " + queue.remove() + "\n") ;

    }
}

Comment: You don't initialize `end` before using it.
Comment: Also, size never increases.
Answer: Your add method is not implemented correctly and will always just change the front.
When you call eventually call remove()
public E remove()
{
    if(size == 0){return null;}
    else
    {
    ListNode <E> temp = front;
    front = temp.getNext();
    size--;
    return temp.getData();
    }

}

since size == 0, you will return null. You then try to dereference null into an int
int number = queue.remove();

This will throw a NullPointerException.
Review your logic, if you add something to the list, you should probably increment the size.
Also, note that in your  add() method
ListNode <E> temp = end;
temp.setNext(null);

will also fail since end is originally null.
Comment: i don't understand what your trying to say
Comment: @user3025774 Because you don't increment `size` when adding the first element, your queue doesn't grow, you just reassign the `front` variable. Your queue holds one object, but is of `size` 0.
Comment: i do increment size with size ++
Comment: @user3025774 You do that in the `else` block, not in the `if`. Basically the `else` branch will never get executed.
Answer: try this..
if(size == 0)
    {
        front = new ListNode(data,null);
        end = first;
        size++;
    }
    else
    {
        ListNode <E> temp = new ListNode(data);
        end.setNext(temp);
        end = end.getNext();
        size++;
    }

nullpointer exception caused with queue


Consulta em .NET Core

Question: Estou aprendendo a lógica de MVC aplicado em .NET Core
porém estou com algumas dúvidas em fazer o processo CRUD, mais especificamente a Consulta.

Como posso fazer o clique do botão se comunicar com um Controller e o mesmo, solicitar a informação para a Model, a mesma retornar o resultado para o Controller e os resultado serem apresentados na tela?

Segue código.
View.
@model WebApplication1.Models.CepViewModel

Manutenção de Cep

<form asp-controller="Cep" asp-action="Cadastro" method="post">

        CEP
        <input asp-for="CepCodigo" style="margin-left: 90px" width="50px" />
        LOGRADOURO
        <input asp-for="CepLogr" style="margin-left: 90px" width="50px" />

        ENDEREÇO
        <input asp-for="CepEnd" style="margin-left: 40px" width="50px" />
        COMPLEMENTO
        <input asp-for="CepCompl" style="margin-left: 82px" width="50px" />

        BAIRRO
        <input asp-for="CepBairro" style="margin-left: 64px" width="50px" />
        CIDADE
        <input asp-for="CepCidade" style="margin-left: 138px" width="50px" />

        UF
        <input asp-for="CepUF" style="margin-left: 100px; width: 50px;" />

            <input type="submit" value="Consulta" />

</form>

Controller.
   public class CepController : Controller
    {
        public IActionResult Cadastro()
        {
            return View();
        }
        public IActionResult Consulta()
        {
            return View();

        }
    }
}

Model.
    public class CepViewModel
    {
        public string CepCodigo { get; set; }
        public string CepLogr { get; set; }
        public string CepEnd { get; set; }
        public string CepCompl { get; set; }
        public string CepBairro { get; set; }
        public string CepCidade { get; set; }
        public string CepUF { get; set; }
        public int CepSetor { get; set; }
        public string CepRegiao { get; set; }
        public string CepRota { get; set; }

        public CepViewModel TakeCepById(int Id)
        {
            CepViewModel cep = null;

            using (var connection = new SqlConnection("DBConect"))
            {

                cep = connection.Query<CepViewModel>("Select * From CEP WHERE CepCodigo = @CepCodigo",
                        new { CepCodigo = Id }).SingleOrDefault();
                return cep;
            }

        }
    }
}

Comment: Acho que você já resolveu essa, não?
Comment: @LeandroAngelo sim amigo, obrigado!
Mas se quiser compartilhar como aplica sua lógica para esse exemplo, também será bem-vinda
Comment: O Ideal seria você colocar a sua solução e marcar como respondida, para que a questão não fique aberta sem resposta ou removê-la, mas a primeira opção é que trás mais benefício para os outros usuários..
Answer: No form você direciona para o controller com a action da sua View:
<form asp-controller="Cep" asp-action="Consulta">

No controller você indica que esta enviando por POST
[HttpPost]
        public IActionResult Consulta(int Id)
        {

            return View();
        }

Consulta em .NET Core


How to prove $f(x) = 4x^{3} + 4x - 6$ has exactly one real root?

Question:
How can I show that $f(x) = 4x^{3} + 4x - 6$ has exactly one real root?

I think the best way is to show $f'(x) = 12x^2 + 4 > 0$ for all $x \in \mathbb{R}$. Thus, $f'(x)$ has zero real roots. Thus, $f(x)$ has at most one real root.
I thought about trying to show that if $f$ is a polynomial and $f'$ has $n$ real roots, then $f$ has $n + 1$ roots by using Rolle's Theorem or Mean Value Theorem, but I don't think this fact, in general, is true. I would need to prove this statement.
Can someone please help me prove this fact?
Comment: The second statement is false. Consider $f(x) = x^2+1$. $f'(x) =x$ which has a single root, but $f$ has no root.
Answer: Your intuition for the first one  is correct!
$f(0)<0$ and $f(1)>0$, so by IVT $f$ has a root say $x_0$
Suppose $f$ has another root $x_1 \neq x_0$ with $x_0<x_1$ .Then $f(x_0)=f(x_1)=0$ and by Rolles theorem $\exists$ $c \in (x_0,x_1)$ such that $f'(c)=0$, contradicting to the fact $f'(x)>0$
Answer: $f(x)=4x^3+4x-6$
$f(0)=-6$ and $f(-1)=-14$
By IVT, there exists at least one real root, $x\in(-1,0)$ such that $f(x)=0$
Now try to prove by using contradiction.
If not, there exists al least $2$ real roots $x_1,x_2$, such that $f(x_1)=f(x_2)=0$
Since $f(x)$ is differentiable, by using Rolle's Theorem, there exists a number $k\in(x_1,x_2)$ such that $f^{\prime}(k)=0$. But $f^{\prime}(x)=12x^2+4>0\ \forall x\ne0$
Comment: KIndly edit your answer: You have calculated and shown $f(x)$  takes **negative values** at both $x=0$ and $x=-1$. In this case IVT cannot allow us to conclude there is a root in between $-1$ and $0$.  Possibly you mean $x=1$ where the function value is positive.
Answer: Your $f'(x)$ is strictly positive  which means your function is strictly increasing. A strictly increasing function does not have more than one real root.
Because otherwise it is not going to be one-to-one. Simply put, with more than one real root you have to have a turning point somewhere between those roots which makes your function both increasing and decreasing between the roots.
Answer: Pedestrian:
$f'(x)>0$ implies $f$ is strictly increasing, i.e.for
$x_1 < x_2$  we have  $f(x_1) < f(x_2)$.
Assume a strictly increasing function has more than one zero.
Let $x_1 < x_2$ be $2$ zeroes of the function:
$f(x_1)=f(x_2)= 0$.
A contradiction.
P.S. Can there be a double zero if $f'(x) >0$?


Showing elements of an ultrapower have the form $j(f)([id]_{\mathcal{U}})$

Question: I am in a set theory class and we just started talking about ultrapowers. My professor mentioned that, if $\kappa$ is a measurable cardinal and $\mathcal{U}$ is a nonprincipal $\kappa$-complete ultrafilter on $\kappa$, then it is an easy consequence of Łoś's theorem that, for any function $f : \kappa \rightarrow V$, the equivalence class $[f]_{\mathcal{U}}$ is the same as $j(f)([id]_{\mathcal{U}})$, where $j$ is the canonical embedding. But when I tried to prove this, it wasn't easy for me! I know $j(f)([id]_{\mathcal{U}})$ must be an element of the ultrapower, and so I set $j(f)([id]_{\mathcal{U}})$ equal to $[g]$ for some $g : \kappa \rightarrow V$. Then I tried to show $\left\{\xi < \kappa : f(\xi) = g(\xi) \right\} \in \mathcal{U}$. If this was true, then by Los's theorem we would get $[f]_{\mathcal{U}} = [g]_{\mathcal{U}} = j(f)([id]_{\mathcal{U}})$. But I don't really understand the relationship between $g$ and $f$ and kept going in circles (one thing I tried to show was that $[id]_{\mathcal{U}}$ was in $j(\left\{\xi < \kappa : f(\xi) = g(\xi) \right\})$, and that definitely didn't seem to be going anywhere). Where am I going wrong?
Comment: Could you see that $j(f)([\mathsf{Id}]_\mathcal{U})$ is equal to the equivalence class of $\langle f(\alpha)\mid \alpha<\kappa\rangle$?
Answer: As a newbie for ultrapower, handling elements of an ultrapower is confusing and not easy. I also experienced trouble to evaluate $j(f)([\mathsf{id}])$.
For me, viewing $j(f)([\mathsf{id}])$ componentwise was helpful. Imagine the function $g$ representing $j(f)([\mathsf{id}])$. What is the value of that function if we put $\alpha$ into $g$? Well, we may view $j(f)$ as a function from $\kappa$ to $V$ that always returns $f$. $\mathsf{Id}$ is just the identity function.
By assumption, $[g]=j(f)([\mathsf{Id}])$. Now let us see the $\alpha$th section of this equality, then it would be $$g(\alpha)=(j(f)(\alpha))(\mathsf{Id}(\alpha))=f(\alpha).$$
Thus we may guess $g=f$.
Of course, the above argument is not an actual proof. The point is that functions in set theory are binary relations technically. Hence the assertion $f(x)=y$ is syntactic sugar for $(x,y)\in f$.
Thus what we have to prove is $([\mathsf{Id}],[f])\in j(f)$, which is equivalent to
$$\{\alpha<\kappa \mid (\alpha,f(\alpha))\in f\}\in\mathcal{U},$$
but you can easily see that the above sentence holds.
Comment: This was really helpful, thank you so much for the detailed response!


Find expected number of red balls until a black ball is chosen

Question:
Suppose we have a box with $n$ red and $m$ black balls. You draw balls
sequentially one at a time without replacement. Let $X$ be the number
of red balls removed before the first black ball is chosen. Please,
compute $E(X)$

Try:
I was thinking perhaps to use indicator functions since trying to find the probability mass function is probably complicated. But, isn't it hypergeometric?
Now, if we use indicators, we can write $X_i$ to be $i$ if first $i-1$ balls selected are red and the ith ball is black and $0$ otherwise. Thus, $X = \sum X_i$, Now
$$ E(X_i) = i P(X=i) = i \cdot \frac{m {n \choose i - 1}}{{n+m \choose i}}
$$
So,
$$ E(X) = \sum_{i=1}^{\infty} E(X_i) = \sum \frac{ im {n \choose i-1 } }{ {m+n \choose i} } $$
but, this sum would be hard to evaluate. Is my approach correct?
Comment: I don't know, but I feel there's something wrong with the claim: $X = \sum X_i$.
Answer: Consider a particular red ball: this has a probability $\frac{1}{1+m}$ of coming before all $m$ black balls, since there are $(m+1)!$ equally likely ways of ordering these particular balls and $m!$ of those have the red ball first
So by linearity of expectation, the expected number of red balls coming before all $m$ black balls is $n$ times this, i.e. $\dfrac{n}{1+m}$
Answer: This question is equivalent to putting all the balls in a row and seeing how many red balls are in the row before the first black ball.
The $m$ black balls separate out $m+1$ runs (some possibly empty) of red balls.  So the average size of each run of red balls is $\frac{n}{m+1}$.
In particular this also gives the expected number of reds before the first black.


LU Decomposition

Question: Can we use partial pivoting when obtaining the upper triangular matrix using Gaussian elimination? If so, how can we do it?
Let $Ax=B$ and $A=LU$
To determine $L$, it seems fancy to use pivoting as we interchange rows in $A$, since we are using the factors used in Gaussian elimination which were found during the search for $U$.
Comment: "Urgent" is not a good word to use here when asking us questions. We are not your horses to be whipped.
Comment: In any event: yes, you can do Gaussian elimination with partial pivoting. The decomposition goes like $\mathbf P\mathbf A=\mathbf L\mathbf U$, where $\mathbf P$ is a permutation matrix.
Answer: If you have $A=L U$ then solving $Ax = b$ is equivalent to solving first $L y = B$ and then $U x=y$. The point being, both of those can be done very easily since they are triangular systems.
Comment: @Tharindu: You'll want to see [this](http://books.google.com/books?id=mlOa7wPX6OYC&pg=PA87).
Comment: Thanks, but my question was not how to decompose a matrix into LU. I wanted to know how to use pivoting when doing LU decomposition.
Comment: Got it. thanks all...

LU Decomposition


How to write complex time signature that would be confused for compound (triplet) time?

Question: This question was sparked by many answers and comments on the site which describe 6/4 as a compound meter of 2 groups of dotted half notes (1  &  a  2  &  a), rather than the way I've always used and heard it (mainly in prog rock and metal genres) as simple meter of 6 groups of quarter notes (1&2&3&4&5&6&) or, if you prefer, a complex meter of 4/4 + 2/4 (1&2&3&4&1&2& 1&2&3&4&1&2&).
I've also been trying to write a piece that is in a complex meter of 4/4 + 1/8 (count 1&2&3&4&5 1&2&3&4&5) so mathematically that would be 9/8 but yet 9/8 feels like it should always be a compound triple meter.
Is there a standard way to denote that a piece should be interpreted as having a certain feel which differs from the "standard" interpretation of the meter, or are there alternate meters that would better convey my ideas?
Comment: 4/4 + 2/4 might rather be written as 3/2.
Comment: have a look at Bartok's Six Dances in Bulgarian Rhythms (Mikrokosmos) for ideas
Answer: There's not a definitive standard, but there are various conventions.
One option is to include two time signatures: the "actual" time signature and, parenthetically, the "compound" version expressing the metrical divisions.

Another option would be to include, say, a dotted barline to help visually divide the measure.

As the previous two examples make clear, the notation itself can make clear the intended metric divisions. Baring eighth-notes in groups of four rather than three, or use of quarter notes rather than dotted quarters, signals strongly the intended interpretation, even in the absence of a "fancy" time signature.

And finally, if needed, you can add accents to really make clear where the metric stresses should be.
Comment: @Dekkadeci These are not unorthodox beamings, they're orthodox beamings of unorthodox metre. It's pretty difficult to comment on the example you give without context, but in most metres, ♪.♪♪ ought not be beamed because it's not a "complete" group -- it would be perfectly correct in something like a duple metre subdivided into 7s.
Comment: There's another option I've seen in several band scores lately: Time signature is 9/8 and above the first system of 9/8 it says "(2+2+2+2+1)". For example, Frank Ticheli's "Vesuvius" has several sections in 9/8 time but counted in four beats with the second beat being 50% longer. Above the first 9/8 measure it says "(2+3+2+2). This seems to be what modern conductors and musicians are expecting. When otherwise 4/4 time is broken down into different beat lengths, the time signature is written as 8/8 and the grouping added above, such as (3+3+2).
Comment: Interesting, especially the second option.
Comment: I have been repeatedly told to not bar notes like dotted 8th note-dotted 8th note-8th note on NinSheetMusic (a video game transcription website I have contributed to) and to use dotted 8th note-16th note-tie-8th note-8th note instead. This implies that the unorthodox beaming may not be considered "proper notation" and may in fact impede readability rather than improve it.
Answer: Adding to the other answer, which covers the 9/8 case very well.
The 6/4 example should probably be written in alternating 4/4 and 2/4 bars -- you can put both time signatures at the start of the piece like Tchaikovsky does here.
Literally the only 6/4 beaming that will unambiguously convey what you're after is 8 + 4, which is going to look very strange and only helps if you don't have any intervening crotchets. You could try halving all your note values and write it in 6/8, but it'll look even worse and upset traditionalists. You might decide that 3/2 is "close enough", but it's not an approximation I'd personally settle for. Alternating time signatures definitely seems the way to go.
Answer: Examples of actual modern practice below.
The first is from Jubilate Deo (2016) by Dan Forrest. I believe the publisher is Hal Leonard or one of their subsidiaries. The time signature is 9/8 but there are four beats per measure, counted and conducted like "1 & uh 2 & 3 & 4 &".

The next two are from "Vesuvius" (1999) by Frank Ticheli, published by Manhattan Beach Music. The first example is again 9/8 time but counted and conducted "1 & 2 & uh 3 & 4 &".

The second example is 8/8 instead of 4/4 because the grouping is different from 4/4. This is "1 & uh 2 & uh 3 &"

This method of indicating non-standard beat groupings is the only method I've seen in scores over the last few years. I think any other method would seem outdated unless it was for an older work and was meant to re-create the manuscript faithfully.


Functions and Algebra question.

Question: Given the function $g(x) = 8 − 2x$

Find $g(2x-3)$

The answer to the question is $14-4x$
I have no idea how the lecturer worked it out and I just jotted down the answer, while trying to do it I just can't seem to work it out. If anyone could give me the steps to tackle this problem it'd be greatly appreciated.
Comment: $g(2x-3)=8-2(2x-3)=8-4x+6=14-4x$.
Answer: Given that $g(x)=8-2x$, let $Y=2x-3$.
Then, $g(Y)=8-2Y=8-2(2x-3)=8-4x+6=14-4x$.

Functions and Algebra question.


syntax for spring binding of  using the tags

Question: For binding the ordinary text box we may place code as:
<spring:bind path="ImageId">

                    <input type="text"  name="${status.expression}" value="${status.value}" id="imageId"  />

</spring:bind>

But in case if the input type is file then what would be the syntax for bind? and what is the position of ${status.expression} and ${status.value}?
Answer: i think this is not possible because HTML spec prevents the setting of the file upload control for security purposes (imagine adding a hidden one preset with some critical file)
Comment: If it not possible by this tag methed, then please suggest me the code to store the image into db using spring & hibernate!!
Comment: example1:http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-multipart example2: http://www.mkyong.com/spring-mvc/spring-mvc-file-upload-example/


How to implement Polymorphic objects in CouchDB / NoSQL?

Question: I'd like to implement Polymorphic objects in a NoSQL / Document DB?
What is best practice?
Example:
Master Class
Item Object (All should have Item.Title, Item.Subtitle, Item.IconURL)
SubClasses: ItemPhoto, ItemPDF, ItemURL, ItemHTML
(Each subclass would have different properties)
I'd like to list all Items Generically - then get specific data when i drill down.
Possible Options:
Save a two different Documents -with Master/Child Type & ID
Save all as SubClass Documents with Internal Item Object
Other options??
Thanks
Answer: CouchDB stores documents (data), not classes (data with code). There's the code in map, validation, list, and show functions which handle documents, but those documents are plain objects that carry data only.
In your example, you can define a library function to check that a given document contains the data of an item, and then use this function to decide what to do. For example:
<code>// in a "appTypes" library:
exports.isItem = function(doc) {
  return doc.Title && doc.Subtitle && doc.IconURL;
}

// in a map function
function(doc) {
  var appTypes = require('appTypes');
  if (appTypes.isItem(doc)) {
    // doc is an Item...
  }
}
</code>
Obviously you can put all code belonging to an Item in an Item class and create instances of that class initialized with the data in the doc. But that's your choice, and does not change how CouchDB will handle the document.


Projeto Maven + Spring MVC + JSP, como compartilhar arquivos de view?

Question: estou tentando ajustar uma estrutura de arquivos para começar um projeto grande, um ERP para ser mais exato. Hoje, existe uma boa parte dele feita em PHP de forma desordenada. Vamos adotar o Java Web (Maven + Spring MVC + JSP + Hibernate) para criar os próximos módulos e futuramente refazer os outros módulos. Dentro do que já foi estudado, estou com uma dúvida, provavelmente boba para vocês, mas para mim, ainda não achei o caminho.
Pensamos em criar um projeto para cada módulo (sistema) só que pode existir a possibilidade de um projeto ter que usar os recursos de outro projeto, em específico, partes da view. Como é possível controlar esta troca de recursos da view?
Sei que o Maven controla via multi-módulos as dependências e tals, mas como ficaria essa questão de, por exemplo, se eu tiver uma pasta com imagens no projeto A, e eu precisar de usá-las no projeto B sem precisar informar o caminho completo?
desde já obrigado.
Answer: Existem várias formas de fazer isso.
Colocar recursos dentro de um jar
Alguns frameworks (como o PrimeFaces e o GWT) fazem isso porque facilita o compartilhamento de recursos estáticos disponíveis no classpath.
Crie um projeto Maven para armazenar esses recursos em java/main/resources. Eles vão junto com o sistema em um jar e podem ser servidos para o client através de um Servlet.
O Spring MVC já faz isso automaticamente com a configuração:
<mvc:resources mapping="/resources/**" location="/, classpath:/META-INF/public-web-resources/"/>

Veja a documentação para maiores detalhes.
War overlay
Outra saída é criar um projeto Maven web (WAR) com os arquivos gerais e configurar o Maven War Plugin dos demais projetos fazer overlay, mesclando os WAR's.
Isso funciona, pois já usei, mas confesso que pode ser meio confuso para configurar e deixar tudo funcionando perfeitamente, além de ser mais complicado de integrar com uma IDE.
Recursos fora da aplicação
É possível configura um servidor web simples (como já mencionado na outra resposta) ou em uma aplicação Java web separada.
Você pode usar caminhos relativos à raiz do servidor, por exemplo: /resources-app/images/image01.png.
Obviamente isso pode ser um problema caso queira usar diferentes versões de projetos que usem diferentes Javascript's, CSS's e imagens.
Além disso, pode ser um problema caso o local dos resources seja diferente. Nesse caso, você pode criar uma configuração no web.xml em cada aplicação com o base path dos resources. Dessa forma, basta mudar um simples local para definir se as imagens vão estar em /app/imagens ou http://18.104.22.168/images.
Comment: Obrigado pelas ideias utluiz e rdeandrade. Vou tentar ver o que faço e qualquer depois eu posto aqui a solução que me foi mais adequada.
Answer: O que você pode fazer no caso, é um servido de arquivos estáticos e colocá-lo num servidor apenas com apache mesmo. É comum isso. Mas no caso se for apenas HTML, CSS, JS, Imagens e etc. Assim em todos os outros módulos basta você referências o servidor de mídias, que pode até ter o mesmo DNS do servidor da aplicação, ficando transparente na hora de fazera  requisição.


Generating series of odd Fibonacci

Question: It is a known fact that $$\sum\limits_{n \geq 0} F_{n}t^{n} = \frac{t}{1-t-t^2}.$$
Now if we want the odd terms just $$\sum\limits_{n \geq 0} F_{2n+1}t^{2n+1} = \frac{1}{2}(F(t)-F(-t)) = \frac{t(1-t^2)}{1-3t^2-t^4}.$$ What I don't get how re-writing the term we end up with $$\sum\limits_{j \geq 2}F_{2j-3}t^j = \sum\limits_{n \geq 0} F_{2n+1}t^{n+2} = \frac{t^2(1-t)}{1-3t-t^2}$$
According to

Any help or hint would be appreciated.
Answer: If $$\sum_{n = 0}^\infty F_{2n+1} t^{2n+1} = \frac{t(1-t^2)}{1 - 3t^2 + t^4}, \tag{1}$$ then dividing both sides by $t$ gives
$$\sum_{n=0}^\infty F_{2n+1} (t^2)^n = \frac{1 - t^2}{1 - 3t^2 + (t^2)^2}, \tag{2}$$
hence letting $t^2 = u$ implies
$$\sum_{n=0}^\infty F_{2n+1} u^n = \frac{1 - u}{1 - 3u + u^2}. \tag{3}$$  All that remains is to now multiply by $u^2$ and rename $u$ to $t$:
$$\sum_{n=0}^\infty F_{2n+1} u^{n+2} = \frac{u^2(1-u)}{1 - 3u + u^2}, \tag{4}$$ therefore
$$\sum_{n=0}^\infty F_{2n+1} t^{n+2} = \frac{t^2(1-t)}{1 - 3t + t^2}. \tag{5}$$
Comment: It's just a figurehead, but maybe it's better to rename $u$ with a variable different from $t$, thanks for the answer.

Generating series of odd Fibonacci


Custom Web Form for Shibboleth login

Question: I recently deployed a server and website that authenticates with my university's Shibboleth authentication system.  Functionally, it works great.  Aesthetically, there is much
When you go to the login page, the login page is redirected to the Shibboleth's server user authentication page.  While it works, I would rather put a username and password text boxes on my website, and, on submission, pass those to Shibboleth.
Is it possible to use an alternate web form and have the information be passed to Shibboleth?
Answer: Having your own custom login form would defeat the point of using Shibboleth. It's meant to send your users to their IdP, which they can recognize as trustworthy and authenticate there, only then to delegate the authentication and authorization assertions to the service provider.
If you're unhappy with the look and feel of your federation WAYF or the institution IdP, talk to your federation or your IdP.
(As a side note, branding and look&feel for WAYFs and IdPs to improve the user experience was one of the topic talked about at the Federated Access Management (FAM10) conference: there will probably be new things coming in the UK federation if you're part of it.)
Comment: Thanks Bruno!  That makes complete sense, and I had not thought of it from that perspective.
Answer: On the off chance anyone does still want to use this approach we've found this can be done but should be strongly evaluated for security (e.g. SSL encrypted throughout, local references as shown below).

Call the client SSO directive with specified redirect end point (e.g. /shib/protected/)
https://acmesite.com/Shibboleth.sso/Login?target=%2Fshib%2Fprotected%2F
a. This really can only be done through redirects since you start hitting CORS issues if you try to pull it off with AJAX or even JSONP
Post using properly named elements
<form id="login" action="https://sso-dev.acme.com/idp/Authn/UserPassword" method="post">
<input class="form-element form-field" name="j_username" type="text" value="">
<input class="form-element form-field" name="j_password" type="password" value="">
<button class="form-element form-button" type="submit">Login</button>
</form>

Custom Web Form for Shibboleth login


What does *Restarting data prefetching from start* mean in caffe

Question: I have been reading up on the log output Restarting data prefetching from start. Apparently, it means that one has not enough data and the data is prefetched* from the start. However, my dataset exists of 10.000 data samples and my batch size is 4. How is it possible that it has to prefetch the data, since my batch size is 4 which means it will take 4 data samples per iteration. Can anyone clarify my understanding?
LOG:
<code>I0409 20:33:35.053406 20072 data_layer.cpp:73] Restarting data prefetching from start.
I0409 20:33:35.053447 20074 data_layer.cpp:73] Restarting data prefetching from start.
I0409 20:33:40.320605 20074 data_layer.cpp:73] Restarting data prefetching from start.
I0409 20:33:40.320598 20072 data_layer.cpp:73] Restarting data prefetching from start.
I0409 20:33:45.591019 20072 data_layer.cpp:73] Restarting data prefetching from start.
I0409 20:33:45.591047 20074 data_layer.cpp:73] Restarting data prefetching from start.
I0409 20:33:49.392580 20034 solver.cpp:398]     Test net output #0: loss = nan (* 1 = nan loss)
I0409 20:33:49.780678 20034 solver.cpp:219] Iteration 0 (-4.2039e-45 iter/s, 20.1106s/100 iters), loss = 54.0694
I0409 20:33:49.780731 20034 solver.cpp:238]     Train net output #0: loss = 54.0694 (* 1 = 54.0694 loss)
I0409 20:33:49.780750 20034 sgd_solver.cpp:105] Iteration 0, lr = 0.0001
I0409 20:34:18.812854 20034 solver.cpp:219] Iteration 100 (3.44442 iter/s, 29.0325s/100 iters), loss = 21.996
I0409 20:34:18.813213 20034 solver.cpp:238]     Train net output #0: loss = 21.996 (* 1 = 21.996 loss)
</code>
Answer: If you have 10,000 samples and you process them in batches of size 4, it means that after 10,000/4=2,500 iterations you will process all your data and caffe will start over reading the data from the beginning.
BTW, going over all samples once is also referred to as an "epoch".
After every epoch caffe will print to the log

Restarting data prefetching from start
Comment: I think I have found my problem. My test dataset is much smaller than the train dataset whereas my batch_size was the same. So obviously for testing the net the network had to prefetch the data from the start. A terrible mistake from me. Sorry for bothering you with such a stupid question! @Shai
Comment: Yeah that could be it. I will check as soon as I get this output again! @Shai
Comment: How come that *Restarting data prefetching from start* is printed multiple times in a row? @Shai
Comment: @thigi I don't know. please add the prototxt of your input layer and the print from your log. Is it possible you complete an epoch of train and test at the same time?
Comment: The prototxt, is basically the Res-Net-50. Do I need to add it for you? I have added my log. @Shai
Comment: The log *Restarting data prefetching from start* only comes before testing the net. @Shai
Comment: @thigi forgive me but I do not know all net prototxts by heart ;)
Comment: I am glad you think like that!


Updating all existing user's custom field

Question: I am fairly new to Drupal development and ran into a problem when trying to create a cron to update the value on a custom field for all the existing users.
Here is the code, when I click run cron it does nothing. I do no see my value in the custom field I created on any of the users.
<code>/**
* Implementation of hook_cron().
*/
function testingdev_cron()
{
  $users = entity_load('user');
  foreach ($users as $user)
  {
    $user->field_my_field = 'test';
    user_save($user);
  }
}
</code>
Comment: Does the code run? Is the module enabled? etc. What debugging have you done?
Comment: To get you started debugging: Stick the following statement inside your hook: `debug("testingdev_cron is running");` and see if that message shows up when you click run cron.
Comment: I have the module enable, I stuck the debug code in there but it isn't displaying on the page after I click run cron. The code is running because I previously threw in code that breaks the module on purpose and I get the error page back after clicking run cron.
Answer: Found out why it was not working (Which also explains why none of my debugging was displaying.) I had to skip over the the user with UID of 0 and modify how I set the field value or else the user_save function would break the code (For anyone that is interested.)
<code>/**
* Implementation of hook_cron().
*/
function testingdev_cron()
{
  $users = entity_load('user');
  foreach ($users as $user)
  {
    if($user->uid == 0)
    {
      continue;
    }

    $edit = array(
      'field_my_field' => array(
        'und' => array(
          0 => array(
            'value' => 'test'
            )
          )
        )
      );
    user_save($user, $edit);
  }
}
</code>


HREF que aponta para um button

Question: Como apontar uma HREF para um botão do tipo submit que está escondido? Escondido/invisivel é porque o botão vai estar usando o atributo hidden.
Comment: Vc já teve algumas respostas, talvez certas e talvez erradas mas por culpa sua. O que exatamente vc quer dizer com "botão escondido"? Se, por acaso, for o fato de que o botão está visível na página, mas apenas fora da visão do usuário porque o formulário e longo e a página precisa ser rolada (scroll), o que vc quer na verdade é um *anchor* (ou *bookmark*): http://www.hypergurl.com/anchors.html
Answer: Um href puro não faz o que você quer, mas um label com for pode te ajudar. Lembrando que você pode deixar o label estilizado como achar melhor.
Veja uma demonstração:

Clique --> [aqui no texto] <-- em vez de clicar no botão ao lado.

<button id="escondido" onclick="alert('fui clicado!')">Eu vou estar escondido</button>

Mas se "precisa mesmo" ser um a, as outras respostas conseguem contornar o problema do a com JavaScript.
Answer: Talvez isso seja o que você procura:
Link maneiro

Answer: A resposta do Bacco deve ser a  solução para o problema, mas não é um HREF.
Se quiser, realmente, ir no HREF pode usar:

Clique aqui para ganhar um alerta

<button style="display:none;" onClick="alert('meu alerta')"></button>

Explicações:
O botão possui um parâmetro onClick que então, quando clicado, exibe o alerta, esta "função" pode não existir, principalmente se utilizar o type como submit, num form, por exemplo.
O botão também possui um style com o display como none, para ocultar sua exibição.
O link (a href) possui um JQuery com a função .click(). Esta função efetua um click no botão escolhido. Se tiver problemas ou duvidas para selecionar ("setar") o botão leia a documentação do JQuery em https://api.jquery.com/category/selectors/.
Em geral e mais comum para SEU USO deve ser:

.classe (ex: $('.botao') se houver class='botao').
#id (ex: $('#botao') se houver id='botao').
tag (ex: $('button') se houver <button>).
tag[atributo=valor] ou tag[atributo] (ex. $('button[type=submit]') se houver <button type='submit'>).

Quanto maior o nível de 'hierarquia' menor será a chance de haver conflitos (exemplo haver dois botões e um errado ser acionado).

HREF que aponta para um button


How to select $6$ shoes from $12$ pairs of shoes

Question:
How to select $6$ shoes from $12$ pairs of shoes where in the selected shoes no two are from the same pair?

that is, how many ways can this be done?

My solution is the following:
Since the $6$ shoes have to belong to different pairs, we select $6$ pairs out of $12$ pairs and that is $\binom{12}6$. But I think I am missing something because we can take the right or the left shoe, but I don't know how to consider this too. Thanks.
Comment: Are you asking for the number of ways in which you can do this?
Comment: @Frpzzd Yes, that's right.
Answer: If you are trying to find the number of ways to select $6$ shoes from $12$ pairs in which no two are from the same pair, then the number of ways to do this is the same as the number of ways to select $6$ shoes from $12$ different shoes (since we only want to count the non-duplicates). Therefore the answer would be $\binom{12}6$ and your answer would be correct. However, you are concerned that the right and left shoes should be counted differently, so I will address that case as well. For each of the $\binom{12}6$ ways to pick $6$ shoes, there are $2^6$ different ways that their "footednesses" could be arranged (since each shoe is right or left, and there are $6$ of them). Then the final answer should be $\binom{12}6\cdot 2^6$.


Issue with printing selenium output as the readable text instead of HTML code

Question: I am trying to learn how to web scrape using selenium and have been watching a youtube series by Tech with Tim. I can't get my output of info scraped using selenium to display as text, only HTML code.
I tried this
driver.get("https://www.techwithtim.net/")

search = driver.find_element("name","s")
search.send_keys("test")
search.send_keys(Keys.RETURN)

try:
    main = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "main"))
    )
    articles = main.find_elements(By.TAG_NAME, "article")
    for article in articles:
        header = article.find_elements(By.CLASS_NAME, "entry-summary")
        print(header.text)

finally:
    driver.quit()

I was expecting an output with all of the text under the class name entry summary, but instead, i get the error:
AttributeError                            Traceback (most recent call last)
Cell In [70], line 19
     17     articles = main.find_elements(By.TAG_NAME, "article")
     18     for article in articles:
---> 19         header = article.find_elements(By.CLASS_NAME, "posted-on").text
     20         print(header)
     24 finally:

AttributeError: 'list' object has no attribute 'text'

I understand that the .text has something to do with converting the HTML to text, but I have not been able to fix it. Any help would be appreciated.
Comment: `.find_elements` returns a list of elements not one single element. You need to iterator over the list to get the text of each element.
Answer: You probably need to use find_element there, not find_elements.
As following:
articles = main.find_elements(By.TAG_NAME, "article")
for article in articles:
    header = article.find_element(By.CLASS_NAME, "entry-summary")
    print(header.text)


How do you change the playback tempo of the score in MuseScore 4?

Question: I'm really struggling to find the way the playback tempo should be changed in MuseScore 4. I tried googling it but still no luck.
Comment: This [documentation](https://musescore.org/en/handbook/3/tempo#playback) seems relevant. Note the point that settings in the "play panel" can (temporarily) modify playback tempo.
Comment: @AndyBonner that's documentation for MuseScore 3
Comment: Here, then: [tempo](https://musescore.org/en/handbook/4/setting-your-score#tempo) and [playback](https://musescore.org/en/handbook/4/playback-controls#play-position-and-tempo)
Answer:
First, select a note at the point in the score that you want the tempo marking to go.

Then, open the Tempo palette and click on the tempo marking that has the right beat value, for example "crotchet=80".
This will place the tempo marking above the note you selected.

To change the BPM value, double click on the number in the tempo marking that you just placed, type in a different number and then click away.

If you want to hide the marking, you can deselect "visible" in the properties panel.

As seen in the documentation, there is another way to adjust the playback tempo:

Undock the Play toolbar (by dragging the rectangle of dots).
This reveals a slider for playback position, and a slider for Tempo %.
Comment: Wow - yeah, undocking worked but I never would have guessed that. I spent a lot of time looking for this. Wish they hadn't needlessly made it so complicated.


hook_page_alter called once

Question: I have a Drupal 7 theme which is a Bootstrap child theme.
In my version of page.vars.php, I have a THEME_page_alter() call which runs only once until I do a clear cache. Other hooks such as THEME_process_page or THEME_preprocess_page are called each time I reload the page.
A second theme, with the same page_alter hook works just fine and is called each page-reload without the need for a clear-cache first.
What could be causing this?
Comment: Are the 2 themes tested on the same site?
Comment: Yes, they are on a multi-domain setup, but all running from the same Drupal instance.
Comment: I suspect it is due to the page cache...
Comment: Why would the output change though? Surely it would cache the same result as the first run?
Comment: As I remember, rendering array is cached if you enable page cache. But preprocess function still work because the cache is made before the preprocess function.
Answer: Theme settings are specific to each theme. Go to /admin/appearance/settings/yourtheme and check for any theme-specific caching options. I can't tell you exactly what the options would be because that depends on your theme.
Comment: I couldn't see anything of relevance in there. The thing is that the logic that runs the first time around in `THEME_page_alter()` works correctly, but then it's not like it caches the correct logic on the subsequent page load. It seems to not run at all, and displays a region that I specifically want to hide (unset)

hook_page_alter called once


react custom hook state is not updating when re-rendering

Question: I'm having an issue when repopulating form for edit using react hooks.
Parent Component : Edit.js
const EditData = (props) => {
    const { Id } = props.match.params;
    const dispatch = useDispatch();
    // calling redux action to get the data
    useEffect(() => {
      dispatch(getDataById(Id));
    }, [Id]);
    const data = useSelector((state) => state.data);
    const initialState = {
      Id: data.cardId || '',
      Number: data.Number || '',
      Date: data.Date,
    };
    //calling custom hook
    const { handleChange, handleSubmit, values,errors } = useForm(
        initialState,// passing initial state to custom hook
        validateOnSubmit,
        submit
    );
    // used to submit the data
    function submit() {
      dispatch(updateCard(values));
    }
    return (<DateForm
            handleSubmit={handleSubmit}
            handleChange={handleChange}
            values={values}
            />);
  };

Custom hook: useform.js
  const useForm = (initialState, validateOnSubmit, callback) => {
    const [values, setValues] = useState(initialState);
    const [errors, setErrors] = useState({});
    const [isSubmitting, setIsSubmitting] = useState(false);

    const handleChange = (event) => {
      const { name, value } = event.target;
      setValues({
        ...values,
        [name]: value
      });
    };
    const handleSubmit = (event) => {
      event.preventDefault();
      setErrors(validateOnSubmit(values));
      setIsSubmitting(true);
    };

    useEffect(() => {
      if (Object.keys(errors).length === 0 && isSubmitting) {
        callback();
      }
    }, [errors]);

    return {
      handleChange,
      handleSubmit,
      values,
      errors
    };
  };

when the API call get finished the react re-render the custom but the local state of the hook is not updating.
const useForm = (initialState, validateOnSubmit, callback) => {
      console.log(initialState);

on second render, here i can receive data from the API

    const [values, setValues] = useState(initialState);

but values is not getting updated, values is still holding the state from the initial render

I cannot figure out why this is. I'm just started to use react hooks, please help me.
Comment: Are you asking why `initialState` is updated but the `values` arent?
Comment: I assume getDataById is imported?
Comment: Although not strictly related to this, it's advised not to capitalize property names. So, is 'Id' correct from props.match.params or should it be 'id'?
Comment: @DennisVash yes, the `initialState` variable is updated when the api call get completed,im passing that `initialState` variable to   `const [values, setValues] = useState(initialState);` , so it should update the `values` variable right?. but its not !
Comment: @rrd yes. its a redux action
Answer: As OP stated in a comment:

the initialState variable is updated when the API call get completed,I'm passing that initialState variable to const [values, setValues] = useState(initialState); , so it should update the values variable right?. but it's not!

It is should update the state, the initial state is assigned once until the component unmounts.
See useState API, it stated in lazy initialization:

The initialState argument is the state used during the initial render. In subsequent renders, it is disregarded.


Limpar textearea vindo do Laravel

Question: Estou com o seguinte cenário, usando o Plugin summernote para um textarea com as configurações:
<textarea id="summernote" name="editordata">{{$termos->termos}}</textarea>

Ele retorna dos dados corretamente do banco, porem estou criando um buttom para tentar limpar os dados caso o cliente queira reescrever.
Linha de código:
<button type="button" class="text-center btn btn-warning" id="limpar">Limpar</button>

E o jQuery esta da seguinte forma:
$('#limpar').click(function() {
    $('#summernote').val(" ");
});

Tentei o empyt() também sem sucesso, alguém teria alguma solução para esse impasse?
Answer: Segundo a documentação vc precisa fazer um reset https://summernote.org/deep-dive/#reset

Reset: Clear the editor content and remove all stored history.

Então sei script deveria ficar assim
$('#limpar').click(function() {
    $('#summernote').summernote('reset');
});

Comment: Funcionou perfeitamente. Obrigado
Comment: @BetiniO.Heleno sem problemas meu caro []´s

Limpar textearea vindo do Laravel


Regra de seleção de registros baseado na data e na hora

Question: Eu estou desenvolvendo um sistema de apostas online e ao selecionar os jogos cadastrados no sistema eu preciso selecionar somente os jogos do dia atual em diante, adicionalmente eu preciso me certificar de não selecionar os jogos que já começaram, ou seja, aqueles nos quais a hora atual seja maior que a hora do registro.
Até agora eu consigo selecionar os registros de hoje em diante por data, mas eu não consegui fazer a condição da hora. Vou deixar a query que tenho atualmente abaixo.
SELECT GROUP_CONCAT(timee.nome_time ORDER BY timee.nome_time SEPARATOR ' X ') AS nome_time,
partida.id, DATE_FORMAT(partida.data_hora, '%d/%m/%Y %H:%i') AS data_hora,
partida.tb_cotacao_id
FROM tb_partida AS partida, tb_time AS timee, tb_partida_time AS partidaTime
WHERE (partida.id = tb_partida_id && timee.id = tb_time_id)
AND (partida.flag_ativo = 1 AND partida.flag_cancelado <> 1 AND partida.flag_finalizado <> 1)
AND (date(partida.data_hora) >= date(now()) AND (TIME_TO_SEC(TIMEDIFF(now(), partida.data_hora)) > 600))
AND partida.tb_campeonato_id = 11
GROUP BY partida.id

Answer: Pela estrutura você está utilizando o DATETIME em partida.data_hora.
Se você usa:
date(partida.data_hora) >= date(now())

Está garantindo que o ano, mês e dia será maior e igual ao atual, mas o horário em ambos não entra na comparação, em outras palavras:
SELECT DATE('2017-12-31 01:02:03');
// Resultado : 2017-12-31

Você pode simplesmente remover o DATE(), dessa forma ficaria:
partida.data_hora >= now()

Isso iria fazer com que comparasse também o 01:02:03, assim atingindo o que deseja.
Por exemplo:
Utilizando sem o date(), a solução:
SELECT '2017-01-02 01:02:03' >= '2017-01-02 01:02:01'
// Resposta: 1

SELECT '2017-01-02 01:02:03' >= '2017-01-02 01:02:04'
// Resposta: 0

Enquanto que usando date():
SELECT DATE('2017-01-02 01:02:03') >= DATE('2017-01-02 01:02:01')
// Resposta: 1

SELECT DATE('2017-01-02 01:02:03') >= DATE('2017-01-02 01:02:04')
// Resposta: 1

Extra:
Se eu compreendi corretamente o SQL, quando você usa o >= now() não faz sentido usar o (TIME_TO_SEC(TIMEDIFF(now(), partida.data_hora)) > 600, isso seria redundante.
Você poderia substituir:
(date(partida.data_hora) >= date(now()) AND (TIME_TO_SEC(TIMEDIFF(now(), partida.data_hora)) > 600))

Por:
(partida.data_hora >= (now() + INTERVAL 10 MINUTE))

Isso iria garantir que obrigatoriamente o partida.data_hora seja maior do que a data atual somado com 10 minutos, o que iria resolver os dois problemas.


How to find automorphism of a particular order.

Question: Given a finite  group  if  the  automorphism group  is  known  is  it  possible  to  write  down  all  the  automorphisms  with  respective  orders?
For  example say the  group $Z_{p^{2}}$  has  automorphism  group isomorphic  to  $Z_{p(p-1)}$ and I  have  to  find  an automorphism  of  order $p$, $p-1$. Now I know  that one automorphism  of  order $p$  is $y \mapsto y^{p+1}$ . But  how  to  actually find  them  out  for  this  other  groups?
Comment: Can you generalize the automorphism of $\mathbb{Z}/p$ of order $p-1$?
Comment: $Aut(Z_{p})$ is a  cyclic  group of  order  $p-1$ . So  there  are $\phi(p-1)$ such automorphisms . That much I can see but  genaralization?
Comment: Now, what is $p\mathbb{Z}/p^2$ isomorphic to?
Comment: $pZ_{p}$  as  the  elements  are { $p,2p,3p,......(p-1)p$} ?
Comment: And $0$.  (So, how many elements are there?)
Comment: There are $p$ elements.
Comment: But what  next? @MichaelBurr A  little more  help  to  lead  to  the  answer, please?
Answer: Below is some background on the automorphism group of any cyclic group $\mathbb{Z}/n\mathbb{Z}$, then we give a general way to find such an element of order $p$, and leave the case of powers $p-1$ for the time being.
First, note that an automorphism $\psi:\mathbb{Z}/n\mathbb{Z}\rightarrow \mathbb{Z}/n\mathbb{Z}$ is completely determined by the image of $1$. So $\psi(1)$ must be an element relatively prime to $n$, otherwise the order collapses. That is, if $\psi(1)=d$ where $\gcd(d,n)>1$, then $ord(d)<n$.
So $\psi(1)$ is relatively prime to $n$ and there are exactly $\phi(n)$ choices for the image of $1$, each of which determine a unique automorphism of the group $\mathbb{Z}/n\mathbb{Z}$. This gives $|Aut(\mathbb{Z}/n\mathbb{Z})|=\phi(n)$ and every element of the group is a map $1\mapsto r$ where $\gcd(r,n)=1$.
Let $\psi_r$ denote the map $1\mapsto r$ in $Aut(\mathbb{Z}/n\mathbb{Z})$. To calculate $ord(\psi_r)$ note $\psi_r(1)=r$, $\psi_r(\psi_r(1))=r^2$, and so forth. In this way we can define an isomorphism $Aut(\mathbb{Z}/n\mathbb{Z})\rightarrow (\mathbb{Z}/n\mathbb{Z})^\times$ by sending $\psi_r\mapsto r$.
So the problem at hand is equivalent to finding the least power $m$ such that $r^m\equiv 1 \pmod{n}$ and to find an element $r$ such that $r^m\equiv 1\pmod{n}$ with $m$ fixed.
Let's work in $\mathbb{Z}/p^2\mathbb{Z}$ for odd primes $p$ now so that the elements of $Aut(\mathbb{Z}/p^2\mathbb{Z})$ are $\{1,...,p-1,p+1,...,2p-1,2p+1,...,p^2-1\}$. We want to choose an element $r$ of the above such that when raised to the power of $p$ we get $1$.
Pick a general element $(mp+k)$ where $k\in \{1,...,p-1\}$ and $m\in \{0,...p-1\}$. By the binomial theorem we have
$$(mp+k)^p=\sum_{i=0}^p {p\choose i}(mp)^{p-i}(k)^i$$
Taking congruences modulo $p^2$ gives the last two terms
$$(mp+k)^p\equiv {p\choose p-1}(mp)k^{p-1}+k^p\equiv k^p \pmod{p^2}$$
Where the last congruence is found after calculating ${p\choose p-1}=p$. So we can check all powers $k^p\equiv 1 \pmod{p^2}$ where $k\in \{1,...,p-1\}$ and we get all others by varying $m\in \{0,...,p-1\}$.
To find at least one solution observe $k=1$ satisfies $k^p\equiv 1 \pmod{p^2}$ so that we can take any element of the set $\{1, p+1, 2p+1,..., p^2-p+1\}$.
Now for the case to the power of $p-1$ we can follow the above so that the binomial theorem gives
$$(mp+k)^{p-1}=\sum_{i=0}^{p-1}{p-1\choose i} (mp)^{p-1-i}k^i$$
Taking congruences again
$$(mp+k)^{p-1}\equiv {p-1\choose p-2}(mp)k^{p-2}+k^{p-1}=(p-1)(mp)k^{p-2}+k^{p-1}\equiv k^{p-1}-mpk^{p-2}\pmod{p^2}$$
So we want to simplify $k^{p-1}-mpk^{p-2}=(k-pm)k^{p-2}\equiv 1\pmod{p^2}$. I'm currently stuck so I'll think about this last one for a little bit.
Comment: I'm pretty sure in general it is difficult to find elements of particular orders unless you know the group structure itself and have orders in mind. It's possible to just manually check the orders of elements of $\mathbb{Z}/n\mathbb{Z}^\times$ by hand but it's not necessarily easy to find elements of particular orders.
Comment: [Here's a wikipedia page](https://en.wikipedia.org/wiki/Root_of_unity_modulo_n#Finding_a_primitive_k-th_root_of_unity_modulo_n) that may be relevant to your question.
Comment: I know  that's  not  easy .Actually  I am learning  semi direct products  of  groups  and  automorphisms  are  necessary  for  that , of course  the structures  of  the  groups  being  specified. Examples  are  shown  in  books but I cannot  understand  how  they  found  that  automorphism or  on  what  basis  that  particular  one  is  chosen.
Comment: @user118494 That sounds interesting. I would venture "inspired guess" but it's probably just the use of a lot deeper theory. I don't think I know enough group theory to properly respond. :D


Why is there a module for version 9 of core?

Question: I checked this module page, it have the download option for Drupal 9 version. Why is Drupal 9 is launched when there isn't an official stable Drupal 8 release? Is there anything wrong with Drupal 8?
Why did they ignore Drupal 8? I also found the Drupal 9 development snapshot release.
Answer: Well the "Bad Judgment" module you linked to claims:

This module provides an explicit dependency for modules whose usage requires bad judgement. Joke modules often require "bad judgement".

So I wouldn't take that version number too seriously.
From the core download page you linked to:

Placeholder for the Drupal 9.x release. Not intended for actual use by anyone except the issue queue version selector.

It's just a placeholder for the next version (forward-thinking and all that). It doesn't mean there's anything wrong with Drupal 8, and it doesn't mean Drupal 9 will be out any time soon.
Comment: A tiny thing I want to add is that the 9.x branch was created in the issue queue when the feature freeze for D8 approached. There has to be somewhere to put those issues/features that get rejected from D8. :)


Making a variable in a certain node type and access that variable in another node type

Question: I'm fairly new to Drupal. But I'm trying to learn.
What I'm try to accomplish is have a variable in a certain node type (artist) and I want to access this variable in another node type (news). Is this possible?
Let's say I have two content types, Artists and News. The artist node will have (at some point) related pictures, songs, and news. But at default it does not have any. So I wanted a variable that acts like a flag that if there are any related pictures the flag is changed. In the news node, I have tags that point to an artist if the news is related to him/her, then I'll show the same related songs, pictures of the same tagged artist. I want the flag variable as a checker if there are truly related songs/pictures. In that way I'll just use the flag and before I query the related pictures/songs
Comment: What do you mean by variable? Is it supposed to be something different than a field? And what exactly do you mean by accessing it from another type? Please provide simplified use case :)
Comment: Sounds like you are wanting some sort of node or entity reference field, but without further information, that's only a guess...
Comment: @user21688 you are supposed to edit your question. Comments are ephemeral in nature, and here you can't expect them to be read by anyone but the person who asked. As the text says, they are here to ask for clarification, not to *provide* it. They can be deleted without notice and no one will bother. I'll edit your last comment into your question for you now, but next time please do it on your own :)
Comment: check this module https://drupal.org/project/entityreference  as mentioned by @Jimajamma
Comment: Let's say I have two nodes. Artists and News. The artist node will have (at some point) related pictures, songs, and news. But at default it does not have any. So I wanted a variable that acts like a flag that if there are any related pictures the flag is changed.  In the news node, I have tags that point to an artist if the news is related to him/her, then I'll show the same related songs, pictures of the same tagged artist. I want the flag variable as a checker if there are truly related songs/pictures.   In that way I'll just use the flag and before I query the related pictures/songs
Answer: What you are looking for is, basically, Entity Reference, as mentioned by Jimajamma and Bala:

Provides a field type that can reference arbitrary entities

Just add entity reference field to news and allow artists to be selected. For pictures and songs, use either simply fields in Artist content type, or repeat the process - create content types for them, and add entity reference fields to artist content type.
Now, for display consider Views - it can use entity reference field to show all songs by artist in setup like that. I believe that's the easiest way.
Comment: I'll look into this. I'm not very familiar with drupal yet. I'll read in to this.
Answer: If you are using terms to relate the nodes, you can create a view that shows the related content by using relationships via the taxonomy term.
Then show the view on your node page and if there are no related content then the view will just not display.
You will still be running the query even if there are no results, but that shouldn't really be an issue unless you have a very complex view and very large amounts of content and no caching.
Another way you could do it if you prefer is to create a checkbox field on your node as the flag you refer to, then using the rules module you could set that flag on node save, based on other field data.
Then you could use that flag to do whatever you are planning.
I would recommend the first option though.
Comment: This is what I have done. and I use the views_get_view_results(). But Unfortunately, I'm going to query a very huge amount of data. Like in millions. Just imagine almost all artists with along with their songs along.


ajax form submission + modal

Question: So the problem when I click on submit it gives me this + no data is inserted into the db :
Screen shot of modal
I don't see any errors in the console.
my ajax code :

my form + modal :

                     <button type="button" class="close" data-dismiss="modal">×</button>

Add mew course

                      <form id="lmao"class="js-validation-courses form-horizontal push-10-t" data-async data-target="#add_data_Modal" action="add_c.php" method="post">

                                      <input class="form-control" type="text" id="course_title" name="course_title" >
                                      course title

                                          <input class="form-control" type="text"  id="course_cord"name="course_cord" >
                                          Course cord

                                              <input class="form-control" type="text"  id="course_hours"name="course_hours" >
                                              hours

                                                  <input class="form-control" type="text" id="course_price" name="course_price" >
                                                  price

                                  <button class="btn btn-sm btn-primary" name="add_course" id="submitForm" type="submit">Add course</button>

                        </form>

I have the add query in a separate file called add_c.PHP
so I have tried several answers from a lot of questions but I didn't manage to get something useful.
The PHP code in add_c.php :
Php code - pastebin
My knowledge is very small about ajax so I appreciate any help.
Comment: What is the value of `data`? If you put a breakpoint into the `success` function and inspect it, is it what you were expecting? If not, maybe what you were expecting is a property of `data`?
Comment: open your developer console and go to the network tab... fire your form ajax request and see if any request gets fired... the post request must be popping up, click on it, and click on response and see if you get any output
Comment: @sietse85 Yes I get in " Form Data " the output .. check the screenshot. [Screenshot](http://prntscr.com/j4ula1)
Comment: i see 2 requests XHR getting fired with your code, for a start try changing the button type to: button and not submit, your code triggers submission twice it seems
Answer: I tried your code, and the php file retrieves this post array
Array ( [course_title] => test [course_cord] => tet [course_hours] => tet [course_price] => tt )

your php code:
if(isset($_POST['add_course'])) {

add_course nevers gets posted, so it will never come into the if. Another issue is your form gets submitted twice the way you build it.
Change the button type into button, not submit. You already have a event listener on the button ;)
<button class="btn btn-sm btn-primary" name="add_course" id="submitForm" type="button">Add course</button>

Comment: did you change your if statement? as i said in the post above?
Comment: I did you deserve it !. one more thing how I can reset the form and display success msg  on top of the form?
Comment: `if(isset($_POST['course_title'])) {` for example ... also beware of possible SQL injection with the way you build it
Comment: but how? I use prepare  statement
Comment: I'm recommending that you follow some courses in javascript and php :) i cannot teach all, you have to teach yourself ;) There is tons of stuff on this subject on youtube for example for free ;)
Comment: i am not sure if prepared statements are 100 percent safe, just to be sure do some input validation on the post data ;)
Comment: also if you want to test for SQL injection attacks use nmap for example... that way you can see if your script is safe.

ajax form submission + modal


Significance of differences between two scenarios

Question: CAPTCHAs are used to distinguish legitimate human users from computerized programs that are trying to abuse online services. There is a way to bypass the security by relaying CAPTCHA challenges to remote human-solvers via crowdsourcing techniques.
A study was conducted. Four types of CAPTCHAs were solved by (1) legitimate human users, (2) human users after the CAPTCHA was streamed to their computer and their answer was collected (simulating the effect of a program relaying the CAPTCHA to crowdsourcing workers and then collecting the responses).
How could the significance of differences of completion time between the two scenarios (1) and (2) across the 4 different CAPTCHAs be analyzed?
Comment: Suggest you think in simpler terms:  how might time differences be analyzed in some routine situation where there are two conditions to be compared and where an independent variable can take on 4 values in each condition?
Comment: Can you do some designed experiment where you know the conditions, and know the correct assignment of situation for each data point?  Then, based on that, we could build a discrimination model (or see if such is going to work).
Answer: You probably could use ANOVA to analyze your data. (Anova stands for analysis of variance.)  But, if you need a statistical test to detect meaningful differences, then the differences may be too small to be of practical usefulness.  Why not start out with simple data summaries, such as means, standard deviations, and plots.  If you cannot notice sizeable differences, looking for small differeneces using statistical tests may or may not be helpful to you, depending on what you are planning to do based on your conclusions.
Comment: Response/waiting times are probably not close to normally distributed, but we could use the idea behind anova within some generalized linear model (maybe with gamma distributed variables?).
Comment: Checking the distribution is a good idea if you are going to conduct a statistical test.  It might be a good idea in any case.  Sometimes differences in variance or other measures are as important or more important as a differences in means.


Como criar link para chamar o resource destroy?

Question: Tenho uma view blade com a seguinte estrutura:
@forelse($posts as $p)

    id }}">{{ $p->titulo }}
    {{ $p->status_mutator }}
    {{ $p->user->name }}
    {{ $p->created_at->format('d/m/Y à\s H:i:s')}}

        id }}/edit">Editar /
        id }}">Excluir

@empty

    Não existem posts para serem listados

@endforelse

Mas minha rota utiliza a estrutura resource, ou seja, tenho que submeter a opção de Excluir via método DELETE. Alguma ideia de como fazer isso?
Comment: Excluir algo por meio de um simples link é inseguro. Melhor você criar um formulário, definir o método "DELETE" para a rota e utilizar um botão ou um evento em um link que submeta o formulário
Comment: Sim a ideia é essa. Conforme havia dito quero utilizar o método DELETE (verbo DELETE) via form. Só preciso de ajuda para construir algo em JavaScript que capture o id do link clicado e submeta o form
Answer: Você deve trocar o link por um formulário, da seguinte forma:
Substitua isso:

        id }}/edit">Editar
        id }}">Excluir

Por isso:

    id }}/edit">Editar
    <form actio="/painel/post/{{ $p->id }}" ...>
        <button type="submit">Excluir</buttom>
    </form>

Se por questão de estilo você quer manter o link. Você deve capturar o evento de clique do link e submeter o formulário dinamicamente.
Supondo que você utilize jQuery, o código vai ser +- esse(Não testei):
HTML:

    id }}/edit">Editar /
    <form actio="/painel/post/{{ $p->id }}">
        Excluir
    </form>

Javascript:

UPDATE
Já ia me esquecendo. O metodo DELETE não é suportado pelo HTML em formulário. Então você deve postar, por meio de um campo do tipo "hidden" o método utilizado. +- Assim.
 <input type="hidden" name="_method" value="delete"/>

Answer: Pode também utilizar um callback Javascript para fazer isso utilizando o Fetch:
id }}')">...

function deletarPost(id) {
    fetch('/painel/post/' + id, { method: 'DELETE' })
        .then(() => alert("Deletado com sucesso!");
}


How can I say about these two compact sets?

Question: My problem:
Suppose $E \subset [0,1]$ and $C \subset [0,1]$ are two compact sets such that $E \subsetneq C$ and $\mathop C\limits^ \circ
=\mathop E\limits^ \circ
=\emptyset$ and $|E|=|C|=0$.
Can I say that there exist $0 \leq a<b \leq 1$ such that $]a,b[ \subset [0,1]-C$ and $\{a,b\} \cap C-E \neq \emptyset$?
My attempt:
I tried writing $C^c$ as an opportune union of connected components, but I cannot reach any conclusion.
Comment: I understand you are looking for $0 \leq a < b \leq 1$ so that $]a,b[ \subset [0,1]-C$ and $\{ a, b\} \cap C-E\neq \emptyset$. Does this rephrase your question?
Comment: I think that you have a quantifier problem here: it should probably be "there exists $t_0$ such that for all $t$, blah blah if $t<t_0$ and blah blah otherwise".
Comment: @FormulaWriter Yes you are right, this rephrase my question and it looks better.
Comment: @ArnaudMortier I meant $\exists t$ and $\exists t_0$. Maybe FormulaWriter's comment is clearly stated.
Comment: @FilippoGiovagnini Ok, then I think it is better that you edit your question accordingly, for as it is currently stated it does not look so clear.
Comment: @FormulaWriter I edited the question as you remarked.
Answer: HINT:
Pick a point $x\in C-E $.
$E$ is closed, therefore you can find $r>0$ so that $(x-r, x+r)\cap E = \emptyset$. Now look for suitable $a,b \in (x-r, x+r)\cap [0,1]$.
EDIT: adding further details.
Suppose $x\neq 1$ and define $A:=(x,x+r)$.
If $A\cap C = \emptyset$, a possible solution is $a=x,$ $b= \min\{x+r,1\}$.
Suppose now $y \in A\cap C$. The interval $(x,y)$ cannot be a subset of $C$, because $\mathop C\limits^ \circ = \emptyset$. For this reason, there exists $ z\in (x,y) - C$. You can now choose $(a,b)$ as the connected component of $z$ in $C^c$.
If $x=1$, you can look at $B:=(x-r,x)$ instead of $A$ and exploit the same idea.
Comment: In my experience, when the question seems a bit odd, more often than not a couple of well-intended people try their best still answering it until the OP realizes that they did not really mean what they have asked.
Comment: It may be syntaxically correct but it is still weirdly stated.
Comment: The question can be reworded better, nevertheless what is asked is quite clear I think.
Comment: Ok, I see your point.
Comment: @FormulaWriter I did not undestand the case $A \cap C = \emptyset$. Could you please explain it clearer?
Comment: @FilippoGiovagnini I edited the answer to make it clearer, let me know if you have any doubts left


Insert mode default keys in vim

Question: The following items are useful to me in editing text, and I was wondering if vim had something for this built out of the box (though I didn't see it on the https://vimhelp.org/index.txt.html#index.txt page), or I had to create mappings for it:

Forward-delete a character. This is X in normal mode.
Forward-delete all text to the right of the cursor on the line. This is the inverse of ctrl-u.

Are either of these mappings available? And if not, are there 'standard' mappings for this that are common (for example, how it might be done in another unix program).
Note that this is the keyboard I have -- there is only one delete key (which acts like a normal backspace key) and there is no backspace key:

Note: for forward-delete, I am currently mapping ctrl-d as:
"Ctrl-d to forward-delete when in insert or command mode
noremap! <C-d> <Delete>

However, this interferes with the tab in insert mode (which I don't use) and the help-options in command mode (which I do use!) so I may have to modify this later, or hopefully someone suggests a better solution.
Answer:
though I didn't see it on the https://vimhelp.org/index.txt.html#index.txt page

If you can't find it in the documentation, then it doesn't exist.

You can use fn+delete for "Forward-delete a character".

"Forward-delete all text to the right of the cursor on the line" is ctrl+k in MacOS, but Vim has its own use for that combo, :help i_ctrl-k so it is up to you to create a mapping for it.
Something like:
inoremap <key> <C-o>ld$

Insert mode default keys in vim


Junção de colunas: HTML5 e Angular

Question: Galera, estou querendo saber como eu posso fazer essa junção com o angularjs? Vi que tem o ng-repeat-start e o end, mas não consegui implementar.
Comment: Talvez isso te ajude (SO em inglês): http://stackoverflow.com/questions/21104750/use-of-rowspan-to-group-hierarchical-data#26834906
Comment: Você precisa colocar o JSON que está usando de modelo para montar as tabelas.
Answer: O recurso de unir linhas no HTML é o rowspan.

HTML  rowspan Attribute
Original: The rowspan attribute specifies the number of rows a cell should span.
Tradução livre: O atributo rowspan especifica o número de linhas que uma célula deve ocupar.

Considerando o seguinte JSON:
[
  {
    lab: 'Lab1',
    slogan: 'slogan 1',
    analista: 'Analista 1',
    documento: 'Documento 1'
  },
  {
    lab: 'Lab1',
    slogan: 'slogan 1',
    analista: 'Analista 2',
    documento: 'Documento 2'
  },
  {
    lab: 'Lab1',
    slogan: 'slogan 1',
    analista: 'Analista 3',
    documento: 'Documento 3'
  },
  {
    lab: 'Lab2',
    slogan: 'slogan 2',
    analista: 'Analista 4',
    documento: 'Documento 4'
  }
]

Criei uma função organizar que transforma-o em:
[
  {
    lab: 'Lab1',
    slogan: 'slogan 1',
    documentos: [{
      analista: 'Analista 1',
      documento: 'Documento 1'
    }, {
      analista: 'Analista 2',
      documento: 'Documento 2'
    }, {
      analista: 'Analista 3',
      documento: 'Documento 3'
    }]
  },
  {
    lab: 'Lab2',
    slogan: 'slogan 2',
    documentos: [{
      analista: 'Analista 4',
      documento: 'Documento 4'
    }]
  }
]

Sendo assim apliquei o rowspan e percorri o elemento que foi formado (documentos) para criar as outras linhas. Note que criei um ng-repeat adicional que ignora o registro de índice 0 para que as demais linhas sejam mostradas. Exemplo funcionando a seguir:

angular
  .module('meuModulo', []);

angular
  .module('meuModulo')
  .controller('MeuController', MeuController);

MeuController.$inject = [];

function MeuController() {
  var vm = this;

  iniciar();

  function iniciar() {
    var base = [{
        lab: 'Lab1',
        slogan: 'slogan 1',
        analista: 'Analista 1',
        documento: 'Documento 1'
      },
      {
        lab: 'Lab1',
        slogan: 'slogan 1',
        analista: 'Analista 2',
        documento: 'Documento 2'
      },
      {
        lab: 'Lab1',
        slogan: 'slogan 1',
        analista: 'Analista 3',
        documento: 'Documento 3'
      },
      {
        lab: 'Lab2',
        slogan: 'slogan 2',
        analista: 'Analista 4',
        documento: 'Documento 4'
      }
    ];
    ordenar(base);
  }

  function ordenar(base) {
    var organizados = {};
    vm.dados = [];

    angular.forEach(base, function percorrer(item) {
      if (angular.isUndefined(organizados[item.lab])) {
        organizados[item.lab] = {};
        organizados[item.lab].lab = item.lab;
        organizados[item.lab].slogan = item.slogan;
        organizados[item.lab].documentos = [];
      }

      organizados[item.lab].documentos.push({
        analista: item.analista,
        documento: item.documento
      });
    });

    for (var lab in organizados) {
      vm.dados.push(organizados[lab]);
    }
  }
}
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}

          {{dado.lab}}
          {{dado.slogan}}
          {{dado.documentos[0].analista}}
          {{dado.documentos[0].documento}}

 0">
          {{documento.analista}}
          {{documento.documento}}

Resposta para uma pergunta similar no StackOverflow: Use of rowspan to group hierarchical data

Junção de colunas: HTML5 e Angular


Boost Circular Buffer push_back inserts data at front

Question: I have below code:
#include "boost/circular_buffer.hpp"

int main()
{
    // Create a circular buffer with a capacity for 3 integers.
    boost::circular_buffer<int> cb(3);

    // Insert threee elements into the buffer.
    cb.push_back(1);

    int a = cb[0];  // a == 1

}

As per documentation push_back API means "Insert a new element at the end of the circular_buffer" - then how cb[0] is 1? Shouldn't cb[2] should store value 1?
=======================================UPDATE=============================
// Insert threee elements into the buffer.
cb.push_front(11);
cb.push_back(2);
cb.push_back(3);

int a = cb[0];  // a == 11
int b = cb[1];  // b == 2
int c = cb[2];  // c == 3

It seems that in case there are 0 elements in an buffer it takes up the first but if the same has one then it puts it at the end
Comment: You're confusing yourself by overthinking this. The behaviour of `push_back` is consistent and does not depend on how many elements there are to begin with. It adds one to the logical end, period. I think you're just misunderstanding what "start" and "end" mean in this context.
Answer: No. The buffer has capacity for three elements, but only contains one.
When you do your first push_back, you push to the end of a series of zero elements. So the new element becomes the first.
If you want to fill it up completely on construction, you can do that! Just like you would with a vector:
boost::circular_buffer<int> cb(3, 0);

But then, your first push_back will still alter cb[0], because it's a circular buffer! That means it wraps around to the front when full. cb[3] is out of range. There is no cb[3].
Comment: @Programmer Sorry, I don't know how else to explain it. It's pretty simple. You start with no elements. Then you add an element. So now you have one element. That's the first element, out of a total of one element.
Comment: Thanks  - yes the last index will be 2 - cb[2] - however can you please exaplain "push to the end of a series of zero elements. So the new element becomes the first."?
Comment: Thanks I have updated the question as per my understanding and noted the behaviour as mentioned by you
Answer: No, because the element got inserted at the end of the buffer.
This is your empty buffer:
[ ] [ ] [ ]

After calling push_back(1) it looks like this:
[1] [ ] [ ]

After calling `push_back(2) it looks like this:
[1] [2] [ ]

Comment: @Programmer -- The documentation is not confusing if you don't read so much into it.  It does mean "the item is placed in the back", but that is conceptual.  Internally, multiple things are happening to keep the integrity of the circular queue.  The "front" needs to be adjusted, `begin()` is now changed, etc.  So the optimal way of doing a "push_back" is to merely overwrite the element that was "front" and adjust `begin()` and `front()`.
Comment: @Programmer It's the same terminology used by standard containers like vector. So if you understand those (from your book) then you understand this. The underlying reserved memory is not the same as the "logical" collection of elements that you have added to the container.
Comment: Because it's pushing the element to the back, that's what I was trying to explain. 'back' doesn't refer to the last cell in the buffer but to the first free cell, meaning the last of all occupied cells
Comment: Yes that seems the case - then why API is called push_back()?
Comment: Yes as per output it matches what you state - but - https://www.boost.org/doc/libs/1_61_0/doc/html/boost/circular_buffer.html#idp8551216-bb states - "Insert a new element at the end of the circular_buffer. " - I agree to what you state based on the ouput but the documentation is probably confusing


Defining censoring level in survival analysis

Question: I'm conducting a simulation analysis using the Exponential, Weibull and Gompertz distribution. To get the times I'm using the table from Austin 2012.

But how can I define the censoring level to be ~30%, ~40% and ~50%?
For the censored observations I'm using $Y_{i} \sim U(0,b)$. The problem is I'm selecting $b$ by trial and error. How can I select $b$ in a general way to give me the censoring levels needed?
Thanks in advance!
Comment: Are you just simulating based on a single combination of covariate values, or are you simulating over ranges of covariate values?
Comment: On a single combination of covariates.
Answer: If you only have a single combination of covariate values, then $\exp(\beta'x)$ is the same for all of your simulated values. It can thus be included in a single adjusted value of $\lambda$ for any of those distributions, if they are parameterized as above with respect to covariates $x$.
This Math Stack Exchange page shows the approach given the event probability distribution as a function of time, $f(t)$. If the censoring time $C\sim U(0,b)$ and event times are $T$, then the probability of censoring is:
$$P(C<T) = P(C<T \ \& \ T<b) + {P(T \ge b)}.$$
That is, all event times of $b$ or greater are censored, along with a fraction of those at earlier times. Given $f(t)$ you then solve for $b$ to get the desired $P(C<T)$.
The second term is:
$${P(T \ge b)} = \int_b^{\infty} f(t) dt.$$
The first term is:
$$P(C<T \ \& \ T<b) =\frac{1}{b}\int_0^b tf(t) dt.$$
For the exponential, the linked page shows
$$P(C<T)=\frac{1-e^{-\lambda b}}{\lambda b},$$
for the following curve of censoring probability versus $b/\lambda$:

In principle you can do this for any distribution of event times $f(t)$ and censoring based on a uniform distribution.
If you have already generated a set of $N$ (uncensored) event times $t_i$, you have an empirical distribution with $f(t_i)=1/N$ and 0 for other values of $t$. Plugging into the above general formula for censoring probability gives:
$$P(C<T) = \frac{\sum_{t_i <b} t_i+b\sum I(t_i\ge b)}{bN}, $$
which is pretty easy to solve for a desired value of $b$. With the empirical distribution it doesn't matter from which (if any) parametric distribution you drew, or whether you used a single set of covariate values or let them vary. Some simple R code:
censSolve <- function(b,t,cp) {abs(cp - (sum(t>=b) + sum(t[t<b])/b)/length(t))}
optimize(censSolve, interval=c(min(tvals),max(tvals)), t=tvals, cp=targetCensProb)$minimum

where tvals is your vector of uncensored event times and targetCensProb is your desired censoring probability should do the trick to return your desired value of $b$.
Comment: Thanks for the clear and concise explanation! I tried the code and works perfectly as well. Very appreciated!


Ansible to Conditionally Prompt for a Variable?

Question: I would like to be able to prompt for my super secure password variable if it is not already in the environment variables. (I'm thinking that I might not want to put the definition into .bash_profile or one of the other spots.)
This is not working. It always prompts me.
vars:
  THISUSER: "{{ lookup('env','LOGNAME') }}"
  SSHPWD:   "{{ lookup('env','MY_PWD') }}"

vars_prompt:
  - name: "release_version"
    prompt: "Product release version"
    default: "1.0"
    when: SSHPWD == null

NOTE: I'm on a Mac, but I'd like for any solutions to be platform-independent.
Comment: @AnnTheAgile When you hardcode the above variable (SSHPWD) to some dummy / actual value, did the above piece of code work for you, i.e. for NOT prompting you at all? My understanding is, it'll alway prompt you no matter whether SSHPWD was set to `null` or was set to a valid value (if hardcoded to some value instead of using/depending upon an ENV variable).
Answer: According to the replies from the devs and a quick test I've done with the latest version, the vars_prompt is run before "GATHERING FACTS". This means that the env var SSHPWD is always null at the time of your check with when.
Unfortunately it seems there is no way of allowing the vars_prompt statement at task level.
Michael DeHaan's reasoning for this is that allowing prompts at the task-level would open up the doors to roles asking a lot of questions.  This would make using Ansible Galaxy roles which do this difficult:

There's been a decided emphasis in automation in Ansible and asking questions at task level is not something we really want to do.
However, you can still ask vars_prompt questions at play level and use those variables throughout tasks.   You just can't ask questions in roles.
And really, that's what I would like to enforce -- if a lot of Galaxy roles start asking questions, I can see that being annoying :)
Comment: good explanation for the ordering of GATHERING FACTS vs vars_prompt part.
Answer: I might be late to the party but a quick way to avoid vars_prompt is to disable the interactive mode by doing that simple trick:
echo -n | ansible-playbook -e MyVar=blih site.yaml

This add no control over which vars_prompt to avoid but coupled with default: "my_default" it can be used in a script.
Full example here:
---
- hosts: localhost
  vars_prompt:
    - prompt: Enter blah value
    - default: "{{ my_blah }}"
    - name: blah

echo -n | ansible-playbook -e my_blah=blih site.yaml
EDIT:
I've found that using the pause module and the prompt argument was doing what I wanted:
---
- pause:
      prompt: "Sudo password for localhost "
  when: ( env == 'local' ) and
      ( inventory_hostname == "localhost" ) and
      ( hostvars["localhost"]["ansible_become_password"] is not defined )
  register: sudo_password
  no_log: true
  tags:
       - always

Answer: Based on tehmoon's answer with some modifications I did it that way:
- hosts:
    - hostA
  become: yes
  pre_tasks:
    - pause:
        prompt: "Give your username"
      register: prompt
      no_log: yes
      run_once: yes
    - set_fact:
        username: "{{prompt.user_input}}"
      no_log: yes
      run_once: yes
    - pause:
        prompt: "Give your password"
        echo: no
      register: prompt
      no_log: yes
      run_once: yes
    - set_fact:
        password: "{{prompt.user_input}}"
      no_log: yes
      run_once: yes
  tags: [my_role_using_user_pass]
  roles:
    - role: my_role_using_user_pass

Comment: Thanks! I use tag and this works for me without 2 last lines (roles: and - role:)
Answer: This is indeed not possible by default in Ansible. I understand the reasoning behind not allowing it, yet I think it can be appropriate in some contexts. I've been writing an AWS EC2 deploy script, using the blue/green deploy system, and at some point in the role I need to ask the user if a rollback needs to be done if something has gone awry. As said, there is no way to do this (conditionally and/or non-fugly).
So I wrote a very simple Ansible (2.x) action plugin, based on the pause action from the standard library. It a bit spartan in that it only accepts a single key press, but it might be of use. You can find it in a Github gist here. You need to copy the whole Gist file to the action_plugins directory of your playbook directory. See the documentation in the file.
Comment: Pleae include the relevant part of your link in your answer. GitHub depositories may change at any time. Thanks.
Comment: The whole file is the relevant part. It's a module than needs to be included wholly to add extra functionality to Ansible. I added a bit more documentation to the anwer. If you mean 'relevant git commit': if I find a bug tomorrow I want future visitors to see the newer version.
Answer: As can be seen in the source code, the when keyword isn't implemented for vars_prompt (and in fact never was). The same was mentioned in this Github comment.
The only way in which vars_prompt is currently conditional is that it only prompts when the variable (defined in name) is already defined (using the command-line extra_vars argument).
Answer: This works for me (2.3) .. do two bits in the one file.
This allows me to consruct a tmp vars file when running the playbook via jenkins.. but also allow prompting on the command line
And you get to do it with only the one var used
---
- name: first bit
  hosts:                            all
  connection:                       local
  tasks:
  - set_fact:
      favColour:                   "{{ favColour }}"
    when: favColour is defined

- name: second bit
  hosts:                            all
  connection:                       local
  vars_prompt:
    favColour:
      prompt:                       "Whats ya favorite colour: "
    when: favColour is not defined

  tasks:
    - debug:                        msg="{{favColour}}"

Answer: Based on @tehmoon's answer, this is what worked for me with ansible-core 2.14:
  tasks:
    - name: Prompt SSH password if necessary
      when: ansible_password is undefined
      block:
        - name: Conditionally prompt for ssh/sudo password
          ansible.builtin.pause:
            prompt: "Password for {{ ansible_user_id }}@{{ ansible_host }}"
            echo: false
          register: password_prompt
          no_log: true

        - name: Set ansible_password
          ansible.builtin.set_fact:
            ansible_password: "{{ password_prompt.user_input }}"
          no_log: true

    - name: Set ansible_become_password
      ansible.builtin.set_fact:
        ansible_become_password: "{{ ansible_password }}"
      no_log: true
      when: ansible_become_password is undefined


Different stdout with supervisord using docker vs docker-compose

Question: I have a service running inside docker using nginx and php-fpm. I have been beating my head against the wall to get all of the logs to redirect to stdout. The approach that I took was to use supervisord. Using docker-compose up my-app everything worked as expected; all of the logs are being sent to stdout. However, when I run
docker run -p 81:80 \
       -v $(pwd)/myapp:/var/www/html \
       my-app

I get no output.
Here is my supervisor configuration:
[supervisord]
nodaemon=true
user=root

[program:php-fpm]
command=/usr/sbin/php-fpm7.0 -F

[program:nginx]
command=/usr/sbin/nginx -g "daemon off;"

[program:nginx-log-access]
command=/usr/bin/tail -f /var/log/nginx/access.log
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
autorestart=true

[program:nginx-log-error]
command=/usr/bin/tail -f /var/log/nginx/error.log
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
autorestart=true

[program:php-fpm-log]
command=/usr/bin/tail -f /var/log/php7.0-fpm.log
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
autorestart=true
startsecs=3

[program:laravel-log]
command=/usr/bin/tail -f /var/www/html/storage/logs/laravel.log
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
autorestart=true

and my docker-compose
version: '3'
services:
  my-app:
    build:
      context: ../../my-app
      dockerfile: docker/Dockerfile
    image: my-app
    ports:
     - "81:80"
    volumes:
    - ../../my-app:/var/www/html

my base dockerfile
FROM ubuntu

# Update
RUN apt-get update --fix-missing && apt-get -y upgrade

# Install Python Setup Tools
RUN apt-get install -y python-pip

# Intall Supervisord
RUN easy_install supervisor

# Install NGINX
RUN apt-get -y install nginx

# Install PHP
RUN apt-get -y install php7.0-fpm \
    php7.0-mbstring \
    php7.0-xml \
    php7.0-curl

# Configure PHP-FPM
RUN sed -i 's/;daemonize = .*/daemonize = no/' /etc/php/7.0/fpm/php-fpm.conf && \
    sed -i "/;clear_env = .*/c\clear_env = no" /etc/php/7.0/fpm/pool.d/www.conf && \
    sed -i -e 's/max_execution_time = 30/max_execution_time = 300/g' /etc/php/7.0/fpm/php.ini && \
    sed -i -e 's/upload_max_filesize = 2M/upload_max_filesize = 50M/g' /etc/php/7.0/fpm/php.ini && \
    sed -i -e 's/post_max_size = 8M/post_max_size = 50M/g' /etc/php/7.0/fpm/php.ini && \
    sed -i -e "s/variables_order = \"GPCS\"/variables_order = \"EGPCS\"/g" /etc/php/7.0/fpm/php.ini && \
    service php7.0-fpm start && \
    service php7.0-fpm stop

COPY supervisor.conf /etc/supervisor/conf.d/supervisor.conf

CMD ["supervisord", "-n", "-c", "/etc/supervisor/conf.d/supervisor.conf"]

and my application dockerfile
FROM mybase

# Configure NGINX
COPY docker/dev2/default.conf /etc/nginx/sites-enabled/default

# Copy application into container
COPY . /var/www/html

RUN touch /var/www/html/storage/logs/laravel.log && \
    chown www-data:www-data /var/www/html/storage/logs/laravel.log && \
    chmod 644 /var/www/html/storage/logs/laravel.log

COPY docker/dev2/supervisor.conf /etc/supervisor/conf.d/supervisor.conf

CMD ["supervisord", "-c", "/etc/supervisor/conf.d/supervisor.conf"]

What is the difference between docker and docker-compose where redirection to stdout is behaving differently? These containers will be deployed in AWS ECS; I haven't tested this yet, but I am fearful that I will not get successful logging in ECS if I am experiencing this behavior with docker. Any thoughts, ideas, or suggestions would be greatly appreciated!
Answer: When you run docker-compose up output from all docker containers is aggregated and displayed in the console as per
https://docs.docker.com/compose/reference/up/
When you simply run docker run the output is not shown and can only be retrieved with docker logs -f $CONTAINERID
You can also "hide" output with docker compose by using -d flag.
When you run your docker containers in ECS, in the task definition, you can choose the logdriver from the list
http://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_LogConfiguration.html
Hope this helps.


Uniqueness of functional equation amongst smooth functions?

Question: Conjecture: the functional equation $x \cdot F(x) - (1-x) \cdot F(1-x) \equiv 0$
has a unique "family" of solutions $x \mapsto \frac{K}{x}$ (indexed by the real number $K$) if we restrict ourselves to smooth functions on $(\epsilon, 1-\epsilon)$ for some small $\epsilon$.
Is this true?
If we do not restrict ourselves to smooth functions uniqueness does clearly not hold. You can take some function $G$ and let $F = \mathcal{1}_{\{x > 0.5\}} \cdot G(x) + \mathcal{1}_{\{x \leq 0.5\}} \cdot \frac{1-x}{x} \cdot G(1-x) $. This will even be continuous if $G$ is continuous.
Answer: From the relation that $F$ has to satisfy we get
\begin{equation}
F(x)=\frac{1-x}{x}F(1-x),
\end{equation}
therefore we only need to define $F$ in the segment $(\epsilon, \frac{1}{2}]$. Take a smooth function $\phi$ with support in $[\frac{1}{6}, \frac{1}{3}]$ and define $F(x)=\phi(x)$ for $x$ in $(\epsilon, \frac{1}{2}]$. Now you can define $F$ by symmetry in the remaining region.


Check if there are missing arguments in enclosing call using C/Rcpp

Question: I need to use function written in C or Rcpp to check if enclosing R call had missing arguments. Is that possible to do? If so how?
Here is what I came up with after reading some R source code.
Rcpp::cppFunction('
void check_missing(SEXP e) {
  Rcpp::Environment env(e);
  Rcpp::CharacterVector names = env.ls(false);
  SEXP unevaluatedArg;
  for(int i=0; i<names.length(); i++){
    std::string name = as<std::string>(names[i]);
    Rcpp::Rcout << "argument - " << name << std::endl;
    SEXP nameSym = Rf_install(name.c_str());
    unevaluatedArg = Rf_findVarInFrame(e, nameSym);
    if (MISSING(unevaluatedArg) || CAR(unevaluatedArg) == R_MissingArg) {
      Rcpp::Rcout << "missing" << std::endl;
    }
  }
}')
f <- function(x, y) {
  check_missing(environment())
}
f()

But somehow MISSING(unevaluatedArg) || CAR(unevaluatedArg) == R_MissingArg never evaluates to TRUE. Is it because I am enumerating the environment? Or what is going wrong?
P.S. I have reasons for doing that in C, rather than using standard missing, because in my project check_missing needs to be applied to any environment, and here I just gave a simplified case.
Answer: You need if ( unevaluatedArg == R_MissingArg){ ... }. This slightly modified code works for me:
#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
void check_missing(SEXP e) {
  Rcpp::Environment env(e);
  Rcpp::CharacterVector names = env.ls(false);
  SEXP unevaluatedArg;
  for(int i=0; i<names.length(); i++){
    std::string name = as<std::string>(names[i]);
    Rcpp::Rcout << "argument - " << name << std::endl;
    SEXP nameSym = Rf_install(name.c_str());
    unevaluatedArg = Rf_findVarInFrame(e, nameSym);
    if ( unevaluatedArg == R_MissingArg) {
      Rcpp::Rcout << "missing" << std::endl;
    }
  }
}

Giving:
> f()
argument - x
missing
argument - y
missing

> f(1)
argument - x
argument - y
missing


Translating taxonomy list name for a custom link in rewrite result field

Question: Very hard to describe this problem in a title. Let me explain:
I have a taxonomy list named 'Meubelen'. I translated the name to 'Meubles' for the French version of the website.
I created a view of the terms in this list (an overview of categories). An image of a representative node is shown for each term. I like te rewrite the output of this image to a link directing to the taxonomy page. I can do this for one language, like this:
 meubelen/[term-name]

But this should change to
 meubles/[term-name]

when visiting the French side of the website.
How can I achieve this? There's no translatable field for this view that I can add and use as variable.
Answer:
How can I achieve this? There's no translatable field for this view that I can add and use as variable.

Really?!? If you have a representative node of the category content (with the proper language set) you should be able to have a relationship to that nodes language settings, and also the url path to nodes' url path for say, French, in this case.
There's no token support to Rewrite the link in Views to the path with X language setting for the node? .... eg, under Replacement Tokens for the field there's no configurable token for like, node:path:lang:YOUR-LANG or something similar -- I typically dont do internation sites, but i'm 99% sure this type of flexability comes out of the box.
Comment: Maybe I wasn't clear enough. I'm not trying to find the i18n-name for the node, but for the taxonomy list name.. I use the name of the list in Pathauto, like so:

http://www.example.com/nl/**meubelen**/tafel
http://www.example.com/fr/**meubles**/table

I'd like to link the image of a representative node to the terms page. But in Views, I can't find the right translatable field for the bold part to use in rewrite field.