How do i detect collision between 2 rectangles??? LIBGDX

Question: So I have this problem that the Rectangle.overlaps isn't working for some reason or I don't know.
All this does is it draws a jet (MyActor) and a bullet Actor and on touch it makes the bullet move towards the blue enemy Actor and i want it to System.out.println("touched"); if bullet hits the enemy.
I'll just paste the whole code.
public class MyGdxGame implements ApplicationListener{

private Texture texture;
private Texture bulletTexture;
private Texture enemyTexture;
private MyActor myActor;
private BulletActor bulletActor;
private EnemyActor enemyActor;
private Stage stage;
private BackGroundActor backGroundActor;

private Rectangle bulletRectangle;

private Rectangle enemyRectangle;
float X=500,Y =600;

float bulletX = X, bulletY = Y+43;
float enemyX =0, enemyY = 615;
boolean started;
int touched = 0;

public class EnemyActor extends Actor{

    @Override
    public void draw(Batch batch, float parentAlpha) {
        batch.draw(enemyTexture,enemyX,enemyY);
    }

    @Override
    public void act(float delta) {
        if(bulletRectangle.overlaps(enemyRectangle)){
            System.out.println("Overlaps");
        }
    }
}

public class BackGroundActor extends Actor{
    public BackGroundActor() {
        setBounds(0,0,1280,720);
        addListener(new InputListener(){
            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                started = true;
                touched++;
                System.out.println(touched);
                return true;
            }
        });
    }
}

public class MyActor extends Actor{
    @Override
    public void draw(Batch batch, float parentAlpha) {
        batch.draw(texture,X,Y);
    }
}

public class BulletActor extends Actor{

    @Override
    public void draw(Batch batch, float parentAlpha) {
        batch.draw(bulletTexture,bulletX,bulletY);
    }

    @Override
    public void act(float delta) {
        if(started) {
            bulletX -= 3;
        }
    }
}
@Override
public void create() {

    texture = new Texture("C:\\Users\\User\\Documents\\LibGdxMainProjects\\SampleGame1\\android\\assets\\0001.png");
    bulletTexture = new Texture("C:\\Users\\User\\Documents\\LibGdxMainProjects\\SampleGame1\\android\\assets\\bullet.png");
    enemyTexture = new Texture("C:\\Users\\User\\Documents\\LibGdxMainProjects\\SampleGame1\\android\\assets\\fuel.png");

    bulletRectangle = new Rectangle(bulletX,bulletY,bulletTexture.getWidth(),bulletTexture.getHeight());
    enemyRectangle = new Rectangle(enemyX,enemyY,enemyTexture.getWidth(),enemyTexture.getHeight());

    stage = new Stage();
    myActor = new MyActor();
    enemyActor = new EnemyActor();
    bulletActor = new BulletActor();
    backGroundActor = new BackGroundActor();
    backGroundActor.setTouchable(Touchable.enabled);

    stage.addActor(bulletActor);
    stage.addActor(myActor);
    stage.addActor(backGroundActor);
    stage.addActor(enemyActor);

    Gdx.input.setInputProcessor(stage);

}

@Override
public void dispose() {
}

@Override
public void render() {
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();

    if(enemyRectangle.overlaps(bulletRectangle)){
        System.out.println("HIT I SAY");
    }

}

@Override
public void resize ( int width, int height){

}

@Override
public void pause () {

}

@Override
public void resume () {

}

}
Answer: According to the java documentation, there is a method intersects(Rectangle r). You can use this to determine whether two rectangles intersect. Take a look here.
Comment: This is not the same Rectangle as libGDX [Rectangle](https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/math/Rectangle.html#overlaps-com.badlogic.gdx.math.Rectangle-)
Answer: The issue here is that the bulletRectangle is not updated with the new position of the bullet, bulletX is not directly linked to bulletRectangle.
You could do
if(started) {
    bulletX -= 3;
    bulletRectangle.setX(bulletX);
}

You might want also to update the other rectangle with the proper position of the enemy
Answer: if(enemyRectangle.overlaps(bulletRectangle)){
    System.out.println("HIT I SAY");
}

add this code in your update method


Is $\lim_{x\to a}\frac{f(x)}{g(x)}=\frac{\lim_{x\to a}f(x)}{\lim_{x\to a}g(x)}$?

Question: I'm learning limits and I was wondering is this true:
$$\lim_{x\to a}\frac{f(x)}{g(x)}=\frac{\lim_{x\to a}f(x)}{\lim_{x\to a}g(x)}$$
Do limits have this property?
Comment: Yes, the cases that need to be excluded (without extra info on $f$ and $g$) are when the limits on the right *both* don't exist, or *both* go to zero, or *both* go to infinity.  In all other cases the equality is true for sure.
Comment: What if *g* goes to zero yet *f* doesn't? There's no trivial decent rule to divide by zero and still *g*'s sign should be concerned.
Answer: If $\displaystyle\lim_{x\to a}f(x)$ and $\displaystyle\lim_{x\to a}g(x)$ exist and if $\displaystyle\lim_{x\to a}g(x) \ne 0$, then you have:
$$\lim_{x\to a}\frac{f(x)}{g(x)}=\frac{\displaystyle \lim_{x\to a}f(x)}{\displaystyle\lim_{x\to a}g(x)}$$
Comment: Not quite, $f$ and $g$ can also diverge on $a$, but not the ratio...
Comment: @Martigan I only gave an **if**-statement (and didn't comment on the converse) but I'll rephrase to emphasize the correct implication (I intended).
Comment: The answer says **if**, not 'if and only if'.
Answer: So we have a lot of different cases:
If $\lim_{x\to a} g(x)=0$ and $\lim_{x\to a}f(x)=b\ne0$ then no
If both $\lim_{x\to a}g(x)$ and $\lim_{x\to a}f(x)$ converge and not going to $0$ then yes
If the ratio between $\lim_{x\to a}f(x)$ and $\lim_{x\to a}g(x)$ diverge then no
If both $\lim_{x\to a}g(x)$ and $\lim_{x\to a}f(x)$ diverge then... We can't tell anything yet, we need to know more about $f(x),g(x)$
If both $\lim_{x\to a}g(x)$ and $\lim_{x\to a}f(x)$ are equal $0$ then we still can't tell anything yet, we need to know more about $f(x),g(x)$
If $\lim_{x\to a}g(x)=0$ and $\lim_{x\to a}f(x)$ diverge to infinity are still can't tell anything yet, we need to know more about $f(x),g(x)$
If $\lim_{x\to a}g(x)=0$ and $\lim_{x\to a}f(x)$ diverge between $2$ numbers ($\limsup_{x\to a}f(x)\ne \liminf_{x\to a}f(x)$) then no
Answer: If $f,g:\mathbb{R}\rightarrowtail\mathbb{R}$ and $a\in((\text{dom}(f))'\cap(\text{dom}(g))')$ and $\exists \lim\limits_af=F, \lim\limits_ag=G$, then:
- $\exists \lim\limits_a(f+g)=F+G$
- $\exists \lim\limits_a(fg)=FG$
- if $G\neq0$ then $\exists \lim\limits_a\left(\frac{f}{g}\right)=\frac{F}{G}$
Comment: $(+1)$ for the great answer, and for the fact that someone bothered to write the symbol, $\rightarrowtail$ :P
Comment: @user477343 Thank you :) My teacher used the $f: E \rightarrowtail F$ when $\text{dom}(f) \subseteq E$, and $g: E \rightarrow F$ when $\text{dom}(g) = E$
Comment: Yeah most people get lazy and just right the arrows like $\to$. But you and your teacher didn't, and I respect that. Notation does not define math, but it definitely makes it look that bit prettier :P
Comment: @user477343 Yes :) Personally, I like to use a variety of notations, based on my mood, the topic, and the conversation partner. A good example might be the Einstein notation, or $\int f(x) \mathrm{d} x$ vs $\int \mathrm{d} x f(x)$.


Existence of 2D Quasicrystal with vertex having only even (or odd) coordination number.

Question: The coordination number for a vertex is the number of links connected to it.
In the Penrose lattice, it takes range from 3 to 7.  However, the mean coordination number is 4, the same as a square lattice.

For Ammann-Beenker quasicrystal, coordination number takes value in range 3-8, and interestingly it's mean is the same as the coordination number of the square and Penrose lattice.

The same story also applies to generalized Rauzy tiling. The coordination number change between 3-5 with a mean equal to 4!

We can see all of them have a continuous distribution of coordination numbers.
I am curious to know is there any quasicrystal in 2D with, for example, only even (or odd) coordination number?
Comment: @uhoh, Actually Penrose and Ammann-Beenker center models have only even coordination numbers.  The Center model is given when you put vertex inside tiles and connect them if they have a common edge.
Comment: @uhoh, Also If we use a version of Penrose tiling with triangles, its center model gives a lattice with only an odd coordination number.
Comment: Which definition are you using for quasicrystal? Just an FLC repetitive tiling? If so, you can obviously increase the mean valence of the vertices by cutting tiles in half. This would break the cut and project structure though.
Comment: @DanRust Thank you. You are right, by breaking bipartite properties of these repetitive quasicrystals, we can get even (or odd) coordination number for any vertexes.  However, is there any possibility to have a bipartite version?
Comment: I try several times to break the tilings in Penrose lattice. However, it seems after that, we have a mixture of odd and even coordination numbers.  So, I think my question is not so trivial!
Comment: related in Matter Modeling SE: [Proposing a 2D quasicrystal; what are the necessary and sufficient conditions? (If it looks like a duck and quacks like a duck, or...?)](https://mattermodeling.stackexchange.com/q/6993/201) and here in Math SE: [What is 12-fold Stampfli-inflation tiling and where/how can I recognize it in this analysis of dodecagonal 30° twisted bilayer graphene quasicrystal?](https://math.stackexchange.com/q/4412856/284619) where *any help or insight* will be greatly appreciated!
Comment: @DanRust I've just added a bounty
Answer: I think this can be an answer regarding existence. Yes, there is a systematic way to make a tiling with only odd or even coordination numbers.
The strategy uses the center model.
For even coordinated tilings:

First find the tiling with parallelogram tiles.
Put a vertex inside each tile

Connect these vertices if their corresponding tiles have common
edges.

For odd coordinated tiling

triangulate (connect vertices in a way to all tiles become a triangles without overlap) the tiling by respecting quasiperiodicity (for instance use inflation rules).
Put a vertex inside each tile
Connect these vertices if their corresponding tiles have common
edges.


Obter conteúdo entre marcações [x] e [/x] com Expressão Regular

Question: A minha dúvida é a seguinte, eu tenho o conteúdo abaixo que vem de uma tabela em um banco de dados e eu gostaria de usar uma expressão regular ou se tiver algo melhor, para separar apenas o conteúdo de dentro dos colchetes.

[pt-br]
Qual é Lorem Ipsum?
Lorem Ipsum  é simplesmente texto manequim da impressão e composição
  indústria. Lorem Ipsum tem sido o texto padrão do manequim da
  indústria desde os anos 1500, quando uma impressora desconhecida tomou
  uma galera de tipo e mexidos-lo para fazer um livro tipo espécime. Ele
  sobreviveu não apenas cinco séculos, mas também o salto para
  composição eletrônica, permanecendo essencialmente inalterado. Foi
  popularizado na década de 1960 com o lançamento de folhas Letraset
  contendo Lorem Ipsum passagens, e mais recentemente com software de
  editoração como Aldus PageMaker, incluindo versões de Lorem Ipsum.
[/pt-br]

[en-us]
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting
  industry. Lorem Ipsum has been the industry's standard dummy text ever
  since the 1500s, when an unknown printer took a galley of type and
  scrambled it to make a type specimen book. It has survived not only
  five centuries, but also the leap into electronic typesetting,
  remaining essentially unchanged. It was popularised in the 1960s with
  the release of Letraset sheets containing Lorem Ipsum passages, and
  more recently with desktop publishing software like Aldus PageMaker
  including versions of Lorem Ipsum.
[/en-us]
Comment: http://pt.stackoverflow.com/questions/121285/como-pegar-as-strings-que-estao-entre-colchetes
Comment: Acredito que este "dentro dos colchetes" seja o conteúdo entre as tags `[pt-br]` e `[/pt-br]`, mas a ideia continua sendo a mesma.
Comment: bom, o conteúdo é [pt-br] conteúdo aqui [/pt-br] assim por diante.
Answer: <?php

$texto = "[pt-br]

Qual é Lorem Ipsum?

Lorem Ipsum é simplesmente texto manequim da impressão e composição
indústria. Lorem Ipsum tem sido o texto padrão do manequim da indústria
desde os anos 1500, quando uma impressora desconhecida tomou uma galera
de tipo e mexidos-lo para fazer um livro tipo espécime. Ele sobreviveu
não apenas cinco séculos, mas também o salto para composição eletrônica,
permanecendo essencialmente inalterado. Foi popularizado na década de 1960
com o lançamento de folhas Letraset contendo Lorem Ipsum passagens, e mais
recentemente com software de editoração como Aldus PageMaker, incluindo
versões de Lorem Ipsum.

[/pt-br]";

$output = array();
preg_match_all("/\[(.*?)\]/", $texto, $output);
$texto = str_replace($output[0],'', $texto);
echo $texto;

Exemplos:

Ideone 1
Ideone 2

Separando em um array:
$output = array();
preg_match_all("/\[(.*?)\]/", $texto, $output);
$result = array();
for($i = 0; $i < count($output[0]); $i = $i + 2)
{
    $ini = strripos($texto, $output[0][$i]);
    $end = strripos($texto, $output[0][$i+1]);
    $result[str_replace(['[',']'],'',$output[0][$i])] =
        str_replace($output[0],'', substr($texto, $ini, $end-$ini));

}

var_dump($result);

Exemplo:

Ideone 3
Comment: Ahh tá agora sim.
Comment: esse reg aí vai pegar o [/pt-br] também? Porque aqui não pegou não.
Comment: @AsuraKhan sim pegou olha nos exemplos por favor!
Comment: @OsvaldoQueta eu fiz um edite, por favor verifique.
Comment: Que erro @OsvaldoQueta
Comment: @OsvaldoQueta não tem problema algum o código é esse mesmo, o  não vai causar nenhum problema, acabei de testar! olha [o link](http://ideone.com/6QQk5M)
Comment: O que tem de errado @OsvaldoQueta?
Comment: @OsvaldoQueta se está imprimindo o valor como? se você está usando var_dump poxa vida ta errado o jeito de programar;
Comment: Cara se ta programando errado. É com echo. Ta vendo !!! @OsvaldoQueta
Comment: @OsvaldoQueta o texto não esta como na pergunta, sem padrão pode acontecer isso.
Comment: Cole o texto que está lá gravado para mim ver @OsvaldoQueta tipo https://jsfiddle.net/ na parte html salva e manda o link deixa eu ver o padrao atual?
Comment: Blz, vou fazer isso! o texto é salvo no db apartir de um editor WYSIWYG! e talvez seja por isso né!
Comment: O link do jsfiddle: https://jsfiddle.net/8mn6eeq8/
Comment: desde já MUITO OBRIGADO @Virgilio Novic já me ajudou bem, me deu uma grande luz de como proceder
Comment: @OsvaldoQueta isso é. A falta de padrão e a sua duvida na pergunta está resolvida. Como você montou uma pergunta com um padrão tem que seguir nas resposta o mesmo. Ok? O texto do link esta sem padrão
Comment: @OsvaldoGueta sinalize então como resposta para a sua pergunta e se puder apagar os comentários é melhor
Answer: Tente essa regex (?<=\[\w{2}\-\w{2}\])(\.*)(?=\[\/\w{2}\-\w{2}\]).
Answer: Pode utilizar o seguinte código que irá retornar tanto para [pt-br] como para [en-us], ou qualquer outro tipo de valor entre os square brackets.
$re = '/\[[^]]+\]([^[]+)\[\/[^]]+\]/is';
$str = '[pt-br]

Qual é Lorem Ipsum?

Lorem Ipsum é simplesmente texto manequim da impressão e composição indústria. Lorem Ipsum tem sido o texto padrão do manequim da indústria desde os anos 1500, quando uma impressora desconhecida tomou uma galera de tipo e mexidos-lo para fazer um livro tipo espécime. Ele sobreviveu não apenas cinco séculos, mas também o salto para composição eletrônica, permanecendo essencialmente inalterado. Foi popularizado na década de 1960 com o lançamento de folhas Letraset contendo Lorem Ipsum passagens, e mais recentemente com software de editoração como Aldus PageMaker, incluindo versões de Lorem Ipsum.

[/pt-br]';

preg_match($re, $str, $matches);

// Retorna os valores encontrado
print_r($matches);

No seu caso irá encontrar 2 grupos, e no segundo está apenas o texto.
Ou seja, deve aceder a segunda posição do array.
Answer: O ideal quando se captura conteúdo de marcação é ter o padrão da marcação em um grupo.
Exemplo

Marcação [pt-br][/pt-br], o padrão é o pt-br.
Marcação [en-us][/en-us], o padrão é o en-us.

Porque por isso em um grupo? Pois assim você usa a própria captura para identificar o final da marcação.
Resolução
~\[([^]]+?)\](.*)\[/\1\]~s
Explicação

\[([^]]+?)\] - Temos o inicio da marcação que deve começar com [ e terminar com ] onde aplicamos a regra do grupo citada a cima.
(.*) - Captura qualquer coisa, lembrando que como temos o modificador s, inclui o \n.
\[/\1\] - Aqui é onde garante que vai parar na ocorrência do final marcação, pois deve capturar [/ + marcação ja capturada no grupo1 (\1) + ]

Problemas

Segue a mesma ideia do HTML e o ideal para tratar estes casos é um parser, não regex.

Veja no REGEX101
Comment: bem, explicado valeu! mesmo todos você me ajudaram muito e acatei as sugestões de todos vocês, VALEU MESMO
Comment: Olá @Guilherme Lautert vc disse no seu post que: "o ideal para tratar estes casos é um parser, não regex." pode exemplificar? como você trataria esse problema dá um exemplo para mim por favor.
Comment: @OsvaldoQueta Aqui eu explico a questão do parses, que entraria no seu caso. O que quero disser é que teria de ser feito via programação e não REGEX, pois não seria possível tag que estiverem dentro da outra.


Chartist on click function without jQuery

Question: I am trying to get a simple function to trigger after I click on a data point on a line graph in Chartist with the following code:
chart.on('draw', function(data) {
    if(data.type === 'point') {
        data.element._node.onclick =  click(data)
    }
});

Nothing seems to occur, can anyone figure out why this does not work?
The click function works fine if called without the click
Answer: What is click(data)? The function that should be called on click? when yes then you did it wrong. You have to assign a function to a click handler:
chart.on('draw', function(data) {
    if(data.type === 'point') {
        data.element._node.onclick = event => click(data);
    }
});


How to check if an article is referenced from a collection?

Question: I have a collection content type which is just a list of EntityReferences to articles.
When I am loading an article, how can I use the Entity API to check if it belongs to one or more collections?
Previously I would query the DB, but I wonder if there is a more idiomatic way?
Comment: If you do not know all fields that might be referencing this entity type then I doubt you can get that information with entity query. One thing that comes to mind is to load all entity reference fields, filter out those that do not allow your entity to be referenced and then construct entity query accordingly to match those fields and entity types they are attached to.
Comment: Thanks @IvanJaros for your comment. My use case is not that complex, There is only one field that references the articles so far.
Answer: To load all collection id's, which have a reference to $article_id:
$collection_ids = \Drupal::entityQuery('node')
  ->condition('type', 'collection')
  ->condition('field_article_ref', $article_id)
  ->execute();
if ( count($collection_ids) > 0 ) {
  echo "the article $article_id is referenced in one or more collections";
}

Comment: Thanks, it works. Nice and simple.What would be the right way to encapsulate this method? I would like to be able to do something like `$article->collections()` but that is maybe [a different question](http://drupal.stackexchange.com/questions/173922/what-is-the-best-way-to-extend-drupal-node-entity-node)


Alternate plain English algorithm for Towers of Hanoi

Question: There are four plain English algorithms for the Towers of Hanoi Puzzle available on Wikipedia, but when I was first solving the puzzle, I came up with an algorithm that is different from any of the solutions I have seen.
Wikipedia algorithms:

Iterative solution
Simpler statement of iterative solution
Equivalent iterative solution
Recursive solution

Of course the results of the algorithms are the same, and they are really just different ways of thinking about the same thing, but I am talking about plain English ways of describing the process.
My process goes like this:

Never move same tile twice in a row(obviously)
Prioritize moving right
When moving right, move to the closest pole that can be legally moved to.
When moving left, move to the farthest pole that can be legally moved to.

..

These rules differ from other descriptions of the algorithm in that:

The initial stack can be placed on any of the 3 pillars and still work without any adjustment to the rules needed.(Unlike solutions 2 and 3 and 4)
You don't have to number the disks(Unlike solutions 1 and 3 and 4)

Has anyone seen this description of the puzzle before?
Comment: I don't think it is right to say that solution 1 requires you to "number the disks". All it requires is that you can distinguish the smallest disk from the rest of the disks. But that's not a question of numbering -- if you can recognize a valid move, you're able to compare the sizes of the disks, and so figure out from scratch for each move which disk is smallest, just by comparing the three _visible_ disks.
Comment: In fact your description is very closely the same as the one you call solution 1. As Wikipedia points out, the only time you have a choice is when the disk you're moving is the smallest ones, so your rules 2-4 simply drop out of consideration in the moves where you just touched the smallest one. And when you _are_ moving the smallest disk, you can always move it anywhere, so the collected outcome of rules 2-4 is "move it right, wrapping around at the end".
Comment: x @David: Your solution is unidirectional because you don't care which peg the next tower is going to be built on -- following your recipe the location of the next full tower will depend on whether there's an odd or an even number of disks in the game. You could remove the choice of direction from the description of solution 1 too, replacing it with "always move to the right", and get the same outcome.
Comment: Please comment if you down-vote :-\
Comment: @HenningMakholm That's true. Still, solution one requires adjustments based on the starting direction, where as my solution is unidirectional.
Comment: @HenningMakholm Ok. That's what I was looking for. If you would post that as an answer, I'll accept.
Answer: In simple language (and note that the process is the same, of course):

(pre-step) Decide on the cyclic sequence of pegs for the smallest disc to move: S-M-D or S-D-M (where "S" denotes source peg, "D" denotes destination peg, and the other peg "M" is the "mid" peg). Choose the first for even towers and the second for odd towers.
Loop over the following moves:
** move the smallest disc on its cycle - if this completes the tower, stop
** make the only possible move not involving the smallest disc

Very hard to go wrong following this pair of instructions. And if you happened to pick the wrong cycle, just carry on (after the "null" move that signals a complete tower)  - the tower will move to the correct peg eventually.
Answer: This solution is a unidirectional version of the first iterative solution.
The difference between the unidirectional solution and the mono-directional version is the unidirectional solution doesn't specify an end position.

A simple solution for the toy puzzle: Alternate moves between the
  smallest piece and a non-smallest piece. When moving the smallest
  piece, always move it to the next position in the same direction (to
  the right if the starting number of pieces is even, to the left if the
  starting number of pieces is odd). If there is no tower position in
  the chosen direction, move the piece to the opposite end, but then
  continue to move in the correct direction. For example, if you started
  with three pieces, you would move the smallest piece to the opposite
  end, then continue in the left direction after that. When the turn is
  to move the non-smallest piece, there is only one legal move. Doing
  this will complete the puzzle in the fewest number of moves.

This description of the mono-directional version can be changed to be unidirectional if direction choices of direction are replaced with the rules from the unidirectional solution revolving around prioritizing moving right.


Is it always possible to create a intuition for abstract algebra theorems?

Question: I am a Ph.D student in computer science, and I work on graph isomorphism. My research work requires some level of mathematics (mostly group theory ). I have done basic level abstract algebra course. I try to write down the theorems on peace of paper and try to understand them; I usually repeat this process four five times. Some time by doing this I understand the theorem and its proof, but there are times when I find it difficult. The biggest problem I have faced is that theorems related to abstract algebra are really abstract I mean there is no way to create an intuition (Is it true ?).

My question : How to create an intuition for abstract algebra theorems?

For Example
Comment: You may see [this](https://www.amazon.com/Visual-Classroom-Resource-Materials-Problem/dp/088385757X). (ps: However I haven't read this.)
Comment: stating a theorem carefully with proper terminology etc. is actually easier than developing/ having the intuitive idea of the theorem. Intuition is a goal not always easily attained (at least for me) But, being an optimist, I do think it's possible, with work, to attain intuition.
Comment: @new_bee it's different for different folks. For one of my students, intuition flows from his ability to restate the problem in terms of category theory. For me, it's more about comparing and contrasting to things I already know. Often understanding the limitations or generalizations of a given statement brings a sense of intuition. But, for others, there is a secret formula or picture which, while a lie, gives insight into the source of the idea. For others, its meaning in physics has merit. What is intuition? What is dear to you? Answer that and answer the question.
Comment: @Eric - that's an excellent book for building intuition. I definitely recommend it.
Comment: @JamesS.Cook for Ramanujan, it's from his connection to the Hindu Goddess Namagiri while dreaming. [The Secrets of Ramanujan's Garden](https://www.scienceandnonduality.com/the-secrets-of-ramanujans-garden/)
Answer: I think the best way to understand abstractions intuitively is to study lots of examples. To understand group actions, write some down. Then think about whether each is transitive, whether it's primitive, look at the stabilizers of elements. Verify that the theorem is true; try to understand why in each particular case. Look for examples where some hypothesis fails and see whether (and why) the conclusion fails.
That learning strategy reproduces (in part) the explorations that led to the useful abstractions of group theory. Mathematicians studying the symmetries of various geometrical objects realized that they could reason about the symmetry of just about anything by inventing an abstract language whose definitions captured the essence of the properties of symmetries.
Unfortunately, often the abstractions - the definitions and theorems - take center stage in teaching and learning. Students find it hard to understand what's going on without the examples. I would tell my students that for me the category of groups consisted of those groups with which I was personally familiar. I assigned homework that called for working out examples at least as much as proving theorems.
In your own discipline (computer science) there are analogous historical trends leading from examples to abstractions: the concepts of object oriented or functional programming languages, the development of abstract tools to reason about databases.
Comment: For me too, a big part of intuition is definitely a reportoire of working examples and counterexamples, and the understanding necessary to know why they are (counter)examples.
Answer: One way to build intuition is to reframe results in terms of objects and relationships that you know of and are familiar with. Since it seems as though you're looking at group action in the context of graph theory, this might be a good route to go.
For example, consider the first theorem you state about the primitivity of a transitive group action. For a graph $X$, think of $\Omega = V(X)$ and $G=\operatorname{Aut}(X)$. Then a system of imprimitivity can be seen as a partition of $X$ into subgraphs that 'look the same.' Now, the theorem states

Assume that $\operatorname{Aut}(X)$ acts transitivity on $V(X)$, and consider $v\in V(X)$. Then $\operatorname{Aut}(X)$ has a system of imprimitivity if and only if there is some nontrivial subgroup $H$ containing $\operatorname{stab}(v)$.

This might start to seem more concrete. Since $\operatorname{Aut}(X)$ acts transitively on $X$, the subgroup that sends these subgraphs to themselves not only contains $\operatorname{stab}(v)$, but strictly contains it, since $v$ can also be mapped to any other vertex in its partition.


Why is there fret buzz on an acoustic after not playing it for a year?

Question: I gave my brother's girlfriend an acoustic guitar and stand over a year ago. I was over at their place the other day and I thought I would play the guitar. Of course it was out of tune, but I was surprised that there was terrible fret buzz everywhere on the guitar! When I gave it to her fret buzz wasn't an issue. It played great. I'm pretty sure that the guitar has been on the stand almost the entire time she's had it. It's one of the "normal" stands that has neck support.
What would cause the guitar to have so much fret buzz? As a bonus, what's a good way to prevent that?
Some additional information: The guitar is in Southwest Ohio in an air conditioned and heated house. I've never noticed any issues with the humidity in their house. Also, it's not exposed to direct sunlight. They keep the blinds down in that room.
Comment: No.1 - don't give guitars to someone who may never play them! No.2 the neck has straightened out and needs adjustment on the trussrod. No.3 - it may well have been subjected to too much sun.
Comment: @AlbrechtHügli -  the neck would have a back bow, so the strings are too close. That's the opposite. Tightening the strings (not a good idea) may help.
Comment: We really need to know more about the guitar & the environment. I've had guitars sitting out in a room for 20 years or more with no ill-effects… some of them haven't even been re-strung in that time [yeah, I know, I like that dead string sound on some instruments, it's apropos.]
Comment: They could make a clone of you from the DNA on that guitar.
Comment: I let him out, alternate weekends, to give myself a rest :P
Comment: Have you controlled the neck? If it's bowed, then Tim must be right. To avoid this deformation you can release the strings that they have less tension.
Comment: Tim, I was assuming that that guitar has no truss-rod. I think there are cheap guitars without one. I don't remember that mine ever had one.
Comment: One thing I find interesting, IME, is that high end guitars are more prone to damage when neglected (they're daisies).  In contrast it seems that cheaper guitars can handle a bit of abuse.  Thought that is probably due to heavy coats of finish and sealer (even on the inside) and that reduces quality of tone.
Answer: Where do you live?  If the seasons changed dramatically then the guitar would have dried out in the dry seasons, expanded when humid.  Temperature changes will also cause expansion and contraction of the wood and this will not be uniform throughout the instrument.  This translates to the instrument being a different shape after a year (or less, or more depending on circumstances).
Ideally one should not keep an acoustic out like that.  It should be in the case with a damp humidifier in there with it.  The humidifier should be checked every day.  This is more important in the winter when the air is dry and heat on in the house.  In dry climates this should be practiced.  It's okay to leave the instrument out if there is some type of humidifier in the house that is on all the time.  Some centralized heating and A/C units have humidifiers built in that will blow moist air into the home.  Then there are large floor units.  Many musicians keep these in their music room and keep the instruments out.
After a year of sitting out and not being looked after I'd guess the neck is warped and needs to be adjusted, as per Tim's comment.  However the top could also be warped given that it was not taken care of.  If you take it in for an overall adjustment a Luthier will let it sit near a humidifier to reanimate the wood.  If it's in really bad shape even an adjustment might not bring it back to its original state.
Typically guitars need an adjustment at least once a year (sometimes every season) even when they are being taken care of properly.  I am quite surprised that some people leave guitars out all year and DON'T get buzzing, dead spots, and permanent damage.
Comment: This sounds very contra to what I would have to deal with in the UK [or anyone in the dampest parts of Asia for that matter]. We don't get dry winters here, humidifiers are definitely not a common domestic appliance… nor is air conditioning.
Comment: Where I am in the US the seasonal changes are drastic!  Also, even if the air is not dry in the winter turning on the heat w/o a humidifier will dry it out.  It is not uncommon for my skin to crack a bleed if I don't hit it with gobs of lotion, which is NOT good for the finish.
Comment: "The US" is a pretty big place, so I've heard. Alaska vs Florida, for instance… I think your guide is clear, but very very climate-specific.
Comment: I agree, it is climate specific.  And by climate I mean indoor climate as much as outdoor.
Comment: For sure, but as I've never ever met anyone who owns a humidifier of any description, nor anyone with domestic air-con [except for myself, who owns a small portable] it all sounds a bit… excessive.
Comment: Oh well.  Now you "know" someone with "domestic air-con", and large 10 gallon floor humidifiers, and case humidifiers.  This is not excessive where I'm from.
Comment: I leave my guitars out all the time - on hangers - and don't need to do annual adjustments. U.K. and Europe seem to be far more guitar-friendly than some of U.S.


Is there is something like cron in rails application on windows?

Question: I'm trying to use cron in my application to send mails every week but I think it doesn't work on Windows.
Does anybody knows any equivalent to cron solution that works on Windows?
Comment: On Windows, you'd use the [Task Scheduler](https://msdn.microsoft.com/en-us/library/windows/desktop/aa383614.aspx). Doesn't look like it's being actively developed, but maybe the [win32-taskscheduler](https://rubygems.org/gems/win32-taskscheduler/) gem is of any help to you.
Comment: how to use win32-taskscheduler ?
Answer: Windows equivalent of Unix's cron is a "Task Scheduler". You can configure your periodical task there.

Purely Ruby solution
If you want a purely Ruby solution look into:

rufus-scheduler - it's Windows cron gem.
crono - it's a in-Rails cron scheduler, so it should work anywhere.
Web services - there are plenty of free online services that would make a request to a given URL in specific time periods. This is basically a poor man's cronjob.
Answer: I recommend taking a look at Resque and the extension Resque-scheduler gems. You will need to have a resque scheduler process running with bundle exec rake resque:scheduler and at least one worker process running with QUEUE=* bundle exec rake resque:work.
If you want these services to run in the background as a windows service, you can do it with srvany.exe as described in this SO question.
The above assumes you are ok with installing Redis - a key-value store that is very popular among the Rails community as it can be easily used to support other Rails components such as caching and ActionCable, and it is awesome by itself for many multi-process use cases.
Resque is a queue system on top of Redis that allows you to define jobs that can be executed asynchronously in the background. When you run QUEUE=* bundle exec rake resque:work, a worker process runs constantly and polls the queue. Once a job is enqueued, an available worker pops it from the queue and starts working on it. This architecture is quite scalable, as you can have multiple workers listening to the queues if you'd like.
To define a job, you do this:
class MyWeeklyEmailSenderJob
  def self.perform
    # Your code to send weekly emails
  end
end

While you can enqueue this job to the queue yourself from anywhere (e.g. from a controller as a response to an action), in your case you want it to automatically be placed into the queue once a week. This is what Resque-scheduler is for. It allows you to configure a file such as app/config/resque_schedule.yml in which you can define which jobs should be enqueued in which time interval. For example:
send_weekly_emails:
  cron: 0 8 * * Mon
  class: MyWeeklyEmailSenderJob
  queue: email_sender_queue
  description: "Send weekly emails"

Remember that a scheduling process has to run in order for this to work with bundle exec rake resque:scheduler.
Answer: thanks guys , actually i tried rufus scheduler gem and it worked for me , i guess it's the best and easier solution


Whats the $L_2$ Norm in relation to Wavelets and functions?

Question: I have read that in order for a function to be a wavelet, it needs to fufull the L2 Norm property.
But I don't know what that is and there wasn't an explanation either. I know theres a L2 norm in relation to vectors, but that doesn't seam to be the same thing.
So what does it mean for a function to be L2 conform?
Answer: While some context is missing, like what the domain of your function is, for a function $f$ to have bounded $L^2$ norm means that $\int_D |f(x)|^2 dx<\infty$.  The norm is induced by an inner product $\langle f, g \rangle = \int_D f(x)\overline{g(x)}dx$, and the collection of all functions with bounded $L^2$ norm on $D$ form a Hilbert space.  There is a lot of nice theory of Hilbert spaces, and all of this is standard when studying measure theory and functional analysis, so a book on measure theory might be a good starting place.
Comment: thanks, but what is the line ontop of g(x) for, also why does f(x) need to be absolute when  (-x)*(-x)=x*x?
Comment: Complex conjugation, in case you want to deal with complex valued functions instead of just real valued ones, in which case the absolute value becomes necessary because $|z|^2=z\overline z \neq z^2$ for complex numbers.
Comment: ah, thanks makes sense


How to resize image using multi_image_picker in Flutter?

Question: I'm using multi_image_picker package to pick images and upload to server, but before uploading I want to resize images. I'm trying to accomplish it using dart.ui but having a problem:
//assets is List<Asset> from MultiImagePicker.pickImages
 assets.forEach((asset) {
      Future<ByteData> byteData = asset.getByteData();
      byteData.then((d) async {
        List<int> imageData = d.buffer.asUint8List();
        String b64 =base64Encode(imageData);
        print(b64); // prints [/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE...
        //if i send b64 to server then decode it and save as img it's working well

  //Resize
    ui.instantiateImageCodec(imageData,targetHeight: 800, targetWidth: 600)
        .then((codec) {
      codec.getNextFrame().then((frameInfo) async {
        ui.Image i = frameInfo.image;
        ByteData bytes = await i.toByteData();
        List<int> resizedImageData = bytes.buffer.asUint8List();
        String rb64 = base64Encode(resizedImageData);
        print(rb64); // prints too many backslashes:[k5KO/5qWk/+ZlZL/mpaT/5uXlP+alpP/mJSR/5iUkf+YlJH/mZSR/5uWk/+blpP/n5qX/6GcmP+gm5f/oZyY/6GcmP+fmpb/nZi..
        //If i send rb64 to server then server cannot decode and save it.
      });
    });
  });
});

Comment: The important first question is whether Flutter on the mobile or on the Web? On mobile, it works just fine. On the Web, I have about three bug reports currently standing that make it impossible for the time being but I hope it will be fixed soon. :-)
Comment: I ended up using https://pub.dev/packages/flutter_native_image to resize
Answer: This is the function I normally use to resize:
import 'dart:ui' as skia;

Future<skia.Image> resizeImage(String path, {int width, int height}) async {
  Uint8List data = await File(path).readAsBytes();
  final codec = await skia.instantiateImageCodec(data, targetWidth: width, targetHeight: height);
  final frame = await codec.getNextFrame();
  return frame.image;
}

As I mentioned in the comment, this is currently not working in Flutter Web but it's due to a bug that will be fixed soon, hopefully.
Comment: how to get Uint8List from resized ui.Image to encode it to base64 to send it to server? I think the code in my question is the same as yours except the encoding part.
Comment: Yes, using `toByteData()`. I can see nothing really wrong with your code. Do you have specific problems with it? Note that `toByteData()`, unless you provide the format, will return raw RGBA bitmap, not a PNG or JPG or similar, so you have to treat it as such on the server.


I can't find a quote in [class.copy.elision] confirming that the initialization `T x = T();` is eligible for the mandatory copy elision

Question: cppreference.com cites two cases for the Mandatory elision of copy/move operations. I'm interested in the second case as follows:

In the initialization of an object, when the initializer expression is
  a prvalue of the same class type (ignoring cv-qualification) as the
  variable type.

Thus, the initialization below will have mandatory elision of the copy operation:
T x = T();

In fact, this initialization doesn't compile in C++14 when T's copy constructor is deleted, but it does compile in C++17 (see example), as stated in cppreference.com.
But I can't find a quote in [class.copy.elision] supporting this.
Answer: That's because the wording is in [dcl.init]/17.6.1

Otherwise, if the destination type is a (possibly cv-qualified) class type:

If the initializer expression is a prvalue and the cv-unqualified version of the source type is the same class as the class of the
  destination, the initializer expression is used to initialize the
  destination object. [ Example: T x = T(T(T())); calls the T default
  constructor to initialize x. — end example ]

Guaranteed copy elision involved a clever alteration of the way value categories behave and interact. So it's spread across several places in the standard. You can see them by examining the original proposal


automoveToNext() method from developer guide is not working properly

Question: I'm using the method automoveToNext from developer guide for phone number fields. Even on simulator I'm able to reproduce the issue. After entering the number in the fourth field it circles back to first field or second field and starts overriding the first field, second field so on. Please find the attached screenshot for reference. There is flickering of the entered text as well. Please let me know, if any one have any thing different for Text field control to use for phone number with moveToNextField functionality. Also, focus of the field is not switching appropriately: meaning, cursor will be present more than one field. Please find the code below.
Second question, Can I use same field for phone number with extension combination also. Codenameone don't have phone number control which area code and extension splits. Please let me know
Fields Declaration:
TextField num1 = new TextField("", "1234", 4, TextArea.NUMERIC);
TextField num2 = new TextField("", "1234", 4, TextArea.NUMERIC);
TextField num3 = new TextField("", "1234", 4, TextArea.NUMERIC);
TextField num4 = new TextField("", "1234", 4, TextArea.NUMERIC);

Methods:
private void automoveToNext1(final TextField current, final TextField next) {
    current.addDataChangeListener(new DataChangedListener() {
        public void dataChanged(int type, int index) {
            if (current.getText().length() == 4) {
                Display.getInstance().stopEditing(current);
                String val = current.getText();
                current.setText(val.substring(0, 3));
                next.setText(val.substring(4));
                Display.getInstance().editString(next, 3, current.getConstraint(), next.getText());
            }
        }
    });
}

private void automoveToNext2(final TextField current, final TextField next) {
    current.addDataChangeListener(new DataChangedListener() {
        public void dataChanged(int type, int index) {
            if (current.getText().length() == 5) {
                Display.getInstance().stopEditing(current);
                String val = current.getText();
                current.setText(val.substring(0, 4));
                next.setText(val.substring(5));
                Display.getInstance().editString(next, 4, current.getConstraint(), next.getText());

            }
        }
    });
}

private void automoveToNext3(final TextField current, final TextField num1, final TextField num2, final TextField num3) {
    current.addDataChangeListener(new DataChangedListener() {
        public void dataChanged(int type, int index) {
            if (current.getText().length() == 5) {
                current.stopEditing();
                String val = current.getText();
                current.setText(val.substring(0, 4));
                current.setFocus(true);
                if (num1.getText().length() == 3) {
                    num1.stopEditing();
                }
                if (num2.getText().length() == 3) {
                    num2.stopEditing();
                }
                if (num3.getText().length() == 4) {
                    num3.stopEditing();
                }
                if (current.getText().length() == 4) {
                    current.stopEditing();
                }

            }
        }
    });
}

Calling the methods like this:
        if (num2.getText().isEmpty()) {
            automoveToNext1(num1, num2);
        }
        if (num3.getText().isEmpty()) {
            automoveToNext1(num2, num3);
        }
        if (num4.getText().isEmpty()) {
            automoveToNext2(num3, num4);
            automoveToNext3(num4, num1, num2, num3);
        }

Comment: I answered the second question, I'm not sure I follow what you are seeing in the first. A video or screenshots might help clarify that
Answer: There is a cn1lib with a control that lets you pick the area: https://www.codenameone.com/blog/tip-activation-ui-builder-pattern.html
There is a similar control in the login page of the Uber clone app.
The code of auto move to next seems to be a bit old try this:
private void onTypeNext(TextField current, TextField next, int length) {
    current.addDataChangedListener((i, ii) -> {
        if(current.getText().length() == length) {
            current.stopEditing();
            next.startEditingAsync();
        }
    });
}

Comment: This control is to have phone number selection for different countries. But I want to have control for US in the format (111)222-2222-4444. So I'm using Credit card fields and modified to fit the phone number appropriately. Please correct me if wrong.
Comment: Codenameone have single text field for phone number control which is not usable because landline numbers will have extensions. some scenarios user need flexibility in the control to have area code for state and extension separate in the phone number control to enter.
Comment: Yes our control is designed for SMS verification not for your use case. Your approach should be the way to go and you can get inspiration from what we did in that control. The screenshot you are seeing looks like a bug in the text editing. Was this on an Android device or the simulator? Is this something you can reproduce consistently with a test case/instructions? If so please file an issue on that [here](http://github.com/codenameone/CodenameOne/issues/new) it's a constant whack-a-mole on text editing nuances with the various platforms
Comment: Sure Shai. Thnak You. Screenshot refers Textfield overlapping text on Simulator. Same thing happens on IOS and android as well.
Comment: I feel cn1 should have inbuilt control for this functionality. Do you think this can happen anytime soon. Thanks.
Comment: Looking again at the code it seems automove next is a bit out of date, I edited my answer with a newer version. Where did you get that from exactly? What would you expect us to have? A number control or a masking control? The former is a bit user specific. The latter is a bit hard to generalize correctly as input validation on mobile is nothing like input validation on desktop where you can just detect keyboard input. We thought about this a lot when doing the validation framework but it's hard to generalize effectively
Comment: I'm looking for masking control. In US, that is the standard format every one follows. So either new phone control  or at least masking will help. This is the link I used the code from : https://www.codenameone.com/blog/validation-regex-masking.html. Same code exists in the latest Developer Guide as well. Thanks
Comment: I don't think a phone UI control makes sense in the core but it should be pretty easy to add a cn1lib for common controls like we did with the SMS callback code. We'll try to fix the sample in the developer guide and note the outdated nature of the code in the masking post
Comment: Modified still doesn't work properly.  Current field value will gets copied over to next fireld automatically and I have applied fieldname.maxSize(10) and fieldname.maxSize(4) still field is editable and will be able to enter more digits. Please see the screenshot for reference.
Comment: Which screenshot? Is the one on the top of this post still happening? On the device or on the simulator? Notice that the device input is very different from the simulator!
Comment: Sorry Shai. I missed the screenshot. Please see the screenshot. This is on iOS device. Text entered in first field gets copied over to second field and still editable from there.
Comment: Is this something you get consistently with this code? Can you please file an issue with a simple test case we can reproduce? Thanks.


Let $T_1,...,T_n, T \in V^{*}$. If $\bigcap_{i=1}^{n} T_i ^{-1}(0) \subset T^{-1}(0)$, then T is a linear combination of $T_1,...,T_n$.

Question: What I did:
Put $F:V \rightarrow \mathbb{K}^n, F(x)=(T_1(x),...,T_n(x))$ linear transformation, but $F^{-1}(0) \subset \bigcap_{i=1}^{n} T_i ^{-1}(0) \subset T^{-1}(0)$,besides, as $T_i^{-1}(0)$ is a hyperplane, there is $v_i \in V$, $V = T_i ^{-1}(0) \oplus [v_i]$
How can I proceed?
Answer: I'm not assuming $V$ is finite-dimensional (there might be a simple proof in that case). I'll proceed via induction over $n$.

$n=1$: if $T_1=0$ and $\ker T_1\subset \ker T$, then $T=0$. If $T_1\neq 0$, there is some $x_1$ such that $T_1x_1\neq 0$. Now note that $\displaystyle \forall x, x-\frac{T_1x}{T_1x_1}x_1\in \ker T_1$. Therefore, $\displaystyle T=\frac{Tx_1}{T_1x_1}T_1$
suppose the claim holds for $n-1$ functionals, and consider $T_1,...,T_n, T \in V^{*}$ such that $\bigcap_{i=1}^{n} \ker T_i \subset \ker T$.

WLOG $T_1,\ldots, T_n$ is linearly independent. In that case, there exists (I leave the proof to you) $x_1,\ldots, x_n$ such that $\forall i, x_i \in \left(\bigcap_{j\neq i}\ker T_j\right)\setminus \ker T_i$.
Then $\displaystyle \forall x, x-\sum_{i} \frac{T_ix}{T_ix_i}x_i \in\bigcap_{i=1}^{n} \ker T_i$, which proves the claim.


Porque comparar Enum com um Objeto enum

Question: Quando estava aprendendo Java, eu tinha uma Class que tinha uma propriedade do tipo Enum,
e, em um certo momento, eu queria saber se o que estava vindo em um Método era igual a uma constante da Enum, algo assim:
public void teste( TipoAlteracaoValor valor ) {
        if( valor.equals(TipoAlteracaoValor.ALTERACAO_VALOR) ) {
            System.out.println( "é Alteração ");
        }
        //Deveria ser assim:
        if( TipoAlteracaoValor.ALTERACAO_VALOR.equals(valor)) {
            System.out.println("é Alteração" );
        }
    }

Mas me disseram que isso é errado de se fazer, o certo é comparar a Constante do Enum com o valor que estiver vindo pelo parâmetro. Porém não me lembro... qual é a razão técnica de ser usar essa comparação?
Answer: Ao comparar como abaixo, você poderá tomar um NullPointerException. Imagine o que aconteceria se a variável valor estivesse nula:
    if( valor.equals(TipoAlteracaoValor.ALTERACAO_VALOR) ) {
        System.out.println( "é Alteração ");
    }

Ao comparar o enum com o objeto que chegou, você evita tomar erro caso o atributo esteja NULL:
    if( TipoAlteracaoValor.ALTERACAO_VALOR.equals(valor)) {
        System.out.println("é Alteração" );
    }

Tanto faz se valor está null ou não, você não terá exceção.
Só isso mesmo. [=
Comment: Nada que uma checagem adicional `valor != null` não resolva (com a desvantagem de você ter que fazer essa checagem adicional :)
Comment: Uhum. Eu ainda assim prefiro o sem a checagem, é um if a menos. :3
Answer: O problema com valor.equals(TipoAlteracaoValor.ALTERACAO_VALOR) é que se o parâmetro valor for nulo, então você receberá uma exceção NullPointerException por tentar acessar o método equals num objeto nulo.
A outra forma resolve o problema porque a "constante" TipoAlteracaoValor.ALTERACAO_VALOR nunca será nula e, caso o parâmetro valor seja também não há problemas, simplesmente o if não vai ser executado.
Porém, posso dizer que a melhor forma de comparar Enums em Java não é nenhuma das duas apresentadas.
Você pode simplesmente usar o operador ==, como com tipos primitivos.
O == quando aplicado a objetos verifica se os mesmos são a mesma instância. E isso é justamente a vantagem do Enum. Cada "constante" do Enum é na verdade uma instância única do mesmo.
Considere o código:
public void teste( TipoAlteracaoValor valor ) {
    if( valor == TipoAlteracaoValor.ALTERACAO_VALOR ) {
        System.out.println( "é Alteração ");
    }
}

Além de mais legível ele não incorre no problema com null.

Fontes sobre o assunto (em Inglês):

Comparing Java enum members: == or equals() ?
Use == (or !=) to Compare Java Enums

Porque comparar Enum com um Objeto enum


Is there way to skip minute part out of time if it's zero while formatting DateTime?

Question: Here's what I need: 15h37, but 15h instead of 15h00 (H'h'mm) or 15h0(H'h'm).
It looks like there is no way to achieve this with just formatting engine itself, is there?
Answer: You can format hours and minutes separately, and use separate formatting for positive-negative-zero values, like this:
static string FormatTime(DateTime dt) {
    return string.Format("{0}h{1:##m;;}", dt.Hour, dt.Minute);
}

Demo.
Comment: @AndriyK Unfortunately, .NET designers didn't think of `m` as a number, forcing us to resort to some ugly tricks, such as this one. At least this way you don't have to replace `"00m"` with regex in an additional step after formatting. On the other hand, you can build your own `HoursMinutes` object, make it `IFormattable`, and provide your custom formatting logic there. Adding an extension method to `DateTime` that produces an `HourMinute` object simplifies the way you call the formatter. Unfortunately, you have to do it outside the format string. Дуже прикро, але нажаль, це так :-)
Comment: Right, but this way zeroes will be there if it's 0 minutes, and that's exactly the problem I was trying to solve. I ended up with something in between: `{1:00;;''}`.
Comment: Well, that does the trick, but that's exactly what I'd love to avoid.
Comment: In fact, I don't need that trailing m, so way clearer `{1:##}` is sufficient for my case. And yes, I just ended up implementing my own `HoursMinutes` class. Дякую, anyway!
Comment: You'll might want to use `{1:00}` instead of `{1:##}` if you want to coerce nonzero minutes to a two-digit format, e.g. `15h01` instead of `15h1`.


Dovecot/Pigeonhole: How to specify default directory permission for newly created ./sieve directory for fresh uers?

Question: I am running Dovecot 2.3.20 with enabled Sieve support. I am using virtual mail boxes for several hosted virtual domains. The system account and group which owns (shall own) the directories and mail files on the filesystem is vmail:vmail.
I want all directories, incl. the directory which stores the user-specific sieve scripts, to be group readable and executable. However, if a fresh user accesses its mail account for the first time Dovecot creates the sieve directory within the user's mail home direcoty with permission 2700, i.e. the group vmail has no read access. How do I change that?
Background
The relevant Dovecot settings are
home=/var/spool/mail/vmail/%d/%{ldap:uid}
mail_location = sdbox:~/Maildir
sieve = file:~/sieve;active=~/.dovecot.sieve

The permissions on the top directory are as
server ~ # ls -lhad /var/spool/mail/vmail/
drwxr-s--- 4 vmail vmail 60 22. Dec 18:43 /var/spool/mail/vmail/

If I add a new account to LDAP and the relevant directories do not yet exist, Dovecot creates the following directory structure
server ~ # ls -lhR /var/spool/mail/vmail/my-test.tld
/var/spool/mail/vmail/my-test.tld:
insgesamt 0
drwxr-s--- 4 vmail vmail 56 16. Jan 00:45 john.doe

/var/spool/mail/vmail/my-test.tld/john.doe:
insgesamt 0
drwxr-s--- 3 vmail vmail 164 14. Jan 18:37 Maildir
drwx--S--- 3 vmail vmail  35 14. Jan 18:48 sieve     # <-- this should be drwxr-s---, too

/var/spool/mail/vmail/my-test.tld/john.doe/Maildir
insgesamt 0

/var/spool/mail/vmail/my-test.tld/john.doe/sieve
insgesamt 0

Answer: You can use umask
There is a very good write-up with examples here
Comment: I doubt that the problem is umask related. As ar as I can tell the umask value for the system account which runs the Dovecot daemon is 0022. If the directory was created accordingly, the permissions should be 0755. It rather seems that the daemon deliberately sets the directory permissions to a stricter value after creation. Hence, umask does not help here.


Db2: How to update the current value of a sequence

Question: We use a sequence in a Db2 database. Recently, we have migrated the data from an AIX server to a Linux server. During that the latest number of that sequence was not moved to the Linux system. As a consequence, we are seeing duplicates values now.
Here is how we use the sequence:
SELECT NEXTVAL FOR SEQ_YFS_ORDER_NO FROM SYSIBM.SYSDUMMY1

The current value of the sequence on Linux is 100092142. How can I update it to the current value that we have on the AIX system, i.e to (100110960)?
Answer: You can modify the sequence using ALTER SEQUENCE. An option offered by ALTER SEQUENCE is to RESTART it with a specific value. Try something like this:
ALTER SEQUENCE SEQ_YFS_ORDER_NO RESTART WITH 100110960

Also note that sequence numbers typically are cached. This may lead to a gap and could have caused the issue during the migration.
Answer: Use the below query to fetch next sequence value from DB2 database.
  SELECT NEXT VALUE FOR "Sequence_name"  FROM SYSIBM.SYSDUMMY1

Answer: Work Around
ALTER SEQUENCE SEQ_YFS_ORDER_NO INCREMENT BY (100110960-100092142);
SELECT SEQ_YFS_ORDER_NO FROM dual;
ALTER SEQUENCE SEQ_YFS_ORDER_NO INCREMENT BY 1;

Before backup of your database, you can too create one Stored Procedure to SET "START WITH" with current_value to all your SEQUENCES, so when you will do restore, they will be restored with your desired starts.


how to pass ComponentController to a controller

Question: I have a controller. I want to pass a DAO component userRepo to it
class UserController @Inject()(userRepo: Repository[User,Integer],cc: ControllerComponents)(implicit exec: ExecutionContext) extends AbstractController(cc){...}

I am hooking compile time DI as follows:
class AppComponents(context: Context) extends BuiltInComponentsFromContext(context) with CassandraRepositoryComponents {

  lazy val applicationController = new controllers.UserController(userRepository)
  lazy val assets = new controllers.Assets(httpErrorHandler)

  override def router: Router = new Routes(
    httpErrorHandler,
    applicationController,
    assets
  )
}

Question 1 - My issue is that I don't know what to pass as ControllerComponent
Question 2 - I am getting the following error missing parameter meta:AssetsMetaData for lazy val assets = new controllers.Assets(httpErrorHandler)
Question 3 - I suppose I am not using Routes correctly as well. I can see that IDE is displaying a potential error cannot resolve constructor
  override def router: Router = new Routes(
    httpErrorHandler,
    applicationController,
    assets
  )

I am following the following tutorial but as it is based on Play 2.4, it will probably not run in 2.6. How could I make the code above work in Play 2.6?
http://manuel.kiessling.net/2016/01/17/compile-time-cassandra-injection-in-play-2-4/
Answer: Answer to 1 - BuiltInComponentsFromContext has an instance of ControllerComponents
Answer to 2 - Used assets defined in BuiltInComponentsFromContext.
Answer to 3 - The routes file expects that all the controllers are passed to it. In my case. I wasn't passing all the controllers.
Full code
class AppComponents (context: Context) extends BuiltInComponentsFromContext(context)
  with CassandraRepositoryComponents
  with HttpFiltersComponents
  with controllers.AssetsComponents
  with CSRFComponents{

  lazy val userRepositoryController = new controllers.UserController(userRepository, controllerComponents) //answer 1
  lazy val homeController = new controllers.HomeController(controllerComponents, csrfAddToken,csrfCheck) //answer 3. create all controllers and pass it to Routes below
  //AtomicCounter is application's class, not Play's class to it is instantiated explicitly in the loader.
  lazy val countController = new controllers.CountController(controllerComponents,new AtomicCounter())
  lazy val asyncController = new controllers.AsyncController(controllerComponents, actorSystem)

  lazy val userWSRoutes = new WSRouters.User.UserRouter(userRepositoryController) //I am using SIRD router, so creating them here

  lazy val router = new Routes(httpErrorHandler, homeController,userWSRoutes, countController,asyncController, assets) //answer to 2

}


Jacobian Invariant

Question: I'm trying to find an on-line source for the "Jacobian Invariant" of four points on a line.
The cross-ratio depends on the order of the points, while this one doesn't.
I've done several Google searches and can't seem to find anything.
Does anyone know of a good source off-hand?
Answer: The commonly used name is $j$-invariant. See here or here (you will have to read a little to realize that they are talking about the same thing!)

Jacobian Invariant


Console dump of a DCOM configuration for a given GUID?

Question: Is there a way to dump the DCOM settings for a given DCOM object on the command line, if the GUID is known? (Maybe using PowerShell)
Comment: I can't recall anything built in but a few uses of `reg query /s ‹path›` over the usual places (`HKEY_CLASSES_ROOT\AppId\‹GUID›`, ...) shouldn't be too hard to put together. In PSH It would be more work because `Get-ItemProperty` to get the values doesn't have a recursive option, so a combination of `Get-ChildItem -recurse` and `Get-ItemProperty` would be needed.
Answer: I've never done it but it looks like you could use the comadmin class to begin exploring the administrative interfaces ( <code>$comadmin = new-object -com "comadmin.comadmincatalog"</code> )
See http://msdn.microsoft.com/en-us/library/ms683573(v=vs.85) for an overview of the comadmin namespace


Why does the .Net Dictionary look like it is sorted?

Question: I was looking at some code my co-worker checked in, it looked like this:
return list.OrderBy(item => item.Order).ToDictionary(item => item.Id);

I immediately told my co-worker that his code is wrong, because the Dictionary is a hash table, a non-sorted collection. He should either use an order-preserving collection, or sort the items later as he reads them from the dictionary with foreach, I said.
But he replied "No, no, my code is correct! Look: now that I have added the OrderBy, the items appear in correct order."
Turns out, on the test case, he was right. I tried on some other data, but it still was perfectly sorted!
I told him that he should not rely on this behaviour, but he disagrees, and I'm having trouble explaining why. Besides, I'm interested in why the order so often seem to be preserved.
So my question is... Why does the Dictionary, a fundamentally unsorted collection, looks so much like it is sorted?
Comment: Dictionary<> provides no guarantee that the collection is unordered.  It doesn't use Random on purpose.  Yes, the code is wrong.
Comment: @EldritchConundrum -- It was the first result on Google for `.net dictionary order`.  I find that Google sometimes works better than the built in search.
Comment: yes Justin, this is a duplicate. The answer of the question you linked is what I wanted. How can you find duplicates so quickly among so many questions about dictionaries? I searched and couldn't find it. Thank you!
Comment: I don't know (which is why I'm posting this as a comment) but I imagine it's the same as in SQL: the rows returned by `SELECT` are returned in unspecified order unless an `ORDER BY` clause is included. Often, particularly in small data sets, the rows are returned in the same order they were inserted, which trips a lot of people up. (I always tell people to include an `ORDER BY` if they care at all about the ordering of the results. It *might* work without it, but it also might break horribly.)
Answer: It is sorted, because of how Dictionary is implemented (and in your case items are added in order). But this is implementation details.
Tell your co-worker there is a SortedDictionary class that exists, this should convince him we can't rely on the items order with a simple Dictionary ;)
Comment: It is an implementation detail, sure, but I don't think it is going to change. Maybe it is ok to say that Add()-only dictionaries do preserve order.
Comment: @EldritchConundrum Really, you shouldn't assume that. Currently it is the case, but in a future version it might not be. And think about other implementations of the framework (Mono for instance), there is no guarantee they implemented Dictionary the same way.
Comment: Yes. More importantly, now I know how to build a test case that my co-worker's code will fail on ;) I just have to remove and add before the foreach.
Answer: When iterating over a dictionary you would get the items in it in the order they were inserted to the dictionary.
In the example, a list gets sorted, then each item gets added to the dictionary in turn.
The end result is that the items in the dictionary are in the sort order of the list.
However, this just happens to be the case with the current implementation of Dictionary - there is no guarantee that it will stay that way.
If you need to have the items in a Dictionary in a specific order, you should be using a SortedDictionary.
Comment: @LuisFilipe - I don't follow. The list got ordered (`list.OrderBy(item => item.Order)` then converted to a `Dictionary`. The conversion works by adding each item to the dictionary. The items in the dictionary are "ordered" in that they are in insertion order. Since they were _inserted_ in order, the dictionary is in order.
Comment: Luis, actually keys are stored in a hash-dependent order, but values are not, and the dictionary enumerator uses the value store.
Comment: Can you explain better why are they sorted. I'd say they are "ordered" by their hash which is the property "Id"
Comment: Is this guaranteed by specification/contract, or is it an artifact of how a specific implementation is written? If it is guaranteed behavior, a citation would be useful.
Comment: @MichaelKjörling - There is no guarantee, it is simply how the current version of `Dictionary` is implemented.
Comment: Yes, I saw your edit after I added that comment. :)


Mostrar / Esconder div, mudando o icone

Question: Tenho o seguinte Snippet, onde ao clicar no  o conteúdo da div é mostrado (revelado) e ao clicar no  o conteúdo da div é recolhido (escondido), porém as imagens não estão alterando corretamente, alguém sabe como corrigir isso!?

//    Script para revelar/esconder os endereços
jQuery.fn.toggleText = function(a, b) {
    return this.html(this.html().replace(new RegExp('(' + a + '|' + b + ')'), function(x) {
        return (x == a) ? b : a;
    }));
}
$(document).ready(function() {
    var img = document.getElementById('mostraEsconde');
    $('.tgl').css('display', 'none')
    $('legend', '#box-toggle').click(function(){
        $(this).next().slideToggle('slow')
            .siblings('.tgl:visible').slideToggle('fast');
        // aqui começa o funcionamento do plugin
        $(this).toggleText(img.srcset = 'https://cdn2.iconfinder.com/data/icons/icojoy/noshadow/transparent/png/24x24/001_01.png', img.srcset = 'https://cdn2.iconfinder.com/data/icons/icojoy/shadow/standart/png/24x24/001_02.png')
            .siblings('legend').next('.tgl:visible').prev()
            .toggleText(img.srcset = 'https://cdn2.iconfinder.com/data/icons/icojoy/noshadow/transparent/png/24x24/001_01.png', img.srcset = 'https://cdn2.iconfinder.com/data/icons/icojoy/shadow/standart/png/24x24/001_02.png')
    });
})

    <fieldset>
        <legend style="overflow: hidden;">
            Endereço Cobrança

        </legend>

            <input name="data[Endereco0][id]" id="enderecoID" value="49781" type="hidden">

                Tipo Endereço
                <select name="data[Endereco0][tipo_endereco_id]" id="tipos_enderecoID" style="width: 98%">
                    <option value=""> Selecionar </option>
                    <option value="1">Residencial</option>
                    <option value="2">Entrega</option>
                    <option value="3" selected="selected">Cobrança</option>
                    <option value="4">Comercial</option>
                </select>

                Rua
                <input name="data[Endereco0][rua]" value="R SETE DE SETEMBRO" id="Endereco0Rua" type="text">

                Numero
                <input name="data[Endereco0][numero]" value="427" id="Endereco0Numero" type="text">

                Complemento
                <input name="data[Endereco0][complemento]" value="Complemento teste" id="Endereco0Complemento" type="text">

                Cep
                <input name="data[Endereco0][cep]" value="96015300" id="Endereco0Cep" type="text">

                Bairro
                <input name="data[Endereco0][bairro]" value="CENTRO" id="Endereco0Bairro" type="text">

                Selecione o Estado
                <select name="data[Endereco0][uf]" id="estadoID_0" style="width: 98%">
                    <option value=""> Selecionar </option>
                    <option value="IN">IN - Indefinido</option>
                    <option value="AC">AC - Acre</option>
                    <option value="AL">AL - Alagoas</option>
                    <option value="AM">AM - Amazonas</option>
                    <option value="AP">AP - Amapá</option>
                    <option value="BA">BA - Bahia</option>
                    <option value="CE">CE - Ceará</option>
                    <option value="DF">DF - Distrito Federal</option>
                    <option value="ES">ES - Espírito Santo</option>
                    <option value="GO">GO - Goiás</option>
                    <option value="MA">MA - Maranhão</option>
                    <option value="MG" selected="selected">MG - Minas Gerais</option>
                    <option value="EX">EX - Exterior</option>
                </select>

                Selecione a Cidade
                <select name="data[Endereco0][municipio_id]" id="municipioID_0" style="width: 98%">
                    <option value=""> Selecionar </option>
                    <option value="3" selected="selected">Abadia dos Dourados</option>
                    <option value="6">Abaeté</option>
                    <option value="7">Abaeté dos Mendes (Rio Paranaíba)</option>
                </select>

    </fieldset>

    <fieldset>
        <legend style="overflow: hidden;"> Endereço Cobrança
        </legend>

            <input name="data[Endereco1][id]" id="enderecoID" value="50888" type="hidden">

                Tipo Endereço
                <select name="data[Endereco1][tipo_endereco_id]" id="tipos_enderecoID" style="width: 98%">
                    <option value=""> Selecionar </option>
                    <option value="1">Residencial</option>
                    <option value="2">Entrega</option>
                    <option value="3" selected="selected">Cobrança</option>
                    <option value="4">Comercial</option>
                </select>

                Rua
                <input name="data[Endereco1][rua]" value="R SETE DE SETEMBRO" id="Endereco1Rua" type="text">

                Numero
                <input name="data[Endereco1][numero]" value="427" id="Endereco1Numero" type="text">

                Complemento
                <input name="data[Endereco1][complemento]" value="Complemento teste" id="Endereco1Complemento" type="text">

                Cep
                <input name="data[Endereco1][cep]" value="96015300" id="Endereco1Cep" type="text">

                Bairro
                <input name="data[Endereco1][bairro]" value="CENTRO" id="Endereco1Bairro" type="text">

                Selecione o Estado
                <select name="data[Endereco1][uf]" id="estadoID_1" style="width: 98%">
                    <option value=""> Selecionar </option>
                    <option value="IN">IN - Indefinido</option>
                    <option value="AC">AC - Acre</option>
                    <option value="AL">AL - Alagoas</option>
                    <option value="AM">AM - Amazonas</option>
                    <option value="AP">AP - Amapá</option>
                    <option value="BA">BA - Bahia</option>
                    <option value="CE">CE - Ceará</option>
                    <option value="DF">DF - Distrito Federal</option>
                    <option value="ES">ES - Espírito Santo</option>
                    <option value="GO">GO - Goiás</option>
                    <option value="MA">MA - Maranhão</option>
                    <option value="MG" selected="selected">MG - Minas Gerais</option>
                </select>

    </fieldset>

        <input value="Editar" type="submit">

OBS.: O segundo item, funciona normalmente, o primeiro é que está bugando...
Comment: Cara, primeiro veja esse erro: `Uncaught TypeError: Cannot read property 'replace' of undefined`. Está dando esse erro no momento em que clica no ícone.
Comment: Pois é @DouglasGarrido, eu percebi, mas acho que é erro do snippet, pois no meu código aqui não ta dando esse erro. (deve ser alguma biblioteca do jquery)
Comment: Joga tem código então em um [JSFiddle](https://jsfiddle.net/) e veja se lá dá erro.
Comment: Blz, vou testar!
Answer: O problema está ocorrendo pois o seletor document.getElementById espera retornar um único elemento, já que a propriedade id serve para identificar um elemento único no DOM. Uma alternativa seria trocar o atributo "id" por "name" nos links clicáveis (name="mostraEsconde") e alterar o seletor para:
var img = document.getElementsByName('mostraEsconde');

Você pode testar o funcionamento aqui: https://jsfiddle.net/marcellalves/cuww8Lky/10/
Comment: Descobri o problema, ele cria o versionamento via url, segue a url com a correção: https://jsfiddle.net/marcellalves/cuww8Lky/10/
Comment: _Cara, teu `fiddle` não funcionou._  Fiz uma alteração no meu código, testando com id's diferentes e o mesmo erro prosseguiu, fiz alterando para `getElementsByName` e não alterava as imagens de nenhum.
Comment: Testa de novo o meu fiddle. Fiz uma correção agora.
Comment: Eu estou corrigindo o fiddle, mas parece que ele não está salvando as minhas alterações. Fiz uma nova correção, peço desculpas pelo transtorno.
Comment: Corrigi o link do fiddle na resposta também.
Answer: Troque o seletor para:
var img = document.querySelectorAll('img');

jQuery.fn.toggleText = function(a, b) {
    return this.html(this.html().replace(new RegExp('(' + a + '|' + b + ')'), function(x) {
        return (x == a) ? b : a;
    }));
}
$(document).ready(function() {
    var img = document.querySelectorAll('img');
    $('.tgl').css('display', 'none')
    $('legend', '#box-toggle').click(function(){
        $(this).next().slideToggle('slow')
            .siblings('.tgl:visible').slideToggle('fast');
        // aqui começa o funcionamento do plugin
        $(this).toggleText(img.srcset = 'https://cdn2.iconfinder.com/data/icons/icojoy/noshadow/transparent/png/24x24/001_01.png', img.srcset = 'https://cdn2.iconfinder.com/data/icons/icojoy/shadow/standart/png/24x24/001_02.png')
            .siblings('legend').next('.tgl:visible').prev()
            .toggleText(img.srcset = 'https://cdn2.iconfinder.com/data/icons/icojoy/noshadow/transparent/png/24x24/001_01.png', img.srcset = 'https://cdn2.iconfinder.com/data/icons/icojoy/shadow/standart/png/24x24/001_02.png')
    });
})

    <fieldset>
        <legend style="overflow: hidden;">
            Endereço Cobrança

        </legend>

            <input name="data[Endereco0][id]" id="enderecoID" value="49781" type="hidden">

                Tipo Endereço
                <select name="data[Endereco0][tipo_endereco_id]" id="tipos_enderecoID" style="width: 98%">
                    <option value=""> Selecionar </option>
                    <option value="1">Residencial</option>
                    <option value="2">Entrega</option>
                    <option value="3" selected="selected">Cobrança</option>
                    <option value="4">Comercial</option>
                </select>

                Rua
                <input name="data[Endereco0][rua]" value="R SETE DE SETEMBRO" id="Endereco0Rua" type="text">

                Numero
                <input name="data[Endereco0][numero]" value="427" id="Endereco0Numero" type="text">

                Complemento
                <input name="data[Endereco0][complemento]" value="Complemento teste" id="Endereco0Complemento" type="text">

                Cep
                <input name="data[Endereco0][cep]" value="96015300" id="Endereco0Cep" type="text">

                Bairro
                <input name="data[Endereco0][bairro]" value="CENTRO" id="Endereco0Bairro" type="text">

                Selecione o Estado
                <select name="data[Endereco0][uf]" id="estadoID_0" style="width: 98%">
                    <option value=""> Selecionar </option>
                    <option value="IN">IN - Indefinido</option>
                    <option value="AC">AC - Acre</option>
                    <option value="AL">AL - Alagoas</option>
                    <option value="AM">AM - Amazonas</option>
                    <option value="AP">AP - Amapá</option>
                    <option value="BA">BA - Bahia</option>
                    <option value="CE">CE - Ceará</option>
                    <option value="DF">DF - Distrito Federal</option>
                    <option value="ES">ES - Espírito Santo</option>
                    <option value="GO">GO - Goiás</option>
                    <option value="MA">MA - Maranhão</option>
                    <option value="MG" selected="selected">MG - Minas Gerais</option>
                    <option value="EX">EX - Exterior</option>
                </select>

                Selecione a Cidade
                <select name="data[Endereco0][municipio_id]" id="municipioID_0" style="width: 98%">
                    <option value=""> Selecionar </option>
                    <option value="3" selected="selected">Abadia dos Dourados</option>
                    <option value="6">Abaeté</option>
                    <option value="7">Abaeté dos Mendes (Rio Paranaíba)</option>
                </select>

    </fieldset>

    <fieldset>
        <legend style="overflow: hidden;"> Endereço Cobrança
        </legend>

            <input name="data[Endereco1][id]" id="enderecoID" value="50888" type="hidden">

                Tipo Endereço
                <select name="data[Endereco1][tipo_endereco_id]" id="tipos_enderecoID" style="width: 98%">
                    <option value=""> Selecionar </option>
                    <option value="1">Residencial</option>
                    <option value="2">Entrega</option>
                    <option value="3" selected="selected">Cobrança</option>
                    <option value="4">Comercial</option>
                </select>

                Rua
                <input name="data[Endereco1][rua]" value="R SETE DE SETEMBRO" id="Endereco1Rua" type="text">

                Numero
                <input name="data[Endereco1][numero]" value="427" id="Endereco1Numero" type="text">

                Complemento
                <input name="data[Endereco1][complemento]" value="Complemento teste" id="Endereco1Complemento" type="text">

                Cep
                <input name="data[Endereco1][cep]" value="96015300" id="Endereco1Cep" type="text">

                Bairro
                <input name="data[Endereco1][bairro]" value="CENTRO" id="Endereco1Bairro" type="text">

                Selecione o Estado
                <select name="data[Endereco1][uf]" id="estadoID_1" style="width: 98%">
                    <option value=""> Selecionar </option>
                    <option value="IN">IN - Indefinido</option>
                    <option value="AC">AC - Acre</option>
                    <option value="AL">AL - Alagoas</option>
                    <option value="AM">AM - Amazonas</option>
                    <option value="AP">AP - Amapá</option>
                    <option value="BA">BA - Bahia</option>
                    <option value="CE">CE - Ceará</option>
                    <option value="DF">DF - Distrito Federal</option>
                    <option value="ES">ES - Espírito Santo</option>
                    <option value="GO">GO - Goiás</option>
                    <option value="MA">MA - Maranhão</option>
                    <option value="MG" selected="selected">MG - Minas Gerais</option>
                </select>

    </fieldset>

        <input value="Editar" type="submit">

Comment: Lembre-se o `id` deve ser único em cada página....
Comment: Perfeito @MagicHat, não conhecia esse seletor!
Mudei no meu código e funcionou perfeitamente!
Valeu
Comment: Verdade, falha minha, mas foi bom, pois aprendi mais um pouquinho 8)

Mostrar / Esconder div, mudando o icone


How do I convert a PIL Image into a NumPy array?

Question: How do I convert a PIL Image back and forth to a NumPy array so that I can do faster pixel-wise transformations than PIL's PixelAccess allows? I can convert it to a NumPy array via:
pic = Image.open("foo.jpg")
pix = numpy.array(pic.getdata()).reshape(pic.size[0], pic.size[1], 3)

But how do I load it back into the PIL Image after I've modified the array? pic.putdata() isn't working well.
Comment: Note that `pic.size[0]` and `pic.size[1]` should be swapped (ie. `reshape(pic.size[1], pic.size[0], 3)`), since `size` is `width x height` or `x * y`, while matrix ordering is `rows x columns`.
Answer: You're not saying how exactly putdata() is not behaving. I'm assuming you're doing
>>> pic.putdata(a)
Traceback (most recent call last):
  File "...blablabla.../PIL/Image.py", line 1185, in putdata
    self.im.putdata(data, scale, offset)
SystemError: new style getargs format but argument is not a tuple

This is because putdata expects a sequence of tuples and you're giving it a numpy array. This
>>> data = list(tuple(pixel) for pixel in pix)
>>> pic.putdata(data)

will work but it is very slow.
As of PIL 1.1.6, the "proper" way to convert between images and numpy arrays is simply
>>> pix = numpy.array(pic)

although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case).
Then, after you make your changes to the array, you should be able to do either pic.putdata(pix) or create a new image with Image.fromarray(pix).
Comment: That page lists `numpy.asarray(pic)` as the "proper" way to convert, not `numpy.array(pic)`. As per [this answer](http://stackoverflow.com/questions/14415741/numpy-array-vs-asarray) `array` will make a copy whereas `asarray` will not (but then the `asarray` result will be read-only).
Comment: The second answer is better.
Comment: Type check warns: 'Expected type 'Union[ndarray, Iterable, int, float]', got 'Image' instead'
Answer: Open I as an array:
>>> I = numpy.asarray(PIL.Image.open('test.jpg'))

Do some stuff to I, then, convert it back to an image:
>>> im = PIL.Image.fromarray(numpy.uint8(I))

Source: Filter numpy images with FFT, Python
If you want to do it explicitly for some reason, there are pil2array() and array2pil() functions using getdata() on this page in correlation.zip.
Comment: Is the `uint8` conversion necessary?
Comment: `numpy.asarray(Image.open(filename))` seems to work for .jpg images but not for .png.  The result displays as `array(, dtype=object)`.  There seem to be no obviously-named methods of the `PngImagePlugin.PngImageFile` object for solving this.  Guess I should ask this as a new question but it's very relevant to this thread. Anybody understand what's going wrong here?
Comment: @jez Check if the Image object is closed before you convert it to numpy. The same happened to me and I found I closed the image object somewhere.
Comment: @Rebs: here's the reason *why* this is so much faster: `getdata()` returns a sequence like object (http://pillow.readthedocs.io/en/3.4.x/reference/Image.html#PIL.Image.Image.getdata), but a pillow image implements the `__array_interface__` which `numpy` can use to access the raw bytes of an image without having to pass through an iterator (see https://github.com/python-pillow/Pillow/blob/730cf93c32ffb747c018afffe597ef9ae264a20a/PIL/Image.py#L633 and https://docs.scipy.org/doc/numpy/reference/arrays.interface.html). You can even just use `numpy.array(PIL.Image.open('test.jpg'))`
Comment: @ArditS.: Did you `import Image` first?  Do you have PIL installed?
Comment: you might need to use numpy.copy to have I be editable: `I = numpy.copy(numpy.asarray(Image.open('test.jpg')))`
Comment: Thanks for this, I was using np.array(image.getdata(),...) which is incredibly slow compared to this.
Comment: @NeilTraft No, sorry.  Note that if your image is a float array from 0 to 1, you need to scale it first: `Image.fromarray(J*255)`
Comment: @jez I use `numpy.asarray(PIL.Image.open('test.png').convert('RGB'))` which works for even for .png images
Answer: I am using Pillow 4.1.1 (the successor of PIL) in Python 3.5. The conversion between Pillow and numpy is straightforward.
from PIL import Image
import numpy as np
im = Image.open('1.jpg')
im2arr = np.array(im) # im2arr.shape: height x width x channel
arr2im = Image.fromarray(im2arr)

One thing that needs noticing is that Pillow-style im is column-major while numpy-style im2arr is row-major. However, the function Image.fromarray already takes this into consideration. That is, arr2im.size == im.size and arr2im.mode == im.mode in the above example.
We should take care of the HxWxC data format when processing the transformed numpy arrays, e.g. do the transform im2arr = np.rollaxis(im2arr, 2, 0) or im2arr = np.transpose(im2arr, (2, 0, 1)) into CxHxW format.
Comment: This is about the cleanest example, including import statements (thanks for that detail). Let's vote this answer up to increase visibility.
Comment: I found that when I converted a PIL drawn image to a numpy array, when using matplotlib imshow on the array, it showed it upside down requiring a `np.flipud` to fix. Although my PIL image was created from scratch using `ImageDraw.Draw`. I think one must be careful where the origin of their coordinates comes from.
Comment: Bless you!! I have been looking for this answer for half a day. It solves my problem of restoring the original axis after of the plot image to the original one.
Answer: You need to convert your image to a numpy array this way:
import numpy
import PIL

img = PIL.Image.open("foo.jpg").convert("L")
imgarr = numpy.array(img)

Comment: @moondra If I understand your question, you can replace `.convert("L") ` by `.convert("RGB")`
Comment: This way of conversion retains the image but results in a loss of colors. Anyway to avoid the color loss?
Comment: "L" produces the image in grayscale
Answer: Convert Numpy to PIL image  and PIL to Numpy
import numpy as np
from PIL import Image

def pilToNumpy(img):
    return np.array(img)

def NumpyToPil(img):
    return Image.fromarray(img)

Answer: The example, I have used today:
import PIL
import numpy
from PIL import Image

def resize_image(numpy_array_image, new_height):
    # convert nympy array image to PIL.Image
    image = Image.fromarray(numpy.uint8(numpy_array_image))
    old_width = float(image.size[0])
    old_height = float(image.size[1])
    ratio = float( new_height / old_height)
    new_width = int(old_width * ratio)
    image = image.resize((new_width, new_height), PIL.Image.ANTIALIAS)
    # convert PIL.Image into nympy array back again
    return array(image)

Answer: If your image is stored in a Blob format (i.e. in a database) you can use the same technique explained by Billal Begueradj to convert your image from Blobs to a byte array.
In my case, I needed my images where stored in a blob column in a db table:
def select_all_X_values(conn):
    cur = conn.cursor()
    cur.execute("SELECT ImageData from PiecesTable")
    rows = cur.fetchall()
    return rows

I then created a helper function to change my dataset into np.array:
X_dataset = select_all_X_values(conn)
imagesList = convertToByteIO(np.array(X_dataset))

def convertToByteIO(imagesArray):
    """
    # Converts an array of images into an array of Bytes
    """
    imagesList = []

    for i in range(len(imagesArray)):
        img = Image.open(BytesIO(imagesArray[i])).convert("RGB")
        imagesList.insert(i, np.array(img))

    return imagesList

After this, I was able to use the byteArrays in my Neural Network.
plt.imshow(imagesList[0])

Answer: I can vouch for svgtrace, I found it both super simple and relatively fast. Find it here: https://pypi.org/project/svgtrace/
This  is how I used it:
from svgtrace import trace

asset_path = 'image.png'
save_path = 'traced_image.svg'

Path(save_path).write_text(trace(asset_path), encoding='utf-8')

It took an average of 3 seconds for a 1080x1080px image on my machine. (MacBook Pro 2017)
Answer: def imshow(img):
    img = img / 2 + 0.5     # unnormalize
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()

You can transform the image into numpy
by parsing the image into numpy() function after squishing out the features( unnormalization)
Comment: This is for conversion between numpy and a tensor in e.g. PyTorch. This question is about PIL.


maybe stupid question: If a single java app on a separate server is causing 23Gigs of Binlogs to be sent to the db replica

Question: does this mean there is 23gb of traffic (or more ) moving between the Java app (server) and the master Mysql server?
this has been bugging me.
The reason why I ask is because we have one server that is dedicated to our App.  Nothing else connects to the DB.  Our Binlogs on the master average about 23gigs per day.
does this make sense?
Comment: just to add: there are no other databases on the db servers.
Answer: If nothing else connects to the DB look at Bytes_received from a mysql show status; query 24 hours apart.


Urn balls without replacement, probability on nth position

Question:
An urn contains $w$ white and $b$ black balls. $n$ extractions without replacement are made. What are the probabilty of:

get a black ball on $i-th$ extraction?
get a black ball on $i-th$ extraction and white on $j-th$ extraction, with $j > i$?

I know that the hypergeometric distribution doesn't care about position, so what is the math behind this problem?
Comment: For the first question, ask yourself, which of the $(w+b)$ balls is/are more or less likely to be the one chosen at the $i-th$ turn? For the second question, you can reason similarly but keep in mind that the two events are not quite independent.
Comment: For the second, by symmetry it is the same as the probability of black on the first and white on the second. This is easy.
Comment: @Ned I would say $\frac{b}{w+b}$, but I don't really understand why.
Comment: yes for the first question, because each of the balls is equally likely to be the $i-th$ one chosen. Thinking about conditional probability and/or the previous choices here just adds extraneous information that isn't needed to answer the question.
Comment: @Ned So, if I understand the symmetry the probability to get a black ball on $i−th$ extraction, white on $j−th$ extraction, black on $k−th$ extraction and white on $z−th$ extraction, with $z>k>j>i$ is
$\frac{b}{w+b}\frac{w}{w+b-1}\frac{b-1}{w+b-2}\frac{w-1}{w+b-3}$, right?
Comment: yes, that looks right--ignore the other draws because each of the non-specified balls is equally likely to be the chosen ball at each turn you are considering (i.e. values of $i, j, k, l$ are irrelevant beyond the ordering among them).
Answer: Just imagine them all placed randomly  in a row, their position won't change by extraction
Then P(a black ball is in any position) $=\frac{b}{w+b}$,
and P(a white ball is in any position) $= \frac{w}{w+b}$.
This directly gives the answer for the first part

P(get a black ball on i−th extraction) $=\frac{b}{w+b}$
For P(get a black ball on i−th extraction and white on j−th extraction), the logic is more subtle, the probabilities of a $B-W$ pair occupying any  two positions will be the same, hence the same as $B-W$ occupying positions $1$ and $2$, $=\frac{bw}{(b+w)(b+w-1)}$
Comment: I think I'm closer. The probability to get a black ball on first draw is $\frac{b}{w+b}$. If I get a black ball on first draw then the probability to get a black ball on second draw is $\frac{b-1}{w+b-1}$, but in this case I conditioned the result.
Comment: Suppose there is 1 white ball and 1 black ball.  Let i=1 and j=2.  Clearly the probability of black then white is 1/2 not 1/4 as suggested by the above answer.
Comment: My answer to the 2nd part was incorrect. I will amend.
Comment: So, using the symmetry stuff provided by André Nicolas the answer to 2nd part is $\frac{b}{w+b}\frac{w}{w+b-1}$?
Comment: That's right. In my revision, I have indicated the type of symmetry involved.
Answer:
Number of all $i$ extractions are $S(i)=\binom{n}{i}*i!$
Number of cases where to get a black ball on $i$th extraction is $B(i)$

$B(i)=b*\binom{n-1}{i-1}(i-1)!$
probability is $P(i)=\frac{B(i)}{S(i)}$

Number of cases where to get a black ball on $i$th then white on $j$th is $W(i)$

$W(j)=b*w*\binom{n-2}{j-2}(j-2)!$
probability is $P(j)=\frac{W(j)}{S(j)}$
Answer: Simplest way to visualize this (at least for me) is to forget the fact that there are balls of two colors in the urn, and just imagine that each ball in the urn is a 'mixture' of both the colors.
Now, it is easy to see that each draw doesn't change any thing w.r.t. the distribution. That way the probability is independeny of each draw.


Is there a way to pass tags to SonarQube via maven command line?

Question: I am running the sonar-plugin in my Jenkinsfile. I'd like to pass some tags for the builds I am running. My projects consists of multiple modules (article, authentication) and I'd like to add <moduleName>_<branchName> as a SonarQube tag.
My maven command line I run in the Jenkinsfile looks like this:
sh "mvn -B -Dsonar.projectName=MyProject_${module}_${env.BRANCH_NAME} -Dsonar.projectKey=${Config.groupId}:${module}_${env.BRANCH_NAME} -Dsonar.host.url=${Config.sonarUrl}"

Is there any way to pass tags to SonarQube or do I have to apply them in SonarQube manually?
Comment: Did you consider using the new "branch" feature of the (paid) Developer Edition of SonarQube 6.7?
Answer: You can use the project_tags api, to set project tags. An example:
curl -XPOST http://your.sonarqube/api/project_tags/set?project=yourproject&tags=yourmodule_yourbranch

Comment: You can vote for this feature: https://community.sonarsource.com/t/add-tags-through-maven-pom-file/28611


Error consolidation/annotated-command

Question: Trying to install Drush using Composer, i get an error concerning consolidation/annotated-command. What does it mean "locked at 2.0.3" and "requires 2.8.1"?
This is the error:
Your requirements could not be resolved to an installable set of packages.

  Problem 1

- Installation request for drush/drush dev-master -> satisfiable by drush/drush[dev-master].
- Conclusion: remove consolidation/annotated-command 2.0.3
- Conclusion: don't install consolidation/annotated-command 2.0.3
- drush/drush dev-master requires consolidation/annotated-command ^2.8.1 -> satisfiable by consolidation/annotated-command[2.8.1, 2.8.2].
- Can only install one of: consolidation/annotated-command[2.8.1, 2.0.3].
- Can only install one of: consolidation/annotated-command[2.8.2, 2.0.3].
- Installation request for consolidation/annotated-command (locked at 2.0.3) -> satisfiable by consolidation/annotated-command[2.0.3].

Installation failed, reverting ./composer.json to its original content.

Comment: You have something already installed that's locked to a version of a dependency that drush needs a more recent version of. See what's in your global composer file
Comment: @Clive, thx for pointing me to _composer.lock_. But how to overcome this constraint? _Composer info_ shows v2.8.1 for _annotated-command_.
Comment: You can't overcome the constraint, it's a hard constraint. You'll need to find the package that depends on the old version and remove/upgrade it. Try running `composer prohibits consolidation/annotated-command 2.8.1`, hopefully that'll give you some info to go on
Comment: The command results in "no installed package depending on _consolidation/annotated-command_ in versions not matching 2.8.1"
When I changed to 2.0.3, the result is "__ root __  -  requires  consolidation/annotated-command (2.8.1)"
Answer: I get this error after changing the minimum version of drush/drush to ~9.0 in my composer.json and running composer update drush/drush afterwards.
I solved it by just executing composer require drush/drush:~9.0 which lead to the error message drush/drush 9.5.x-dev requires symfony/config ^3.4, so I had to execute composer require symfony/config:^3.4 before composer require drush/drush:~9.0 could be finished successful.
Don't know if this is the only way or best practice to solve such a dependency conflict but in short this worked for me:

composer require symfony/config:^3.4
composer require drush/drush:~9.0

Error consolidation/annotated-command