Three.js Texture scaling issue when using THREE.ShaderMaterial to map a renderTarget.texture to a quad

Question: A codepen demonstrating this issue is here: https://codepen.io/lilrooness/pen/QWjdjgP
I'm rendering noise to a render target and then using that render target to texture a quad that I render to the screen.
When using the render target as a texure I'm encoutering a problem with the textures size.
It works fine if I use new THREE.MeshBasicMaterial({ map: renderTarget.texture })

but when I use my own material
        var renderMaterial = new THREE.ShaderMaterial({
            uniforms: {
                tex: { type: 'sampler2D', value: renderTarget.texture }
            },
            fragmentShader: pixelateFragmentShader(),
            vertexShader: standardVertexShader()
        })

I get a very small texture that's clamped

This is the vertex shader that I use for both renders:
                varying lowp vec3 vUv;

                void main() {
                    vUv = position;
                    vec4 modelViewPosition = modelViewMatrix * vec4(position, 1.0);
                    gl_Position = projectionMatrix * modelViewPosition;
                }

this is the rendering function (im using the same camera to render both times)
        function animate() {
            time += 0.1;
            quad.material.uniforms.time.value = time;
            requestAnimationFrame(animate);
            renderer.setRenderTarget(renderTarget);
            renderer.render(bufferScene, camera);
            renderer.setRenderTarget(null);
            renderer.render(scene, camera);
        }

Again, this works fine if I use the MeshBasicMaterial. What am I doing wrong?
Comment: There are many interesting things: using `PlaneGeometry()` (instead of `PlaneBufferGeoemtry()`), `position` as uv.
Comment: Any chances to demonstrate the issue with a live example? Or maybe with a GitHub repository?
Comment: THanks for the hint @prisoner849 - changed the vertex shader to use UV instaed of position and it started working. I'm new to this and I didn't realise UV was available to the vertext shader
Comment: @manthrax this was intentional for the perlin noise fragment shader, however I was re-suing the same vertex shader for the final render, and this was causing problems

thanks for the help :)
Comment: https://codepen.io/lilrooness/pen/QWjdjgP here is a codepen demonstrating the issue
Comment: @manthrax - I don't want the texture repeated or clamped, I want it to be stretched to the same size as the quad it is rendered to
Comment: You're not getting your vUv from the geometry.. you're setting it from the position.. is that intentional?
Answer: The problem was that, in my vertex shader I was setting
vUv = position
While this was desired behaviour for the perlin noise effect, I was re-using the same vertex shader to render the render target texture
I changed it to:
vUv = uv;


What statistical test should i use for the given scenario?

Question: I have an hypothesis that in people who have used both ios and android, a majority of them say 70% prefer android. I have a sample size of 50-60 users who have used both ios and android. What statistical methodology/tool/test should I use to confirm my hypothesis ?
Answer: After interrogating each of the users about his/her preference, you can easily check your hypothesis using the one-sample z-Test for proportions. You can find it in most statistical softwares. Alternatively, you can directly apply the test and calculate the z value using the formula $z = (p - p_0)/\sqrt{p_0(1 - p_0)/n\,{}}$, where $p$ is the proportion actually observed (in your case, the proportion of users who prefer android), $p_0$ is the initial claim/hypothesis (in this case $0.70$), and $n$ is the sample size. Then you can search the p-value corresponding to the z-value using the standard tables or online conversion tools.
If the test provides a nonsignificant p-value, then it means that the null hypothesis (your initial claim) cannot be rejected.


Volume of a cube in spherical polars

Question: Let us calculate the volume of the cube using spherical coordinates. The cube has side-length $a$, and we will centre it on the origin of the coordinates. Denote elevation angle by $\theta$, and the azimuthal angle by $\phi$.
Split the cube into 6 identical square based pyramids, by the planes $x = y, x = -y, x = z$ etc.
Take the square-based pyramid with the base on the plane $x = \frac{a}{2}$.
Then this pyramid is described by the following set of inequalities;
$\frac{\pi}{4} < \theta < \frac{3\pi}{4},
\;-\frac{\pi}{4} < \phi < \frac{\pi}{4},
\;0 < x < \frac{a}{2}$
Rewriting the last inequality in polar coordinates gives
$0 < r < \frac{a}{2 \cos(\phi)\sin(\theta)}$
and now we are in a position to write down the integral.
$V_\mathrm{cube} = 6 V_\mathrm{pyramid} = 6\iiint_\mathrm{pyramid} r^2 \sin(\theta) \mathrm{d}r \mathrm{d}\theta \mathrm{d}\phi$
Solve first the r integral, which gives
$\int_0^\frac{a}{2 \cos(\phi)\sin(\theta)} r^2 dr = \frac{1}{24}\frac{a^3}{ \cos(\phi)^3\sin(\theta)^3}$
and so
$V_\mathrm{cube} = \frac{a^3}{4} \int_{-\frac{\pi}{4}}^\frac{\pi}{4} \frac{\mathrm{d}\phi}{\cos(\phi)^3} \int_{\frac{\pi}{4}}^\frac{3\pi}{4} \frac{\mathrm{d}\theta}{\sin(\theta)^2}   $
The antiderivative of $\sin^{-2} \theta$ is $-\cot \theta$, so the $\theta$ integral evaluates to 2, giving
$V_\mathrm{cube} = \frac{a^3}{2} \int_{-\frac{\pi}{4}}^\frac{\pi}{4} \frac{\mathrm{d}\phi}{\cos(\phi)^3}$
Mathematica tells me the remaining integral is not equal to 2, so I must've messed up somewhere. I can't see where though, can anyone else see what I've done wrong?
Comment: +1 for matter-of-factly beginning a post with "Let us calculate the volume of the cube using spherical coordinates" :-)
Answer: The surfaces $\theta=\pi/4$ and $\theta=3\pi/4$ are cones, but your pyramid is bounded by planes that touch these cones, not by the cones.
Comment: Great, thanks very much!
Answer: As noted already, part of the boundary of your region of integration is
formed by the cones $\theta=\frac\pi4$ and $\theta=\frac{3\pi}4$
(curved surfaces),
whereas the boundary should be completely composed of planar polygons.
Your region of integration includes regions outside the desired pyramid.
The limits of $\theta$ are indeed $\frac\pi4 \leq \theta \leq \frac{3\pi}4$
when $\phi = 0$, but when $\phi = \pm\frac\pi4$
(on the edges of the pyramid's base parallel to the $z$ axis),
the correct limits are
$\arctan\left(\sqrt2\right) \leq \theta \leq \pi - \arctan\left(\sqrt2\right)$.
More generally, consider the point $\left(\frac a2, y, \frac a2 \right)$
along the top edge of the pyramid's base.
The polar angle of that point is
$$\theta = \arctan\left( \frac{\sqrt{\left( \frac a2 \right)^2 + y^2}}
                    {\left( \frac a2 \right)} \right)
= \arctan\left( \sqrt{1 + \frac{4y^2}{a^2}}\right)
$$
The azimuthal angle at that point is
$$\phi = \arctan\left(\frac{y}{\left( \frac a2 \right)} \right)
 = \arctan\left(\frac{2y}{a} \right)$$
which gives us $\frac{2y}{a} = \tan\phi$ and therefore
$\theta  = \arctan\left( \sqrt{1 + \tan^2 \phi}\right) = \arctan(\sec\phi).$
So if you want to give the integration of the pyramid another shot,
try it with the limits
$\arctan(\sec\phi) \leq \theta \leq \pi - \arctan(\sec\phi).$
Comment: Thanks but I've got it already now from Joriki's help. I took $-\frac{\pi}{4} < \phi < \frac{\pi}{4}$ still, and substituted in the polar coordinate transformation into the planes which bound the pyramid; $z = \pm y$ to give $\tan\theta = \pm \mathrm{cosec} \phi$

This is what happens when you don't actually think about a problem and just plug in what looks like it should be the right answer!
Comment: Whoops, that cosec should be sec
Comment: @Joe  Thanks for alerting me to the fact that I inadvertently swapped the symbols $\phi$ and $\theta$ about halfway through my answer. There are conventions in which $\phi$ is the polar angle and apparently I slipped into one of them. I have edited the answer to correct that mistake.
Comment: So we in fact both found that the bounds of $\theta$ occur when $\tan\theta = \sec\phi$. (Note that $\tan(\pi - \arctan(\sec\phi)) = -\sec\phi$, so we agree on the upper limit as well as the lower limit.)

Volume of a cube in spherical polars


In which cases is it necessary to use MTLStoreActionStoreAndMultisampleResolve instead of MTLStoreActionMultisampleResolve?

Question: With MTLStoreActionStoreAndMultisampleResolve, the multisample values are stored in the attachment and also resolved into single-sample values that are stored in the texture specified by the resolveTexture property. But in which cases is it useful to store the multisample values in the attachment? As far as I know there is no load action for the multisample texture (or I missed something). I also don't really know in which way this multisample texture is used.
Answer: This store action can be used when you want to resolve an MSAA render target in the ordinary way, and also preserve its contents for further operations.
One example of such an operation would be a custom MSAA resolve filter. Metal allows you to bind a multisample texture as a shader function argument, provided its access attribute is read (meaning you can't write or sample a multisample texture). The Metal Shading Language (MSL) includes functions for specifying a coordinate and sample index to read from:
Tv read(uint2 coord, uint sample) const

The get_num_samples() function is available determine the sample count of a multisampled texture.
If you have customized sample positions (set with the setSamplePositions:count: method of MTLRenderPassDescriptor), the free function get_sample_position(uint index) returns the position for the specified index.
These shader functions can be used together to manually resolve an MSAA texture with a shader. You can imagine that certain applications could benefit from using a custom set of sample positions and combining the samples in a way that differs from the ordinary technique of taking the average.


Execução de Script jQuery

Question: Tenho um script de progress bar, gostaria que a animação do preenchimento da barra de progresso fosse iniciado assim que o usuário rolasse a pagina até os elementos que serão animados.
Tentei usar $('.progress-bar').scroll(function() { etc..., mas toda vez que uso o scroll do mouse reinicia a execução do script.
Gostaria que o script fosse executado apenas uma vez.

$('.skill-progress').each(function() {
  $('.html-css.circle').circleProgress({
    value: 0.87,
    size: 160,
    startAngle: -1.5,
    fill: {
      gradient: [['#EC6630', .5], ['#0096E6', .5]], gradientAngle: Math.PI / 5
    }
  }).on('circle-animation-progress', function(event, progress) {
    $(this).find('strong').html('HTML / CSS');
  });
  $('.jq-js.circle').circleProgress({
    value: 0.63,
    size: 160,
    startAngle: -1.5,
    fill: {
      gradient: [['#1169AE', .5], ['#EEAF4B', .5]], gradientAngle: Math.PI / 1.8
    }
  }).on('circle-animation-progress', function(event, progress) {
    $(this).find('strong').html('JQ / JS');
  });
  $('.php-mysql.circle').circleProgress({
    value: 0.47,
    size: 160,
    startAngle: -1.5,
    fill: {
      gradient: [['#8993BE', .5], ['#F88500', .5]], gradientAngle: Math.PI / 1.5
    }
  }).on('circle-animation-progress', function(event, progress) {
    $(this).find('strong').html('PHP / MYSQL');
  });
  $('.ps-cd.circle').circleProgress({
    value: 0.53,
    size: 160,
    startAngle: -1.5,
    fill: {
      gradient: [['#5889C4', .5], ['#55A746', .5]], gradientAngle: Math.PI / 2
    }
  }).on('circle-animation-progress', function(event, progress) {
    $(this).find('strong').html('PS / CDR');
  });
});
.circle {
  margin: 6px 6px 20px;
  display: inline-block;
  position: relative;
  text-align: center;
  line-height: 1.2;
}
.circle strong {
  position: absolute;
  top: 51px;
  left: 0;
  width: 100%;
  text-align: center;
  line-height: 60px;
}
.circle strong i {
  font-style: normal;
  font-size: 1.4em;
  font-weight: 300;
}

Comment: Poderia postar mais código.
Comment: @mauhumor Pronto, editei. Tentei `.each();` não virou em nada
Answer: Não entendi direito o objetivo final da pergunta, existem duas interpretações do que necessita
1)
Gostaria que fosse uma barra de progresso pro conteúdo da pagina?
Se for isso mesmo: Podes usar window.addEventListener('scroll', function() { pegando o tamanho da tela do usuário (var height = document.body.getBoundingClientRect().height - window.innerHeight;) com a posição atual da tela (var top = window.scrollY;) para ir recalculando a porcentagem atual e recarregando o script $('.circle').circleProgress({ com o valor da porcentagem.
Função adaptada desta outra: progress-bar-when-scroll

function updateProgress(num1, num2) {
  var percent = Math.ceil(num1 / num2 * 100);
  $('.circle').circleProgress({
    value: percent / 100,
    animation: false,
    fill: {color: '#0000ff'}
  })
}

window.addEventListener('scroll', function() {
  var top = window.scrollY;
  var height = document.body.getBoundingClientRect().height - window.innerHeight;
  updateProgress(top, height);
});
.circle {
  margin: 6px 6px 20px;
  display: inline-block;
  position: relative;
  text-align: center;
  line-height: 1.2;
}
.circle strong {
  position: absolute;
  top: 51px;
  left: 0;
  width: 100%;
  text-align: center;
  line-height: 60px;
}
.circle strong i {
  font-style: normal;
  font-size: 1.4em;
  font-weight: 300;
}
.fixo {
  position: fixed!important;
  top: 0;
}

2)
Gostaria que a animação iniciasse assim que chegar no elemento?
Pode fazer algo parecido: Ao iniciar a pagina chamar a função $('.circle').circleProgress({ com value: 0, criar uma função que calcule qual a distancia do elemento levando em consideração a atual visualização da tela:
$(window).scroll(function() {
  var $circle = $(".circle");
  var window_offset = $circle.offset().top - $(window).scrollTop();
});

E dentro desta função chamar outra função que se "alto destrua" quando ultrapassar um certo limite estipulado:
var myFunction = function(window_offset) {
  if (window_offset < 100) {
    myFunction = function() {};

Dentro desse limite estipulado ainda chamar novamente a função $('.circle').circleProgress({ com o valor da porcentagem que você gostaria.

$('.circle').circleProgress({
  value: 0,
  fill: {
    color: '#0000ff'
  }
})

var myFunction = function () {
    $(".circle").circleProgress({
      value: 0.85,
      fill: {
        color: '#0000ff'
      }
    });

    myFunction = function() {};
    return 1;
};

$(window).bind("scroll resize", function() {
  var $circle = $(".circle");
  var win = $(window);

  var isVibile = win.scrollTop() + win.height() > $circle.offset().top + $circle.outerHeight();

  $("#window_offset").html(isVibile ? "Visível" : "Invisível");

  if (isVibile) {
     myFunction($circle);
  }
});
.circle {
  margin: 6px 6px 20px;
  display: inline-block;
  position: relative;
  text-align: center;
  line-height: 1.2;
}
.circle strong {
  position: absolute;
  top: 51px;
  left: 0;
  width: 100%;
  text-align: center;
  line-height: 60px;
}
.circle strong i {
  font-style: normal;
  font-size: 1.4em;
  font-weight: 300;
}
.fixo {
  position: fixed!important;
  top: 0px;
}

Comment: Venho lhe deixar o +1, todavia preciso lhe alertar sobre uma aparente falha no **2)**, se eu redimensiono o Snippet clicando [Pagina toda] o efeito não funciona. Creio que em janelas normais o problema também ocorra acaso redimencione
Comment: É a segunda opção, assim que chegar ao elemento a animação inicia. Obrigado!

Execução de Script jQuery


Generic question about obtaining arc trig functions..

Question: First post here, and it's rather simple and generic..
In one of my Calc II problems, in trig substitutions, I've come across the following while solving for theta while back-substituting:
$$ x=2sec\theta $$
$$ \frac x2 = sec\theta $$
$$ \theta = arcsec(\frac x2) $$
My question is, is this a general rule for dividing trig functions from one side to the other? Would be great to know. There are a million little tid-bits like this I've failed to pick up along the way, which adds to my frustration. Trying to make up for that now.
Thanks for anyone who has the time to give an answer!
Answer: This has nothing to do with "dividing". You're applying the function $\operatorname{arcsec}$ to each side of the equation $x/2 = \sec \theta$, which results in the equation $\operatorname{arcsec}(x/2) = \operatorname{arcsec}(\sec \theta) = \theta$ because $\operatorname{arcsec}$ is the inverse function of $\sec$.
Comment: Makes total sense! Thanks.


creating multiple image views with label with foreach

Question: I need to create design like in picture below (ignore label):

My question is can I solve this using dictionary with 32 keys and create this design with foreach loop or I need to create it manually? Im using programmatically way.
Comment: `UICollectionView` would be a better solution.
Comment: I would add that the reason a collection view is better involves everything from simplifying layout to (most importantly) reusable cells. Better performance!
Answer: Direct answer to the question:
How to build imageviews and labels based on a dictionary using for each?
dict.enumerated().forEach { offset, pair in
    let imageView = UIImageView()
    let label = UILabel()

    label.text = pair.key // or pair.value or etc.
    // Do the the rest of the setup
}

Where the offset gives you the index of the element and the pair contains a single (key, value) object.
Note that dictionaries are Unordered!

Indirect answer
You may want to use a structured view like a UICollectionView for this instead. Then you can use the map to build the dataSource for the collectionView.


Dúvidas sobre relacionamentos no Rails "campo must exists"

Question: Bom dia,
comecei a estudar o rails recentemente e sempre que vou definir os relacionamentos entre as entidades do meu banco de dados surgem algumas dúvidas.
Na primeira vez, eu criei e defini os relacionamentos nas migrations. Fiz dessa forma:
class CreatePrecos < ActiveRecord::Migration[5.1]
  def change
    create_table :precos, id: false do |t|
      t.decimal :valor, :null => false
      t.decimal :valor_anterior
      t.string :cod_filme, references: [:Filme, :codigo]
      t.string :id_locadora, references: [:Locadora, :id]

      t.timestamps
    end
    add_index :precos, [:cod_filme, :id_locadora], unique: true
  end
end

A minha ideia é criar uma chave primária composta com os campos cod_filme e id_locadora e para isso eu crio duas chaves estrangeiras referenciando as duas tabelas. Quando fiz o comando rake db:migrate não recebi nenhum erro, mas encontrei um tutorial em que é feito de outra forma.
Nesse tutorial, eles modificam o arquivo de modelo e definem os relacionamentos lá. Desas forma:
class Preco < ApplicationRecord
    belongs_to :locadora
    belongs_to :filme
end

E depois que fazem isso, eles adicionam novas colunas às tabelas criando migrations:
$ rails g migration add_column_id_locadora_to_precos id_locadora
$ rails g migration add_column_cod_filme_to_precos cod_filme

e depois disso eles executam o migrate e da certo. Eu estou tendo problemas quando tento adicionar um preço. Eu já criei registros em locadora e em filme, mas quando tento adicionar um filme recebo o erro:

["Locadoras must exist"]

Eu percebi que quando o relacionamento é belongs_to o nome da tabela referenciada tem que estar no singular, mas mesmo depois de ter modificado eu continuo recebendo o erro.
Minha dúvida é: eu preciso definir os relacionamentos nos arquivos de migration ou posso deixar pra definir só nos arquivos de model? Eu devo executar um comando para as modificações serem aplicadas depois que modifico os arquivos de modelo? Se alguém puder me passar um passo a passo de como isso deve ser feito ajudaria muito! Acho que estou misturando tudo :(
Answer: Olá
Você pode fazer o seguinte, nas migrations:
rails g scaffold preco valor:decimal references:locadora references:filme
Assim o Rails criará a migration e o model preco corretamente dizendo que este modelo se relaciona com locadora e filme, também já criará no seu form, index e view, e referenciará o id das tabelas relacionadas. No model de Locadora e Filme depois você adiciona um has_many: precos.
Respondendo bem sua dúvida, você pode fazer só nos models mas na forma como te explico acima você fará tudo bem certo, abraço.
Abraço espero que te ajude.
Comment: Entendi, obrigada!


Is the compact interval $[0,1]$ in the usual topology compact in this new topology?

Question: Let $\mathbb{R}$ be a topological space with topology consisting of the sets $A \cup B$, where $A$ is open in the usual topology, and $B \subseteq \mathbb{R} \setminus \mathbb{Q}$. Is the interval $[0,1]$ compact in this topology?
I think that it might be, as if we have an open cover of $[0,1]$ in this topology, the cover consists of open sets of the form $A \cup B$. $B$ is a set of irrational numbers in the interval $[0,1]$. We can always find an open interval in $[0,1]$ to cover each irrational number, since for any irrational $p \in [0,1]$ there are $a,b \in \mathbb{Q} \cap [0,1]$ such that $a < p < b$, and then $p \in (a,b)$. Therefore now we have an open cover entirely composed of sets from $A$. But we know closed intervals in the usual topology are compact, so then $[0,1]$ is compact in the $A \cup B$ topology.
Could you please tell me whether my argument is correct or not?
Comment: The fact that you can always find an open interval containing any given irrational is irrelevant: it may be that no open interval containing that irrational belongs to your cover.
Comment: You need to show that _any_ open cover of $[0,1]$ contains a finite cover.
Comment: It looks strange because there is a subset that is not compact. In fact with this topology any irrational point is open  (take $A=\emptyset$). So the set of irrational points has a cover from which we cannot extract a finite cover.
Comment: @BrianM.Scott's comment is the only answer to the actual question.
Answer: It is not a compact space.
Let $\pi_n$  be a positive increasing succession converging to an irrational number $p<1$. You had that $\{p\}=\emptyset \cup \{p\}$ is open in $[0,1]$.
So in particular $X=\cup_{n>0} \{(0,\pi_{n})\} \cup \{[0,\pi_1),\{p\},(p,1]\}$ is an open cover, from where you cannot extract a finite one.
Answer: HINT: This is not a compact space anymore. In fact not even Lindelof. Take an $\varepsilon$ cover of the rational numbers, then generate from it a cover without a finite subcover. Indeed without a countable subcover.
Answer: I am sorry for not looking at your argument, but if $\tau_1$, $\tau_2$ are topologies on $X$, $\tau_2\supset\tau_1$, $(X,\tau_1)$ compact Hausdorff, then $(X,\tau_2)$ is compact if and only if $\tau_1=\tau_2$.


Run all assertions of a test in Cypress

Question: I've a question regarding test structure. The docs clearly state to write tests with multiple assertions instead of multiple tests with single assertions.
But if I want to test if multiple elements are visible the test will fail if the first element was not visible and I therefore have no clue about the other elements. Is there anything I can do to run all assertions?
it("Page should show two actions", () => {
  cy.visit("users/list");
  cy.get("[data-cy=createUser]")
    .should("be.visible")
    .and("have.text", "Create user");
  cy.get("[data-cy=exportUserData]")
    .should("be.visible")
    .and("have.text", "Export data");
});

Answer: To run all the assertions you have to make sure the elements are visible. Usually while running cypress it takes time to load everything, between each assertion you can wait, by using this function cy.wait(2000)
Comment: This doesn't answer my question. I've posted the correct way to use soft assertions.
FYI: [Cypress discourages you from using cy.wait in most cases](https://docs.cypress.io/api/commands/wait.html#Time)
Comment: You don't have to use wait in cypress , but the elements visibility check can be taken into consideration.
Answer: Apparently I just didn't find the correct wording for this. Of course it is called soft assertion and not build into Cypress and actually against Chai's assertion philosophy.
There are workarounds although I couldn't really find official documentation of Cypress or Chai that could tell me why they approached against soft assertions.
What you can do is:

Use the npm package soft-assert as mentioned here
Implement it yourself as mentioned here (can break Cypress' retry/timeout mechanism)

Run all assertions of a test in Cypress


What is the decimal form of 1/299,792,458

Question: I'm seeking the decimal form to the fraction 1/c, something like 3.35692(548672), where the number in the brackets would be reoccurring integers. Most calculators round after 10 digits, and the calculator app on my Android just computes the numbers endlessly (if I swipe left) making it hard to find the reoccurring pattern.
My intention is to find the decimal form of the definition of the metre.
Comment: @MichaelBurr The fact is that since 1983 the metre has been re-defied so that the speed of light in $m/s$ is that integer.
Comment: do you mean $$\frac{1}{299792458}$$?
Comment: @DietrichBurde: the OP wants to find the period.
Comment: How accurate is $c$?  If $c$ has been rounded, then the full decimal form might not be useful to you.
Comment: Out of curiosity, why are you even interested in this?
Comment: the value of $c$ is exact, per wikipedia.
Comment: @NickBailuc And even if we take $c$ to be an exact quantity by definition of the meter and second, then this just kinda shifts the goalpost since then you have to deal with the second being defined via the oscillation frequency of some Caesium atom being subject to uncertainty.
Comment: i think this is not the end
Comment: and have you found the period?
Comment: @Hyperplane im interested in this because the answer to 1/c is the time it takes for light to travel 1 metre, which is the definition
Comment: @NickBailuc Yes but as others already pointed out when you deal with physical constants you have to keep in mind that they are not exact, but have some error bar attached to them. So what use is there in computing the period of the decimal representation of $1/c$? It seems really meaningless to me....
Answer: The prime factorization of $299792458$ is $2 \cdot 7 \cdot 73 \cdot 293339$.
$10$ has order $6$ mod $7$.
$10$ has order $8$ mod $73$.
$10$ has order $293338 $ mod $293339$.
Therefore, the length of the periodic part is $lcm(6,8,293338)= 3520056 $.
Answer: Here is a solution from Mathematica given here:
normalizeDigitSequence = {{{beforeRecurring___, {recurring__}},
     c_?NonPositive} :> {{0, beforeRecurring, {recurring}},
     c + 1}, {{beforeRecurring___, {recurring__}}, c_?Positive} /;
     Length[{beforeRecurring}] < c :> {{beforeRecurring,
      First[{recurring}], RotateLeft[{recurring}]}, c}};
addOverlineToRepeating = {{beforeRecurring___, {recurring___}},
     c_?Positive} /; Length[{beforeRecurring}] >= c :>
   Row[Append[Insert[{beforeRecurring}, ".", c + 1],
     Overscript[Row[{recurring}], _]]];
RealDigits[1/72] //. normalizeDigitSequence /. addOverlineToRepeating

where you'd put in 1/299792458 instead of my example 1/72.  Alas, with your number, the repeated sequence is (as lhf showed), much too long to print here.


Issue with kfold through the loo package for R through rstanarm

Question: I am comparing two models with 10 fold cv with each specified as:
<code>stan_lm(form_b, prior = R2(0.5), data = models_rf)
stan_glm(form_b, family = gaussian, prior_intercept = normal(0, 2, autoscale = FALSE), data = models_rf )
</code>
I get sensible coefficients for both models and no errors from stan. Diagnostics all look great, however when I run kfold with K = 10 I get
<code>[[1]]

 10-fold cross-validation

           Estimate SE
elpd_kfold      NaN NA

[[2]]

10-fold cross-validation

           Estimate  SE
elpd_kfold    -44.1 3.1
</code>
Any ideas what I'm missing? There are no NAs in the dataframe, but I'm wondering if there is some underlying statistical error I am making.
Answer: This question was answered in Stan discussion forum http://discourse.mc-stan.org/t/kfold-returning-nan/1943


Emacs Lisp - bind `(` to `()` and `()` to `()`

Question: I've gotten a nice rebind, ( to (<cur>) working, but I would like to be able to still type () to do ()<cur>. Is this possible in Emacs Lisp?
Comment: Yes, it's possible.  Most/all "paren-pairing" packages do that for you, for example.  You might like to start with `electric-pair-mode` which comes bundled with recent Emacsen.
Answer: Use the following to get a character,
(interactive "c`)' will insert ), else will go inside and insert")

Then just test if the parameter is equal to 41 (close parens).


Problems keeping Git history after migrating from Eclipse to Android Studio

Question: I want to migrate from Eclipse to Android Studio. The import works fine, but the file structure is different after import.
I followed the steps in this thread, and copied the .git directory in the root of the newly imported Android-Studio project. But git does not seem to recognize my "moved" source files but lists them as deleted and also as new files.
Old structure:
MyApp
|--src
    |--com.myapp

New structure:
NewApp
|--_myApp
    |--src
       |--main
          |--java
             |--com.myapp

Is there any I can tell git to find my files without manually doing it?
Comment: did you try a simple `git add -u` at the root directory? blobs should be recognized since they haven't changed
Answer: Thank you,  Sebastien Dawans, this was indeed the missing link. After adding with git add -u, git recognized some of my files as renamed. I wonder why not all files. Android Studio seems to touch some files while importing, which causes git to have problems identifying them. So I copied the com.myapp folder containing the java files from my eclipse folders to Android Studio folder replacing the imported files. Same with the res directory. Than git add . and git add -u
That seems to fix the issue.
Comment: I needed first to use git mv on my original repository in order to update the folders hierarchy commit, and then copied the .git to the migration folder and all worked.


Coloring dodecahedron

Question: I found some months ago that there are the Polya's enumeration theorem to compute number of colorings of dodecahedron. I got interested to find how to show by using only Burnside's lemma that there are 9099 ways to color dodecahedrom by three colors. How can I do the computation?
Answer: The following MSE link shows how to compute the cycle index of the face permutation group of the dodecahedron for use with the Polya Enumeration Theorem (PET) which generalizes Burnside.
It is shown that the cycle index is
$$ Z(G) = \frac{1}{60}
\left( a_1^{12} + 24 a_1^2 a_5^2 + 20 a_3^4 + 15  a_2^6\right).$$
This allows to derive a formula for the colorings with at most $n$ colors and that formula is
$${\frac {1}{60}}\,{n}^{12}+\frac{1}{4}\,{n}^{6}+{\frac {11}{15}}\,{n}^{4}.$$
Substitituting $n=3$ into this formula we obtain for the desired number of colorings with at most $3$ colors that indeed the count is
$$9099.$$
Answer: You need to work out what the group of rotations of a dodecahedron is (assuming you are not considering reflections), and find the number of colourings which are preserved by each element in the group. Then you can calculate the number of orbits (i.e. the number of distinct colourings up to rotation) from Burnside's lemma.

Coloring dodecahedron


Evaluating $\frac{d(\sin x )}{d(\cos x)}$ in a strange way.

Question: I am aware this is too easy to solve. I have evaluated this in several ways (dividing both with $dx$, writing one in terms of other, geometrically etc.)
I am having trouble with this following method, I made two assumption and I guess one of them is wrong or both, or there is other problem.
The Method:

Assumption 1: $df=f(x+dx)-f(x)$
Assumption 2: When $dx$ is so small which it is, $\sin (dx)=dx$ and $\cos (dx)= 1-dx$

Using Assumption 1:
$$D=\dfrac{d(\sin x )}{d(\cos x)}=\dfrac{\sin (x+dx)-\sin x}{\cos (x+dx)-\cos x} = \dfrac{\sin x\cos dx+ \sin dx\cos x-\sin x}{\cos x\cos dx-\sin x\sin \,dx-\cos x}$$
Then using Assumption 2:
$$D=\dfrac{\sin x(1-dx)+ dx\cos x-\sin x}{\cos x(1-dx)-\sin x \, dx-\cos x} =\dfrac{dx\,(\sin x- \cos x)}{dx\,(\sin x +\cos x)}=\dfrac{\sin x- \cos x}{\sin x +\cos x}$$
But it is not equal to $-\cot x$ which is obtained by other simple methods.
So where is the mistake? Thank you in advanced.
Comment: when $h$ is small $\cos (h) = 1 - \frac 12 h^2$ which will effectively be 0 as we look at the limit.
Comment: [Papa Flammy ?](https://www.youtube.com/watch?v=zrgS56vZ_Co&t=56s)
Answer: The problem is that $\cos dx = 1$, not $1-dx$. Those assumptions follows from the Taylor series expansions:
$$
\sin x = \sum_{n=0}^\infty \frac{(-1)^n}{(2n+1)!}x^{2n+1} = x + O(x^3),
$$
$$
\cos x = \sum_{n=0}^\infty \frac{(-1)^n}{(2n)!}x^{2n} = 1 + O(x^2),
$$
If $x$ is very small, the terms with $x^2$ and $x^3$ become very small and they can be neglected, leading to $\sin x \approx x$ and $\cos x \approx 1$.
If you proceed with the derivation you will get $-\cot x$.


convergence of the maximum of a series of identically distributed variables

Question: My friend and I have been stumped on this problem for a little while and I thought asking for tips couldn't hurt (we did ask the teacher, but we got other problems after)
Here is the question :
Let $\{X_n\}_{n \geq 1}$ be a sequence of random variables defined on the same probability space $(\Omega, F, \mathbb{P})$ with the same law of finite expected value (E(|X_1|)<\infty ). Let
$Y_n = n^{-1} \max_{1 \leq i \leq n} |X_i|$.
Show that
$\lim_{n\rightarrow \infty} E(Y_n) = 0$
and
$Y_n \rightarrow 0$ almost surely.
We have ideas of many parts of the proof, for example for the first one it would suffice to show that the expected value of the max of all $|X_i|$ is finite... and since the max is one of the $|X_i|$ for each $\omega \in \Omega$ it seems reasonable but we're not sure how to show it.
We also tried splitting the integral for the expected value into a partition of $\Omega$ considering the sets on which $X_i$ is the max, but didn't get too far with that.
For the second part, I think we could show it if we knew that $X_i(\omega)$ diverges for only a measure 0 set, but it's not that obvious (I think).
Any pointers to the right direction appreciated!
Comment: @kahen The random variables $X_n$ are supposed to be identically distributed.
Comment: It's been a *long* time since I had anything to do with random variables and the like, but I can't see how this isn't just plain wrong? E.g. take $\Omega = \{\omega\}$ (IOW a singleton) and $X_n(\omega) = n^2$
Answer: Assume without loss of generality that $X_1$ is almost surely nonnegative.
Almost sure convergence
This is a consequence of the first Borel-Cantelli lemma. To see this, fix any positive $x$. Then $P(X_n\ge nx)=P(X_1\ge nx)$ for every $n$ and
$$\sum_{n\ge1}P(X_1\ge nx)\le x^{-1}E(X_1),
$$
hence the series of general term $P(X_n\ge nx)$ converges. By the first Borel-Cantelli lemma, the limsup of the events $[X_n\ge nx]$ has probability $0$. This means that $X_n<nx$ for every $n$ large enough and can be translated as $X_n\le Z+nx$ for every $n$, for an almost surely finite $Z$. Hence $nY_n\le Z+nx$ for every $n$, and $\limsup Y_n\le x$ almost surely. This holds for every positive $x$, hence $Y_n\to0$ almost surely.
Convergence of the expectations
Two ingredients are useful here: the fact that, for every nonnegative $Z$, $E(Z)$ is the integral of the function $x\mapsto P(Z\ge x)$ over $x\ge0$, and the fact that if $nY_n\ge x$, then $X_k\ge x$ for at least one integer $k$ between $1$ and $n$, hence $P(nY_n\ge x)\le nP(X_1\ge x)$.
Thanks to the first ingredient, $E(Y_n)$ is the integral of $g_n$ with $g_n(x)=P(nY_n\ge x)/n$. Thanks to the second ingredient, $g_n(x)\le P(X_1\ge x)=g_1(x)$. Now, $g_n(x)\le1/n$ hence $g_n(x)\to0$, and since $E(X_1)$ is finite, $g_1$ is integrable. By dominated convergence, the integral of $g_n$ converges to $0$, that is, $E(Y_n)\to0$.
Remark You do not say where you found the exercise but your source is to be complimented because many people add the hypothesis that the sequence $(X_n)$ is independent although it is not necessary.
Added later on The upper bound of a series by $x^{-1}E(X_1)$ used above can be proved as follows. First assume that $x=1$ and note that for any nonnegative $Z$ (random or deterministic),
$$
\sum_{n\ge1}\mathbf{1}_{Z\ge n}=\lfloor Z\rfloor\le Z,
$$
where $\lfloor \ \rfloor$ denotes the integer part. Integrating both sides of the inequality with respect to $P$ yields, for any nonnegative random variable $Z$,
$$
\sum_{n\ge1}P(Z\ge n)=E(\lfloor Z\rfloor)\le E(Z).
$$
For the case at hand, apply this inequality to the random variable $Z=x^{-1}X_1$, using
$$
\sum_{n\ge1}\mathbf{1}_{X_1\ge nx}=\lfloor x^{-1}X_1\rfloor\le x^{-1}X_1.
$$
Comment: I am not sure about the first inequality... could there by any chance be a confusion in the multiple "n" present in the solution? By the way, thank you very much!
Comment: @Vhailor, for a *nonnegative* random variable $X$ with $G(x) = \mathbb{P}(X > x)$ it is a fact that $\mathbb{E}(X) = \int_0^\infty G(x) \,\mathrm{d}x$. Now $s_m = \sum_{n=1}^m P(X_n > n x) \leq \int_0^m G(ux) \mathrm{d}u = x^{-1} \int_0^{m x} G(v) \mathrm{d}v$ where the inequality follows since $G$ is nonincreasing. So, $s_m \leq x^{-1} \mathbb{E} X$ for all $m$. Hence $\limsup_m s_m < \infty$, which by Borel--Cantelli let's one conclude that $\mathbb{P}(X_n > n x \; \mathrm{ i.o.}) = 0$. Does that help?
Comment: @Vhailor No confusion. I added a proof of the inequality at the end of my post. @cardinal Thanks.
Comment: I am a little confused of your construction of Z. Would you explain more? Can it be constructed explicitly?
Comment: @Syl.Qiu This is a deterministic result: assume some real valued sequence $(x_n)$ is such that $x_nN$, then there exists some finite $z$ such that $x_n<z+nx$ for every $n$. Any idea to show this?
Comment: @Did Ah yes I can take maximum of $(x_1,\dots,x_N)$, and since $EX_1<+\infty$, $Z$ defined as the pointwise maximum will be a.s. finite.
Comment: @Syl.Qiu Finite expectation is not needed for almost sure finiteness but yes, this is roughly the idea.
Comment: @Did Thanks! But may I ask why it is not needed? I had used the a.s finiteness of $X_1,...,X_N$ to get $Z$ a.s. finiteness.
Comment: @Syl.Qiu Yes, you used the almost sure finiteness, not the (strictly stronger hypothesis of) integrability.
Answer: Note first that $E \max_{i \ge 0} |X_i|$ (one should really write $\sup$ instead of $\max$) need not be finite.  Indeed, if the $X_i$ are, say, iid normal, then one can show $\sup_{i \ge 0} |X_i| = +\infty$ almost surely.
To get $L^1$ convergence, the trick is to split into the events where the $X_i$ are small and where they are large.  When they are small they do not contribute much to $Y_n$, and they can be large only with small probability.  So fix $M$ and let $U_i = |X_i| 1_{\{|X_i| \le M\}}$, $V_i = |X_i| 1_{\{|X_i| > M\}}$.  Then $Y_n \le \frac{1}{n} (\max_{i \le n} U_i + \max_{i \le n} V_i)$.  The first term is bounded by $M$, and the second by $V_1 + \dots + V_n$.  Taking expectations, $E Y_n \le \frac{M}{n} + E V_1$, so $\limsup_{n \to \infty} E Y_n \le E V_1$.  By choosing $M$ large enough, $E V_1$ can be made as small as desired (think dominated convergence).
For almost sure convergence, the argument that went here previously was wrong.


Prometheus alert test issue

Question: I'm using Prometheus 2.5 and following the tutorial on tests here https://prometheus.io/docs/prometheus/2.5/configuration/unit_testing_rules/ I get
user@nb ~/Downloads/prometheus-2.5.0.linux-amd64 $ ./promtool check rules test.yml
Checking test.yml
  FAILED:
yaml: unmarshal errors:
  line 4: field rule_files not found in type rulefmt.RuleGroups
  line 7: field evaluation_interval not found in type rulefmt.RuleGroups
  line 9: field tests not found in type rulefmt.RuleGroups

I created alerts.yml and test.yml as specified in the tutorial.
  Not sure where to find rulefmt.RuleGroups or how to update it.
Answer: check rules is a syntax check for a rules files. You want test rules to run PromQL unittests.
Comment: thanks, sry about this, should've noticed it earlier

Prometheus alert test issue


Adaptation of argument list by inserting () has been deprecated

Question: I'm just in the process of upgrading from Scala 2.10.x to 2.11.2 and I'm receiving the following warning with the following code:
  override def validateKey(key: String): Either[InvalidKeyError, Unit] =
    keys.contains(key) match {
      case true => Right()
      case false => Left(InvalidKeyError(context, key))
    }

Adaptation of argument list by inserting () has been deprecated: this
  is unlikely to be what you want. signature: Right.apply[A, B](b: B):
  scala.util.Right[A,B] given arguments:  after adaptation:
  Right((): Unit)

I am able to solve this by changing the "true" case statement to:
case true => Right(()) //() is a shortcut to a Unit instance

Is this the proper way to address this warning?
Edit: perhaps a "why we have to do this now" type answer would be appropriate, my cursory investigation seems to indicate that Scala inserting "Unit" when it thinks it needs to causes other problems
Comment: Old question, I know, but why not use `Option[InvalidKeyError]`? Or perhaps `Try[Unit]`, since you're returning an error?
Answer: Automatic Unit inference has been deprecated in scala 2.11, and the reason behind this is that it can lead to confusing behavior, especially for people learning the language.
Here's an example
class Foo[T](value: T)
val x = new Foo

This should not compile, right? You are calling the constructor with no arguments, where one is required. Surprisingly, until scala 2.10.4 this compiles just fine, with no errors or warnings.
And that's because the compiler inferred a Unit argument, so it actually replaced your code with
val x = new Foo[Unit](()) // Foo[Unit]

As the newly introduced warning message says, this is unlikely to be what you want.
Another famous example is this
scala> List(1,2,3).toSet()
// res1: Boolean = false

calling toSet() should be a compile-time error, since toSet does not take arguments, but the compiler desperately tries to make it compile, ultimately interpreting the code as
scala> List(1,2,3).toSet.apply(())

which means: test whether () belongs to the set. Since it's not the case, you get a false!
So, starting from scala 2.11, you have to be explicit if you want to pass () (aka Unit) as an argument. That's why you have to write:
Right(())

instead of
Right()

examples taken from Simplifying Scala — The Past, Present and Future by Simon Ochsenreither.
Comment: ah no, found! Edited the link ;)
Comment: Is there some link for "Automatic Unit inference has been deprecated in scala 2.11"? Also the "Past, Present and Future" link is rotten and I did not find it anywhere, I am not sure what can be done about it now :(
Comment: added a link to the PR that introduced the deprecation. Simon's video seems lost :(
Answer: Perhaps it should be Right(()). Have you tried that?
Answer: My explanation is that since the Right.apply is polymorphic it can take all kind of parameters, doing Right() means passing in a Unit and the compiler simply advise you that maybe that's not what you want, he doesn't know that this is what you actually want.
If you see your deprecate message it states:

... after adaptation: Right((): Unit)

Which means that the compiler has automatically decided that you are passing in a Unit, since this is kinda like void he doesn't really likes it, specifically passing in a Unit like () explicitly tells the compiler that you do want a Unit there. Anyway seems a new deprecation form scala 2.11, I can't reproduce this on 2.10.4.


Best method of importing a large csv file with fields containing multiple values and sub-fields like paragraphs and field collections

Question: I exported an old Drupal 7 site using the Views data export module. Now I need to import this back into my new Drupal 7 site, but some of my fields contain multiple values and fields that have sub fields in them (field collections).

What would be the best method of importing this?
Do I have to write my own custom module using the migrate module or use feeds?
And how do I deal with importing data into a field collection or a field with multiple values?
Answer: You could try using Field Collection Feeds

Provide feeds integration for field collection module.
Comment: I'm actually using paragraphs and not field collection as that seems to going to be deprecated down the line as it looks like everything is moving to paragraphs.
Comment: best method right now is feeds right?
Comment: ......... right.
Answer: This took a good 2 weeks to figure out. Here it is. Comment if you need advice.
I had to import 20k records and each record had some fields with multi-value along with sub-values like the ones used in field collections and paragraphs. Also I need taxonomy terms to be populated on the fly as it was importing the paragraphs.
On my new Drupal 7 site, I did the following using Paragraphs instead of field collections due to it being deprecated in the coming year or so:

Create the content type your making with all the fields matched up to the old field.
Create all the paragraphs that match up with the sub-fields and make sure to set them with proper limit values as it would error out if u limit the values to 1.
Setup your taxonomies
Be sure to install: https://www.drupal.org/sandbox/shaney/2862236 --- Major recoding is needed to fit how you want it to fit your data. I had to modify alot of the code there as it wasn't fully finished.
In the feeds importer. Pick processor as Node processor and pick the content type your targeting
Start mapping out your fields. The source column MUST match what you have in the csv. It could be in any order, it doesn't matter as it will know by the column name to target name.
The trickiest part was the paragraph mappings as it involves formatting the data properly with properly used deliminator's if you have subfields of subfields. Below is a quick screen shot of what I have when mapping paragraph fields.
Also I had to split up my 20k record file into 1500 records per a file. As my import was crashing if it went over 2000 records. I used the terminal command "split -l 15000 myfile.csv" to get it split up. then do each one at a time and cross your fingers it doesnt mess up.

I had to modify the paragraphs mapper to look like this. By default the mapper can only do 1 field. I just needed max 5 fields so I added them in manually. The proper way to do this is provide an add more fields functionality. I didn't get to do this as I only needed 5 fields mapped.

This is how it looks when an import is complete:


Throw error for required field in hook_form_alter?

Question: I have a node type that can be created by authenticated users. In the node create form, I added a terms-of-service checkbox via a form hook like so:
function themename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_nodetype_form') {
    $form['field_tos_accept'] = array(
      '#type' => 'checkbox',
      '#title' => t('I agree to the terms of service.'),
      '#weight' => '999',
      '#required' => TRUE,
    );
  }
}

This gives me the ability to have this checkbox in the node create form, but not in node edit form since it isn't needed there. When I add
'#required_error' => t('Please accept the terms of service.'),

This should - in my understanding - throw an error message when the form is submitted. But instead the required state of the field prevents the form from beeing submitted. So, there's also no error message thrown.
Is there any way to set this in a form_alter? Or should I just validate the checkbox state via JS? What would be considered best practise? Thank you very much in advance!
Comment: @apaderno I use just the above code in my themename.theme file. But since I hook into the node-nodetype-form and not into the node-nodetype-edit-form, it's only shown in the node add/create form, and not in the edit form. You are right about the submission. The required state doesn't prevent form submission, but triggers the default HTML5-field validation which I don't see because I made a switch button out of the default checkbox input. Guess I'll do it in JS and throw an error when the submit button is clicked, but the checkbox is not checked.
Comment: The form to edit a node is the same form used to create it, the one implemented by the `Drupal\node\NodeForm` class. If you want to add a form element only when the node is created, you should add code similar to the following one: `$node = $form_state->getFormObject()->getEntity(); if ($node && $node->isNew()) { /* The node is being created. */ }`
Comment: `#required_error` is the error shown when the form is validated and the form element is required, but users didn't enter any value. `#required` is used to mean users must enter a value for that form element. Neither of them prevent the form to be submitted. As long as users provide a value for that form element, the form is submitted.
Comment: Also, if you are adding the checkbox only when a node is created, but not when a node is edited, you are using more code than the question is showing.
Answer: Is there any way to set this in a form_alter? Or should I just validate the checkbox state via JS?
You could replace #required by setting a custom validation handler in the form alter hook, if you want to generate the error message server-side:
$form_state->setErrorByName('field_tos_accept', $error_message);

When I add '#required_error', this should - in my understanding - throw an error message when the form is submitted.
#required_error' was introduced in 2011, but when Drupal 8 was released it seems to have stopped working in browsers supporting HTML5 form validation and so it was never really adopted.
However, you can use the HTML5 form attribute novalidate to disable client-side form validation, then this property works again and you get the custom error message without a custom validation handler:
function themename_form_alter(&$form, &$form_state, $form_id) {
  // for entity forms $form_id consists of
  // ENTITY_TYPE_BUNDLE_FORM_MODE_form
  // BUNDLE only if entity has bundles
  // FORM_MODE only if not default
  // Examples:
  // node_article_edit_form - node edit form for the content type article
  // node_page_form - node create form for the content type page
  // nodes use for the create form the form mode default
  if ($form_id == 'node_nodetype_form') {
    $form['#attributes']['novalidate'] = 'novalidate';
    $form['field_tos_accept'] = [
      '#type' => 'checkbox',
      '#title' => t('I agree to the terms of service.'),
      '#weight' => '999',
      '#required' => TRUE,
      '#required_error' => t('Please accept the terms of service.'),
    ];
  }
}

See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-novalidate
Comment: Wow - thank you very much! This was exactly what I was looking for and it works like desired. Once again, thank you very much!


How to post out the value of a radio button into MySQL

Question: I've been struggling to solve my issue.
so here it is, I was building a form that will insert new online games to my website via my admin panel, everything working perfect but then I added games categories, so when I upload a game, i can choose which category page it will be uploaded into...
So I was choosing a radio button for each category and I tried to bring the value of a specific category I ticked to MySQL using the method $_POST, and for some reason the game is uploaded to MySQL without an empty value under "game_category"...
Here is my code:
<!DOCTYPE HTML>

<form method="post" id="insert_form" action="insert_game.php" enctype="multipart/form-data">

Insert New Game Here

Game name:
<input type="text" name="game_name">

Game category:
<input class="radio" type="radio" name="game_category" value="action"<?php print $action_status; ?>/> Action
<input class="radio" type="radio" name="game_category" value="sports"<?php print $sports_status; ?>/> Sports

Game keywords:
<textarea name="game_keywords" cols="60" rows="15"></textarea>

Game image:
<input type="file" name="game_image">

Game code:
<input type="file" name="game_code">

Game flash file:
<input type="file" name="game_file">

Game description:
<textarea name="game_desc" cols="60" rows="15"></textarea>

<input type="submit" name="submit" value="Publish Game Now">

</form>

<?php
include("../includes/connect.php");

$action_status = 'unchecked';
$sports_status = 'unchecked';

if(isset($_POST['submit'])){

$game_name = $_POST['game_name'];
$game_category = $_POST['game_category'];
$game_keywords = $_POST['game_keywords'];
$game_image = $_FILES['game_image']['name'];
$image_tmp = $_FILES['game_image']['tmp_name'];
$game_code = $_FILES['game_code']['name'];
$code_tmp = $_FILES['game_code']['tmp_name'];
$game_file = $_FILES['game_file']['name'];
$file_tmp = $_FILES['game_file']['tmp_name'];
$game_desc = $_POST['game_desc'];

if($game_name=='' or $game_category='' or $game_keywords=='' or $game_image=='' or $game_code=='' or $game_file=='' or $game_desc==''){

echo "";

exit();

}
else {

 $path = "../games/games_files/$game_name";

 mkdir("$path", 0777);

 move_uploaded_file($image_tmp,"../images/games_images/$game_image");

 move_uploaded_file($code_tmp,"$path/$game_code");

 move_uploaded_file($file_tmp,"$path/$game_file");

 $insert_query = "insert into games (game_name,game_category,game_keywords,game_image,game_code,game_file,game_desc) values ('$game_name','$game_category','$game_keywords','$game_image','$game_code','$game_file','$game_desc')";

 if($game_category == 'action'){

 $action_status = 'checked';

 }else if($game_category == 'sports'){

 $sports_status = 'checked';

 }else if(mysql_query($insert_query)){

 echo "";

 echo "";

 }

}

}

?>

<?php } ?>

Help anyone? :(
Comment: I am not sure what value="action" part of your code does it may be causing an error because the value should just be "action" EDIT: I just scrolled and saw unchecked. okay
Comment: So what is still wrong with my code? :o
Comment: I don't know how this script will work based on the way it is been written. I advice you put all the PHP related code above the HTML code
Comment: Thanks Lepanto, will try that now, but I don't think its matter wether the php code is above or bellow my HTML code...
Comment: It does matter how you write the script. Because you have use `` in HTML where `$action_status` gets value from PHP script below
Answer: David try updating the script as below.
 $insert_query = "insert into games (game_name,game_category,game_keywords,game_image,game_code,game_file,game_desc) values ('$game_name','$game_category','$game_keywords','$game_image','$game_code','$game_file','$game_desc')";
 if($game_category == 'action'){
   $action_status = 'checked';
 }else if($game_category == 'sports'){
     $sports_status = 'checked';
 }

 if(mysql_query($insert_query)){
   echo "";
   echo "";
 }

And also, in the big if condition, you can see that you have missed one = sign in $game_category=''.
So correct following
if($game_name=='' or $game_category='' or $game_keywords=='' or $game_image=='' or $game_code=='' or $game_file=='' or $game_desc==''){
to
if($game_name=='' or $game_category=='' or $game_keywords=='' or $game_image=='' or $game_code=='' or $game_file=='' or $game_desc==''){
Comment: Thanks! will try that in a moment and will inform you shortly ;)
Comment: Still, I get no value under "game_category" in phpmyadmin... :(
Comment: Can you put `echo $insert_query; exit;` before `if($game_category == 'action'){` and see if you get value for game_category?
Comment: It doesn't work... after I submit the game its echoing this: "insert into games (game_name,game_category,game_keywords,game_image,game_code,game_file,game_desc) values ('Test Game','','hshs','1starship_large.jpg','1starship.html','1starship.swf','hsjsjsjk')" note: the 'hsjsjsjk' is a dummy text for the description of the game...
Comment: Remove that echo statement and see the last edit of my answer above
Comment: Thanks mate, will try now again ;)
Comment: It Worked like a charm!!! Thanks buddy :) However it seems that uploading a game takes now a bit too long :o
Answer: The solution is as follows:
1. Create an "if" statement like the following code:
if($game_category == '3d'){

$three_d_status = 'checked';

}else if($game_category == 'action'){

$action_status = 'checked';

}else if($game_category == 'adventure'){

$adventure_status = 'checked';

}

2. Then, create for each field you want to use with a "radio button" a line like this:
<input class="radio" type="radio" name="game_category" value="3d"<?php print $three_d_status; ?>/>3D

That's it, You are ready to go :)


Somewhat specific question about Guitar String Gauge

Question: If a guitar is setup for 011-056, would i need to re=setup my guitar for 011-049 or 011-52 set of strings.
Comment: Check this answer https://music.stackexchange.com/questions/1467/do-i-need-to-have-my-guitar-re-set-up-if-i-change-the-string-gauge?rq=1, your question is just a specific case.
Answer: If you haven't change your tuning or your string height (from the fretboard), then no, you would not.
Your new string may are fatter and with different gauge, but they are design to have same string tension.
However, if you prefer different string height due to different string gauge you will definitely need a new setup for your guitar.
Comment: Completely inaccurate answer.


Need help discerning category isomorphism

Question: I'm new to category theory, and I'm trying to define two categories which are not isomorphic, yet have identical graphs.

Category $A$ has 3 objects: {0, 1, 2}. For each pair of objects $m, n \in A$ there is a morphism $f_{m} : m \xrightarrow{f_{m}} n$ iff $(m + m) \% 3 = n$. Each object additionally has a morphism $id_{m} : m \xrightarrow{id_{m}} m$. Composition $f_{n} \circ f_{m} = id_{m}$ whenever the codomain of $f_{m}$ is equal to the domain of $f_{n}$.
The objects of category $B$ are 3 kinds of flowers: {"Bluebell", "Texas Bluebonnet", "Red Poppy"}. For each pair of (not necessarily distinct) flowers $p, r \in B$ there is a morphism $h_{pr} : p \xrightarrow{h_{pr}} r$ iff $p$ and $r$ have the same color petals (as implied by their names). The composition $h_{qr} \circ h_{pq}$ is equal to $h_{pr}$.
Functor $F : A \rightarrow B$ maps objects $F(2) = $"Bluebell", $F(1) =$ "Texas Bluebonnet", and $F(0) = $"Red Poppy". It also maps identities of $A$ according to $F(id_{m}) = h_{F(m)F(m)}$, where $m \in A$, and maps the modulo morphisms of $A$ according to $F(f_{m}) = h_{F(m)F(n)}$ where $n = (m + m) \% 3$.
Functor $G : B \rightarrow A$ maps objects $G($"Bluebell"$) = 2$, $G($"Texas Bluebonnet"$) = 1$, and $G($"Red Poppy"$) = 0$. It also maps morphisms of B according to $G(h_{pp}) = id_{G(p)}$, and $G(h_{pr}) = f_{G(p)}$, where $p,r \in B$ and $p \neq r$.

The categories are not isomorphic, because $F(f_{0}) = F(id_{0}) = h_{BB}$, while $G(h_{BB}) = id_{0}$ (abbreviating "Bluebell" as $_{B}$). But the graphs should still be the same, because identity morphisms do not appear in the graph of a category. Is this correct?
Comment: The definitions of $A$ and $B$ are unclear. Please elaborate.
Comment: Can you tell me what is unclear? I revised the whole question several times before posting, so it includes all the details I can think of. Please let me know what is missing.
Comment: @Byron: I'm writing an answer that will hopefully clear things up.
Answer: The definitions of the categories are fundamentally flawed. I suggest that you go back to the definition of a category and try to understand why what you've written down doesn't work out. A morphism is an arrow from one object to another, so "its only morphism is addition modulo $3$" doesn't make sense: addition modulo $3$ assigns a third number to two numbers, which isn't what we need to define a morphism. The same for path composition, which assigns a third path to two paths.
Here are three categories that have some similarity with what you've written; perhaps one or two of them are what you were trying to get at.
Category $A'$ has one object, the set $\mathbb Z_3=\{0,1,2\}$. For every $n\in\mathbb Z_3$, there is one morphism from $\mathbb Z_3$ to $\mathbb Z_3$, namely the function that sends $x$ to $x+n\bmod3$. Composing the morphisms corresponding to $n_1$ and $n_2$ yields the morphism corresponding to $n_1+n_2\bmod3$. The identity morphism for the only object is the one corresponding to $n=0$.
Category $A''$ has three objects, $0$, $1$ and $2$. There is one morphism for each pair of objects. Composition yields the only morphism between the appropriate objects, and the identity morphism for an object is the only morphism from that object to itself.
Category $B'$ has three objects, $a$, $b$ and $c$. There is one morphism from $x$ to $y$ for each path from $x$ to $y$ in the complete graph on $\{a,b,c\}$. Composition of morphisms is defined by composition of the corresponding paths. The identity morphism for an object is the path beginning and ending at that object without any edges.
Now we can define a functor $F$ from $B'$ to $A''$ that assigns to the objects $a$, $b$, $c$ the objects $0$, $1$, $2$, respectively, and to the morphism corresponding to a path from $x$ to $y$ the only morphism from $F(x)$ to $F(y)$. We can also define a functor $G$ from $A''$ to $A'$ that assigns to each object in $A''$ the only object in $A'$, and to the morphism from $x$ to $y$ the morphism that maps $x$ to $y$. We can also define the composition $H=G\circ F$ from $B'$ to $A'$.
Comment: @Byron: You're absolutely right to start out with these simple examples. I wouldn't say that in general the objects "ought to be" structures instead of atomic units -- it's perfectly usual to consider objects without internal structure e.g. in a [poset category](http://en.wikipedia.org/wiki/Partially_ordered_set#In_category_theory). Regarding your new definitions, I don't understand them. First, for $A$, you define six morphisms, one for each ordered pair of distinct objects. This would preclude the existence of identity morphisms, since those have to be from an object to itself.
Comment: @Byron: You're welcome -- I'm glad to hear it paid off in the end :-)
Comment: Yes, $A''$ and $B'$ are precisely what I was meaning to define. Given these corrections, can we say that $F$ and $F^{-1}$ are isomorphic functors? It's unclear to me whether $F \circ F^{-1} = id_{A''}$. In particular, I don't understand exactly how one ought to define $F(id_{A''})$. Perhaps it depends on how $id_{A''}$ is defined, and there seem to be 2 options:

**1.** $id_{A''}(x) = x$
**2.** $id_{A''}(x) = (x + 0) \% 3$ (i.e., it is selected from among the other $A''$ morphisms)
Comment: By the way, I don't actually see the difference between your definitions of $A''$ and $B'$ and my definitions of $A$ and $B$. I didn't intend to introduce any third object in the morphisms. Can you help me understand what is incorrect about the way I defined them?
Comment: @Byron: A lot of your first comment is again fundamentally flawed. a) No $F^{-1}$ has been defined, and I don't see how to define one. b) Your use of $\operatorname{id}_{A''}$ is inconsistent. In $F \circ F^{-1} = \operatorname{id}_{A''}$ it seems to be a functor whereas in $F(\operatorname{id}_{A''})$ it seems to be a morphism. c) I don't see the difference between 1. and 2., since $(x+0)\%3=x$. About your second comment: But addition modulo $3$ *does* introduce a third object. I think you should spell out your definition of $A$; that would make it easier to see what's wrong with it.
Comment: Thanks for your help, I really appreciate. Do you perhaps know of any online documents that give examples of small, specific category definitions like the one I am attempting here? I just don't have a clue how to specify the components of the category. If I could just see a few dozen examples, fully elaborated with all the details, then I could start to see how one properly articulates the definition.
Comment: @Byron: I don't, unfortunately. My impression is that you may be confusing objects and sets. Keep in mind that one of the main points of category theory is to abstract away from the view of structures as sets and characterize the objects purely in terms of their morphisms. Also, again I would suggest that you try to spell out very explicitly your attempted definition of $A$. Either you will notice in the process of having to spell it out what goes wrong, or if not, at least it will allow us to point out more explicitly what's wrong.
Comment: I've redefined $A$ and $B$ in the original post, and withdrawn my functor definitions because I'm stuck at that point. Your help would be greatly appreciated (as noted in the new version).
Comment: btw, I do realize that my "categories" here are pointlessly simplistic, and that in general the objects of $A$ and $B$ ought to be structures instead of atomic units. The thing is, I'm doing research in programming languages and type theory, which requires having a very specific grasp of the way the concepts of category theory correlate to their constituent elements. So I am making example categories with "hyper trivial" object domains, as a way to verify that I understand all the detailed implications of each theoretical concept.
Comment: @Bryon: Then you write that "The identity morphism is trivially $\forall m \in A : id_{m} = m$." Is that supposed to be the definition of further morphisms? If not, it must be wrong, since the previously defined morphisms weren't identity morphisms. If yes, "trivially" would be misleading, since it seems to imply a deduction rather than a definition. Also, it's not clear to me what the intent would be of calling this identity morphism by the same name $m$ as the object -- that seems to just create confusion. Or are you saying that there's some reason for the two to be identical?
Comment: @Byron: A further problem with the definition of $A$ is that you say that the morphisms can be composed, as indeed they should, but in fact they can't, since e.g. composing the one from $0$ to $1$ with the one from $1$ to $0$ should lead to one from $0$ to $0$, but no such morphism has been defined.
Comment: Category $A$ does have 9 morphisms, and in $id_{m} = m$, the subscript $ _{m}$ just means "the one that goes from $m$ to $m$". These $id$ morphisms should resolve the composition issue you mentioned, right? As for the format, my textbook always describes $id$ morphisms separately from the others, just like I have done here. It sounds like this is not conventional?
Comment: @Byron: I understand that the subscript $m$ indicates that this is the identity morphism from $m$ to $m$. What I don't understand is why you write that this is equal to $m$. I guess there's nothing to keep you from saying that, but it seems extremely confusing to me and I don't see the point of it. I've never seen objects and morphisms mixed up before; it seems like a certain recipe for chaos. Why do you want to equate the identity morphism and the object?
Comment: @Byron:  As to the format, yes, I don't think that's conventional. I'd define all the morphisms in one go, not define some, then talk about their composition, which makes no sense without the missing ones, and only then define the missing ones. Also, I don't understand why you're bringing modulo $3$ into it at all. If you do have all $9$ morphisms for all $9$ ordered pairs of objects, then indeed as you say this is the same as my $A''$; but the connection with modulo $3$ now seems very artificial and it's much easier to just say there's one morphism between every pair of objects.
Comment: Right, I was focused on defining the categories and lost track of what they are supposed to contain. I've updated the original post with new $A$ and $B$ that have the kind of content I originally intended.
Comment: @Byron: About $A$: Now you've defined six morphisms, $f_0:0\to0$, $f_1:1\to2$, $f_2:2\to1$, $\def\id{\operatorname{id}}\id_0:0\to0$, $\id_1:1\to1$, $\id_2:2\to2$, but you haven't said how they compose. Most of that is determined by the domains, codomains and identities, but you still have to specify whether $f_0\circ f_0$ is $f_0$ or $\id_0$, and it wouldn't hurt to also describe the remaining compositions, even though they're determined. About $B$: I have no idea what colours the petals of those flowers have; a definition that requires encyclopedic research strikes me as very inconvenient.
Comment: Sure, I can add the composition details. But the colors of the flower petals are right there in the flower names: two have blue petals, one has red petals. So is there a way to make a functor between 2 categories like this, where the morphisms are not logically related?
Comment: @Byron: Yes, there is. Those two categories are very similar, the only difference is that $A$ has one more morphism. If we let $F(0)=\text{Red Poppy}$, $F(1)=\text{Bluebell}$ and $F(2)=\text{Texas Bluebonnet}$, then five of the morphisms correspond to each other, and we have to map $f_0$ to $\operatorname{id}_{\text{Red Poppy}}$ since that's the only morphism with the right domain and codomain. We can similarly define a functor $G$ in the other direction, but then $f_0$ has no preimage, so the two functors aren't inverses of each other.
Comment: @Byron: By the way, even if the structure weren't so similar, you can always define a trivial functor from any category to any other simply by mapping all objects to the same object and mapping all morphisms to that object's identity morphism. (About the colours: I saw that there are colours in the names, but I didn't know whether the flowers also had petals in other colours besides the ones in their names.) (And about "composition details": Those aren't just details. You haven't fully specified a category because you haven't specified the composition law and it's not determined by the rest.)
Comment: I've attempted to define the functors according to what you suggested. Let me know what you think when you get a chance. (By the way, how do you get an "at" sign in your comments? It disappears when I try...)
Comment: @Byron: The "at" sign serves two purposes, a) getting someone notified of a comment and b) indicating whom the comment is directed at. In the present case, neither is necessary, since a) I get notified of comments under my own post anyway and b) no-one else has commented on this post so the comment can only be directed at me anyway. The software realizes this and deletes the "at" construction, but you should be able to use it in other comment threads (or as soon as someone else chimes in here).
Comment: @Byron: About your functors: There's a reason I mapped $0$ to $\text{Red Poppy}$ in my definition; I don't think there's a functor that maps $0$ to $\text{Bluebell}$. But more fundamentally than that, your definition is incomplete because it contains a function $f$ that you haven't defined. If I may offer some advice after what has now been quite an extensive exposure to your ideas: You appear to be very seriously confused about a lot of things. You might want to go back and gain more experience with more basic aspects of mathematics before tackling something as abstract as category theory.
Comment: @Byron: Your functor $G$ also doesn't work out; I believe this too has to map $\text{Red Poppy}$ to $0$ to work. For $G$ to be a functor, $G(h_{pr})$ has to be a morphism from $G(p)$ to $G(r)$, but for $p=\text{Bluebell}$ and $r=\text{Texas Bluebonnet}$, the morphism $G(h_{pr})=f_{G(p)}=f_0$ is a morphism from $0$ to $0$, not from $G(p)=0$ to $G(r)=1$.
Comment: Well, I honestly think it's more of a typo. When I typed in the mapping for ($0 \rightarrow $ "Bluebonnet"), I was thinking ($2 \rightarrow $ "Bluebonnet"), but was also thinking about too many other things to notice the typo. I corrected the indexes so the functors align properly now. Regarding $f$: I am taking $f_{m}$ to be synonymous with $f(m)$, both referring to the morphism of $A$. Is this not allowable?
Comment: @Byron: Sure you can consider $f(m)$ and $f_m$ as synonymous. It doesn't exactly increase clarity to introduce one and then use the other, though. The reason I didn't infer that this is what you meant is that this makes your definition of $F(f_m)$ circular. Regarding the typo, I'll be quite frank: I think you'd be fooling yourself if you think that this is just a question of isolated typos. Every single one of your attempts contained fundamental flaws, and my overall impression is that you're rather confused about quite basic things, let alone category theory. I'd try something easier first.
Comment: I think it's a notational problem again. The syntax admits resolution in two different sequences, and I see now that in the environment of category theory, only one of those resolution orders is permissible. The new version explicitly resolves $f_{m}$ to $(m + m) \% 3$ in the intended manner.
Comment: @Byron: OK, I think you're almost there now. One more problem (perhaps just a typo? ;-) is that "$h_{rq} \circ h_{pr}$ is $h_{rr}$" should be "$h_{rp} \circ h_{pq}$ is $h_{rq}$". About the graphs: I still haven't understood why you keep treating identity morphisms separately. However, even if for some reason you omit the identity morphisms from the graphs, they would still be different since the graph for $A$ would have a loop for $f_0$ at $0$ and the graph for $B$ wouldn't have any loops.
Comment: Yes, a typo. Note that there are 2 conventions for composition: one in which the rightmost is applied first, another in which the leftmost is applied first. Authors in category theory point this out, and usually state which one they are using. Here (after my correction) the former is used. As for the graphs, that's the original reason for this post--at a conceptual level there's something I don't understand. One textbook author says it is possible for 2 categories to have identical graphs yet not be isomorphic. But if every graph edge represents a morphism, how could this ever be?
Comment: @Byron: I see your point about the order of composition; however, it's still wrong, since the result should be $h_{pr}$. Perhaps you're not that confused after all and just staggeringly careless? About the graphs: The graphs don't contain information about composition. Two categories could have the same number of morphisms between any two objects, and thus the same directed graph, and yet not be isomorphic. The simplest example would be a category with a single object and two morphisms, where in one case the squares are both the identity and in the other case one of the squares isn't.
Comment: Sorry to be a bother with my syntactic difficulties, but it looks correct to me. As I understand it, $f_{qr} \circ f_{pq}$ yields $p \rightarrow q \rightarrow r$, which given the structure will be the same as $f_{pp}$, since $r$ and $p$ will always refer to the same object.
Comment: I'm not grasping the non-isomorphism in your example. How can a morphism be directed from a single object to itself and not be an identity? Apologies if it's a dumb question, but I'm just not able to see the exact semantics of "identity" in this context.
Comment: ...and those are meant to be $h$ in my first comment--too late to edit again now.
Comment: @Byron: No, you could have $p=q=\text{Bluebell}$ and $r=\text{Texas Bluebonnet}$, then $h_{pr}\ne h_{pp}$. (Something tells me that your response will involve somehow treating the identity morphisms separately. :-) About your other question: You yourself *created* this example in which $f_0$ is a morphism from $0$ to $0$ that's distinct from the identity morphism on $0$. In the "real world", a typical example of this would be an [endomorphism](http://en.wikipedia.org/wiki/Endomorphism) from a group to itself or from a vector space to itself (e.g. a rotation).
Comment: Right, I made a mistake in the logic for composition in $B$. I didn't think of that possibility. So it's corrected now.
Comment: Suppose category $C$ has one object $x$. A morphism $t : x \rightarrow x$ can transform $x$ such that, within the context of $x$, it is an endomorphism and not an identity. Suppose a second morphism is defined, $s : x \rightarrow x$, having no transformation. When I compare $t$ and $s$ in the context of $C$, are they still distinct? I can see it two possibilities: 1) $C$ only recognizes a distinction between two morphisms when the distinction occurs in the terms by which $C$ is defined. 2) $C$ recognizes all distinctions of morphisms, even those wholly contained within one of its objects.
Comment: In the case of 1) category $C$ regards $s = t$. In the case of 2) it regards $s \neq t$. Again, sorry if it's a dumb question, but this kind of semantic distinction is not discussed in the textbooks. I've got to ask someone about it, otherwise I'll never know which way it works.
Comment: @Byron: No, this is not at all a dumb question; now we're finally getting to the stuff that's interesting about category theory. The idea in category theory is to fully abstract from the internals of objects and discuss the objects *solely* in terms of the morphisms between them. So there's no talk in category theory about the morphism $t$ "transforming" the object $x$, or about something happening "within" one of the objects. But that doesn't mean that category theory can't distinguish between $t$ and $s$. The distinction can be expressed entirely in terms of the compositional behaviour of...
Comment: ... the morphisms. $s$ is the identity morphism on $x$, with the unique property that composing it with any other morphism $m$ yields $m$. That's not the case for $t$. (If there were two identity morphisms $t$ and $s$ for an object, then $t\circ s=t$ and $t\circ s=s$ would imply $t=s$.)
Comment: An example would be linear maps between vector spaces. There are all sorts of endomorphisms on a vector space, i.e. linear maps mapping it to itself. But there's only one identity map, and that's the only one with the property that if you compose it with any linear map $L$ to or from the vector space, you end up with $L$ again.
Comment: Ah, excellent, now I'm starting to see how it works :-) But is it allowable to define $t$ as having the identity property, even though it does a transformation on $x$? Supposing, for example, that I want my category $C$ to consider this transformation negligible. Would it be incorrect to assert $t$ as an identity?
Comment: @Byron: As I wrote above, there can be only one identity morphism per object, since you can use the properties of an identity morphism to show that any two identity morphisms for the same object are equal. Your formulation "even though it does a transformation on $x$" has no place in category theory. You can define any morphisms you want as long as they satisfy the basic axioms for composition of morphisms, and one of the consequences of those axioms is that there is exactly one identity morphism per object.
Comment: Apologies, I should have reformulated the whole example (so category $C$ has only the one morphism $t : x \rightarrow x$). Generally speaking, it sounds like the only thing that really "counts" is the composition rule. From the perspective of the category, if its morphism has the compositional behavior of an identity, then--for that reason--it is an identity. Is this correct?
Comment: @Byron: Yes, that's absolutely correct.
Comment: Awesome--that actually answers about 15 other questions I was having about category basics. And now I see why my original examples were so badly disoriented. Many thanks for your patience!


Converting distinct values of a Spark dataframe column into a list

Question: I have a dataset that looks something like this:
+-------+-----+----------+--------------+
| Name  | Age | Pet Name | Phone Number |
+-------+-----+----------+--------------+
| Brett |  14 | Rover    | 123 456 7889 |
| Amy   |  15 | Ginger   | 123 456 8888 |
| Amy   |  15 | Polly    | 123 456 8888 |
| Josh  |  14 | Fido     | 312 456 9999 |
+-------+-----+----------+--------------+

And I need to present it in the following format using Spark:
+-------+-----+---------------+--------------+
| Name  | Age |   Pet Name    | Phone Number |
+-------+-----+---------------+--------------+
| Brett |  14 | Rover         | 123 456 7889 |
| Amy   |  15 | Ginger, Polly | 123 456 8888 |
| Josh  |  14 | Fido          | 312 456 9999 |
+-------+-----+---------------+--------------+

Can someone please help me with the best way to go about this?
Answer: You can also use groupBy Name and Age and collect as list for Pet Name as below
df.groupBy("Name", "Age")
  .agg(collect_list($"Pet Name").as("PetName"), first("Phone Number").as("PhoneNumber"))

Or you could also do
data.groupBy("Name", "Age", "Phone Number")
  .agg(collect_list($"Pet Name").as("PetName"))

Output:
+-----+---+---------------+------------+
|Name |Age|PetName        |PhoneNumber |
+-----+---+---------------+------------+
|Amy  |15 |[Ginger, Polly]|123 456 8888|
|Brett|14 |[Rover]        |123 456 7889|
|Josh |14 |[Fido]         |312 456 9999|
+-----+---+---------------+------------+

If you need string you can use concat_ws as
data.groupBy("Name", "Age", "Phone Number")
  .agg(concat_ws(",",collect_list($"Pet Name")).as("PetName"))

Output:
+-----+---+------------+------------+
|Name |Age|Phone Number|PetName     |
+-----+---+------------+------------+
|Brett|14 |123 456 7889|Rover       |
|Amy  |15 |123 456 8888|Ginger,Polly|
|Josh |14 |312 456 9999|Fido        |
+-----+---+------------+------------+


Dificuldades com ionic framework e android sdk?

Question: estou começando a trabalhar com o framework ionic, e estou com algumas dificuldades na hora de construir (build) o aplicativo.
quando executo o comando
ionic build android
retorna o seguinte erro
C:\Program Files\Android\android-sdk\tools\ant\build.xml:483: SDK does not have any Buil Tools instaled.
Sendo que instalei todas as opções de build-tools disponiveis no SDK manager e configurei as variáveis de ambiente exatamente como diz o tutorial do site mas mesmo assim não funciona.
Qualquer duvida com relação à pergunta estou  a disposição.
Desde já agradeço pelas respostas.
Obrigado.
Answer: Pelo erro parece que você não instalou (ou removeu?) o pacote Build Tools.
Vá até o diretório onde está instalado o SDK do Android, execute o SDK Manager.exe e confira se o pacote está instalado conforme a imagem abaixo:


Contextually filtering a view using values from a completely separate table?

Question: I have a table "user_connections"
id | uid1 | uid2
1  | 1    | 2
2  | 3    | 1
etc

So, if the current user has uid = 1, then according to my table, he is "connected" to use 2 and 3. So I just want to be able to do something like:
select uid1 from user_connections where uid2 = :currentUserUid

Then pass these uids as a parameter to the view. So that it is ultimately used as a "where in" condition.
Any ideas how to do this? Or what is the best way?
Comment: Updated my answer.
Answer: Make sure you check mark allow multiple values on your contextual filter's "More" settings.

Use hook_views_pre_view to pass your uid's to the arguments (contextual filter).
/*
 * Implements hook_views_pre_view()
 */
function mymodule_views_pre_view(\Drupal\views\ViewExecutable $view, $display_id, array &$args) {

  if ($view->id() == "view_name" && $view->current_display == 'page_1') {
    $uids = [2, 19]; // hard coded example, you would query db here.
    if (is_array($uids)) {
      $uids = implode('+', $uids);
    }
    $args[0] = $uids;
  }

}

You will also need to disable the view's caching or add a cache tag if you created one for your other table query.


How to return default value when no rows return from table

Question: When the table ERRORMESSAGE contains no rows that satisfy the "WHERE" condition, IFNULL fails and I get null, not the default value provided in the IFNULL clause.
select IFNULL(errorCode , 'NOERRORCODE') as "errorCode",
    IFNULL(errorText , 'NOERROR') as "errorText" from
    (select errorcode,
        IFNULL((select errorText from STATIC_ERRORCODES a
        where a.errorcode = b.errorcode), '') as errorText
     from ERRORMESSAGE b  where b.route_id = 'IPN4'
     order by b.row_index)

When there are no rows in ERRORMESSAGE with route_id = 'IPN4', the output should be:
errorCode = NOERRORCODE
errorText = NOERROR

But I get null/empty values. How can I resolve this?
Answer: You could use NOT EXISTS and UNION ALL
SELECT errorCode, errorText
FROM ERRORMESSAGE WHERE <condition>
UNION ALL
SELECT 'NOERRORCODE', 'NOERROR'
FROM ERRORMESSAGE
WHERE NOT EXISTS (SELECT * FROM ERRORMESSAGE WHERE <condition>)

You need to replace <condition> with actual criteria. So, when there is are row exists, then SELECT after UNION ALL will get executed, which will show static row.
Please note: I have never used HSQLDB, so I wasn't sure how to show static rows, but I used as explained here


How to access UITableView subview selection?

Question: I've created a UIViewController (AnestDrugCalcViewController) that has a button that opens a UITableViewController (DrugTableViewController) to select a drug. The DrugTableViewController is populated based on a NSMutableArray and is made up of several NSDictionary objects (drugName, drugDose, drugConcentration, etc.).
I'm able to open DrugTableViewController by pushing it onto the navigation stack, but I can't figure out how to tell from my AnestDrugCalcViewController what the properties of the selected item are.
//  DrugTableViewController.h
#import <UIKit/UIKit.h>

@interface DrugTableViewController : UITableViewController {
NSMutableArray          *drugList;
NSIndexPath *lastIndexPath;
IBOutlet UITableView    *myTableView;
NSObject *selectedDrug;
}

@property (nonatomic, retain) NSArray *drugList;
@property (nonatomic, retain) UITableView *myTableView;
@property (nonatomic, retain) NSObject *selectedDrug;

@end

Top of DrugTableViewController.m
    #import "DrugTableViewController.h"
@implementation DrugTableViewController

@synthesize drugList,myTableView, selectedDrug;

Comment: Is vwCalc a UIView, or is it a UIViewController?
Comment: vwCalc is a UIViewController. vwDrugTable is a UITableViewController
Answer: You could have a property in vwDrugTable that stores the the selected row when the user selects it. Then, after that table view is removed and you are back in vwCalc, just get the data from that property.
So that means in vwDrugTable, have something like this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.selectedDrug = [self.drugs objectAtIndex:indexPath.row];
}

Then just access selectedDrug from vwCalc when you need it.
Comment: Sorry -- I'm a noob --
The two views have separate view controllers.
I've created selectedDrug as an NSObject and can access it from vwDrugTable, but how do I access it from vwCalc?
I've included DrugTableViewController.h in CalculatorViewController.m and have defined the drugListViewController as a local variable (also including @property in .h and @synthesize in .m).

When I try to access the property (NSLog(@"%@"),drugListViewController.selectedDrug), it refuses to compile ("request for member 'selectedDrug' in somthing not a structure or union)

What am I missing?

I a
Comment: Edit your question and show me your .h and top of your .m (where @synthesize sits) for DrugTableViewController. That will help me help you.
Answer: UITableView's -indexPathForSelectedRow method will allow you to determine which row is selected:
NSIndexPath *selectionPath = [vwDrugTable indexPathForSelectedRow];
if (index) {
    NSLog(@"Selected row:%u in section:%u", [selectionPath row], [selectionPath section]);
} else {
    NSLog(@"No selection");
}

To be notified when the selection changes, implement tableView:didSelectRowAtIndexPath: in your table view delegate:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Selection Changed");
}

Comment: Also, hungarian notation is not recommended in Objective-C.


Not outputting newline in php

Question: $whichwrong = "The following questions were not answered correctly: \n\n";
$whichwrong .= "Question Number: $questionNum || Your Answer: $userAnswers[$s][$q]\n";
echo $whichwrong;

Displays:

The following questions were not answered correctly: Question Number:
  2 || Your Answer: b Question Number: 4 || Your Answer: c Question
  Number: 5 || Your Answer: a Question Number: 1 || Your Answer: b
  Question Number: 3 || Your Answer: b Question Number: 1 || Your
  Answer: b Question Number: 2 || Your Answer: a Question Number: 1 ||
  Your Answer: b Question Number: 2 || Your Answer: b

Why is the "\n" not working correctly?
Meanwhile this works just fine:
$totalValue .= "Correct: {$correct}\n";
$totalValue .= "Wrong: {$wrong}\n";

Comment: whitespace is collapsed in the browser, view source and you will see your newlines, use a  element instead for a hard break;
Comment: Use `\r\n` - `\r` is a Carriage Return, `\n` is a New Line
Answer: Use nl2br for inserting html-linebreaks (
)
echo nl2br($whichwrong);

Normal \n are treated by browsers like normal whitespaces.
Comment: `Fatal error: Call to undefined function: n12br() in /home/web/i/imed.com/htdocs/test.php on line 205`
Comment: nl = new line. ;) not new 1
Comment: Ok Sorry that solved it! I updated my question, to show how come another lines of code works just fine?
Comment: aaaaaahhhhhhhh... didnt read it correctly. makes sense now :)
Answer: If you're viewing it in a browser, you need to use
 - you can also use the nl2br() function. If you're in the console, try \r\n

Not outputting newline in php


Javascript not displaying in internet explorer 7 and 8

Question: This seem to no be working in ie7 and ie8, is there a simple fix for this?
  var collapsables = document.getElementsByClassName('collapsable');

function unhide(divID) {

  // Hide previous
  for (var i = 0; i < collapsables.length; i++) {
    collapsables[i].className = 'collapsable hidden';
  }

  // Show new
  var item = document.getElementById(divID);
  if (item) {
    item.className = 'collapsable';
  }
}

Comment: `getElementsByClassName` isn't supported below IE9.
Comment: [`getElementsByClassName`](https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName) minimum version with support IE9 Shim http://stackoverflow.com/questions/16777885/get-all-elements-by-classname-and-change-classname/16778755#16778755
Answer: Try to use:
 var collapsables = document.querySelector('.collapsable');
querySelector supported from IE8
But if you need IE7, try to use dirty hack:
if(document.getElementsByClassName == undefined) {
   document.getElementsByClassName = function(cl) {
      var retnode = [];
      var myclass = new RegExp('\\b'+cl+'\\b');
      var elem = this.getElementsByTagName('*');
      for (var i = 0; i < elem.length; i++) {
         var classes = elem[i].className;
         if (myclass.test(classes)) {
            retnode.push(elem[i]);
         }
      }
      return retnode;
   }
};

You should understand - this is very slow operation. This function iterates all DOM elements
Comment: Slow when compared to the native method. But an average of 300ops/sec is plenty for me.
Answer: I'll bet this will get closed because it is a duplicate pretty soon, but Web_Designer has a nice working solution posted here.
Web_Designers solution for IE versions prior to IE9:
function getElementsByClassName(node, classname) {
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

Usage:
var tabs = getElementsByClassName(document.body,'collapsable');


Agrupar funcionários por empresa em query

Question: Estou fazendo um relatório, onde preciso seguir o seguinte layout:

Com a query abaixo, acabou se criando mais linhas, ao invés de agrupar os funcionários por empresa:
<code>select e.cnpj as cnpj,
       e.nome_completo as empresa,
       li.cod as solicitacao,
       ''  funcionarios
       from liberacoes li,
                  empresa    e
             where
                 li.cnpj = e.cnpj and
                 li.dt_acesso_ini = curdate()
union all

select '' as cnpj,
       '' as empresa,
       '' as solicitacao,
       f.nome_completo as funcionario
                                     from funcionarios f,
                                          empresa      e
                                     where
                                         f.cnpj = e.cnpj
                                     order by 1 desc;
</code>
Me trazendo esse resultado:

Em uma query apenas eu consigo fazer o layout de saida ficar igual ao que preciso seguir?
UPDATE
Tentei a query abaixo, mas o resultado ainda está fora do que preciso:
<code>  select
       li.cod,
       e.cnpj,
       e.nome_completo as empresa,
       coalesce(f.nome_completo,'X') as funcionario
   from empresa e
   left outer join funcionarios f on f.cnpj = e.cnpj
   left outer join liberacoes li on li.cnpj = e.cnpj
</code>
Resultado:
Answer: você não precisa do union nesse caso:
<code>   select distinct
       e.cnpj,
       e.nome_completo as empresa,
       coalesce(f.nome_completo,'X') as funcionario
   from empresa e
   left outer join funcionario f on f.cnpj = e.cnpj
</code>
Comment: Não deu certo amigo, o resultado ficou igual.
Comment: Editei a pergunta, veja como ficou o resultado.
Comment: coloca a estrutura das tabelas, e tente utilizar o SQLFiddle
Comment: coloquei um distinct ali, faz um teste
Comment: obs. O agrupamento pro nome da empresa aparecer apenas uma vez, para n funcionários, é feito na hora da exibição, assim, para cada funcionário o nome da empresa irá aparecer mesmo no resultado da query


Questions on Openstack networking (Neutron) configuration

Question: newbie here who's trying to understand Openstack networking topic.
My setup:
I have 3 physical machines with Openstack installed and running:
- controller (with Keystone, Glance, Placement, Neutron, Nova, Heat and Magnum installed)
- compute (with Nova installed)
- block storage (with Cinder installed)

These 3 machines are physically connected (through Ethernet cable) to a router inside the same LAN (with for example addresses 192.168.x.y) , so I don't have a management and a provider network as suggested in Openstack documentation, but  I have only a single network.
All installations went good, I am able to create instances and all works correctly.
Now, I have installed Heat and Magnum on my controller to use K8s with Openstack, and I am having some issues during the cluster deployment and I think they're related also to my network configuration.

In fact, I am using the ml2 plugin and the Linux Bridge, but I wasn't able to create a VXLAN or a router, or a Floating IP (it doesn't exist the option to create it even in my Horizon dashboard) because they were disabled in my neutron.conf file (I have followed this guide during my installation, so the configurations for Neutron are pretty much the same (remember I have only one network).

Now, I was reading this from Openstack documentation, and I think that I must have been followed the "Network Option 2: Self-service network" (in the Configure Network options paragraph) for my Neutron installation.

So my questions are:
1) Is the "Network Option 2: Self-service network" the correct network configuration I have to follow in my specific case for my setup?
2) To modify my neutron.conf file with the new options, I have to delete the Neutron DB in Keystone and repopulate it at the end? What are the correct steps to follow?
3) To create my k8s cluster with Magnum do I need to create a VXLAN, with routers to have also external Floating IPs, right?
Answer:
Is the "Network Option 2: Self-service network" the correct network configuration I have to follow in my specific case for my setup?

Yes, "Network Option 2: Self-service network" is the appropriate configuration for your single network scenario.

To modify my neutron.conf file with the new options, I have to delete the Neutron DB in Keystone and repopulate it at the end? What are the correct steps to follow?

You don't have to delete the Neutron DB, you can just modify the neutron.conf (make sure to backup first!) then restart the neutron service by running the commands from the official docs:

Restart the Compute API service:
service nova-api restart
Restart the Networking services.
service neutron-server restart

service neutron-openvswitch-agent restart

service neutron-dhcp-agent restart

service neutron-metadata-agent restart

service neutron-l3-agent restart

To create my k8s cluster with Magnum do I need to create a VXLAN, with routers to have also external Floating IPs, right?

Deploying your Kubernetes cluster with Magnum without immediate VXLAN or floating IP configurations is feasible if external access isn't a current requirement, focusing on internal cluster communication and operations. However, considering the dynamic needs of Kubernetes workloads and potential future requirements for external connectivity, it's advisable to plan for enabling VXLANs for network isolation and floating IPs for external service exposure.