How to find operation type in validating form?

Question: I have created a custom validate function for specific node form.
But validate rules are different between edit a current node or add a new node modes.
Now, I want to know, is there any way that we understand whether we are in edit mode or create mode in form_validate function ?
Comment: In which version you are trying to adding your custom form... D7 or D8?
Comment: I apologize, I forgot to write drupal version . D7
Answer: A new node will not have a node ID.
So you can check the form values or the original form for that to determine whether it is a new node or not.
For example:
if (empty($form_state['values']['nid'])) {
  // This is a new node.
}
else {
  // This is an existing node.
}

Comment: Thanks a lot rooby. I used your suggestion and it worked.
Answer: Rooby solution is good, but I usually check the presence of "nid" property in $form['#node']
function my_module_form_validate_func(&$form, &$form_state) {
  if (!isset($form['#node']->nid)) {
    //new node
  }
  else {
    //existing node
  }
}

Comment: Yep, there are at least 4 ways I can think of to check in various places in $form and $form_state. All valid.
Comment: Thanks for you attention. I have some other questions in different issues in drupal 7. if you can please visit https://drupal.stackexchange.com/questions/264230/activate-or-deactivate-requirement-status-of-field-based-on-another-field


What is wrong with this python command?

Question: Let me first say that I'm a newbie to python, and I've written a python shell named test.py. The content is as follows:
#!/usr/bin/python
import os
cur_dir = os.getcwd();
print 'hello world' > cur_dir+"/test.log" 2>&1

When I run test.py by "python test.py", it says:
File "test.py", line 4
print 'hello world' > cur_dir+"/test.log" 2>&1
                                          ^
SyntaxError: invalid syntax

Could anyone give me some idea? Thanks!
P.S.
what I want is to write a string in test.log file. That's all. As I said first, I'm REALLY new to python, so please don't be so harsh to me :), I'm gonna read through the tutorial first to have a glimpse of python, Thanks to all you guys!
Comment: Python is not bash.
Comment: You can't use shell redirection stuff like `>` and `2>&1` inside a Python program, because that's not Python code.  Read [the Python tutorial](http://docs.python.org/tutorial/) to familiarize yourself with the basics of Python.
Comment: Updated my answer. I can also recommend [Learn Python the Hard Way](http://learnpythonthehardway.org/) .
Answer: You are using invalid syntax. As a result Python gives you the error:
SyntaxError: invalid syntax

To fix this, stop using the invalid syntax.
Also in the future, explain what you are trying to achieve, and your answers are likely to tell you how to achieve that.
The invalid syntax looks like it's a bash redirection of stderr to stdout which makes no sense in the context above, so it's not possible to figure out what you are actually trying to do.
To write to a file you do this:
thefile = open('path_to_the_file', 'wt')
thefile.write('The file text.\n')

However, to do logging, you are better off using the logging module.
Answer: Use '>>' with print to redirect it to an alternate stream.
See How to print to stderr in Python?
Comment: Note that the shell redirection in the OP's example would print to stdout.

What is wrong with this python command?


Proof regarding the number of elements in a group, which are not self-inverse

Question: I have to prove that the number of elements $x$ in a group with $x\neq x^{-1}$ is always even.
My thoughts:
That means the number of elements $x$, which are not self-inverse, is even. By definition of a group, each element has one distinct inverse element. We don't count the identity element, since it is self-inverse. Let's say the number of elements (without the identity element) is odd. That would mean there does exist one element $y$, with $y=y^{-1}$. That would mean, that $y$ is self inverse, which is a contradiction. Therefore the number must be even.
Is my proof correct?
Comment: Simply note that the elements you want to count come in pairs $\{g,g^{-1}\}$. Thus their total is twice the number of such pairs, an even number.
Comment: The step where you write "That would mean ..." really lacks a justification.
Comment: @HenningMakholm: Why? The only way a group could have an odd number of elements is when at least one element is self-inverse.
Comment: @de_dust: Yes, that is _what you're being asked to prove_. Simply asserting that it is true does not constitute a proof.
Comment: As a consequence, every group of even order has a least one element of order two.
Comment: @ÉricGuirbal: Could you explain why this is a consequence?
Comment: @de_dust: Suppose $G$ is a group of even order. As the cardinal of the set $\{x\in G \mid x^{-1} \neq x\}$ is even, the cardinal of its complement $\{x\in G \mid x^2 = e\}$ is even too.  As this latter set is not empty (it contains the identity element), the group $G$ has at least one $x\neq e$ such that $x^2 = e$.
Answer:
This answer is just a synopsis of the answers given in comments, so the question doesn't hang around forever looking unanswered.

As per comments, the supplied proof has problems: it assumes what it's trying to prove.
To prove the result, note that the non-self-inverse elements come in pairs: if $x$ is not self-inverse then $x\ne x^{-1}$, i.e. $x^{-1}$ is also not self-inverse. If the group is finite, the number of non-self-inverse elements is even, as required.
This result has an interesting corollary.
Corollary. If a group $G$ has even order then $G$ has at least one element of order 2.
Proof. The number of elements in $G$ is even, and (as just shown) the number of non-self-inverse elements in $G$ is even, so the number of self-inverse elements in $G$ is even.  Since the identity $e$ is self-inverse, there must be at least one other self-inverse element of $G$ to make the total even.


Weird problem in exploding string with newline

Question: I dont know what's wrong with this PHP code:

$sql = "CREATE TABLE test (
 id mediumint(9) unsigned NOT NULL auto_increment,
 filenames text NOT NULL,
 meta longtext,
 added_date datetime NOT NULL default '0000-00-00 00:00:00',
 PRIMARY KEY  (id)
)";
var_export(explode("\n",$sql));

The code above basically explode the string in $sql with newline char ('\n') and then output it using var_export. I have some PHP tests file to worked with the code but not all of them displaying what I hope it would be:
array ( 0 => 'CREATE TABLE test ( ',
        1 => ' id mediumint(9) unsigned NOT NULL auto_increment, ',
        2 => ' filenames text NOT NULL, ',
        3 => ' meta longtext, ',
        4 => ' added_date datetime NOT NULL default \'0000-00-00 00:00:00\', ',
        5 => ' PRIMARY KEY (id) ', 6 => ') ;',
)
some diplaying this instead:

array ( 0 => 'CREATE TABLE test ( id mediumint(9) unsigned NOT NULL auto_increment, filenames text NOT NULL, meta longtext, added_date datetime NOT NULL default \'0000-00-00 00:00:00\', PRIMARY KEY (id) ) ;', )

notice the difference? the second one displaying it as there are no newline to exploding the string. I don't get what's happening here. Anyone knows something maybe?
Comment: Your editor probably used `\r` instead of `\n`.
Comment: If this is on a Windows system it could be a carriage return \r or if you're viewing the results in a webpage it could be an html
Comment: Yeah, I think thats the problem, but its weird that several PHP worked like I hope but not the rest, and the weirdest of all is the test files are all in the same directory.
Answer: You need to be flexible with what a line feed looks like. You can make a flexible explode:
preg_split("/[\r\n]+/", $sql)

... or you can normalize line feeds to the format of your choice:
$sql = strtr($sql, array(
    "\r\n" => "\n",
    "\r" => "\n",
));
explode("\n",$sql)

It's also worth noting that MySQL offers several SHOW statements that allow you to fetch most useful piece of data from table definitions. Parsing the SHOW CREATE TABLE output is often not necessary:
http://dev.mysql.com/doc/refman/5.1/en/show.html
Comment: What a great solution you have there. Thanks so much.
Answer: Were all pages created on the same computer? The line ending character code is different for different operating systems. It can be one of the following: \n, \r, and \r\n, depending on whether the system is Windows, Mac, or *nix. You may want to check for all three.
Comment: Yes, its in the same computer and same directory too. Yes it worked with \r well. I just know that it actually depend on the OS. Thanks so much, and to solve the problem I will go with Álvaro method above.


How to switch fixed elements when scrolling down the page

Question: How do people switch fixed elements when scrolling down the page? Here's a perfect example of what I mean at www.Joel.is.  If you look at the share buttons, as you scroll down past one post, the share button of the next post replaces the previous one using position:fixed
I have only seen posts that answer how to create the initial fixed position, but not switching. (http://stackoverflow.com/questions/4907872/changing-an-elements-css-position-after-scrolling-down-the-page).
Comment: Ever heard of "View Source..."?
Comment: Did that already. Still not sure...js scripts are jumbled
Answer: You would use the same principles, but edit the style of the element.

and then:
document.getElementById('ele').style.position = "absolute";

or for jQuery:
$('#ele').css('position', 'absolute');


charsets problems with php

Question: we are aproblems with codification in php, we are web site www.toroalbala.com and select rusian lenguage and is imposible to read caracter, we use a comun.php for all web, this is the codification, but when i change to tf8, i can read corect caracter in spanish-french

        Toro Albalá
    <meta http-equiv="Content-type" content="text/html;charset=iso-8859-1">
    <?PHP if ((($_REQUEST["seccion"] == "distribuidores") || ($_REQUEST["seccion"] == "admin")) && (isset($_REQUEST["salir"]))) { echo "<meta http-equiv='refresh' content='3;URL=comun.php?seccion=inicio&idioma=".$_SESSION["idioma"]."'>"; } ?>
    <link rel="stylesheet" type="text/css" href="estilo/estilo.css">

    <link rel="stylesheet" href="estilo/sifr.css" type="text/css" media="screen">

<?PHP
    if ($_REQUEST["seccion"] == "contacto")
    {
        echo "";
    }else
    {
        echo "";
    }
    // Se comprueba si se a solicitado un cambio de idioma, y se aplica dicho cambio
    if ((isset($_REQUEST["idioma"])) && (($_REQUEST["idioma"] == "ENG") || ($_REQUEST["idioma"] == "ESP") || ($_REQUEST["idioma"] == "FRA") || ($_REQUEST["idioma"] == "ITA")|| ($_REQUEST["idioma"] == "RUS")))
    {
        $_SESSION["idioma"] = $_REQUEST["idioma"];
    }

    // El idioma por defecto será Español. En caso de no encontrarse asignado se asignará por defecto
    if (!isset ($_SESSION["idioma"]))
    {
        $_SESSION["idioma"] = "ESP";
    }

    // Se incluye el fichero de idioma según el escogido
    switch ($_SESSION["idioma"])
    {
        case "ENG":
            include ("idioma/english.php");
            break;
        case "ESP":
            include ("idioma/espanol.php");
            break;
        case "FRA":
            include ("idioma/french.php");
            break;
        case "ITA":
            include ("idioma/italiano.php");
            break;
        case "RUS":
            include ("idioma/ruso.php");
            break;

    }

    // Generamos una URL para el cambio de idioma cumpliendo con los estándares (ampersand) y evitando la duplicación de variables
    $URL_div = split ("&", $_SERVER['REQUEST_URI']);
    $URL = $URL_div[0];
    for ($contador1 = 1; $contador1 < count($URL_div); $contador1++)
    {
        if ($URL_div[$contador1] != "idioma=".$_REQUEST["idioma"]."")
        {
            $URL = $URL."&".$URL_div[$contador1];
        }
    }
?>

<?PHP echo constant("_INICIO"); ?>
    <?PHP
        if ($_SESSION["idioma"] != "ENG"){ echo "  ";}
        if ($_SESSION["idioma"] != "ESP"){ echo "  ";}
        if ($_SESSION["idioma"] != "FRA"){ echo "  ";}
        if ($_SESSION["idioma"] != "ITA"){ echo "  ";}
        if ($_SESSION["idioma"] != "RUS"){ echo "  ";}

    ?>

<img style="max-width: 180px" src="imagenes/estructura/<?PHP echo $_SESSION["idioma"]; ?>/logotipo.gif" alt="Toro Albalá">

                <a href="comun.php?seccion=bodega&pag=1" OnMouseOver="cambio('boton1', '<?PHP echo $_SESSION["idioma"]; ?>');" OnMouseOut="volver('boton1', '<?PHP echo $_SESSION["idioma"]; ?>');"><img class="menu" id="boton1" src="imagenes/botones/<?PHP echo $_SESSION["idioma"]; ?>/boton1_inicio.gif" alt="Nuestra bodega">
                <a href="comun.php?seccion=vinos" OnMouseOver="cambio('boton2', '<?PHP echo $_SESSION["idioma"]; ?>');" OnMouseOut="volver('boton2', '<?PHP echo $_SESSION["idioma"]; ?>');"><img class="menu" id="boton2" src="imagenes/botones/<?PHP echo $_SESSION["idioma"]; ?>/boton2_inicio.gif" alt="Nuestros vinos">
                <a href="comun.php?seccion=otros_productos" OnMouseOver="cambio('boton3', '<?PHP echo $_SESSION["idioma"]; ?>');" OnMouseOut="volver('boton3', '<?PHP echo $_SESSION["idioma"]; ?>');"><img class="menu" id="boton3" src="imagenes/botones/<?PHP echo $_SESSION["idioma"]; ?>/boton3_inicio.gif" alt="Otros productos">
                <a href="comun.php?seccion=palmares" OnMouseOver="cambio('boton4', '<?PHP echo $_SESSION["idioma"]; ?>');" OnMouseOut="volver('boton4', '<?PHP echo $_SESSION["idioma"]; ?>');"><img class="menu" id="boton4" src="imagenes/botones/<?PHP echo $_SESSION["idioma"]; ?>/boton4_inicio.gif" alt="Palmarés">
                <a href="comun.php?seccion=gastronomia" OnMouseOver="cambio('boton5', '<?PHP echo $_SESSION["idioma"]; ?>');" OnMouseOut="volver('boton5', '<?PHP echo $_SESSION["idioma"]; ?>');"><img class="menu" id="boton5" src="imagenes/botones/<?PHP echo $_SESSION["idioma"]; ?>/boton5_inicio.gif" alt="Gastronomía">
                <a href="comun.php?seccion=prensa" OnMouseOver="cambio('boton6', '<?PHP echo $_SESSION["idioma"]; ?>');" OnMouseOut="volver('boton6', '<?PHP echo $_SESSION["idioma"]; ?>');"><img class="menu" id="boton6" src="imagenes/botones/<?PHP echo $_SESSION["idioma"]; ?>/boton6_inicio.gif" alt="Prensa">
                <a href="comun.php?seccion=visita_virtual" OnMouseOver="cambio('boton7', '<?PHP echo $_SESSION["idioma"]; ?>');" OnMouseOut="volver('boton7', '<?PHP echo $_SESSION["idioma"]; ?>');"><img class="menu" id="boton7" src="imagenes/botones/<?PHP echo $_SESSION["idioma"]; ?>/boton7_inicio.gif" alt="Visita virtual">
                <a href="comun.php?seccion=contacto" OnMouseOver="cambio('boton8', '<?PHP echo $_SESSION["idioma"]; ?>');" OnMouseOut="volver('boton8', '<?PHP echo $_SESSION["idioma"]; ?>');"><img class="menu" id="boton8" src="imagenes/botones/<?PHP echo $_SESSION["idioma"]; ?>/boton8_inicio.gif" alt="Contacto">

<a href="comun.php?seccion=distribuidores" OnMouseOver="cambio('boton9', '<?PHP echo $_SESSION["idioma"]; ?>');" OnMouseOut="volver('boton9', '<?PHP echo $_SESSION["idioma"]; ?>');"><img style="border-width: 0;" id="boton9" src="imagenes/botones/<?PHP echo $_SESSION["idioma"]; ?>/boton9_inicio.gif" alt="Distribuidores">

<?PHP include ($_REQUEST["seccion"].".php"); ?>

    <?PHP include ("copyright.php"); ?>

Answer: You have to make sure your php files are saved as UTF-8 and additionally you can add following;
<?php header('Content-type: text/html; charset=utf-8'); ?>

Of course don't forget to add meta (:
<meta charset="utf-8">

Comment: meta is optional when serving the files from a server because http headers preveil but this is indeed a good idea not to keep a meta says iso while the headers say utf8 ;-)
Comment: Well, no matter if I will add PHP headers or not, I will still define meta charset in my html pages. I used to this and I will always use it (:

charsets problems with php


Strategies in Memory game

Question: There's well known Memory game where you have $2n$ cards of $n$ colours face down (it's originally a two-player game, but I'll consider solitaire version). You can $k$ times flip $2$ cards face up and take them if they have same colour, and you obviously want to collect as much as possible. It's pretty obvious that optimal strategy should be like that: flip $c_1(n, k)$ disjoint pairs, then take all $p_1$ pairs you saw, flip $c_2(n, k, p_1)$ more, repeat until you run out of flips.

What is the (asymptotic for $n \gg 1$) optimal strategy and how does distribution of score look like? Are there some breakpoints for certain ratios $k/n$?
What about optimal strategy, if goal is to maximize ratio between taken and flipped cards?
Comment: You must choose the second card to flip without looking at the first, correct?
Answer: The strategy can be much simpler:  take a pair if you know one, otherwise flip two unknown cards.  If you know a pair, you will need to use a flip to take it, so use the flip now.  That makes the analysis much easier.
Now a position is specified by $n$, the number of pairs remaining, $f$, the number of flips remaining, and $u$, the number of unpaired cards you know.  $u$ is always even.  We only need to consider cases where you don't know any pairs.  From a position $(n,f,u)$ you move to $$\begin {array} {c | c | c} \text{state}&\text{probability}&\text{pairs found}\\ \hline
(n,f-1,u+2)&\frac {(2n-u)(2n-u-2)}{2n(2n-1)}&0\\
(n-1,f-2,u)&\frac {2u(2n-u)+(2n-u)}{2n(2n-1)}&1\\
(n-2,f-3,u-2)&\frac {u(u-1)}{2n(2n-1)}&2 \end {array}$$
where the first line comes from picking two cards that don't match anything you know and don't match each other, the first term in the second line is picking one that matches a known card and one that is unknown, the second term in the second line is picking an unknown card and its match, and the thrid line is picking two known cards. There is a perturbation at the end where you might run out of flips.  If you have only one flip remaining you can't claim any pair you find.

Strategies in Memory game


Can't find maxPwdAge in AD LDAP

Question: I need to use the field "maxPwdAge" but I can't find out where it is.
I can read pwdLastSet without problems, but that field it's missing.
According to this
https://msdn.microsoft.com/en-us/library/ms676863(v=vs.85).aspx
the field it's available up to 2012 version, but it's missing in 2016 version? or it's a lack of documentation update?
I've created a VM which runs a trial version of MS Server 2016 and can't find the field there either (nor in my production AD Server)
Any hint of because this field is missing?
Answer: It is an attribute of the domain. You need to correct your query.
Comment: Correct it how?
Comment: Just found it, you're right. Now I have to figure out how to obtain it. I'm using spring boot

Can't find maxPwdAge in AD LDAP


Adicionando caractere em uma string

Question: Boa pessoa minha dúvida e a seguinte, eu tenho a seguinte situação:
eu tenho a seguinte variável
>>> a = "EXAMPLE"

Vamos supor que tive que remover a letra "M" destra string, neste caso faria
>>> a = a.replace("M", "")

Então sabendo-se que as string são imutáveis, sé por acaso eu quise-se retornar com string "M" na mesma posição, para que a mesma retorna-se para seu formato original que seria EXAMPLE". Obrigado.
Comment: Relendo sua pergunta, não tenho certeza se entendi a dúvida. Você está querendo saber se "volta" pro mesmo objeto após a reinserção da letra "M", por ser imutável? Se for isso, veja minha resposta abaixo. Se era outra coisa que você queria perguntar, favor [edit] a pergunta esclarecendo isso. P.S. Se a dúvida não for específica do Python 2.7, sugiro retaguear a mesma só com `python`.
Answer: Mesmo se você reinserir a letra retirada, você ainda estaria criando uma nova string, pois como você mesmo apontou elas são imutáveis, então tanto retirar quanto colocar criam novos objetos. Isso pode ser verificado facilmente observando o id do objeto:
>>> a = "EXAMPLE"
>>> id(a)
32844376L
>>> b = a.replace("M", "")
>>> id(b)
32845176L
>>> c = b[:3] + "M" + b[3:]
>>> id(c)
32843016L
>>> c
'EXAMPLE'

Muito embora as strings sejam imutáveis, o Python não "cacheia" as mesmas por padrão. Se você quiser uma string única - que possa ser comparada só pelo endereço de memória (por eficiência) - você precisa explicitamente dizer pro Python colocá-la na cache, usando intern:
>>> a = intern("EXAMPLE")
>>> id(a)
32843976L
>>> b = intern(a.replace("M", ""))
>>> id(b)
32844256L
>>> c = intern(b[:3] + "M" + b[3:])
>>> id(c)
32843976L

(entretanto, se nenhuma referência adicional existir pra string cacheada, ela pode ser recolhida pelo coletor de lixo e uma nova ser criada no futuro)
Comment: Não, o `intern` simplesmente garante que duas strings iguais (no mesmo momento da execução) sejam representadas pelo mesmo objeto. Ou seja, se você coloca uma string retornada pelo `intern` em uma estrutura de dados, e depois tenta pesquisar nessa estrutura usando uma string também retornada pelo `intern`, então ele pode encontrar esse dado sem ter que comparar caractere por caractere, olhando só pelo endereço de memória. Entretanto, não sei quais estruturas de dados do Python se aproveitam desse fato, nem como isso funciona internamente.
Comment: entendi, funcionou perfeitamente. Esse intern que vc informou seria  no caso de eu manipular dados na memória. Seria isso
Comment: Beleza, valeu ajudou bastante obrigado.

Adicionando caractere em uma string


Problems with update and update_idletasks

Question: I've been learning python for a month now and run into my first brick wall.  I have a large art viewer GUI program and at one point want to put an image on screen with a countdown counter-approx every 5 secs.  I thought of a code such as the one below    The problem is that this uses update and all my reading says that update is bad (starts a new event loop (?)) and that I should use update_idletasks.  when I replace update with update_idletasks in the code below the countdown button is not visible until it reaches single figures, update superficially works fine.  But also the q bound key calls the subroutine but has no effect
from tkinter import *
import sys
import time

root = Tk()

def q_key(event):
    sys.exit()

frame=Frame(root, padx=100, pady=100, bd=10, relief=FLAT)
frame.pack()
button=Button(frame,relief="flat",bg="grey",fg="white",font="-size 18",text="60")
button.pack()
root.bind("q",q_key)

for x in range(30, -1, -5) :
   button.configure(text=str(x))
   button.update()
   print(x)
   button.after(5000)

root.mainloop()

Comment: Actually,it wil also block your code,you could think about make a function and call `.after()` to do it.
Comment: Does this answer your question? [tkinter: how to use after method](https://stackoverflow.com/questions/25753632/tkinter-how-to-use-after-method)
Comment: First you have to understand [Event-driven_programming](https://en.m.wikipedia.org/wiki/Event-driven_programming). Read through [`[tkinter] event driven programming`](https://stackoverflow.com/search?q=is%3Aanswer+%5Btkinter%5D+event+driven+programming+entry)
Answer: In this case you don't need update nor update_idletasks. You also don't need the loop, because tkinter is already running in a loop: mainloop.
Instead, move the body of the loop to a function, and call the function via after. What happens is that you do whatever work you want to do, and then schedule your function to run again after a delay. Since your function exits, tkinter returns to the event loop and is able to process events as normal. When the delay is up, tkinter calls your function and the whole process starts over again.
It looks something like this:
def show(x):
    button.configure(text=x)
    if x > 0:
        button.after(5000, show, x-5)

show(30)


Why is sampling distribution = likelihood function? due to the central limit theorem?

Question: I noticed something peculiar when I define the binomial distribution:
$$p(r,n,\theta)=\theta^r(1-\theta)^{n-r} {n\choose r}$$
we can look at this distribution as a function of $r$, the sampling distribution: $s_{n,\theta}(r)=p(r,n,\theta)$, or as the likelihood of $\theta$: $L_{r,n}(\theta)=p(r,n,\theta)$.
What I noticed is that if we set $n$ small, these functions resemble each other somewhat though they are not the same, but when we set n very large, these functions tend to exactly the same values: $$s_{n,a}(x)\approx L_{a,n}(x)$$

Then I noticed that in the case of the normal distribution $\frac 1 {\sqrt {2\pi \sigma ^2}}e^{-\frac {(x-\mu)^2} {2 \sigma ^2}}$, the sampling distribution and the likelihood of $\mu$ are exactly the same, since we can just swap $x$ and $\mu$.
Of course in the normal distribution this is obvious from the formula, though I never explicitly thought about this in terms of the sampling distribution being equal to the likelihood function.
But in the case of the binomial distribution, it is not at all obvious to me from the formula why sampling distribution = likelihood function.

More generally, is there a general principle that the likelihood function and the sampling distributions should equal each other? Is there an intuitive reason why this should be the case?
Answer: Because of the definition of the likelihood function, which is defined as the joint probability of your sample observations (cf. Wackerly,  Mathematical Statistics With Applications).
If your observations are independant from each other, then the joint probability is the product of the probabilities (cf. Bayes https://stats.stackexchange.com/questions/21822/understanding-naive-bayes/21849#21849).
So in the end you just have a product of probability density functions.
But to answer your question, clearly the sampling distribution of a statistic function of your sample is not always equal to the likelihood function. Take for example the normal distribution : the likelihood will be : $$ L(\mu, \sigma^2 ) = f(y_1, y_2, ...,y_n |\mu, \sigma^2) = \left(\frac{1}{2\pi\sigma^2}\right)^{n/2}e^{\frac{-1}{2\sigma^2}\sum_{i=1}^{n}(y_i-\mu)^2}$$
Now compare it to the probability density of the sampling distribution of  $\bar{Y},$ the sample mean of  variables $  \sim N(\mu,\sigma^2) $ :$$ f(y) = \frac{1}{\frac{\sigma}{\sqrt{n}}\sqrt{2\pi}}e^{-\frac{(y-\mu)^2}{2\sigma^2}}$$


How to retrieve data from Firebase to TableViewCell

Question: I'm working on simple program - I create objects of products and then I count their calories.
I want to get all my product in TableViewController
I've created a method, allowing me to save data properly in Firebase, but I got stuck while retrieving them to cell. I got no mistakes, but I don't have any results as well
import UIKit
import Firebase

class MainTableViewController: UITableViewController {

    var products = [Products]()

    override func viewDidLoad() {
        super.viewDidLoad()

            DataService.dataService.PRODUCT_BASE.observeEventType(.Value, withBlock: { snapshot in

                print(snapshot.value)

                self.products = []

                if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {

                    for snap in snapshots {

                        if let postDictionary = snap.value as? Dictionary<String, AnyObject> {

                            let key = snap.key

                            let product = Products(key: key, dictionary: postDictionary)

                        }
                    }
                }

                self.tableView.reloadData()
        })

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return products.count
    }

    override func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("ProductCell") as! UITableViewCell?
        let ProductItem = products[indexPath.row]

        cell?.textLabel?.text = ProductItem.productName
        cell?.detailTextLabel?.text = String(ProductItem.productCalories)

        return cell!

    }

This is my DataService file:
import Foundation
import Firebase

let URL_BASE = FIRDatabase.database().reference()

class DataService {

    static let dataService = DataService()

    private var _REF_BASE = URL_BASE
    private var _USER_BASE = URL_BASE.child("users")
    private var _PRODUCЕ_BASE = URL_BASE.child("products")

    var REF_BASE: FIRDatabaseReference {
        return _REF_BASE
    }

    var USER_BASE: FIRDatabaseReference {
        return _USER_BASE
    }

    var PRODUCT_BASE: FIRDatabaseReference {
        return _PRODUCЕ_BASE
    }

    var CURRENT_USER_REF: FIRDatabaseReference {

        let userID = NSUserDefaults.standardUserDefaults().valueForKey("uid") as! String

        let currentUser = URL_BASE.child("users").child(userID)

        return currentUser

    }

    func CreateNewProduct(product: Dictionary<String, AnyObject>) {

        let ProductNewRef = DataService.dataService.PRODUCT_BASE.childByAutoId()

        ProductNewRef.setValue(product)

    }

I can't get what I'm doing wrong. All products are represented as a dictionary.
import Foundation
import Firebase

class Products {

    private var _productName: String!

    private var _productCalories: Int!

    var productName: String {

        return _productName

    }

    var productCalories: Int {

        return _productCalories
    }

    init(key: String, dictionary: Dictionary<String, AnyObject>) {

        if let calories = dictionary["calories"] as? Int {

            self._productCalories = calories
        }

        if let name = dictionary["name"] as? String {

            self._productName = name
        }

    }

}

Comment: what is your actual  issue?
Answer: You intilized the
var products = [Products]()

But not adding any items from firebase callback
if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
         let key = snap.key
         let product = Products(key: key, dictionary: postDictionary)
 }

please add self.products.append(product)
if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
         let key = snap.key
         let product = Products(key: key, dictionary: postDictionary)
         self.products.append(product)
 }


What type of regression model do I need to use?

Question: I am looking at the relationship between the two concepts of psychological strategy (PS) usage and athlete engagement (AE), looking to see if PS predicts AE as a whole and if certain subscales of PS predict subscales of AE.
I thought my data was ordinal but having second thoughts now as it may be different due to how I have inputted the data. Each component of both questionnaires is on a Likert scale of 1 to 5. In SPSS, I have inputted each item separately (e.g., item 1 and inputted their answer, e.g., 4) and then calculated specific subscales in a separate variable column. There are 9 subscales for PS and 4 for AE plus AE as whole.
Comment: Please do not delete & re-ask the same question.
Comment: Can you give some more details on how you calculate the subscales? Do you add the numerical values for different questions in the same category?
Comment: Yes, so for each sub scale on both questionnaires there are 4 questions, rated on a likert 1 to 5... the numbers are added and then averaged to produce a figure for each sub scale.
Comment: The individual question scales are ordinal, but as soon as you started adding them to produce subscales, you already assumed they were interval. I don't see a good reason to back away from that assumption if you were prepared to make it before. It's not like they became less-interval-scaled after you added them.
Answer: You will face a number of technical difficulties. First, the AE subscales are correlated with each other, so looking at the results from individual regressions in isolation is going to overestimate the effect of the PS predictors. Second, as you already surmised, the data are not really interval data, so calculating the subscales is questionable (even though "everybody" does it).
My guess is that you should sit down first and formulate a few hypotheses. Which measures and subscales of AE do you think should be related to the PS measures and why? Which of the PS measures and subscales do you think they relate to? DO THIS WITHOUT PEEKING AT THE DATA!
After that, you can look at correlations. Are the PS and AE measures and subscales correlated in the way your hypotheses say they should be? To start with, ordinary Pearson correlation is probably good enough. You might eventually want to switch to something that more closely models your data, such as Kruskal's gamma.
Finally, you might want to consider ordinal logistic regression, possibly multivariate ordinal logistic regression.


$E$ is a nonempty subset of an ordered set. If $\alpha$ is a lower bound of $E$ and $\beta$ is an upper bound, then $\alpha \leq \beta$.

Question: I think I  may be citing the law of transitivity incorrectly in this proof.
Theorem. Let $E$ be a nonempty subset of an ordered set. Suppose $\alpha$ is a lower bound of $E$ and $\beta$ is an upper bound of $E$. Prove that $\alpha \leq \beta$.
Proof.  Since $\alpha$ is a lower bound of $E$, and $E$ is nonempty, we have that $\forall x \in E, x \geq \alpha$. Similarly, since $\beta$ is an upper bound, we have $\forall x \in E, x \leq \beta$. Stringing these together yields $\forall x \in E, \alpha \leq x \leq \beta$, which by the transitivity property of ordered sets yields $\alpha \leq \beta$.
Here are my questions on this:
(a) Is it a fair assumption that a subset of an ordered set is also ordered? I wasn't sure whether I ought to 'prove' this first, though it seems almost too trivial to prove.
(b) I use transitivity a bit differently from Rudin's definition, based on past formulations I've seen. He seems to define this as $x < y \wedge y < z \implies x < z$, i.e., with strict inequalities. Should I break this into cases, wherein I consider all possible cases of strict inequalities as well as equalities between $\alpha$, $x$, and $\beta$? Or is this a natural extension of this property?
Thanks.
Comment: It seems good. Regarding your second question, it is a natural extension.
Answer: You're proof is almost correct.

The fact that E is nonempty is useless to state that ∀x∈E, x≥α (it would also be the case if E were empty!). Same for ∀x∈E, x≤β. These two relations are the definition of lower and upper bounds, respectively.
However, you need the fact that E is nonempty to prove that α≤β, because ∀x∈E,α≤x≤β would be also true if E were empty, but you couldn't argue that α≤β (because in this case α≤x≤β would never happen). A correct statement would be "E is nonempty so ∃x∈E. So α≤x and x≤β so α≤β."

(a) Yes, you can prove it easily.
(b) "<" and ">" are not orders because they do not check the reflexivity property of an order
Comment: They can be considered as strict orders. In fact, some books define orders as $<$ instead of $\leq$.
Comment: Would you mind explaining why they don't satisfy antisymmetry? It seems that $a < b$, for example, cannot coexist with $b < a$. Surely $<$ wouldn't be reflexive, though, whereas $\leq$ would be.
Comment: @Matt.P Oh, very good point. I think he/s wanted to say reflexivity.
Comment: Yes, my mistake I wanted to say reflexivity. I fixed it, thx
Answer: For your first question, your ordering actually relies on the ordering on the larger set, since the upper and lower bounds need not be members of the subset $E$ itself! For instance, if the original set is $\mathbb{R}$ and the subset is $(0,1)$, your lower bound could be $0$. So really you rely on the fact that the ordering is defined on the original set.
For your second question, to be completely rigorous, the transitivity of $\leq$ follows from transitivity of $<$ and $=$. Personally, I think it is fine to simply leave it as you have, but perhaps your professor wants you to add in additional detail if this is a first course in proofs or something.


Dagger NullPointerException 3ª classe que depende de 2ª classe

Question: Em um projeto que tem a Activity, Presenter e um Model, o Activity tem o Presenter e o Presenter tem um Model. Quando faço @Inject no Presenter para instanciar o Model ele nunca é instanciado.

FATAL EXCEPTION: main
                                                                                Process: fipedaggerrxjava, PID: 22258
                                                                                java.lang.NullPointerException: Attempt to invoke interface method
  'void
  fipedaggerrxjava.mvp.SelectMarcaContractMVP$Model.getMarcas(java.lang.String)'
  on a null object reference
                                                                                at
  fipedaggerrxjava.module.marca.MarcaPresenter.initData(MarcaPresenter.java:35)
                                                                                at
  fipedaggerrxjava.module.marca.MarcaActivity$1.onCheckedChanged(MarcaActivity.java:63)

Ja verifiquei no Debug e realmente o Model que não esta sendo instanciado pelo Dagger mas não consigo entender porque.
App
public class App extends Application implements HasActivityInjector{

    @Inject
    public DispatchingAndroidInjector<Activity> activityDispatchingAndroidInjector;

    @Override
    public void onCreate() {
        super.onCreate();
        DaggerAppComponent.builder().build().inject(App.this);
    }

    @Override
    public AndroidInjector<Activity> activityInjector() {
        return activityDispatchingAndroidInjector;
    }
}

ActivityBuilder
@Module
public abstract class ActivityBuilder {

    @Binds
    @IntoMap
    @ActivityKey(MarcaActivity.class)
    abstract AndroidInjector.Factory<? extends Activity> bindMarcaActivity (MarcaComponent.Builder builder);

}

AppComponent
@Component(modules = {ActivityBuilder.class, AndroidInjectionModule.class, AppModule.class})
@Singleton
public interface AppComponent {

    void inject(App app);

}

AppModule
@Module(subcomponents = MarcaComponent.class)
public class AppModule {

    @Provides
    @Singleton
    @Named("URL_MARCA")
    String provideStringURLBase(){
        return "https://fipe.parallelum.com.br/api/v1/";
    }

    @Provides
    @Singleton
    Context provideContext(App app){
        return app;
    }

    @Provides
    @Singleton
    Gson provideGsonRepositorie(){
        return new GsonBuilder()
                .create();
    }

    @Singleton
    @Provides
    OkHttpClient provideOkHttpCliente1(){
        return new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
    }

    @Singleton
    @Provides
    RxJavaCallAdapterFactory provideRxJavaCallAdapterFactory(){
        return RxJavaCallAdapterFactory.create();
    }

    @Provides
    @Singleton
    Retrofit provideRetrofit(OkHttpClient okHttpClient, Gson gson, RxJavaCallAdapterFactory rxAdapter, @Named("URL_MARCA") String stringBaseURL){
        return new Retrofit.Builder()
                .baseUrl(stringBaseURL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(rxAdapter)
                .client(okHttpClient)
                .build();
    }
}

MarcaComponent
@Subcomponent(modules = MarcaModule.class)
@PerMarca
public interface MarcaComponent extends AndroidInjector<MarcaActivity>{

    @Subcomponent.Builder
    abstract class Builder extends AndroidInjector.Builder<MarcaActivity> {}

}

MarcaModule
@Module
public class MarcaModule{

    @Provides
    @PerMarca
    APIFIPE provideAPIFIPE(Retrofit retrofit){
        return retrofit.create(APIFIPE.class);
    }

    @Provides
    @PerMarca
    View provideViewMarca(MarcaActivity activity){
        return activity;
    }

    @Provides
    @PerMarca
    Presenter providePresenterMarca(){
        return new MarcaPresenter();
    }

    @Provides
    @PerMarca
    Model provideModelMarca(){
        return new MarcaModel();
    }

}

AdapterMarca
public class AdapterMarca extends BaseAdapter {

private List<Marca> mListMarca;

@Inject
public Context mContext;

public AdapterMarca(List<Marca> listMarca){
    this.mListMarca = listMarca;
}

@Override
public int getCount() {
    return mListMarca.size();
}

@Override
public Object getItem(int position) {
    return mListMarca.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.layout_list_item, parent, false);

    TextView tvNome = view.findViewById(R.id.tv_marca);
    tvNome.setText(mListMarca.get(position).getName().toString());

    return view;
}

public void addListMarca(List<Marca> marcaList){
    mListMarca.clear();
    mListMarca.addAll(marcaList);
    notifyDataSetChanged();
}

}
MarcaActivity
public class MarcaActivity extends BaseActivity implements HasActivityInjector, View {

    private RadioGroup radioGroupMarca;
    private String tipoSelect = "";

    private List<Marca> mListMarca;
    private AdapterMarca mAdapterMarca;

    private ListView listViewMarca;

    @Inject
    public Presenter mMarcaPresenter;

    @Inject
    protected DispatchingAndroidInjector<Activity> activityDispatchingAndroidInjector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AndroidInjection.inject(MarcaActivity.this);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        listViewMarca = findViewById(R.id.lv_marca);

        radioGroupMarca = findViewById(R.id.rg_tipo);

        radioGroupMarca.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int id = group.getCheckedRadioButtonId();

                switch (id){
                    case R.id.rb_carros : tipoSelect = "carros";
                        mMarcaPresenter.initData(tipoSelect);
                        break;

                    case R.id.rb_motos : tipoSelect = "motos";
                        mMarcaPresenter.initData(tipoSelect);
                        break;

                    case R.id.rb_caminhoes : tipoSelect = "caminhoes";
                        mMarcaPresenter.initData(tipoSelect);
                        break;
                }
            }
        });

    }

    @Override
    public AndroidInjector<Activity> activityInjector() {
        return activityDispatchingAndroidInjector;
    }

    @Override
    public void onMarcaLoader(List<Marca> listMarcas) {
        if(mListMarca==null && listMarcas!=null){
            initListView();
        }

        if(mAdapterMarca!=null){
            mListMarca.clear();
            mListMarca = listMarcas;

            mAdapterMarca.addListMarca(mListMarca);
        }

    }

    private void initListView(){
        mAdapterMarca = new AdapterMarca(mListMarca);
        listViewMarca.setAdapter(mAdapterMarca);
    }

}

MarcaPresenter
@PerMarca
public class MarcaPresenter implements Presenter {

    @Inject
    View mMarcaView;

    @Inject
    Model mMarcaModel;

    @Inject
    public MarcaPresenter(){

    }

    @Override
    public void initData(String tipoMarca) {
        mMarcaModel.getMarcas(tipoMarca);
    }

    @Override
    public void getMarcas(List<Marca> listMarcas) {
        mMarcaView.onMarcaLoader(listMarcas);
    }

    @Override
    public void onShowDialog(String title, String msg) {
        mMarcaView.onShowDialog(title, msg);
    }

    @Override
    public void onHideShowDialog() {
        mMarcaView.onHideShowDialog();
    }

    @Override
    public void onShowToast(String s) {
        mMarcaView.onShowToast(s);
    }
}

MarcaModel
@PerMarca
public class MarcaModel implements Model {

    @Inject
    APIFIPE mApiFIPE;

    @Inject
    Presenter mMarcaPresenter;

    @Inject
    public MarcaModel(){

    }

    @Override
    public void getMarcas(String tipoVeiculo) {
        final List<Marca> marcaList = new ArrayList<>();
        Observable<List<Marca>> observable = mApiFIPE.getRepositories(tipoVeiculo);
        observable.subscribe(new Observer<List<Marca>>() {
            @Override
            public void onCompleted() {
                mMarcaPresenter.getMarcas(marcaList);
            }

            @Override
            public void onError(Throwable e) {
                mMarcaPresenter.onShowDialog("Erro", "Falha ao carregar lista de marcas");
            }

            @Override
            public void onNext(List<Marca> marcas) {
                marcaList.addAll(marcas);
            }
        });

    }
}

Answer: Deixe o Dagger injetar automaticamente o seu Presenter e Model a partir do grafo de dependências, ou seja, não precisa instancia-los dentro do modulo.
Existe também uma maneira melhor de injetar atividades no Android com a anotação: @ContributesAndroidInjector, irá diminuir bastante códigos boilerplate. Segue um ótimo artigo indicando como faze-lo: https://medium.com/@iammert/new-android-injector-with-dagger-2-part-2-4af05fd783d0
EDIT
Fiz algumas mudanças nas suas classes. Você não deve instanciar seus objetos, e sim fazer a inversão de controle, ou seja, o Dagger irá instancia-los para você.
MarcaModule
@Module
public class MarcaModule{
    ....

    @Provides
    @PerMarca
    Presenter providePresenterMarca(MarcaPresenter presenter){
        return presenter;
    }

    @Provides
    @PerMarca
    Model provideModelMarca(MarcaModel marca){
        return marca;
    }
}

MarcaActivity
public class MarcaActivity extends BaseActivity implements HasActivityInjector, View {
    ....

    @Inject
    AdapterMarca mAdapterMarca;

    ....

    private void initListView(){
        mAdapterMarca.addListMarca(mListMarca);
        listViewMarca.setAdapter(mAdapterMarca);
    }

}

AdapterMarca
public class AdapterMarca extends BaseAdapter {

    private List<Marca> mListMarca;

    @Inject
    Context mContext;

    public AdapterMarca(){
        this.mListMarca = new ArrayList();
    }
    ...
}

Comment: "Deixe o Dagger injetar automaticamente o seu Presenter e Model a partir do grafo de dependências, ou seja, não precisa instancia-los dentro do modulo."

Mas como eu faria isso?
E essa questão de ter Classe A que tem B e B que tem C.
A classe B deve conseguir instanciar @Inject Class C normalmente ou tenho algo em especial para fazer?
Comment: Se B for injetada pelo Dagger e depende de C, então C será injetada também, desde que C possua a anotação `@Inject`.
Comment: Ja tentei de diversas formas e não consigo fazer o model receber um objeto vindo de do Degger com o @Inject.
Sempre da NullPointerException.

O Caique sugeriu acima não instanciar no Modulo e sim deixar o dagger instanciar automaticamenete, mas como faço isso?


Understanding the calls to the cost function in cv.glm in R's boot package?

Question: Looking at the cv.glm function I am trying to understand how its cost function parameter is used.
I think I understand that cost gets called to calculate the "error" for the test set. But it gets called several more times than I have expected. Take a look at the following code using the data sets mentioned in the Introduction to Statistical Learning book.
library(ISLR)
library(boot)
set.seed(1)

nrow(Auto)
# prints: [1] 392

cost <- function(r, pi) {
  print("Calling into costFunction")
  print(sprintf("r lenght: %s", length(r)))
  # print(r)
  print(sprintf("pi lenght: %s", length(pi)))
  # print(pi)
  return(mean((r - pi)^2))
}

glm.fit <- glm(mpg ~ horsepower, data = Auto)
cv.err <- cv.glm(Auto, glm.fit, cost = cost, K = 2)
cv.err$delta

Here I have a cost function that still returns the mean squared error with some debug prints.
The number of datapoints in Auto data is 392. I am doing K-fold cross validation where K is 2.
Running this prints
[1] "Calling into costFunction"
[1] "r lenght: 392"
[1] "pi lenght: 392"
[1] "Calling into costFunction"
[1] "r lenght: 196"
[1] "pi lenght: 196"
[1] "Calling into costFunction"
[1] "r lenght: 392"
[1] "pi lenght: 392"
[1] "Calling into costFunction"
[1] "r lenght: 196"
[1] "pi lenght: 196"
[1] "Calling into costFunction"
[1] "r lenght: 392"
[1] "pi lenght: 392"

With K = 2, the test sets would be 392/2 = 196. So the calls to cost with input arguments with 196 entries make sense. There are two such folds and each having half of the original data (=196 rows) as the test set.
But what are the other calls to cost function with 392 long vectors? Total number of data points is 392.
Answer: The source code of cv.glm shows the call places for the cost function.
The other calls to cost are used to calculate the bias corrected MSE.
In the docs for cv.glm it mentions as:

delta
A vector of length two. The first component is the raw
cross-validation estimate of prediction error. The second component is
the adjusted cross-validation estimate. The adjustment is designed to
compensate for the bias introduced by not using leave-one-out
cross-validation.
Comment: cool. was about to answer the question, but you found it


Função com insert de acordo com um select que retorna uma lista de ID's - Postgresql

Question: Preciso fazer uma trigger after insert que chama uma função que pegue o último registro inserido em certa tabela e insira o ID desse último registro em outra tabela de acordo com um select que retorna vários ID's. EX:
tb_1
.-------------.
|  ID  | NOME |
.-------------.
|   1  |   A  |
|   2  |   B  |
|   3  |   C  | <- Último ID inserido
'------'------'

tb_2
.-------------.
|  ID  | NOME |
|------|------|
|  41  |  AAA |
|  42  |  BBB |
|  43  |  CCC |
|  44  |  AAA |
|  45  |  AAA |
'------'------'

INSERT INTO tb_3 (tb_1_id,tb_2_id)
VALUES (
        (SELECT MAX(ID) FROM tb_1),
        (SELECT ID FROM tb_2 WHERE NOME = 'AAA')
       )

tb_3
.----------.----------.
|  tb_1_id |  tb_2_id |
|----------|----------|
|     3    |    41    |
|     3    |    44    |
|     3    |    45    |
'----------'----------'

Como fazer um insert que faz essa lógica que mostrei? É possível?
As estruturas da trigger e function eu faço depois.
Comment: Não me parece ser possível por trigger pois são duas tabelas
Comment: Você basicamente explicou o comportamento, faz sentido sua lógica pra mim. Tenta fazer, caso tiver algum problema faça uma pergunta do respectivo problema.
Comment: Eu quero saber se é possível fazer um insert nesse tipo, pois o exemplo que mostrei da errado, mas a lógica é essa.
Comment: **Vote hoje! Vote amanhã! Vote sempre! Vote consciente!** O seu voto é muito importante para nossa comunidade, contribua conosco e ajude a tornar a Stack Overflow em Português (SOpt) cada vez maior. Você pode saber mais em: [**Vote cedo, vote frequentemente**](https://pt.meta.stackoverflow.com/questions/159/vote-cedo-vote-frequentemente)
Comment: Você já avaliou o uso da cláusula RETURNING do comando INSERT? Creio que ela possa facilitar seu procedimento.
Answer: O que você quer fazer é inserir esses ids em uma tabela de ligação, mas pelo que entendi essa tab_2 retorna vários ids, então no final das contas o insert fica assim:
INSERT INTO tb_3 (tb_1_id,1)
INSERT INTO tb_3 (tb_1_id,2)
INSERT INTO tb_3 (tb_1_id,3)

Três ids da tb_2 para o mesmo id da db_1.
O que você pode fazer é um FOR que vai percorrer essa tab_2 (SELECT ID FROM tb_2 WHERE NOME = 'AAA'), nesse seu exemplo terão três registros, então é só ir inserindo cada um com seu novo id da tb_2 e o mesmo id da tb_1.
EX:
FOR _table2 in (SELECT ID FROM tb_2 WHERE NOME = 'AAA')

LOOP

   INSERT INTO tb_3 (tb_1_id,tb_2_id) VALUES(SELECT MAX(ID) FROM tb_1,_table2.id)

END LOOP;

Comment: Isso, seria bem um loop mesmo, mas abriu uma luz aqui e percebi que daria pra resolver de um jeito muito simples, hehe. Desde já muito obrigado!
Answer: Achei a solução do jeito mais simples e que já fiz várias vezes. (até agora não caiu a ficha de que entrei nesse mundo de loop só pra isso).
INSERT INTO tb_3 (tb_1_id, tb_2_id) (
     SELECT (SELECT MAX(ID) FROM tb_1) AS tb_1_id, ID AS tb_2_id
       FROM tb_2 WHERE NOME = 'AAA')


Self-closing a  tag

Question: I came across a code where a developer attempted to close an empty table cell like this  instead of 	.
Is  valid? When is it appropriate to close a tag like <tag />? What language does it come from originally?
Comment: Related, possible duplicate (but doesn't address the direct question of 'is `` a valid(void) tag'): https://stackoverflow.com/questions/3558119/are-non-void-self-closing-tags-valid-in-html5
Answer: Non-HTML Compatible XHTML (so not if you want to use a text/html content-type or support IE 8 or older).

If an element permits content (e.g., the div element) but an instance of that element has no content (e.g., an empty section), DO NOT use the "minimized" tag syntax (e.g.,
).

— http://www.w3.org/TR/xhtml-media-types/#C_3
Answer: No,  is not valid HTML. If you check this in the W3C's HTML validator, you get an error:

Self-closing syntax (/>) used on a non-void HTML element. Ignoring the slash and treating as a start tag.

Screenshot:

However, in HTML, for table rows, you can declare opening table rows without closing them (see Is it safe to omit 	 and
 tags? for more info); this is valid:
...

    Lorem Ipsum
    Dolor Sit

...

If I were to add an empty, self-closed td (e.g.  to that table row, it would probably be parsed by browsers like this:
...

    Lorem Ipsum
    Dolor Sit

But this is not guaranteed, and it also may or may not be what you are wanting, so it is dangerous to rely on; you should only self-close valid void tags, a list of which can be found on MDN. For table elements, either use opening tags as shown above or use the much more common opening and closing tags,  and 	, respectively.
Self-closing tags comes from XML/XHTML, as Quentin's answer already discusses.

Self-closing a  tag


Django - can't apply migration

Question: I'm new to django development, I'm working with Mezzanine == 4.2.2 CMS and django == 1.8 .It was working fine before but from past 2 days it's giving me the following error when I apply migrations.
<code>python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: adminactions, raven_compat, staticfiles, boot, filebrowser_safe, djrill, sitemaps, compressor, django_countries, django_extensions, rest_framework, mailchimp, grappelli_safe, thumbnail, localflavor
  Apply all migrations: shop, core, redirects, generic, django_comments, sessions, admin, report_builder, twitter, galleries, swingtime, sites, auth, blog, brochure, contenttypes, conf, forms, cities_light, checkout, pages
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states...Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
    output = self.handle(*args, **options)
  File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 221, in handle
    executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
  File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/db/migrations/executor.py", line 104, in migrate
    state = migration.mutate_state(state, preserve=do_run)
  File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/db/migrations/migration.py", line 83, in mutate_state
    operation.state_forwards(self.app_label, new_state)
  File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 51, in state_forwards
    state.reload_model(app_label, self.model_name_lower)
  File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/db/migrations/state.py", line 97, in reload_model
    related_models = get_related_models_recursive(old_model)
  File "/Users/VinayManeti/Documents/hedgehog_lab_projects/backend/venv/latest_gs/lib/python2.7/site-packages/django/db/migrations/state.py", line 57, in get_related_models_recursive
    rel_app_label, rel_model_name = rel_mod._meta.app_label, rel_mod._meta.model_name
AttributeError: 'NoneType' object has no attribute '_meta'
</code>
Comment: Show us your models.
Comment: I have 160 tables, it's very huge file
Answer: Maybe any of the related model referenced as ForeignKey before, is not exists now.
Make sure all related fields are configured properly.
Comment: Is there anyway to check unreferenced fields?
Comment: I don't know anyway to check unreferenced fields.

Django - can't apply migration


Installing pfsense 2.5.2 ( freebsd 12 ) in KVM

Question: Seems that I am having an issue installing pfsense firewall which is build on freeBSD12 into a qemu/kvm in Ubuntu.
When it starts to boot, prior to the 'Install Box' I get a kernal panic Image of fail
Here are my versions
bridge-utils is already the newest version (1.6-2ubuntu1).
libvirt-clients is already the newest version (6.0.0-0ubuntu8.15).
libvirt-daemon-system is already the newest version (6.0.0-0ubuntu8.15).
qemu-kvm is already the newest version (1:4.2-3ubuntu6.19).
virt-manager is already the newest version (1:2.2.1-3ubuntu2.1).
virtinst is already the newest version (1:2.2.1-3ubuntu2.1).

It seems that there had been a bug in the past where you needed to have the chipset to i440fx, however that is where I am set.
I have tried with both qcow2 and ISO storage as other posts that i have read suggested, but to change to the error. I also have re-downloaded the install pfsense ISO form a different mirror, as well as tried to install just freebsd 12.  I get the same kernel panic.
I am not sure if this is a setting that I am missing in kvm, as I am new to it, or if the version that I am using has issues with freebsd?
As a side note / update, I have been able to install OPNsense which uses a different BSD as I recall.
virt-manager Config XLM
domain type="kvm">
  <name>freebsd12.0</name>
  <uuid>ec3e8b14-bceb-49d9-a4bd-1608af31fc9d</uuid>
  <metadata>
    <libosinfo:libosinfo xmlns:libosinfo="http://libosinfo.org/xmlns/libvirt/domain/1.0">
      <libosinfo:os id="http://freebsd.org/freebsd/12.0"/>
    </libosinfo:libosinfo>
  </metadata>
  <memory unit="KiB">1048576</memory>
  <currentMemory unit="KiB">1048576</currentMemory>
  <vcpu placement="static">1</vcpu>
  <os>
    <type arch="x86_64" machine="pc-i440fx-focal">hvm</type>
    <boot dev="hd"/>
  </os>
  <features>
    <acpi/>
    <apic/>
    <vmport state="off"/>
  </features>
  <cpu mode="host-model" check="partial"/>
  <clock offset="utc">
    <timer name="rtc" tickpolicy="catchup"/>
    <timer name="pit" tickpolicy="delay"/>
    <timer name="hpet" present="no"/>
  </clock>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
  <on_crash>destroy</on_crash>
  <pm>
    <suspend-to-mem enabled="no"/>
    <suspend-to-disk enabled="no"/>
  </pm>
  <devices>
    <emulator>/usr/bin/qemu-system-x86_64</emulator>
    <disk type="file" device="disk">
      <driver name="qemu" type="qcow2"/>
      <source file="/home/jc/Virtual Machines/pfsense.qcow2"/>
      <target dev="vda" bus="virtio"/>
      <address type="pci" domain="0x0000" bus="0x00" slot="0x07" function="0x0"/>
    </disk>
    <disk type="file" device="cdrom">
      <driver name="qemu" type="raw"/>
      <target dev="hda" bus="ide"/>
      <readonly/>
      <address type="drive" controller="0" bus="0" target="0" unit="0"/>
    </disk>
    <controller type="usb" index="0" model="ich9-ehci1">
      <address type="pci" domain="0x0000" bus="0x00" slot="0x05" function="0x7"/>
    </controller>
    <controller type="usb" index="0" model="ich9-uhci1">
      <master startport="0"/>
      <address type="pci" domain="0x0000" bus="0x00" slot="0x05" function="0x0" multifunction="on"/>
    </controller>
    <controller type="usb" index="0" model="ich9-uhci2">
      <master startport="2"/>
      <address type="pci" domain="0x0000" bus="0x00" slot="0x05" function="0x1"/>
    </controller>
    <controller type="usb" index="0" model="ich9-uhci3">
      <master startport="4"/>
      <address type="pci" domain="0x0000" bus="0x00" slot="0x05" function="0x2"/>
    </controller>
    <controller type="pci" index="0" model="pci-root"/>
    <controller type="ide" index="0">
      <address type="pci" domain="0x0000" bus="0x00" slot="0x01" function="0x1"/>
    </controller>
    <controller type="virtio-serial" index="0">
      <address type="pci" domain="0x0000" bus="0x00" slot="0x06" function="0x0"/>
    </controller>
    <interface type="bridge">
      <mac address="52:54:00:55:83:9c"/>
      <source bridge="br1"/>
      <model type="virtio"/>
      <address type="pci" domain="0x0000" bus="0x00" slot="0x03" function="0x0"/>
    </interface>
    <serial type="pty">
      <target type="isa-serial" port="0">
        <model name="isa-serial"/>
      </target>
    </serial>
    <console type="pty">
      <target type="serial" port="0"/>
    </console>
    <channel type="spicevmc">
      <target type="virtio" name="com.redhat.spice.0"/>
      <address type="virtio-serial" controller="0" bus="0" port="1"/>
    </channel>
    <input type="mouse" bus="ps2"/>
    <input type="keyboard" bus="ps2"/>
    <graphics type="spice" autoport="yes">
      <listen type="address"/>
      <image compression="off"/>
    </graphics>
    <sound model="ich6">
      <address type="pci" domain="0x0000" bus="0x00" slot="0x04" function="0x0"/>
    </sound>
    <video>
      <model type="qxl" ram="65536" vram="65536" vgamem="16384" heads="1" primary="yes"/>
      <address type="pci" domain="0x0000" bus="0x00" slot="0x02" function="0x0"/>
    </video>
    <redirdev bus="usb" type="spicevmc">
      <address type="usb" bus="0" port="1"/>
    </redirdev>
    <redirdev bus="usb" type="spicevmc">
      <address type="usb" bus="0" port="2"/>
    </redirdev>
    <memballoon model="virtio">
      <address type="pci" domain="0x0000" bus="0x00" slot="0x08" function="0x0"/>
    </memballoon>
  </devices>
</domain>

Thoughts on what to try are greatly appreciated.
Regards,
Comment: There were quite a few bugs in the past involving freeBSD and KVM. Would you mind trying to install OPNsense?
Comment: I have had success with OPNsense install.  No change to the settings that I tried with pfsense
Comment: Is the panic identical each time - i.e. does the syslogd trigger the trap ?
Comment: The panic seems the same each time, is there a good way to see what triggers? I cant scroll up to see
Comment: Seems or is. That was a simple question.
Comment: Is :), the screen shot results are the same each time.
Comment: Then it's a FreeBSD bug and it should be reported into the FreeBSD bugtracker along with attaching the crashdump.
Comment: But if the backtrace is random each time (even if it's still `fatal trap 12`) then it's not.
Comment: I just tried to reproduce the behavior on Arch and Debian, both work fine. The used versions of libvirt etc. seem pretty outdated.
Comment: @drookie I don't think this is a FreeBSD bug but rather one in KVM or libvirt
Comment: @Lost_Ones would you mind sharing your settings for the VM in virt-manager, preferably the XML?
Comment: I hope that when I go to overview, that has it all.  Added it the original  post
Comment: Just tried to also reproduce it on Ubuntu with the same config. For me it works without a problem. Which version of ubuntu are you using? The KVM related packages seem to be pretty outdated.
Comment: Kubuntu 20.04   VERSION="20.04.3 LTS (Focal Fossa)"     Installed via sudo apt
Answer: It seems you are using a very old version of libvirt.
You have the following options:
use OPNsense instead
OPNsense is a fork of m0n0wall as PfSense is. It has a similar set of features, but sometimes it feels a bit more complicated to do the same things.
OPNSense builds on top of HardenedBSD, with overall better security and addresses various security issues of PfSense, like running the webinterface as root.
I switched from PfSense to OPNsense about half a year ago and so far haven't had any problems with it.
install newer version of Kubuntu
You could simply go with a non-LTS version of Kubuntu.
wait for Kubuntu 22.04 LTS
Ubuntu 22.04 LTS should be released on 21 April 2022.
Upgrading is quite easy and gives you access to newer packages.
If you can wait that long and want to stay on a LTS version, this would be the preferred option.
find a PPA with newer versions
The hardest part would be to find the PPA, adding it is quite easy.
build it yourself
Add the deb-src of a newer version of ubuntu to your sources.list and get the necessary packages, or get a tarball for each of them and compile them according to their documentation.
libvirt for example is compiled via meson.
Comment: Outstanding information.  I have been using OPNsense for a few days now, and I found it rather straight forward to setup.    I appreciate the attention and I will digest what route that I will go.


get hidden nested data value from datatable server side

Question: i have json data like this :
[{"id_asset":"4b5c2a52-a4fb-44f3-8b15-be369878ff1e","id_safety":{"id_safety":"64fa5f8b-44c2-4906-9bf8-27f826e026a5","referensi":"default","keterangan":"default","safety_procedure":"default","alat_safety":"default"},"asset_name":"roll","serial":"r129","asset_code":"C1-R1","parent_code":"C1-R11","purchase_date":"2020-03-03","grup":"bahan bakar","model":"CR123","location":"bengkel","asset_tag":"C1222","warranty":12.0,"safety_referensi":"default","vendor":"daeyang","consume":0,"stok":0,"end_balance":0,"price":1111.0},{"id_asset":"5ef6c6f2-9cfd-475a-8d21-5ade18d2fd20","id_safety":null,"asset_name":"C01829XX","serial":"C1-R11","asset_code":"xxx","parent_code":"","purchase_date":"2020-02-24","grup":"bahan baku sipil","model":"bengkel","location":"C1111","asset_tag":"xx","warranty":0.0,"safety_referensi":"daeyang","vendor":"sss","consume":0,"stok":0,"end_balance":0,"price":1111111.0}]

and i want get value from id_safety, (example: id_safety:64fa5f8b-44c2-4906-9bf8-27f826e026a5)  but when i click datatable always return undifined
this is js for select value :
var dat = $('#tabelass').DataTable().row('.selected').data();
       console.log(dat );
       alert("id_asset:" + dat ['id_asset'] + "\id_safety:" + dat ['id_safety.id_safety']);

Answer: You have a small issue in here. Just replace this in your code:
dat ['id_safety.id_safety']

with this:
dat['id_safety']['id_safety']

as dat['id_safety'] retuns the inner object in this format:
{id_safety: "64fa5f8b-44c2-4906-9bf8-27f826e026a5", ... }

and in order to access the id_safety property in this object, you will need to do like:
dat['id_safety']['id_safety']
// returns "64fa5f8b-44c2-4906-9bf8-27f826e026a5"


PHP access cifs share

Question: I need to move files through windows shares by php pages.
In a linux context I will use samba client to mount the share to a local path, however i can not understand how to do this in a windows webserver.
The webserver is running as "SYSTEM" user and I can not specify a valid share user.
Answer: In Windows, just use the following synthax in the php command "copy":
copy("\\server_source\path", "\\server_dest\path");

You need permissions to copy files (check the configuration of the webserver you're using, the user who's running the webserver must be included with r/w permissions).
If you haven't permissions, run a
system("net use drive1: \\server_source\path password /USER:firstname.lastname@example.com");
system("net use drive2: \\server_dest\path password /USER:email@example.com");

then:
copy("drive1:\path", "drive2:\path");

You must know which drive letter from Z: down to E: are available on your server.
Comment: Is "net use" global for all account and also for webserver?
Comment: This don't work, I can access drive1:\\ and driver2:\\ but copy fails.
Comment: Which version of Windows you're using?
Comment: Windows Server2012
Comment: Can you post the exact error?
Comment: Warning: copy(Z:\TEST_1.MPF): failed to open stream: No such file or directory in D:\www\test.php on line 3
The code is: copy("Z:\\TEST_1.MPF","c:\\test.txt");
I tried in a cmd: copy Z:\TEST_1.MPF c:\test.txt and this works!

I think this is because SYSTEM user of apache service can not access shares...
Comment: From [http://httpd.apache.org/docs/2.2/platform/windows.html](http://httpd.apache.org/docs/2.2/platform/windows.html):  "By default, all Apache services are registered to run as the system user (the LocalSystem account). The LocalSystem account has no privileges to your network via any Windows-secured mechanism, including the file system, named pipes, DCOM, or secure RPC. It has, however, wide privileges locally."  So, go to that page and follow instructions on how to run apache as a network-enabled account.
Comment: I followed this instrunctions, I made a new user with log as service privileges and now apache is running as that account... however copy still doesn't work.

PHP access cifs share


Hardest question IMO I had ever seen!

Question: Let $\alpha$ and $\beta$ and $\gamma$ be 3 real numbers.
Prove that there exist only one polynomial $P(x)$ of the second degree such that $$\begin{cases}P(1)=\alpha \\
P(2)=\beta \\
P(3)=\gamma\end{cases}$$
I don't even know how to start?? Perhaps this is a new type of question to me and so if I know how to solve this one I will be able to solve similar questions!
Also this is second part of the question maybe that would help: Determine $P(x)$ in every case: $$\alpha=\beta=\gamma=2500\text{ and } \alpha=3;\beta=6;\gamma=9$$
Thanks!!
Comment: http://en.wikipedia.org/wiki/Lagrange_polynomial
Comment: $p(x)=ax^2+bx+c$, so we get a system of equations $a+b+c=\alpha$, $4a+2b+c=\beta$ and $9a+3b+c=\gamma$. Solving this we get $a=\gamma-\alpha$ and so on... If I understood the problem correctly.
Comment: @VosPost: This one comes to mind (but mentioning it is rather pointless for this question). A sphere and an interior point $P$ (not the center) is given. Determine the locus of the points $Q$ with the following property: $P$ and $Q$ are diagonally opposite points of a rectangular block, of which the three vertices connected to $P$ by an edge lie on the sphere. IMO 1978 if I recall correctly.
Answer: The statement is false. For $\alpha=1$, $\beta=2$, $\gamma=3$ there is only one polynomial of degree at most $2$ that satifies the evaluations, namely $P(x)=x$; it is not of degree$~2$. There are many similar counterexamples.
Answer: Hints:
Solve the system
$$\begin{align*}a+b+c&=\alpha\\
4a+2b+c&=\beta\\
9a+3b+c&=\gamma\end{align*}$$
and show the polynomial $\;p(x)=ax^2+bx+c\;$ fulfills the conditions. And about uniqueness: suppose there's another polynomial $\;g(x)\;$ that fulfills the same conditions. What can you say about the roots of $\;h(x):=f(x)-g(x)\;$ ?
Comment: Why should there be any other discussion about uniqueness? Isn't a second degree polynomial uniquely specified by its coefficients?
Comment: " there's another polynomial g(x) that fulfills the same conditions. What can you say about the roots of h(x):=f(x)−g(x) ?" Euuuuuuuuuuuuuuh.... No idea....
Comment: And how can I show that the polynomial p(x)=ax2+bx+c fulfills the conditions.
Comment: And how do you intend to show that the given conditions uniquely specify the coefficients of quadratic polynomial, @hhsaffar ?
Answer: assume the quadratic equation
$$ ax^2+bx+c= P(x)$$
when you substitute the values of $x$ into the function. you get $3$ equations in $a,b$ and $c$ which has unique solutions.
Comment: This simply restates what needs to be proved, without actually proving it.
Comment: rather than giving a readymade solution i prefer such hints so that the person who asks the question can put some effort himself to get it. and also i dont this is a restating of the question.
Answer: Assume that there are 2 polynomials $p(x)$ and $g(x)$
Then $q(x)=p(x)-g(x)$ is of degree at most $2$ and the equation $q(x)=0$ has $3$ solutions
the numbers $1,2,3$ which is a contradiction.
So, $g(x)=0$ which means $p(x)=g(x)$

Hardest question IMO I had ever seen!


How can I view the source of the Android Support Library?

Question: I'm having issues viewing any of the Java source code for all of the Android Support Library. This encompasses classes like Fragment, ViewPager, etc. I've added dependencies in my gradle build file, and can view these dependencies in the Project Structure dialog:
Gradle
Project Structure
When I try to view the source code, I only have the option of viewing the decompiled class file (example). I've run into this issue several times over the course of the past several years, but there have been a decent number of changes to Android Studio (currently using 3.3), so the ways I used in the past and many of the ways I've seen on StackOverflow seem outdated.
Approaches that I've tried:
-The Download Sources option. Nothing happens when clicking on this.
-The Choose Sources... option. Not really sure where to choose from.
-Adding an explicit call to ask idea to download sources and javadocs. Read this in a few StackOverflow posts, but it didn't change anything on my end.
What I found but haven't tried:
-Grabbing the .jar from the .aar and putting it in libs. This feels like a hacky workaround, especially when all of Google documentation suggests to add the dependency in the gradle build file.
Definitely appreciate any help, because I'd really rather not just look up the code in my browser. Thanks so much in advance!
Answer: You can find the source code of the Framework here. For instance the link to the Fragment is this one. If you are looking for a specific class - let's say Fragment - its easiest most of the time to just google "fragment.java android" or something similar and you will find it. If it does not help just use the first link, but keep in mind that it might be difficult to find out in which subfolder the file you are looking for is.
Comment: Right, I know this is an option, but I'd like to view/browse the code in the IDE rather than in a browser


Open external links in new tab

Question: I am using the Bootstrap theme for Drupal 7. I want to open all external links in new tab. For this there are some contribute modules available. But I want to do it in programmatically. When I searched I found this but it is not working for me. Is there any other hook to do this?
This is the code I am using.
function mytheme_links($variables) {
  dpm($variables);
  $variables['options']['attributes']['target'] = '_blank';
}

Comment: Do you want all links to be opened in a new tab or just only the external links? The code you wrote doesn't even check if a link is internal or external.
Comment: Secondly, why don't you use the module?
Comment: Only external links to be open in new tab@ЕлинЙ.
Comment: Then you should find a way to distinguish the external links in a menu from the internal ones. If you use the module [External Links](https://drupal.org/project/extlink) you don't need to find your own way. Why don't you want to use that module?
Answer: Try this js based code;
Drupal.behaviors.externalMenu = function(context, settings) {
    $('#your_menu_id').attr('target', '_blank');
};

Comment: I want all external links to open in new tab. Also can we do it in drupal way using preprocess functions@Adi
Comment: This js based code is also Drupal way. Why do you think it is not?
Answer: Drupal doesn't pass any $variables['options'] to that theme function. That is clear from the documentation for theme_links().
Since you just want to add an attribute, and not alter the output of a theme function, you just need to implement a theme preprocess function.
function mytheme_preprocess_links(&$variables) {
  $links = $variables['links'];
  if (count($links) > 0) {
    foreach ($links as $key => $link) {
      if (url_is_external($link['href'])) {
        $links[$key]['attributes']['target'] = '_blank';
      }
    }
    $variables['links'] = $links;
  }
}

Comment: This answer, too, doesn't distinguish the links if they're external or not.
Comment: It is not working @kiamlaluno
Comment: @Vamsi I am sorry: I missed the part about external links. I updated my answer.
Comment: @kiamlaluno still link opens in same tab
Comment: @Vamsi Right... Because `$variables['links']` was not updated.
Comment: @kiamlaluno I have pasted the above code in template.php and changed mytheme to my theme name and cleared cache. Still it is not opening in new tab
Answer: Try url_is_external() function to determine if link is internal or external.
Your code could be something like below:
function mytheme_links($variables) {
  $link = $variables['options'];
  if (url_is_external($link)) {
    $variables['options']['attributes']['target'] = '_blank';
  }
}

Comment: it's not working
Comment: Drupal 7 doesn't pass any `$variables['options']`.
Answer: I have found another solution which works as expected. This is the code I have used
      $('a').not('[href*="mailto:"]').each(function () {
        var isInternalLink = new RegExp('/' + window.location.host + '/');
        if ( ! isInternalLink.test(this.href) ) {
          $(this).attr('target', '_blank');
        }
      });

which opens the external links in new tab. Place the code in your custom js file

Open external links in new tab


How to compile Opencv with Visual Studio Code?

Question: I installed opencv3 with brew. I tried many times to set pkg-config but I could not succeed to compile. I searched the way on internet but I could not find out.
The task is below:
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "g++",
    "isShellCommand": true,
    "showOutput": "always",
    "suppressTaskName": true,
    "tasks": [
        {
            "taskName": "build",
            "isBuildCommand": true,
            "args": [
                `pkg-config --libs opencv --cflags opencv`,
                "-o",
                "vsc",
                "${workspaceRoot}/main.cpp",
                "-g" // Debug
            ],
            "showOutput": "always"
        }
    ]
}

My pkg-config are like below:
pkg-config --libs
$ pkg-config --libs opencv
-L/usr/local/Cellar/opencv3/3.1.0_3/lib -lopencv_shape -lopencv_stitching -lopencv_objdetect -lopencv_superres -lopencv_videostab -lippicv -lopencv_calib3d -lopencv_features2d -lopencv_highgui -lopencv_videoio -lopencv_imgcodecs -lopencv_video -lopencv_photo -lopencv_ml -lopencv_imgproc -lopencv_flann -lopencv_core

pkg-config --cflags
$ pkg-config --cflags opencv
-I/usr/local/Cellar/opencv3/3.1.0_3/include/opencv -I/usr/local/Cellar/opencv3/3.1.0_3/include

Do you know how to compile opencv with Visual Studio Code??
Answer: OS: Ubuntu 16.04, OpenCV version: 3.2.0, program filename: videocapture_starter.cpp, and output filename: videocapture_starter
To build I used the following task.json file
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "g++",
    "isShellCommand": true,
    "showOutput": "always",
    "args": ["-g", "videocapture_starter.cpp", "-o", "videocapture_starter", "-I/usr/local/include/opencv", "-I/usr/local/include","-I/usr/include", "-L/usr/local/lib",
     "-lopencv_shape", "-lopencv_stitching", "-lopencv_objdetect", "-lopencv_superres", "-lopencv_videostab", "-lopencv_calib3d",
     "-lopencv_features2d", "-lopencv_highgui", "-lopencv_videoio", "-lopencv_imgcodecs", "-lopencv_video", "-lopencv_photo",
     "-lopencv_ml", "-lopencv_imgproc", "-lopencv_flann", "-lopencv_core"]
}

To debug the program I used the following launch.json file
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "C++ Launch",
      "type": "cppdbg",
      "request": "launch",
      "program": "${workspaceRoot}/videocapture_starter",
      "args": ["0"],
      "stopAtEntry": false,
      "cwd": "${workspaceRoot}",
      "environment": [],
      "externalConsole": true,
      "linux": {
        "MIMode": "gdb",
        "includePath": ["/usr/include", "/usr/local/include/opencv", "/usr/local/include"],
        "setupCommands": [
          {
            "description": "Enable pretty-printing for gdb",
            "text": "-enable-pretty-printing",
            "ignoreFailures": true
          }]
      }
    },
    {
      "name": "C++ Attach",
      "type": "cppdbg",
      "request": "attach",
      "program": "${workspaceRoot}/a.out",
      "processId": "${command:pickProcess}",
      "linux":
        {
        "MIMode": "gdb",
        "setupCommands": [
          {
            "description": "Enable pretty-printing for gdb",
            "text": "-enable-pretty-printing",
            "ignoreFailures": true
          }]
        }
    }
  ]
}

Comment: showOutput is deprecated. It will ask you to use "presentation" and inside "reveal" should be set to "always".


What is the intuitive notion of an isotopy?

Question: I'm studying introduction to topology. The book is trying to give an intuitive notion of an homeomorphism and isotopy. As I understand it an homeomorphism is the continous function ( with continous inverse ) that represents the "deformation" of one topological space ( such as a bottle ) into another ( an squeezed bottle ). What is an isotopy then? Thank you in advance.
Answer: Think about how you would untie a knot $K$. Starting at time $t=0$ and ending at time $t=1$, you continuously move pieces of it around inside 3-dimensional space, and do so in a non-impossible way (e.g. the knot can't move through itself).
Now the knot remains "the same" at each moment in time - "$K_{t_1}$" and "$K_{t_2}$" are homeomorphic for any times $t_1, t_2$. But this isn't really the main feature of "untying a knot" - rather, we care about how it moves through the ambient space.
This is the idea behind isotopy. We think of $K$ as an abstract space, and $K_0$ and $K_1$ as the images of two separate embeddings of $K$ into $\mathbb{R}^3$; and the fact that $K_0$ can be deformed into $K_1$ in a "nice" way means that there is an isotopy between these two embeddings (namely the process of deforming the knot).
(EDIT: actually, this is misleading - unknotting knots is a really nice process, and is better thought of as an example of ambient isotopy. General isotopies allow you to do weirder (but still reasonably "tame") things (see Andreas' comment below).)

There are then many special kinds of isotopy - ambient isotopy, smooth isotopy (in the context of differential geometry), etc. - but this should give the general picture.
Comment: Concerning knots and the importance of ambient isotopy, see my comment on the answer from arctic tern.
Comment: @AndreasBlass Good point, I didn't mean to be misleading; fixed!
Answer: While a homeomorphism 'connects' two topological spaces, an isotopy 'connects' two embeddings (maps) between topological spaces, so they concern different type of objects.


Why don't we see jazz music played on the church organ?

Question: I'm just curious as to what about let's say a saxophone makes it very well suited to jazz music and what about the church organ makes it unsuitable for jazz music.
Is there something innate to the character of those instruments that leads them to be played in certain styles or is Jazz church organ just a style waiting to be created by some young whippersnapper?
Comment: Because tritone is illegal in church...
Comment: I think this question needs some substantiation - how do you know that about the organ? See: [**_Bethel Gospel Assembly, New York_**](https://www.youtube.com/watch?v=YEy9OU6hbTs) - That's an organ in the back on the right side. OK - it's not 'modern jazz', but....
Comment: Example of a jazz artist who used a church organ: https://en.wikipedia.org/wiki/Fats_Waller
Comment: Check out **Above the Clouds** by Mark Ramsden (saxophone) and Steve Lodder (pipe organ). It's on spotify. Mark Ramsden played sax on the Tom Robinson song War Baby. His playing is gorgeous.
Answer: There is so much jazz music written for pipe organ it'll make your head spin. (Just last month I played a nice toccata on O when the saints for my congregation.) In general, at least some practitioners of most religions, and certainly of most Christian denominations, embrace almost any musical style there is.
The reason you don't hear it more often is the same reason as for many other styles: location, location, location! Pipe organs are found almost exclusively in churches and concert halls, while jazz is more often played in clubs and bars.
Comment: Sure, they almost always do this with new things. In fact, the Christian church also called "blasphemy!" at the first *pipe organs*! But within a generation it had become the accepted way to make music in churches.
Comment: Depends which denominations, but I guarantee when Jazz started back then over 90% of churchs would of called 'blasphemy'!
Comment: @KilianFoth church of christ denominations would generally STILL call pipe organs blasphemy. A Capella is the only acceptable worship for a lot of em.
Answer: You are aware that the Hammond organ was created as a church organ?  It became one of the seminal instruments for jazz, with the main reasons being portability (well, compared to a pipe organ that is) and affordability (well, again compared to a pipe organ).  The Leslie rotary speakers helped setting its sound off from congregational use.  It took a number of decades before Hammond accepted them as a legit extension of the organ: he changed the organ connectors several times in order to stop the use of Leslie speakers.
The previous compromise, namely a theater organ, was still rather immobile and expensive and many were scrapped eventually when silent film died.
Since Hammond organs were designed as church organs, it is probably fair to say that price and venue were the main impediment for pipe organs as a mainstream jazz instrument.  After all, jazz was the music of the devil, so practice and performance in a church would have been somewhat tricky.
Answer: It does happen occasionally, but it's not common. One example off the top of my head is Barbara Dennerlein's numerous pipe organ albums. But it's not common for exactly the same reasons as why, for example, rock typically features guitars. Each genre of music has its own typical instrument lineup, and while some people will experiment with other instruments most people will stick to what's standard.
Answer: "Church" organs are basically permanently installed in the building and can't be moved around to church socials in the basement (which is why the Hammond was created for the church), or to honkytonks, juke joints or other clubs, or recording studios (which is where jazz is played).
Answer: Barbara Dennerlein does it on a regular basis; about 50% of her concerts are pipe organ concerts.
One of the main reasons you seldom hear jazz on pipe organs: Most jazz organists don't have the sufficient bass pedal technique. And the bass pedals are a major part of pipe organs.
Answer: Any organ in a church would be a "church organ" right? Unless you specifically mean a pipe organ.
Of course organs are used in jazz: Jimmy Smith for example. Wild Bill Davis is another.
Do the old giant theater organs not count? Certainly jazz was played on those organs.
If you mean something like "why isn't jazz played on organs in a church", the obvious answer is churches already have music for services and it isn't jazz.
Now "what is jazz?" needs to be unpacked.
If you consider certain blues or gospel styles to be essentially forms of jazz, but with different lyrical content, then you have jazz in church. Then question the circles back around to: does the church have an organ?
I'm reminded of a Pentecostal family I was friends with in high school who ran a small church. The eldest song played jazzy gospel keyboard. They had organs in the house and in the church. There wasn't much difference in his playing in the church or in the house, although his playing was probably funkier in the house and more subdued in church. His playing was totally ad lib. I think it fair to say his style was jazz.
Just like European "classical" music had a secular/sacred dichotomy, so does African-American music. I read a very good book that discusses the topic: Murray, Stomping the Blues. The chapter The Blue Devils and the Holy Ghost is the main discussion. Don't dismiss the "blues" in the title, the book covers Ellington, Basie, Armstrong, etc. The book broadly makes the point that the only difference between secular/sacred, jazz/gospel, is the venue.
I think the answer is if you go to a church with the right musical tradition, and that church happens to have an organ, you will hear jazz on a church organ.
There may not be a lot of churches like that compared to other churches, or they may not be in your social circle.
Comment: reason for the downvote?
Answer: Two Reasons that I'd suggest:
Location, Context, Cost: Where are church organs? In churches... jazz is commonly a rejected genre preference by churches that own church organs. Remember that is today, just ponder on the rejection jazz would of received from churches in the era in which jazz originated. Clearly the church organ wasn't off to a good start in the culture of jazz. Many of the instruments in main stream jazz aren't that all expensive in the time of early jazz and back then it was a source of income for many  families. So there would always be a neighbour or household in the street with a piano  or other affordable instruments (guitar and woodwinds). Many of the homes would contain mini church organs too, but who wants to lunk that thing around gig to gig when you're trying to make an income?
Sound: Just like any genre, the culture of a jazz defined its basic 'what's allowed' instruments many years ago, most of us still stick to today. In fact, Google's definition of jazz literally contains those main stream instruments that were defined in its making. You'll notice that all the instruments that are mentioned all share a common theme, they're mellow instruments or can be played that way. Since the church organ is reliant on great amounts of air pressure, being mellow is simply not an option. The church organ would simply overpower a jazz band. Therefore, a church organ would simply throw off main stream jazz.
Overall, the reason why the church organ isn't commonly seen in jazz is because the instrument was impractical in era in which jazz was defined. Think of rock'n'roll, it was defined by electric guitars, drums and some crazy singing, why don't we add bag-pipes to rock'n'roll? The same goes with church organs and jazz, mainstream musical culture. However, as technology progressed having a church organ can now be as accessible as clicking a button on your keyboard. Since that, the organ occasionally makes an appearance in jazz, usually with the rotary effect. See! But still not that common because of the genre's culture.
Comment: good post, the last para made me think of this rock'n'roll song, you may find it interesting. https://www.youtube.com/watch?v=-sUXMzkh-jI
Comment: @ToddWilcox - the answer I heard was 'A start.'
Comment: The definition of a **gentleman**: *one who owns bagpipes, but doesn't play them.*
Comment: A piano is very far from being a cheap instrument to say the least.
Comment: The rotary effect predates the organ being available as "a click on the keyboard" by several decades.  Also, the statement "Since the church organ is reliant on great amounts of air pressure, being mellow is simply not an option" is utterly false.
Comment: Hahaha. Damn, I was hoping there wasn't a bag pipe, glad it's not too high in the mix.
Comment: What do you call a set of bagpipes at the bottom of the sea...?
Comment: @Tim A tragedy in need of salvage and restoration.
Comment: @jazzboy https://www.youtube.com/watch?v=b01wTOPOZT4 https://www.youtube.com/watch?v=iijKLHCQw5o
Comment: Didn't Roy Wood have a christmas song with bagpipes?


phase portrait in dynamics systems

Question: Write the system
$x'=-y-xy$
$y'=x+x^2 $
in polar coordinates, use
$rr'=xx'+yy'$
$r^2\theta'=xy'-yx'$
Then for above example, have
$r'=0$ and $\theta'=1+x>0$, for $x>-1$.
$r(t)$ is constante and $\theta(t)$ increases without bound, when $t\to \infty$.
We have the point $(0.0)$ and the straight $x=-1$ of equilibrium points.
How can I sketch the phase portrait for this system? I understood that in a neighborhood of the origin has a center, but I am in doubt how the phase portrait looks for different solution curves. Any site where I can plot this system?
Answer: Hint.
Making
$$
\cases{
x \dot x = -x y-x^2 y\\
y \dot y = x y + x^2 y
}
$$
after addition we have
$$
\frac 12 \frac{d}{dt}(x^2+y^2) = 0\Rightarrow x^2+y^2= C
$$
are the orbits. Follows a plot showing the stream plot in light blue and the orbit $x^2+y^2=0.5$ in red.

NOTE
This stream plot has a line $(x = -1)$ with null flux. Thus for $r \lt 1$ the orbits are given by
$$
x^2+y^2 = r^2
$$
while for $r \gt 1$ we have the orbits composed by two circle segments. For example, for $r = 1+\delta,\ \ \delta > 0$ we have
$$
(1+\delta)(\cos\alpha,\sin\alpha),\ \ \ \text{for}\ \ \ \arctan(-1,-\delta(\delta+2))\le \alpha\le \arctan(-1,\delta(\delta+2))
$$
and
$$
(1+\delta)(\cos(-\alpha),\sin(-\alpha)),\ \ \ \text{for}\ \ \ \arctan(-1,\delta(\delta+2))\le \alpha\le \arctan(-1,-\delta(\delta+2))
$$
Comment: How are the orbits along the line x=1?
Comment: @Toy Please. See attached note.
Comment: Thank you very much!! But I'm still in doubt in plotting with respect to the curves of the portrait for x<-1. Can you plot that same drawing with a longer interval? Or would it be the continuity of this but with contrary orientation to x<-1?
Comment: Along the $y=0$ axis, the flow is characterized by a vector which is $(0,x(x+1))$ and obviously for $-1 < x < 0$ this vector has downwards orientation and for $x < -1, x > 0$ it has upwards orientation.
Comment: Yeah, as I had thought!! Thank's.
Comment: @Cesareo, what did you use to plot this?
Comment: I used MATHEMATICA.

phase portrait in dynamics systems


Usando o select para abrir iframe

Question: Tenho um código e quero que ele abra um caminho no iframe quando eu clico em um option do select. Consegui fazer isso, porém para mudar a opção para que ele abra outra coisa no iframe eu tenho que atualizar a página. Se eu clicar em um e depois quiser mudar para outro não acontece.
Vou colar o código para vocês darem uma olhada:
<form>
    <select name="Exames" onChange="abrir.location = options[selectedIndex].value">
        <option label="Selecione sua opção" value="0"></option>
        <option value="https://www.youtube.com/?gl=BR&hl=pt">opção1</option>
        <option value="https://www.google.com.br/">opção2</option>
    </select>
</form>

Comment: Você está verificando se de fato o src do iframe recebe o value quando tenta a segunda vez?
Answer: Caso queira utilizar jquery atribua um id ao seu select
$("#Exames").change(function(){
  var url = $(this).val();
  $("#abrir").attr("src",url);
});

Caso queira javascript puro mude para isso
onChange="document.getElementById('abrir').src = this.Exames[this.selectedIndex].value

Answer: Você pode fazer com Jquery:
$('select').on('change',function(){
   var src = $(this).find('option:selected').val();
   $('#abrir').attr('src',src);
});

Atenção: Alguns sites enviam "X-Frame-Options: SAMEORIGIN" como cabeçalho de resposta, isto evita que o navegador exiba iframes que não estão hospedados no mesmo domínio que a página pai, no caso o Youtube e o Google, que você colocou no select, não abrirão:
Exemplo

Usando o select para abrir iframe


Linux Startup Script + add one command

Question: I need one command line to run at startup. I've tested the command (it re-assosiates an Amazon IP to a Linux Server) and the command run successfully.
Just need to know the best method to execute this on server reboot? The server is RedHat and I've read a bit about /etc/init.d but still unsure.
command is:
<code>ec2-associate-address -v -i i-xxx xxx.xxx.xxx.xxx --region ap-southeast-1 -O key -W secret
</code>
Comment: possible duplicate of [Running Script on EC2 Boot](http://serverfault.com/questions/301918/running-script-on-ec2-boot)
Answer: Make sure the script file has exectable flag
<code>  chmod filename.sh +x
</code>
I would recommend putting it in /etc/rc.local.  Also, make sure there is a
<code>  &
</code>
at the end of the line of the script so that it runs in the background and doesn't stop other things from running.

Linux Startup Script + add one command