Parsing json file in hive

Question: I am trying to load the json file in hive.Below is sample json file.
{"Result":[
{"Col1":"Key1","Col2":"email@example.com","Col3":"7"},
{"Col1":"Key2","Col2":"email@example.com","Col3":"7"},
{"Col1":"Key3","Col2":"firstname.lastname@example.com","Col3":"7"},
{"Col1":"Key4","Col2":"firstname.lastname@example.com","Col3":"7"}
]}

I have tried below create statement in hive.
create table if not exists sample_json (A Array<struct<"Col1":String,"Col2":string,"Col3":string>>) ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe' LOCATION '/a/b/c'

I am not able to retrieve the each columns data from table.I have tried to explode the array but it returns only 1st record .Can anyone please suggest what is wrong with it?
Answer:
Create

CREATE EXTERNAL TABLE testJson (
      Result ARRAY <struct<Col1:String ,
                           Col2 : string ,
                           Col3 : string > >)
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
LOCATION 's3n://temp_db.db/testjsonstring';

Query

SELECT
        t.col1
        ,t.col2
        ,t.col3
    FROM
        testJson LATERAL VIEW explode (result) r AS t LIMIT 100

Result

Col1    Col2          Col3
Key1    firstname.lastname@example.com   7
Key2    email@example.com   7
Key3    email@example.com   7
Key4    firstname.lastname@example.com   7

Comment: Thanks @rbyndoor it worked after writting seperate load inpath statement.

Parsing json file in hive


What are the pros and cons of applying pointwise mutual information on a word cooccurrence matrix before SVD?

Question: One way to generate word embeddings is as follows (mirror):

Get a corpora, e.g. "I enjoy flying. I like NLP. I like deep learning."
Build the word cooccurrence matrix from it:

Perform SVD on $X$, and keep the first $k$ columns of U.

Each row of the submatrix $U_{1:|V|,1:k}$ will be the word embedding of the word that the row represents (row 1 = "I", row 2 = "like", …).
Between steps 2 and 3, pointwise mutual information is sometimes applied (e.g. A. Herbelot and E.M. Vecchi. 2015. Building a shared world: Mapping distributional to model-theoretic semantic spaces. In Proceedings of the 2015 Conference on Empirical Methods in Natural Language Processing. Lisbon, Portugal.).
What are the pros and cons of applying pointwise mutual information on a word cooccurrence matrix before SVD?
Answer: according to Dan Jurafsky and James H. Martin book:
"It turns out, however, that simple frequency isn't
the best measure of association between words. One problem is that raw frequency
is very skewed and not very discriminative. If we want to know what kinds of
contexts are shared by apricot and pineapple but not by digital and information,
we're not going to get good discrimination from words like the, it, or they, which
occur frequently with all sorts of words and aren't informative about any particular
word."
sometimes we replace this raw frequency with positive pointwise mutual information:
$$\text{PPMI}(w,c) = \max{\left(\log_{2}{\frac{P(w,c)}{P(w)P(c)}},0\right)}$$
PMI on its own shows how much it's possible to observe a word w with a context word C compare to observing them independently. In PPMI we only keep positive values of PMI. Let's think about when PMI is + or - and why we only keep negative ones:
What    does    positive    PMI mean?

$\frac{P(w,c)}{(P(w)P(c))} > 1$
$P(w,c) > (P(w)P(c))$
it happens when $w$ and $c$ occur mutually more than individually
like kick and ball. We'd like to keep these!

What    does    negative    PMI mean?

$\frac{P(w,c)}{(P(w)P(c))} < 1$
$P(w,c) < (P(w)P(c))$
it means both of $w$ and $c$ or one of them tend to occur individually! It might indicate unreliable stats due to limited data otherwise it shows uninformative co-occurrences e.g., 'the' and 'ball'. ('the' occurs with most of the words too.)

PMI or particularly PPMI helps us to catch such situations with informative co-occurrence.


Discord.py deleting every channel in a server

Question: im working on a building discord bot in py and im wondering how to delete every channel. Someone help?
Comment: What packages are you using, there are several wrappers out there and what have you tried so far? You should at least give it a go before posting a question :)
Answer: Don't abuse this.
@bot.command()
async def delchannels(ctx):
    for c in ctx.guild.channels: # iterating through each guild channel
        await c.delete()

You can also vary this specifically for text channels or voice channels using the links from the references.
Note that you can also use a try/except if you wish to pass the channels that the bot doesn't have permissions to delete.
Consider this less destructive command:
@bot.command()
async def delchannel(ctx, channel: discord.TextChannel):
    await channel.delete()

And alter the argument type for specific channel types (VoiceChannel, CategoryChannel).

References:

Guild.channels
Guild.voice_channels
Guild.text_channels
GuildChannel.delete()


Array with List as Element

Question: I am currently making a Library simulation program where the Index of the array is the BookID of books available.
What I want to do is assign a linked-list / clist to every Index of the array so I can store which borrowerID has loaned out specific books.
I have all of the CList library files and to create a CList I can type the following code.
clist *xs;
xs = new_clist();

My array is currently
borrower[1000];

For each index I want to add create a new_clist().
Answer: You can do the following:
clist* borrower[1000];
int i;
for(i = 0; i<1000; i++){
    borrower[i] = new_clist();
}

Comment: Thank you so much! I'm really trying to get my head around pointers. Pointers seem to be my down point at the moment and I can't seem to visualise them very well.
Comment: You're welcome. Check http://www.cplusplus.com/doc/tutorial/pointers/ for additional information.

Array with List as Element


Multiple rendering causing a ul more

Question: I had following code in template.php this is in function bartik_process_page(&$variables)
 $main_menu_tree = menu_tree_all_data('main-menu');
 $variables['main_menu_expanded'] = menu_tree_output($main_menu_tree);

and in page.tpl.php
<?php if ($main_menu): ?>

                        <?php print render($main_menu_expanded); ?>

        <?php endif; ?>
                          <?php if ($main_menu): ?>

                        <?php print render($main_menu_expanded); ?>

        <?php endif; ?>
                            <?php if ($main_menu): ?>

                        <?php print render($main_menu_expanded); ?>

        <?php endif; ?>

and output it is like this in bartik
1

Home

2. Now u can see i m getting
 extra

Home

Any idea how can i stop it
Comment: Why do you need 3 IF STATEMENT in page.tpl.php with the same condition. Because it is repeated 3 times so the menu will be generated 3 times.
Answer: I have found the answer of it since in render variables are passed by reference https://api.drupal.org/api/drupal/includes!common.inc/function/render/7
so i was passing $main_menu_expanded multiple times in render which was culprit.
Fix is
$variables['main_menu_expanded'] = render(menu_tree_output($main_menu_tree));
<?php if ($main_menu): ?>

                        <?php print ($main_menu_expanded); ?>

<?php endif; ?>

<?php if ($main_menu): ?>

                        <?php print ($main_menu_expanded); ?>

<?php endif; ?>

Now i dont get extra ul

Multiple rendering causing a ul more


Chrome driver - Selenium

Question: I'm a new student of programmin and I'm trying to use Chromedriver and Selenium for the first time. I definitely can't access to the downloaded file, don't know why.
This is my input:
from selenium import webdriver
driver = webdriver.Chrome(executable_path = "/Users/silvia/Desktop/executables/chromedriver")

As you can see below, the result I get is the following. Says there's no such file on my Desktop, but there is! I tried with backslash, double backslash and everything. Maybe I should try the whole process from the beginning! Any idea of why not working? Thank you in advance!
This is the error message:
------------------
FileNotFoundError                         Traceback (most recent call last)
/opt/anaconda3/lib/python3.8/site-packages/selenium/webdriver/common/service.py in start(self)
     71             cmd.extend(self.command_line_args())
---> 72             self.process = subprocess.Popen(cmd, env=self.env,
     73                                             close_fds=platform.system() != 'Windows',

/opt/anaconda3/lib/python3.8/subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
    853
--> 854             self._execute_child(args, executable, preexec_fn, close_fds,
    855                                 pass_fds, cwd, env,

/opt/anaconda3/lib/python3.8/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
   1701                         err_msg = os.strerror(errno_num)
-> 1702                     raise child_exception_type(errno_num, err_msg, err_filename)
   1703                 raise child_exception_type(err_msg)

**FileNotFoundError: [Errno 2] No such file or directory: '/Users/silvia/Desktop/executables/chromedriver'**

During handling of the above exception, another exception occurred:

WebDriverException                        Traceback (most recent call last)
<ipython-input-6-a1abac069770> in <module>
      1 from selenium import webdriver
      2
----> 3 driver = webdriver.Chrome(executable_path = "/Users/silviafabbi/Desktop/executables/chromedriver.exe")

/opt/anaconda3/lib/python3.8/site-packages/selenium/webdriver/chrome/webdriver.py in __init__(self, executable_path, port, options, service_args, desired_capabilities, service_log_path, chrome_options, keep_alive)
     71             service_args=service_args,
     72             log_path=service_log_path)
---> 73         self.service.start()
     74
     75         try:

/opt/anaconda3/lib/python3.8/site-packages/selenium/webdriver/common/service.py in start(self)
     79 except OSError as err:
     80 if err.errno == errno.ENOENT:
---> 81 raise WebDriverException(
     82 "'%s' executable needs to be in PATH. %s" % (
     83 os.path.basename(self.path), self.start_error_message)

WebDriverException: Message: 'chromedriver.exe' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home

Comment: I always had this issue with chrome driver. So I will suggest you to use `webdriver_manage` so that you don't have to link the chrome driver executable script.
Answer: Without giving executable path:
You can use webdriver_manage (install it by pip install webdriver_manager)
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager

chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)

Comment: Try: https://stackoverflow.com/questions/55201226/session-not-created-this-version-of-chromedriver-only-supports-chrome-version-7
Comment: I have least idea about macos.  I think issue is with the chrome version.
Comment: It was actually that. Many thanks for suggesting the right way!
Comment: Glad it helped! Close the question by accepting the answer(clicking on tick) if answer helps :)
Comment: thank you! Now it says

ValueError: Could not get version for Chrome with this command: /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --version

Still trying the other ways suggested, without succes anyway :) I'll keeep trying
Answer: Silvia, try
C:/Users/silvia/Desktop/executables/chromedriver
or whatever your harddisk name it is
Comment: Thanks a lot! I tried with all possible names (MacintoshHD instead C:, Scrivania instead Desktop and so on....). Still doesn't work :(
Answer: I dont know if you have already solved it, but this also happened to me and I realized that after downloading chromedriver I forgot to put the file inside the very same directory where python.exe is located. Usually, you can find your python.exe file by going to (C:) --> Users --> your User and finally anaconda3 directory (considering that you have installed anaconda package, which I highly recommend). Put your chromedriver file inside anaconda3 directory, which is the exact same place where you can find python.exe. And thats it! After doing this, I could run my code without a problem.
Greetings from Brazil! ;)

Chrome driver - Selenium


Como se comportam o StringBuffer() e o StringBuilder()?

Question: Problema e Mistério:

StringBuffer y = new StringBuffer("Eduardo");

Estou usando um StringBuffer, pois preciso acrescentar alguns valores depois a ela. Estava fazendo debug e observei que existem um espaços em branco no final. Observe a imagem:

Imagem 1: Espaços adicionais no StringBuffer.

O mesmo acontece quando uso o StringBuilder, alguém saber por que esses espaços são incrementados?
Existem alguns aspectos entre StringBuilder e StringBuffer. Como usar o Builder quando não envolve Thread. Acredito não ter invertido.
Answer: Os espaços em branco são para aprimorar a performance na hora de concatenar as Strings. Por isso que é um "buffer".
Por exemplo: se vc concatena duas Strings assim: "abc" + "def", o Java vai criar, além desses dois objetos String, um terceiro objeto contendo o resultado "abcdef". No entanto, ao usar o buffer, o Java vai jogar os chars 'd', 'e' e 'f' dentro dos espaços vazios do buffer e atualizar aquele 'count' da sua figura para refletir o novo tamanho do conjunto. Isso é uma operação muito mais rápida.
Caso os espaços em branco não sejam suficientes, o Java vai aumentar automaticamente o tamanho do buffer para você.
Tamanho esse que, aliás, você pode configurar no construtor. Isso é bom porque custa um pouco (em termos de performance) para o Java redimensionar o buffer.
Comment: Lógico que, no meu exemplo, a operação não é "muito mais rápida", pois fiz uma concatenação trivial de duas strings. Agora tente isso num loop grande o bastante e você vai sentir a diferença.
Answer: A hierarquia
As classes java.lang.StringBuffer e java.lang.StringBuilder possuem exatamente a mesma interface estendem java.lang.AbstractStringBuilder, que possui dois atributos principais:
char value[];
int count;

Ali são armazenados os caracteres e o tamanho real do mesmo.
Sobre o Buffer
String é um tipo que armazena um conjunto de caracteres. Ela é imutável, isto é, não pode ter o conteúdo modificado, assim como seu tamanho.
O problema com isso é que para criar novas Strings, por exemplo, através da concatenação de duas ou mais Strings, uma nova String como o tamanho total delas deve ser criada em memória. Se várias dessas operações forem executadas em sequência, a JVM precisará alocar novos blocos de memória e executar o Garbage Collector para desalocar o que não é usado a todo momento. Isso é muito "custoso" em termos de desempenho.
O StringBuffer surge para resolver o problema. Um StringBuffer nada mais é do que uma String com um Buffer, isto é, um espaço reservado para novos caracteres que pode ser modificado e torna desnecessário, até certo ponto, alocar mais memória a todo momento.
O buffer é simplesmente um vetor de caracteres maior do que o conteúdo real. Por exemplo, o buffer pode ter 1000 posições e a String real apenas 500. Isso é controlado pelo atributo count. Neste exemplo, poderíamos adicionar ainda mais 500 caracteres sem degradar o desempenho do programa.
O tamanho inicial
Em muitas situações é importante definir o tamanho inicial do buffer com um tamanho médio do que se pretende usar.
Ao fazer new StringBuffer() ou new StringBuilder(), isto é, sem definir um tamanho inicial, estamos subutilizando a classe. A capacidade inicial do buffer é de apenas 16 caracteres.
Isso significa que, se adicionarmos mais de 16 caracteres, um novo buffer terá que ser alocado.
Aumentando o tamanho
Ao estourar a capacidade do buffer o próximo será criado com o dobro do tamanho. Veja o cálculo da nova capacidade do buffer no método expandCapacity da classe AbstractStringBuilder:
void expandCapacity(int minimumCapacity) {
    int newCapacity = (value.length + 1) * 2;
    if (newCapacity < 0) {
        newCapacity = Integer.MAX_VALUE;
    } else if (minimumCapacity > newCapacity) {
        newCapacity = minimumCapacity;
    }
    value = Arrays.copyOf(value, newCapacity);
}

StringBuffer ou StringBuilder?
Esta é uma dúvida comum. Olhe o Javadoc (links estão no início da resposta) e note que ambas tem exatamente a mesma interface, isto é, os mesmos métodos e assinaturas de métodos.
Qual a diferença? Vamos analisar um método básico nas duas versões, o append(String).
A versão no StringBuilder é:
public StringBuilder append(String str) {
    super.append(str);
    return this;
}

E a versão no StringBuffer é:
public synchronized StringBuffer append(String str) {
    super.append(str);
    return this;
}

Notou a diferença? É o synchronized!
Dizemos que a classe StringBuffer é sincronizada, enquanto a classe StringBuilder não é sincronizada.
Sincronizado vs. Não Sincronizado
Quais as vantagens e desvantagens em ser ou não sincronizado?
Quando uma classe é sincronizada, ela é mais própria para trabalhar em ambientes com várias threads, por exemplo, num servidor de aplicação que atende a vários usuários ao mesmo tempo. Imagine várias threads escrevendo um log em memória, por exemplo.
Nesse caso, somente uma thread por vez pode adicionar conteúdo ao StringBuffer. O problema é que isso gera também bloqueios indesejados na execução, pois nem sempre estamos modificando a classe.
Se várias threads querem apenas ler alguma informação da classe, então a sincronização está atrasando eles sem motivo. Só para citar um exemplo, a classe StringBuffer tem o método de busca indexOf sincronizado.
Já quando uma classe não é sincronizada, ela não é adequada para ser usada concorrentemente por mais de uma thread, porém ela obtém o máximo de aproveitamento para ser modificada por uma única thread e também para ser usada no modo de leitura por várias threads.
Como regra geral, se o objeto será usado apenas no escopo de um método, não sendo compartilhado, opta-se sempre pelo StringBuilder, que foi criado justamente com esse propósito.
Já se o objeto for compartilhado de alguma forma com outras classes e for possível que alguém o use em múltiplas threadas, o StringBuffer é mais adequado.
Esse raciocínio de aplica a diversas outras classes da JVM. Veja por exemplo, as classes Hashtable (sincronizada), HashMap (não sincronizada) e ConcurrentHashMap (sincronizada apenas para alteração, mas não para leitura).
Por isso, é evidente a importância de conhecer bem as APIs da linguagem antes de sair usando sempre as mesmas soluções indiscriminadamente.

Para maiores detalhes, ver minha outra resposta aqui no SO.
Answer: Isso tem relação com os tamanhos padrão e a forma como o buffer interno é incrementado, tanto para o StringBuffer quanto para o StringBuilder.
Você consegue ver isso porque está inspecionando o campo value do objeto, onde a string é construida e armazenada. Repare, de qualquer forma, que o tamanho real da sua string é mantido no campo count.
Answer: Apenas para acrescentar, se olha na classe StringBuilder está assim:
/**
 * Constructs a string builder that contains the same characters
 * as the specified CharSequence. The initial capacity of
 * the string builder is 16 plus the length of the
 * CharSequence argument.
 *
 * @param      seq   the sequence to copy.
 * @throws    NullPointerException if seq is null
 */
public StringBuilder(CharSequence seq) {
    this(seq.length() + 16);
    append(seq);
}

public StringBuilder append(Object obj) {
    return append(String.valueOf(obj));
}

public StringBuilder append(String str) {
    super.append(str);
    return this;
}

Repare que no construtor ele deixa 16 caracteres em branco inicialmente, exatamente a quantidade de espaços em branco que está depois do Eduardo, no seu exemplo. Esse é o tamanho que é deixado como buffer por padrão, mas como dito em outra resposta você pode passar o tamanho inicial no StringBuffer ou StringBuilder.
Esse espaço sobrando faz que o tamanho não necessariamente fique mudando a cada inserção de valores no seu objeto, e ao mesmo tempo não tem um sobra tão grande assim ao ponto de consumir um espaço significativo de memória.


List all available items with Apache Solr if the search keyword is empty

Question: I have created 2 search pages with Apache Solr module one with content type filter and another for search in taxonomy terms. By default if the keyword string is empty the search pages don't return any results. How can I list all available items with certain content type or with taxonomy term in this case? Thanks
Comment: Then I don't understand how you are listing terms/content types.
Comment: Are there facets involved?
Comment: no, just a simple search pages for content type nodes search and for searching within taxonomy term.
Answer: Thanks Letharion, to answer your question I have found this option in the Advanced options region for the search pages. Here is how to get there:
admin/config/search/apachesolr/search-pages
Create a new search page for Solr search with content type filter or enable one for taxonomy/term/%
Select "Show enabled facets' blocks in their configured regions and first page of all available results" under the Advanced options for this page
Answer: check "Custom Filter" text box and add text : bundle:content type, content type is your specific content type name


Stripe STPAddCardViewController navigation bar not showing

Question: I am using stripe in my code. I have one navigationBar in my viewController.
Here is the image of my viewController:

But when I navigate to STPAddCardViewController, navigation bar of STPAddCardViewController isn't shown. I am using this code:
let addCardViewController = STPAddCardViewController()

addCardViewController.delegate = self

navigationController?.pushViewController(addCardViewController, animated: true)

Here is the resulting image:

What is going wrong?
Answer: Are you, possibly somewhere else in your code, doing something of the sort (or similar) that would result in hiding the nav bar ?
self.navigationController?.navigationBar.isHidden = true
With just the snippet you posted it's I think hard to say exactly why this is happening. We might need to see a bit more code of your ViewController
I would suggest looking to see if your code is not doing something like the above.
Here is a very bare bone example VC that uses AddCardViewController pushed onto a nav controller that hopefully can help. This shouldn't have the problem that you described:
https://gist.github.com/spastorelli-stripe/9ec230dad7a7da5a6f85147deb6a4b3b
Comment: that did it for me, thanks! :)


Which fingering to use for this section of a song

Question: I can't figure out the best fingering for this part of Sound of Silence. What should I do?
Answer: For starters, do you know what 2/3CIII and 1/2CV mean? They're there to guide people like yourself who need help working out which fingers to use.
Let's take 2/3CIII. it represents a barre of 4 out of the 6 strings (2/3) as a barre. while III means do that on fret 3, with the usual index finger. That will allow the notes on the fourth and second strings to be in the right place. Leaving the remaining fingers to fret on 5 and 7 as you want. Although it's quite a stretch to reach fret 7 at the bar's end. Maybe leave that note as one on its own, as the whole hand moves up the the next bar's position.
1/2CV is a bit different, as there appears to be a barre on fret 5, looking after, basically, the 3rd string. That'll be with the index finger again, ring finger on first fret 7. Again pinky will play top string notes, and again, the last note (on the top string), will be played as an individual as the hand moves to the next bar's position - which we really need to see, to complete the answer.
Comment: Thank you @Tim. I did not know what 2/3CIII and 1/2CV mean and honestly didn't even notice them, so I'm glad you pointed them out. This is helpful. And, to address your last point, the next bar begins in first position.


user authentication with powershell

Question: I have the following simple script which I'm using to push some files to a number of Win7 and Server2008 machines. In most cases the local user has no password. However the scripts fails because I'm trying to write through the admin share (c$). What is the most simple way to pass a user for each host machine in the ip.txt?
Also if I'm on a domain how simple is it to modify the script to authenticate with a user and password.
 Write-Host 'Deploy Tools'

    $reader = [System.IO.File]::OpenText("c:\scripts\ip.txt")
    try {
        for(;;) {
            $line = $reader.ReadLine()
            if ($line -eq $null) { break }
                echo "**** files being copied to: $line ****"
                xcopy c:\scripts\tools  \\$line\c$\windows\system32\ /Y
        }
    }
    finally {
        $reader.Close()
    }

Answer: Since you are already calling a non-PowerShell command (xcopy), you could as well call another one:
net use \\$server\c$ /user:$username $password
xcopy c:\scripts\tools  \\$server\c$\windows\system32\ /Y

As for storing usernames and passwords in your input file, you can do that quite easily by using the CSV format and the Import-Csv cmdlet.
Also, see this StackOverflow question.

user authentication with powershell


Solution of Vector equation

Question: If $\mathbf{a} \wedge \mathbf{x}$= $\mathbf{a} \wedge \mathbf{b}$ and $\mathbf{a}\cdot \mathbf{(x-b)}=2a^2$, show that $\mathbf{x=2a+b}$.
I take cross product throughout
$$\mathbf{a} \wedge \mathbf{a} \wedge \mathbf{x} = \mathbf{a} \wedge \mathbf{a} \wedge \mathbf{b}$$
$$\mathbf{(a.x).a-(a.a).x}=\mathbf{(a.b).a-(a.a).b}$$
$$\mathbf{(a.x).a-|a|^{2}.x}=\mathbf{(a.b).a-|a|^2.b}$$
$$\mathbf{|a|^2(x-b)-(a.x).a-(a.b).a}=0$$
Then,I do not know how to proceed.
A second part in the question is
Given $\mathbf{x}$^$\mathbf{a}$=$\mathbf{b-x}$
Prove
$(a^2+1)\mathbf{x}=\mathbf{a}$^$\mathbf{b+b(a.b)a}$
I have been using this same dot product and crossproduct method, but don't get it.
Comment: Do you mean that $\mathbf a \cdot (\mathbf{x - b}) = 2|\mathbf a|^2$?
Answer: $$
\mathbf{a}\times (\mathbf{x}-\mathbf{b}) = \mathbf{0}\\
\mathbf{a}\cdot (\mathbf{x}-\mathbf{b}) = 2a^2
$$
From the first equation you know that
$$
(\mathbf{x}-\mathbf{b}) = \lambda \mathbf{a}
$$
from the second we have (since the brackets terms must be parallel to $\mathbf{a}$)
$$
\mathbf{a}\cdot (\mathbf{x}-\mathbf{b}) =\mathbf{a}\cdot \lambda\mathbf{a} = \lambda \mathbf{a}\cdot \mathbf{a} = 2a^2 \implies \lambda = 2
$$
thus we have
$$
\mathbf{x} = \lambda \mathbf{a} + \mathbf{b} = 2\mathbf{a}  +\mathbf{b}
$$
Answer: By the expulsion formula,
$$\mathbf a\wedge (\mathbf a\wedge (\mathbf x-\mathbf b))=(\mathbf a(\mathbf x-\mathbf b))\mathbf a-\mathbf a^2(\mathbf x-\mathbf b)=2\mathbf a^2\mathbf a-\mathbf a^2(\mathbf x-\mathbf b)=0.$$
Obviously, unless $\mathbf a=\mathbf 0$,
$$\mathbf x-\mathbf b=2\mathbf a.$$
Comment: What is the expulsion formula @Yves Daoust? And I could not follow you after your second equal sign.
Comment: @Toshina11: the one that you used, obviously.
Comment: Dear friend, I am a bit confused on how (a(x-b))a becomes $2a^2a$
Comment: @Toshina11: that's given.
Comment: I got it now, sorry for the trouble
Answer: Answer for part(i)
$\mathbf{a} \wedge \mathbf{x}$= $\mathbf{a} \wedge \mathbf{b}$ [EQN(1)]
$\mathbf{a}\cdot \mathbf{(x-b)}=2a^2$ [EQN(2)]
R.T.S
$\mathbf{x=2a+b}$.
Consider EQN(2)
$a^2=\mathbf{a.a}$
$\mathbf{a}\cdot \mathbf{(x-b)}=2\mathbf{a.a}$
This implies $\mathbf{x-b=2a}$
Hence, we make $\mathbf{x}$ subject of formula.
Answer for part(ii)
Given $\mathbf{xΛa=b-x}$
RTS
$(a^2+1)\mathbf{x}=\mathbf{a}$^$\mathbf{b+b(a.b)a}$
Cross with $\mathbf{a}$
$\mathbf{aΛ(xΛa)=aΛb-aΛx}$
$\mathbf{(a.a)x-(a.x)a=aΛb-aΛx}$
$\mathbf{aΛx=-(xΛa)=-(b-x)}$ [Cross-product is anti-commutative]
$\mathbf{(a.a)x-(a.x)a=aΛb+b-x}$
$\mathbf{(a^2)x+x=aΛb+b+(a.x)a}$
$\mathbf{(a^2+1)x=aΛb+b+(a.x)a}$
Dot product with $\mathbf{a}$ to eliminate $\mathbf{(a.x)}$ /EQN 3
$\mathbf{(a^2+1)(x.a)=aΛb.a+b.a+(a.x)a.a}$
$\mathbf{(a^2+1)(x.a)=aΛb.a+b.a+(x.a)a^2}$ [Dot product is commutative]
$\mathbf{(a^2+1)(x.a)=b.a+(x.a)a^2}$
$\mathbf{(a^2+1-a^2)(x.a)=b.a}$
$\mathbf{a.x=b.a=a.b}$
Hence replace
$\mathbf{a.x=b.a=a.b}$ in EQN 3 to get the answer.

Solution of Vector equation


Is there a built in way to reject certain SOP Classes on a fo-DICOM server?

Question: I want to run a fo-DICOM server that returns the DicomStatus SOPClassNotSupported if for instance I try doing a CStoreRequest on it with the SOP class for Encapsulated PDF documents. Can I define the SOP classes to reject beforehand instead of having to explicitly reject it in the OnCStoreRequest() method?
What I have so far:
public DicomCStoreResponse OnCStoreRequest(DicomCStoreRequest request)
{
   DicomStatus dicomStatus = DicomStatus.Success;
   var SOPClassUID = request.Dataset.GetSingleValue<DicomUID>(DicomTag.SOPClassUID);
   if(SOPClassUID == DicomUID.EncapsulatedPDFStorage) {
      dicomStatus = DicomStatus.SOPClassNotSupported;
   }
   return new DicomCStoreResponse(request, dicomStatus);
}

The code above works, but I'd do it differently if there is some official/built in way to define which SOP classes to reject.
Answer: You can control this behavior on ASSOCIATION level. Validate the Abstract Syntax proposed before sending ASSOCIATE_ACCEPT.
public Task OnReceiveAssociationRequestAsync(DicomAssociation association)
{
    foreach(var pc in association.PresentationContexts)
    {
        if(pc.AbstractSyntax == DicomUID.EncapsulatedPDFStorage)
            pc.SetResult(DicomPresentationContextResult.RejectAbstractSyntaxNotSupported);
        else
        {
            pc.AcceptTransferSyntaxes(AcceptedImageTransferSyntaxes);
            pc.SetResult(DicomPresentationContextResult.Accept);
        }
    }

    return SendAssociationAcceptAsync(association);
}

The DicomAssociation association is ASSOCIATION_REQUEST you received. The association.PresentationContexts holds all proposed Presentation Contexts in received association. You enumerate through each of it. Each proposed Presentation Context contain Abstract Syntax and list of proposed Transfer Syntaxes. You can loop through list of transfer syntaxes and set the one you prefer; as your question is not about it, I skipped that part in code.
If you can accept (receive/process) the pair of Abstract Syntax and Transfer Syntax that is proposed, you accept that specific Presentation Context by setting its result. If you don't, set the result accordingly with reason.
Finally, send the ASSOCIATE_ACCEPT (or reject...).


Distance calculation which is faster mongodb or mysql

Question: I am little bit confused about following problem & their solutions:
i have 2 tables users & userfriends having following structure
users
userid         lat          long

userfriends
    userid         friendid

so in users table i have lat & long of all the users & in userfriends i have list of friends for each user.
Now i want to calculate nearby users (distance) so my friend told me to use mongodb which have fast performance.
But i found another function which i can use in stored procedure in mysql
function distance($lat1, $lon1, $lat2, $lon2, $unit) {

  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344);
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

So basically i want my distance calculation faster & quick.
So can somebody tell me am i correct in my way or i need to send needed data (lat & long of users friends) to mongodb & calculate & mongodb will return results to my database (MySQL)?
Comment: I wouldn't use both DBS. Choose one and stick with it. The performance you gain from choosing the right DBS (if there is one) will definately be lost by transfereing data between them. I think MySQL will do fine with this problem. Just use some fitting indexes.
Comment: You will also not need to calculate the exact distance. There must be some heursitics to guess a vague distance that will calculate much faster.
Answer: Both MySQL and MongoDB support geospatial indexing. IME, NoSQL databases have huge performance advantages when dealing with selecting individual records, but offer less of a performance benefit (still usually faster) compared with a relational database when dealing with range queries - YMMV.
There are other very fundamental differences - which are well covered elsewhere.
You really want to spend a lot of time reading the linked documents - the method you describe will be phenomonally innefficient.
Comment: I am going to use MongoDB as its also calculate distance for me in just few miliseconds. Thanks for your answer


ListBox SelectedItem binded: page navigation, getting item, showing its properties in a new view and reset SelectedIndex. How can i do?

Question: i'm trying to apply the MVVM pattern in my application with MVVM Light. I've a databinded ListBox...
MainView.xaml [extract]
<ListBox Name="recipesListBox"
                             ItemsSource="{Binding RecipeList}"
                             SelectedItem="{Binding SelectedRecipe, Mode=TwoWay}"
                             HorizontalAlignment="Stretch"
                             VerticalAlignment="Stretch"
                             Grid.Row="1"
                             Margin="12,0,12,0"
                             SelectionChanged="recipesListBox_SelectionChanged" >

MainViewModel.cs [extract]
    private Recipe selectedRecipe;

    public Recipe SelectedRecipe
    {
        get
        {
            return selectedRecipe;
        }
        set
        {
            selectedRecipe = value;
            RaisePropertyChanged("SelectedRecipe");
        }
    }

...that performs a page navigation on SelectionChanged:
MainView.xaml.cs [extract]
private void recipesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string destination = "/RecipeView.xaml";
            if (recipesListBox.SelectedIndex == -1) // If selected index is -1 (no selection) do nothing
                return;
            this.NavigationService.Navigate(new Uri(destination, UriKind.Relative));
            //recipesListBox.SelectedIndex = -1; // Reset selected index to -1 (no selection)
        }

After // you can see the old code that reset the index after page navigation - now, with binded data, obviously it also set null my selected item! How can i do for navigate to a new view, show the property of selected item and reset the selected index when i go back? Thank you!
Answer: The best way is to have your collection stored somewhere you can access it anywhere (like in the Windows Phone Databound Application project) and pass the index of the selected item in your navigation uri
int index = recipesListBox.SelectedIndex;
this.NavigationService.Navigate(new Uri(destination +"?index="+index , UriKind.Relative));

Then in the OnNavigatedTo method of your new page get the index from the query and get the item
override OnNavigatedTo(
{
    string index;
    if(NavigationContext.QueryString.TryGetValue("index", index))
    {
        // get the item from your collection based on this index
    }

}

Comment: Thank you for your answer! My old code was like: Recipe selectedRecipe = recipesListBox.SelectedItem as Recipe; this.NavigationService.Navigate(new Uri(destination + "?RecipeID=" + selectedRecipe.ID, UriKind.Relative)); this.recipesListBox.SelectedIndex = -1; ...in OnNavigatedTo i retrieved the recipe through ID with a LINQ query on my xml "database" and as long as i performed actions in the method all works normally but outside the method the recipe appeared null! I obviously saved "outside" the recipe getted but it always appearing null! Regulary in OnNavigatedTo and null outside :(
Comment: Are you saying that the QueryString "RecipeID" is not available and is null? Is should stay in the NavigationContext. Or are you saying that the Recipe itself is null? Or that the Recipe collection is null? and in what page is it null?
Comment: Recipe itself becomes null! My code behind in the new view was like: private Recipe selectedRecipe; override OnNavigatedTo(
{
    string ID; if(NavigationContext.QueryString.TryGetValue("ID", ID))
    {
        this.selectedRecipe = GetRecipeByID(ID);
    }} i.e., if i try to get the Name (selectedRecipe.Name) inside OnNavigatedTo, i get exactly what i want, if i try outside i get Null*something*Exception!
Answer: The way I did it was this:
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
    if (listBox.SelectedItem != null)
    {
        listBox.SelectedIndex = -1;
    }

    base.OnNavigatedFrom(e);
}

then add the following to SelectionChanged event
if(SelectedItem != null)
{
    // Do something with SelectedItem
}

Comment: Thank you for your answer! I found solution myself just yesterday, i wrote code exactly in your way! Except for if () and base.OnNavigatedFrom(e), i'm adding it right now XD Thank you again! :D


the problem with ajax i don't get the content

Question: On submit the .saveInsurance I get a 204 no content answer instead of getting the content of the page can anybody help me sometime I get a error in data
the error is

examples.js:70 Uncaught TypeError: $(...).closest(...)[0].data is not
  a function

the actual result is to get a 200 status code and get the content
var targetUrl = $(curInput).closest('.CustomeStepWizard').attr('data-url');
var dataSW = $(curInput).closest('.CustomeStepWizard')[0].data;
if (targetUrl)
{
    bindObj ={
        url: targetUrl,
        data: dataSW
    };

    $(curInput).closest('.CustomeStepWizard').find('.saveInsuranceBTN')
            .removeAttr('disabled').click(function () {
                createPostRequest(this.url, bindObj.data);
            }
            .bind(bindObj));
}
else {}

Answer: As your HTML file is not shown, I want to believe that you have some data attribute attached to the $(.CustomeStepWizard) object. However, this data could be retrieved by using
$(.CustomeStepWizard)[0].data(); /returns all data. Mind the () after the data./
    $(.CustomeStepWizard)[0].data('foo');
    $(.CustomeStepWizard)[0].attr('data-foo');  /* retrieve a particular data. */


WPF : How can i show my login window(project imported) before my application window?

Question: I have made a project for a login WPF application that basically performs a database connection. Now I am developing an application (always in WPF) that need this login project to start. I have added the Login.Exe to the reference in my current project, but I can't find a way to force the start with the login and only after that run my MainWindow().
I'm currently trying something like this
namespace Administrator
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Window login = new Login.MainWindow();
            login.Show();
        }
    }
}

My mainwindow.xaml has empty content, and this piece of code it shows the login form, but also a blank window. How can I achieve my goal?
Comment: Is the login window a `Window` or a `UserControl`?
Answer: You can achieve this with the following pattern.
In your App.xaml change StartupUri="MainWindow.xaml" to Startup="ApplicationStart" and in your App.xaml.cs create the method ApplicationStart.
private void ApplicationStart(object sender, StartupEventArgs e)
{
    Window login = new Login.MainWindow();
    login.Show();

    // Determine if login was successful
    if (login.DataContext is LoginViewModel loginVM)
    {
        if (!loginVM.LoginSuccessful)
        {
            // handle any cleanup and close/shutdown app
        }
    }

    //show your MainWindow
}

I prefere this pattern because you can e.g. setup your DI container in the ApplicationStart or anything else you want to before your main view is shown.
Comment: Your welcome :) Would be nice if you accept the answer when it's working.
Comment: Now just another question. Since my login project was developed following MVVM pattern, and i need a variable from it, is it correct to access to the Login VM using something like: VMinstance = login.Datacontext as ViewModel ?
Comment: Good question and there are different solutions. Maybe there are cleaner solutions but I would do it like you and use the ViewModel to get the data.
Answer: Set in the App.xaml the "ShutdownMode" and the "StartupUri":
   <Application x:Class="MyApp.App"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:MyApp"
                ShutdownMode="OnExplicitShutdown"
                StartupUri="Login.xaml">

The "StartupUri" is your login form.
Comment: Possible as well but in my opinion it's not the cleanest way of programming when your login window has to open your main window. That logic depends not in the login window. That's why I prefere the ApplicationStart method (like in my answer shown).


how to store value of ansible fact variable in another variable

Question: I wanted to store value of ansible fact variable in some other variable, and also wanted to check is that fact variable is empty or not
Below is my code where i can print the value of ansible_local fact variable but i wanted that value to store in another variable say xyz. And also wanted to check that ansible_local.sj.inventory.as_tag variable value is empty or not
<code>- name: -> Apply common configuration to {{ target }} nodes
  hosts: "{{ target }}"
  gather_facts: True

  user: root

  pre_tasks:
   - setup:
      filter: ansible_local

 tasks:
   - action: debug msg="{{ ansible_local.sj.inventory.as_tag }}"
</code>
Sample O/P:
<code>TASK: [debug msg="{{ansible_local.sj.inventory.as_tag}}"]
    ***********
Monday 09 May 2016  09:48:49 -0700 (0:00:01.375)       0:00:02.785
  ************
ok: [abcserver] => {
  "msg": "abcd-123"
</code>
Answer: You can use the set_fact module.
Here is an example....
<code>- name: -> Apply common configuration to {{ target }} nodes
  hosts: "{{ target }}"
  gather_facts: True
  user: root

  pre_tasks:
   - setup:
      filter: ansible_local
   - set_fact:
       tag: "{{ ansible_local.sj.inventory.as_tag }}"
   - debug:
       var: tag
</code>


Reached maximum VM restart count for {nombre_vm}

Question: We have 4 ESX Server in cluster. Yesterday i received this warning in all VM: Reached maximum VM restart count for {vm_name}. We can´t do VMotion and others tasks whit these machines.
Any idea? what we can do?
Thanks.
Answer: What kind of Licenses do you have installed. I have found, that VMware is moving some Products to Guest based licences. For example the Vmware Enterprise you get with VMware View only allow up to a certain  limit of guests to be running.
Answer: I'm assuming you're using HA in your cluster. Maybe the VM's don't meet the Fault Tolerance.
Have you tried do deactivate HA and try to move the VM's to another Host?
If everything is alright with the cluster (hardware, licenses) I would just deactivate HA, wait a few minutes and activate HA again.


findViewById retorna null

Question: Estou a receber null da minha chamada findViewById, e não consigo perceber porque. O código em baixo é relativo a uma Activity no meu programa:
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.dashboard);
        getLayoutInflater().inflate(R.layout.activity_cpc_select, frameLayout);

        TreeNode root = TreeNode.root();
        TreeNode parent = new TreeNode("MyParentNode");
        TreeNode child0 = new TreeNode("ChildNode0");
        TreeNode child1 = new TreeNode("ChildNode1");
        parent.addChildren(child0, child1);
        root.addChild(parent);

        AndroidTreeView tView = new AndroidTreeView(this, root);
        FrameLayout view= (FrameLayout) findViewById(R.id.cpc_tree_view);
        view.addView(tView.getView());
    }

O meu layout está definido assim:
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/cpc_tree_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>
</FrameLayout>

Comment: Para usar o método `Activity#findViewById()` tem de indicar que a Activity usa o layout onde está esse FrameLayout através de `setContentView()`.
Comment: assim funciona. obrigado!
Answer: O problema está na linha comentada do setContentView
Trocando seu codigo para:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dashboard);

        TreeNode root = TreeNode.root();
        TreeNode parent = new TreeNode("MyParentNode");
        TreeNode child0 = new TreeNode("ChildNode0");
        TreeNode child1 = new TreeNode("ChildNode1");
        parent.addChildren(child0, child1);
        root.addChild(parent);

        AndroidTreeView tView = new AndroidTreeView(this, root);
        FrameLayout view= (FrameLayout) findViewById(R.id.cpc_tree_view);
        view.addView(tView.getView());
    }

você consegue acessar a view com o findViewById(); Obrigatóriamente, segundo a documentação, toda view que for incializada em uma activity, tem que ser criada com o setContentView.

findViewById retorna null


Why is the set $K$ recursively enumerable?

Question: I am trying to understand why the set $K=\{i \mid M_i(i) \;\mathsf{halts}\}$ is recursively enumerable, where $M_i(i)$ is a Turing machine that is given its own index (in the standard enumeration of Turing machines) as input ("the halting problem").
If we cannot determine if $M_i(i)$ halts, how could we even produce the set $K$ in the first place? If $K$ were recursively enumerable, we could have a Turing machine $M_K$ that takes this set as input and outputs a list of all of its elements. But if this were the case, the halting problem would be solvable because of the fact that all of the elements of $K$ are known in the first place.
I am obviously missing a big point here. What am I missing?
Answer: You're misunderstanding what "recursively enumerable" means. If taking the set as input were allowed, then everything would be recursively enumerable (or nothing noncomputable would be, if you require the input the be computed first) because given a set $X$ as input, enumerating its members is as simple as reading them off.
A set $S$ is recursively enumerable if there is a Turing machine $M_S$ which, given no input, lists out the members of $S$. In this case, the halting set can be enumerated by the following process:
At stage $0$, start $M_0$ running on input $0$.
At any stage $s > 0$, start $M_s$ running on input $s$, and advance each machine started at an earlier stage by one step. If there is an $M_i$ for $i < s$ so that $M_i$ just now halted, output $i$.
This process enumerates the members of $K$, in no particular order. It's still difficult to tell whether a given $n$ is in $K$; if it is, it'll eventually show up, but if it isn't we'll never be sure of that.
Answer: Just because you have a machine that outputs the elements of $K$ doesn't mean they "are all known".
The problem is that $M_K$ does not necessarily output the elements in order, so just observing the run of that machine will never allow you to conclude that some number is not in $K$. You can fun the machine for a year and notice that your favorite number has not yet been output, but you can't know whether it will be output next week, or in another year, or a century -- or, indeed, never at all.
This is THE difference between "decidable" and "recursively enumerable".


Hide the price when stock is 0

Question: Is there a way to hide the price on display of a product when the stock goes to zero?
Comment: How are you currently showing price on the product display?
Comment: Hi David Thomas. I use the regular display price field of drupal commerce.
Answer: This explains how I did something similar. You'll just need to adjust your selectors to hide the price as well as the add to cart button...
Step 1 – Create New "Product Status" Field
Go to  Administration > Store settings > Product settings > Variation types and select "Manage Fields" for the variation type you want to modify (I just use the default "Product" variation type for my site). Add a new field called "Product Status" of the type "List (text)." For "Allowed values list," I entered the following because it occurred to me the client might want similar display-but-don't-sell functionality for upcoming releases…
soldout|SOLD OUT
comingsoon|COMING SOON
Of course you can just include the sold out line if you prefer. The string before the pipe is the machine name and the part after the pipe is what will display. Save your changes. Now go to "Manage Display" for the product variation type and add the new field for any display types you use for your products. I just use the default and teaser display types on my site. Remember to adjust the label settings (I'm guessing you want "hidden") and to order the field so it displays relative to other fields as you desire. Save your display changes.
Step 2 – Set Products to Product Status = SOLD OUT
Go to Products > Manage Products and edit your sold out products, setting the new status field to SOLD OUT as appropriate. Note: this is the only step the client will need to do in the future whenever he runs out of a certain product…
Screen Shot 2013-09-24 at 4.59.24 PMSave your changes.
OK – we've created a mechanism for indicating when something is sold out, but this doesn't prevent site visitors from adding sold out items to their carts. Probably nobody would try to put these items in their cart, but you never know. I certainly don't want my client to have to hassle with issuing PayPal refunds, so I'm going to make sure these products can't be added to the cart. It seems to me the easiest way to do this is to use jQuery to remove the add-to-cart button for sold out products.
Step 3 – jQuery to Remove Add-to-Cart Button From Sold Out Product Displays
The following jQuery script simply looks for the class that wraps my Product Status ("field-name-field-product-status"): if it finds the class, it removes the Add-to-Cart form for that product. This works because Drupal's default behavior is to not render the field and its wrapper classes if there is no data to display. In other words, only products I set to "Sold Out" (or "COMING SOON") will have this field and class. I reiterate this technique because there are two possible display pages for products on my site (full and a teaser view), and each has a different DOM that needs to be traversed differently. You will almost certainly need to adjust my selectors for your particular needs (browser developer tools, firebug or just viewing the page source will guide you)…
<code>/*Script for Gench product pages - removes add-to-cart button/form if product is sold out*/
/*wrap everything in a safety  "no-conflict" function so dollar sign works*/
(function($){
/*wait until page is fully loaded before firing script*/
$(document).ready(function(){
        /*remove add-to-cart button if product has status of sold out - for product display page*/
        $(".field-name-field-product-status").closest("td.views-field").find("form.commerce-add-to-cart").remove();
        /*remove add-to-cart button if product has status of sold out - for product teasers page*/
        $(".field-name-field-product-status").closest("div.content").find("form.commerce-add-to-cart").remove();
    });
})(jQuery);
Because I was already using javascript on my product pages, I just added the above script to the existing script, so I don't have to do anything additional to call the new script. If you write this as a stand-alone .js file in your sites/all/themes/themename directory, you'll need to reference the script which can be done globally in your theme's .info file, or for select content, in your theme's template.php file. For example…

function genchstyle_preprocess_page(&$variables, $user) {

  if(arg(0) === 'productdisplay' || 'store') {
    drupal_add_js(path_to_theme().'/js/soldout.js');
    $variables['scripts'] = drupal_get_js();
    $scripts = drupal_get_js();
  }
}
</code>
Here is what a product looks like when it is in stock (full display)…

And this is what it looks like when it is no longer in stock…

Again, you probably want to go with an actual inventory control module/approach for bigger/busier sites, but this kluge works pretty well for my purposes (and doesn't preclude adding the Commerce Stock module later should the need arise).
Cheers
Comment: Hi Anne, thanks for taking the time to answer - we don't actually allow "link-only" answers (as they've come to be known) because external resources are ephemeral in nature and your answer would unfortunately become useless if the site you linked to went down. If you could summarise the main points from your blog post here, and just use the link for supplementary information, that would be great and we can avoid having to delete the answer. Many thanks.
Comment: Clive - OK I've fixed it. Any way you can remove the negative vote now? Anne
Comment: Thanks Anne, that's great. I didn't actually vote on this answer the first time around, the downvote wasn't from me - I've just voted it up though, hopefully it'll get some more exposure and more upvotes too
Comment: Cool - glad to help! Go Brazil! Hope you win today!

Hide the price when stock is 0


How to correctly benchmark sequential read speeds on 2.5" hard drive with fio on FreeBSD?

Question: Like suggested in https://askubuntu.com/a/991311 I tested the read speed of a 2.5" spinning hard drive on a TrueNAS/FreeBSD system.
For "Sequential READ speed with big blocks":
fio --name TEST --eta-newline=5s --filename=fio-tempfile.dat --rw=read --size=500m --io_size=10g --blocksize=1024k --ioengine=posixaio --fsync=10000 --iodepth=32 --direct=1 --numjobs=1 --runtime=60 --group_reporting

I got 8037 MB/s.
I don't believe this.
I did replace liaio with posixaio, do I need another engine?
Answer: I think you are testing the speed of your system's filesystem cache because you are only fsyncing every 10000 I/Os (so that's every 9GBytes). Does your speed change if you use you choose use the direct=1 option?


Is it good to use for all $\delta$ there exists $\epsilon$?

Question: Logically, the following two definitions are exactly the same:

For all $\epsilon >0$, there exist $\delta >0$ such that if $0<\vert x-a\vert<\delta$, then $\vert f(x)-L\vert<\epsilon$.
For all $\delta >0$, there exist $\epsilon >0$ such that if $0<\vert x-a\vert<\epsilon$, then $\vert f(x)-L\vert<\delta$.

But would people say that the second one follows a "bad notation", a "hard-to-read notation", "less-elegant notation", or an "unconventional notation"? I am trying to make the readers happy.
Comment: It's just a convention. Do you have a good reason to break the convention?
Comment: In which case, can you keep (2) but replace $\epsilon$ with another Greek letter. I recommend $\eta$. Even that is much better than (2). I don't know what your proof is, so cannot give an absolute answer.
Comment: You can also use $\epsilon', \epsilon^*, \epsilon_0$, etc. so that it still helpfully suggests that we are referencing the epsilon-delta definition of limit.
Comment: It's such an ingrained convention it would throw everyone off.  It'd be likes say "let's use the notation $\frac mn$ to mean $m$ multiplies by $n$ so $6 = \frac 23$ and $\frac 4{16}=\frac 88 = 64$.  you can do it and it's consistent and there's nothing wrong with it.... but WTF man....
Comment: @BenjaminWang In my second part of the proof I am using epsilon as a small number. But at the end I found out that I had to add some definitions to the first part, which is similar to the definition (2) I wrote above. That is, if I don't want to change all the symbols in the second part and I want all my letters to be consistent, then I would have to use the definition (2) instead of the standard (1).
Comment: Logically of course letters and symbols can be used as you please. But anyway, atleast my opinion is that certain greek letters "always come in pairs/triples", like $\alpha,\beta, (\gamma)$ or $\mu,\nu$ or $\epsilon, \delta$ or $\xi,\eta, \zeta$ or $\theta, \phi, \psi$. Basically, it would be weird to break up these pairs and switch them around amongst themselves. If you need a different symbol to signify a small number, use something like $\epsilon', \tilde{\epsilon}$, or use another greek letter. Of course without anymore specifics, we can't really say what's "better".
Answer: Yes, people would object. Although the choice of variable name doesn't matter mathematically, it can still be helpful or misleading. There is a general convention around the use of that particular pair of variables, and going against it will only confuse readers.
(Granted, every so often there is a good reason to go against such a convention ... but that tends to be pretty rare.)


big endian vs little endian

Question: i work on a 64 bit intel processor...i was learning about big and little endian and what i understood was that these are byte orderings within a word such that in a 64 bit data, msb will have lowest address in big endian form and the highest address in little endian form...now i have a problem:
I wrote this code
to determine whether my processor was little or big endian...
I input
0102030405060708 (this is in hex)

and hoped to get 08 and 07 and 06 and... and 01 as answer
but instead got 0 and 25 and 50 and -125 and -13 and 501 and -41 and 66.
when I wrote the same code taking 's' as 2 byte(short), the output for 0102 was 2 and 1 (which is in accordance with little endian)...so what went wrong here?
Comment: When you write your question, note that it shows a preview of what it's going to look like. Please use that to ensure that your question looks *readable*. Thank you :)
Comment: What do you expect to be the bit-code of a double that represents 0x0102030405060708?
Comment: See [here](http://stackoverflow.com/q/9971369/440558) for a question containing a method to find the endianess.
Comment: char is a signed type. Use unsigned char if you don't want the negative numbers.
Comment: I'm voting to close this question because the code isn't included and the link has expired
Answer: You are storing your input value as a double, which stores the value as a floating point value. Try using a long long instead, which is a 64 bit integer, and should store the value as you expect.
Comment: if my word is of 64 bit and there was a data type 9 byte long and i set it to 0x010203040506070809...and follow the same procedure...would i see 09 and 08 and 07... and 02? where would 01 go....lowest address byte or highest address byte of next word?
Comment: @avinash It's impossible to store a 9byte data type in 8byte, hence before even storing it, it would usually throw a compile time error (well or you get some kind of truncation, which usually means you lose the higher byte that can't be represented)
Answer: Taking a hex number into a (double) is not likely to do what you expect; it's a floating point value consisting of a base 2 mantissa and exponent.  You might find (long) or (long long) to be closer to what you intended.

big endian vs little endian


Inbound path processor is not processing

Question: I'm trying to use an Inbound Path Processor to redirect a path(to a webapp based on this tutorial), but Drupal is not picking it up.
I tried the following code to simply redirect every page on the site to /happy, but after rebuilding the cache, nothing happens; I can navigate the site normally and never get redirected.
/mymodule/src/PathProcessor/MyPathProcessor.php
namespace Drupal\mymodule\PathProcessor;

use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;

class MyPathProcessor implements InboundPathProcessorInterface {

  public function processInbound($path, Request $request) {
    return '/happy';
  }

}

Am I using this wrong?  What do I need to do to get Drupal to use the path processor?
Comment: This is not a redirect by the way. Path processing is like rewriting in .htaccess without `[R,L]`. If you want to rewrite the path with a redirect you can use an event subscriber. See https://www.drupal.org/node/2013014
Answer: A path processor is a service tagged with path_processor_inbound. For example, this is the definition of the path_processor.files path processor used by Drupal core.
path_processor.files:
  class: Drupal\system\PathProcessor\PathProcessorFiles
  tags:
    - { name: path_processor_inbound, priority: 200 }

Keep in mind that all the path processors are invoked. If the path set by a path processor isn't used from Drupal, another path processor could have changed it. Services like path_processor.files use the priority for that reason: to avoid conflicts with other services of the same type which, in this case, could change the path already altered by another path processor.


Agora.io - is it possible to modify the video chat in real time

Question: I'm using Agora.io in Unity for video chat, is it possible to edit the video chat in real time in Agora.io Example: send a heart to the friend which you are having video chat. As I know Agora use the VideoSurface component to broadcast the camera texture in real time (please correct me if i'm wrong, i'm new to agora), I don't know if it's possible to edit the texture create by VideoSurface
Answer: The VideoSurface component is rendering the received video data for you.  It does not broadcast anything.  The SDK engine encodes and transmits the video for you to remote endpoints.
Will you please clarify on "edit the texture"? Did you mean changing size or replacing the contents of the rendering texture?  In both cases the answer is yes.  You may update the transform of the texture game object for sizing.  And you may call SetForUser() to assign a different user to render on that hosting texture.
Comment: What I mean is modify the content of the texture received texture in real time,  like distord, transform, or add additional image on the texture. I kind of understand what you mean, will test it, thanks


Como copiar o conteúdo html gerado dentro do ng-repeat em uma textarea?

Question:

BLOCO {{ keyC }}

          <formulario  data="p" ></formulario>

Como copiar o conteúdo que foi gerado no DOM para uma textarea?
Na verdade deve ser gerado somente algumas coisas dentro da textarea:

BLOCO 0

88888

BLOCO 1

123123123

Jsfiddle para melhor explicação:
https://jsfiddle.net/na4t6k57/
tentei fazer isso, mas creio que está totalmente errado:

  {{ html += '
' }}
    {{ html += '
BLOCO' + keyC '
' }}

          {{ html += '<formulario  data="p" ></formulario>' }}

  {{ html += '
' }}

<textarea ng-model="html"></textarea>

Comment: Porquê você colocou um ng-model na div ?
Answer: Consegui obter o html através do JQuery Lite que vem embutido no Angular.
Coloquei um id no ng-repeat inicial e criei um botão com a função de colocar o html no model segue link do meu JsFiddle - https://jsfiddle.net/unahk45a/
$scope.seta=function(){
    $scope.textarea = angular.element(document.querySelectorAll('#id')).html();
}

Explicação:
document.querySelectorAll() seletor nativo do Javascript
angular.element() vai transformar o objeto passado em um objeto jquery lite (se você tiver colocado a dependência do JQuery no seu projeto será um objeto JQuery)
html() metódo Jquery que retorna o conteúdo html do objeto JQuery
Comment: Tem ainda mais 1 desafio que é fazer um watch para isto ou rodar a função seta() depois que o ng-repeat ter rodado.


Get all nodes where date field matches month and year

Question: I have a content type with a date field (myFieldDate) whose values are timestamps. (I'm collecting only day, month, and year.)
I have a custom form where I have a select list to select month and year.
I need to use the EntityFieldQuery class to get all the nodes where the date field contains the month and the year I specified.
$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'horas')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_day', 'value', $myFieldDate, '=');

If the select list contains '2015-05', for example, the query should return all nodes where myFieldDate contains a date for that month and year.
Answer: You can use a range like condition:
$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'horas')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_day', 'value', $myFieldDate . '-01', '>=')
  ->fieldCondition('field_day', 'value', $myFieldDate . '-31', '<=');


Skip to Main Content link not working?

Question: The theme I'm using (AT Panels Everywhere subtheme for Adaptivetheme) has the following skip navigation link:

Skip to main content

but that link goes nowhere when I hit Enter when that div becomes focused as I tab through on the keyboard.
I tried adding the "content" anchor tag like this:

<?php print $content; ?>

but it still doesn't work. I'm still forced to tab through every link on the page.
What am I doing wrong?
Answer: Try changing your code like this

Skip
<?php print $content; ?>

Comment: Hi Nikhil, I'm not sure that's right. The code I mentioned above is for the anchor tag that is being linked by the 'Skip to main content' link in my site template which is this:
Skip to main content
`

Skip to Main Content link not working?


Generate a fancy PDF certificate from form?

Question: Anyone have ideas on how to generate a fancy PDF certificate in drupal based on user-supplied form input? Here's an example of what I want to do here:
http://www.infiniteskills.com/cert/01596
This form just collects a name and build a nice PDF. Not sure if the email address is used for anything (other than perhaps collecting email addresses).
I've attached a screenshot of the final PDF so you can see the result without using the form.
Thanks for any ideas or pointers.
Edit: Adding a link the Drupal certificate module: http://drupal.org/project/certificate
This module requires the print module and seems a little heavy for what I'm trying to do. Also, as far as I can tell, it will only create a PDF from existing HTML page.
Answer: You can build a proper fillable PDF form and then use the Fill PDF module to merge it with data from a node or a webform.
Have a look at the demo on the Fill PDF service website.
Comment: tostini - cool, thanks. I think that might work. Will take a look.
Comment: tostini - PDF fill is awesome - thanks for the pointer. I'm testing it with webform and webform_token, and it's a piece of cake to map the webform fields to the form fields in the PDF. Works great. How do I close this question?
Comment: Glad to see it helped you. To "close" the question accept it by clicking the tick beyond the arrows and points on the left side of my answer.
Answer: Did you see Certify in the Related Projects right sidebar of Certificate module you linked !?
It sounds leaner.
Comment: tenken - thank you. I looked at that a few weeks and completely forgot about it. The readme makes it look like book and quiz modules are dependencies but it doesn't appear that way on the project page. I'll take a look. Certify is probably a useful starting point either way.
Comment: Tenken - PDF fill is awesome - thanks for the pointer. I'm testing it with webform and webform_token, and it's a piece of cake to map the webform fields to the form fields in the PDF. Works great. How do I close this question?
Comment: Put the comment in the wrong place but can't remove it so I added a new comment above.


streamlit does not work with multiprocessing

Question: I am working on a project in which I am using streamlit, it works fine except of that when I add multiprocessing to the code, it does not work (the streamlit part), so I starting debugging and stripping my code down to get to the bottom of it, and I reached to a very simple code, and it does not work, anyone has any idea why it does not work please? Here is the code:
import streamlit as st
import multiprocessing as mp

def fun():
    st.write('Testing streamlit with multiprocessing')

if __name__ == "__main__":
    p1 = mp.Process(target=fun)
    p1.start()
    p1.join()

It runs but not will be displayed on the browser, and I am using streamlit run file.py from the command prompt to run it
UPDATE:
BTW, if I move the MTing from the code, it runs well, like below:
import streamlit as st
import multiprocessing as mp

def fun():
    st.write('Testing streamlit with multiprocessing')

if __name__ == "__main__":
    fun()

Comment: I'd invert the way you're doing this and generally have a wrapper spawn the subprocesses and then gather the results up to present to the streamlit app rather than having any subprocess attempt to write to it
Comment: Does this answer your question? [What kind of problems (if any) would there be combining asyncio with multiprocessing?](https://stackoverflow.com/questions/21159103/what-kind-of-problems-if-any-would-there-be-combining-asyncio-with-multiproces)
Comment: First, I am not sure if I understood your first comment clearly, would appreciate if you can put small code, second I actually have 3 different processes (functions), one for capturing, one for calculations, and the this for streamlit, the problem is when I add the streamlit into the MPing, if the first 2 are running on their own, everything is fine, and as you can see in my sample, nothing much to gather and present, it is simply printing, finally, the `asyncio` is not really a multiprocessing, so this is not what I am looking for, but thanks for your response anyway, I really appreciate it
Answer: So what I suspect is happening is that Streamlit is running in the main process which means your child processes cannot interact with it directly. You can use a shared memory object like a Queue to communicate between the child processes (functions) and the main process (Streamlit).
Based on your comment in the chat, here's how you could structure your code:
import streamlit as st
import multiprocessing as mp

# Function to capture data
def capture(q1):
   # Capture data and put it into q1
   pass

# Function to do calculations on captured data
def calculate(q1, q2):
   # Retrieve data from q1, do calculations, and put results
   # into q2
   pass

# Function to display results in Streamlit app
def display(q2):
   while True:
         # Retrieve results from q2 and display them in
         # Streamlit app
         results = q2.get()
         st.write(results)

if __name__ == "__main__":
# Create Queues for communication between processes
q1 = mp.Queue()
q2 = mp.Queue()

# Create and start child processes
p1 = mp.Process(target=capture, args=(q1,))
p2 = mp.Process(target=calculate, args=(q1, q2))
p1.start()
p2.start()

# Start display loop in the main process
display(q2)

Comment: Hi Tony, I actually moved on with this, I think streamlit is not compatible with Multiprocessing, because I have created a simple app that only prints (Hello) and it did not work, I have posted the question on their community pages and no response, so I am working on plotly dash, which I started to like, even though a new phase of learning. But thanks anyway
Comment: You can definitely run Streamlit with multiprocessing. I do it all the time with no issues. Streamlit has a help chat where they explain how to do it.


SQL Server Reporting Services - localize reports?

Question: I have some SSRS 2008 reports that need to be localized. That is:

Report titles, column headers, etc. all need to be in the user's locale. (Note that in my situation, the User!Language expression may or may not be useful, but that's not the major problem.)
The localized strings must be retrievable from a table within the same DB as the actual report data. Separate localized RDLs won't work for us. Localization will be managed by non-developers, so we've provided a UI for them to change localized strings themselves.
We'd very much prefer not to retrieve strings through a custom assembly, if we can help it. We've had trouble in the past deploying custom assemblies, and of course it introduces some debugging complexity as well.

All ideas are welcome.
Answer: I guess you just need a table on the db with everyone's country preference against their user ID. Then based on the user ID you can set the formatting accordingly.
Pretty bad practice though. Why can't you use User!Language?


Listview has been removed from react native error after adding react-native-gridview

Question: I have installed react-native-gridview and after that I am getting this error.

The line number shown in error is Media.js:134. It contains the following code.
<GridView data={this.state.dataList} itemsPerRow={2}
    renderItem={(item) => {
        return (
            <View style={{ flex: 1, backgroundColor: '#8F8', borderWidth: 1, margin: 8 }}>
                <Image style={styles.imageThumbnail} source={{ uri: item.path}} />
            </View>
        );
    }}/>

I can't understand why I am getting this error. I am not using any ListView
Please Help. Thanks.
Answer: The problem is that react-native-gridview is using Listview in their library as you can see here.

And now react-native stopped giving support to Listviews, rather now you
  can use FlatList, SectionList and modify them as per your requirement, as they have more features and stability.

 That's why you are getting the above error.
Comment: Accept it if it helps for you, Thanks :)


Using Angular Material Design ng-model date format works but firebug throws error

Question: I am trying to format a date time and it works but, firebug throws an error
This is my code.
<md-input-container>
<input ng-model="item.myDate| date:'yyyy-MM-dd'" disabled=""/>
</md-input-container>

So for instance if I put this: 2016-01-04T14:37:35.029
I do get this: 2016-01-04
but here is firebugs error:
Error: [ngModel:nonassign] Expression 'item.myDate| date:'yyyy-MM-dd'' is non-assignable. Element:
http://errors.angularjs.org/1.4.6/ngModel/nonassign?p0=item.myDate ....
Any suggestions?
Thank you.
Comment: Just FYI- I do not want to use ng-value as I am going to loose the page format.
or this
Answer: item.myDate = $filter('date')(item.myDate,'yyyy-MM-dd');

ng-model can't use date filter format. you can try above code in your js file.
Comment: If you explain how can i assign this to above question, 'll be appreciable. Thanks in advance.


how to concatenate multiple row or column data into one row or column from a text file while importing data into db2 table

Question: For Eg:
1)File has
ID|Name|job|hobby|salary|hobby2

2)Data:
1|ram|architect|tennis|20000|cricket
1|ram|architect|football|20000|gardening
2|krish|teacher|painting|25000|cooking

3)Table:
Columns in table: ID-Name-Job-Hobby-Salary
Is it possible to load data into table as below:
1-ram-architect-tenniscricketfootbalgardening-20000
2-krish-teacher-paintingcooking-25000

Command: db2 "Load CLIENT FROM ABC.FILE of DEL MODIFIED BY coldel0x7x keepblanks REPLACE INTO tablename(ID,Name,Job,Hobby,salary) nonrecoverable"
Comment: Kindly do add your efforts(in form of code) in your question, which is highly encouraged on SO, thank you.
Comment: What exactly is the problem or question? LOAD and IMPORT use a line from the input file as new row in the target table. If you need to more, search for ETL.
Comment: you can ignore this '-' symbol. I just used that for explaining purpose. As mentioned in the file,the data is delimited with | and I  what to load the data into a normal db2 table in the mentioned way that i have explained i.e i want to combine hobby and hobby2 and also  if we have another row for same ID i want to add those hobbies too and load into table as one row.
Answer: You cannot achieve what you think you want in a single action with either LOAD CLIENT or IMPORT.
You are asking to denormalize, and I presume you understand the consequences.
Regardless, you can use a multi-step approach, first load/import into a temporary table, and then in a second step use SQL to denormalize into the final table, before discarding the temporary table.
Or if you are adept with awk , and the data file is correctly sorted, then you can pre-process the file externally to a database before load/import.
Or use an ETL tool.
Answer: You may use the INGEST command instead of LOAD.
You must create the corresponding infrastructure for this command beforehand with the following command, for example:
CALL SYSINSTALLOBJECTS('INGEST', 'C', 'USERSPACE1', NULL);

Load your file afterwards with the following command:
INGEST FROM FILE ABC.FILE
FORMAT DELIMITED by '|'
(
  $id       INTEGER EXTERNAL
, $name     CHAR(8)
, $job      CHAR(20)
, $hobby    CHAR(20)
, $salary   INTEGER EXTERNAL
, $hobby2   CHAR(20)
)
MERGE INTO tablename
ON ID = $id
WHEN MATCHED THEN
    UPDATE SET hobby = hobby CONCAT $hobby CONCAT $hobby2
WHEN NOT MATCHED THEN
    INSERT (ID, NAME, JOB, HOBBY, SALARY) VALUES($id, $name, $job, $hobby CONCAT $hobby2, $salary);

Comment: what if the file does not contain headers.
Comment: The file **must not** contain any headers. The $ variables are assigned by you with any naming you like. Their number and types must be compatible with the file contents.
Comment: CALL SYSINSTALLOBJECTS('INGEST', 'C', 'USERSPACE1', NULL);   could you please explain what is C,USERSPACE1 and null specify in these parameters
Comment: Look at the [SYSINSTALLOBJECTS procedure](https://www.ibm.com/support/knowledgecenter/SSEPGG_11.5.0/com.ibm.db2.luw.sql.rtn.doc/doc/r0011876.html) description in the Db2 documentation.


Improving a SQL query when I need to select IN multiple fields combined together

Question: Here is my SQL query
SELECT date(metrics_session.created_at) as day, COUNT(metrics_session.user_id) as total_logins,
            sum(TIMESTAMPDIFF(MINUTE,metrics_session.created_at,metrics_session.completed_at)) as total_time_spent
            FROM metrics_session
            inner join metrics_training on metrics_training.id = metrics_session.training_id
            inner join metrics_course on metrics_course.id = metrics_training.course_id
            inner join metrics_user_training_cohort on  metrics_training.id = metrics_user_training_cohort.training_id
            inner join auth_user on auth_user.id = metrics_user_training_cohort.user_id

            WHERE metrics_session.created_at >= '2021-01-15'
            AND metrics_session.created_at <= '2022-10-15'
            AND metrics_session.completed_at IS NOT NULL
            AND metrics_session.user_id In (SELECT user_id from metrics_user_training_cohort  where user_id = 44 and training_id = 4)
            AND metrics_session.training_id In (SELECT training_id from metrics_user_training_cohort  where user_id = 44 and training_id = 4)

            #AND EXISTS(SELECT user_id,training_id from metrics_user_training_cohort  where user_id = 44 and training_id = 4)
            GROUP BY date(metrics_session.created_at) ORDER BY date(metrics_session.created_at)

the goal of this query is to select the sessions that were created by some user_id and are linked to some training_id , but only if in the table metrics_user_training_cohort I have that same user_id and training_id in the same row registered.
I managed to achieve that with the 2 last lines before GROUP BY:
AND metrics_session.user_id In (SELECT user_id from metrics_user_training_cohort  where user_id = 44 and training_id = 4)
AND metrics_session.training_id In (SELECT training_id from metrics_user_training_cohort  where user_id = 44 and training_id = 4)

however the repeated subquery used for the IN statement seems unnecessary to me and likely degrading performance, but I can't quite figure out a better way since the IN statement can only be used with 1 column.
The commented line is not the solution because it just checks for the existence of the row in the table in isolation without association to the sessions, but I left it there to give you a better idea what I'm trying to achieve.
Comment: table metrics_user_training_cohort seems to be the boss table so that should be in the from clause then inner joins will ensure everything else follows.
Answer: It is usually better to use JOIN or EXISTS instead of IN ( SELECT ... )
These may help:
metrics_session:  INDEX(created_at, completed_at, user_id, training_id)
metrics_user_training_cohort:  INDEX(training_id,  user_id)


Prove $\int_{0}^{\pi/2} \ln \left(x^{2} + (\ln\cos x)^2 \right) \, dx=\pi\ln\ln2 $

Question:
How to prove
  $$
\int_{0}^{\pi/2}\ln\left(\,x^{2} + \ln^{2}\left(\,\cos\left(\,x\,\right)\,\right) \,\right)\,{\rm d}x\ =\ \pi\ln\left(\,\ln\left(\, 2\,\right)\,\right)
$$

I don't know how to answer it.
When I asked this integral to my brother, after less than half hours he said it has a nice closed-form involving $\pi$ and $\ln\left(2\right)$ but, as always, he didn't tell me the closed-form and how to obtain it ( I didn't believe him and I think he tried to mess around with me ).
I have also searched the similar question here but it looks like nothing is similar or related.
Could anyone here please help me to obtain the closed form of the integral preferably with elementary ways ( high school methods )?. Any help would be greatly appreciated. Thank you.

Edit:
He is being a little bit nice to me today, he said the closed form is $\pi\ln\ln2$ and it's numerically correct.
This is not a duplicate problem, I am looking for a proof without using complex analysis.
Comment: The indefinite integral can be written as $$x\log\left(x^2+\log^2\cos x\right) - \int\dfrac{2x\left(x-\tan (x)\log\cos x\right)}{x^2+\log^2\cos x}\,dx$$ Note that if $f(x)$ is the denominator then the numerator is $xf'(x)$
Comment: This looks simpler
$$\int_{0}^{\pi/2} \ln \left(x^{2} + \ln^{2}\cos x \right) \, dx=2 \Re \left[\int_{0}^{\pi/2} \ln \ln \left( \frac{1 + e^{2ix}}{2} \right) \, dx\right] $$
Comment: @zibadawatimmy While I don't want to dispute that generally, I have come across integrals that were doable with normal integration but the computersystems couldn't do it. If (and only IF) Darksonn's approach works, that should be the way...That would also explain the double ln in the answer.
Comment: I have no idea, but perhaps you can use the identity $\Re(\ln(x+iy))=\dfrac12\ln(x^2+y^2)$ where $x,y\in\mathbb R$.
Comment: @imranfat I got stuck trying to solve for $x$ in $t=x^2+\log^2\cos x$
Comment: @Darksonn But that first part you don't need to integrate that. I assume that's what you meant? That's plug in work, and since it is an improper integral, you may have to work with L'Hospital or something. For the second one, if the num is the derivative of the denom, that would become an ln term?
Comment: [Wolframalpha]( http://wolframalpha.com/input/?i=Integrate+ln%28x%5E2%2B%28ln%28cos%28x%29%29%29%5E2%29+from+0+to+pi%2F2&x=0&y=0) doesn't even return an exact value or give a closed form for the indefinite integral. So calculus level is pretty much impossible, and there is some definite chain pulling going on here.
Comment: @imranfat True. And in any case I'm sure one of the resident integral masters will crack it and get many upvotes.
Comment: @Darksonn  That factor $x$ in the num creates a problem here...
Comment: @imranfat If $f(x)=x^2+\log^2\cos x$ and $t=x^2+\log^2\cos x$ then the integral is equal to $$x\log(x^2+\log^2\cos x)-\int\dfrac{f^{-1}(t)}{t}\,dt$$ where $f^{-1}(x)$ is the inverse of $f(x)$
Comment: I have changed the formatting of the title so as to
[make it take up less vertical space](https://math.meta.stackexchange.com/a/9686/290189) --
this is a policy to ensure that the scarce space on the main
page is distributed evenly over the questions.
See [here](https://math.meta.stackexchange.com/a/9730)
for more information. Please take this into consideration for future
questions. Thanks in advance.
Answer: Here is a real-analytic method.
We have

$$
\int_{0}^{\Large \frac{\pi}{2}} \ln \left(x^{2} + \ln^2\cos x\right) \, {\rm d}x=\pi\ln(\ln2) \tag1
$$

Proof. Let $s$ be a real number such that $-1<s<1$. One may use the following theorem (proved here)
$$
\int_{0}^{\Large \frac{\pi}{2}} \frac{\cos \left( s \arctan \left(\frac{x}{-\ln \cos x}\right)\right)}{(x^2+\ln^2\! \cos x)^{s/2}} \mathrm{d}x = \frac{\pi}{2}\frac{1}{\ln^{s}\!2}. \tag2
$$
We are then allowed to differentiate both sides of $(2)$
$$
\begin{align}
\partial_s \left. \left( \frac{\cos \left( s \arctan \left(\frac{x}{-\ln \cos x}\right)\right)}{(x^2+\ln^2\! \cos x)^{s/2}}\right) \right|_{s=0} &=-\frac 12 \ln \left(x^{2} + \ln^2\cos x\right) \\\\
\partial_s \left. \left( \frac{\pi}{2}\frac{1}{\ln^{s}\!2}\right) \right|_{s=0} &=-\frac{\pi}{2}\ln(\ln2)
\end{align}
$$
which gives the result $(1)$.
Comment: Wow! Very brilliant! +1
Comment: This is brilliant. Can you please look at my solution and let me know if it is incorrect? Many thanks!
Answer: As noted in the comments, the integral is:
$$2\Re\int_0^{\pi/2} \ln\ln\left(\frac{1+e^{2ix}}{2}\right)\,dx=2\Re\int_0^{\pi/2} \ln\left(\ln\left(1+e^{2ix}\right)-\ln 2\right)\,dx$$
Consider
$$f(x)=\ln(\ln(1+x)-\ln2)$$
Around $x=0$, the taylor expansion can be written as:
$$f(x)=f(0)+f'(0)x+f''(0)\frac{x^2}{2!}+f'''(0)\frac{x^3}{3!}+....$$
Replace $x$ with $e^{2ix}$. Notice that integrating the powers of $e^{2ix}$ would result in either zero or a purely imaginary number and since the derivatives of $f(x)$ at $0$ are real, we need to consider only the constant term i.e $f(0)$. Since $f(0)=\ln(-\ln 2)=\ln\ln 2+i\pi$, hence,
$$2\Re\int_0^{\pi/2} \ln\left(\ln\left(1+e^{2ix}\right)-\ln 2\right)\,dx=2\int_0^{\pi/2} \ln\ln 2\,dx=\boxed{\pi\ln\ln 2}$$
$\blacksquare$
Comment: Indeed, I agree with Mr. @FelixMarin. I think the correct form for Taylor expansion should be
$$f(x)=f(x)\bigg|_{x=0}+f'(x)\bigg|_{x=0}x+ f''(x)\bigg|_{x=0} \frac{x^2}{2!} + \cdots$$
Hence
$$f(e^{2ix})=f(e^{2ix})\bigg|_{x=0}+f'(e^{2ix})\bigg|_{x=0}(e^{2ix}) + f''(e^{2ix})\bigg|_{x=0} \frac{(e^{2ix})^2}{2!} + \cdots$$
Comment: Very nice Pranav! This is brilliant answer!! d(ˆ▽ˆ)b
Comment: Summon @VladimirReshetnikov! (‐^▽^‐)
Comment: Wait!? I'm missing something here. You said $f(x)=\ln(\ln(1+e^{\large2ix})-\ln2)$, right? But, then $f(0)\to-\infty$.
Comment: Nope, look at f(x) again.
Comment: Does the series converge ?. I'm worry about it because $\left\vert\,{\rm e}^{2{\rm i}x}\,\right\vert = 1$.
Comment: @PranavArora Thank you for the compliment. Concerning your answer, it would be nice to tell which determination you considered for $\log(x)$ and it would be nice to justify why you are allowed to switch $\int$ and $\sum$.
Comment: @OlivierOloa: Sorry, I do not know what does "determination for $\log(x)$" mean. About switching $\int$ and $\sum$, I did not do that, I integrate term by term. I integrated the first few powers to see that they result in either zero or an imaginary number so I kept only the first term and took the real part. Can you please answer the questions raised by OP and Felix? I do not have much knowledge about convergence of series and expansions, thanks!
Comment: @PranavArora You said "I integrated the first few powers to see that they result in either zero or an imaginary number so I kept only the first term and took the real part." This is the point: is the integral of the rest of your series really tending to  zero? I think yes it is, but I won't prove it now. Your reasoning is similar to the one I had given in my answer to your question about $\int_0^{\pi} \frac{x}{x^2+\ln^2(2\sin x)}\,dx,$ that's why I had dwelt with convergence issue there. Thanks!
Answer: A solution using complex analysis is given here by sos440.
Comment: Thanks for the link, but I'm looking for real analysis method. +1 anyway (>‿◠)✌


create date vector, change to factor and format

Question: I have the following code:
gsub("-","/",paste(cut(seq(as.POSIXct(Sys.Date(),format="%d-%b-%y"), by = "-1 day", length.out = 10),"days"),collapse = ","))

The output:
"2019/03/20,2019/03/19,2019/03/18,2019/03/17,2019/03/16,2019/03/15,2019/03/14,2019/03/13,2019/03/12,2019/03/11"

However the desired result is
'20/03/2019','19/03/2019','18/03/2019','17/03/2019','16/03/2019','15/03/2019','14/03/2019','13/03/2019','12/03/2019','11/03/2019'

How can I accomplish that ?
Regards
Answer: Not sure what you are trying to do but you can generate the required output by doing
format(Sys.Date() - 1:10, "%d/%m/%Y")

#[1] "20/03/2019" "19/03/2019" "18/03/2019" "17/03/2019" "16/03/2019" "15/03/2019"
#    "14/03/2019" "13/03/2019" "12/03/2019" "11/03/2019"


Proving there exists $V$ so that $\{x_0\}\times I\subset V\times I\subset U$

Question: Let $X$ be a topological space, and $I=[0,1]$. Consider $X \times I$ with the product topology. Now fix $x_0\in X$ and $U\subset X\times I$ an open that contains $\{x_0\}\times I$. Prove that there exists an open $V\subset X$ so that $\{x_0\}\times I\subset V\times I\subset U$
My attempt:
Since U is an open set in the product topology, $U=\bigcup( U_{x_0}\times I_i)$ where $I_i$ are open sets of I and $U_{x_0}$ is an open set of $X$ that contains $x_0$. Since I is compact $W$ is the finite union $W=\bigcup( U_{x_0}\times I_i)\subset U$.
Now I would need to find a subset of $U_{x_0}$ that also contained $x_0$, how?
Comment: Hint: Think about fundamental systems of neighbourhoods.
Answer: We suppose here that the topology used on $I$ is the stadard one
As $U$ is an open that contains $\{x_0\}\times I$, for all $i \in I$, there is an open $U_i \subseteq X$ that contains $x_0$ and an open $J_i \subseteq [0,1]$ that contains $i$ such that $(x_0,i) \in U_i \times J_i$.
$\mathcal J = \{J_i \mid i \in I\}$ is an open cover of $I$. Using the introduction remark, $I$ is compact and we can extract from $\mathcal J$ a finite subcover $\{J_{i_1}, \dots ,J_{i_n}\}$.
$V=\cap_{j=1}^n U_{i_j}$ is an open subset of $X$ that satisfies the conditions we're looking for.


a problem regarding conditional probability and binomial distribution.

Question: Die A has 4 red and 2 white faces whereas die B has 2 red and 4 white faces . A coin (fair) is tossed once . If it falls head , the game is carried on by throwing die A alone. If it falls tail die B is used . Let $X_n =1$ or $0$ according as the nth draw is white or red . and let $S_n = X_1 + X_2 +X _3 +\cdots+X_n$
now, i tried to find the expectation and variance of $S_n$ . and i think $S_n$  it follows Bin(n,1/2).
$P(X_n= 1)=P(X_n=1\mid \text{coin turned out to be head})\cdot0.5+P(X_n=1\mid \text{coin turned out to be tail})\cdot0.5= (4/6)\cdot(0.5) +(2/6)\cdot(0.5)=0.5$
so, $S_n $follows Bin (n, 0.5)]
and in that case , E($S_n$)=.5n and
Var($S_n$)=.25n----(1)
but if i solve it in this way :
Var($S_n$)=[Var($S_n$|coin turned out to be head)]*0.5+Var[($S_n$|coin turned out to be tail)]*0.5
=$[E(S_n|$coin turned out to be head$)-E(S_n)]^2$*0.5+$[E(S_n|$coin turned out to be tail$)-E(S_n)]^2$*0.5
implies  Var($S_n$) =2n/9+$n^2$/36-----(2)
what is the reason of difference between the two results obtained in (1) and (2) ?
my book says $S_n$ doesn't follow binomial (n, 0.5) . is it the reason of this error  ? but, why isn't it binomial ?
Comment: $E[S_n\mid \text{coin turned out to be head}]$ is meaningless because behind $S_n$ there are $n$ coin tosses. You could condition on $HHTH..TH$'s and then you would have to add $2^n$ products.
Comment: no ,you got it wrong. only once the coin is tossed. if it falls head, we take the die A and keep throwing it. that means, we don't throw the coin every time before  throwing the die. read my problem carefully please.
Comment: I followed your instructions to read your problem carefully and found that you don't seem to have written it carefully. Do you really want the two dice to have the same number of faces of each colour?
Comment: No, I was asking whether you really want the two dice to have the same number of faces of each colour. You just quoted the sentence that states that the two dice have the same number of faces of each colour.
Comment: sorry . edited.  :/ thank you .
Answer: First off, note that a binomial distribution is for the sum of $n$ independent identically distributed Bernoulli variables.  This is not the case here, since $\Pr(X_2=1|X_1=1)\ne\Pr(X_2=1|X_1=0)$, and hence we're not actually dealing with a binomial distribution.  The conditional distributions of $S_n$, however, are binomially distributed, which we will use to our advantage.
$S_n|Heads\sim Binom(n,\frac{2}{6})$ , and $ S_n|Tails\sim Binom(n,\frac{4}{6})$.  Also, due to the symmetry of the problem, the expected value is still $E(S_n)=\frac{n}{2}$
Also, in your variance calculation, the law of total variance( https://en.wikipedia.org/wiki/Conditional_variance ) says that it is actually:
$$Var(S_n)=Var(E(S_n|C))+E(Var(S_n|C)),$$
where $C$ represents whether the coin was heads($H$) or tails($T$). And so we need:
 $$E(Var(S_n|C)=Var(S_n|H)\cdot0.5+Var(S_n|T)\cdot0.5\\
=n(\frac{2}{6})(\frac{4}{6})\cdot0.5 + n(\frac{4}{6})(\frac{2}{6})\cdot0.5\\
=\frac{2n}{9}$$
and
$$Var(E(S_n|C))=[E(S_n|H)−E(S_n)]^2\cdot0.5+[E(S_n|T)−E(S_n)]^2\cdot0.5\\
=(\frac{2n}{6}-\frac{n}{2})^2+(\frac{4n}{6}-\frac{n}{2})^2\\
=\frac{n^2}{18}$$
And so your variance should actually be $\frac{4n+n^2}{18}$
Answer: $S_n$ doesn't follow $Bin(n,1/2)$ but follows $Bin(n,2/3)$ with probability $1/2$ and $Bin(n,1/3)$ with probability $1/2.$ These distributions have the same variance but not the same mean.
So your second approach is the right one.
Comment: Brent's answer explains the point fully.
Comment: thank you for your answer. sure , you are right. but i'll like it if you help me  to remove my confusion. .

say X is a discrete random  variable that takes values 1, 2, 3 ...n

now the PMF of X is given by , by the basic idea of PMF , f(k)=P[x=k] , k=1,2,...n.

here P[$X_n$= k]=  .5 . k=1,2 (ref : calculation shown in OP is it wrong ?) for all n.

and then $X_n$ can be regarded as Bernoulli random variable. and then sum of Bernoulli is binomial.  what is wrong in it ?