Understanding Primitive Polynomials in GF(2)?

Question: This is an entire field over my head right now, but my research into LFSRs has brought me here.
It's my understanding that a primitive polynomial in $GF(2)$ of degree $n$ indicates which taps will create an LFSR. Such as $x^4+x^3+1$ is primitive in $GF(2)$ and has degree $4$, so a 4 bit LFSR will have taps on bits 4 and 3.
Let's say I didn't have tables telling me what taps work for what sizes of LFSRs. What process can I go through to determine that $x^4+x^3+1$ is primitive and also show that $x^4+x^2+x+1$ is not (I made that equation up off the top of my head from what I understand about LFSRs, I think it's not primitive)?
Several pages online say that you should divide $x^e+1$ (where e is $2^n-1$ and $n$ is the degree of the polynomial) by the polynomial, e.g. for $x^4+x^3+1$, you do $(x^{15}+1)/(x^4+x^3+1)$. I can divide polynomials but I don't know what the result of that division will tell me? Am I looking for something that divides evenly? Does that mean it's not primitive?
Comment: You can find some good starting points on how to format mathematics on the site [here](http://meta.math.stackexchange.com/questions/5020). [This AMS reference](ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf) is very useful. If you need to format more advanced things, there are many excellent references on LaTeX on the internet, including StackExchange's own [TeX.SE](http://tex.stackexchange.com/) site.
Comment: Sorry, I was rushed when I was posting. I'll look it over.
Answer: For a polynomial $p(x)$ of degree $n$ with coefficients in $GF(2)$ to be primitive, it must satisfy the condition that $2^n-1$ is the smallest positive integer $e$ with the property that
$$
x^e\equiv 1\pmod{p(x)}.
$$
You got that right.
For a polynomial to be primitive, it is necessary (but not sufficient) for it to be irreducible. Your "random" polynomial
$$
x^4+x^2+x+1=(x+1)(x^3+x^2+1)
$$
fails this lithmus test, so we don't need to check anything more.
Whenever I am implementing a finite field of characteristic two in a computer program at the beginning I generate a table of discrete logarithms. While doing that I also automatically verify that $2^n-1$ is, indeed, the smallest power of $x$ that yield remainder $=1$. For an in situ example see the latter half of my answer to this question, where I verify that $x^3+x+1$ is primitive by showing that we need to go up to $x^7$ to get remainder equal to $1$.
Doing it by hand becomes tedious after while. There are several shortcuts available, if you know that $p(x)$ is irreducible and if you know the prime factorization of $2^n-1$. These depend on the fact the multiplicative group of $GF(2^n)$ is always cyclic. Your example of $p(x)=x^4+x^3+1$ is a case in point. It is relatively easy to decide that it is
irreducible. Then the theory of cyclic groups tells that the smallest $e$ will be factor of $15$. So to prove that it is actually equal to fifteen it suffices to check that none of
$e=1,3,5$ work. This is easy. The only non-trivial check is that
$$
x^5\equiv x^5+x(x^4+x^3+1)=x^4+x\equiv x^4+x+(x^4+x^3+1)=x^3+x+1\not\equiv1\pmod{x^4+x^3+1},
$$
and this gives us the proof.
Even with the shortcuts, finding a primitive polynomial of a given degree is a task I would rather avoid. So I use look up tables. My favorite on-line source is at
http://web.eecs.utk.edu/~plank/plank/papers/CS-07-593/primitive-polynomial-table.txt
After you have one primitive polynomial, you often want to find other closely related ones. For example, when calculating generating polynomials of a BCH-code or an LFSR of a Gold sequence (or other sequence with known structure) you encounter the following task. The given primitive polynomial is the so called minimal polynomial of any one of its roots, say $\alpha$. Those constructions require you to find the minimal polynomial of $\alpha^d$ for some $d$. For example $d=3$ or $d=5$ are very common. The minimal polynomial of $\alpha^d$ will be primitive, iff $\gcd(d,2^n-1)=1$, and this often holds.
Then relatively basic algebra of field extensions gives you an algorithm for finding the desired minimal polynomial. Space won't permit me to get into that here, though.
Comment: "Then relatively basic algebra of field extensions gives you an algorithm for finding the desired minimal polynomial. Space won't permit me to get into that here, though." -- any pointers along those lines?
Comment: What are algorithms for finding minimal polynomials in $GF(2)$?
Comment: is it this one? https://math.stackexchange.com/a/2234211/120
Answer: A good (not too theoretical) oveview is Kerl's "Computation in finite fields" (it is incomplete, sadly). It looks a bit at LFSRs too. BTW, any polynomial defines a LFSR, the point is that primitive polynomials give ones with nice properties.
Comment: thanks for the reference! I like [Saxena & McCluskey's algorithm](http://crc.stanford.edu/crc_papers/CRC-TR-04-03.pdf) for finding primitive polynomials.
Comment: crc.stanford.edu seems inaccessable; Saxena + McCluskey "Primitive Polynomial Generation Algorithms Implementation and Performance Analysis" is archived at https://www.researchgate.net/publication/251501522_Primitive_Polynomial_Generation_Algorithms_Implementation_and_Performance_Analysis and http://www.academia.edu/28494547


WPF Binding not being updated

Question: On my View model, I have the following property:
public Visibility IsModelBusy { get; set; }

I have a long processing task that does:
private void DoSomething(object obj)
{
    IsModelBusy = Visibility.Visible;
    OnPropertyChanged("IsModelBusy");
    DoHeavyWork();
    IsModelBusy = Visibility.Collapsed;
    OnPropertyChanged("IsModelBusy");
}

I have a UI element that is bound to IsModelBusy:
<Border Visibility="{Binding IsModelBusy, UpdateSourceTrigger=PropertyChanged}">
...
</Border>

PROBLEM
My Border never gets visible and the main window hangs while the heavy task is ongoing (I can't run this in a background thread)
I tried wrapping the property changed call in an action passed to a Dispatcher with no luck, the problem still persists.
Now if I do this:
private void DoSomething(object obj)
{
    IsModelBusy = Visibility.Visible;
    OnPropertyChanged("IsModelBusy");
    MessageBox.Show("What the...");  <=========
    DoHeavyWork();
    IsModelBusy = Visibility.Collapsed;
    OnPropertyChanged("IsModelBusy");
}

With the introduction of the MessageBox, the UI seems to process the property changed events and update correctly.
QUESTION
Without using background tasks, how can I force the UI to process the PropertyChanged events?
Comment: > I can't run this in a background thread - can you explain, why?
Comment: @Bob Two-way binding to Visibility does not make any sense.
Comment: Have you tried setting `Binding Mode` to `Two-Way`? I believe Visibility is default `One-Way`.
Comment: who's calling DoSomething()?
Comment: @Dennis Multithreading is not an option - this is a requirement :)
Answer: You're blocking the UI thread with your DoHeavyWork().
The Dispatcher cannot process any other operations (such as refreshing the UI) because it's busy executing your code.
Put that in a background thread.
Comment: -1. This does not answer my questionings at all. I know that `DoHeavyWork` is blocking my workflow. What I am after is why does `MessageBox` force the UI to refresh?
Comment: There is not technical argument about not using threads - the only problem are my requirements. I can't use multi-threading by requirement - isn't this a clear enough reason?
Comment: @GETah what kind of requirement is that? is this an exam or something?
Answer: After playing around with this a lot, I finally found the answers to my questions:

With the introduction of the MessageBox, the UI seems to process the property changed events and update correctly.

The message box forces the application to process its message queue, hence processing the property changed events and updating the UI.

Without using background tasks, how can I force the UI to process the PropertyChanged events?

There is no way around this - I kept the message box solution to force the UI to process all events

WPF Binding not being updated


error with a private static variable

Question: I have a class that has a private static variable,
private static counter = 0;

but it gives an error when I compile it:
Car.java:3:  <identifier>  expected
private static counter = 0;
                      ^

Does anyone know why it does this?  I don't understand what's wrong with it.
Here's the whole code:
public class Car
{
    private static counter = 0;
    private String name;

    public Car()
    {
    name = "car" +counter;
    counter++;
    }
}

Answer: You need to specify type of variable
private static int counter = 0;

Answer: You forgot the type. It seems that you mean
private static int count = 0;

error with a private static variable


How to get getSherlockActivity()?

Question: I am trying for a code that sends message using WhatsApp Application.  I found a useful code at this post.
When I paste the code into my eclipse it start showing me error for undefined method getSherlockActivity().
I tired import library files using ctrl+shift+o key and ctrl+space key. But it seems this method requires any special kind of library ( .jar ) file. I tried to search on google, but could not successed init.
Can anyone please where can I get this method ?
Comment: what does your activity extend?
Comment: extend SherlockActivity
Comment: You can find the jar file here http://actionbarsherlock.com/
Comment: @sayed.jalil, I found it, can you please post it as answer so that I can accept it and it can be helpful for future user.
Comment: Glad it worked. I have posted it as answer.
Answer: Use getActivity() instead, if you are not using Sherlock Library and you are inside Fragment. If you are using this code inside an Activity then you can just start with getContentResolver()....
Answer: You need to include the Sherlock library. You can find it Here: http://actionbarsherlock.com/
Answer: include the Sherlock library and use extend SherlockActivity not extend Activity

How to get getSherlockActivity()?


How to set Font size and font family in document using docx4j

Question: FileReader fr=new FileReader("E://HtmlToDoc//LETTER.html" );
BufferedReader br=new BufferedReader(fr);
while( (s=br.readLine())!= null ){
    html=html+s;}

html=""+html.substring(html.indexOf(""));

/************************ Setting Page Size   **********************************/
Docx4jProperties.getProperties().setProperty("docx4j.PageSize", "B4JIS");
String papersize= Docx4jProperties.getProperties().getProperty("docx4j.PageSize", "B4JIS");

String landscapeString = Docx4jProperties.getProperties().getProperty("docx4j.PageOrientationLandscape", "true");
boolean landscape= Boolean.parseBoolean(landscapeString);

WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(PageSizePaper.valueOf(papersize), landscape);

AlternativeFormatInputPart afiPart = new AlternativeFormatInputPart(new PartName("/hw.html"));
afiPart.setBinaryData(html.getBytes());
//afiPart.setBinaryData(fileContent);

afiPart.setContentType(new ContentType("text/html"));
Relationship altChunkRel = wordMLPackage.getMainDocumentPart().addTargetPart(afiPart);

// .. the bit in document body
CTAltChunk ac = Context.getWmlObjectFactory().createCTAltChunk();
ac.setId(altChunkRel.getId() );
wordMLPackage.getMainDocumentPart().addObject(ac);

// .. content type
wordMLPackage.getContentTypeManager().addDefaultContentType("html", "text/html");
wordMLPackage.save(new java.io.File("E://HtmlToDoc//" + "test.docx"));

This is my code converts from HTML to Word document. How to set font size and font family for this word document.
Answer: You're pulling HTML content in to a Word document as a collection of AltChunk instances, which means the HTML exists in the docx 'bundle' as separate file, and not as part of the flow of the actual Word document.
If you want to manipulate the imported content as native MS Word content, you need to import the source XHTML instead. This means that docx4j takes the mark-up and (some) related styles, converting them into the various constituent parts of a docx file (for example, table, text, run and paragraph elements). Once you have content imported in that way, you can style it as you would any other docx entities.


What does "Moderately slow, in 2" mean at the top of a piece of music?

Question:
I have a song that is 96bpm but it says "Moderately slow, in 2" at the top. Does this mean the song is actually 192bpm and that the person who wrote the notation decided to write it as 96bpm? Could someone explain what this is and why it is used?
It is different because this piece is in 4/4 and also, I was more interested to know why the sheet music is written this way. if "in 2" @ 96bpm is the same as 192bpm why not just write the sheet music in 192bpm?
Comment: According to your image, this piece is not in 4/4. The time signature indicates cut time, 2/2.
Comment: What's the time signature? I'm guessing the "in 2" part refers to the method of conducting.
Comment: @John Doe time signature is 4/4
Comment: @ Neal I read that thread before posting but it is different because this piece is in 4/4 and also, I was more interested to know why the sheet music is written this way. if "in 2" @ 96bpm is the same as 192bpm why not just write the sheet music in 192bpm? This is not covered in that post so mine is not a duplicate. Thanks
Comment: @armani With the suggested bpm, is there a note (quarter, eighth, half) associated with it?
Comment: @ John Doe, please see here, I took a photo of it https://ufile.io/du48y
Comment: @ Thanks Neal. I realize this now. I also have watched several videos on the topic of cut time and what it is etc so have a much better understanding. It is a bit confusing because you also get half-time which is the opposite of "cut time" if I am not mistaken
Answer: The photo you posted shows that the music is in "cut common time" (denoted by the crossed C time signature), which is another way of writing 2/2.  Your beat-note is a minim (half-note), so there are 2 beats per bar (measure).  The metronome marking is also clear: minim = 96 is 96 minims per minute. I do understand your confusion, though: the stipulation "in 2" is redundant in this case, adding nothing to understanding of the tempo.
Now, if the tempo marking was along the lines of Moderate, in 2 ♩=192 the "in 2" would convey some extra information, namely that the feel would be a 96 bpm 2-in-a-bar.
Comment: I don't know why the piece is notated like this because isn't this the same as 4/4 time? I can count 2/2 but I can also count 4/4 time just as well albeit much faster. Is music notated like this to be easier to read?
Comment: @armani — Halving the number of beats, but not the rate of notes, makes all the difference in the world to how the music "feels". 4-in-a-bar @ 192 feels cramped compared with 2-in-a-bar @ 96: the music "breathes" more at the slower tempo. Now there are occasions where one needs the music to have a frenetic cascade of beats, but this piece is not one of them.
Answer: It's notated in 4/4, but it's to be played in a 2/2 feel. Think 'One.. Two..'  rather than 'One, Two, Three Four'.   I suspect the mm mark of 96 refers to half notes, not quarters.  'Beats' can be any note length.   You've been told the 'beat' is a half-note by the 'in 2' instruction.
Also consider the possibility that the piece was notated by someone who isn't very good at notation.  He might not know quite what to ask for.
Comment: Yes the 96 refers to half notes but wouldn't this be identical to 192 @ quarter notes? When I listen to the song I find myself counting 4/4 not 2/2. The song is called "Do you remember" by Jack Johnson. Thanks


Find a permutation with the given square or cube

Question: Problem: find a permutation such that

$x^2 = (1\;3\;4\;5\;7)$,  $x\in S_7$
$x^3 = (1\;3\;4\;5\;7)$,  $x\in S_7$

Must find all possible solutions for $x$.
Progress
I have solved for the first part, $x=(57134)$ but I am not sure on how to prove that there is only one $x$ value.
Comment: Surely you are posing two separate problems, since we cannot have $x^2=x^3$ unless $x = x^2 = x^3$ is the identity map.
Comment: I have solved for the first part, x=(57134) but I am not sure on how to prove that there is only one x value
Comment: @hardmath Thanks for the comment on my solution; I had missed the "all possible solutions" part of the question.
Answer: Note that in cycle notation for permutations, $(1~3~4~5~7) = (5~7~1~3~4)$.
Part 1: The idea here would be to create a cycle that moved 1 to 3 after two moves, 3 to 4 after two moves, 4 to 5 after two moves, 5 to 7 after two moves, and 7 to one after two moves.
Then (arbitrarily and without loss of generality), 1 is first in our cycle notation, followed by something, then 3, then something, then 4. So we have $(1~a_1~3~a_2~4)$ as our cycle. Now we try to figure out what goes in place of $a_1$ and $a_2$. After 1 iteration of this permutation, 4 maps to 1. On the second iteration, it should map to five, so that $x^2(4) = 5$. Note that I'm viewing $x$ as a function with $x^2 = x \circ x$. We now have $x = (1~5~3~a_2~4)$. Next, we need $x^2(5) = 7$. The way to do that is to set $a_2 = 7$. Thus we see, and can confirm, that $(1~5~3~7~4)^2 = (1~3~4~5~7)$. There's a pair left over in $S_7$; we haven't moved 2 or 6. Since $(2~6)^2$ is the identity, we can set $x = (1~5~3~7~4)(2~6)$ as well.
Hopefully this helps; the teacher in me won't let me do the whole problem (or the actual proof) for you. :)


Criar um URL para abrir um arquivo PDF - PHP

Question: Boa tarde a todos,
Estou desenvolvendo um código para busca de palavras-chave nos dados do banco. Até aí, ok! Porém, estou patinando ao tentar abrir o arquivo referente ao resultado que achei.
Esse é o código para busca da palavra-chave:
<?php

// Include conexão com o bd.
include 'conexaoBD/conexao.php';
include 'teste.php';

$btn     = $_POST['btn'];
$p_chave = $_POST['palavra'];

if(isset($btn)){
    $busca = $p_chave;

    if($busca == null or $busca == " "){

        echo 'Digite a palavra-chave para pesquisar!';

    } else {

        $busca_div = explode(' ',$busca);
        $quant     = count($busca_div);
        $exibe_id  = array("");

        for($i=0; $i<$quant; $i++){
            $pesquisa = $busca_div[$i];

            $_sql       = "SELECT * FROM conteudo_dcm WHERE DCM_conteudo LIKE '%$pesquisa%';";
            $sql        = mysqli_query($conn,$_sql);

            $quant_cmps = mysqli_num_rows($sql);

            if($quant_cmps == 0){

                echo 'Nenhum resultado obtido!';

            } else {

                while($linha = mysqli_fetch_array($sql)){
                    $id       = $linha['DCM_id'];
                    $nome     = $linha['DCM_nome'];
                    $conteudo = $linha['DCM_conteudo'];

                    $_href = $_folder.$_DS.$nome; // Variável definida no arquivo "teste.php"

                    if(!array_search($id,$exibe_id)){
                        echo '<a href="<?php $_href; ?>">'.$nome.''."

".
                             substr($conteudo, 0, 600)." ...".
                             "
---------------------
";

                        array_push($exibe_id,$id);
                    }
                }
            }
        }
    }
}
?>

Minha dúvida está principalmente nesta parte do código (como montar a url refente ao arquivo que salvei no servidor).
echo '<a href="<?php $_href; ?>">'.$nome.''."

".
                                 substr($conteudo, 0, 600)." ...".
                                 "
---------------------
";

Comment: Eu estou chutando que a sua variável `$folder` está preenchida com o diretório dentro do sistema operacional onde você grava os arquivos, é isso mesmo? Se for o caso você tem que traduzir este caminho para a rota que leva até o arquivo entrando pelo http. Se puder colocar o trecho que cria esta variável eu posso tentar ajudar mais.
Comment: Sim @DiegoMartins, a variável $folder é o diretório onde os arq. estão armazenados. Segue o trecho que cria essa variável: " $_DS = DIRECTORY_SEPARATOR;
$_folder = dirname(__DIR__).$_DS.'03-OCR-PDFlib'.$_DS.'arqs_Teste'; "
Answer: Quando um arquivo PDF for aberto em um navegador, a primeira página do arquivo PDF será mostrada por padrão. Você pode adicionar uma sequência de caracteres no link HTML para que um arquivo PDF seja aberto e pule para uma página especificada ou defina o destino. Para usar um desses dois métodos, faça o seguinte:
Abrir um arquivo PDF em uma página específica
Para direcionar um link HTML em uma página em um arquivo PDF específico, adicione #page= [número da página] no final do URL do link.
Por exemplo, esse tag HTML abre a página 4 de um arquivo PDF denominado myfile.pdf:

Observação: se você usar locais do servidor UNC (\ nome_do_servidor\ pasta) em um link, defina o link para abrir um destino definido usando o procedimento na próxima seção. Se você usa URLs contendo endereços locais do disco rígido (c:\pasta), não é possível vincular aos números de página ou aos destinos definidos. Com produtos Adobe Acrobat 7.0, um link para um número de página somente funciona se você usar locais HTTP ou HTTPS. Os locais do servidor UNC somente funcionarão se você usar o método destinos definidos descrito na próxima seção deste documento.


dyld: Library not loaded: @rpath/MapboxMobileEvents.framework/MapboxMobileEvents

Question: I am just trying to install mapBox in my project, and I'm getting this error:

dyld: Library not loaded:
  @rpath/MapboxMobileEvents.framework/MapboxMobileEvents   Referenced
  from:
  /Users/digitalgravity/Library/Developer/CoreSimulator/Devices/D6A86A86-478C-4988-9BFF-1A0DA6B05566/data/Containers/Bundle/Application/049C7FB8-4B79-4428-8AF7-6D9D1FF2846B/ADFD.app/Frameworks/Mapbox.framework/Mapbox
  Reason: image not found
Comment: Please check this:https://github.com/mapbox/mapbox-gl-native-ios/issues/131
Answer: This usually means that you did not add Mapbox framework to Framework, Libraries and Embedded Content correctly or your Pods were not linked properly (depending on react-native version you are using)
 This was asked and answered already so check OS X Framework Library not loaded: 'Image not found'


Find all sequences whose range is contained in $\{0, 1, 2, ..., 9\}$ whose decimal expansion series have the same value.

Question: Define the series to be $\sum_{n=0}^\infty x_n 10^{-n-1}$ and find all sequences $x\neq y$ but $\sum_{n=0}^\infty x_n 10^{-n-1} =\sum_{n=0}^\infty y_n 10^{-n-1}$.
I don't see how this is ever true, I know for example that if x=99999....999 then the value of the series is $1$.
Answer: It's true whenever you have one series ends in an infinite repetition of 9's and the other series ends 1 higher in the previous digit and then has an infinite number of 0s.  For example:
$.0200000000000.....=.0199999999999....$,  by the fact that these sums are defined by convergence, and both converge to $.02$
Edit:  This is also the only case this is true, because we need the two sequences to converge to the same number but not be identical, and the only way for that to happen is for at every single partial sum we get smaller and smaller differences, which only happens in this case.  The formal proof of that follows from that logic.


Unable to resolve relative module paths when eslint run from sub-folder

Question: When I run eslint from the root folder of my repo everything runs fine, with no errors.
But when I run from a subfolder I get a ton of import/no-unresolved that don't happen when I run from root:
/reporoot/subfolder0/subfolder1/MyFile.js
  11:8   error  Unable to resolve path to module 'foo'  import/no-unresolved
  11:8   error  Missing file extension for "foo"        import/extensions
  14:97  error  Unable to resolve path to module 'foo'  import/no-unresolved
  14:97  error  Missing file extension for "foo"        import/extensions

Doesn't matter how I run. e.g.:
This will work:
cd /reporoot
eslint .

All of these commands will fail with error shown above:
cd subfolder0
eslint .

or
eslint subfolder0

or
eslint /reporoot/subfolder0/subfolder1/MyFile.js

Any idea what the issue is, or thoughts about how to fix it?
Answer: This is probably a problem with absolute paths in your imports according to this GitHub issue.
Try to set this in your .eslintrc.json (Or convert it to any other filetype if you don't use JSON)
"settings": {
    "import/resolver": {
        "node": {
            "extensions": [".js", ".jsx", ".ts", ".tsx"]
        }
    }
}

If the above doesn't work and you just want to get rid of these errors just add this instead:
"settings": {
    "import/no-unresolved": 0, // Turn off "Unable to resolve path to module ..." error
    "import/extensions": 0 // Turn off "Missing file extension for ..." error
}

Disabling this is not that big of a deal anyway because linters are pretty well known for having problems with pathing.
Comment: `'import/extensions': 0,` worked for me in `rules` but not in `settings`.


Especific Query in Symfony2

Question: i have an entity with my products, an i have a relation of one to many to another entity with the types and prices for each product.
In my galery view, i want to bring all the products with their types and prices respectively, to do something like this:
{% for product in products%}

{{ product.name }}

Description: {{ product.description }}

            {% for type in types %}

                {{ type.type }}

            {% endfor %}

             {% for type in types %}

                {{ type.price }}

             {% endfor %}

{% endfor %}

i think that i have to do only one query, where i find all the products with their prices and types. But I do not know how.
i have exactly this:
Catalogo.php
Class Catalogo {

/**
     * @var string
     *
     * @ORM\Column(name="articulo", type="string", length=70, unique = true)
     */
    private $articulo;

/**
     * @ORM\OneToMany(targetEntity="Unidades", mappedBy="catalogo")
     */
    protected $unidades;

Medidas.php
Class Medidas{

/**
     * @var float
     *
     * @ORM\Column(name="medida", type="float")
     */
    private $medida;

    /**
     * @var float
     *
     * @ORM\Column(name="precio", type="float")
     */
    private $precio;

    /**
     * @ORM\ManyToOne(targetEntity="Catalogo", inversedBy="unidades", cascade={"persist"})
     * @ORM\JoinColumn(name="catalogo_id", referencedColumnName="id")
     */
    protected $catalogo;

And i do this, but it doesnt work:
public function findByArticuloYPrecios()
    {
        $em = $this->getEntityManager();
        $repository = $em->getRepository('ProyectoAdminBundle:Catalogo');
        $query = $repository->createQueryBuilder('Catalogo')
        ->select("Catalogo, Unidades")
        ->from("Catalogo", "catalogo")
        ->leftJoin("catalogo.unidades", "medida")
        ->getQuery();

        try
        {
            return $query->getResult();
        }

        catch (\Doctrine\ORM\NoResultException $e) {
            return null;
        }
    }

The function return null.
Comment: Read [Doctrine Query Builder](http://docs.doctrine-project.org/en/latest/reference/query-builder.html)
Answer: If you have for example:
Product and some types in relation try to do this just like this:
 $query = $repository->createQueryBuilder('Catalogo')
    ->select("catalogo, unidades")
    ->from("Catalogo", "catalogo")
    ->leftJoin("catalogo.unidades", "unidades")
    ->getQuery()

Comment: In the second line you put the properties, in the third the name of the entity, and the property, and finally in the quarter line, the link and the property ???
Comment: Second: aliases to entities (aliases of mapped DB objects) Third: Product entity and its alias, Fourth: join type and its alias
Comment: Can you check what i modificated, because it doesnt work??
Comment: Try something like this above. and one more thing. If you create classes/write some code please do this in english. It is more clear.
Comment: Sorry but i am from Argentina. The code doesnt work. For me, the second line are the name of the properties that you are requesting, the theird line, the name of the entity and the alias, finally the fourth line, you have to put the link property and it alias. What you think ?

Especific Query in Symfony2


How to practice organ at home?

Question: Finding a real organ to practice can be cumbersome: it can be located quite far from your home and not always be available. Are there alternatives that allow one to practice at home (especially the pedals)? I was thinking of a keyboard with MIDI pedals: does it exist and is it expensive?
Edit: In particular, I am interested in a 2-octave pedal range, little DIY, and compact (apartment).
Comment: Short compass (1 or 2 octave) straight "electronic organ" pedal boards are relatively cheap - even free if you salvage one from a scrapped instrument. But a standard 30 or 32 note radial board isn't cheap, and is also quite big and heavy (some weigh close to 50 Kg or 100 pounds), won't necessarily fit under your existing manual keyboards at home, and you will probably need a proper bench as well. But most "traditional" organ builders now supply keyboards and pedal boards wired for MIDI, so that is the easiest part of the problem to deal with.
Comment: Googling for "midi organ pedals" will turn up alternatives from Hammond, Nord, and others.
Answer: I've seen organ pedalboards attached to a piano.  Thank goodness we now have electric keyboards which can easily emulate a multi-manual organ and its pedals.  If you want a 'RCO spec radiating & concave' pedalboard, it's going to cost you, I'm afraid.  But for a real enthusiast, a full organ console with pedalboard is not THAT expensive.  Here's Viscount Organs.  You probably paid more for your car. And it's difficult to kill anyone with an organ. Get one instead!
http://viscountorgans.net/
Answer: It'll depend on whether you need to play one octave pedals,straight, or more, radials. Some time ago, I used the pedalboard from an oldish Hammond two manual + 1 octave pedals, and re-wired them to make a separate pedal 'manual'. This was then MIDId through whatever synth I fancy, and works well. I guess you could find a two octave pedalboard if needed, and do the same. Got to say, it was a nice little project, and works well - there's also a Nanobass synth that fits with it, for a plethora of bass sounds.And a darn sight cheaper than those advertised...
Any synth or workstation will do the manual job for you, as they generally have the organ touch, so for not a lot, you could set yourself up with one/two manuals and the pedals below. And loads and loads of other sounds, apart from the inevitable (and gorgeous) Hammond sounds.
Comment: Hardly elecronics - more a soldering exercise. The cheapest cheerful way would be to find  two manual with pedals, pre-loved. Virtually being given away these days. Plug and play!
Comment: Does it always involve DIY electronics etc? I am more looking for a quick, compact solution.
Answer: There is a man called jan veen in the Netherlands who made a churchorgan system which is very capable of replacing a real organ for a fraction of the money.
Youtube Jan Veen organ
Comment: We prefer to have answers that have some detail in them. Can you add in some of the details of what components Jan Veen used to make his system?

How to practice organ at home?


Can anything be serialized as long as it implements Serializable?

Question: I've already seen this: How to test in java that a class implements serializable correctly
I just have a more general question. If you create an object (say a circle) like this (assume imports are there):
<code>class Circle implements Serializable {
     int radius;
     Circle(int radius){
         this.radius = radius;
     }

     public void updateRadius(int radius){
         this.radius = radius
     }

     public int getRadius(){
         return radius;
     }
}
</code>
Is that all that is needed for it to be serializable? Do I need to add more methods to it for it to be serialized properly? I have a class a lot more complex, but didn't feel like posting all of it when this should provide ample example.
Answer: All of the instance variables also need to be serializable as well. This can cause problems when you're working with an external library and your "serializable" class holds a reference to a non-serializable class.
Comment: @Steve good point! Tbh I never knew what that keyword was for
Answer: Yes, it's all you need as long as the transitive closure of all the referenced objects are all serializable.
Note this doesn't mean the deserialized object will actually work - that depends on the semantics of "Circle".  The easiest way to lose out is becase the new object will be
a copy, not the identical object.
Answer: Very simple answer.
Let's say you live in a certain province of good ol Canada that requires all your business communication to be conducted in French.
The name of your business is la chance. It performs debt-collection, spam-mail marketing and user tracking services.
Your parent company is la connerie. Your company does not have the facility to conduct debt-collection, spam-mail marketing and user tracking services in French. Anyway, your parent company la connerie conducts all transactions for your company anyway and they have the facility to conduct debt-collection, spam-mail marketing and user tracking services in French. So your company is safe from being raided by the provincial government authorities - no worries.
Actually la connerie does not have facilities to conduct debt-collection, spam-mail marketing and user tracking services in French because it is actually owned by a holding company du fumier. And du fumier has the facilities to conduct debt-collection, spam-mail marketing and user tracking services in French and does so for all its child entities.
So every little business entity under the du fumier umbrella can safely declare that they IMPLEMENT French debt-collection, spam-mail marketing and user tracking services without needing each of themselves the facilities to conduct such French business communication, because they depend on du fumier to do it for them.
One day, your company decided to acquire another company les merdes du chevre and their business is debt-collection. The company is newly set up and is actually an empty shell. but it is safe from the provincial French linguistic authorities because it can depend on your company to perform debt-collection in French. So les merdes du chevre can happily declare that they IMPLEMENT French debt-collection services without lifting a finger to do anything about it.
The next week, your company acquires another company les crapes des crabes whose business is selling crabby by-products. However, they do not have the facilities to sell crabby by-products in French. And because of that you will have to create a dept to IMPLEMENT selling crabby by-products in French. And failing to do so, the provincial linguistic authorities would take the EXCEPTION of hauling your company to court for not IMPLEMENTING selling crabby by-products in French.
But you can escape the prosecution/persecution by the linguistic authorities if you declare that les crapes des crabes is a TRANSIENT entity. You acquired it with intention of transferring it to british columbia and that you never had any intention to actively use that company to sell crabby by-products in the province.
Comment: ah I see... Thank you for this long and complex, but somehow clear and precise explanation on how this works!


Probability that $x^2+y^2 \leq 1$ for uniformly distributed random variables.

Question: $X$ and $Y$ are independent random variables uniformly distributed on $(0,1)$
Find $P(X^2+Y^2\leq1|X\leq Y)$
^conditional probability where | represents given
The final answer is $\frac{\pi}{4}$
So I know that I'm going to have to set up some sort of integral to solve this problem, but I'm confused where to start. Do I need to convert to radians first?
Comment: You are certain the answer is $\frac{\pi}{4}$?
Comment: yes I am, I have an answer key.
Answer: Note that $P(X\le Y)=1/2$ and the area of $\{(x,y)\in\mathbb{R}_+^2\ :\ x^2+y^2\le 1 \text{ and }x\le y \}$ is exactly the area of $\{(r\cos\theta,r\sin\theta)\ :\ r\le 1\text{ and }\theta\in[\pi/4,\pi/2]\}$. Therefore,
\begin{align*}P(X^2+Y^2\le1\,|\,X\le Y)&=\frac{1}{P(X\le Y)}P(X^2+Y^2\le1,\ X\le Y)\\
&=2\int_0^1\int_{\pi/4}^{\pi/2}r\,\mathrm{d}r\mathrm{d}\theta\\
&=\frac{\pi}{4}.
\end{align*}
Comment: Yes, good answer. I see that range is perfect.(+1)
Answer: Geometrically, the question is equivalent to finding the ratio of the area of a circular sector of angle $\pi/8$ and radius $1$, to the area of the isosceles triangle with vertices $(0,0), (0,1), (1,1)$. This is simply $(\pi/8)/(1/2) = \pi/4.$  This is because the locus of points that satisfy $0 \le X \le Y \le 1$ is the aforementioned isosceles triangle, and the added condition that $X^2 + Y^2 \le 1$ obviously corresponds to the intersection of this triangle with the unit disk centered at the origin.
Answer: We have $P(X^2 + Y^2 \leq1|X\leq Y)$
Note: $x = rcos\theta, y= r sin\theta$, hence $x^2 +y^2 = r^2$
We have a circle where $x \leq y$, hence a circle $\frac{\pi}{4} \leq \theta \leq \frac{5\pi}{4}$ and radius $0 \leq r \leq 1$
Using this we can construct:
 $$\int_0^1\int_{\frac{\pi}{4}}^{\frac{5\pi}{4}} r^3 \mathrm{d\theta dr}$$
$$=\int_0^1 r^3 * \pi \mathrm{dr}$$
$$=[\frac{r^4 * \pi}{4}]_0^1$$
$$=\frac{\pi}{4}$$
Note: $r^3$ is because $x^2 + y^2 = r^2$ then the Jacobian of transformation is $r$.
Comment: Maybe I'm missing something but it seems to me that you calculated $E[X^2+Y^21_{X\le Y}]=\int_{0}^1\int_{0}^1(x^2+y^2)1_{x\le y}\,\mathrm{d}x\mathrm{d}y$, and then did a strange change of variable considering the angle should be between $0$ and $\pi/2$.
Comment: @Ian How is $x\leq y$ at $(1,0)=0$
Comment: Sorry, I forgot the indicator function.
Comment: Maybe you missed that $X,Y$ are nonnegative since they are uniform on $[0,1]$?
Comment: @Ian Sorry, I did indeed miss that.


Determine if a 4-tuple exists

Question: Starting with 2,0,0,3, we construct the sequence 2,0,0,3,5,8,6,..., where each new digit is the mod10 sum of the preceding four terms. Will the 4-tuple 0,4,0,7 ever occur?
Any help is greatly appreciated. Since this problem is from a Working Backwards chapter, I have tried working with the desired four tuple and working backwards to determine other previous integers with no contradiction apparent. Thus, I am greatly confused.
Comment: Well, you can always keep constructing the original sequence until you repeat something, but I think a easier way would be to determine some invariant.

Maybe instead of mod $10$ you can try a smaller number?
Comment: I just wrote a program and my observation is that: The 4 tuple sequence repeats with the length of 1560. The 1st number is 2003, and 1560th number is 1200. You can see that 1561th number is again 2003. 0407 is the 1556th number. You can trace in the reverse order and can see it, that is, 2003 - 1200 - 7120 - 0712- 4071 - 0407.
Comment: So my suggestion is that if we can somehow prove that the sequence will come back to 2003, then it is easy to prove that 0407 will show up as well.
Comment: On the other hand, the rest of four digit numbers (there are 8440 of them) never shows up. I changed the seed to $2004$ (that didn't show up in the original loop) and I got 312 tuples cycling. So I guess that this sequence may be always come back to the seed (initial tuple). It would be interesting to see if somebody can prove it.
Comment: I also posted. Please check my sequence..
Answer:
[Lemma] The sequence will come back to the original tuple (in this case, 2003).

(Proof)
Choosing the next number is always deterministic. At the same time, identifying the previous number is also deterministic. As there are finite set of 4 digit numbers, at some point the sequence will run out. And then it will have to cycle. The initial number should be inside that cycle, as otherwise it would mean that the cycle has a branch (or a junction) that is not possible as the backward sequence is also deterministic.
$$\\$$
So, 2003 will show up 2nd time (and actually over and over again). For 2003 to show up the below sequence should happen:
$$0-4-0-7-1-2-0-0-3$$
Therefore, 0407 will show up.
Comment: The process is invertible (given four numbers, we can determine the previous as well as the next); therefore, the first time it repeats, we must come back to the original.  And it must repeat, since there are only finitely many possible 4-tuples.
Comment: If your program did this, then I must be wrong.
Comment: @fleabood, sorry about that. You were competing with a program. :-)
Comment: @Ted, But how can you say that the reverse sequence will come to the original number?
Comment: @Ted, for example, what I was thinking is that the cycle might be like (calling the initial tuple as $A$) $A-B-C-D-E-F-G-H-C-D-E-F-G-H-C-D-E-F-G-H-...$
Comment: Suppose the 4-tuples we get are $a_0, a_1, a_2, a_3, ...$.  At some point, two of them repeat, say $a_i = a_j$.  We may assume this is the first repeat we encounter.  If $i = 0$, then we have come back to the original.  If $i > 0$, then we have $a_{i-1} = a_{j-1}$ (because the process is invertible), so we have an earlier repeat, contradiction.
Comment: @Ted, my bad. Yes you are right. The sequence is fully deterministic so it should come back.
Comment: As all sequences are backtrackable and there is a maximum of 10,000 4 tuples it *must* repeat and before the repetition it *must* previously be 0,4,0,7,1
Comment: Good observations, but I am having trouble putting it all together. Could someone please explain the proof of why the desired 4-tuple occurs?
Comment: I rephrased everything. Please see if it helps.
Comment: Are you saying the the sequence 0 4 0 7 1 2 0 0 3, by working backwards will start with 2 0 0 3? So this will happen: 2 0 0 3,...,0 4 0 7 1 2 0 0 3 ?
Comment: I am just not convinced that we are guaranteed that 2003 will repeat and to know how many times it will.
Comment: Yes, that's right. 2003 will happen again, which means 0407 should happen too.
Comment: Okay, that's the key. I understand you're not convinced that 2003 will happen again. But are you convinced that the sequence will begin to cyclic in the end?
Comment: No please explain, if you could, why it would cycle in the end.
Comment: Okay, if it doesn't cycle, then there must be infinitely many possible tuples. But it is not possible. So it should be cycling. You may say "can it just keep going around without cycling", right?
Comment: Is there any initial 4-tuple that generates all possible 4-tuples (sort of like a de Bruijn sequence)?
Comment: @marty I don't think so, because there are already a couple of known initial tuples that generate partial cyclic sequences. If there exists a tuple that would generate all possible tuples then it would violate the lemma. These cyclic sequences should be mutually isolated.
Comment: @Analysis15 Let $A$ be the operation by which we go from one tuple to the next, e.g. $A(4, 0, 7, 1) = (2, 0, 0, 3)$. We know $A$ is invertible, call its inverse $A^{-1}$, that is, $A^{-1}(2, 0, 0, 3)  = (4, 0, 7, 1)$. Let $x_0=(2, 0, 0, 3)$, then we're looking at the sequence $A^nx_0$. Since there are only finitely many possible tuples, we must have $A^nx_0=A^mx_0$ for $m$ and some $n>m$. But then $A^{n-m}x_0=x_0$.
Answer: Okay, from any x, y, z, w  we can determine the previous term and there is no choice for variation.  (As A + x +y + z = w has only one answer.)
As there are only finitely many 4-tuples the sequence must eventually repeat.
2,0,0,3 must come from
1,2,0,0 which must come from
7,1,2,0 which must come from
0,7,1,2 which must come from
4,0,7,1 which must come from
0, 4, 0,7.
Thus the sequence must repeat and 0,4,0,7 will appear near the very end of the cycle.

Determine if a 4-tuple exists


Specialize template class for different parameter sets

Question: Suppose I have a template struct like
template <typename T> struct Parser {
  //specializations are expected to have these methods
  inline static const byte* objectEnd(const byte* begin, const byte* end);
  inline static const byte* tryRead(const byte* begin, const byte* end, T* obj);
}

It is used in different classes, some of which are also template classes (so they may not have full info about what class they pass to Parser as a parameter).
Implementing Parser for any given type is easy, like this:
template<> struct Parser<text_line> {
  inline static const byte* objectEnd(const byte* begin, const byte* end){
    return helper::NextByteOrEnd<'\n'>(begin, end);
  }
  inline static const byte* tryRead(const byte* begin const byte* end, text_line* obj){
    const byte* lf = objectEnd(begin, end);
    obj = text_line(begin, lf);
    return lf==end ? lf : lf+1;
  }
}

I can specialize Parser for a family of templates, as well:
template<int sz> struct Parser<be_uint<sz>> {
  inline static const byte* objectEnd(const byte* begin, const byte* end){
    return begin+be_uint<sz>::size > end ? begin : begin+be_uint<sz>::size;
  }
  inline static const byte* tryRead(const byte* begin const byte* end, be_uint<sz>* obj){
    if(begin + be_uint<sz>::size > end) return begin;
    obj = be_uint<sz>::read(begin);
    return begin + be_uint<sz>::size;
  }
}

But what if I want to specialize Parser for some other set of types? Suppose I have a type predicate, say, std::is_base_of<MyHeader, T> and I want to write something like
//not actual code - how would I write this?
template<typename Header> struct Parser {
  static_assert(std::is_base_of<MyHeader, Header>::value, "Wrong!");
  inline static const byte* objectEnd(const byte* begin, const byte* end){
    //MyHeader-specific code here
  }
  inline static const byte* tryRead(const byte* begin const byte* end, Header* obj){
    //MyHeader-specific code here
  }
}

Adding optional parameters to the initial definition of Parser, like
template <typename T, bool MyHeaderFlag = std::is_base_of<MyHeader, T>::value>
struct Parser { //...

doesn't seem like a good idea - I (or any other programmer) may want to use other predicates, say, my_types::is_scientific<T>.
The problem seems like something you could resolve with SFINAE (there's a problem of what should happen if one type fits several predicates - I prefer that it wouldn't result in compiler error, but it isn't very important since such Parser specializations are likely to be palced in .cpp-files). But I couldn't find a way to do this.
Just to be clear, there is no constraint on preserving the exact definition of `Parser' or its methods (or even it being a template), as long as client code can write something like
Parser<TypeArg>::objectEnd(block.begin, block.begin+block.size)

without caring what TypeArg actually is.
Comment: @Jonas If I write the whole template specialization (_including declaration_) in .cpp file, how exactly that is wrong?
Comment: Don't store template functions in cpp-files: https://stackoverflow.com/questions/115703/storing-c-template-function-definitions-in-a-cpp-file
Answer: If you want to make specialization for some set of types, best way is to add second template parameter to your base template.
You can do that with bool, or with actually type and use std::enable_if in specializations.
I prefer the second way.
template <typename T, typename = void> struct Parser {
  //specializations are expected to have these methods
  inline static const byte* objectEnd(const byte* begin, const byte* end);
  inline static const byte* tryRead(const byte* begin, const byte* end, T* obj);
}

and specialization example
template<typename Header>
struct Parser<Header, typename std::enable_if<std::is_base_of<MyHeader, Header>::value>::type> {
  inline static const byte* objectEnd(const byte* begin, const byte* end){
    //MyHeader-specific code here
  }
  inline static const byte* tryRead(const byte* begin, const byte* end, Header* obj){
    //MyHeader-specific code here
  }
}


Scala: slice() does not perform as expected

Question: I am writing a small piece of code that will traverse a 1000 digit number, taking 13 digits at each step. For e.g. in the first iteration it should take digits at places 0-13, in the next iteration it should take digits at place 1-14 and so on. Here is my code but my slice keeps getting smaller as i traverse over the large number. I want to slice 13 digits from the original string each time. What am i doing wrong?
val largeNumber = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
var current13Digits = ""

for (iterator <- 0 to (largeNumber.length-13))
  {
            println("CURRENT VALUE OF ITERATOR IS " + iterator)
            current13Digits = largeNumber.slice(iterator,13)
            println("CURRENT 13 DIGITS ARE " + current13Digits)
  }

Output is as follows and it drops digits after every slice. What am i doing wrong?
CURRENT VALUE OF ITERATOR IS 0
CURRENT 13 DIGITS ARE 7316717653133
CURRENT VALUE OF ITERATOR IS 1
CURRENT 13 DIGITS ARE 316717653133
CURRENT VALUE OF ITERATOR IS 2
CURRENT 13 DIGITS ARE 16717653133
CURRENT VALUE OF ITERATOR IS 3
CURRENT 13 DIGITS ARE 6717653133
CURRENT VALUE OF ITERATOR IS 4
CURRENT 13 DIGITS ARE 717653133
CURRENT VALUE OF ITERATOR IS 5
CURRENT 13 DIGITS ARE 17653133
CURRENT VALUE OF ITERATOR IS 6
CURRENT 13 DIGITS ARE 7653133
CURRENT VALUE OF ITERATOR IS 7
CURRENT 13 DIGITS ARE 653133
CURRENT VALUE OF ITERATOR IS 8
CURRENT 13 DIGITS ARE 53133
CURRENT VALUE OF ITERATOR IS 9
CURRENT 13 DIGITS ARE 3133
CURRENT VALUE OF ITERATOR IS 10
CURRENT 13 DIGITS ARE 133
CURRENT VALUE OF ITERATOR IS 11
CURRENT 13 DIGITS ARE 33
CURRENT VALUE OF ITERATOR IS 12
CURRENT 13 DIGITS ARE 3
CURRENT VALUE OF ITERATOR IS 13
CURRENT 13 DIGITS ARE
CURRENT VALUE OF ITERATOR IS 14
CURRENT 13 DIGITS ARE
CURRENT VALUE OF ITERATOR IS 15
CURRENT 13 DIGITS ARE .....

Comment: Looks like you wish to use `.sliding(13)`
Comment: You misunderstand the slice arguments. The second is the absolute end index, not the slice length. Have a look at the Scaladoc.
Answer: Thanks, sliding works perfectly.
val current13Digits = largeNumber.sliding(13)
while(current13Digits.hasNext)
  {
    current13DigitsAsString = current13Digits.next()
    println("CURRENT 13 DIGITS ARE " + current13DigitsAsString
    ...
  }

Comment: `largeNumber.sliding(13).foreach(s => println("CURRENT 13 DIGITS ARE " + s))`


Log transformation

Question: Supose I have a series of numbers from 1 to 10. Their mean value is 5.5. Now supose I apply some transformation like $y=2x+1$. Now their mean value is 12. Now, if I want to get back the original mean, I apply the inverse function, which in this case is $x=(y-1)/2$.
Simple.
Now I want to do the same, but with the $log$ function.
So, I first apply the $y=log(x)$ function and then take the mean. I get a value of 1.51. But then, if I take the inverse $x=e^y$, I get a value of 4.53 and not the original 5.5.
What is happening?
Comment: Have you heard of the AM-GM inequality?
Comment: No, I will check it out. I much apreciated your answer.
Answer: Your first function is linear. Your other one isn't. Calculating the mean is a linear process so it is maintained over your linear transformation while it isn't for a non-linear transformation.
Comment: I disagree: http://math.stackexchange.com/questions/1398150/the-logarithm-is-non-linear-or-isnt-it
Comment: In the context that OP was asking. You'll just confusing him further throwing higher level math at him.
Comment: What the word 'linear' means in middle school evolves to something different at university. Based on the OP's question I was placing him near the beginning of that journey.
Answer: Your first function is linear. Therefore,
$$
\frac{1}{10}\sum_{i=1}^{10}f(X_i) = \frac{1}{10}\sum_{i=1}^{10}(2X_i + 1) = 2\frac{1}{10}\sum_{i=1}^{10}X_i + 1 = f\left(\frac{1}{10}\sum_{i=1}^{10}X_i\right).
$$
This doesnt work for the logarithm and the exponential function, since these aren't linear.
Comment: I disagree: http://math.stackexchange.com/questions/1398150/the-logarithm-is-non-linear-or-isnt-it
Answer: What you call the mean is actually the arithmetic mean,
$$
\mathrm{AM}(X) = \dfrac{1}{n} \cdot \sum\limits_{k=1}^{n} x_k.
$$
The procedure that you describe in your question is the way the geometric mean is computed:
$$
\begin{array}{rcccl}
\exp\left( \mathrm{AM}(\ln(X)) \right)
  &=& \exp\left( \dfrac{1}{n} \cdot \sum\limits_{k=1}^{n} \ln(x_k) \right) \\
  &=& \exp\left( \dfrac{1}{n} \cdot \ln\left( \prod\limits_{k=1}^{n} x_k \right) \right) \\
  &=& \exp\left( \ln\left( \left( \prod\limits_{k=1}^{n} x_k \right)^{\frac{1}{n}} \right) \right) \\
  &=& \left( \prod\limits_{k=1}^{n} x_k \right)^{\frac{1}{n}}
  &=& \mathrm{GM}(X).
\end{array}
$$
By an inequality known already by the Babylonians and formalized by Jensen, the geometric mean is always smaller or equal to the arithmetic mean, i.e.
$$
\mathrm{GM}(X) \leq \mathrm{AM}(X).
$$
The mathematical reason for this is that the logarithm is a concave (or negative convex) function. Unfortunately, the concept of convexity is often confused with the concept of non-linearity (see this or this).

Log transformation


Swift 2 OSX How do I use a loop at the end of a series of completions which includes a data task?

Question: I'm using completion blocks for each of my functions (to avoid using a while isDoingSomething loop).
I get the expected array when all the blocks complete.  But when I try to loop through this final array, it loops continually as expected but without ever resuming the NSURLSessionDataTask in Request.sendRequest(..) for each iteration.
ViewController.swift
import Cocoa

class ViewController: NSViewController {
    @IBOutlet weak var runButton: NSButton!
    @IBOutlet weak var visitsTextField: NSTextField!

    var accessToken = ""
    var cookies = [NSHTTPCookie]()
    var data = NSData?()
    var userIds = [String]()
    var usernames = [String]()
    var contentsOfURL = NSString()

    @IBAction func runButtonAction(sender: AnyObject) {
        run({
            // if I remove the loop and visit only one profile, it completes OK
            for username in self.usernames {
                let profileVisitor = ProfileVisitor(profile: username)
                profileVisitor.visit({

                })
            }
        })
    }

    func run(completion: () -> Void) {
        let runManager = RunManager(desiredVisits: Int(visitsTextField.stringValue)!)
        runManager.parseJSON({
            self.usernames = runManager.usernames
            completion()
        })
    }
}

RunManger.swift
import Cocoa

class RunManager: NSObject {
    var data = NSData?()
    var desiredVisits = Int()
    var usernames = [String]()
    var userIds = [String]()

    init(desiredVisits: Int) {
        self.desiredVisits = desiredVisits
    }

    func parseJSON(completion: () -> Void) {
        let jsonLimit = 40
        var profileNames = [String]()
        let finalVisits = desiredVisits % jsonLimit
        let repeats = (desiredVisits / jsonLimit) + 1
        let json: [String:NSObject] = [..., "limit":jsonLimit]

        let url = "https://www.awebsite.com/1/path1/path2/path3"
        let URL = NSURL(string: url)!

        let vis = URLVisitor(URL: URL, params: "", method: "POST", jsonParams: json as! [String : NSObject])

        vis.execute({
            for i in 1..<repeats {

                if vis.data != nil {
                    do {
                        let data = vis.data!
                        let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)

                        if let _usernames = json["data"] as? [[String: AnyObject]] {
                            for username in _usernames {
                                if let username = username["username"] as? String {
                                    self.usernames.append(username)
                                }
                            }
                        }
                    } catch {

                    }
                }
            }
            completion()
        })
    }
}

URLVisitor
import Cocoa

class URLVisitor: NSOperation {
    var authorizationHeader = ""
    var contentsOfURL = NSString()
    var jsonParams = [String: NSObject]()
    var isConnected = false
    var method = String()
    var params = String()
    var statusCode = Int()
    var cookies = [NSHTTPCookie]()
    var URL: NSURL?
    var isVisiting = false
    var task = NSURLSessionDataTask()
    var data = NSData?()

    init(URL: NSURL, params: String, method: String, jsonParams: [String:NSObject]) {
        self.URL = URL
        self.params = params
        self.method = method
        self.jsonParams = jsonParams
    }

    func execute(completion: () -> Void) {
        let request = Request(URL: URL!, params: params, method: method, jsonParams: jsonParams)

        if !self.cookies.isEmpty {
            request._setCookies(self.cookies)
        }

        request._setAuthorizationHeader(self.authorizationHeader)
        request.sendRequest ({
            self.contentsOfURL = request.contentsOfURL
            self.statusCode = request.getStatusCode()
            self.data = request.data
            completion()
        })
    }
}

Request
import Cocoa

class Request: NSOperation {
    var authorizationHeader = ""
    var contentsOfURL = NSString()
    var data: NSData?
    var jsonParams = [String:NSObject]()
    var isConnected = false
    var method = String()
    var params = String()
    var statusCode = NSHTTPURLResponse().statusCode
    var session = NSURLSession.sharedSession()
    var url = String()
    var URL = NSURL()
    var cookies = [NSHTTPCookie]()

    init(URL: NSURL, params: String, method: String, jsonParams: [String:NSObject]) {
        self.jsonParams = jsonParams
        self.method = method
        self.params = params
        self.URL = URL
    }

    func sendRequest(completion: () -> Void) {
        let session = NSURLSession.sharedSession()
        let request = NSMutableURLRequest(URL: URL)
        request.HTTPMethod = method

        if jsonParams.count != 0 {
            do {
                let jsonData = try NSJSONSerialization.dataWithJSONObject(jsonParams, options: .PrettyPrinted)

                request.setValue("aplication/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
                request.HTTPBody = jsonData
            } catch {

            }
        } else {
            request.HTTPBody = self.params.dataUsingEncoding(NSUTF8StringEncoding)
        }

        let task = session.dataTaskWithRequest(request) {
            (data, response, error) in

            NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(self.cookies, forURL: self.URL, mainDocumentURL: nil)
        if data != nil {
            self.data = data!
            print(data)
            do {
                swiftlet responseHeaders = response as! NSHTTPURLResponse
                self.statusCode = responseHeaders.statusCode

                switch self.statusCode {
                case 200:
                    print("200: OK. getting contentsOfURL and cookies")
                    self.contentsOfURL = try NSString(contentsOfURL: self.URL, encoding: NSUTF8StringEncoding)
                    self.cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(self.URL)!

                    case 400:
                        print("400: page not found on web")

                    case 404:
                        print("404: page not found on server")

                    case 407:
                        print("407: failed authenticate proxy credentials")

                    default:
                        print("unable to get statusCode")
                    }
                } catch {

                }
            } else {
                print("\(self.statusCode): unable to get response ")
            }
            print("completing")
            completion() // continue inside request call
        }
        task.resume()
    }

    func _setAuthorizationHeader(authorizationHeader: String) {
        self.authorizationHeader = authorizationHeader
    }

    func _setCookies(cookies: [NSHTTPCookie]) {
        self.cookies = cookies
    }

    func getStatusCode() -> Int {
        return self.statusCode
    }

    func getContentsOfURL() -> NSString {
        return self.contentsOfURL
    }
}

Answer: I'm guessing that you didn't intend to declare a local variable for session in the sendRequest method of your Request class.
 let session = NSURLSession.sharedSession()

The local session variable hides your class's session member and will go out of scope as soon as the function finishes (which drops the whole session and task with it).
[EDIT] I just noticed your local variable is using the sharedSession so even if it goes out of scope, the task should remain alive because the session is supposed to keep a strong reference to it (according to the documentation).
The problem must be something else.
Answer: I ended up using a semaphore dispatch and this did the trick.
func sendRequest() {
    let semaphore = dispatch_semaphore_create(0)
let task = session.dataTaskWithRequest(request) {
    // ...
    dispatch_semaphore_signal(semaphore)
}
task.resume()
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)

}


Classificação Automomática com critério de desempate

Question: Boa tarde, utilizando a classificação automática do excel, é possível criar níveis e subníveis? Por exemplo, estou criando uma planilha de futebol e quero ordenar primeiramente por pontuação e caso haja empate, quem tem maior Saldo de gols fica na posição acima. Tentei utilizar os níveis de classificação, porém ele fica sempre alternando ou pega a maior pontuação ou maior saldo de gols. Gostaria que fosse primeiro pontuação e caso tenha empate, quem tem maior saldo de gols fique na frente.
Answer: Boas,
penso que assim resolve o teu problema.


Is it appropriate to calculate odds ratios between groups matched on covariates (propensity scores)?

Question: I have a data set that includes a primary dichotomous independent variable (e.g., smoking), a primary dichotomous dependent variable (e.g., chronic back pain), and several covariates (e.g., diagnosis of several mental disorders, age, sex). I have calculated propensity scores for smoking using the covariates of interest. As an output, I am given a data file that includes only individuals who have been matched. Lets say I have 1000 smokers and 1000 non-smokers, with both groups matched on the covariates. Note that by "matched" I mean the two samples share similar means on the covariates, not that smokers are matched with non-smokers with similar propensity scores.
I am interested in seeing if individuals who smoke are more likely to have chronic pain in this sample matched on the covariates of interest. To do this, I would typically cross tabulate smoking/non-smoking and pain/no pain and calculate odds ratios.
Is it still appropriate to calculate odds ratios after a sample is matched on propensity scores based on covariates?
Does changing the number of participants in the control group create any problems? For instance, I could perhaps have 1000 smokers and 4000 non-smokers and calculate odds ratios using these numbers.
My intuition tells me that doing this is fine, but I want to make sure since I have never seen it done.
Answer: Yes, it is appropriate to calculate odds ratios on samples stratified on covariates by means of propensity scores. Some researchers believe you need to take the matched nature of the data as a sign that the groups are not independent, but this is not necessarily the case (Schafer & Kang, 2008; http://www.ncbi.nlm.nih.gov/pubmed/19071996).
The number of individuals in your control group should not matter as the proportions of individuals who fit within your independent variable classes should be the same. Keep in mind current recommendations on the proportion of individuals to match in your control group compared to your treatment group (Austin, 2010; http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2962254/).
Note that matching on the propensity scores rather than stratifying on the propensity scores (as your are suggesting) would likely lead to less biased estimates (http://www.ncbi.nlm.nih.gov/pubmed/17187347).


Como fazer uma query de um relacionamento polimórfico em Rails 3/4?

Question: Eu tenho uma tabela jobs e uma tabela activities. Um Job pode ter várias Activities. O relacionamento é polimorfico.
Tabelas:
job         activities
----------- -------------
id          id
...         target_id
            target_type
            ...

Classes dos modelos:
class Job < ActiveRecord::Base
  # ...
  has_many :activities, :as => :target, :dependent => :delete_all
  # ...
end

class Activity < ActiveRecord::Base
  # ...
  belongs_to :target, :polymorphic => true
  # ...
end

O estado de um dado Job é igual ao estado da última Activity criada para o Job.
Job +-> Activity 1 - state: new        |
    +-> Activity 2 - state: submitted  +--> Estado desse Job é approved
    `-> Activity 3 - state: approved   |

Qual a melhor maneira de fazer uma query que traga todos os Jobs que estejam num determinado estado, considerando ActiveRecord do Rails 3/4?
Também me ocorreu agora uma ideia de, ao invés de fazer essa query, usar algo como os "counter caches" fazem e desnormalizar esse relacionamento. Eu criaria um campo redundate chamado state no modelo Job e manteria os dois em sincronismo usando um after_create no modelo Activity. Algo assim:
after_create :update_state

def update_state
  target.update_attribute(state: self.state) if target.respond_to?(:state)
end

Seria essa uma alternativa viável?
Answer: Considerando que você está procurando alternativas a query, você poderia utilizar a gem https://github.com/pluginaweek/state_machine

Com o controle de estados e a possibilidade de executar métodos nas mudanças de um estado para outro você resumiria tudo para algo do tipo
  after_transition :to => :submitted do |transition|
    # Sincroniza ou executa o que você quiser após o job ir para o estado submitted
  end

  # Atividade muda o estado de acordo com a máquina que você definiu, sem
  # você se preocupar em dizer o estado que a atividade deve ir
  activity.next

Apesar de parecer mais díficil utilizar uma máquina de estados, no seu caso diminuiria a complexidade do sistema como um todo.
Answer:
Queres trazer todos os jobs approved de um objeto?
Job.first.activities.where(state:'approved')

Queres trazer todos as activities que estão relacionadas a jobs?
Job.joins(:activities).where(activities:{state:'approved')

porém recomendo criar um scope para isso

o proprio active record vai preparar o sql com a query targetable_id = x e targetable_type = 'Job'

também recomendo usar state_machine


Priority Web SDK vs REST API

Question: When developing a website using Priority's new tools, in which cases would I be better served accessing Priority using the Web SDK than by using the REST API?
How about vice-versa?
Comment: I've added the tag. As a courtesy may you update (or write) the tag usage info?
Comment: thanks for the up-votes, but don't do it as they get corrected. https://stackoverflow.com/help/serial-voting-reversed
Answer: It depends on you needs.
REST API is mostly used to integrate with other applications while WEB SDK is used for building stand-alone applications.
You may of course use them both in the same app.
There are some technical differences:

REST API executes triggers at a row level while WEB SDK executes
triggers at a field level.
REST API has no support for procedures and choose/search
lists while the WEB SDK does.

I would recommend using the REST API for large data retrievals and the WEB SDK for smaller request.

Priority Web SDK vs REST API


Finding $\lim_{n\rightarrow \infty}\frac{1}{n^2}\sum^{n}_{r=0}\ln\binom{n}{r}$.

Question: Finding $\displaystyle \lim_{n\rightarrow \infty}\frac{1}{n^2}\sum^{n}_{r=0}\ln\binom{n}{r}$.
My Try: Using $\text{A.M G.M H.M}$
$$ \frac{1}{n+1}\sum^{n}_{r=0}\binom{n}{r}\geq \sqrt[n+1]{\prod^{n}_{r=0}\binom{n}{r}}\geq \frac{n+1}{\sum^{n}_{r=0}\frac{1}{\binom{n}{r}}}$$
$$\bigg(\frac{2^n}{n+1}\bigg)^{\frac{1}{n}}\geq \bigg(\prod^{n}_{r=0}\binom{n}{r}\bigg)^{\frac{1}{n(n+1})}\geq \bigg(\frac{n+1}{\sum^{n}_{r=0}\frac{1}{\binom{n}{r}}}\bigg)^{\frac{1}{n}}$$
Can anyone please explain is my process is right. if not how can i solve it .Help me please. Thanks
Comment: I think the question might be hinting towards relation between Reimann sum and integrals
Comment: https://math.stackexchange.com/questions/2972852/product-of-binomials/2972969#2972969
Comment: https://math.stackexchange.com/questions/4531304/a-limit-that-has-binomials-lim-n-to-infty-sqrtn2-n-prod-i-0n-frac
Answer: Using the Stolz-Cesaro Theorem, we find that
$$\begin{align}
\lim_{n\to \infty}\frac{\sum_{k=0}^n\log\left(\binom{n}{k}\right)}{n^2}&\overbrace{=}^{\text{SCT}}\lim_{n\to \infty}\frac{\sum_{k=0}^{n+1}\log\left(\binom{n+1}{k}\right)-\sum_{k=0}^n\log\left(\binom{n}{k}\right)}{(n+1)^2-n^2}\\\\
&=\lim_{n\to \infty}\frac{\sum_{k=1}^n \left(\log\left(\binom{n+1}{k}\right)-\log\left(\binom{n}{k}\right) \right)}{2n+1}\\\\
&=\lim_{n\to \infty}\frac{\sum_{k=0}^n \log(n+1)-\log(n+1-k)}{2n+1}\\\\
&=\lim_{n\to \infty} \frac{(n+1)\log(n+1)-\sum_{k=1}^n\log(k)}{2n+1}\\\\
&=\lim_{n\to \infty} \frac{(n+1)\log(n+1)-n\log(n)-\sum_{k=1}^n\log(k/n)}{2n+1}\\\\
&=\lim_{n\to \infty}\frac{\log(n+1)+n\log\left(1+\frac1n\right)-n\left(\frac1n \sum_{k=1}^n\log(k/n)\right)}{2n+1}\\\\
&=\frac12
\end{align}$$


Need to Click Popup with Gm script that is not always there

Question: i'm still having a problem clicking a popup button on an auction site,that appears only if u won an auction. This popup seems tbe a problem. Ive managed to get help partially in Need to click a bid button with Grease monkey script, i'm able to get the bid buttons clicked, but the popu is stil a problem. The xpath for the popup is:
.//*[@id='ctl00_mainContentPlaceholder_Button3']
And the script i'm using currently is:
// ==UserScript==
// @name           click popup try1.3
// @include         http://www.trada.net/*

// ==/UserScript==

//  ctl00_mainContentPlaceholder_Button3

function PopClick ()
{var PopBtn1=document.getElementById("ctl00_mainContentPlaceholder_Button3");

alert('try1');
PopBtn1.click (1);
alert('finished');
};

PopClick();

But the problem seems to be that the script doesnt stay active on the page waiting for the popup, I think if i can get it to "wait" for the popup to appear, it should work. I'm very new to GM, so excuse if there is simple errors. I had exelent help from people like Brock sofar, who is showing me the ropes. Slowly but surely I'm gettin the hang of it. Remove the alerts, i just used them to see if it executing.
Answer: The simplest solution would be to run this function, say every second, thus "waiting" for the popup to appear:
setInterval(PopClick, 1000);

It is also better to rewrite PopClick to check if the element is there, before calling click, like this:
function PopClick () {
    var PopBtn1=document.getElementById("ctl00_mainContentPlaceholder_Button3");
    if(PopBtn1) {
        PopBtn1.click ();
        // It is also makes sense to clear interval here. see docs for setInterval/clearInterval please :)
    }
};

May be this will help you with the freezing issue.
The more proper way, however, would be to set up MutationEvent listener. Since you are using Firefox, it should work OK:
function click_if_popup(evt) {
    if(evt.target.hasAttribute('id') && evt.target.getAttrubute('id') =="ctl00_mainContentPlaceholder_Button3")
    evt.target.click();
}

document.addEventListener('DOMNodeInsertedIntoDocument', click_if_popup);

Sorry, I didn't test any of this code: I wanted just to give you the general idea of where to dig.
Comment: When i use it like this setInterval(PopClick, 1000);, most of the time the page freezes. If i change it to 10 seconds, it is okay. Thanks.
Comment: @Ludwig, I updated the answer. You may want to try another approach I added.


Dúvida com if e elseif PHP

Question: Estou tentando fazer um algoritimo que divde o valor da função strtotime e exibi em minutos, horas. E agora estou tentando colocar em dias, criei a variavel $datadia, mas não estou conseguindo exibir caso o valor esteja acima das 24 horas
O resultado só é exibido em minutos e depois horas caso esteja em acima dos 60 minutos.
$phpdate = strtotime( $data );
$mysqldate = date( 'd-m-Y H:i:s', $phpdate );
$data1 = strtotime($mysqldate);
$data2 = strtotime("now");
$data3 = (int)(-($data1 - $data2)/60);
$data4 = (int)(($data3)/60);
$datadia = (int)(($data4)/24);

if (!empty($data) and $data3<=60){
   echo "Chegou $mysqldate
há $data3 minutos atrás
";
}
elseif (!empty($data)) {
   echo "Chegou $mysqldate
há $data4 horas atrás
";
}
 elseif (!empty($data)) {
   echo "Chegou $mysqldate
há $datadia dias atrás
";
}

Comment: O problema não seria estar usando variáveis do tipo `int`?
Sendo `x < 60` o resultado de `x / 60` será menor que 1. Em `int` isso seria um 0.
Answer: Uma possibilidade é utilizar a Classe DateTime para representação de data e hora.
(PHP 5 >= 5.2.0, PHP 7)
<?php
$data = '29/05/2019 18:22:50';
$data1 = DateTime::createFromFormat('d/m/Y H:i:s', $data);
$data2 = new DateTime();
$dataResult = $data1->diff($data2);

$mysqldate = $data2->format('d/m/Y');

if ($data1 < $data2) {
    if ($dataResult->days) {
        $mensagemDia = $dataResult->days . ' Dia (s) ';
    }
    if ($dataResult->h) {
        $mensagemHora = $dataResult->h . ' Horas ';
    }

    if ($dataResult->i) {
        $mensagemMinuto = $dataResult->i . ' minutos ';
    }
    echo "Chegou em " . $mysqldate . " há " . $mensagemDia . $mensagemHora . $mensagemMinuto . $dataResult->s . ' segundos';
}else{
    echo "Ainda não chegou!";
}

Usando strtotime
<?php
    $data = '2019-05-29 11:22:50';
    $data1 = strtotime($data);
    $data2 = strtotime("now");

    $diff = ($data2 - $data1);

    //Calculo de dias
    $calculoDia = 60 * 60 * 24; // minutos em dias

    $dia = (int)($diff / $calculoDia);
    $restoHora = (int)($diff % $calculoDia); //o resto de horas com uso do mod

    if (!empty($dia)) {
        $diff = $restoHora;
    }

    //Calculo de horas
    $calculoHora = 60 * 60; // minutos em hora

    $hora = (int)($diff / $calculoHora);
    $restoMinuto = (int)($diff % $calculoHora); //o resto de minutos com uso do mod

    if (!empty($hora)) {
        $diff = $restoMinuto;
    }

    $calculoMinuto = 60;
    $minuto = (int)($diff / $calculoMinuto); //quantos minutos
    $segundo = (int)($diff % $calculoMinuto); //o resto de minutos com uso do mod

    echo '
';

    if ($data1 < $data2) {
        if ($dia) {
            $mensagemDia = $dia . ' Dia (s) ';
        }
        if ($hora) {
            $mensagemHora = $hora . ' Horas ';
        }
        if ($minuto) {
            $mensagemMinuto = $minuto . ' minutos ';
        }
        echo "Chegou em " . $mysqldate . " há " . $mensagemDia . $mensagemHora . $mensagemMinuto . $segundo . ' segundos';
    }else{
        echo "Ainda não chegou!";
    }

Dúvida com if e elseif PHP


element comparison using list comprehension and conditions

Question: I have two lists in the form:
a = [[x1, 1], [x2, 0], [x3, 4], [x4, 12], [x5, 15]]

b = [[x2, 10], [x3, 41], [x7, 50]]

I thought I could do something like below to get the ids x1, x2, x3 and so on..
x = [item for item in b if item in a]

print(x)
[[x2, 10], [x3, 41]]

I actually want to print the elements in b that are in a and compare their values
[x2, 10] -> [x2, 0]
[x3, 41] -> [x3, 4]

so in the example above only print elements from a if b[0][1] == 0 & a[1][1] != 0
Any help would be most appreciated!
Comment: what's the sense of that condition `b[0][1] == 0 & a[1][1] != 0` ?
Comment: Where `x2` in both lists, compare the values associated with `x2`
Comment: Is there any reason why you are trying to do this with list comprehensions? A ``for`` loop is significantly easier for complex criteria.
Comment: @MisterMiyagi you are correct, for loop worked out easier. I am new to Python so though I could use list comprehension to find values from a in b!
Answer: Something like this might be what you are looking for:
ax = [item[0] for item in a]
x = [item for item in b if item[0] in ax]
print x

Answer: Using list comprehension with enumerate
Ex.
a = [['x1', 1], ['x2', 0], ['x3', 4], ['x4', 12], ['x5', 15]]
b = [['x2', 10], ['x3', 41], ['x7', 50]]
x = [a[index] for y in b for index,x in enumerate(a) if y[0] == x[0]]
print(x)

O/P:
[['x2', 0], ['x3', 4]]

Answer: You can convert a to a dictionary:
adict = dict(a)

and then we can just perform a mapping:
[[k, adict[k]] for k, __ in b if k in adict]

Answer: you can use:
a = [['x1', 1], ['x2', 0], ['x3', 4], ['x4', 12], ['x5', 15]]

b = [['x2', 10], ['x3', 41], ['x7', 50]]

a_dict = dict(a)

print('    b           a')
for x, val in b:
    if x in a_dict:
        print(f'[{x}, {val}] --> [{x}, {a_dict[x]}]')

output:
    b           a
[x2, 10] --> [x2, 0]
[x3, 41] --> [x3, 4]

Comment: Best solution to my problem, thanks! I was able to add two more if statements with the conditions I wanted! Thanks again
Answer: You can also make use of python's operator module.
import operator

getter = operator.itemgetter(0)
c = [j for i in b for j in a if getter(i) == getter(j)]

print(c)

Answer: a = [['x1', 1], ['x2', 0], ['x3', 4], ['x4', 12], ['x5', 15], ['x7', 60]]

b = [['x2', 10], ['x3', 41], ['x7', 50]]

for x in b:
    if x[0] in dict(a):
        v = dict(a)[x[0]]
        if x[1] > v:
            print('{} -> {}'.format(x, [x[0], v] ))
        else:
            print('{} -> {}'.format([x[0], v] , x))

Output
['x2', 10] -> ['x2', 0]
['x3', 41] -> ['x3', 4]
['x7', 60] -> ['x7', 50]


change storage class a folder gcp

Question: change storage class in a folder into a bucket in GCP, I try with
gsutil rewrite -s coldline gs://bucket-name/folder/

I see the
gsutil stat gs://bucket-name/folder/

what am I doing wrong?
Answer: The configuration tab on the console refers to the configuration of your main bucket, not the folder which you changed the storage class to COLDLINE. As seen on your screenshot, the folder test-2 is already configured into COLDLINE. You should be able to confirm it on the console by going to the folder and look at the "Storage Class" column.
Comment: Pherhaps cant assigned storageclass directly to a folder into a bucket, the stat of object (folder) i am not clear, the gsutil stat show that a object (folder) have stotarage class different from what is shown on the dashboard
Comment: The configuration tab (on the dashboard) is displaying the default storage class of your bucket. However, you can also change the storage class of the objects inside the bucket by running the `gsutil rewrite` which you've ran successfully but it doesn't mean that the storage class of your bucket would change. Only the storage class of the objects inside the folder you've specified will change and that explains why on the configuration tab of the bucket you can see it as Standard contrary to what you can see on the objects inside the folder which is already Coldline.

change storage class a folder gcp


how to change the colorbox image size?

Question: I have a content type named gallery and under this, I have created
the gallery content which is belong to that content type and added the
multiple images but the problem is when I click the thumbnail image
color box window opened but small images opened.
Answer:
Create a new image style of any size you want to open the image in colobox.
Now browse to manage display of your content type.
Select the formate 'Colorbox' for image field.
Add newly created image style for Colorbox image style, please follow below screenshot.
Comment: i did but it doesn't open the large plese check i added the image in question

how to change the colorbox image size?


Como ter suporte a transações com JUnit e Demoiselle 2.4.2

Question: Tenho uma aplicação cujos testes unitários estão em pleno funcionamento, exceto para operações de gravação no banco de dados. Nenhum dado é gravado. Ao forçar um flush, recebi a mensagem indicando que nenhuma transação estava em andamento, mesmo estando o método do BusinessController anotado com @Transactional. Tudo funciona corretamente na execução normal da aplicação dentro do JBoss, apenas nos casos de teste o problema se manifesta. Meu persistence.xml segue abaixo:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="restaurante-ds" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>

        <class>...</class>

        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
            <property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver" />
            <property name="hibernate.connection.url" value="jdbc:oracle:thin:@servidororacle" />
            <property name="hibernate.connection.username" value="username" />
            <property name="hibernate.connection.password" value="password" />
            <property name="hibernate.default_schema" value="schema" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
        </properties>
    </persistence-unit>
</persistence>

O que está faltando?
Update 1
Conforme orientação, o arquivo /src/test/resources/META-INF/beans.xml foi alterado para conter a classe do interceptor do Demoiselle, como abaixo:
<?xml version="1.0"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
    <interceptors>
        <class>br.gov.frameworkdemoiselle.transaction.TransactionalInterceptor</class>
    </interceptors>
 </beans>

O comportamento efetivamente mudou, pois antes a chamada do método insert() do meu BusinessController (restauranteUnidadeBC) não executava nenhuma operação no BD, mas agora eu recebo uma exceção com a seguinte mensagem:
Você está tentando obter um objeto não reconhecido pelo CDI via Beans.getReference(javax.transaction.UserTransaction)
Aparentemente falta ainda alguma coisa. O código do teste segue abaixo:
@Test
public void shouldAbrirCaixaComUsuarioLogado() {
    // Arrange
    Pessoa operador = pessoaBC.byChave("11111111111");
    RestauranteUnidade unidade = new RestauranteUnidade("Teste");
    unidade.getOperadores().add(operador);
    unidade = restauranteUnidadeBC.insert(unidade); // <<<< EXCEÇÃO AQUI!!!
    BigDecimal valorAbertura = new BigDecimal(10.50);

    // Act
    ...
}

A primeira invocação, que obtém o operador funciona dentro do esperado.
Update 2
Visando dar mais subsídios, forneço o trace de exceções correspondente ao erro:
br.gov.frameworkdemoiselle.DemoiselleException: Você está tentando obter um objeto não reconhecido pelo CDI via Beans.getReference(javax.transaction.UserTransaction)
    at br.gov.frameworkdemoiselle.util.Beans.getReference(Beans.java:132)
    at br.gov.frameworkdemoiselle.transaction.JTATransaction.getDelegate(JTATransaction.java:65)
    at br.gov.frameworkdemoiselle.transaction.JTATransaction.isActive(JTATransaction.java:77)
    at br.gov.frameworkdemoiselle.transaction.TransactionalInterceptor.initiate(TransactionalInterceptor.java:135)
    at ... diversas outras chamadas

Por este trace conseguimos perceber que o problema se manifesta em um método da classe JTATransaction.
Foi comentado a respeito da indisponibilidade de alguma dependência necessária. Segue abaixo uma versão simplificada do pom.xml para avaliação:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://maven.apache.org/POM/4.0.0"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    ... divresas definições

    <packaging>war</packaging>
    <parent>
        <groupId>br.gov.frameworkdemoiselle</groupId>
        <artifactId>demoiselle-jsf-parent</artifactId>
        <version>2.4.2</version>
    </parent>

    <dependencies>
        ... diversas dependências próprias

        <dependency>
            <groupId>br.gov.frameworkdemoiselle</groupId>
            <artifactId>demoiselle-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>br.gov.frameworkdemoiselle</groupId>
            <artifactId>demoiselle-jta</artifactId>
        </dependency>
        <dependency>
            <groupId>br.gov.frameworkdemoiselle</groupId>
            <artifactId>demoiselle-servlet</artifactId>
        </dependency>

        ... outras dependências específicas do projeto incluindo Hibernate

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>simple-jndi</groupId>
            <artifactId>simple-jndi</artifactId>
            <version>0.11.4.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>br.gov.frameworkdemoiselle.component</groupId>
            <artifactId>demoiselle-junit</artifactId>
            <version>2.3.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>br.gov.frameworkdemoiselle.component</groupId>
            <artifactId>demoiselle-validation</artifactId>
            <version>2.0.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>220.127.116.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    ... definições de plug-ins do Maven
</project>

A suspeita a respeito de uma dependência faltante parece justificada, pois a título de teste eu adicionei ao projeto de teste uma classe implementando a interface UserTransaction e o erro de CDI parou de ocorrer. Como a classe era dummy, não tive mais erro, mas voltei à situação onde as operações de alteração de BD não têm efeito.
Outra evidência é o log do console do Eclipse:
08:12:50,144  INFO Version:207 - WELD-000900 1.1.8 (Final)
08:12:50,418  INFO Bootstrap:245 - WELD-000101 Transactional services not available. Injection of @Inject UserTransaction not available. Transactional observers will be invoked synchronously.
08:12:50,699  INFO CoreBootstrap:209 - Ligando os motores do Demoiselle 2.4.2
08:12:50,702  INFO CoreBootstrap:209 - BeanManager disponível através do utilitário br.gov.frameworkdemoiselle.util.Beans
08:12:52,510  INFO CoreBootstrap:209 - O Demoiselle 2.4.2 decolou

Reitero que a aplicação funciona a contento, o problema somente se manifesta no contexto do JUnit.
Update 3
Após a remoção da dependência de demoiselle-jta, nenhuma diferença perceptível foi observada, o problema persiste. Abaixo o log do console desde o início até o fim da operação:
08:42:01,197  INFO Version:207 - WELD-000900 1.1.8 (Final)
08:42:01,518  INFO Bootstrap:245 - WELD-000101 Transactional services not available. Injection of @Inject UserTransaction not available. Transactional observers will be invoked synchronously.
08:42:01,813  INFO CoreBootstrap:209 - Ligando os motores do Demoiselle 2.4.2
08:42:01,818  INFO CoreBootstrap:209 - BeanManager disponível através do utilitário br.gov.frameworkdemoiselle.util.Beans
08:42:03,678  INFO CoreBootstrap:209 - O Demoiselle 2.4.2 decolou
08:42:06,402  INFO Version:24 - Hibernate Validator 4.2.0.Final
08:42:11,643  INFO Version:37 - HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
08:42:11,697  INFO Version:41 - HHH000412: Hibernate Core {4.1.7.Final}
08:42:11,717  INFO Environment:239 - HHH000206: hibernate.properties not found
08:42:11,724  INFO Environment:342 - HHH000021: Bytecode provider name : javassist
08:42:13,585  INFO DriverManagerConnectionProviderImpl:96 - HHH000402: Using Hibernate built-in connection pool (not for production use!)
08:42:13,891  INFO DriverManagerConnectionProviderImpl:130 - HHH000115: Hibernate connection pool size: 20
08:42:13,892  INFO DriverManagerConnectionProviderImpl:133 - HHH000006: Autocommit mode: true
08:42:13,893  INFO DriverManagerConnectionProviderImpl:147 - HHH000401: using driver [oracle.jdbc.OracleDriver] at URL [jdbc:oracle:thin:@aikanahml.cce.ufpr.br:1521:hml01]
08:42:13,894  INFO DriverManagerConnectionProviderImpl:152 - HHH000046: Connection properties: {user=restaurante_test, password=****, autocommit=true, release_mode=auto}
08:42:15,132  INFO Dialect:125 - HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
08:42:15,297  INFO TransactionFactoryInitiator:73 - HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
08:42:15,332  INFO ASTQueryTranslatorFactory:48 - HHH000397: Using ASTQueryTranslatorFactory
08:42:35,107  INFO LoggerProducer:209 - Gerenciador de entidades criado a partir da unidade de persistência "restaurante-ds".
Hibernate: alguns selects necessários que antecedem o INSERT
...
>>> Aqui ocorreu a exceção, mas nenhuma mensagem é registrada no console, apenas em debug é possível rastrear a exceção e inspecionar seus detalhes

08:44:09,578  INFO CoreBootstrap:209 - Desligando os motores do Demoiselle 2.4.2
08:44:09,579  INFO DriverManagerConnectionProviderImpl:156 - HHH000030: Cleaning up connection pool [jdbc:oracle:thin:@aikanahml.cce.ufpr.br:1521:hml01]

Comment: algum progresso após o update 2 da resposta?
Comment: @JoaquimOliveira, desculpe, não percebi que a resposta havia recebido atualização. Alterei o pom para definir o `scope` da dependência de JTA para `compile` e a dependência de JPA ficou com o `scope` configurado para `test`, mas isso não modificou o comportamento do problema. Eu não havia me atentado do conflito de dependências porque isso não afeta a execução da aplicação, apenas dos testes. Em resumo, continuo na mesma.
Comment: @JoaquimOliveira, removi a dependência de JTA do `pom`. A aplicação executa sem problema, mesmo que no `persistence.xml` eu tenha a configuração de tipo da persistence unit para JTA. O problema não se modificou. Quando eu tirei a dependência de JPA e deixei apenas a de JTA, a aplicação passou a não mais ser iniciada.
Comment: @JoaquimOliveira, retificando, após remover a dependência do demoiselle-jpa passei a ter um erro um uma parte da aplicação, no caso um DAO dependente de `JPACrudExtended<>`, durante um processo de update. Assim sendo, tive que recolocar a dependência de demoiselle-jpa.
Comment: minha sugestão era retirar a **demoiselle-jta**, supondo que sua aplicação não necessita de transações distribuídas.
Comment: @JoaquimOliveira: removi a dependência do `demoiselle-jta`, mas o problema não parece ter se modificado. No trecho de código onde faço um insert recebo uma exceção com a mensagem `Você está tentando obter um objeto não reconhecido pelo CDI via Beans.getReference(javax.transaction.UserTransaction)`. Mais alguma ideia? Vocês já realizaram testes unitários com operações transacionais no BD? o Demoiselle realmente suporta esse cenário?
Comment: veja se o novo update da resposta ajuda. Abraços.
Answer: As anotações de transação são processadas por um interceptor do JavaEE (br.gov.frameworkdemoiselle.transaction.TransactionalInterceptor).
Verifique se ele:
1) Ele está declarado corretamente no src/main/resources/META-INF/beans.xml da sua aplicação e que não existe o mesmo arquivo no src/test/resources/META-INF/ ou
2) Existem o arquivo em ambos os diretórios e ele tem o mesmo conteúdo. Lembre-se que, durante os testes, o arquivo que prevalece é o do src/test/resources/META-INF/
Update 1
Aparentemente, o CDI não está conseguindo achar uma implementação da classe javax.transaction.UserTransaction para injetar. Geralmente, estas classes ficam dentro das dependências demoiselle-jpa ou demoiselle-jta. Verifique se umas dessas dependências está declarada no pom.xml do seu projeto.
Outra coisa que pode estar atrapalhando é a existência de um persistence.xml mal configurado no diretório src/test/resources. Da mesma forma que o beans.xml, se houver este arquivo nesta localização, ele prevalece sobre o src/main/resources durante a execução dos testes unitários.
Update 2
@AlexSC, a partir da documentação do Demoiselle, entendo que você deve escolhar uma das duas estratégias possíveis: JPA ou JTA. Percebi que você tem as duas declaradas no seu pom.xml.
Sugiro testar somente com uma delas e remover a outra dependência. Lembrando que de acordo com a documentação, caso escolha JTA, você precisa:

Configurar no seu persistence.xml o atributo transaction-type="JTA" na persistence-unit e
Incluir a propriedade hibernate.transaction.jta.platform apontando para classe correta.

Update 3
O Demoiselle possui um arquétipo Maven, demoiselle-jsf-jpa, que traz um teste unitário com acesso a BD. Minha sugestão é você criar um outro projeto utilizando o arquétipo como base e verificar as diferenças de configuração entre ele e seu projeto.
O catálogo de arquétipos está disponível em http://demoiselle.sourceforge.net/repository/archetype-catalog.xml.
Comment: A orientação parece estar no caminho certo, mas creio que ainda falte algo. Adicionei detalhes na questão. Obrigado!
Comment: @AlexSC, o seu teste unitário executa no Oracle?
Comment: sim ele executa no Oracle
Comment: Adicionei mais alguns detalhes à pergunta. Aproveito para informar que o `beans.xml` de cada projeto é diferente. no caso dos testes, tenho uma referência ao interceptor JavaEE de transação provida pelo Demoiselle (`br.gov.frameworkdemoiselle.transaction.TransactionalInterceptor`), fato que não ocorre no `beans.xml` da aplicação
Comment: a dica de estudar o projeto de exemplo Bookmark foi feliz. Nele pude perceber diferenças existentes nos arquivos `beans.xml` e `demoiselle.properties`que se mostraram *absolutamente mandatórias* para que tudo funcionasse. Obrigado!


sftp backups with duplicity fail

Question: I'm using duplicity on debian wheezy, which comes with version 0.6.18 as standard package. I also tried version 0.6.24 from wheezy-backports.
I want to use sftp as backend, but if I run:
duplicity --full-if-older-than 1M --exclude /run --exclude /proc --exclude /lost+found --exclude /dev --exclude /sys --exclude /mnt / sftp://$FTP_USER"@"$FTP_HOSTNAME/myserver

I get the following error:
ssh: Exception: Incompatible ssh peer (no acceptable kex algorithm)
ssh: Traceback (most recent call last):
ssh:   File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 1546, in run
ssh:     self._handler_table[ptype](self, m)
ssh:   File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 1618, in _negotiate_keys
ssh:     self._parse_kex_init(m)
ssh:   File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 1731, in _parse_kex_init
ssh:     raise SSHException('Incompatible ssh peer (no acceptable kex algorithm)')
ssh: SSHException: Incompatible ssh peer (no acceptable kex algorithm)
ssh:

I've read that this is might related to the paramiko backend which is used as default, but when I change it to pexpect (...pexpect+sftp://...) I get this error:
UnsupportedBackendScheme: scheme not supported in url: pexpect+sftp://

How can that issue be fixed?
Answer: Try changing the command
duplicity /source-dir pexpect+sftp://backup.server.com/storage

to
duplicity /source-dir --ssh-backend=pexpect sftp://backup.server.com/storage

Tested with duplicity 0.6.24 on debian jessie 8.7
man duplicity:

--ssh-backend backend
Allows the explicit selection of a ssh backend.
   Defaults to paramiko.
Alternatively you might choose pexpect.

The scheme 'pexpect+sftp://' was introduced in a later version of duplicity.

sftp backups with duplicity fail