Unity: Quiz game multiple choice button colors

Question: I'm doing a multiple choice quiz game, and im tryinng to highlight the correct answer in green if the wrong answer is clicked. for example if i have A , B , C and D and "A" is the correct answer. i want if i choose "B" to turn B to red color and display the correct answer to green which is in this case "A". Right now i have if i click the right answer it displays green, as i want it. and if i press wrong answer it displays red. what im missing is when i click wrong answer i want to also highlight the correct answer.
Here's my functions:
In the Game controller:
public bool theAnswerIsCorrect;

public bool IsCorrected()
{
    return theAnswerIsCorrect;
}

public void AnswerButtonClick(bool isCorrect)
{
    if (isCorrect)
    {
        Debug.Log("I'm Correct");
        theAnswerIsCorrect = true;
        playerScore += currentRoundData.pointAddedForCorrectAnswer;
        scoreDisplayText.text = "Score: " + playerScore.ToString();

    }

    else
        theAnswerIsCorrect = false;

    // Do we still have questions?
    if (questionPool.Length > questionIndex + 1)
    {
        //questionIndex++;

        UpdateQuestionIndex();
        StartCoroutine(DelayTime(3));
      //  ShowQuestion();
    }

    else
    {
        EndRound();
    }
}

And this is an a class that just holdes my data
public class answerData {

public string answerTxt;
public bool isCorrect;

}

This is being used in the ButtonClick function (the code in the begging of the question) -> this line
        gameController.AnswerButtonClick (AnswerData.isCorrect);

And in the inspector i specify by the bool what is the correct answer
*** NEW SCRIPT HERE "Picking up the Correct button"
// store reference to btn text
public Text answerText;

private answerData AnswerData;
private GameController gameController;

public static AnswerButton _instace;

private void Awake()
{
    _instace = this;
}

// Use this for initialization
void Start ()
{
    gameController = FindObjectOfType<GameController> ();

}

public void Setup(answerData data)
{
    AnswerData = data;
    answerText.text = AnswerData.answerTxt;
}

IEnumerator ReturnButtonColor()
{
    yield return new WaitForSeconds(2.9f);
    GetComponent<Button>().image.color = Color.white;
    Debug.Log("HiB");

}

public void HandleClick()
{
    gameController.AnswerButtonClick (AnswerData.isCorrect);

    if (gameController.IsCorrected())
    {
       GetComponent<Button>().image.color = Color.green;
        Debug.Log("im true");
        StartCoroutine(ReturnButtonColor());

    }

    else
    {
        GetComponent<Button>().image.color = Color.red;
      //  gameController.IsCorrected().image.color = Color.green;
        StartCoroutine(ReturnButtonColor());

    }

}

Thank you
Comment: You'll need to have a way to get a reference to the correct answer button so you can turn it green.  Maybe you can add a method to your gameController to return the correct button, then call that inside your else clause.  From there, you know how to switch it's color.
Answer: Like using GetComponent<Button>().image.color = Color.green; in the if statement , you could simply add in /*Button A*/.image.color = Color.green; in the else statement.
Comment: At the moment where you initialize your buttons set a `Tag` on the `Button` which holds the correct answer
Comment: i basically need the correct answer to turn green if wrong asnwer is clicked. in the 1st if statement it's easy because im just calling the function that checks for me if the answer is correct or not. but im not sure how will it be in the else statement..
Comment: If you studied generics, simply in `GetComponent` , you just put in what you named ButtonA(Or the class)  in ``
Comment: Im pooling all of my buttons. so actually on the first time i just instantiate them.. so i have no idea how to get "BUTTON A"
Comment: You will need to get a way to get the reference to the correct answer button. You can create a new method/function that returns the correct button to see what you get.
Comment: i am alrady doing that. the correct button has a public bool that returns if it's correct or not. What i dont know what to do is how to call the correct answer button. as you can see in the function posted i have an if and a else the first if i call function that check for the correct answer. The issue now is in the else, i also want to display the correct answer. Im not sure how to do that in the else, i can't get the BUtton A
Answer: What @BadWolf in the comments is saying is the correct answer. If you need more coding help you have to include more information. How do you determine the Correct Button? Does it have a special name in the Scene? Does the gameController know which button is the correct? It seems gameController knows which Button is the correct one so you should create a method which will look something like:
public Button GetCorrectButton(){
    return theCorrectButton;
}

I don't know the code for how you see if it is the correct button but I'm guessing you have some way where you use the Correct Button. Find the Correct Button and return it in the method GetCorrectButton.
which you will then use in your code like:
public void ButtonClick()
{
    gameController.AnswerButtonClick (AnswerData.isCorrect);

    if (gameController.IsCorrected())
    {
        GetComponent<Button>().image.color = Color.green;
        Debug.Log("im true");
        // StartCoroutine(ReturnButtonColor());
    }
    else
    {
        GetComponent<Button>().image.color = Color.red;
        // Like this:
        gameController.GetCorrectButton().image.color = Color.green;
    }
}

I can be more specific if I get some more information/code to see!
Comment: Hi again :), can you check the updated question pls?
Comment: I can't do this         gameController.GetCorrectButton().image.color = Color.green;
 because im not returning the button i just return a bool, the button itself is in a different script
Comment: Well you need to find the Button somehow. In the different script, how do you find it?
Answer: I am assuming that all option button have same script attached.
Create one delegate and register this in your script which is attached to your option button.
Like this
Create delegate and event
#region DELEGATES
public delegate void OnQuestionOptionClicked ();
public static event OnQuestionOptionClicked onQuestionOptionClicked;
#endregion

#region DELEGATE_CALLS
private void RaiseOnQuestionOptionClicked ()
{
    if (onQuestionOptionClicked != null)
        onQuestionOptionClicked ();
}
#endregion

Register it
void OnEnable ()
{
    onQuestionOptionClicked += OnQuestionOptionClicked;
}

void OnDisable ()
{
    onQuestionOptionClicked -= OnQuestionOptionClicked;
}

#region DELEGATE_EVENT_LISTENER
void OnQuestionOptionClicked ()
{
    GetComponent<Button>().interactable = false;
    if (AnswerData.isCorrect){
        GetComponent<Button>().image.color = Color.green;
        Debug.Log("im true");
    }
}
#endregion

Your setup method
public void Setup(answerData data)
{
    AnswerData = data;
    answerText.text = AnswerData.answerTxt;
    GetComponent<Button>().interactable = true;
    GetComponent<Button>().image.color = Color.white;

}

And on button click event
#region BUTTON_CLICK_LISTENER
public void ButtonClick()
{
    gameController.AnswerButtonClick (AnswerData.isCorrect);

    if (!gameController.IsCorrected())
    {
        GetComponent<Button>().image.color = Color.red;
        Debug.Log("im true");
        // StartCoroutine(ReturnButtonColor());
    }

    RaiseOnQuestionOptionClicked ();
}
#endregion

Hope this solution helps you.;)
Comment: ty, but i actually don't understand your solution.. Whenever i click on wrong button i want to display the clicked button red and change the correct button to green. this way i show the user the correct answer before going to th next question
Comment: your solution gives the exact same behavior that i currently have.. my issue is that i can't figure out how to change the correct button to green only IF the user choose the wrong asnwer
Comment: Have you add this code in your project. I mean use this code??
Comment: What - "gameController.IsCorrected()" Return

Can you please share this function?
Comment: it's alrady in the question, it's in the first part of the question, the 1st function
Comment: i think AnswerData.isCorrect refrence variable that holds option text and it is correct or not, and it is in all option button. Am i right??
Comment: what do u mean option button? and yes AnswerData cariesthe check if it's correct or not and the answer text. and in this line i pass it "gameController.AnswerButtonClick (AnswerData.isCorrect);"
Comment: i have Update my answer please check and let me know if it is working or not.
Comment: it's working but i really dont know how... like in my logic it should't work lol xD can u explain the flow? What i understand is u have an event which get's triggered everytime u click on the button
Comment: now i need to clear the colors and return them to default for next question cuz now when i go to next question the buttons stays red / green
Comment: You can set color of button on start or OnEnable method. Where you set text of option.
Comment: I need to make the other buttons not interactable because when user checks an answer i want him to not be able to click on any other button untill other question show\s up. In your opinion how should i do it? deactivate the whole Manager or just loop through the button pooling and make them not interactable?
Comment: i have update code check it out.
Thanks for upvoting my answer ;)
Comment: Thank you for saving me... xD!
Comment: Hey again! if you have some free time would you help me in a other issue im also having :D? if you agree kindly reply so i can create the question
Comment: Sure When i get time i will answer your questions
Comment: Here's the link : http://stackoverflow.com/questions/41698506/unity-remove-the-selected-object-from-random-range


WebRTC JavaScript com servidor Java/PHP

Question: Alguém ai tem algum exemplo ou documentação, de como criar um client WebRTC (navegador), utilizando um servidor Java ou PHP para fazer o "handshake" entre ambos?
Não posso utilizar node.js, e a documentação que encontro, está obtendo algumas informações do servidor node, as quais são necessárias para iniciar a conexão P2P.
Comment: Você poderia especificar as informações do servidor node necessárias para iniciar a conexão que você mencionou?
Answer: Felipe,
Sua dúvida é com relação ao "client" de WebRTC ou ao servidor que será responsável pelo signaling (troca de mensagens)?
Se for com relação servidor, existem vários projetos de WebSocket em PHP, como:

Ratchet
phpwebsocket

Nos pontos de conexão WebRTC (Client/Server) você irá utilizar o WebSocket para sinalizar e enviar as mensagens que negociam a conexão entre os pontos, após isso esses pontos irão se conectar diretamente uns aos outros (ou por intermédio de um servidor TURN).
No site WebRTC tem muito material e conteúdo para te ajudar com a tarefa.
PS.:
Só por curiosidade, poderia me explicar o motivo de não poder usar servidor node?
Comment: O motivo da não utilização de node, são por definições da própria empresa.

WebRTC JavaScript com servidor Java/PHP


How to make np.where work for float datatype

Question: a=np.array([0.5, 1.5, 2.5])
np.where(a < 2)

I got (array([0, 1], dtype=int64),). How can I get array([0.5, 1.5])?
Comment: `a[a < 2]`, no need for `np.where`.
Answer: Let's break this down.
a < 2 gives array([True, True, False]), as it tests the condition element-wise.
np.where(a < 2) gives you the indices where the result of a < 2 is true. It's true in the first and second elements, so it gives you the array of indices [0, 1].
You could use those indices to then index the array:
a[np.where(a < 2)]

However, like @Psidom says, this is unnecessary, as you can just index the array directly using
a[a < 2]

and this would be the most pythonic way.


Question about basis and finite dimensional vector space

Question: I have seen the statement "Every finite dimensional vector space has a basis." (Here on page 5)
I'm confused about what this tells me. It seems to tell me nothing: by definition, the dimension of a vector space is the number of elements in a basis of it. Then saying a vector space is finite dimensional is the same as saying that it has a basis.
Or are there any other definitions of dimension than the number of basis elements?
Comment: You could define a vector space to be "finite dimensional" without reference to a specific dimension or to a basis - a finite dimensional vector space is one which has a finite spanning set. This is stated on page 1 of the link.
Comment: @Sunni, *every* vector space has a basis, even infinite dimensional ones. This is equivalent to the Axiom of Choice.
Comment: Nice question. I think the statment "Every finite dimensional vector space has a basis." is used to distinguish the infinite dimensional case, since "Not Every infinite dimensional vector space has a basis."
Comment: @Mathemagician1234 : The statement "without having the same number of elements" is either meaningless or false; indeed, under any reasonable interpretation of "the same number of elements", there are as many natural numbers as integers.
Comment: @Sunni,ihf,Mark Every vector space has a basis whether it's finite or infinite dimensional,but that doesn't really explain to the OP what's different in going from the finite to the infinite dimensional case. The main difference-from which most of the other properties that distinguish the 2 cases are derived-is that since infinite sets can be put in one to one correspondence without having the same number of elements (for example, the natural numbers and the integers), infinite dimensional vector spaces don't have a unique dimension!
Answer: A more general definition of dimension is the maximal number of nested subspaces: a vector space $V$ has dimension $d$ if and only if $d$ is the largest number such that there exist subspaces.
$$\{0\}\subsetneq V_1\subsetneq V_2\subsetneq\cdots\subsetneq V_d=V$$
This is useful in defining dimension for more general modules.
You can in fact drop the "finite-dimensional" to get the statement that every vector space has a basis (this requires the Axiom of Choice), and then there's no problem. Or indeed, as Mark points out in the comments, the definition of "finite-dimensional" being used is that there is a finite spanning set, so the statement is telling you that the existence of a finite spanning set implies the existence of a finite basis.
Answer: Perhaps a broader context will be valuable. Let $R$ be a commutative ring (noncommutativity isn't relevant to the point I'm trying to make) and $M$ a module over it. We say that $M$ is finitely generated if there exist $m_1, ... m_n \in M$ such that every element of $M$ can be written in the form
$$m = r_1 m_1 + ... + r_n m_n.$$
When $R$ is a field $k$, an $R$-module is precisely a $k$-vector space, and a finitely generated $R$-module is precisely a finite-dimensional $k$-vector space. (Note that I can define "finite-dimensional" without defining "dimension.")
We say that $m_1, ... m_n$ is a basis of $M$ if it is a generating set which is linearly independent in the sense that if
$$0 = r_1 m_1 + ... + r_n m_n$$
then $r_1 = ... = r_n = 0$. This is equivalent to saying that each element of $M$ is uniquely expressible as a sum of the $m_i$. Abstractly, it says that the natural map
$$R^n \to M$$
given by sending $(r_1, ... r_n)$ to $r_1 m_1 + ... + r_n m_n$ is an isomorphism of $R$-modules. When $M$ has this property in module theory, we say that $M$ is a free module.
To say that every finite-dimensional vector space has a basis is to say that every finitely generated module over a field is free. It may be useful to see why this is false for more general rings: for example, a $\mathbb{Z}$-module is just an abelian group, and a $\mathbb{Z}$-module such as $\mathbb{Z}/p\mathbb{Z}$ ($p$ a prime) cannot be free. Indeed, no generating set can be linearly independent since $pm = 0$ for all $m$.
More generally, if $R$ is a commutative ring and $I$ a nontrivial ideal of it, then $R/I$ is never free. Thus the only commutative rings $R$ for which every finitely generated module is free are those with no nontrivial ideals, and this is one of several equivalent ways to define a field.
When $R$ is noncommutative, a more astonishing thing that can go wrong is that free modules can fail to have invariant basis number.
Comment: The point is to demonstrate that the statement has content by showing why a more general statement is false.
Comment: An the key to the  invariant basis number property for commutative rings is the existence of maximal ideals (also equivalent to the axiom of choice) and the invariant basis number property for fields.
Comment: Some very interesting module theory,Quaochu-but I'm not sure what it has to do with the OP's question. I think generalizing the base ring of the module beyond fields kind of loses the point of the question in this case.
Answer: In the document you're linking to, the following is used as the definition of finitely dimensional space.

If a vector space $V$ is spanned by a finite number of vectors, we say that it is finite dimensional.

So we do not know a priori that every finite-dimensional space (w.r.t. this definition) has a basis, we need to show this.
Only after you show that every such space has a finite basis and that any two bases have the same number elements, you can use $V$ has a basis consisting of finitely many elements as an equivalent definition of finite-dimensional space.

I think that the definition of finite-dimensional space as the space having a finite spanning set is used quite often in introductory texts on linear algebra. (Among other things, you can speak about finite-dimensional spaces before defining the notion of basis.)
IIRC I have even seen some texts where basis is assumed to have at least one element, so if you use that definition, then $\{0\}$ is an example of finite dimensional space which does not have a basis. (It is finite dimensional because it is spanned by the finite set $\{0\}$.)
Of course, if you've already mastered linear algebra, you will use any of equivalent definitions of finite-dimensional space almost automatically, details like this are important only in the introductory course, when the students encounter these notions for the first time.

EDIT: Now I noticed that this was explained already in Mark Bennet's comment above.


constexpr for null-initialized constructor in a derived class

Question: I have something similar to the following
class Base {
public:
    explicit Base(int* i) noexcept { type = new int; *type = *i; };
    constexpr Base(std::nullptr_t) : type(nullptr) { };
    ~Base() { cout << "Destroying!" << endl; delete type; };
protected:
    int* type;
};

class Derived : public Base {
public:
    explicit Derived(int* i) noexcept : Base(i) { };
    //constexpr Derived(std::nullptr_t) : type(nullptr) { };
    //constexpr Derived(std::nullptr_t) : Base(nullptr) { };
    ~Derived() { };
};

I would like to achieve some constexpr null constructor for the derived class, but the compiler complains a lot about the two options and similar tests I have done.
Of course the code is more complex, I have an opaque handler and the destructor should behave in a more complex way. The resource free-ing is always the same (no need for multiple destructors, only the Base one).
I don't know how to achieve this, maybe I am going through a wrong path? Any ideas? I expect to be able to do something like:
Derived a(nullptr);
Derived b(handler1);
Base c (nullptr);
Base d (handler2);

and, in cleanup, both handler1 and handler2 are managed in the some way.
Edit:
Clang (version 3.4) complains:
error: constexpr constructor never produces a constant expression [-Winvalid-constexpr]

And gcc (version 4.8 [edit: multiple versions, haven't checked all]) doesn't complain when using
constexpr Derived(std::nullptr_t) : Base(nullptr) { };

In fact, gcc seems to do what I wanted to achieve, but I do not understand the constexpr enough to know which compiler is doing right and how I can amend the problem.
Comment: The error of gcc I got (when using `constexpr Derived a(nullptr);`) is self explanatory: `'Derived' is not literal because:'Derived' has a non-trivial destructor`. (That already happens with `Base`).
Comment: @Jarod42 Interesting, with gcc 4.8.1 -std=c++11 I don't get this error.
Comment: @Jarod42 but I assume that `unique_ptr` doesn't have a trivial destructor, and uses something similar to what I'm doing, doesn't it?
Comment: @Jarod42 @martin_pr `g++-4.7` version 4.7.3 compiles and runs as I wanted (`g++-4.7 (Ubuntu/Linaro 4.7.3-12ubuntu1) 4.7.3`)
Comment: I am still not sure what is the cause, but a newer version of clang gives a bit more details about the error: `note: non-literal type 'Base' cannot be
      used in a constant expression
    constexpr Derived(std::nullptr_t) : Base(nullptr) { };
`
Comment: Note that I got also an error with `unique_ptr` (http://coliru.stacked-crooked.com/a/10f22fc762d1bcb4).
Comment: `constexpr` changed in C++14, see [N3652](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3652.html). With `-std=c++1y`, the warning goes away.
Answer: The type of a constant expression must be a literal type. In fact, the entire purpose of the "literal type" taxon is to "be the thing that can be a constant expression". See [expr.const]:

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:
...
— an invocation of a function other than a constexpr constructor for a literal class, a constexpr function,
...

Therefore, a constexpr constructor only allows you to produce constant expressions on literal classes, and otherwise, as your compiler is telling you, it would "never produce a constant expression".
A literal class is constrained by [basic.types] in this way:

A type is a literal type if it is:
...
— a class type (Clause 9) that has all of the following properties:

it has a trivial destructor,
it is an aggregate type (8.5.1) or has at least one constexpr constructor or constructor template that is not a copy or move constructor, and
all of its non-static data members and base classes are of non-volatile literal types.

However, as of C++14 (particularly, as of N3652), constexpr constructors have another, unrelated use: They permit static initialization (in the sense of [basic.start.init]):

A constant initializer for an object o is an expression that is a
  constant expression, except that it may also invoke constexpr constructors for o and its subobjects even if those objects are of non-literal class types [Note: such a class may have a non-trivial destructor — end note].

So to recap: As of C++14, constexpr has two uses:

The C++11 interpretation: a "constant expression" is an expression that is identical to its value (i.e. its evaluation has no side effects); constexpr variables are just placeholders for their value and not intended to be used for their object identity, and it is generally expected that constant expressions can be freely replaced with their (compile-time knowable) value.
The C++14 constexpr functions, including constructors: These functions, including constructors, may be called in the static initialization phase to constant-initialize variables with static storage duration. If the variables are objects, they still retain their object identity and may need dynamic destruction, but their initialization happens before any dynamic initialization and is not subject to ordering.
Comment: You beat me to it :) A more detailed explanation of literal types can be found [here](http://stackoverflow.com/questions/18581443/need-clarification-on-definition-of-literal-type)
Comment: Yup, it did, but personally I found the old explanation more comprehensible.
Comment: So, the `constexpr` that I have for `std::unique_ptr` constructor doesn't make sense ?
Comment: As far as I understand it, no, because it includes a pointer and has a non-trivial destructor.


Clicar no Link e abrir um player abaixo dele

Question: Tenho alguns links, exemplo: Link1 Link2 Link3 Link4  e gostaria que ao clicar no Linkx ele abra um "embed" logo abaixo dele, e que cada Link traga seu vídeo correspondente.
Estou trabalhando em um theme wordpress, no qual estou tentando modificar algumas partes... Não consegui resolver esta questão pois não sei como esconder os videos.
Clica no Link1 ele abre o video do Link1
Clica no Link2 ele abre o video do Link2
Tem que ser na mesma página e também tem que ser logo abaixo do link...
Comment: Basta colocá-los em um *div* com `display:none`, [nessa pergunta](http://pt.stackoverflow.com/q/44717/4808) existem respostas para mostrar um div quando clicar em um *link*. A lógica é a mesma, se tiver alguma dúvida pode [edit] a sua pergunta explicar o que não conseguiu e se possível incluir algum código (mesmo que não funcionando) de como tentou fazer.
Comment: @renan obrigado, estava acompanhando este outro link... porém ficou a duvida... ao dar play e depois ocultar a div, o play continua rolando... oque posso fazer?
Comment: Vc pode usar jquey. Algo do tipo $('#elementodovideo').pause();
Comment: @rochasdv ainda estou com um problema, os exemplos que vi no link indicado, estão trabalhando somente com 1 botão. No meu cenário eu possuo 1 link para cada vídeo....
Comment: @HenriqueSilva para pausar o video já tentou utilizar uma função do tipo:
`function destroyVideo(objeto){
    var url = $("#video1").attr('src');
    $("#video1").attr('src', '');
    $("#video1").attr('src', url);
}`
Comment: Se for utilizar um embed do youtube, este exemplo no [JSFiddle](https://jsfiddle.net/kd8pbkv9/) pode ser uma opção. Ignore efeitos de transição.
Answer: Eu não trabalho com wordpress mas acredito que dê pra trabalhar com jQuery nele normalmente, certo?
Se puder você coloca um listener para cada link, na ação de clique em cada link você exibe ou escoda uma div, onde abrirá o video.
Algo mais ou menos assim:
    LINK1

        <video id="video1" src="demo.mp4" controls autoplay >HTML5 Video </video>

 LINK2

        <video id="video2" src="demo.mp4" controls autoplay >HTML5 Video </video>

Eu não testei o código, pode ter erros de escrita, mas a ideia (pelo o que entendi) seria mais ou menos isso.
Comment: Testei, não funcionou... Inclui o display:none para eles ficarem ocultos, porém ao clicar no Link1 ele não trouxe o video
Comment: Como eu poderia reutilizar este código: http://pt.stackoverflow.com/questions/66123/alternar-entre-ocultar-exibir-divs-%C3%A0-partir-de-links  . Para que ele não esconda o link que cliquei?
Answer: O seu problema consiste no seguinte:
"Dada uma lista de links, ao clicá-los, abaixo do item clicado será exibido um vídeo"
Para isso, você precisará controlar bem os blocos de exibição da página, para que os vídeos fiquem bem alinhados em relação aos links.

Breve comentário
Eu optei por fazer um menu horizontal (sem apelo visual), mas que o vídeo apareça abaixo dos itens logo que clicado. Você pode dispor de outro modo, por exemplo, pôr cada par item-video em uma linha. O fato é que ao clicar num link, após aberto o primeiro vídeo, o anterior logo se fechará e pausará.
A solução que eu sugiro, tem alguns pontos que vale apena você olhar com mais calma. São eles:

classList.Toggle(): codepen - Class Toggle (pure JavaScript)
forEach: MDN - Array.prototype.forEach()
Flex: MDN - Basic concepts of flexbox (opcional)

Solução:

var v = document.getElementsByClassName('myVideo');
        function classToggle(id) {
            v[id].classList.toggle('hide');
            v[id].classList.toggle('active');
        }

        function closeOtherVideo(id) {
            var c = document.getElementsByClassName('myVideo');
            for(var i=0; i<c.length; i++){
                if(i != id) {
                    v[i].pause();
                    c[i].classList.remove('active')
                    c[i].classList.add('hide')
                }
            }
        }

    document.getElementById('toVideo1').addEventListener('click', function() { classToggle(0),closeOtherVideo(0)});
    document.getElementById('toVideo2').addEventListener('click', function() { classToggle(1),closeOtherVideo(1)});
    document.getElementById('toVideo3').addEventListener('click', function() { classToggle(2),closeOtherVideo(2)});
    document.getElementById('toVideo4').addEventListener('click', function() { classToggle(3),closeOtherVideo(3)});
.container {
    width: 100%;
    background: #ffffff;
    display: flex;
    flex-direction: column;
    align-items: center;
    border: 1px solid #cbc9c7;
    border-radius: 0.25rem;
}

.box {
    width: 100%;
    padding: 2rem;
    text-align: center;
}

 .myVideo {
     background-color: #000000;
     width: 440px;
     margin: 0 auto;
 }

.boxHeader {
    width: 100%;
    text-align: center;
    padding: 1rem 0;
}
.video-menu {
    width: 440px;
    margin: 0 auto;
}

.boxHeader a {
    margin: 0.275rem;
}

.boxBottom {
    width: 100%;
}

.active {
    display: inline-block;
}

.hide {
    display: none;
}

                    video 1
                    video 2
                    video 3
                    video 4

                <video id="video1" class="myVideo hide" controls src="https://instagram.fsdu12-1.fna.fbcdn.net/v/t50.2886-16/100818563_141790667457660_2448482643239076991_n.mp4?_nc_ht=instagram.fsdu12-1.fna.fbcdn.net&_nc_cat=100&_nc_ohc=k6HEU2Q2YFgAX-jAG04&oe=5ED64CB4&oh=a7ac00f8b0f4eb2b680fb19bf6e56bff">

HTML5 audio is not supported on your browser

                </video>
                <video id="video2" class="myVideo hide" controls src="https://instagram.fsdu12-1.fna.fbcdn.net/v/t50.2886-16/101407297_578758382771748_4583302688695556657_n.mp4?_nc_ht=instagram.fsdu12-1.fna.fbcdn.net&_nc_cat=100&_nc_ohc=3rAFHrkfrRsAX97dk3o&oe=5ED6B16D&oh=375b9fc3f99175160b6a308439bd5682">

HTML5 audio is not supported on your browser

                </video>
                <video id="video3" class="myVideo hide" controls src="https://instagram.fsdu12-1.fna.fbcdn.net/v/t50.2886-16/100635180_248551773073170_469297836861370934_n.mp4?_nc_ht=instagram.fsdu12-1.fna.fbcdn.net&_nc_cat=106&_nc_ohc=VjO27SKjb9kAX_YE0Rs&oe=5ED66E98&oh=d301180c213df6954f5f06f32193389e">

HTML5 audio is not supported on your browser

                </video>
                <video id="video4" class="myVideo hide" controls src="https://instagram.fsdu12-1.fna.fbcdn.net/v/t50.2886-16/93155023_146306196903209_2004287997341602261_n.mp4?_nc_ht=instagram.fsdu12-1.fna.fbcdn.net&_nc_cat=105&_nc_ohc=u4WdSeVhJFMAX9uYGeE&oe=5ED662F2&oh=758ea19e44728a476bb89716fee74170">

HTML5 audio is not supported on your browser

                </video>

Deixei no exemplo a adição dos eventos via getElementById pegando cada link "manualmente". Mas você pode deixar mais enxuto e elegante fazendo assim:
    var sv = document.querySelectorAll('.showVideo');
      sv.forEach((element, key) => {
        element.addEventListener('click', function(){
          classToggle(key),
          closeOtherVideo(key)
      })
    });


What's an umbrella term for things like class, struct, interface and enum?

Question: I know what I typed are keywords, but that umbrella term would also contain things like if, new or using. Can I just call class, interface etc. types? I feel like that would be confusing because the keyword class is being used for declaring types.
Comment: Yes, "Types" is correct.
Comment: To be clear, is what you want a term referring to the **words** `class`, `interface`, not the things those words represent?
Comment: If we call them types. Is the rule "all things i can use `typeof` on are types then correct? Or are there exceptions?
Comment: You can use `typeof` on any type identifier, but there are some types you cannot use `typeof` on, like [anonymous types](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/anonymous-types) which do not have an identifier.
Answer: I just found out, the Microsoft documentation calls them "categories of types" here:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/common-type-system?redirectedfrom=MSDN#types_in_the_net_framework
Answer: Interfaces, classes, structs, and enums are all varieties of types in .NET.
Generally, words that are used by the language are called keywords. This would include class, interface, if, new and many others.
There isn't a term that collectively refers to the keywords that represent types (class, interface, but not if, for). I might call these "type declaration keywords".
Comment: Also `delegate` and `record` are types.
Comment: "type declaration keywords" sounds much more descriptive than what Microsoft seems to use ("categories of types")


Is it possible to use correlations between variables at different waves but with different participants to fix error variances in SEM?

Question: I am interested in analyzing data from the World Values Survey; the WVS has different waves, however each wave has a single time point. Participants are not the same between waves but the survey questions overlap to a large degree.
I am primarily interested in analyzing relationships between individual questions (i.e., not scales). I was debating whether SEM might be good a fit for my research questions, and so I would need to fix the error variances in order to have enough degrees of freedom.
I know it's possible to fix the error variances using survey items' test-retest reliability, but this would require longitudinal data, which is not applicable in my case.
Consequently, I was wondering if it is appropriate to use the correlation between the same variable at different waves in order to fix the error variances.
For example, say I have latent variable X which is associated with a single manifest variable X. Could I use the correlation between X at wave 1 and wave 2 to fix the error variance of X?
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: According to classical test theory, the error variance Var(error) associated with a test score variable is given as
Var(error) = Var(variable) * (1 - reliability).
A test-retest correlation typically is not a good estimate of reliability. (Only under very strict/unrealistic conditions would a test-retest correlation equal reliability.) The test-retest correlation typically underestimates the reliability of a variable, leading to an overestimation of the error variance when using it in the above formula. Perhaps a more appropriate reliability estimate could be derived from a different source.


Display MySql results using PHP (Dropdown Menu)

Question: I have created a database that displays images for a portfolio which also have categorys (Fencing & Decking, Lining, Carparks etc).. I am trying to create a dropdown menu that will display only the selected category, with the default being 'all' images.. here's my code, can't seem to get it to work at the moment..
<?php

define('DB_NAME', 'wlarter_portfolio');
define('DB_USER', 'wlarter_user');
define('DB_PASSWORD', 'pw');
define('DB_HOST', 'localhost');

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

if (!$link) {
    die('Could not connect: ' . mysql_error());
}

$db_selected = mysql_select_db(DB_NAME, $link);

if (!$db_selected) {
    die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}

$results= mysql_query("SELECT * FROM images")
    or  die(mysql_error());

?>

<?php
while ($row = mysql_fetch_assoc($results)) { ?>

 <?php echo $row['Img']; ?>

<?php
};
?>

<?php
   $category = isset($_GET['category']) && is_numeric($_GET['category']) ? $_GET['category'] : 1; // where 1 is a default category to show!
?>
<select onchange="if(this.value != '') document.location = '/portfolio.php?category=<?php echo $category; ?>&order_by=' + this.value">
  <option value="">Choose an option</option>
  <option value="Fencing & Decking"<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'Fencing & Decking') echo ' selected="selected"'; ?>>Fencing & Decking</option>
  <option value="Lining"<?php if(isset($_GET['order_by']) && $_GET['order_by'] == 'Lining') echo ' selected="selected"'; ?>>Lining</option>
</select>

Comment: You can do this in 2 ways: using PHP alone and by using AJAX. In the first one you will need to have your page reloaded to pass the `POST` value to the query, while in the 2nd, it's done using javascript so the page won't be reloaded.
Comment: Quentin - I will look into that
@ICanHasCheezburger - Which do you recommend to use? Could you possibly help me to achieve this?
Answer: You need to rewrite your query. use this code:
$qry = "SELECT * FROM images ";
if(isset($_GET['category']) && is_numeric($_GET['category'])){
   $qry .=  "where category = ".$_GET['category'];
}
$results= mysql_query($qry) or  die(mysql_error());

Supposed you you have category_id column in your table. you can replace the name wh
Comment: Error on line 74 isset($_GET['category']) && is_numeric($_GET['category']){
Comment: from replacing the query i now receive an error on selecting from the drop down menu.. 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where category = 1' at line 1'

I apologize I am fairly new to php
Comment: @user3505895 sorry my mistake I have again edited the code plz check now.
Comment: Seems to have fixed the error but the results aren't showing when selecting the category, maybe its a mistake on my part, but the column name is 'category' so should work right?
Comment: @user3505895 hmm should work what values in that column depends on that.
Comment: My table consists of 'ID' 'Img' 'category' I have now seen that If I make the category field '1' it appears when I use the drop down menu but trys to order by "fencing & decking" or "lining", where as I want the category to be either f&d or lining, you follow?
Comment: @user3505895 Is your category column holding number or string value?


how to Pass the elements in a structure to an unamed pipe?

Question: #include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

struct msg
{
    int pid;
    int giffs;
    int curr;
};

main()
{
    struct msg send = {1, 2, 3};
    int p[2], pid, i;
    char inbuff[sizeof(send)];
    char *q;
    pipe(p);
    pid = fork();
    if(pid > 0)
    {
         write(p[1], (char *)&send, sizeof(send));
         printf("%ld \n", sizeof(send));
    }
    else
    {
         read(p[0], inbuff, sizeof(send));
         printf("%s\n", inbuff);
    }
}

The problem is the elements in the structure are not appearing at the read end,
could anyone please check on this. we can pass a string to a pipe, but I need to pass the bunch of integers to the pipe.
Answer: The bytes get read at the receiving end, but you try to print binary data as a string.
Treat the read bytes as struct msg instead:
else
{
     struct msg received;
     read(p[0], &received, sizeof(received));
     printf("%d, %d, %d\n", received.pid, received.giffs, received.curr);
}

Comment: Thank you Klas. It is working fine. I am concerned about large amount of data. if I send 100 elements. It may be difficult to print all the elements at the read end. I want to send the base address of the structure and at the read end I want to print all the elements.
Comment: Once you `fork`, the memory is no longer shared between parent and child (so the child cannot see changes made by the parent). If you want the child to be able to read the memory of the parent process you need to use either shared memory or threads.
Comment: Thank you for your valuable time Klas. So it not possible by using pipes. I think pipes can be used to read the data from a write end b/w two related processes.
Comment: You can use a pipe to send data between processes. however, if you send a pointer that points to a string in the sending process, you cannot expect the reading process to find that string using a pointer sent through a pipe. The pointer has the same value as in the sending process, but the memory address pointed to wouldn't normally contain the same string, or even be readable by the receiving process.
Answer: #include <stdio.h>
#include <unistd.h>
 #include <fcntl.h>
struct msg {
    int pid;
        int giffs;
        int curr;
};

main()
{

    struct msg send = {1, 2, 3};
    int p[2], pid, i;
    int *inbuff;
    char *q;
    pipe(p);
    pid= fork();
    if(pid > 0) {
            write(p[1], (char *)&send, sizeof(send));
            printf("%ld \n", sizeof(send));
            sleep(1);
    } else {
        read(p[0],(char *) inbuff, sizeof(send));
    for (i=0;i<sizeof(send)/sizeof(int);i++){
            printf("%d\n", *inbuff++);
    }
    }
 }

try this code..........
here make sure you use waitpid() instead of sleep so that parent process waits for child procees to terminate or else you will get inappropriate response...........
Comment: I have used waitpid() in the parent process. But child process is printing garbage values. Could you please be specific where to use and how. And what is the function of waitpid(); Any help would be appreciated.
Comment: here what happens is you are making your child process to write and parent process to read from the pipe....
So before the child process writes anything your parent process tries to read from the pipe and hence it receives garbage value...
What you can do here is exchange your if and else statement blocks so that your child reads and parent writes and use sleep in child process this may solve your problem.

ps... the problem with waitpid() occurs as you mentioned i am trying to sort that out...
Comment: I like the way you explained. you are right the parent and child processes must be interchanged. It is working well now. Thank for your time chirag parekh.


How to check with Intel intrinsics if AVX extensions is supported by the CPU?

Question: I'm writing a program using Intel intrinsics. I want to use _mm_permute_pd intrinsic, which is only available on CPUs with AVX. For CPUs without AVX I can use _mm_shuffle_pd but according to the specs it is much slower than _mm_permute_pd. Do the header files for Intel intrinsics define constants that allow me to distinguish whether AVX is supported so that I can write sth like this:
#ifdef __IS_AVX_SUPPORTED__  // is there sth like this defined?
// use _mm_permute_pd
# else
// use _mm_shuffle_pd
#endif

? I have found this tutorial, which shows how to perform a runtime check but I need to do a static, compile-time check for the current machine.
Comment: `_mm_permute_pd` (`vpermilpd`) is not faster than `shufpd dest,same,same`, unless it allows a memory source operand to fold into the instruction.  See http://agner.org/optimize/ for instruction tables, etc.
Answer: GCC, ICC, MSVC, and Clang all define a macro  __AVX__ which you can check.  In fact it's the only SIMD constant defined by all those compilers (MSVC is the one that breaks the mold).  This only tells you if your code was compiled with AVX support (e.g. -mavx with GCC or /arch:AVX with MSVC) it does not tell you if your CPU supports AVX. If you want to know if the CPU supports AVX you need to check CPUID.  Here, asm-in-c-error, is an example to read CPUID from all those compilers.
To do this properly I suggest you make a CPU dispatcher.
Edit: In case anyone wants to know how to use the values from CPUID to find out if AVX is available see https://github.com/Mysticial/FeatureDetector
Comment: If you want GCC / clang to define feature-macros like `__AVX__` *according to whether your computer has them or not*, you have to compile with `-march=native`
Answer: I assume you are using Intel C++ Compiler. In this case - yes, there are such macros: Intel C++ Compiler Reference Guide: __AVX__, __AVX2__.
P.S. Be aware that if you compile you application with AVX instruction set enabled it will fail on CPUs not supporting AVX. If you are going to distribute your software as source code package and compile on target machine - this is may be a viable solution. Otherwise you should check for AVX dynamically.
P.P.S. There are several options for ICC. Take a look at the following compiler options and also references from it to other.
Comment: GCC supports `-mtune=native` to tune the instruction set depending on the current CPU, maybe there's something similar for ICC?
Comment: Yes, there is `-xHost` for MacOS and Linux and `/QxHost` for Windows. There are also various options like `-march`, `-arch` etc.
Answer: It seems to me that the only way is to compile and run a program that identifies whether AVX is available. Then manually or automatically compile separate code with or without AVX functions. For VS 2013, I would used my code in commomAVX folder in the following to identify hasAVX (or not) and use this to execute one of two different BAT files to compile and link the appropriate program.
http://www.roylongbottom.org.uk/gigaflops-benchmarks.zip
My question was to help to identify a solution regarding the use of suitable compile options such as /arch:AVX.


Can we train tensorflow.js to get certain part of image?

Question: My Client has requirement that user will upload image using that image i have to crop some part of image to do that first i have used tesseract.js node module but it's not worked so i moved to tensorflow.js to create my own model and train to crop certain part of images. I want to crop below image signature part and photo. So using object detection of tensorflow can we detect signature and get x and y coordinates to crop images.

if i get coordinates using below code i can crop certain part of images.
<code>const sharp = require("sharp");
sharp("./pancard.jpg")
  .resize(500, 300, {
    fit: sharp.fit.fill
  })
  .toFile("./pancard_new.jpg", (err, info) => {
    sharp("./pancard_new.jpg")
      .extract({ left: 35, top: 220, width: 180, height: 28 })
      .toFile("./pancard_new2.jpg", function(err) {});
  });
</code>
Comment: Are the input images always fixed ( like the example given in the question )? If yes, then we don't need an ML model to do this task. The signature and photo are always at the same position in the image. We can crop them manually.
Comment: No sometimes user upload imaes like this https://new-img.patrika.com/upload/mediafiles/2017/07/06/l_pancard-farzi-1499313521_835x547.jpg
Answer: You would need to have a lot of training data if you wanted to train a machine learning model - maybe thousands of examples of cards which are human annotated with the regions you want to detect and labelled. You can then train something like a segmentation model to extract raw pixels that match those classes, or a multi-box classifier which can give you the bounding box (but may not do so well with things at angles).
The easiest way to train your own and output to TensorFlow.js format would be to try Cloud Auto ML Vision which exports built models to TensorFlow.js. See this tutorial for object detection which gives you bounding boxes back: https://cloud.google.com/vision/automl/object-detection/docs/tensorflow-js-tutorial and then click the Node.js code tab of that tutorial to see how to use in JavaScript on the server side instead of Python.
However as others have mentioned, it may be easier to figure out how to find out where the card is, straighten it, and crop it as that may just be a simple computer vision problem vs a machine learning one.
Comment: Link is in the answer above for the cloud auto ml tutorial. Follow that for the multibox example to retrain on your own data. I dont think there is one for object segmentation yet - for that you would have to make your own manually.
Comment: Hi @jason, You mean to say instead of write code to train data i can use google UI to train data and using that model data i have to write code to get co-ordinates to crop images...is this google edge is paid??
Comment: Hey @Jason i have checked goggle edge is paid tool. Can you please explain little bit about this "You can then train something like a segmentation model to extract raw pixels that match those classes, or a multi-box classifier which can give you the bounding box (but may not do so well with things at angles)". please provide github link or tutorials link if you have any please.


Date format problem in view

Question: hello I encounter difficulties to display a date in the correct format in a view.
I souhaire display my dates like this 2009-07-19T03:00:00+01:00
I created a new format here / admin / config / regional / date-time / formats
here that Y-m-d\TH:i:sP
Then I created a new type of date and selected my new format.
When I go to my view, I select my new date format but the field shows a different format 2016-03-17+01:00 +01:00
So I have a time zone more and I miss the hour, minutes and seconds.
Do you have a solution ?
Comment: Is this Drupal 7 or 8?
Comment: is this Drupal 7
Comment: In views, for date formatter select **custom** and put `Y-m-d\TH:i:sP` and see what happens.
Comment: hello, yes I have set the parameter fields on my custom date
Comment: like [this](http://i.stack.imgur.com/hsd8S.jpg)?
Comment: https://www.drupal.org/node/2689945
Comment: I do not put my screenshot on this site so I opened a post on drupal. Look in the message I have attached pictures
Answer: Try doing it like this, which works fine for me:
For date format select Custom and then enter Y-m-d\TH:i:sP
Comment: I have no personalized format in my view.
Watching capture date1.jpg
Comment: Use "custom" instead of "google shopping"
Comment: I have only the short format, medium, long, google shopping and weather.
Comment: that's very weird, custom should show up under short format as seen [here](http://drupal.stackexchange.com/questions/195105/date-format-problem-in-view/195191?noredirect=1#answer-195191)
Comment: yes it is weird, but I want to display the discount date. Maybe is there a problem with the discount Module

Date format problem in view


My Push method is not working and showing some error

Question: my push method is not working. It is showing some error and I am unable to diGONOSE the error. can someone check what is the problem with my push method.
console.log("Hello, World");

function sum(a, b) {
  return a + b;
}

console.log(sum(2, 5));

let btn1 = document.getElementById("btn1");

btn1.addEventListener("click", function (e) {
  let txt1 = document.getElementById("txt1");

  let notes = localStorage.getItem("notes");

  //notesObj=JSON.parse(notes);
  if (notes == null) {
    notesObj = [];
  } else {
    notesObj = JSON.parse(notes);
  }
  //notesObj.innerHTML="Array=[" + txt1 + "]";
  //var element ="notes.value";
  notesObj.push(txt1.value);
  localStorage.setItem("notes", JSON.stringify(notesObj));
  //txt1.value=();
  console.log(notesObj);
});

Comment: That's not what I asked at all. Do some simple debugging and add `console.log("notes", JSON.stringify(notes))` and let us know **exactly** what it displays
Comment: script.js:23 Uncaught TypeError: Cannot read properties of null (reading 'push')
    at HTMLButtonElement. (script.js:23:18)
Comment: What is the error u are getting when running the code?
Comment: Have you tried debugging the value of `notes`? Perhaps it's the string `"null"`. You're also declaring `notesObj` as global (missing `let notesObj`) which isn't usually a good idea
Comment: yes I am declaring notesObj as string which will be get stringified after I give any notes in my html webpage. here notes is null until I haven't typed anything in my notepad text area(html webpage). After I write some notes in web I am declaring that this notes should get stringify in local storage
Answer: The only way this can happen is if you have the literal string "null" stored in localStorage.

let notes = localStorage.getItem("notes"); // "null"
if (notes == null) { // "null" ≠ null
  notesObj = [];
} else {
  notesObj = JSON.parse(notes); // JSON.parse("null") -> null
}

I would be more inclined to parse whatever value you have in storage and fallback to an empty array using the nullish coalescing operator
const notesObj = JSON.parse(localStorage.getItem("notes")) ?? [];

This way if there's nothing in localStorage (null) or the literal string "null", you'll always get an empty array.


Faster way of finding all indices of specific string in an array

Question: Below code is used to find all indices of a string that might occur only once in an array but the code isn't very fast. Does somebody know a faster and more efficient way to find unique strings in an array?
using System;
using System.Collections.Generic;
using System.Linq;

public static class EM
{
    // Extension method, using Linq to find indices.
    public static int[] FindAllIndicesOf<T>(this IEnumerable<T> values, T val)
    {
        return values.Select((b,i) => Equals(b, val) ? i : -1).Where(i => i != -1).ToArray();
    }
}

public class Program
{
    public static string FindFirstUniqueName(string[] names)
    {
        var results = new List<string>();
        for (var i = 0; i < names.Length; i++)
        {
            var matchedIndices = names.FindAllIndicesOf(names[i]);
            if (matchedIndices.Length == 1)
            {
                results.Add(names[matchedIndices[0]]);
                break;
            }
        }
        return results.Count > 0 ? results[0] : null;
    }

    public static void Main(string[] args)
    {
        Console.WriteLine("Found: " + FindFirstUniqueName(new[]
            {
                "James",
                "Bill",
                "Helen",
                "Bill",
                "Helen",
                "Giles",
                "James",
            }
        ));
    }
}

Comment: This O(n^2). Why don't you insert each name to Hashmap (name->numOfRecurrence) and then return all names that map to 1 - this will be O(n)
Comment: You could just try `names.GroupBy(x => x).Where(grp => grp.Count() == 1).Select(grp => grp.First()).ToList()`
Comment: @DavidWinder that sounds like a good way to go but how do you create a HashMap (Dictionary) with names as keys and recurrence as value, optimally without loop? E.g. similar to `var dictionary = sequence.ToDictionary(item => item.Key, item => item.Value)`
Comment: @BadmintonCat No matter what you do the best you can get is O(n) for this so even if you use Linq, under the covers it's going to use a loop.
Answer: Your solution has O(n^2) complexity. You can improve it to O(n) by using Hash-Map.
Consider a Hash-Map with which in each name has it number of recurrences in your original list. Now all you have to do is check all key in the dictionary (aka hash-map) and return all that equal to 1. Notice that check all key in this dictionary is less then o(n) because it can not hold more then n names.
To implement this dictionary in C# you do as follow:
List<string> stuff = new List<string>();
var groups = stuff.GroupBy(s => s).Select(
    s => new { Stuff = s.Key, Count = s.Count() });
var dictionary = groups.ToDictionary(g => g.Stuff, g => g.Count);

Taken from here or as suggested by juharr
O(n) is the minimum require as you will have to go over all names at least once.
Comment: Thanks for the insights! This helps a lot.
Comment: This makes no sense, the functions are seperate in the code they should probably remain seperate
Comment: What do you mean? Can you please elaborate?


Upside-down down bow

Question: On my Cello Salut D'amour by Elgar score, it has upside-down down bow symbols on it. Does this just mean up bow? I have this on other pieces too:

Salut d'amour, Op.12 (Elgar, Edward)

Mainz: Schott, 1899, 1901. Plate 26657.
Violine (transposed, D major)
Answer: That is the french down bow sign, which is the same thing as normal down bow.
Comment: Yes, they have the same meaning. But this is not "french" but a tradition of certain music publishers and engravers, notably *Durand*.
Comment: I did some searching online, and that's what I found. Considering that Durand is a French publisher, that is not surprising.
Comment: According to OP, the example is from a Russian publisher, which also supports the notion that it is a French convention.

Upside-down down bow


How to solve AmbiguousColumn error in postgresql with ruby project

Question: I would like to join two query result.
First one is
Gig.where(id:gigsInRadioIDS)
When I convert result to json I get this result
[{"id":1,"address":"test1"},{"id":2,"address":"test2"}

Second is.
Slot.where(status:"available").where(Sequel.lit('("from" > ?) AND ("to" < ?)', fromdate, todate))
when I convert result to json I get this result
[{"id":15,"status":"available","gig_id":1}]

What I want is to inner join to result
so I hope to get this result(I abbreviated some non related snippet)
[{"id":15,"status":"available","gig_id":1,"id":1,"address":"test1"}]

What I have tried is
Gig.where(id:gigsInRadioIDS).as(:tb_gig).join(Slot.where(status:"available").where(Sequel.lit('("from" > ?) AND ("to" < ?)', fromdate, todate)), gig_id: :id)

And I got this error
Sequel::DatabaseError - PG::AmbiguousColumn: ERROR:  column reference "id" is ambiguous
LINE 1: ...) AS "t1" ON ("t1"."gig_id" = "gigs"."id") WHERE ("id" IN (2...

Thanks for reading this complex code.
Any news will be big help. Thanks.
Answer: There are a bunch of ways to approach it. It looks like you are querying Slots with some Gigs data mixed in, so you may want to start with your Slot model. The regular join syntax is a little easier to understand and makes it easier to select columns from both tables (i.e. instead of WHERE fk IN (..)). As a bonus, you can mix your gig_id filter into the JOIN clause. Finally, you don't need to use Sequel.lit to do greater than / less than in your WHERE clause, and you should be explicit about the columns you want to select.
Here's how I would write it:
Slot.join(:gigs, [[:id, :gig_id], [:id, gigsInRadioIDS]])
  .where(status: 'available') { (from() > fromdate) & (to() < todate) }
  .select(Sequel[:slots][:id].as(:slot_id), :status, :gig_id, :address)

Getting .all of the records and outputting JSON should yield something like:
[{"slot_id":15,"status":"available","gig_id":1,"address":"test1"}]

Note the Sequel[:table_name][:column_name] syntax. This is the new style of fully-qualifying identifiers in Sequel 4.49+. (In past versions of Sequel, it would have been written like :table_name__column_name, but that syntax is now deprecated.)
Comment: Great. It works well. Thanks very much.
I can't find such query syntac, would you give me reference for that?
Answer: Your where(id:gigsInRadioIDS) translates into WHERE ("id" IN (...)), and since both gigs and slots have an "id" column, the database doesn't know which id you want.
You need to explicitly specify the table with where{{gigs[:id] => gigsInRadioIDS}}
Querying with Sequel
Comment: Thanks but I got this error,
TypeError - no implicit conversion of Symbol into Integer:


Describe the curve in the complex plane determined by $z = e^{(-1-i)t}$

Question: Describe the curve in the complex plane determined by $z = e^{(-1-i)t}$ where $0\leq t \leq 2\pi$.
Comment: From Terminator 2: "you forgot to say please..." ;)
Comment: Break it into two parts $e^{-t}$ and $e^{-it}$
Answer: Hint: write $z(t)=(x(t),y(t))$, with $x(t)=e^{-t}\cos t$ and $y(t)=-e^{-t}\sin t$; in other words, $x(t)=\operatorname{Re}z(t)$, and $y(t)=\operatorname{Im}z(t)$. I used the fact that
$$z(t)=e^{-t}e^{-it}=e^{-t}(\cos t-i\sin t).$$
For all $t\in [0,2\pi]$ one has
$$|z(t)|^2=x(t)^2+y(t)^2=e^{-2t};$$
this means that the point $z(t)$ lies on the circle centered at $0$ in $\mathbb C$ with radius $e^{-t}$. The biggest circle is the one at $t=0$, while the smallest is the one at $t=2\pi$. Now, try to find the points
$z(0), z(\frac{\pi}{2}), z(\pi), z(\frac{3\pi}{2}), z(2\pi)$
on the corresponding circles and "join the dots". This last passage is motivated by the fact that both $x(t)$ and $y(t)$ are continuous functions of $t$.


How to add Random Variables in general

Question: I'm kind of confused how to add two arbitrary random variables. For example, suppose I have a binomial random variable $X$ with parameters $(n, p)$ and I have a Poisson Random Variable $Y$ with parameter $\lambda$. If I say, $Z = X + Y$ what would the pmf of $Z$ look like?
What about for two of the same random variables. For example, two degenerate random variables $X_1, X_2$ which have their distributions localized at $k_1$ and $k_2$ respectively.
I just don't really get how you can add these. I guess my main question is that they both have probabilities that sum to $1$, so how can you add them in any meaningful sense?
Answer: Let it be that $X,Y$ are both random variables that only take values in $\mathbb Z$.
If $X$ and $Y$ are not defined on the same probability space then $X+Y$ makes no sense.
If $X$ and $Y$ are defined on the same probability space then for $k\in\mathbb Z$:
$$P(X+Y=k)=\sum_{i\in\mathbb Z}P(X=i,Y=k-i)$$
If $X$ and $Y$ are independent (hence are defined on the same probability space) then for $k\in\mathbb Z$:
$$P(X+Y=k)=\sum_{i\in\mathbb Z}P(X=i)P(Y=k-i)$$

If $P(X_i=k_i)=1$ for $i=1,2$ then it can be proved that $P(X_1=k_1,X_2=k_2)=1$ and consequently: $$P(X_1+X_2=k_1+k_2)=1$$again provided that $X_1$ and $X_2$ are defined on the same probability space.
Answer: The probability mass function of a vector of random variables will equal the joint probability mass function of the random variables.
The joint probability mass function of independent random variables shall be the product of the probability mass functions of those random variables.
The probability mass functions of identically distributed random variables are identical, and these are a Poisson distributed random variables with parameter $\lambda$.
So....
$$\begin{align}\mathsf P(\langle X_1,\ldots,X_n\rangle{=}\langle x_1,\ldots, x_n\rangle) ~&=~ \mathsf P\left(\bigcap\limits_{i=1}^n( X_i{=}x_i)\right)\\&=~ \prod_{i=1}^n \mathsf P(X_i{=}x_i)\\[0ex]&~~\vdots\end{align}$$
Comment: I thought the OP is asking about **adding** two r.v.'s, in which case the resulting PDF would involve a convolution. Your answer seems to talk about joint PDFs.
Comment: That makes sense, thanks!
Comment: No problem! Glad to help.

How to add Random Variables in general


how to create a histogram by using dataframes in r?

Question: I want to create a histogram, my data is stored in a variable Z. Calling hist(Z) is showing an error. I tried changing Z to numeric but it is still showing errors:
Z=as.numeric(Z)
 Error: (list) object cannot be coerced to type 'double'

year <- c(2010, 2011, 2012, 2013)
disconnected_ppl <- c(116, 54, 310, 110)
df <- data.frame(year=year, disconnected_ppl=disconnected_ppl)
df

year      disconnected_ppl
2010      116
2011       54
2012      310
2013      110

I want to create a histogram of year on xlab and disconnected_ppl on ylab. Each bar plot should be mentioned by the years and names on both the axis but I got the graph in this way:

As am new to R can you please suggest me which is the right option to choose histograms or bar plot?
Comment: Are you sure you want a histogram? Or do you mean a barplot?
Comment: It is very difficult to provide help without looking at some data and your code. Please see the link here regarding posting a reproducible example in `R` - http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example
Answer: Maybe you could try this?
year <- c(2010, 2011, 2012, 2013)
disconnected_ppl <- c(116, 54, 310, 110)
df <- data.frame(year=year, disconnected_ppl=disconnected_ppl)
barplot(df$di,df$year, xlab = "Year", ylab = "disconnected_ppl", names=c(2010, 2011, 2012, 2013))

Or in ggplot:
install.packages("ggplot2")
library(ggplot2)
qplot(year, data=df, geom="bar", weight=disconnected_ppl, ylab="disconnected_ppl")

Comment: @arshia did my answer help?


Exposed filters and taxonomy. How to make a redirect to a term page when exposed form submit?

Question: Let's say there are 2 vocabularies:

Sizes (S, M, L, XL)
Colors (Red, Green, Yellow)

pathauto sizes: /size/s, /size/m, ... pathauto colors: /color/red, /color/green, ...
There is a catalog - taxonomy/term/% view with the following filters:

Size
Color

If we use a filter, then the url will be like this - ?field_size_tid=2&field_color_tid=3 It's normal, when several fields are selected in the filter
But when one field is selected in the filter, the url will be like -
?field_color_tid=2 But in fact the ?field_color_tid=2 = /color/green
How to make an redirect to /color/green instead of ?field_color_tid=2 in this case after exposed form submit?
Comment: This part `But in fact the ?field_color_tid=2 = /color/green` is confusing. Do you want to say it looks like that in URL?
Comment: I meen, that views results for url ?field_color_tid=2 are the same with results for taxonomy term page /color/green (taxonomy/term/2).

?field_color_tid=2 = taxonomy/term/2 (alias for this path: /color/green) (in this case, when in filter selected only one exposed filter, exposed filter results = contextual filter results)
Comment: If you want views page to immediately redirect to taxonomy page after filter is applied, then why use views at all? Just use taxonomy and some kind of taxonomy filter. It really doesn't make sense to render views only for its filter and then never to use the view itself.
Comment: I have a big catalog, with many categories, and also with many exposed filter paramters, and the taxonomy/term/% view is exactly what I need. But this feature with this kind redirect is our SEO managers requirement. If in exposed filter selected only one filter, then after form submit redirect to equivalent taxonomy term page if this exists.
Comment: Hey Viktor, your profile shows you had been online much recently than the question was asked. Please do not leave your questions with no answer accepted if you want others keep helping you.
Comment: I'm still trying to do my function, but your comment with the function is very useful, thanks.
Comment: Viktor, if you want to keep getting help then start accepting answers.
Answer: Here is the code that should work for your use case. Create a custom module and replace YOUR_CUSTOM_MODULE part:
<code>function YOUR_CUSTOM_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    // Exclude cases when query contains 'field_color_tid'.
    if (strpos($_SERVER['QUERY_STRING'],'field_color_tid') === FALSE) {
      // Act only if query string contains 'field_size_tid'
      if (strpos($_SERVER['QUERY_STRING'],'field_size_tid') !== FALSE) {
        $selected_tid = $form_state['view']->exposed_input['field_size_tid'];
        // Check if such taxonomy term exists.
        $term = taxonomy_term_load($selected_tid);
        if (!empty($term)) {
          // Redirect to taxonomy page.
          $path_alias = drupal_get_path_alias('taxonomy/term/'.$selected_tid);
          drupal_goto($path_alias);
        }
      }
    }
  }
}
</code>
Answer: I have a slightly different solution. Hope this helps too...

You can have as many taxonomy categories as you need as exposed filters.
Each vocabulary may have different pathauto patterns.
Other exposed filters should still work without any conflict.

Place this code in your custom module (CUSTOMMODULE.module):

<code>/**
 * Implements hook_form_FORM_ID_alter().
 */
function CUSTOMMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  // Replace `Size` filter.
  CUSTOMMODULE_jumpmenu($form, 'field_size_tid');

  // Replace `Color` filter.
  CUSTOMMODULE_jumpmenu($form, 'field_color_tid');
}

/**
 * Transform select filters into a simple jump menu.
 *
 * @param $form
 *   Nested array of form elements that comprise the form.
 * @param $field_name
 *   String representing the name of the field to be replaced.
 */
function CUSTOMMODULE_jumpmenu(&$form, $field_name) {
  if (
    isset($form[$field_name])
    && ($form[$field_name]['#type'] === 'select')
    && !empty($form[$field_name]['#options'])
  ) {
    $options = &$form[$field_name]['#options'];
    foreach ($options as $tid => $value) {
      if (is_int($tid)) {
        $path = drupal_get_path_alias('taxonomy/term/' . $tid);
        $options[url($path)] = $value;
        unset($options[$tid]);
      }
    }

    $form[$field_name]['#attributes']['onChange'] = 'javascript:if (this.value !== "All") { location.href = this.value; return false; }';

    return $form;
  }

  return [];
}
</code>
You can test this solution with this simple view:

<code>$view = new view();
$view->name = 'example_view';
$view->description = '';
$view->tag = 'drupal_stackexchange';
$view->base_table = 'node';
$view->human_name = 'Example view';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE;

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Example view';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '50';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'field_color' => 'field_color',
  'field_size' => 'field_size',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_color' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_size' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Color */
$handler->display->display_options['fields']['field_color']['id'] = 'field_color';
$handler->display->display_options['fields']['field_color']['table'] = 'field_data_field_color';
$handler->display->display_options['fields']['field_color']['field'] = 'field_color';
/* Field: Content: Size */
$handler->display->display_options['fields']['field_size']['id'] = 'field_size';
$handler->display->display_options['fields']['field_size']['table'] = 'field_data_field_size';
$handler->display->display_options['fields']['field_size']['field'] = 'field_size';
/* Sort criterion: Content: Title */
$handler->display->display_options['sorts']['title']['id'] = 'title';
$handler->display->display_options['sorts']['title']['table'] = 'node';
$handler->display->display_options['sorts']['title']['field'] = 'title';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'tshirt' => 'tshirt',
);
/* Filter criterion: Content: Size (field_size) */
$handler->display->display_options['filters']['field_size_tid']['id'] = 'field_size_tid';
$handler->display->display_options['filters']['field_size_tid']['table'] = 'field_data_field_size';
$handler->display->display_options['filters']['field_size_tid']['field'] = 'field_size_tid';
$handler->display->display_options['filters']['field_size_tid']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_size_tid']['expose']['operator_id'] = 'field_size_tid_op';
$handler->display->display_options['filters']['field_size_tid']['expose']['label'] = 'Size';
$handler->display->display_options['filters']['field_size_tid']['expose']['operator'] = 'field_size_tid_op';
$handler->display->display_options['filters']['field_size_tid']['expose']['identifier'] = 'field_size_tid';
$handler->display->display_options['filters']['field_size_tid']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
$handler->display->display_options['filters']['field_size_tid']['type'] = 'select';
$handler->display->display_options['filters']['field_size_tid']['vocabulary'] = 'size';
/* Filter criterion: Content: Color (field_color) */
$handler->display->display_options['filters']['field_color_tid']['id'] = 'field_color_tid';
$handler->display->display_options['filters']['field_color_tid']['table'] = 'field_data_field_color';
$handler->display->display_options['filters']['field_color_tid']['field'] = 'field_color_tid';
$handler->display->display_options['filters']['field_color_tid']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_color_tid']['expose']['operator_id'] = 'field_color_tid_op';
$handler->display->display_options['filters']['field_color_tid']['expose']['label'] = 'Color';
$handler->display->display_options['filters']['field_color_tid']['expose']['operator'] = 'field_color_tid_op';
$handler->display->display_options['filters']['field_color_tid']['expose']['identifier'] = 'field_color_tid';
$handler->display->display_options['filters']['field_color_tid']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
$handler->display->display_options['filters']['field_color_tid']['type'] = 'select';
$handler->display->display_options['filters']['field_color_tid']['vocabulary'] = 'color';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'example-view';
$handler->display->display_options['menu']['type'] = 'normal';
$handler->display->display_options['menu']['title'] = 'Example view';
$handler->display->display_options['menu']['name'] = 'main-menu';
</code>
Answer: In the end, I did this way:
<code>    $params = drupal_get_query_parameters();
    $redirected_fields = array('field_size_tid','field_class_tid','field_color_tid', field_brand_tid);
    $checked_fields = array();

    foreach ($params as $key => $val) {
      if ($val == '' || $val == 'All') {} else { $checked_fields[] = $key; }
    }

    if ((count($checked_fields) == 1) && (in_array($checked_fields[0],$redirected_fields)) && (count($params[$checked_fields[0]]) == 1)) {
      $selected_tid = $form_state['view']->exposed_input[$checked_fields[0]];
      if (is_array($selected_tid)) {$selected_tid = implode('',$selected_tid);}
      // Check if such taxonomy term exists.
      $term = taxonomy_term_load($selected_tid);
      //dpm($term);
      if (!empty($term)) {
        // Redirect to taxonomy page.
        $path_alias = drupal_get_path_alias('taxonomy/term/'.$selected_tid);
        drupal_goto($path_alias);
      }
    }
</code>
Comment: In principle, it's the same approach as I suggested. Besides you gave only size and color arguments, never mentioned class on your question. Anyways, don't leave your questions with no any answer accepted if you want keep getting help from others.
Comment: Yes, I made my code based on yours, because In my question, the field structure was hardened. Your answer is very helpful, thank you.
Comment: Viktor, that is why you have to be little bit more appreciative and accept my answer. Please understand that you discourage other users to work to help you if you just use their code without accepting their answers.
Comment: But maybe you don't know how to ACCEPT an answer around here? Please read https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Comment: Sorry, I did not know about that. Thank you very much for your advice and help.
Comment: Thanks for accepting my answer. This is how StackExchange work. Users help each other and for the efforts put they hope to get accepts.


Let $f(x)=x^2\operatorname{sign}(x)|\cos\frac{\pi}x|$. Show $f(x)$ has points of non-differentiability in any neighbourhood of $x=0$ and general help.

Question:
Let $f(x)=x^2\operatorname{sign}(x)|\cos\frac{\pi}x|$.
Show that $f(x)$ has points of non-differentiability in any
  neighbourhood of $x=0$.

We have already shown differentiability at $x=0$.
My original post was to verify a step in my work but I've realised whilst typing up here that it is not valid for another reason, so I have reformed the question so that I would still like an answer to the question above but also to the question asked below as it addresses roughly the step I was unsure of in my approach.

In general to show whether or not $f(x)=g(x)+h(x)$ is differentiable
  can we do the following?:
Say $$\lim_{h\rightarrow 0}\frac{g(x+h)+h(x+h)-g(x)-h(x)}h$$ exists or
  we're done. Then to show $$\lim_{h\rightarrow
 0}\frac{g(x+h)+h(x+h)-g(x)-h(x)}h=\lim_{h\rightarrow
 0}\frac{g(x-h)+h(x-h)-g(x)-h(x)}{-h}$$ can I now say this it true if
  and only if $$\lim_{h\rightarrow
 0}\frac{g(x+h)+h(x-h)-g(x)-h(x)}h=\lim_{h\rightarrow
 0}\frac{g(x-h)+h(x+h)-g(x)-h(x)}{-h}?$$ i.e. I've moved the
  $h(\delta\pm h)$s. I'm sure we can do this if $\lim_{h\rightarrow
 0}h(\delta\pm h)$ exists but $\lim_{h\rightarrow 0}f(\delta\pm h)$ can
  exist without $\lim_{h\rightarrow 0}h(\delta\pm h)$ existing, and in
  the case $\lim_{h\rightarrow 0}h(\delta\pm h)$ does not exist I'm not
  sure if this step would be valid.

Thanks and sorry if this post was all over the place.
Answer: If $f(a) = 0$ and $f'(a)\ne 0,$ then $|f(x)|$ is not differentiable at $a.$ Proof: Suppose WLOG $f'(a)>0.$
In the following we assume $x$ is close to, but not equal to, $a.$ The first thing to notice is that $f(x) > 0$ for $x>a$ and $f(x) < 0$ for $x<a.$ Thus if $x>a,$
$$\frac{|f(x)|-|f(a)|}{x-a}=\frac{f(x)-f(a)}{x-a} \to f'(a)$$
as $x\to a^+.$ Similary,
$$\frac{|f(x)|-|f(a)|}{x-a}=\frac{-f(x)-f(a)}{x-a} = -\frac{f(x)-f(a)}{x-a}\to -f'(a)$$
as $x\to a^-.$ Thus the limit fails to exist.
To finish the problem you just need to find lots of points where you can apply the above. (It may be helpful to notice that $|f(x)| = |x^2\cos\frac{\pi}x|.$)
Comment: This is actually very easy, thanks
Answer: In general, $|f(x)|$ has a point of non-differentiability  every time $f$ changes from positive to negative (or vice versa) when $f(x) =
 0$ and $f'(x) \neq 0$. Does this help?
Comment: That's actually not true. For example $|x^3|$ is differentiable at $0.$ Also your comment is incorrect. You can't use the chain rule because the hypotheses of the chain rule theorem are not satisfied. (And you don't want to say "infinite", because there is nothing infinite happening there.)
Comment: Use the chain rule: $\frac{d}{dx} |f(x)| = f'(x) \frac{d}{du} |u|_{u=f(x)}$, and $\frac{d|u|}{du}$ is infinite wherever $u = 0$. You can do it more formally with epsilons and deltas if you need.
Comment: I'm sure it will, thanks- is this easy to show, it looks like it should be?
Comment: @zhw. You're right. I don't know what I was thinking; I must have gotten the first and second derivatives confused (if you think like a physicist, the second derivative of $|x|$ is just $2 \delta(x)$, so it is infinite at $x = 0$).


Classic Tokenizer is not working as expected

Question: I referred this
I tried to do the same. But it didn't work.

Any suggestions?
I understand that it works for I.B.M. But not for I.B.M
Comment: you have to use the ClassicTokenizerFactory with the combination of ClassicFilterFactory. How did you define you fieldType
Comment: @AbhijitBashetti I used both. CT and CF are there in the analyzer.
Answer: You can try the below fieldTYpe for your field.
<fieldType name="customClassicType" class="solr.TextField">
<analyzer type="index">
  <tokenizer class="solr.WhitespaceTokenizerFactory"/>
  <filter class="solr.WordDelimiterGraphFilterFactory" catenateWords="1"/>
  <filter class="solr.FlattenGraphFilterFactory"/>
</analyzer>

<analyzer type="query">
  <tokenizer class="solr.WhitespaceTokenizerFactory"/>
  <filter class="solr.WordDelimiterGraphFilterFactory" catenateWords="1"/>
</analyzer>
</fieldType>

Here is the output on the analysis page.
Comment: @Gibbs:yes the second screenshot shows the search for I.B.M here there is no dot at the end
Comment: @Gibbs: Please try the provided fieldtype at your solr schema and verify
Comment: I will try and let you know. Thanks


menu_get_object() not returning node object when view's display is Entity Reference

Question: I needed get field's value and pass it as contextual filter to "entity reference view" just described as views and contextual filters with entity reference field.
But $Node = menu_get_object() is not retuning node object.
The scenario
Nodes Items of custom content type
Title : Sony LCD
Tags : electronic
Title : The godfather
Tags :Books
.
.
Items(n)
Node of custom content type Review. It's node id is 10
Title : Make a Review
Filter Tags : Taxonomy terms reference (e.x electronic, books, movies etc)
Attach a entityform to above node using entity reference and also back referenced with enityreference_current
My Review Item : EnityReference field - Entity reference view - Autocomplete widget
Review : text area
When node/10 is viewed, user will have to fill "my review item",but should be filter based on "Filter tags" that was already set.
Code inside VIEWS PHP under Contextual Filter
$node = menu_get_object ();
$ Related_ids = array ();
    $ Related = field_get_items ('node', $node, 'field_filter_tags') // Get the term reference field
    if ($related && is_array ($related) && sizeof ($related)> 0) {
      for ($i = 0; $i <count ($related); $i++) {
        $ Related_ids [] = $related [$i]['target_id'];
      }
    }
    return implode (',', $related_ids);//to perform AND

Update : I also tried with $node= node_load(arg(1)); , this time $node variable set but not type of node. Then I dpm(arg(1)); it shows string autocomplete(yes just autocomplete not string entered in field).
Comment: `menu_get_object` gets a loaded object from a router item. If you call it when non-node is displayed, it simply cannot return node. Where exactly do you call it? And what exactly does it return?
Comment: @Mołot entityform is attached to node like mentioned in this [thread](https://drupal.org/node/2041349#comment-7643451).Entity Form submission is done via node(in above case node/10).That means node object is displaying, am I correct?.  In php code I am checking if(isset($node)) return 1; else return 0; and it returning 0.
Comment: That *should* mean it. But if the attached part is rendered separately, that connection might be lost inside. Try to `dpr($node);` in your code and tell us what really is there, OK?
Comment: dpr($node); is not showing anything but, notice shown `Notice: Undefined variable: node in eval() (line 8 of C:\server\www\mysite.local\sites\all\modules\views\plugins\views_plugin_argument_default_php.inc(53) : eval()'d code)`.Another thing menu_get_object() is called without parameter as default is 'node'.Is it possible to use entity_metada_wrapper inside view's php code section to get node?
Comment: If `dpr(menu_get_object())` also fails, we have a problem. What you say about entity_metada_wrapper sounds reasonable, but I can't tell now, sorry.
Comment: Why not just go super-low tech and use `$node = node_load(arg(1))` if you're definitely on the node page?
Comment: @Clive I think you haven't noticed the update made to the question.I also checked that method.
Comment: @kiranking Your edit helps to make sense of it, see the answer below
Answer: The entityreference autocomplete paths are defined in entityreference_menu() as:

entityreference/autocomplete/single/%/%/%
entityreference/autocomplete/tags/%/%/%

The wildcard arguments are field name, entity type and bundle respectively. The entityreference_autocomplete_callback() function also accepts an optional entity id and string parameter (the last being the search string).
So while you're expecting the path to be node/[nid], it'll actually be one of the above - which explains why arg(1) is giving you the string autocomplete.
I haven't tried it but you should be able to use arg(6) to get the node ID in your current context.
Comment: I checked with arg(6) but failed to get node. I also checked from arg(1)_ to arg(10) and dpm that. The last entity that is fetched was "st" beyond that every args returns empty.I didn't get what exactly **st** here.`arg 1  autocomplete   | arg 2   single |  arg 3   field_select_books  |  arg 4   entityform |  arg 5   add_book  |  arg 6   NULL  | arg 7   st`
Comment: When autocomplete field is moved from entityform to its parent node then arg(6) is returning `node` as you told.  `ReviewNode title,tags,{entityform [aucomplete entity reference view]}` - **doesn't work**  `ReviewNode title,tags,[aucomplete entity reference view],{entityform}` **worked**. From this what I am getting is, it is not further backtracing beyond entityform to get its parent element :(.
Comment: I think the problem is with entityform when it is attached node.Some issues @ D.O https://drupal.org/node/2043287#comment-7750131 , https://drupal.org/node/2244987 , https://drupal.org/node/2078573


Bool has not been declared

Question: I have been trying to do some programming in c++ and i'm unable to understand what is the mistake here.  i'm using code blocks ide and when i run the program the only error i'm getting is
error: 'boolean' has not been declared|
||=== Build finished: 1 errors, 0 warnings (0 minutes, 0 seconds) ===||
 Let me know, if you guys found any and put me in right direction.
Ok. here is the actual code. But i'm not yet completed fully. i'm just halfway through.
#include <iostream>

using namespace std;

bool isGoodCountry(char &countryName, int numCities, int numVillages, boolean hasNuclearPower, char &continentName, char &neighborCountries){

if(1==2){

    return false;
}
return true;

}
int main()
{
    cout << "Hello world!" << endl;

    char countryName[25];
    int numCities, numVillages;
    bool hasNuclearPower;
    char continentName[25], neighborCountries[150];

    cout<<"Enter name of the Country: ";
    cin>>countryName;

    cout<<"Enter number of cities in the country: ";
    cin>>numCities;

    cout<<"Enter number of villages in the country: ";
    cin>>numVillages;

    cout<<" Does the country has Nuclear Power: ";
    cin>>hasNuclearPower;

    cout<<"Enter name of the continent: ";
    cin>>continentName;

    cout<<"Enter the neighbor countries names: ";
    cin>>neighborCountries;

    isGoodCountry(*countryName, numCities, numVillages, hasNuclearPower, *continentName, *neighborCountries);
    return 0;
}

 Thanks & regards
Comment: As written your code never uses `boolean`. Could it be that your attempt to simplify has made the essential line of code disappear?
Comment: You don't need #include  and #include , instead if required you should include
Comment: For the edited question, you are using `boolean` type, it should be `bool` in C++.
Comment: You don't need to add `#include` and `include` too.
Comment: what is this `if(condition 1){` ?
Comment: `condition 1` and `Some arguments` appear to be nonsense. What do you expect?
Comment: @user322 - Pls accept computerfreakers answer
Comment: Even i thought it would be wise, as he has relatively low points compared to you. Thanks agian.
Comment: yah. even then the error is showing up.
@david I'm returning false if cond1 satisfies else true
Comment: @user322 - Post code that compiles?
Comment: @ Floris Yah. in order to simplify i did like this. But, now i'hav written all
Comment: @user322- that is why i suggested it
Answer: bool isGoodCountry(char &countryName, int numCities, int numVillages, boolean hasNuclearPower, char &continentName, char &neighborCountries){

boolean isn't a type; you meant bool.
bool isGoodCountry(char &countryName, int numCities, int numVillages, bool hasNuclearPower, char &continentName, char &neighborCountries){

Comment: Your cut'n'paste is quicker than mine by 13 secs!
Comment: @Ed FGITW. ;) Still +1 for you, a right answer is a right answer regardless of when it's posted.
Comment: You got a +1 from me too
Comment: @ Ed Heal & @ computerfreaker
I'm feeling very stupidy after realising my mistake.. i'm lookin at the function instead of the arguments all the time.
Anyhow, thanks for your time dudes..
Answer: Should the line
bool isGoodCountry(char &countryName, int numCities, int numVillages, boolean hasNuclearPower, char &continentName, char &neighborCountries){

be
 bool isGoodCountry(char &countryName, int numCities, int numVillages, bool hasNuclearPower, char &continentName, char &neighborCountries){

Comment: Now, i'm confused whom to accept the answer among both of you :)
Answer: instead of
bool isGoodCountry(char &countryName, int numCities, int numVillages, boolean hasNuclearPower, char &continentName, char &neighborCountries)

you should write
bool isGoodCountry(char &countryName, int numCities, int numVillages, bool hasNuclearPower, char &continentName, char &neighborCountries)

boolean is not a data type. The data type is bool.
in your if statement you write
if(1==2)

this can't be possible, so the function will always return true, so why you have to use if ?

Bool has not been declared


Change diagonal plots in ggpairs

Question: I'm not able to change the diagonal plots in a ggpair-plot. I would like to change their appearance in general and maybe starting by leaving them blank.
This is how I think it should be:
ggpairs(data=df,
             columns=1:3,
             diag = list(discrete = "blank"),
             title="APD pool",
             mapping=ggplot2::aes(colour = Irradiated)
            )

but it ends with a density curve(?!) in the diagonal elements.
Due to Robin's comment I tried it with
ggpairs(data=df,
             columns=1:3,
             diag = list(continous = "blank"),
             title="APD pool",
             mapping=ggplot2::aes(colour = Irradiated)
            )

but it doesn't change.

What am I doing wrong?
Thank you!
Reference: https://rdrr.io/cran/GGally/man/ggpairs.html
Comment: The data are continuous, not discrete.
Comment: Thank you but this didn't change anything
Comment: It should be continuous, not continous :)
Answer: You spelled continuous wrongly. Your code spelt it "continous" instead.
When you use diag, you have to pass in a list that may only contain the variables continuous, discrete, and na. When you assign a value to continuous, it can only be exactly one of

'densityDiag'
'barDiag'
'blankDiag'

So instead of diag = list(continous = "blank") you want to have diag = list(continuous = "blankDiag") instead. That would do the trick:

Change diagonal plots in ggpairs


viewing source of namespace resolver functions linux fedora

Question: I want to see the source of functions like ns_initparse(), res_search() etc. Where can I look for them?
Answer: Here's are the steps I take find the source for res_search.
$ man res_search

I see in that man page: Link with -lresolv

$ ls /usr/lib/libresolv*

Oops, nothing there. Where else do we look? How about:
$ ls /lib/libresolv*
/lib/libresolv-2.7.so  /lib/libresolv.so.2

Great. Now what package is that from?
$ rpm -qf /lib/libresolv-2.7.so
glibc-2.7-2

Ah. It's in glibc. Now, there are two choices. I can fetch the source RPMs, and look through those, in order to get the exact version that that my system was built from, but that's a bit complicated to set up.
If you don't need the exact source RPM that you were built from, you can instead look through the [upstream](http://en.wikipedia.org/wiki/Upstream_(software_development)) source code. Just look around the glibc site to find the source code, and start looking through there.
$ curl -O http://ftp.gnu.org/gnu/glibc/glibc-2.7.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 20.2M  100 20.2M    0     0  12.3M      0  0:00:01  0:00:01 --:--:-- 12.8M
$ tar xzf glibc-2.7.tar.gz
$ cd glibc-2.7
$ find . -name "*.c" | xargs grep res_search
./resolv/res_data.c:res_search(const char *name, /* domain name */
./resolv/res_data.c:# undef res_search
./resolv/res_data.c:weak_alias (__res_search, res_search);

And there you have it!
If you have Git installed, instead of just downloading the tarball, you could clone the git repo, and look through that. That way, you can also look at any past or future version, to see how it's changed over time.
$ git clone git://sourceware.org/git/glibc.git
$ cd glibc
$ git checkout glibc-2.7
$ git grep res_search
resolv/res_data.c:res_search(const char *name,  /* domain name */
resolv/res_data.c:# undef res_search
resolv/res_data.c:weak_alias (__res_search, res_search);
Answer: I am not sure if you are interested in Fedora specific stuff, but I have had good luck with Google Code Search for finding source code for certain functions.
Comment: Thank u very much. This is a great link. I did not know that we search functions at google code.
Comment: The chances are that those library functions are not Fedora specific.
Comment: Google Code Search is now dead. But see http://stackoverflow.com/questions/7778034/replacement-for-google-code-search for various replacements.
Answer: Once you figure out which package provides the functions you are interested in, all you need to do on Fedora is debuginfo-install glibc-2.7-2. More info here.


$\lim_{n \to \infty} (u_{n+1}-u_n)$ does not converge then $\lim_{n \to \infty} u_n$ does not converge

Question: Prove that if $\lim_{n \to \infty} (u_{n+1}-u_n)$ does not converge then $\lim_{n \to \infty} u_n$ does not converge.
My try-
Contrapositive statement - If $\lim_{n \to \infty} u_n$ converges then $\lim_{n \to \infty} (u_{n+1}-u_n)$ converges.
Let , $\lim_{n \to \infty} u_n=L$
Then $\lim_{n \to \infty} u_{n+1}=L$
$\lim_{n \to \infty} (u_{n+1}-u_n)=L-L=0$
Is the proof correct? Any other proof is also desirable.
Comment: Do not edit your question to completely change its meaning.  Doing so creates a moving target for potential answerers.  If you get an answer in the comments, consider self-answering the question using those comments.  Or consider deleting the question if you don't think that the answer in the comments will be of much use to future readers.  If a new question arises use the "Ask Question" button to ask a new question.
Answer: First of all, a bit of terminology: a limit does not converge. Sequences converge, while limits (may) exist and equal something. Another thing: please be sure to define the environment where you are working. What is $u_n$? A sequence of real numbers? A sequence of functions? A sequence with values in which space?
Suppose we are talking about sequences of real numbers. If the sequence converges, then it is a cauchy sequence, meaning that for every $\varepsilon > 0$ there exist a $N \in \mathbb{N}$ such that for all $n,m > N$ we have $ |u_{n+1} - u_n| < \varepsilon$.
Now define the following: $a_n := u_{n+1} - u_n$. You easily see that $a_n$ converges by definition of cauchy sequence.


"covariate*log(time+20)" specified in extended Cox model

Question: In this article by Terry Therneau 2016, to address time-varying effect,
library(survival)

Testing proportional hazard assumption:
vfit <- coxph(Surv(time,status) ~ trt + prior + karno, data = veteran)
zp <- cox.zph (vfit, transform=function(time) log(time+20)
zp

Extended Cox model addressing time-varying effect:
vfit3 <- coxph (Surv(time,status) ~ trt + prior + karno + tt(karno),
              data = veteran,
              tt = function (x,t, ...) x*log(t+20))

I am concerned with usage of log(t+20) that author used in both analyses (testing assumption and addressing time-varying effect). why using specifically log(t+20) rather than just log(t) which is commonly used by some people (I think)?
*Something I would like to add, not directly related to my post question:
I strongly suggest someone with rep above 300 add a new tag "time-varying-coefficients" (only "time-varying-covariates" exist, but the two are different and very important to distinguish them). With appropriate 'tag' make post efficiently be searched. Thanks in advance.*
Answer: On page 19, the authors said:
"The time scale for the cox.zph plot used further above of $\log(t + 20)$ was chosen to make the first 200 days of the plot roughly linear."
t is survival time. $\log(t) = - \infty $ as $t \rightarrow 0$. So I think it is another reason to have +20 there so that the value of the function will not be close to large negative number. In fact you can construct the function of survival time as you like and suitable to the data.