Bundler + RVM + Passenger + Capistrano deployment & missing gems

Question: I got the server with the configuration above.
This is the important part of my deploy.rb recipe:
$:.unshift(File.expand_path('./lib', ENV['rvm_path']))
require 'rvm/capistrano'
require 'bundler/capistrano'

set :rvm_ruby_string, 'ruby-1.9.2-p290'
set :rvm_type, :system
set :bundle_flags, "--deployment"

set :default_environment, {
  'PATH' => ENV['PATH'],
  'RAILS_ENV' => ENV['RAILS_ENV']
}

set :stages, %w(staging production)
require 'capistrano/ext/multistage'

Running cap staging deploy as is, leads to an error:
* executing "cd /mnt/data-store/project/releases/shared &&
bundle install --gemfile /mnt/data-store/project/releases/shared/Gemfile
--path /mnt/data-store/project/shared/bundle --deployment --without development test"

** [out :: localhost] The --deployment flag requires a Gemfile.lock.
Please make sure you have checked your Gemfile.lock into version control
before deploying.

... rolling back ...

failed: "env PATH=... RAILS_ENV=staging rvm_path=/usr/local/rvm /usr/local/rvm/bin/rvm-shell 'ruby-1.9.2-p290' -c 'cd /mnt/data-store/project/releases/shared && bundle install --gemfile /mnt/data-store/project/releases/shared/Gemfile --path /mnt/data-store/project/shared/bundle --deployment --without development test'" on localhost

Gemfile and Gemfile.lock are in the source control. I ran bundle install locally first to generate the .lock file. But the bundler/capistrano points to /mnt/data-store/project/releases/shared/Gemfile so I just copied manually both files there. I'm sure I'm doing it wrong here. I guess it should be copied automatically.
Executed deploy again (1) and it didn't fail on the bundle install, it even had
Your bundle is complete! It was installed into /mnt/data-store/project/shared/bundle in the output.
BUT, one of my cap tasks executes a rake. The result of this is:
*Could not find bcrypt-ruby-3.0.1 in any of the sources
*Try running bundle install.
Proceeding with my adventure, I discovered that once you have .bundle/config with
BUNDLE_PATH: /mnt/data-store/project/shared/bundle
It works.
I had this directory, probably created by bundler, under /mnt/data-store/releases/shared/, so I copied manually to the rails root.
Now, rake/rails c work.
bundle show twitter shows .../shared/bundle/ruby/1.9.1/gems/twitter-1.7.1.
BUT, redeploying brings me back to (1), because the .bundle dir isn't there.
Concrete questions:

Do I need to create/copy .bundle/config manually?
Do I need to copy Gemfile/Gemfile.lock manually to the shared dir? What happens if I add gems? Should I hold two copies, or manually/programmatically sync them?
WHAT AM I DOING WRONG?

Thanks!
Answer: Look at this part in the deployment.rb file (Bundler code)
args = ["--gemfile #{File.join(context.fetch(:current_release), bundle_gemfile)}"]
args << "--path #{bundle_dir}" unless bundle_dir.to_s.empty?

There's a key called :current_release, this key is probably not being set correctly with Capistrano for some reason.
the :current_release in bundler will point to the "shared" folder instead of the latest release (with the timestamp)
This is getting executed on before 'deploy:finalize_update'.
What I would do in order to fix this is to add your own hook on this event.
before 'deploy:finalize_update', 'x:set_current_release'

And this is the actual method
task :set_current_release, :roles => :app do
    set :current_release, latest_release
end

Comment: Thanks! I still don't get why `current_release` points to the shared path instead of the actual release.
Answer: Error
The --deployment flag requires a Gemfile.lock. Please make sure you have checked your Gemfile.lock into version control before deploying.

occurs when there is something unwantend inside your releases directory on server. There should be only directories with previous versions of your app (their names starts with date and looks like 20111025125442).
So, remove unwanted directories or files and then try to deploy again.


Bypass IIS Basic Authentication for localhost

Question: I'd like to have a website authenticated with basic auth, but then also allow the website to access itself locally. That is, I want to allow unauthenticated access only from localhost.
In IIS I have only basic authentication enabled (not worrying about SSL for now), and I have the correct file system permissions such that outside users can login successfully and view the website.
I have tried setting IIS_IUSR as owner of the directory, and added IUSR with modify permissions, however I'm still getting a 401 error when the website tries to access itself.
Anyone have any idea how to get this to work?
Answer: Setup another site that is pointed to the same content directory.  Enable a couple things
1) only allow connections from 127.0.0.1
2) Use a location tag in the applicationHost.config enabling anonymous.  If you don't have any of the security providers config'd in the web.config, that'd be the best, then you can control the authentication providers within applicationhost.config
3) use a local hosts file with a dummy name in the bindings or update the bindings ip address to be 127.0.0.1 or pick something like 127.0.0.10


Magento. O conteúdo do CMS está bloqueado

Question: Quando entro no painel do Magento (CMS>Pages), e entro em uma das página já existentes, não consigo abrir o Page Information e o Content. Além disso, não consigo criar nenhuma página.
Como faço para desbloquear isso?
Answer: Existe alguma informação de erro na página ou no console do navegador? Instalaram algum módulo recentemente?
Caso tenha sido instalado algum módulo, peço que crie um ambiente de testes por segurança se ainda não houver um, e desabilite o módulo instalado para verificar se as funcionalidades normalizam, pois pode ser algum conflito. Lembrando que para desativar um módulo completamente, a melhor forma é indo em app/etc/modules/nomedomodulo.xml e renomeando o xml. Exemplo: nomedomodulo.xml.disabled
Caso não seja isso, nos dê mais informações para que possamos lhe ajudar ;)


All images within my articles have a link of their own: why?

Question: The article content type has a field to upload images with the article text (body and teaser). I noticed that every image I upload gets its own URL after submitting the article, e.g. http://www.example.com/imagejpg.
This is messing up my Google SEO as each image has its own URL, and it is showing up in the search index for my domain.
Is there any way to stop these images from having their own URL?
Answer: All entities in drupal have their own page, you can use the Rabbit hole module to control what should happen when an entity is being viewed at its own page.
Inside module there is a sub-modules for each entity type, you have to install rabbit_hole and rh_file.


imshow defaults to inverted y axis, can't be flipped using invert_yaxis

Question: Whenever I generate a graph in matplotlib, the axis seems to be inverted. As an example, I created a figure from an array of 0s:
dims = [100,100]

square = np.zeros(dims)
plt.imshow(square)

This produces the following figure:

Whilst doing:
dims = [100,100]
square = np.zeros(dims)
plt.gca().invert_yaxis()
plt.imshow(square)

produces the exact same figure.
How can I make it so my y-axis starts at 0 at the origin?
Comment: The imshow function defaults to putting the origin at the top left of the Axes. You could do `invert_axes` after imshow, or alternatively just tell imshow where you want the origin to be, with `plt.imshow(square, origin='lower')`
Comment: Do it after the plot.
Answer: I think invert_yaxis doesn't work because in your case Axes are empty:
plt.gca()
# > <Axes: >

You can set axis manually instead:
dims = [100,100]
square = np.zeros(dims)
plt.gca().set_xlim([0, dims[0]])
plt.gca().set_ylim([0, dims[1]])
plt.imshow(square)


Hairpins just affect the volume of the next note in Musescore 3.4

Question: I faced a problem in Musescore 3.4.2.When I use a hairpin (e.g diminuendo) for a note , it only affects the volume of the next untied note (and without any gradient,a solid diminution) and the current note is held intact.By the next untied note here I mean E4 in the following screenshot but that's not the case here because I've used Dynamics.

And here's the properties in the inspector window :

What am I doing wrong? Is it related to the SoundFont I'm using ? BTW I use a different soundfont for Violoncell.
Thanks in advance.
Comment: https://musescore.org/en/forum
Comment: I can't explain why no volume gradient is audible in Musescore 3 **.4**, which should support single-note volume gradients, but I must note that your decrescendo has only one note between its beginning and end and therefore may justifiably affect only that middle note (at best) and may not even reach the ending note with "mp" on it (at worst).
Comment: If you switch to the standard soundfont that shipped with the package, does it then do as you wish?   In the mixer, it's "Cello Expr."
Comment: @NevinWilliams Yeah.That only works with the default soundfont.What can I do to achieve the same thing from a custom soundfont?
Comment: @Dekkadeci From the musescore manual : ```By default, a hairpin always affects playback when it spans a series of separate notes. In addition, for instruments supporting single note dynamics (e.g. strings, brass etc.), playback is also enabled across a single note or series of tied notes. (Note: Prior to version 3.1 hairpins only affected playback between notes, not that of single or tied notes.)```.How should an instrument in a soundfont support single note dynamics?
Comment: That's probably something you'll have to ask the folks in a forum at Musescore:
Comment: I tried with the built in piano, bass clarinet, and cello, and all "performed" the diminuendo. So it would seem to be the specific sound font you're using.
Comment: @Aaron did you use a new Musescore version? There have been enourmous improvements made in the last year, particularly in the area of playback.
Comment: @leftaroundabout 3.4.2. (I also have v4, but I ran my tests in 3)
Answer: The problem you're encountering with the hairpin in MuseScore is due to the SoundFont you're using; different SoundFonts can produce various volume changes.
A SoundFont that supports single note dynamics would typically contain samples of each instrument at different dynamic levels. These dynamic levels playback the volume changes across a single note or tied notes.
The SoundFont needs to include separate samples for different dynamic levels. Some SoundFonts may also include additional information, such as velocity mapping or layer switching, to control the dynamic level of the instrument based on the velocity of the note being played.
It would be best if you had a SoundFont that specifically advertises single note dynamics and ensure that it's compatible with MuseScore.


Abrir e fechar menu

Question: Tenho o seguinte menu, que funciona quando a tela está com width: 768px ou menor.
Quando eu clico no fa-bars, ele desaparece e mostra o fa-times. Abrindo o menu. Até aí tudo certo.
Quero que quando eu clique no fa-bars ele esconda o menu novamente e mostre o fa-bars.

$('header nav div.menuMobile').click(function(event) {
  event.preventDefault();
  $('header nav div.menuMobile ul').show(300);
  $('.fa-bars').hide(300);
  $('.fa-times').show(300);
});

$('.fa-times').click(function(event) {
  event.preventDefault();
  $('header nav div.menuMobile ul').show(300);
  $('.fa-times').hide(300);
  $('.fa-bars').show(300);
});
header nav ul,
header nav a img {
  display: none
}

.menuMobile {
  display: block
}

.menuMobileClose {
  display: block
}

          Home

          Quem Somos

          Contato

          E-commerce

                Plataformas E-commerce

                Lojas virtuais customizadas

                Solução virtual para venda

Answer: Fiz este exemplo com algumas mudanças básicas. Dê mais foco nas minhas mudanças do JS porque de restante eu tive que mudar do seu código para funcionar aqui no site. Eu retirei também o logo porque era uma imagem quebrada que estava em cima do menu.

$('.fa-bars').click(function(event) {
  event.preventDefault();
  $('header nav div.menuMobile ul').show(300);
  $('.fa-bars').hide(300);
  $('.fa-times').show(300);
});

$('.fa-times').click(function(event) {
  event.preventDefault();
  $('header nav div.menuMobile ul').hide(300);
  $('.fa-times').hide(300);
  $('.fa-bars').show(300);
});
header nav ul,
header nav a img {
  display: none
}

.menuMobile {
  display: block
}

.menuMobileClose {
  display: block
}

div.fa-times {
  width: 10px;
  height: 10px;
  background: black;
  cursor: pointer;
}

div.fa-bars {
  width: 10px;
  height: 10px;
  background: red;
  cursor: pointer;
}

          Home

          Quem Somos

          Contato

          E-commerce

                Plataformas E-commerce

                Lojas virtuais customizadas

                Solução virtual para venda

Abrir e fechar menu


Closed immersions of schemes vs closed immersions of LRS

Question: In my course (that vaguely follows Liu's Algebraic Geometry) the definition of closed (resp. open) immersion $f:Y\to X$, is that $f$ induces a homeomorphism onto $f(Y)$, $f(Y)$ is closed (resp. open) in $X$, and ($*$) $i^\#_y:\mathcal O_{X,i(y)}\to\mathcal O_{Y,y}$ is surjective (resp. bijective).
But I read that on Gortz & Wedhorn's Algebraic Geometry I closed and open immersions are defined differently (the only hypothesis changing is ($*$), the others, the topological ones, are as above). So for an open immersion ($*$) is substituted by this one: $\mathcal O_X|_{f(Y)}$ is isomorphic to $f_*(\mathcal O_Y)|_{f(Y)}$.  Now, this is equivalent to $\mathcal O_{X,f(y)}\to f_*(\mathcal O_Y)_{f(y)}$ being an isomorphism for every $y\in Y$; plus the induced $f_*(\mathcal O_Y)_{f(y)}\to \mathcal O_{Y,y}$ is an isomorphism because $f$ is a homeomorphism onto its image, so I see that our condition is actually equivalent to ($*$).
In the definition of closed immersion instead, ($*$) is replaced by $\mathcal O_{X}(U)\to f_*(\mathcal O_Y)(U)$ being surjective for every open $U\subseteq X$. Since $f$ is a homeomorphism onto the image, $f_*(\mathcal O_Y)_{f(y)}\to \mathcal O_{Y,y}$ is again an isomorphism and  ($*$) is equivalent to $\mathcal O_{X,f(y)}\to f_*(\mathcal O_Y)_{f(y)}$ being surjective for every $y\in Y$.  But if $x\in X\setminus f(Y)$, there is surely an open neighborhood $V\ni x$ such that $V\subseteq X\setminus f(Y)$, using that $f(Y)$ is closed; so $f_*(\mathcal O_Y)(V)=\mathcal O_Y(\emptyset)=0$,  meaning that $f_*(\mathcal O_Y)_x=0$. Hence $\mathcal O_{X,x}\to f_*(\mathcal O_Y)_x$ is surjective for  every $x\in f(Y)$ if and only if it is surjective for every  $x\in X$. However this is still not equivalent to $\mathcal O_{X}(U)\to f_*(\mathcal O_Y)(U)$ being surjective for every open $U\subseteq X$. I see that, even with the definition of the book, a closed immersion of schemes is a closed immersion of LRS, because if $\mathcal O_{X}(U)\to f_*(\mathcal O_Y)(U)$ is surjective for every open $U\subseteq X$, then $\mathcal O_{X,x}\to f_*(\mathcal O_Y)_x$ is surjective for  every $x\in X$, and we said that this is equivalent to ($*$). However it seems unlikely to me that some books use a weaker definition, so my question is: does in this setting $\mathcal O_{X,x}\to f_*(\mathcal O_Y)_x$ being surjective for  every $x\in X$ implies $\mathcal O_{X}\to f_*(\mathcal O_Y)$ being surjective for every open $U$? Thanks in advance
Answer: No. Let $Y=\operatorname{Spec} k\times k$, and let $X=\Bbb P^1_k$. Embed $Y$ as the two points $[1:0]$ and $[0:1]$. Then $k=\mathcal{O}_X(X)\to f_*(\mathcal{O}_Y)(X)\cong \mathcal{O}_Y(Y)=k^2$ is not surjective.
If instead you had said $\mathcal{O}_X\to f_*\mathcal{O}_Y$ surjective for all affine open $U\subset X$, this would be correct: see for instance 01QO.
Comment: No, I disagree - I think it is likely that you're misinterpreting their text. Can you provide an exact location where "$\mathcal{O}_X(U)\to f_*\mathcal{O}_Y(U)$ surjective for all $U$" is said? (The reason I think you're misinterpreting is because a map of schemes is called a closed immersion if it's a closed immersion of locally ringed spaces; I doubt G&W would get something so basic wrong, but it's known to happen - Hartshorne's definition of immersions, for example.)
Comment: Thanks the example is clear; so do you confirm that, with G&W's definition, a  morphism of schemes can be a closed immersion of LRS without being a closed immersion of schemes?


Long violin pegs

Question: I have recently purchased an old violin (1805 on the label) to restore myself.
I am, however, surprised by the long pegs it has; see the the image.
Have you ever seen such long pegs?
They look quite old so I would say they are the original ones. Is it possible that they are from a viola or something else?
What do you think?
Answer: As long as the pegs still fit and tune well, they are fine.  This is what happens to pegs after time: the holes wear larger, the pegs smaller, and they therefore stick further in.  At some point you will need either new pegs or (depending on how large the holes are) also the holes bushed out (made smaller with inserts).  But they look still useable to me.
Btw- the pegs are not that old, and perhaps the violin also not.
The peg heads are not as flat as would be usual for 200 year old plus pegs, and they also have the modern taper of 1:30 rather than the old 1:20. And while I of course can't tell how old the violin is from just this photo, statistically speaking there are probably ten times as many newer instruments with false labels than violins really made in 1805

Long violin pegs


Zeek cluster fails with pcap_error: socket: Operation not permitted (pcap_activate)

Question: I'm trying to setting up a Zeek IDS cluster (v.3.2.0-dev.271) on 3 Ubuntu 18.04 LTS hosts to no avail - running zeek deploy command fails with the following output:
fatal error: problem with interface ens3 (pcap_error: socket: Operation not permitted (pcap_activate))

I have followed the official documentation (which is pretty generic at best) and set up passwordless SSH authentication between the zeek nodes.
I also preemptively created the /usr/local/zeek path on all hosts and gave the zeek user full permissions on that directory. The documentation says The Zeek user must be able to either create this directory or, where it already exists, must have write permission inside this directory on all hosts.
The documentation also says that on the worker nodes this user must have access to the target network interface in promiscuous mode.
My zeek user is a sudoer AND a member of netdev group on all 3 nodes. Yet, the cluster deployment fails. Apparently, when zeekctl establishes the SSH connection to the workers it cannot get a hold of the network interfaces and set caps.
Eventually I was able to successfully run the cluster by following this article - however it requires you to set up the entire cluster as root, which I would like to avoid if at all possible.
So my question is, is there anything blatantly obvious that I am missing? To the best of my knowledge this setup should work, otherwise I don't know how to force zeekctl to run 'sudo' in front of every SSH command it is supposed to run on the workers, or how to satisfy this requirement.
Any guidance will be greatly appreciated, thanks!
Answer: I was experiencing the same error for my standalone setup. Found this question from googling it. More googling the error brought me to a few blogs including one in which the comments mentioned the same error. The author mentioned giving the binaries permissions using setcap:
$sudo setcap cap_net_raw,cap_net_admin=eip /usr/local/zeek/bin/zeek

$sudo setcap cap_net_raw,cap_net_admin=eip /usr/local/zeek/bin/zeekctl

After running them both, my instance of zeek is now running successfully.
Source: https://www.ericooi.com/zeekurity-zen-part-i-how-to-install-zeek-on-centos-8/#comment-1586
Comment: For a cluster deployment, in theory you should only 'groom' the zeek manager server; `zeekctl` command is responsible for copying all the configurations over to the workers and, somehow, without being root, the zeek user couldn't accomplish that.
Answer: So, just in case someone else stumbles upon the same issue - I figured out what was happening.
I streamlined the cluster deployment with Ansible (using 'become' directive at task level) and did not elevate when running the handlers responsible for issuing the zeekctl deploy command.
Once I did, the Zeek Cluster deployment succeeded.
Answer: Actually, if you see crates of pcap pkg https://crates.io/crates/pcap they've mentioned providing certain permission for the build file.
Note: If not running as root, you need to set capabilities like so:
sudo setcap cap_net_raw,cap_net_admin=eip path/to/bin


A problem on Measure preserving dynamical system

Question: Let us consider a measure preserving dynamical system $(X,\mathscr{B},\mu,T)$, where $X$ is a compact metric space, $\mathscr{B}$ is a $\sigma$- algebra which contains the Borel $\sigma$-algebra on $X$ and $T:X\rightarrow X$ is continuous.
Then for some fixed $\:f:X\rightarrow \mathbb{R}$ continuous, can we say that  $$\mathbb E_\mu(f|T^{-1}\mathcal B)=0 \implies f = 0$$
[ This question came up in my mind when studying the proof of Proposition 3.4 from 'Recurrence in Ergodic Theory and Combinatorial Number Theory' by Harry Furstenberg. ]
Thanks in advance for any help.
Comment: No: let $X=\{0,1\}^{\mathbb Z_{\ge 0}}$ and $\mu$ be the coin-tossing meaure. Let $\mathcal B$ be the Borel $\sigma$-algebra and let $f(x)=1$ if $x_0=1$; and $-1$ id $x_0=1$. Then $\mathbb E_\mu(f|T^{-1}\mathcal B)=0$. Proof: let $A$ be a subset of $X$. Then $T^{-1}A=0A\cup 1A$, where $iA=T^{-1}A\cap \{x\colon x_0=i\}$. Now $\mu(iA)=\frac 12\mu(A)$ (you can check this for cylinder sets and then it follows for all sets). Now $\int_{T^{-1}A}f\,d\mu=\int_{0A}f\,d\mu+\int_{1A}f\,d\mu=\mu(0A)-\mu(1A)=(\frac 12-\frac 12)\mu(A)=0$.
Comment: Since $\int_Z f\,d\mu=0$ for any $Z\in T^{-1}\mathcal B$, you deduce $\mathbb E(f|T^{-1}\mathcal B)=0$.
Comment: @anthonyquas  Thank you.
Comment: @Surajit can you either (1) delete this question or (2) post an answer and accept it as correct please?
Answer: This answer is just rewriting of the above comment by 'anthonyquas'.
In an Ergodic dynamical system $(X,\mathscr{{B}},\mu,T)$, $\mathbb{{E}_{\mu}}(f|T^{-1}\mathscr{B})=0$ may not imply $f=0$ a.e in $\mathscr{B}$. For example, consider $X=\{0,1\}^{\mathbb{N}}$ with the induced measure $\mu$ from the measure $\nu$ on $\{0,1\}$ defined by $\nu(0)=\nu(1)=\frac{1}{2}$, and $T:X\rightarrow X$ the left shift map defined by $T(x_{0},x_{1},x_{2},...)=(x_{1},x_{2},...)$. Then this system is Ergodic.
But, consider the continuous function $f:X\rightarrow\mathbb{R}$ defined by
$$
f(x_0,x_1,x_2, ...)=
\begin{cases}
1 & \text{ if }x_0=0 \\
-1 & \text{ if }x_0=1
\end{cases}
$$
Then for any $A\in\mathscr{B},T^{-1}A=\{0,1\}\times A$, and therefore
$$\int_{T^{-1}A}fd\mu=\int_{T^{-1}A\cap \{x_0=0\}}fd\mu + \int_{T^{-1}A\cap \{x_0=1\}}fd\mu=\frac{\mu (A)}{2}-\frac{\mu (A)}{2}=0.$$
So, in this case $\mathbb{E_{\mu}}(f|T^{-1}\mathscr{B})=0$ but $f\neq0$ in $\mathscr{B}$.


Twig_Sandbox_SecurityError: Calling "setOption" method on RC4

Question: I'm porting light_skeleton to Drupal 8, and it was working fine on RC2 but I ran into this issue after updating to Drupal 8 RC4.
Twig_Sandbox_SecurityError: Calling "setOption" method on a "Drupal\Core\Url" object is not allowed in "themes/light_skeleton/template/html.html.twig" at line 55. in Drupal\Core\Template\TwigSandboxPolicy->checkMethodAllowed() (line 101 of core/lib/Drupal/Core/Template/TwigSandboxPolicy.php).

After debugging I find out that it was due to this line:
{{ link(item.title, item.url.setOptions({'set_active_class' : TRUE, 'attributes' : {'class' : 'navbar-link'}})) }}

Which I stole from - Custom classes for menu links  and it was working until RC4.
My question is what I'm doing wrong in here ? All I'm doing in there is setting up a variable into the links and in addition setting up the links if the link is active.
There seem to be a similar issue with the bear skin theme. You can look at this issue Twig_Sandbox_SecurityError
Update
Here is the results after debuggin on item.url {{ kint(item.url) }}
RC4 (this is the one that does not work)

RC2 - this how it use to be and it was working.
Comment: What `item.url` is in your context? And what it is in context you stole from? Tried to `var_dump` (or whatever equivalent there is in twig) both?
Comment: @Mołot, I have attached two screenshot debugging information about `item.url`.
Answer: Core recently added a default sandbox so that it's not possible to e.g. call the delete method on node objects.
See https://www.drupal.org/node/2513266, you can bring it up there and try to allow it, try to extend it yourself or call that option in preprocess. Not sure what the best option is.
Answer: I ran into the same problem today. for me i had the same use of setOptions to add class to the menu link. I manage to solve it after reading Functions - In Twig Templates
So instead of using setOptions() with attributes i could just use
{{ link(item.title, item.url, { 'class':['nav__link']}) }} to solve it.
Comment: But does not filter to the active element right ? The only thing that it does is adding the class.
Comment: Correct that just adds the class. Although if you only use one level on menu it ads the is-active class by itself. With that said, if you take a look at   `core/themes/classy/templates/navigation/menu.html.twig` they use menu-item--active-trail to target node/subnode and give parent indication on active trail.


How to troubleshoot slow powerconnect 62xx management interface

Question: Our Dell Powerconnect 62xx switches have a very high packetloss on the management interface. I presume this is caused by a new appliance which uses multicast for communication but I am not sure.
Our network setup is following:
servers a -> Dell PC6248 |
servers b -> Dell PC6248 |-> juniper core router
servers c -> Dell PC6248 |
What we see is that the multicast traffic arrives at all servers (but only the servers b use the multicast) and I fear that this multicast traffic floods the switch management interface.
The switches' management interfaces are reachable via vlan101, all other traffic is sent over other vlans. When I tcpdump on one of the 2 servers with a  vlan 101 ip address, I only get a few arp requests but almost nothing. When I try to ping between these 2 servers, it works like a charm.
I would like to know what a good way is to troubleshoot this problem and maybe help me understand what is going wrong on that subnet.
Answer:
Our Dell Powerconnect 62xx switches have a very high packetloss on the management interface. I presume this is caused by a new appliance which uses multicast for communication but I am not sure.

This sounds like an excellent theory. I would recommend you test it by trying to collect a Wireshark capture either from your workstation connected to the management interface (good) or from your wokrstation's port using a traffic mirroring function (better). You should confirm that you are getting multicast traffic on those interfaces some how before proceeding.

The switches' management interfaces are reachable via vlan101, all other traffic is sent over other vlans.

This is what seems confusing to me. If your application is not sending out multicast traffic on your management VLAN (101) then why would you think its affecting your access to the management interface?
Comment: It seems the problem was indeed the multicast traffic. The switches processed the multicast traffic in software instead of in hardware. which caused the switch lack processing power to process the management traffic.


Criar um Webapp de Controle de estoque

Question: Olá, estou aprendendo Javascript e tenho uma duvida. Tenho conhecimento já em HTML, CSS e SQL
Quais linguagens eu preciso para criar um sistema (controle de estoque) que adiciona , altera (já adicionado) e exclui, elemento através  de pesquisa  interna no site com javascript.
Quero também armazenar os dados do cliente, no client-side, para que ele possa abrir em seu sistema os dados guardados, que ele já tem, e possa ser armazenado em armazenamentos portátil.
Já tenho um código
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Evento de Botão</title>

    <input type="text" id="codigo" placeholder="insira o codigo do produto">
    <input type="text" id="precoCompra" placeholder="preco de compra">
    <input type="text" id="precoVenda" placeholder="preco de venda">
    <button id="btn-adicionar">
        Adcionar
    </button>
    <button id="btn-alterar">
        Alterar
    </button>

            <input type="text" placeholder="pesquise o codigo" id="campoPesquisa">

                Codigo do Produto
                preço compra
                preço Venda
                lucro

Comment: Você vai precisar ter uma bagagem boa de javascript. Para o otimizar seu trabalho você pode usar algum framework como reactjs. Para armazenar dados no cliente-side você pode usar o alguma biblioteca como sql.js
Comment: Ainda estou no Inicio mais Aprendo rápido, vou da uma olhada no reactjs
Comment: Boa noite, trabalho atualmente em uma empresa de sistema de transportadora e ja tenho bastante experiencia e bagagem nesse tipo de sistema, a forma mais correta e segura é você trabalhar com java no back-end e usar um banco de dados ( no meu caso uso e prefiro o postgres ), recomendo você estudar um pouco e entender o funcionamento de servlet e o padrão MVC, sobre onde e quando tratar regra de negocio e coisa do tipo, assim você vai ter um sistema estável e seguro.
Comment: Muito obrigado vou seguir sua dica
Answer: Na minha visão não siga receitas de bolo, antes pesquise e veja se encaixa em sua necessidade.
Necessariamente você vai precisar de tecnologias front(html, css e js) e back(tem varias)...
Pelo que entendi na sua pergunta, você quer ter bastante interação no client, sugeriria um framework SPA como o angular ou uma biblioteca como react e vue.
De alguma forma ira precisar de alguém no server,servindo seu client. Se quiser utilizar somente javascript(client e server), pode utilizar node.js.
De uma pesquisada sobre essas tecnologias e comece aprendendo elas na pratica criando o "protótipo" da sua ideia, isso vai te dar um bom resultado, tanto para o futuro da sua ideia e motivação de aprendizado.

Criar um Webapp de Controle de estoque


Load webform submission

Question: How can I load a webform submission programmatically ?
I've tried : <code>$webform_submission = WebformSubmission::load($sid);</code>
but it return null.
I do this in a custom module call by an handler after webform submission.
Comment: What is the content of the variable $sid?
Comment: It's a submission ID
Comment: I meant the actual content, this would be the first step to debug this.
Comment: I'm getting the submission ID from a custom handler, the data is send by GET to my controller (ID is 1051 currently)
Comment: Did you check if the sid 1051 exists in admin/structure/webform/submissions/manage?
Comment: Yes it does exist, I've double checked it
Comment: Then you need to debug this step-by-step, you've mentioned a controller and a handler, so check how the sid gets from the GET request to the controller and then to the handler.
Answer: I think you have to load sid like below
<code>// Load submission using sid.
/** @var \Drupal\webform\WebformSubmissionInterface $webform_submission */
$webform_submission = \Drupal\webform\Entity\WebformSubmission::load($sid);
</code>
Answer: To load webform submissions of a particular webform programmatically -
<code>    $webform = \Drupal\webform\Entity\Webform::load('WEBFORM_ID');  //webform id is the webform name
    if ($webform->hasSubmissions()) {
      $query = \Drupal::entityQuery('webform_submission')
        ->condition('webform_id', 'WEBFORM_ID');
      $result = $query->execute();
      $submission_data = [];
      foreach ($result as $item) {
        $submission = \Drupal\webform\Entity\WebformSubmission::load($item);
        $submission_data = $submission->getData();
      }
    }
</code>

Load webform submission


php oop variable scope

Question: So I have a class.. In its constructor I include the code which connects me to my database via the mysqli extension:
class MyClass
{
    public function __construct()
    {
        include("dbconnect");
    }
}

dbconnect looks like this:
$host = "localhost";
$user = "user";
$pass = "123";
$database = "myDatabase";

$mysqli = new mysqli($host, $user, $pass, $database);
$mysqli->set_charset('utf8-bin');

Now to my problem: Since mysqli can be used OOP-Style, how do I get access to the variable in MyClass?
function doIt()
{
    $query = "SELECT * FROM myTable";
    $result = $mysqli->multi_query($query);
}

A call to this function results in

Notice: Undefined variable: mysqli in
  ... on line ...
      Fatal error: Call to a member function multi_query() on a non-object
  in ... on line ...

So it seems the scope of the variable is not right. Does anyone know how to fix this? It would be best if MyClass would not need an extra reference or something to mysqli, since I would like to keep it seperated.
Comment: just a warning: If your file is just named 'dbconnect' and nothing more, and it is placed inside the webroot, the webserver might decide to share your database password with the whole world. It's good practice to give configuration data a `.php` file type, so that if it's run by a web server, nothing happens.
Comment: thx for the tip :) Actually, it is not placed in the webroot, and protected by .htaccess, too. But I'm thinking of using a connection class, anyway.
Answer: The $mysqli variable is only available inside the scope of the constructor. Change your constructor like so:
class MyClass
{
    public function __construct()
    {
        include("dbconnect");
        $this->mysqli = $mysqli;
    }
}

Now you can use $this->mysqli in other methods on that object.
Comment: alright, thats ok I can live with that :) Thank you very much!!
Answer: The variable has the same scope as any other variable inside a function: it is only valid inside the function. As soon as the function returns, it's gone. If you want to "persist" a variable for other function in the class, make it a Class member:
class MyClass {
    var $member = null;

    function foo() {
        $localVar = $this->member;
        $this->anotherMember = 'bar';  // $anotherMember is now available for other functions
    }
}

Reusing code via an include is not good precisely because it doesn't give you any control over how the variables will be used. I'd think about restructuring the thing, like making a function that establishes the DB connection, then returns the DB handle.
Comment: yeah, could do that.. maybe I will.. But since I'm using include only to manage my db-connection within one file, and for nothing else (and never will for nothing else ;) ), I think it's ok.. Yes, I could put the whole thing in a Connection-Class, but I'm lazy ^^
Comment: @Thomas Laziness is a necessary attribute for a programmer, but it's also what'll make his programs a mess... ;)
Comment: You're absolutely right. Often enough I was annoyed by myself because of that. And regarding this, I will put the connection into a dedicated class, even if there's not really a good point (except for the mentioned above) doing this ;)
Answer: What you're looking for is the "global" keyword. In general, though, I would avoid globals and rethink your design.
Comment: no, I did not look for the word global.. I looked for something like the posts above....

php oop variable scope


Can a nonabelian group $G$ have a normal abelian subgroup $H$ with $[G:H]=3$?

Question: If $H$ is a cyclic group, for instance, and $[G:H]=2$, then $G$ is a dihedral group with elements equal to the possible states of a regular polygon upon which rotations and reflections are applied. In this case, the quotient group $G/H$ of order $2$ can be interpreted as the group whose elements are the states "not reflected" and "reflected."
I'm having lots of trouble imagining what it would mean if $H$ were a cyclic normal subgroup of $G$ and $[G:H]=3$, or any odd number, for that matter. For even numbers, however, I can imagine the group whose elements are states of a regular polygon upon which rotations and reflections are applied, and whose vertices change color whenever two reflections are applied. In this case, if $H$ is the subgroup of rotations, then  $[G:H]$ could be made to be any even numbers. However, I can't imagine any such thing for odd numbers.
Any hints or advice would be greatly appreciated. For context, I'm doing research about Cayley graphs, and my group theory knowledge isn't as good as it should be. I tried looking through textbooks to find the answer to this question, but I haven't been successful.
Comment: Here's a simple infinite example: take $\mathbb Z^3 \rtimes (\mathbb Z/3\mathbb Z)$, where $t$ is a generator of the $\mathbb Z/3\mathbb Z$ factor and conjugation by $t$ cyclically permutes the factors of $\mathbb Z^3$, i.e. $t^{-1}(a,b,c)t = (c,a,b)$ for $(a,b,c) \in \mathbb Z^3$. $\mathbb Z^3$ is normal and has index $3$.
Answer: Yes.  The Klein subgroup $\{1, (1~2)(3~4), (1~3)(2~4), (1~4)(2~3)\} \triangleleft A_4$.  This subgroup is abelian, as the title of the question requests, but it's not cyclic.
Answer: More generally, let $p$ be any prime. If one has a finite group $G$ of order $p^n$,
then it has a composition series with quotients of order $p$, that is there is
a sequence ${e}=G_0\triangleleft G_1\triangleleft G_2\triangleleft
\cdots \triangleleft G_{n-1} \triangleleft G_n=G$
with each $|G_j|=p^j$. Each $|G_j:G_{j-1}|=p$. If $G$ is non-Abelian,
then somewhere the sequence flips from Abelian to non-Abelian, so there
is some $j$ with $G_{j-1}$ Abelian, and normal of index $p$ in the non-Abelian
group $G_j$.
ADDED IN EDIT
Here's a construction for the original problem with $H$ cyclic.
Let $H$ be a cyclic group of prime order $p$ with $p\equiv 1\pmod3$
(for instance $p=7$). Then $H$ has an automorphism of order $3$. Now let
$G$ be the semidirect product of $H$ by a cyclic group of order $3$
acting on $H$ via this automorphism.
This construction also works for other values of $3$.....


Kubernetes: Receiving Server returned HTTP response code: 403 for URL: https://kubernetes.default.svc.cluster.local:443 while deploying Ignite

Question: While deploying Apache Ignite on Kubernetes I am getting following error in logs of the apache ignite pods
Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: https://kubernetes.default.svc.cluster.local:443/api/v1/namespaces/ignite-stack/endpoints/ignite-service
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)
    at org.apache.ignite.internal.kubernetes.connection.KubernetesServiceAddressResolver.getServiceAddresses(KubernetesServiceAddressResolver.java:109)
    ... 21 more

Answer: These kind of error :
Server returned HTTP response code: 403 for URL:https://kubernetes.default.svc.cluster.local:443
usally happens when serviceaccount, secret token for service account, and clusterrolebinding is not in sync (means there is some discrepancy either in token not to service account, or they are totally in different namespaces). Therefore, apiServer cant validate the request as authentic request and gives 403 error.
In my case, service account was having wrong namespace as shown below:

Where as if you see my service account details i configured with following namespace
apiVersion: v1
kind: ServiceAccount
metadata:
  creationTimestamp: "2022-09-12T14:35:38Z"
  name: ignite
  namespace: ignite-stack
  resourceVersion: "854530"
  uid: b6177528-b05c-4d10-9446-09f54164ca39
secrets:
- name: ignite-secret

So make sure to check these mistakes first.


Install Twisted on CentOS 5.5

Question: CentOS 5.5 is using the old python 2.4 ! But I want to install Twisted on it ! Does anyone maintain a RPM of this library ?
Answer: Twisted is in EPEL as the python-twisted-* packages.

Install Twisted on CentOS 5.5


How to mock Angular's 'LocationChangeListener' interface with Jasmine?

Question: I'm having a bad time trying to mock Angular's LocationChangeListener interface, using Jasmine.
This is what my code do:
<code>      onPopState(fn: LocationChangeListener): void {
        this.platformLocation.onPopState((ev: LocationChangeEvent): void => {

        ... here I do the stuff I actually want to test ...

      }
    }
</code>
So basically, I'm trying to call onPopState with a LocatioNChangeListener, so I can test all the logic inside the function.
I already mocked the LocationChangeEvent:
<code>      const locationChangeEventMock: LocationChangeEvent = {
        type: 'typemock',
        state: 1,
      };
</code>
But all my efforts to mock LocationChangeListener are in vain... Is it actually possible? Due to TypeScript 'issues' with interfaces?
Edit: after some debugging, it looks like ev: LocationChangeEvent doesn't comes from LocationChangeListener (apparently), so I need to, somehow, trigger LocationChangeEvent?
By now, I sorted it doing some code refactor: extracting the code I wanted to a method, and then calling that method... but still curious how to test this.
Comment: How do you use `fn` inside your method?
Comment: At the end of the method, like this: `fn(ev);`. What is really important for me is to be able to work with the `LocationChangeEvent`, as it's what I work with inside the method, so I truly need a workable mock of `LocationChangeListener` that calls the `LocationChangeEvent` mock.
Comment: I have added an answer and created an example of mock. https://codesandbox.io/s/fomfx
You can check it in the Typescript playground. This mock is valid.
Answer: Probably, you can pass an empty cb-function as a mock like this:
<code>function onPopState(fn: LocationChangeListener): void {}

onPopState((val)=>{console.log('some logic', val)});

// OR
function mockFunc(val: LocationChangeEvent){
  console.log(val);
}

onPopState(mockFunc);
</code>
It should be valid.
Comment: Thanks for answering, but I think I'm missing something, as I can't see how to use this on the test: if in my test I'm calling `service.onPopState()` (`service.onPopState(mockFunc)` in this case), so I can then check the functionality inside the method, I can't pass from `this.platformLocation.onPopState((ev: LocationChangeEvent): void => {` point. It looks like `LocationChangeEvent` is not properly set.


How to sort taxonomy terms on a term reference field?

Question: I have a taxonomy term reference field on a node. On the "node/add" page I would like to sort the terms by "due date" (a field added to that vocabulary).
Comment: Taxonomy terms are entities, could you use the Entity Reference module with a view as the widget? Then you could use a view to order the terms by the custom field
Comment: You can do if you want a more advanced widget, but if you just need a dropdown you can use the built in views integration. Just create a view with an _Entity Reference_ display, then use the _Views: Filter by entity reference view_ mode when you're configuring the field
Comment: didn't know ER can do that. Do I need to use http://drupal.org/project/entityreference_view_widget?
Answer: If you're stuck using a term reference field, here are some widget options:

https://drupal.org/project/term_reference_sortable
https://drupal.org/project/ttr_configurable_widget
https://drupal.org/project/taxonomy_orderselect
Answer: I had succsefull manage this by this module, Views Term Hierarchy Weight Field, just add (hidden) Hierarchical weight field, then, on sort settings, sort by this new field.


Proving an identity involving factorials

Question: I have stumbled upon the following statement and have verified it computationally for many $n$ (up to n=500, it took a long time for my computer to do out all of the math), yet I have no idea how to go about proving it.
$$\sum _{ i=0 }^{ n } \sum _{ j=0 }^{ n } \frac { { ((2n)! })^{ 2 }(-1)^{ i+j }(2i+2j)! }{ (n-i)!(n-j)!(2i)!(2j)!2^{ i+j }(i+j)! } =\frac { (4n)! }{ { 4 }^{ n }(2n)! } $$
One thing to note is that if we multiply the top and bottom of the fraction by $(i)!$, $(j)!$, and $(n!)^2$, then certain terms simplify into the factorial definition of the binomial coefficient, so the sum is also expressible as:
$$\sum _{ i=0 }^{ n } \sum _{ j=0 }^{ n } (-1)^{ i+j } \binom{n}{i}\binom{n}{j} \frac { { ((2n)! })^{ 2 }}{(n!)^2}\frac{(i)!}{(2i)!}\frac{(j)!}{(2j)!}\frac{(2i+2j)! }{2^{ i+j }(i+j)! } =\frac { (4n)! }{ { 4 }^{ n }(2n)! } $$
Also, let us define $P(n)$ to be equal to the product of the first $n$ positive odd numbers (or more specifically, $P(n)=(2n-1)!!$). We can use the explicit formula $P(n)=\frac{(2n)!}{2^n n!}$ (see here for explanation) to rewrite various expressions:
$$\frac{(2i+2j)! }{2^{ i+j }(i+j)! }=P(i+j)$$
$$\frac{((2n)!)^2}{(n!)^2}=(P(n))^2 2^{2n}$$
$$\frac{(i)!}{(2i)!}=\frac{1}{2^i P(i)}$$
$$\frac{(4n)!}{4^{n}(2n)!}=P(2n)$$
And so the statement can be rewritten as:
$$ \sum _{ i=0 }^{ n } \sum _{ j=0 }^{ n } (-1)^{ i+j } \binom{n}{i}\binom{n}{j} \frac{2^{2n}(P(n))^2 P(i+j)}{2^{i+j}P(i)P(j)}=P(2n) $$
Interestingly enough, this proves that the left hand side must be an integer (see here for an explanation), which i believe is a step in the right direction.
This is all just random stuff I have been trying to attempt to prove the identity although so far I have not gotten very far. If anyone has any idea on how I could prove this identity or even just begin to prove the identity, please help me out! Any and all help is appreciated!
Edit, here is some more work done on the topic:
Let us define: $$R_n = \sum _{ i=0 }^{ n } \sum _{ j=0 }^{ n } \frac { { ((2n)! })^{ 2 }(-1)^{ i+j }(2i+2j)! }{ (n-i)!(n-j)!(2i)!(2j)!2^{ i+j }(i+j)! }$$
I am currently trying to prove that $R_n=P(2n)$. Since $P(n)$ is the product of the first $n$ odd integers, and $2n-1$ is the $n$th odd integer, it follows that $P(2(n+1))=P(2n+2)=P(2n) \cdot (4n+1) \cdot (4n+3)$. Thus (since the base case works, and you can confirm that if you truly want), a statement equivalent to what I am trying to prove is:
$$R_{n+1}=(4n+1)(4n+3)R_{n}$$
Comment: Maple outputs
$$\sum _{i=0}^{n}{\frac { \left(  \left( 2\,n \right) ! \right) ^{2}
 \left( -1 \right) ^{i}{\mbox{$_2$F$_1$}(-n,1/2+i;\,1/2;\,1/2)}}{
 \left( n-i \right) !\,n!\,{2}^{i}i!}}$$
 for the double sum under consideration.
Comment: This problem admits a straightforward solution using computer algebra techniques.  The hypergeometric summand means that Zeilberger's algorithm applies.  (Unfortunately I am too busy at this point to write out such a solution.)
Comment: When you get the chance, can you please write out a solution or even just provide a link that explains the algorithm you are referring to?
Comment: I will try to.  Zeilberger's algorithm is implemented in Maple for example.  (The sticking point is that Maple's recurrence solving is not strong enough for your particular problem.  That means I would need a little more time.)
Comment: Thank you very much. If the bounty expires by the time that you get the answer, then I will open up a new bounty for you.
Answer: The equation
$$
\sum_{i = 0}^{n}\sum_{j = 0}^{n} (-1)^{i + j} \binom{n}{i} \binom{n}{j} \frac{2^{2n}(P(n))^{2}P(i + j)}{2^{i+j}P(i)P(j)} = P(2n)
$$
is a prime suspect for combinatorial proof (combinatorial proof). The idea would be to find a quantity that both sides are counting.
Particularly, the quantity $\binom{n}{i}\binom{n}{j}$ is what suggests the nature of the sum. If we let
$$f(i, j) = (-1)^{i + j}\frac{2^{2n} P(n)^{2} P(i + j)}{2^{i+j} P(i)P(j)}$$
then it reduces to
$$
\sum_{i = 0}^{n}\sum_{j = 0}^{n}\binom{n}{i}\binom{n}{j}f(i,j)
$$
This is then a sum of $f(i,j)$ over a very particular set: the set of two-part partitions of subsets of $\{1,2,\dots 2n\}$. This set is less complicated than it sounds: any element is just a pair of subsets, one of $\{1, 2, \dots n\}$ and the other of $\{n + 1, n+2, \dots 2n\}$. Why this makes sense is not clear.
As for simplifying $f(i,j)$, we can break it up into pieces. The first thing to note is the $2^{i + j}$. The number of subsets of a set with $k$ elements is $2^{k}$ (more information).
Therefore, we might consider that
$$\frac{2^{2n}}{2^{i+j}} = 2^{2n - i - j} = (2^{n - i})(2^{n - j})$$
may be a good way to decompose it. Then the quantity represents the number of subsets of the remaining elements
after removing $i$ from the first $n$ and $j$ from the second.
Also, this suggests the origin of $(-1)^{i + j}$. When summing over certain sets of subsets, we run into sign changes due to the principle of inclusion-exclusion (also known as PIE).
The significance of $\left(P(n)^2 \frac{P(i + j)}{P(i)P(j)}\right)$ then is a bit clearer. Consider the relation between $P(2n)$ and $P(n)^{2}$.
Since $P$ is nonlinear, the difference is analogous to a crossterm
(e.g $(x+y)^{2} - (x^{2} + y^{2})$).
Therefore, the sum may be quantifying the size of this crossterm. Indeed, if we move $P(n)^{2}$ to the other side, we get:
$$
\sum_{i = 0}^{n}\sum_{j = 0}^{n} \binom{n}{i} \binom{n}{j} \left((-1)^{i + j} \cdot 2^{2n - i - j}\right) \frac{P(i + j)}{P(i)P(j)} = \frac{P(n + n)}{P(n)P(n)}
$$
Or, letting $g(i,j) = \frac{P(i + j)}{P(i)P(j)}$,
$$
\sum_{i = 0}^{n}\sum_{j = 0}^{n} \binom{n}{i} \binom{n}{j} \left((-1)^{i + j} \cdot 2^{2n - i - j}\right) g(i,j) = g(n,n)
$$
This still does not have a clear interpretation, but it is getting there.
The next step would be to find a concrete interpretation to one of $P$ or $g$
(an interpretation of the other would likely follow).
Update:
It turns out that for even integers $g$ has a particularly nice interpretation.
Note that
$$
(2k)!! = (2k)(2k-2) \dots (4)(2) = 2^{k}[(k)(k-1) \dots (2)(1)] = 2^{k} k!
$$
Therefore,
$$
g(2i,2j) = \frac{2^{i+j}(i+j)!}{2^{i}2^{j} \ i! \ j!} = \frac{(i+j)!}{i! \ j!} = \binom{i+j}{i}
$$
which is the number of $i$ element subsets of $\{1, 2, \dots i+j\}$.
Unfortunately it does not work so nicely for odd integers ($g(i,j)$ is typically not an integer when at least one of $i, j$ is odd).
The double factorial has a number of interpretations, particularly for odd values (see wikipedia).
Also of potential use is a paper about relevant identities (A combinatorial survey of identities for the double factorial).
Answer: Consider the polynomial
$$
f_n(x)=\left(x^2+1-\frac{\left(x+1\right)^2}{2}\right)^{2n}.
$$
The left and right hand sides of the OP's identity each compute the coefficient of $x^{2n}$ in $f_n(x)$.
One the one hand, we can expand $f_n$ using the trinomial and binomial theorems:
\begin{align*}
f_n(x)&=\sum_{a+b\leq 2n}\frac{(2n)!}{a!b!(2n-a-b)!}x^{2a}\left(x+1\right)^{2(2n-a-b)}\frac{(-1)^{2n-a-b}}{2^{2n-a-b}}\\
&=\sum_{\substack{a+b\leq 2n\\r\leq 4n-2a-2b}}\frac{(2n)!}{a!b!(2n-a-b)!}{4n-2a-2b\choose r}\frac{(-1)^{2n-a-b}}{2^{2n-a-b}}x^{2a+r}.
\end{align*}
To get $x^{2n}$, we need $r=2n-2a$, so that $a\leq n$. Additionally, $r=2n-2a$ and $r\leq 4n-2b-2b$ imply $b\leq n$, so we are summing over $0\leq a,b\leq n$. Make the substitution $i=n-a$, $j=n-b$ (so that $r=2i$). In terms of $i$ and $j$, the sum is over $0\leq i,j\leq n$. This shows that the coefficient of $x^{2n}$ is the left hand side of the OP's identity.
On the other hand, we can simplify $f_n$:
\begin{align*}
f_n(x)&=\left(\frac{(x-1)^2}{2}\right)^{2n}\\
&=\frac{(x-1)^{4n}}{4^n}.
\end{align*}
The binomial theorem then shows the coefficient of $x^{2n}$ is the right hand side of the OP's identity.
Comment: Wow, this looks amazing. I will go verify the logic and if everything works out then I will award you the bounty.
Comment: Can you further explain why in the second summation, the bound went from $a+b \leq 2n$ to $a+b \leq n$?
Comment: The only problem I am having with this proof is that I am not understanding exactly how/why the bounds become $i \leq n$ and $j \leq n$ when the $i$ and $j$ substitutions are made
Comment: The $a+b\leq n$ was a typo. I made an edit to fix that, and I tried to explain why the range of summation (in terms of $i$ and $j$) is $0\leq i,j\leq n$.
Comment: Ah it makes sense now. This proof works! Thank you very much!
Answer: Let,
$$S_1(n)=\sum _{ i=0 }^{ n } \sum _{ j=0 }^{ n } \frac { { ((2n)! })^{ 2 }(-1)^{ i+j }(2i+2j)! }{ (n-i)!(n-j)!(2i)!(2j)!2^{ i+j }(i+j)! } \\
S_2(n) =\frac { (4n)! }{ { 4 }^{ n }(2n)! } $$
Notice that $S_1(0)=S_2(0) = 1$.  Secondly observe by elementary manipulations that,
$$ S_2(n+1) = (1+4n)(3+4n)S_2(n)$$
Substitute $S_1(n)$ into the same recurrence and observe it also satisfies,
$$S_1(n+1) = (1+4n)(3+4n)S_1(n)$$
The two sequences, $S_1$ and $S_2$, agree at $n=0$ and one may compute their $(n+1)^\textrm{th}$ values by the same recurrence it must be that the two sequences agree for all $n$ by induction.  One concludes that,
$S_1(n) = S_2(n)$.
Additional Remarks:  To help understanding I will further sketch how to verify the recurrence for $S_1$.  I wish to avoid typing endlessly so will not give all the algebra.  Also the exercise is far harder than usual!
Start from $S_1(n+1)$ and start manipulating,
$$ S_1(n+1) = \sum _{ i=0 }^{ n+1 } \sum _{ j=0 }^{ n+1 } \frac { { ((2n+2)! })^{ 2 }f(i,j)}{ (n+1-i)!(n+1-j)!} $$
Here $f(i,j)$ is used just to shorten expressions.  Compare to above for a definition.  Continuing,
$$ S_1(n+1) = \sum _{ i=0 }^{ n+1 } \sum _{ j=0 }^{ n+1 } \frac { { ((2n+2)! })^{ 2 }f(i,j)}{ (n+1-i)!(n+1-j)!}\\
= \sum _{ i=0 }^{ n+1 }\left[ \frac { { ((2n+2)! })^{ 2 }f(i,n+1)}{ (n+1-i)!}+ \sum _{ j=0 }^{ n } \frac { { ((2n+2)! })^{ 2 }f(i,j)}{ (n+1-i)!(n+1-j)!}\right]\\
= \sum _{ i=0 }^{ n+1 }\left[ \sum _{ j=0 }^{ n }  \frac { { ((2n+2)! })^{ 2 }f(i,n+1)}{ (n+1) (n+1-i)!}+ \frac { { ((2n+2)! })^{ 2 }f(i,j)}{ (n+1-i)!(n+1-j)!}\right]\\
=\left[ \sum _{ j=0 }^{ n }  \frac { { ((2n+2)! })^{ 2 }f(n+1,n+1)}{ (n+1)}+ \frac { { ((2n+2)! })^{ 2 }f(n+1,j)}{ (n+1-j)!}\right]+ \sum _{ i=0 }^{ n}\left[ \sum _{ j=0 }^{ n }  \frac { { ((2n+2)! })^{ 2 }f(i,n+1)}{ (n+1) (n+1-i)!}+ \frac { { ((2n+2)! })^{ 2 }f(i,j)}{ (n+1-i)!(n+1-j)!}\right]\\
= \sum _{ i=0 }^{ n} \sum _{ j=0 }^{ n }\frac { { ((2n+2)! })^{ 2 }f(n+1,n+1)}{ (n+1)^2}+ \frac { { ((2n+2)! })^{ 2 }f(n+1,j)}{ (n+1)(n+1-j)!}+  \frac { { ((2n+2)! })^{ 2 }f(i,n+1)}{ (n+1) (n+1-i)!}+ \frac { { ((2n+2)! })^{ 2 }f(i,j)}{ (n+1-i)!(n+1-j)!}  $$
Placing this into the recurrence, putting the polynomial on the front of $S_1(n)$ should give a remaining double sum.  The double sum indeed vanishes and my computer is currently doing the algebra to show that...
Comment: Can you explain how you know that S1 satisfies the same recurrence?
Comment: I obtained the $S_1$ recurrence by using computer algebra techniques (omitted because they are unhelpful to a website).  It is possible to substitute the sum definition into the recurrence and manipulate.  I will try to make that clearer later so that I have not merely re-written the problem if you see it that way!
Comment: I have a few questions, What computer algebra system are you using and how are you using it to prove that this statement holds?
Comment: Those questions have long answers!  I am using a Mathematica package called sigma available by request [here](http://www.risc.jku.at/research/combinat/software/Sigma/index.php) and you can find references on how it works.  The THEORY is that once you know the recurrence one can substitute in the sum.  Here that is harder but I am still optimistic of giving a neat proof.


Is $x^\alpha \sin(1/x^\beta)$ an anti-derivative on $[0,1]$?

Question: Define $f: [0,1] \to \mathbb{R}$ as
$$f(x)=\begin{cases}x^\alpha  \sin(1/x^\beta) &\text{if }0 < x \leq 1\\
0 & \text{if } x = 0 \end{cases}$$
where $\alpha$ and $\beta$ are positive real numbers.
If $0 < \alpha - \beta \leq 1$, then the derivative of $f$ at 0 is not defined. However, $f'$ is well-defined on $(0,1]$ and $\int_0^1 |f'| < \infty$. Is it still valid to apply the Fundamental Theorem of Calculus to write
$$
f(x) = \int_0^x f'
$$
Answer: For $x > y > 0$, we have $\int_{y}^x f'(t)\; dt = f(x) - f(y)$.  Since $\lim_{y \to 0+} f(y) = 0$, $\int_0^x f'(t)\; dt = f(x)$ as an improper Riemann integral.


Server room door automatic opener

Question: I'm looking to solve the problem of having the server room door open "automatically" when we need to move a large amount of equipment into the room.  The typical case is the lab admin gets a large box and holds it with both hands as he hip-checks the badge scanner and then kicks the door open.  It would be nice to have something like the ADA automatic door opener but with badge access.
Does anyone have experience with such a system or possible have a better idea of enabling "hands free" access while retaining security?  (Yes, we tried to make the obvious process fix of using a cart to keep your back safe and hands free, but the success rate is low)
edit: Sorry, but I don't think I described the issue correctly.  The problem isn't holding the door open (doorstop) but people opening the door with their hands full and kicking the door to do so.  The obvious solution is to not open the door with your hands full.  Telling people to do this (the process change) isn't effective.  If there is an $x,000 solution folks are familiar with, I'd appreciate sharing a solution.
Comment: I'm voting to close this question as off-topic because it's overlooking the common sense solution: a doorstop.
Comment: I've seen plenty of server rooms and other secure locations with an ADA opener **as well as** a proximity badge reader. The ADA openers are designed such that if someone tries to activate the motor, it'll try to open the door, but will notice the resistance and will quit. Users just need to scan their badge and then hit the opener button.
Comment: Does your office have an intern? Holding a door open is great on-the-job experience.
Comment: @ewwhite Doorstop kind of violates the whole principle of being able to open the door while carrying something heavy and then having the door close automatically. A doorstop is a fine idea for an unsecured environment but a *terrible* one for someplace that needs to be locked down.
Comment: @scottpack I work in a number of secured data center environments. None have automatic doors. They *do* have doorstops and rolling equipment carts and racks...
Comment: @ewwhite I find that pretty terrible for all kinds of reasons.
Answer: How about a $2.99 door stop?  Seriously.  Putting an automatic door opening systems seems a bit much; never mind it'll be $$$.
Comment: +1 - Thank you! Common sense and simple solutions to (not very) complex problems win the day!
Comment: I like simple solutions as well, but I have seen inspectors get grumpy when they see door stops around rooms that have FM-200 (or the like) gas fire suppression systems.
Answer: Can you get the badge system to, in addition to the normal door strike release, close a normally-open relay wired in-line with the button for the door opener, allowing the user to press the button for the opener when required (but still having it be optional), and not wear out the motor in the opener by opening against the locked strike?

Server room door automatic opener


Send HTML email to all users of a role in action not display .....help me please

Question:
Send HTML email to all users of a role in action not display ;
only send HTML-email display
help me please.
Comment: Welcome to Drupal Answers! It's not really clear what are you asking; are you saying that you don't see the "Send HTML mail to all users of a role" in the options?
Answer: That action comes from the Mime Mail module, it's not one of Rules's defaults.
Once you've downloaded and installed the new module, just re-visit the Rules setup page and you'll find it in the list.


When writing in math, do you use a comma or colon preceding an equation?

Question: This is a general question about mathematical writing especially for writing research papers and the like.

Question: Do you precede an equation with a comma or colon?

Example A:

The following equation is the Yosida-Hawking-Penrose-Dantzig function
\begin{equation}
f(x) = \frac{1}{2} D_\alpha(x,y)
\end{equation}
The following equation is the Yosida-Hawking-Penrose-Dantzig function,
\begin{equation}
f(x) = \frac{1}{2} D_\alpha(x,y)
\end{equation}
The following equation is the Yosida-Hawking-Penrose-Dantzig function:
\begin{equation}
f(x) = \frac{1}{2} D_\alpha(x,y)
\end{equation}

Example B:

In fact, we can express the earlier function using a much simpler expression
\begin{equation}
f(x) = \varphi(x,y)
\end{equation}
where $\varphi(x,y)$ is the Demiane functional
In fact, we can express the earlier function using a much simpler expression,
\begin{equation}
f(x) = \varphi(x,y)
\end{equation}
where $\varphi(x,y)$ is the Demiane functional
In fact, we can express the earlier function using a much simpler expression:
\begin{equation}
f(x) = \varphi(x,y)
\end{equation}
where $\varphi(x,y)$ is the Demiane functional

Can anyone comment on which one is the best practice?
Comment: You should have "following" instead of "follow".
Comment: Tangential comment, but the equation and the function are two different things (they are not even the same type of thing), so I might avoid saying that the equation "is" the function.
Comment: This has also [been discussed](http://mathoverflow.net/questions/6675/periods-and-commas-in-mathematical-writing) at MathOverflow.
Comment: I agree with what the others have said, but if you precede the equation with a comma as in the second example and then continue the sentence after the equation, you should put a comma after the equation itself also.  This is hinted by Olivier's answer.
Comment: I would go for colons in first and comma in the second, at the very least use full stops after equations. [this](http://math.stackexchange.com/questions/1810816) amongst many others may be helpful, but at the same time, should it be moved to a chat or flagged as duplicate?
Comment: I find it interesting that none of the answers to date distinguish between a displayed equation and an in-line equation. My gut is telling me that there are differences between the two cases, although I have trouble articulating what they are (which is why I am not answering myself yet).
Comment: In example A, we have a 4th option: precede a (non-inline) equation with a full stop.
Answer: Generally, I would treat the equation as if it were any ordinary noun phrase, and use the usual rules for comma, colon, or no punctuation.
A colon is used if the equation is an elaboration, or an item.  So, just as you might write

Lips are characterized by the following properties: fleshy, paired, red.

you would write

An ellipse is characterized by the following equation:
$$ \frac{x^2}{a^2}+\frac{y^2}{b^2} = 1 $$

A comma precedes a non-restrictive clause (one that describes rather than identifies the noun phrase), so by analogy with

The line can be assigned to a simpler character, Polonius.

we might write

A line can be described with a simpler equation,
$$ y = mx+b $$

In comparison, with a restrictive clause, we use no comma, so just as we would write

From this, the oiler obtained the formula CH$_3$C$_6$H$_4$C$_2$H$_5$.

we would also write

From this, Euler obtained the formula
$$ e^{i\pi}+1 = 0 $$

I suspect there aren't any hard and fast rules for this, however.  Whatever you choose to do, be consistent and reasonable.

ETA (2017-09-10): You'll notice that I have no periods at the ends of these equations.  The papers I have generally (though not universally) observe this pattern.  However, in other fields, equations may have ending punctuation depending on how they occur within a sentence.  It may be useful for a writer to consult the publication's style guide, if applicable, or at least examine previous articles within the same publication or outlet.

ETA (2022-05-01): Somewhat coincidentally, on the same day (today), I both (a) received a straggling upvote on this rather middle-aged answer, and (b) found the following in the foreword to the third edition of Ian Stewart's classic book, Galois Theory (2004):

[after discussing the need for punctuation for formulas in the main body of the text] But I have come to the conclusion that eliminating visual junk from the printed page is more important than punctuatory pedantry, so that when the same formula is displayed, for example
$$ t^2+1 $$
then it looks silly if the comma is included, like this,
$$ t^2+1, $$
and everything is much cleaner and less ambiguous without punctuation.
Purists will hate this, though many of them would not have noticed had I not pointed it out here. Until recently, I would have agreed. But I think it is time we accepted that the act of displaying a formula equips it with implicit (invisible) punctuation. This is the $21$st century, and typography has moved on.
Comment: Good answer. But are you not forgetting the dots at the end of the sentences? :^)
Comment: What about periods at the end of the equations if they end the sentence? Like $$e^{i\pi}+1=0.$$
Comment: @BrianTung I have never seen periods *not* used after equations ending a sentence (examples of what I read are given in my answer). Can you provide an example of this from what you consider an exemplary publication?
Comment: @Olivier: I'm in computer science.  I just looked over some papers that appeared in IEEE Security and Privacy, and lo and behold, it's a mixed bag.  About one paper in five seems to have the periods at the end.  That confirms the notion that it's a matter of what papers one reads.  I'll edit my answer accordingly.  Thanks for the tip!
Comment: But this is asking about mathematical papers, not IEEE Security and Privacy? Within mathematical papers, I have never seen a paper drop punctuation or commas after an equation =)
Comment: @YashasSamaga Euler's last name is pronounced exactly like "oiler" (at least in the US, where the uninitiated often pronounce it "yoo-ler"), so the last pair of examples is funny to me (maybe "pun" isn't exactly the right word).
Comment: @Readin: I would probably put a period after it.  But you know, I almost never put in an equation inline at the end of a sentence—possibly because subconsciously I want to avoid having a period end the equation.  I suspect my hangup has to do with overloading the period.
Comment: "Generally, I would treat the equation as if it were any ordinary noun phrase, and use the usual rules for comma, colon, or no punctuation." I'll just be one more voice in this comment thread that thinks this rule extends to the use of a period following an equation if it ends the sentence.
Comment: @AustinMohr: Fair enough, duly noted :-P
Comment: @Brian I would appreciate that you take a look at my answer and provide appropriate feedback. There seems to be a misunderstanding...
Comment: @Olivier: Sorry, but this time, it seems some comments have been deleted.  I will say that I think your formatting is defensible, but it is not the only reasonable approach.  And equations swallow the period. :-)
Comment: @Brian Thanks for the feedback. I deleted my comments that encouraged an empty conversation. In scientific articles, there is a period at the end of equations ending a sentence. See [this very well written article](http://statweb.stanford.edu/~cgates/PERSI/papers/bayer92.pdf) published in the Annals of Applied Probability, for instance.
Comment: @Olivier: Interesting, but I would say that though that is reasonable, it is not universal.  There are plenty of articles where no punctuation would be used in those places.  I tend to find it distracting, but not unreasonable.
Comment: @Ruslan: I would say that that is not unknown, but I don't see it that often.  That may be a consequence of the papers/books I read, however.
Comment: What if the equation is inline in the paragraph rather than on it's own line?
Comment: @N3buchadnezzar: There are mathematical equations in IEEE S&P.  But I won't contest the primacy of mathematics journals.  I'll look at those papers at work tomorrow; I have some of them there.
Comment: Haha "oiler" - love it!
Comment: When typing displayed equations in $\LaTeX$, I add a thin space (``\,``) after the equation but before the punctuation. For instance: ``\begin{equation*}a^2 + b^2 = c^2 \,. \end{equation*}``. The idea is to try and to make it clear that the punctuation is part of the sentence, not the equation or expression being displayed. Not sure how common this is, but I find it helps the eye if you're displaying set-builder notation, or use ``\dots`` somewhere. I've seen this recommended on various TeX Stack Exchange answers, but see also [this MathOverflow post](http://mathoverflow.net/a/6677/80429).
Comment: @DavidRobertson: Yes, I've seen this too.
Comment: @pjs36 What's the Euler pun?
Comment: Excellent answer. Re: periods and equations, I put periods at the end of equations that are the end of sentences and **in-line**. Out of line equations I don't give periods to.
Comment: Thanks, noble editor, but I think I'd prefer to let the answer stand as is, with the comments discussing the presence or absence of the displayed equations.
Comment: Agree completely regarding the pedantic punctuation comment.

Do any of the punctuation hardliners include commas after each line in a series of equation modifications when using an AMS align environment and a period after the last. It would be very distracting and very ugly. Actually, my junior high grammar teacher might argue that one should use semicolons followed by an ending period. Even uglier and more distracting.

The priority of writing is to convey ideas not to obey schoolmarms.
Answer: Equations should be included as part of the sentence, as in the following.

Consider the Yosida-Hawking-Penrose-Dantzig function
$$
f(x) = \frac{1}{2}D_\alpha(x,y).
$$

It can also be expressed as
$$f(x)=\phi(x,y),$$
where $\phi(x,y)$ is the Demiane functional.

In example B, if you don't want to change the sentence:

In fact, we can express the earlier function using the much simpler expression
$$f(x)=\phi(x,y),$$
where $\phi(x,y)$ is the Demiane functional.

I use this style example. Milnor's book, referenced in the comments below, follows the same rules, as do all the references and publications in my bookshelf (Polya's Problems and Theorems in Analysis, Rudin's Real and Complex analysis, etc.)
Standard guides

Knuth's Mathematical Writing.

How to Write Mathematics, by P. Halmos.
Comment: @ThomasAndrews rather "Consider the scientist Stephen Hawking. It can also be expressed as something, where whatever". Nevertheless, the OP started with examples conatining "follow[ing]". There, I'd use a colon: "The following person is a scientist: Stephen Hawking."
Comment: I think your first example is standard, grammatically correct, and clear.  I read such statements often in math writing.  For example I think a similar statement appears on p. 35 of Milnor's book Topology from the Differentiable Viewpoint: "The sum ... is equal to the Euler number $\chi(M) = \sum_{i=0}^m (-1)^i \, \text{rank} \, H_i(M)$." (The formula for $\chi$ is displayed on its own line, as is the formula for $f$ in your first example.)
Comment: For what it's worth, your _principle_ is correct (the formula _is_ part of the sentence that surrounds it and punctuation should be applied accordingly) and your last two examples look fine to me. But sentences sometimes contain commas or colons, and sometimes those occur just before a formula. I would put a comma after "function" in your first example.
Comment: Another example, from one of Terence Tao's [blog posts](https://terrytao.wordpress.com/2016/10/23/another-problem-about-power-series/), is shown in this image: http://imgur.com/gallery/XmOvO Notice the lack of a comma after the word "function".
Answer: No punctuation should be used between the word "function" and an immediately following expression that defines it, unless "the function" has already been defined and its expression in the text is just a convenient reminder of its definition. Exactly the same applies in ordinary Language. Compare, for example the following two sentences:
My sister Laura lives in London.
My sister, Laura, lives in London.
The second sentence implies that "my sister" has already been defined, perhaps as the only sister or the sister who was previously discussed. In contrast, the first sentence makes no such implication: Laura, as far as we can tell from the sentence, might be any one of many sisters; but the sentence does specify which sister is being considered.
In general, the punctuation of mathematical writing should follow that of the corresponding natural language. In particular, a mathematical expression that ends a sentence should be followed by a full stop.
Answer: This is what I remember from my technical writing class of twenty years ago.
The most important thing is that a colon must only be used at the end of a complete sentence.
For example
A line can be excpressed as: $$y=mx + b.$$
is incorrect, and
A line can be expressed as $$y=mx + b$$
and
The following equation is the slope-intercept equation of a line: $$y = mx + b$$
are correct
Answer: For papers, it always depends on what is specified in the style guide for the publication or journal. Having said that, however, the guide is often not so specific as to whether the sentence with the equation should be punctuated with commas, colons or little flags.
For example, from the Monthly Notices of the Royal Astronomical Society

Mathematics
...
Equations should be punctuated as part of the sentence. Displayed equations are ranged left (i.e. no indent). Numbering of equations should follow the convention (1), (2)… throughout the whole paper, or (2.1), (2.2)… by section. Equations in appendices should be numbered (A1), (A2), (B1), etc.

This is indented, but still accepted:
image from paper at https://arxiv.org/pdf/1401.2593.pdf
edit: added picture

Much seems to depend how particular/pedantic a reviewer is in relation to the style guide (which they may not know in such detail for specifics like this), and grammar conventions are not universal.
Check the style guide, read some of the published papers from the journal in question, and be consistent in application of grammar rules when inserting equations.
Comment: The editor of a journal has just asked me politely to check the Editorial Style Guide. I think the most noticeable deviations of mine were to end equations with a comma if "where a denotes..." followed, and ended with a dot if it was the end of the sentence.
Answer: I was told to use correct punctuation as defined by grammatical rules, but to always place the equation or formula on a line of its own, even if this meant starting a line with a punctuation mark. Even though the layout may look a little odd there can be no confusion as to the meaning. While it would be very rare for a comma to be misconstrued imagine the confusion an exclamation mark would cause.
Comment: My experience is that an equation earns its own line in a paper only when it is complicated or important enough to merit the additional space.


Consultar valores duplicados na mesma tabela

Question: Estou com dificuldades em fazer uma consulta para exibir valores duplicados na mesma tabela.
Tenho uma tabela de registro de medições elétricas com os seguintes campos:
ID_EQUIPAMENTO, DATA, HORA, FASE_A, FASE_B, FASE_C

Independente da DATA e HORA, preciso identificar registros iguais na FASE_A, FASE_B, FASE_C em equipamentos diferentes, salientando que são muitos equipamentos.
segue imagem pra ilustrar melhor:
Comment: Certo, e até agora, o que você já tentou ? Adicione o código na pergunta.
Answer: Acredito que isso deva ajudar. Eu teria sido mais específico se você tivesse fornecido mais informações. Basicamente o que você precisa é determinar um referencial referente aos registros não únicos que quer monitorar, e em uma sub-querie verifica-los através de um COUNT(), agrupando de maneira conveniente.
SELECT * FROM Tabela WHERE Referencial in
(SELECT Referencial FROM Tabela GROUP BY Referencial HAVING COUNT(*) > 1)

Comment: @RodriggoSantana, algo que pode ajudar é você criar um modelo do resultado esperado. Algo como o que foi feito [nesta pergunta](https://pt.stackoverflow.com/questions/345502/como-simular-as-fun%C3%A7%C3%B5es-lead-e-lag-mysql). Aguardo suas edições.
Comment: Entendi a consulta mas ainda não é isso, provavelmente não expressei minha duvida claramente, mesmo assim obrigado!
Answer: Levando em consideração suas informações (algumas superficiais) vou supor uma solução, acredito que já seja o necessário para o seu caso.
Você pode utilizar o HAVING onde você pode utilizar funções agregadas.
Segue um exemplo para você adequar e implementar para o seu problema:
Nesta tabela vamos imaginar que tenha somente os campos COD_PRODUTO e DESCRICAO e ainda que contenha registros duplicados ou triplicados ...
SELECT COD_PRODUTO, DESCRICAO FROM PRODUTOS
GROUP BY
    COD_PRODUTO, DESCRICAO
HAVING COUNT(*) > 1;

Caso tenha um produto que esteja "cadastrado" mais de uma vez no banco, ele será retornado nesta instrução acima.
Espero ter ajudado.


Como ocultar a metabox dos "Campos Personalizados" do Wordpress?

Question: criei implementei uma função no meu tema wordpress que salva a quantidade de vezes que um post foi visualizado, está funcionando como queria, porém quando vou editar o post esse campo personalizavél fica disponivél para ser alterado.
Meu objetivo é que não sejá possível ser alterado manualmente na edição do post:
inserir a descrição da imagem aqui
Segue a função que salva no banco:
<code>function setPostViews($postID)
{
    $countKey = 'post_views_count';
    $count = get_post_meta($postID, $countKey, true);
    if ($count == '') {
        $count = 0;
        delete_post_meta($postID, $countKey);
        add_post_meta($postID, $countKey, '0');
    } else {
        $count++;
        update_post_meta($postID, $countKey, $count);
    }
}
</code>
Answer: Ainda será possível manipular o valor através da requisição de criação ou edição do post, no entanto, visualmente, não será mais possível editar, a não ser que a pessoa modifique o css da página para exibir novamente o metabox
Esse snippet irá "esconder" com css essa box de edição dos postmeta:
<code>// Adiciona um estilo css inline no head da wpadmin pra esconder o postmeta metabox
add_action('admin_head', 'hide_postmeta_metabox');
function hide_postmeta_metabox() {
    // Variavel global da administração que diz em que página estamos.
    global $pagenow;

    // Verifica se estamos na página de edição de post ou criação de um novo post para não conflitar com nada administração
    if ( $pagenow == 'post.php' || $pagenow == 'post-new.php' ) {
        echo '<style>
        .postbox#postcustom {
            display: none;
        }
        </style>';
    }
}
</code>
Comment: Obrigado JassRiver, com base no que informou eu consegui adaptar para o meu caso. Como não queria esconder todos os campos alterei o if para esconder apenas o campo que não queria que fosse exibido para o usuario.                                                               if ( $pagenow == 'post.php' || $pagenow == 'post-new.php' ) {
        echo '';
    }


Integral of two terms involving Erf function

Question: I was solving another problem, and it remains to prove the following integral:
$$
\int_0^{\infty }\left(3{\exp \left(-2t \right)\over t}\operatorname{erf}^2(\sqrt t) -\frac{\sqrt\pi}2{\exp \left(-t \right)\over t^{3/2}}\operatorname{erf}^3(\sqrt t)\right)dt=\frac{\pi}4
$$
Can somebody give me a hint?
Thank you very much.
Best regards.
Comment: @KamalSaleh Ok. I have added a hyperlink.
Comment: [This representation for $\operatorname{erf}^2(\sqrt t)$](https://dlmf.nist.gov/7.7#E5) may be useful for attacking the first term in the integral
Comment: The integrand of the original volume integral is equal to $\nabla^2[-\tan^{-1}(r)/(2r)]$, where $r = \sqrt{x^2+y^2+z^2}$. Perhaps this could help?
Comment: What is that problem? We need to know your context so that the answers would satisfy you.
Comment: Okay, that is good. But how did that integral bring you to the one in the OP?
Comment: @KamalSaleh I multiplied by a constant $\frac4\pi$.
Answer: $$\left(\frac\pi4\text{erf}\left(\sqrt{t}\right)^4+\sqrt{\pi\over t}e^{-t} \text{erf}\left(\sqrt{t}\right)^3\right)'=3{\exp \left(-2t \right)\over t}\operatorname{erf}^2(\sqrt t) -\frac{\sqrt\pi}2{\exp \left(-t \right)\over t^{3/2}}\operatorname{erf}^3(\sqrt t)$$
Evaluating the limit
$$\lim_{t\to0}\frac\pi4\text{erf}\left(\sqrt{t}\right)^4+\sqrt{\pi\over t}e^{-t} \text{erf}\left(\sqrt{t}\right)^3=0+0=0$$
and$$\lim_{t\to\infty}\frac\pi4\text{erf}\left(\sqrt{t}\right)^4+\sqrt{\pi\over t}e^{-t} \text{erf}\left(\sqrt{t}\right)^3=\frac\pi4\times1^4+0\times1^3=\frac\pi4$$
So the integral is $\pi\over4$


Controller splitting ViewBag model into multiple pages with database parameters is skipping records

Question: Summary: Separating a list of Services into multiple pages by a page limit is losing a record in between the two pages.  The second page starts from the same ID regardless of change using Razor.  In other words, I need Page 2 to pick up where Page 1 ends.  This is probably a basic ASP.net issue.  The controller is breaking up the views wrong.
I have inherited a project, and am unable to find where the parameters are set for a View.  I am unable to determine which element is causing the problem and will need guidance as to what code specifically to include beyond what's included.  I will revise the question with the code or other specifics upon receiving comments in an effort to keep the question only as detailed as necessary.
update NOTE:  I have no folder named Controllers in the project.  References to the database are found in 'bin\work1.dll'
Expectation:
There are two Wall Displays, each with an internal webpage listing "Services", much like an airport terminal lists flight times.  The resolution on the screen is ideal for 5 Services.
There is a SQL table with parameters to define "WallSortBy" and amount of "ServicesPerPage".
By changing the value of ServicesPerPage from 6 to 5, "WallDisplay1" should display Services 1-5 and "WallDisplay2" 6-10, or if there are less than 10 total services, just 6-[Last Service].  If there are more than 10, after the "Countdown" reaches 60 seconds, the pages would cycle with Wall1[6-10], Wall2[11-15], and so on or something to that effect.
Problem:
Given 9 Total Services for example. (true with other totals as well)
When ServicesPerPage is changed from 6 to 5:
WallDisplay1 = [1 to 5]
WallDisplay2 = [7 to 9]

Service 6 is missing.
Set ServicesPerPage to ANYTHING:
WallDisplay1 = [1 to ANYTHING]
WallDisplay2 = [7 to 9]

Dashboard:
The Dashboard is working fine, using the same View layout as the Wall Displays for each "Service"
All 9 Records show there correctly.
WallDisplay1:

WallDisplay2:

I have searched through the entire project for hard coded 6's and 7's, and have found none.  I can't see any references to the SQL table that stores the parameters by the name of the table. (update: in the bin\work1.dll there are multiple references) .
The connection string in the web.config has the database, but the table name isn't anywhere I can find, in the entire project.  Neither is "ServicesPerPage", and the id for that parameter in the SQL table is a hash id.
The examples I've read on binding models don't have multiple pages split into separate web pages, usually the examples are using a navigator to display the pages from a single web page.
The ViewBag is sorted by "Location", meaning the location of the service not to be confused with the property "windows.location".
There are three Razor .vbhtml pages that use the ViewBag with the Service list:
Dashboard.vbhtml,
WallDisplay1.vbhtml,
WallDisplay2.vbhtml
Relevant Dashboard Code:
@ModelType IEnumerable(Of work1.Service)

@code
    ViewData("Title") = "Board"

    Dim lstServiceStatus As SelectList
    lstServiceStatus = New SelectList(ViewBag.lstServiceStatus, "Value", "Text", ViewBag.viewStatus)

     Dim SortBy As String = If(HttpContext.Current.Request.QueryString("SortBy") Is Nothing, "Location", _
                               HttpContext.Current.Request.QueryString("SortBy"))
     Dim viewStatus As String = If(HttpContext.Current.Request.QueryString("viewStatus") Is Nothing, "Active", _
                                  HttpContext.Current.Request.QueryString("viewStatus"))

End Code

            Sort by:
            @If ViewBag.sortby = "Date" Then
                @Html.ActionLink("Location", "Dashboard", New With {.SortBy = "Location", .viewStatus = viewStatus})
                @/ Date
            Else
                @Location /
                @Html.ActionLink("Date", "Dashboard", New With {.SortBy = "Date",.viewStatus=viewStatus})
            End If

            Status:
            @Html.DropDownList("selStatus", lstServiceStatus, New With {.onchange = "javascript:selectViewStatus(this);"})

    @For Each item In Model

The bulk of the formatting goes on, then the wrap up, saving the ID.  The other windows are called from this page, this is the end of it.
    function saveField(th, SrvId) {
        $.post("saveServiceField", {
            FieldName: th.id,
            Value: th.value,
            SrvId: SrvId
        }, function (data) { th.value = data; });
    }

    function selectViewStatus(th) {
        if (getquerystring()["SortBy"] != null) {
            window.location = "/Roster/Dashboard?SortBy=" + getquerystring()["SortBy"] + "&viewStatus=" + th.value;
        }
        else {
            window.location = "/Roster/Dashboard?viewStatus=" + th.value;
        }
    }

    function getquerystring() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
</script>

The WallDisplays are almost identical.
The difference between them here:
WallDisplay1:

            Sort by:
            @If ViewBag.sortby = "Date" Then
                @Html.ActionLink("Location", "WallDisplay", New With {.SrvId = Guid.Empty, .SortBy = "Location"})
                @/ Date
            Else
                @Location /
                @Html.ActionLink("Date", "WallDisplay", New With {.SrvId = Guid.Empty, .SortBy = "Date"})
            End If
            <input type="hidden" id="hSortBy" value="@ViewBag.SortBy" />
            <input type="hidden" id="hLastSrvId" value="@ViewBag.LastSrvId" />
            <input type="hidden" id="hRefreshTime" value="@ViewBag.RefreshTime" />
             Page @ViewData("currentpage") of @ViewData("totalpage") - Refresh in @ViewData("RefreshTime1")  Seconds

    @For Each item In Model

WallDisplay2:
  <input type="hidden" id="hSortBy" value="@ViewBag.SortBy" />
            <input type="hidden" id="hLastSrvId" value="@ViewBag.LastSrvId" />
            <input type="hidden" id="hRefreshTime" value="@ViewBag.RefreshTime" />

            Sort by:
            @If ViewBag.sortby = "Date" Then
                @Html.ActionLink("Location", "WallDisplay", New With {.SrvId = Guid.Empty, .SortBy = "Location"})
                @/ Date
            Else
                @Location /
                @Html.ActionLink("Date", "WallDisplay", New With {.SrvId = Guid.Empty, .SortBy = "Date"})
End If
           Page @ViewData("currentpage2") of @ViewData("totalpage2") - Refresh in @ViewData("RefreshTime2")  Seconds

@If  ViewData("requiredSecondScree")=False Then
    @All Services are on the first screen...
Else
      @
    For Each item In Model

update Note: All references to LastSrvId are shown in the code already posted.
Here are the scripts.

I will quickly update this question with any more relevant information or code upon request.
UPDATE:  Apologies for the abundance of code:
JScript1.js  The only instance I could find in the project of "loadWall" that isn't already shown above.
var wall1Object = null;

var screenRefresher = {
    wallObject: null,

    setWall1Object: function (obj) {
        this.wallObject = obj;
        alert(this.wallObject);
        wall1Object = obj;
    },

    getWall: function () {
        alert(wall1Object);
    },

    reloadWall1Object: function () {
        console.log(wall1Object);
        if (this.wallObject != null) {
            this.wallObject.location.reload();
            return true;
        }
    }
};
var setWall1Object = function (obj) {
    wall1Object = obj;
    alert(wall1Object);
};
var reloadWall1Object = function () {
    //    wall1Object.location.reload();
    alert(wall1Object);
};

Comment: What about your controller code?  I suspect your model isn't being populated correctly in your WallDisplay2.  What are you using a different action for that?
Comment: I suspect the controller as well, but since the project was inherited, I don't know where to find it.  There isn't a folder for controller in the project.  There is a view folder.  As far as wallDisplay 2, it has a separate url, I don't know if that's why it was designed that way.  All the code for those displays is listed, apart from the actual row formatting, columns etc.  I am new to asp.net as well,so this is difficult to find names, everything is set dynamically
Comment: The part I can't seem to figure out, is where in the code, does the parameter ServicesPerPage get passed to the controller.  If I could find that, I think I'd be able to sort it out.
Comment: Search the project for a "RosterController".  You could also search for "WallDisplay2". You've posted a good bit of code, but your issue is in the model being passed to that View from the controller, so that code is important. Other stuff...I see the "loadWall" javascript function, but don't see it used anywhere in the code you posted.  You also mention "ServicesPerPage", but no code posted references that.
Comment: ServicesPerPage is the parameter name in the database this is bound to.  Its in SQL.  I don't see any "select from dbo.DRParameters " , name of the table containing the parameter. Or any sign of where it's bound in code.  Even if it was bound using visual studio features, you'd think there would be some code generated.
Comment: Could be retrieved using a user function, stored proc, Entity Framework, or data access compiled into a DLL that you can't see. Just no way to tell without seeing the controller code.
Comment: Is is possible it's being controlled in a javascript or jquery?  The problem with finding it, from what I can see, is that ASP.NET is awesome and is capable of creating this code dynamically, so the variable names aren't unique.  If my logic could tell me, I'd say that WallDisplay1 is controlled using the parameter, and WallDisplay2 was added after the initial scope of the project required "6" ServicesPerPage.  The original designer might have just said, "we can just start Wall2 on record 7"
Comment: I found some references to the actual database table in the BIN folder, under Work1.dll, and work1.xml.  I'm looking deeper into that.
Answer: After long reading of your question i think this is cause of your problem if you can find this in your project you will see the controller code and also the logic of how pages are split based on this value.
@ViewBag.LastSrvId

Find ViewBag.LastSrvId in your project and you will get in controller code and there you can see the logic setting page number. I have seen your code and i can see that page is refreshed based on this viewbag value passed as query string to controller "Roster/WallDisplay2" and in this controller there would be all logic of how your pages will be shown.
Update
Your controller folder is not in the project it may be written separately and included in project as dll file that's why you are unable to locate Controller code and Controller folder.
Comment: I will look at that right now.  That was my first thought, but then I was lead to think it was what generates the URL, concatenated with the sort type.
Comment: Unfortunately, it looks like all references to that are as shown in WallDisplay1 & WallDisplay2.
Comment: Is it possible that the controller be located in the "\bin" folder?
Comment: Yes this is possible but if it was written separately in another project.
Comment: You are finding this in whole project ?
Comment: updated question with notes per discussion, and will look into the source code to make sure I'm not missing the controller.
Answer: From everything I have looked at, I really think your problem lies in the WallDisplay2 action in the Roster Controller.  Somewhere in there, it's pulling the data incorrectly based on your ServicesPerPage.
Your Controllers don't need to be in a "Controller" folder in order to work.  They could be in a DLL or another folder.  It just needs to be named something like this, which hoping that helps you to find it.
public class RosterController : Controller

The Action may not be WallDisplay1 or WallDisplay2 like what you're looking for.  You may find those used like this as well:
public ActionResult NewAction()
{
  return View("WallDisplay2");
}

Also, take a look at the value of @ViewBag.LastSrvId that gets written out to the following HTML field.  Make sure that changes when you update your "ServicesPerPage" and reload from the Dashboard.  If it's the same, then it's possible that value isn't being calculated using the "ServicesPerPage".
<input type="hidden" id="hLastSrvId" value="@ViewBag.LastSrvId" />

Lastly, if you're finding your DB access code in a DLL and the Controller in a DLL without the source code, you may be better off just rewriting the code to implement paging so it works correctly if more services get added.  Keying off last LastSrvId will end up causing the same issue when you reload WallDisplay2 and a service has been added to your previous page depending on the sort.
Comment: Rewriting it would be a good option, but the client wants it only modified.  Tracking down the project source code is the way I have to go.


Sync user roles across websites

Question: I am using Drupal 7. I want to sync my Drupal website roles on 2 websites on the same top level domain, as in, one is example.com, the other is other.example.com, how can i achieve this? Bakery module does not seem to share user roles, and i want to avoid sharing databases across my sites since it works but not recommended.
Basically, i want to reduce loading time on my main site and push my payment system (which contains many modules) to a new Drupal install so that when the payment is made on the slave site, the user role is updated on the slave site which is in turn captured on the main site. How can i achieve this?
Answer: i cannot provide detailed steps to achieve this but there are various alternatives Comparison of Single Sign On (SSO) Modules to the bakery module you mentioned that are capable of sharing users. although you might want to just create those roles via a feature, depending on what you mean by

sync my drupal website roles.

Services
i18n_sso
Domainaccess
CAS
account_sync
simplesamlphp_auth
shib_auth
Omniauth https://drupal.org/node/2177681
Oauth Connector
Bakery 3.x current development effort suggest it might soon support exporting roles in 3.x if you are a developer you can look there. i believe issue 556666 was committed to 2.x already aswell
Comment: in that case you might want to consider using https://drupal.org/project/role_export with features for ensuring the roles are the same accross sites
Comment: by "sync my drupal website roles" i mean that the "roles" table on site B (siteb.domain.com) is the same "roles" table being used by site A (www.domain.com)
Answer: Typically when staging roles on D7 across multiple environments or sites is tricky since roles are referenced using rid, we solved this by using this module since it exports your role definitions and maintain the assigned permissions which can be painful to achieve. Since your sites are "clones" this should work perfectly.
Even though what you want is to sync the table like so, perhaps you can opt for a database focused approach like described here and here depending on your server configuration.

Sync user roles across websites


mysql multiple conditions in if statement

Question: New to mysql, so I am not sure I am even asking the question correctly. I am trying to add multiple parameters to an if statement. I am trying to check if a game between two teams was a league match.
SELECT visitor AS school, home AS temp, vl.leagueid AS vleague, hl.leagueid AS hleague,
if(vl.leagueid = hl.leagueid, 1, 0) AS leaguematch
FROM schedule
LEFT JOIN schools AS vl ON vl.id = visitor
LEFT JOIN schools AS hl ON hl.id = home
WHERE gamedate between '2013-01-01' AND '2013-12-31'

To the check if leagueid's are equal I want to add ((vl.leagueid = 26 AND hl.leagueid = 27) OR (vl.leagueid = 27 AND hl.leagueid = 26)). No combinations of () that I have tried seems to work, so I get the feeling I am going about this wrong.
Thanks,
Mike
Thanks to chofer, here is my working query
SELECT visitor AS school, home AS temp, vl.leagueid AS vleague, hl.leagueid AS hleague,
CASE
    WHEN vl.leagueid = hl.leagueid THEN '1'
    WHEN ((vl.leagueid = 26 AND hl.leagueid = 27) OR (vl.leagueid = 27 AND hl.leagueid = 26)) THEN '1'
    ELSE 0
END AS leaguematch

FROM u96nk_rvball_schedule
LEFT JOIN u96nk_rvball_schools AS vl ON vl.id = visitor
LEFT JOIN u96nk_rvball_schools AS hl ON hl.id = home
WHERE gamedate between '2013-01-01' AND '2013-12-31'

Answer: if you need vl.leagueid and hl.leagueid are equal put the condition on where, like this
WHERE gamedate between '2013-01-01' AND '2013-12-31'
      AND vl.leagueid = hl.leagueid
EDIT
 If you want to set leaguematch to specific value if the conditions are met, 0 if they are not CASE would be the best option
SELECT visitor AS school,
       home AS temp,
       vl.leagueid AS vleague,
       hl.leagueid AS hleague,
       CASE
          WHEN school = 50 AND temp = 2 THEN '1'
          WHEN school = 51 AND temp = 3 THEN '2'
          ELSE 0
       END AS leaguematch
FROM ......

I
Comment: Sorry, probably didn't explain well enough - bad habit - I want to set leaguematch to 1 if the conditions are met, 0 if they are not. So I would a record that would end up looking like this
    school = 50 temp = 2 vleague = 25 hleague = 25 leaguematch = 1
Comment: Look at the edit, I think a CASE statement would be good for you.