The elements of $[0,1]$ cannot be put in an array,(sequence?). Proof.

Question: The answer is given I will highlights the deduction which I don't understand:
Let's suppose the opposite:
$$a_1=0,a_{11},a_{12},a_{13}... \\ a_2=0,a_{21},a_{22},a_{23}... \\ ....$$
Lets look at the element $a^*=0.a_{11}^*a_{22}^*a_{33}^*...$ such that $a_{ii}^*=\begin{cases}0 ,a_{ii}=1 \\ 1, a_{ii}\neq1 \end{cases}$
Then $a* \in [0,1]$
The following steps are what I don't understand:

$$\implies (\exists n) a_n=a_{i}^* \\ a_{ni}=a_{ii}^* \\ a_{nn}=a_{nn}^*$$

Then the proof concludes:
If $a_{nn}=1 \implies a_{nn}^*=0 \ a_{nn}\neq a_{nn}^*$ basically same analogy with $a_{nn}\neq 1$$\implies a_n \neq a_n^*$  contradiction.
Comment: I highlighted it in the yellow box. From $\exists n $ and so on... the detals there are unclear as to why..
Answer: The number $a^*$ is in $[0,1]$ so it must appear in the listing somewhere. That is, there is some $n$ such that $a^* = a_n$.
Now, consider the $i$th digit of that number, for arbitrary $i$. $a^*_{ii}$ is that $i$th digit. That is also $a_{ni}$ because $a^* = a_n$. Therefore $a^*_{ii} = a_{ni}$.
Finally, specialise to $i=n$. Obtain $a^*_{nn} = a_{nn}$, which contradicts the definition of the $^*$ operation.


Listar grupos local do windows com forms c#

Question: Boas users!
Estou tentando listar todos os grupos local do windows com o forms c#, mas não obtive sucesso.
quero listar os grupos e a partir daí selecionar e incluir na criação do usuário.
desde já agradeço.
Comment: Se não tem o código, como disse no tópico que está tentando mas não obteve sucesso?
Comment: Pode compartilhar o código que usou pra tentar listar? Ficará mais fácil ajudar! :)
Comment: @GeorgeWurthmann Na verdade não tenho Código montado ainda, eu estou criando um programinha para criação de usuários local do windows, e queria achar um jeito de listar os grupos existente no computador para a pessoa selecionar e quando criar, já colocar esse usuario nos grupos selecionado.
Comment: Na verdade eu fiz um codigo de criacao de usuarios, e queria um jeito de puxar os grupos jogar em uma checkedListBox e dar a opcao de selecionar e ja criar esse usuario nos grupos selecionados.
Answer: Para grupos locais talvez isto seja o suficiente:
using System.DirectoryServices;

DirectoryEntry machine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",Computer");

if (machine.Children != null)
{
    var results = machine.Children.Cast<DirectoryEntry>().Where(r => r.SchemaClassName == "Group").OrderBy(r => r.Name);

    foreach (DirectoryEntry child in results)
        Debug.Print(child.Name);
}

Para algo mais abrangente, por exemplo todo o domínio:
using System.DirectoryServices.AccountManagement;

PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);

var results = srch.FindAll().Where(r => r.StructuralObjectClass == "group").OrderBy(r => r.Name);

// encontrar todos os resultados
foreach (var found in results)
    Debug.Print(found.Name);

Aplicação prática de ambos os códigos:

Exemplo 1
using System;
using System.Windows.Forms;
using System.DirectoryServices;
using System.Linq;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DirectoryEntry machine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",Computer");

            if (machine.Children != null)
            {
                var results = machine.Children.Cast<DirectoryEntry>().Where(r => r.SchemaClassName == "Group").OrderBy(r => r.Name);

                label1.Text = string.Format(@"{0:#,##0} grupos", results.Count());

                foreach (DirectoryEntry child in results)
                    checkedListBox1.Items.Add(child.Name);
            }
        }
    }
}

Exemplo 2
using System;
using System.Windows.Forms;
using System.DirectoryServices.AccountManagement;
using System.Linq;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
            GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
            PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);

            var results = srch.FindAll().Where(r => r.StructuralObjectClass == "group").OrderBy(r => r.Name);

            label1.Text = string.Format(@"{0:#,##0} grupos", results.Count());

            // encontrar todos os resultados
            foreach (var found in results)
                checkedListBox1.Items.Add(found.Name);
        }
    }
}

Comment: Opa cara, blz!
esse segundo código eu consegui ter retorno com um MessageBox e ele me retornou varias coisas, o primeiro nao fiz funcionar, em casa vou olhar com calma. meu Muito obrigado! vc ja me deu uma luz.
Comment: Minha ideia é jogar em uma checkedListBox.
Comment: O 1º código seria o mais indicado. Mas qual o erro que lhe dá no 1º código?
Comment: na verdade eu não soube fazer ele retorna algo, eu não tenho experiencia.
Qual o Código que coloco aqui para postar o código?
Comment: Resposta editada com exemplos funcionais!
Comment: Show!  Agora funcionou aqui!
@João Martins
Comment: Perfeito! Marque a resposta como correta e dê um UP! :)


Open Shortcut in new browser window

Question: drupal 7.61 adminimal_menu
I need to have two shortcuts on the shortcut bar open in a new browser window instead of the default same window without having to "right-click".
Users are sometimes forgetting to right click
Answer: You cann't set/configure it from admin panel (admin/config/user-interface/shortcut/link) because there are no option in Shortcut module configuration.
Now you can use any one of following modules:
https://www.drupal.org/project/menu_attributes
https://www.drupal.org/project/extlink
or following jQuery script to your page.tpl.php
<code>$(document).ready(function(){
$('#id').children(":first").attr("target", "_blank");
});
</code>

Open Shortcut in new browser window


Cannot return from outside a function or method?

Question: While developing a web application I want to perform certain validation check and only after sucesssful validation I need to post the form and redirect control to next page.
JavaScript code:
function fnCheckEmptyField()
{
    var strDomain = document.getElementsByName("txtIIDN").value;
    if (strDomain == null)
    {
        document.getElementById("lblValidityStatus").innerHTML = "";
        document.getElementById("lblValidityStatus").innerHTML = "Domain Name Field Can't be Left Blank";
        return false;
    }
    else
    {
        return true;
    }
}

Relevant HTML code:
<form action="Result.jsp" name="validityCheck" onsubmit="return fnCheckEmptyField()">
    <input type="text" id="txtIIDN"/>
    <input type="submit" id="btnValidityCheck" value="Check Validity" />
</form>

The line onsubmit="return fnCheckEmptyField()" shows an error Cannot return from outside a function or method and after execution of the JavaScript function form is getting submitted regardless the text field is blank or not.
I have placed alerts inside if condition and it is sure that if field is empty function returns false.
I don't know what's wrong with my code and why this errors with Cannot return from outside a function or method.
What's the cause and how can I solve it?
Answer:
the line onsubmit="return fnCheckEmptyField()" showing an error Cannot return from outside a function or method

That's specific to Eclipse. Eclipse is wrong here, that line is perfectly fine. Just ignore  the Eclipse error. If you want, you can always disable its JS validation.

and after execution of the java script function form is getting submitted regardless the text field is blank or not.

That's because your JavaScript function is wrong. You've 2 mistakes in your JS code.

The getElementsByName() call is incorrect.
var strDomain = document.getElementsByName("txtIIDN").value;

To retrieve an element by ID, you need getElementById().
var strDomain = document.getElementById("txtIIDN").value;

Empty values are not null, but just empty string.
if (strDomain == null)

You need to check its length instead.
if (strDomain.length == 0)

Or just make use of JS boolean magic.
if (!strDomain)

By the way, the line document.getElementById("lblValidityStatus").innerHTML = ""; is unnecessary in this code.
Comment: Good explanation. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=353209 for related bug.
Answer: remove the "return" from onsubmit attribut
your code should look like this
<form action="Result.jsp" name="validityCheck" onsubmit="fnCheckEmptyField()">

<input type="text" id="txtIIDN"/>
</form>

hope this solve your problem :-)
Comment: return is required since we expect the method defined in "onsubmit" is doing a validation and submit the form only if this method returns true.
Answer: Also,
var strDomain= document.getElementsByName("txtIIDN").value;

should be
var strDomain= document.getElementById("txtIIDN").value;

The text field has an id, not a name
Answer: I'm no javascript expert but I think you should lose the return keyword in your onsubmit parameter in the HTML; like below:
onsubmit="fnCheckEmptyField()"

edit: sorry was posting concurrently with previous answer
Answer: Remove Action from Form Tag.
function fnCheckEmptyField()
{
   var strDomain= document.getElementsByName("txtIIDN").value;
   if(strDomain == null)
   {
      document.getElementById("lblValidityStatus").innerHTML="";
      document.getElementById("lblValidityStatus").innerHTML="Domain Name Field Can't be Left Blank";
   }
   else
   {
      window.navigate("top.jsp");
   }
}


Unable to write CSR generated using org.bouncycastle.asn1.pkcs.CertificationRequest in PEM file format


Bayesian lognormal model: how to correctly back-transform the estimates?

Question: I have a Bayesian model of the form:
$$
\begin{align}
y & \sim logNormal(\mu, \sigma)\\
\mu_n & = \alpha + \beta_0  c_n + \beta_1  d_n + \beta_2  c_n  d_n
\end{align}
$$
Where:

$y$ is a variable measured in ms
$c$ is a sum-contrast coded variable equal to 1 or -1.
$d$ is a scaled and centered continuous variable

This omits assumed prior distributions, and slope and intercept adjustments, I believe they are not important with respect to the main point.
Since the likelihood is logNormal the results are on the log scale.
I want to back-transform the estimates from the model and compute the effect sizes of different variables. I think I know how to do this for $c$:
$$
\mu|_{c=1} - \mu|_{c=-1} = \exp (\alpha + \beta_0 + \beta_1  d_n + \beta_2 d_n ) - \exp (\alpha - \beta_0 + \beta_1  d_n - \beta_2 d_n )
$$
For interaction this is slightly more complicated. Let the interaction effect be:
$IE = \frac{\partial \mu}{\partial d}|_{c = 1} - \frac{\partial \mu}{\partial d}|_{c = -1}$. I remove the log by exponentiation and then I take the derivative which results in:
$$
\frac{\partial \mu}{\partial d} = \exp (\alpha + \beta_0  c_n + \beta_1  d_n + \beta_2  c_n  d_n ) (\beta_1 + \beta_2  c_n)
$$
So the interaction effect is the difference of these two terms:
$$
\begin{align}
\frac{\partial \mu}{\partial d}|_{c = 1} = & \exp (\alpha + \beta_0  + \beta_1  d_n + \beta_2  d_n ) (\beta_1 + \beta_2) \\
\frac{\partial \mu}{\partial d}|_{c = -1} = & \exp (\alpha - \beta_0  + \beta_1  d_n - \beta_2  d_n ) (\beta_1 - \beta_2) \\
\end{align}
$$
My questions are:

Are the derivations for the interaction effect and the effect of $c$ correct?
If yes, this means that these effects are functions of $d$, but fitting the model returns the effects (on the log scale) as constants. Where does this difference come from?
How do I derive and interpret the effect for $d$? Ie. what are the meaningful points at which to evaluate the function $\mu$? Or maybe is there a better way of doing this?
Comment: Small nitpick on notation. Shouldn't it be (for example) $\partial \mu / \partial d$ instead of $\partial y / \partial d$? $y$ is a random variable, so it does not immediately make sense to take its derivative. Similarly, should $y |_{c=1}$ instead be $\mu |_{c = 1}$?
Comment: @stats_model Yes, I think you're right. Thanks, I'll correct it.
Answer: The effect size of a log-normal model has not a univoque value on the same scale of y, because of the log-relation between $\mu$ and the position of the log-normal distribution (its median, its mean). When changing a covariate, the model predictions move linearly with the covariate on the log scale, not on the original scale, so on the log scale there is a constant effect size, while on the original scale there is not, it varies.
The effect sizes you already have are good as they are, you can't "back-transform" them without making a mess of them. Although you may make a simple exponentiation of the betas. This is called "time ratio" in AFT models, and expresses the proportion between the predicted value for two observations with unit variation in the corresponding  covariate (the proportion, because the difference varies!).
Comment: likelihood and link functions are not the same thing, link functions really apply only to GLMs, and this is not a GLM, but I used the term hoping it would make things clearer. You are also right about the fact that $\mu$ here is equal to the linear predictor, not a transformation (so we may say link function is identity). What I intended is that the position of the predictive distribution (its median, its expected value) vary with the exponential of the linear predictor.
Comment: Thanks, I think I understood what you meant but wanted to be sure. I'll accept (and award you the bounty) if no other answers appear in the next few days.
Comment: Thanks for answering this is helpful. One question/remark though: is this correct to call the likelihood here a "link function"? I thought the link would be eg. $f$ if the model was specified like $f(\mu) = \ldots$. Even more in the brms package it's explicitly stated that the link for lognormal is "identity".
Comment: I edited the answer


Self Organizing Map and input normalizing

Question: I've been playing around with self organizing maps (SOM) recently.
I tried to implement a simple example. You can see the training implementation function gist here and full contained SOM example here.
There is something strange I'm noticing and I'm not really sure why it's happening. I'm using the iris data set to both train and validate the SOM parameters. Iris data set contains data for 3 different kinds of flowers i.e. it contains 3 different groups/clusters of data.
Once I have trained the SOM I should be able to validate using the trained parameters that the Iris data really does cluster to three groups - each per flower type.
However I'm seeing something strange when validating the SOM parameters. When I normalize the input data and then try to verify/validate the trained SOM parameters using the original non-normalized iris data, the validation data seem to cluster into the same best matching unit (BMU). That is, if I normalize the input for learning and don't normalize the data for validation, I get one cluster classification instead of expected three.
However when I normalize both the input and the validation data set (like I said validation data is the same data set as the one used for training the SOM - iris data set), I do get the expected result - i.e. the data does cluster into 3 [clearly identifiable] clusters.
Equally, when I don't normalize either of the data sets I get the expected validation results.
So my question is, what would be the potential cause of the first case be: ie. training the model on normalized data and getting incorrect results when validating the model using the exact same data as validation data, but not non-normalized.
I would expect that normalizing the data to train the SOM model should have no effect on validation i.e. that once you have the model parameters, you should be able to classify non-normalized data.
I'm guessing that this could be because of using the same data set for training and validation?
Comment: You need to make this self-contained. People aren't going to want to navigate elsewhere and read a lot of stuff to answer your question for you. In addition, are you just asking for code check? That would be off topic here, but can be on topic on the [codereview.SE] site.
Comment: thanks, I've modified the question. I hope it's better now :-/
Answer: A common way to normalize a SOM is to scale features to unit variance. The mean is subtracted from each observation and divided by the standard deviation, which is in the range [0, 1].
If you normalize the training set, but not the validation set, then you are likely comparing observations on different scales. I'd suggest using the mean and stds of the training set to normalize the validation set.
Comment: Yeah… If a feature is in the range [99, 100] and you normalize it to be [0, 1] for training, but query the model with data that hasn't been normalized, all the data will just go into the bin with the value closest to 99. Is this what's happening?


Complex Analysis - Bruce P . Palka - Ex: 4.12

Question: Please help me with this question. I tried to prove the HINT. But I have no idea how to solve this.
Question :
Knowing that  $ Re(z)>0 $ , demonstrate that $|z+\sqrt{z^2-1}|\geqslant 1$, with equality holding only when z is a real number in the interval $(0,1]$. ( Hint : First check that $Re(\bar{z}\sqrt{z^2-1})\geqslant 0$ for every $z$ under consideration.
I proved that $|z+\sqrt{z^2-1}|^2\geqslant 1+Re(\bar{z}\sqrt{z^2-1})$ . But I can not prove the HINT.
Comment: What branch of $\sqrt{z^2-1}$ is used?
Comment: The product of the two branches is $1$. This means that your inequality is true for one of the branches and false for the other.
Comment: This is the exact question from the book. So I had the same question too.
Comment: There are two 'standard' branches for $z \mapsto \sqrt{z^2-1}$: One with branch cut $(-\infty,-1] \cup [1,\infty)$ and another $[-1,1]$.  In either case, there needs to be more restrictions than just $\operatorname{re} z >0$.
Answer: Let's show $\text {Re}\,\bar z (z^2-1)^{1/2}\ge 0,$ where throughout I use the principal branches of $\arg z, z^{1/2}.$ This is obviously true if $z=1,$ so below I'll assume $z\ne 1.$
Fact: If $0 \le \arg w < \pi,$ then $\arg (w-1) \ge \arg w.$ Hopefully that's clear from the geometry. Suppose now $\text {Re}\, z > 0$ and $0\le\arg z < \pi/2.$ Then $\arg z^2 = 2 \arg z.$ Thus $\arg (z^2-1) \ge \arg z^2 = 2\arg z.$ Taking square roots gives $\arg (z^2-1)^{1/2} \ge \arg z.$ Since $\arg \bar z = -\arg z,$ we have $\arg \bar z (z^2-1)^{1/2}\ge 0,$ hence $\text {Re}\,\bar z (z^2-1)^{1/2}\ge 0.$ That takes care of the first quadrant; the proof for the fouth quadrant is similar.


Install module that requires composer on server with only FTP

Question: I am working on website that only has restricted ftp access. Ya, no way around it.
I want to install the module PHPmailer, which uses composer to install libraries.
I have a local composer run dev site, from which I installed properly, then moved the module dir, and composer.json, composer.lock to the server, but when installing the module on the server I get the error
Please install the PHPMailer library by executing 'composer update' in your site's root directory. (Currently using PHPMailer library version Missing).
Does composer update the database or what is going on here?
How can I easily install a module that made it self dependant on composer?
Comment: Composer doesn't update the database. It just updates its files.
Answer: That error message is called from the modules install file.  It's checking to see if the PHPMailer class exists, and if not, let's you know the library needs to be installed before you can install the module.
If you successfully installed the module on your local dev site, then Composer downloaded the PHPMailer library to the root 'vendor' folder.  In the 'vendor' folder there should be a 'phpmailer' folder.  You just need to copy this folder over to your website's server (to it's root 'vender' folder) and then you should be able to install the module.
Comment: Thanks! Just moving the phpmailer dir didnt work, I noticed there are references to the new module in other files inside vender so i synced the whole vender dir, and it works.
Comment: Yeah you'll need to sync all of phpmailer's dependencies too. If you're forced into this workflow, syncing the whole vendor folder is probably the way to go


Error because of private access in the autoload_static class of Composer

Question: I am currently working on a Laravel 5.4 project. I am using PHPStorm.
Out of nowhere, today I had this error in the class autoload_static.php which is in project/vendor/composer:
   public static function getInitializer(ClassLoader $loader)
    {
        return \Closure::bind(function () use ($loader) {
            $loader->prefixLengthsPsr4 = ComposerStaticInit3a641324e203eb2b3307dce659628bd1::$prefixLengthsPsr4;
            $loader->prefixDirsPsr4 = ComposerStaticInit3a641324e203eb2b3307dce659628bd1::$prefixDirsPsr4;
            $loader->prefixesPsr0 = ComposerStaticInit3a641324e203eb2b3307dce659628bd1::$prefixesPsr0;
            $loader->classMap = ComposerStaticInit3a641324e203eb2b3307dce659628bd1::$classMap;

        }, null, ClassLoader::class);
    }

There is a red line under each $loader->variable that says that it is private and therefore not accesible. Fair enough, I went to the declaration of ClassLoader in the same folder which is where this $loader object comes from and they are indeed private.
I never change anything in the vendor folder. Everything work just fine. I wonder if anyone knows why this is happening and if I should change them from private to protected to stop getting the error, or if it will break anything.
Answer: Nothing will break, it seems. Somebody asked the same question on Github before.
Hope this helps.


Azure Bastion - Troubleshooting Connection Issues

Question:
The target machine is either currently unreachable or username/password is not correct. Please re-verify your credentials. If the problem persists please contact support.

Can anyone solve this problem?
Comment: This is not a programming question, so you're in the wrong place. And if it persists, they are asking you to contact support...
Comment: I'm voting to close this question because it's a cloud service connection issue
Answer: Please make sure you are using the correct credentials to connect to the vm and also try to reset the password from the azure portal and try connecting.
if the problem persists please submit a support ticket from azure portal>>help+support section.


slant height and surface area of oblique prisms

Question: I am guessing that the slant height of an oblique prism is defined as the length of each segment connecting corresponding points of the two bases rather than the distance up the middle of any of the lateral faces, since all 3 pairs of lateral faces can be different in a parallelepiped.  Is this correct?
I realized that an oblique prism can either slant in only one direction (so its faces include 2 parallelograms and 4 rectangles, as in the picture) or slant in both directions (a parallelepiped with 6 parallelograms as faces).  Is there a formula for the surface area that always applies in the first case?  I'm guessing that for the surface area of a parallelepiped one has to calculate the area of each parallelogram separately and add them together since the 6 parallelograms are not guaranteed to all be congruent.
Answer: I believe the lengths of the segments connecting the corresponding points would be the "lateral edges."
I don't think the term "slant height" could apply here since the sides are not triangles, but the dimension that would correspond to slant height of a pyramid would, I believe, be the height of each of the parallelogram faces (which, as you say, can be different from each other in an oblique prism).


If $B^{m\times m}$ is positive semidefinite, is $A^TBA$ is positive semidefinite?

Question: If $B^{m\times m}$ is positive semidefinite, is it true that $A^TBA$ is positive semidefinite with $A^{m\times n}$? I think it is, because all of my counterexamples have failed, but I don't know how to prove it. I know that $x^TBx\ge 0$ if B is positive semidefinite. Is this the same? Do I need to prove it or is it well-known?
Comment: As the comment above states, whether the property used is a definition or a theorem about psd matrices depends on your definition. But it is well known, and [very often used as definition](https://en.wikipedia.org/wiki/Definite_symmetric_matrix#Definitions_for_real_matrices).
Comment: Gotcha, thanks! I was somehow thinking that there was a matrix version of that, e.g. $A$ serves the function of $x$ in $A^TBA$, but I guess your answer makes much more sense.
Comment: The level of detail you'd need to give in a proof of this result definitely depends upon the definition of "positive semidefinite," and there are a number of definitions floating around (all equivalent, but maybe you'd want to only use one and not the others, depending on your audience). The "if" property you recite involving $B$ is an "if and only if" and often the definition. As the answer below explains carefully, it solves the problem.
Comment: Another characterization of positive semidefiniteness of a square matrix is the existence of the factorization of the form $X^T X$. You can see how this would lead to another proof of the result.
Answer: First, note that $M := A^\top B A$ is an $n$-by-$n$ square matrix, and further it is symmetric:
$$
M^\top = (A^\top B A)^\top = A^\top B^\top A = A^\top B A = M
$$
since $B$ is symmetric. Now, indeed, a (real) symmetric $n$-by-$n$ matrix $M$ is psd if, and only if, $x^\top M x \geq 0$ for every $x\in\mathbb{R}^n$. In our case, we can check that, for every $x\in\mathbb{R}^n$,
$$
x^\top M x = x^\top A^\top B A x = (Ax)^\top B (Ax) \geq 0
$$
since $Ax\in\mathbb{R}^m$ and $B$ itself is psd, so $y^\top B y \geq 0$ for every $y\in \mathbb{R}^m$.


Going to lighter string gauge and bending in tune

Question: I usually play on electric guitar with strings that are marked as '10 in gauge. I learned to play bends in tune (most of the time) and recently I bought a new (electric) guitar that's also set up to '10.
I'm thinking about switching to '9 (only on that new guitar, I'd still practice on my '10 for part of the time) and giving the guitar a proper setup. I'm not sure how changing the tension of the strings will affect my ability to bend in tune.
The reason for this is to be able to play faster, facilitate the legato, play bends easier & not hurt my fingers when playing for a while.
I learned to bend mostly by muscle memory (with tuner), but I also hear when I'm out of tune.
Does anybody have any experience in this matter? Is there anything else I should be aware of when I switch to lighter gauge? I'm worrying that this could require me to completely relearn the technique, so I hope you can share your observations. Thank you kindly.
Comment: @piiperiReinstateMonica - I thought people question and ridicule Autotune all the time.
Comment: @piiperiReinstateMonica - I know what you're saying, and recording time was never cheap, even back in the '60s. But it seems sad that untalent can be made to sound good. Technology to the rescue, so that second rate stuff can be made to sound good. The upshot of this has become 'don't bother getting it good, wasting time practising, it will be faked anyhow'. That 10,000 hrs could come down to 'give us half an hour, and I'll be ready enough...' Just goes against the grain!
Comment: I know this is a completely heretic idea, but ... metal bands use sample triggers in drums and quantize it to grid in protools for their records, so why don't guitarists use pitch correction? It works great. Singers use pitch correction and nobody questions it. People use _harmonizer_ pedals for guitar. Virtual guitars, guitar synths, MIDI guitars... Play an electric guitar and have all sorts of sounds come out. A simple effect could set your bends in tune. :)
Comment: @Dekkadeci Maybe if it's used on extreme settings, producing the infamous "Cher effect". When it's used at moderate speed and tolerance settings, nobody notices anything. I think its use is completely accepted in music production. Just autotune and get your stuff in tune immediately, get the project going. But try it in a guitar solo!
Comment: @piiperiReinstateMonica - Needing to use autotune, how could someone even call themselves a singer?Surely being *in tune* is the basic premise of being a vocalist.
Comment: @Tim It's like, if you have a good feeling throughout the take, but a few places out of tune, so re-take the whole thing countless times, trying to reach the good feeling AND in tune? Or just use autotune? The end result will be the same, nobody can tell a difference, only with autotune you spent 99% less time. Everything is virtualized make-believe... sampled and programmed drums sounding like a million dollar studio, virtual acoustics, virtual amps, hollywood string sections, multi-tracked, quantized ... Maybe a drop of reality makes a difference in the ocean of faking, I don't know.
Answer: There's little difference, and always the possibility that the two guitars aren't the same scale length exactly anyway. You won't have to bend quite so much to get the same semitone/tone bend, and using ears is really the only way to accomplish this properly. Imagine being on stage and relying on a tuner?!
Vibrato will be slightly easier, but be careful not to fret too hard, as .009s will go sharper more easily than .010s.
If you were going to .008s or .007s, then there would be some concerns, but you'll be surprised at how quickly you adapt to such a small change.
Comment: I used tuner to start, I didn't want to be too much off the desired pitch. When I improvise/play some artists solo I rely on ears and muscle memory, so you're completely right. Thank you for your insight, it's really helpful!
Answer: Be aware that lighter strings are easier to bend when you want to, but they are also easier to bend unintentionally and get some notes a bit sharp just because they are harder to finger.
Lighter strings also easier get out of tune (esp. by bending).
Comment: Having used .008s for 40+ yrs, I dispute the last statement. And the first is open to question.
Comment: @Tim - I think they are saying the same thing you put in your second sentence in your answer


how to define node_acl public accessible resources

Question: guys am having a hard time wiht node_Acl.
i have adedd.
acl.allow('guest',['/docs/'],['show']);

app.use(acl.middleware);

but its shows me User is not authorized. when accessing
acl.addUserRoles('api_user', 'business',function(err) {

  if(!err) {
    log.debug("api_user with business role created");
  }
});

acl.addUserRoles('helpdesk', 'helpdesk',function(err) {

  if(!err) {
    log.debug("helpdesk with helpdesk role created");
  }
});

acl.userRoles( 'admin', function(err, roles) {
log.debug(roles);
});

acl.roleUsers( 'business', function(err, users){

  log.debug(users);
});

acl.hasRole( 'admin', 'business', function(err, hasRole) {
log.debug("admin user hasRole business =>"+hasRole);
});

acl.allow('admin', ['/api/hellobill/v1/hello'], ['get'], function(err) {
  console.log("EROOR"+err);
});

acl.allow([
        {
            roles: ['guest'],
            allows: [
                { resources: '/docs/', permissions: 'get' }
            ],
        }
    ]);

acl.allow('guest', '/docs/', ['get','put', 'delete']);

app.get('/docs/', acl.middleware(), function (req, res) {
        console.log(req);
    });

acl.allow('public', ['/', '/docs/', '/api-docs/'], 'view');

acl.whatResources('public',function(err,resources){
      console.log(resources);
 })

Answer: I can't be certain without seeing the rest of your code, but I'm going to guess that the user in question has not been granted the 'guest' role, or else there is no active user when you hit that resource. As far as I can tell, with that library you have to explicitly grant any roles you refer to, there's no magic in the role names that imply behavior.
So at some point you'd have to do acl.addUserRoles(theUser, "guest") for it to work.
If you want a resource that is simply not protected, truly public, then I would recommend only mounting the middleware on the routes that should be protected, eg:
app.use('/private', acl.middleware())
/* Update */
OK, and what user is trying to access the resource and getting the error?
I don't think it's related, but you also don't need the slashes in your resource. So you can do acl.allow('guest', 'docs', ['get','put', 'delete']);
Comment: Thanks for the edits; I can never get formatting to work right from my iphone.
Comment: btw am using swagger middleware ?


The curious case of a Drupal Button

Question: The code below is used to get the word count of a field (field_body) using ajax callback. It works great and everything functions as it should, well almost.
For some reason, the click of a button is also calling the default node form submit action.
So what happens is after I update count, and suppose I don't save the content. In fact, just go to another page or refresh the page, I get something like
Categories is required
Tags is required
Thumbnail is required....
Basically whatever I would get on form validation. It's just that the result is delayed as I am using ajax.
The problem is not with ajax, because even I comment the callback, and I click the button it tries to submit the form, when clearly it should not as executes submit callback is False.
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form' || $form_id == 'q_and_a_node_form' ) {

    $form['get_word_count'] = array(
     '#type' => 'button',
     '#value' => t('Update Count'),
     '#weight' => 5,
     '#executes_submit_callback' => FALSE,
     '#ajax' => array(
      'callback' => 'count_words',
      ),
    );

    $form['body_words'] = array(
     '#title' => t('Words in Body'),
     '#type' => 'textfield',
     '#disabled' => TRUE,
     '#weight' => 5,
     '#prefix' => '
',
     '#suffix' => '
',
    );
   $form['field_length_type']['#prefix'] = '
';
    $form['field_length_type']['#suffix'] = '
';
  }
}

function count_words($form, $form_state) {
  $str = $form['field_body']['und'][0]['value']['#value'];
  $count = preg_match_all("/\S+/", preg_replace('/(' . chr(160) .'| )/', ' ', strip_tags(str_replace('><', '> <', trim($str)))), $matches);
  $form['body_words']['#value'] = $count;
  if ($count < 500) {
    $form['field_length_type']['und']['#value'] = "short";
  }
  else if ($count > 500 && $count < 800 ) {
    $form['field_length_type']['und']['#value'] = "medium";
  }
  else {
    $form['field_length_type']['und']['#value'] = "long";
  }
  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace("#replace_body_words", $form['body_words']),
      ajax_command_replace("#replace_field_length_type", $form['field_length_type'])
     )
   );
 }
}

Any help would be much appreciated. Any workaround?
Comment: Wouldn't it be easier to do this simply through JS? This way you could even show a real-time word counter. Unless you must have AJAX by design somehow or it follows up some other workflows, I think JS is by far the easiest solution. And you won't have to worry about avoiding form submittal.
Comment: This is a part of the snippet, there a few other things happening making JS difficult.
Answer: When using the #type => 'button' the submit callback is never executed, it already receives  a FALSE as default value.
Even if the submit callback is not executed, the validate callback is always executed (even on ajax posts). You can bypass this validation on a trigger element by using the #limit_validation_errors property.
In your case, you can set it on the body_words form element to only validate on this scope instead of the whole form.
$form['get_word_count'] = array(
    '#type' => 'button',
    '#value' => t('Update Count'),
    '#weight' => 5,
    '#limit_validation_errors' => array(
        array('body_words'),
    ),
    '#ajax' => array(
        'callback' => 'count_words',
    ),
);

Comment: Worked in a snap!

The curious case of a Drupal Button


Is it possible (and within convention) to insert a hidden field in an views exposed filter to control form content (e.g for re-submit search)?

Question: Examples:

(my requirement) when wanting to control the content of the view title for a listing of locations (E.g. title "venues near you") created using a view with Drupal module ip_geoloc ("IP Geolocation Views & Maps") based on the user's detected location (via html5 geo location) and then offering further searches (e.g. a different specific location) and wanting to display a different title in those results "venues near New York City"
simpler example "search again" for subsequent displays of the form (an user-visible views exposed filter).

For example 1., I'm currently using hook_views_pre_render in my own custom module to compare the submitted value with the detected location to be able to set a custom title for the view, snippets (note, not full declaration and module) of how I get each of these here:
    $locationAsString = "";

    if (function_exists('ip_geoloc_get_visitor_location') ) {
      $locationAsArray = ip_geoloc_get_visitor_location();

      // debug
      //dpm($locationAsArray);

      if ( isset($locationAsArray['locality']) ) {
        $locationAsString = t($locationAsArray['locality'].", ".$locationAsArray['country']);
      }
    }

    $submittedLocationAsString = "";
    if ( isset($view->exposed_raw_input['field_geofield_distance']['origin'] ) )
    {
       $submittedLocationAsString = $view->exposed_raw_input['field_geofield_distance']['origin'];
    }

    // debug:
    //drupal_set_message( "submitted location is: ".$submittedLocationAsString );
    //drupal_set_message( "actuallocation is: ".$locationAsString );

    if ( $locationAsString == $submittedLocationAsString )
    {
      $view->build_info['title'] = "We think you're near ".$locationAsString.". ".$thereAreAsString." here.";
    }
    else
    {
      $view->build_info['title'] = $resultsAsString." near ".$submittedLocationAsString;
    }

My ideal solution
But as you can see, this straight compare is not necessarily that robust. To determine the title I want, I think it may actually be better to insert a hidden field in the form, in hook_form_alter and detect the value/presence of this field in cgformutils_views_pre_render - is this approach within convention and not 'illegal' or bad practice?
Comment: Related answer here: http://drupal.stackexchange.com/questions/35504/can-i-prepopulate-an-exposed-filter-text-field
Answer: Though I am providing the solution for the question which you have asked but as per your description I understand you are looking to achieve content boosting with views.
It's a nice idea which has been implemented on some websites like meetup.com, where they boost the local event at top when you visit & these works for anonymous users too as well as authenticated.
You will need 3 modules to achieve this - Location, Smart IP & Views.
I have written a blog post about configuring them to achieve this, which you can find at - http://drupalconnect.in/content-boosting-views
I will recommend you to try this if you trying something like this :)


Drupal node add form is empty: why?

Question: Just transferred my brand new Drupal webshop to shared to host and guess what: it doesn't work.
I can't figure out that why node add page is lacking form? Everything else is in place. And to be more spefic it is just for one content type, other work fine.
I've tried drush rr, drush cc all etc. I've checked permissions etc. I'm using Display Suite forms as template for node add form.
This all of the rendered form markup that has a empty div container:
<form class="node-form node-content_type-form" enctype="multipart/form-data" action="/content_type" method="post" id="content-type-node-form" accept-charset="UTF-8" novalidate="novalidate">

</form>

And this is for anonymous users. For admins it work normally but it also has another theme.
When I tranferred the site I took a archive dump with drush and imported it into shared host.
UPDATE
Like always this Drupal like problem seemed very odd. So I decided just to change the theme and see if it has any effect.
Using the base theme of my custom the form is rendered normally.
However, custom theme works just fine on my localhost so I can't tell what is the problem. Seems like a theme issue but on the other hand not.
UPDATE 2
Base theme showed some "new" errors on second load. These errors refer to a oooold theme and shows that Drupal is trying to use that tpl file. I assume that this is the core problem which causes different results depending on theme.
'/home/user/public_html/sites/all/themes/custom_boot/node-content_type-form.tpl.php

UPDATE 3
I found the old code that registered this "theme" or template and which is still somehow required/requested on page load:
function custom_boot_theme($existing, $type, $theme, $path){

    return array('node__content_type__form'=>
            array(
                'render element' => 'form',
                //'path' => drupal_get_path('theme', 'custom_boot') . '/templates',
                'template'=> 'content-type-node-form',
            'user_register_form'=>
            array(
                'render element' => 'form',
                //'path' => drupal_get_path('theme', 'custom_boot') . '/templates',
                'template'=> 'content-type-node-form',
            ),
        );
}

How could I undo this?
UPDATE 4
If I remove this old theme and run drush rr, it will give following error every time:
    The following theme is missing from the file system: custom_boot. For information about how to fix this, see the documentation page. bootstrap.inc:1128

Even though custom_boot is removed from system table by drush rr, it will still try to find some files related to this removed theme.
UPDATE 5 - FINDINGS AND POSSIBLE SOLUTIONS
First of all it seems that the problem is somehow in the current theme.
What is it? I don't know.
Secondly, why does this site work perfectly on localhost but not on this live server? Could I make some changes to PHP ini settings that would "look through"/disregard the small hickup of missing theme? I don't understand that why localhost won't die on this missing theme problem...
UPDATE 6
Well, since I couldn't get a rid of I had to stick with it. I've just enabled this old theme but which I'm not using. Now the form shows but it is rendered with this old themes custom form template file described above.
BUT, as soon as I visit /admin/structure/types/manage/content-types/fields the form starts failing again. So Display Suite and old theme have some issues.
AND TO ADD, it is all the same if the content-type-node-form.tpl.php file has content or not: the form is rendered and I can put any code in there and it won't change or break anything.
Comment: I think it is cache issue. just clear the cache or for testing just disable "Cache pages for anonymous users" from the performance settings.
Comment: drush rr, drush cc all - not a cache issue. And so far cache has been disabled.
Comment: _How could I undo this?_ Remove the implementation of the hook (remove the entire `custom_boot_theme` function) and clear the caches once more.
Comment: I forgot to mention that this code was already disabled i.e. commented out. But the things it did are still somewhere in the system. I understand that this registers so to say "hooks" and now they should be removed/unregistered (manually/db/etc). This should have been happened when code was commented or  theme disabled but for some mysterious Drupal reason that didn't happen.
Comment: You should disable that theme before removing it. Now the database thinks it has an active theme and can't find it.
Comment: Well, I've done it few times and I don't think it is that easy. On the other hand I ended up thinking that is that if I uncomment the old code, then enable, do this and do that and eventually disable it with the actual code then it might work...
Comment: If the theme is disabled the code should not be getting hit. IMO it sounds like caching layers that exist on the server that do not exist locally. I would flush memcache or redis if they are there or just reboot the servers.
Comment: And it doesn't get hits since no matter how I modify the code or completely remove it from the tpl file the form is still rendered with that template and that template file is required or otherwise errors start popping up. And this code has been commented out since beginning so it basically can't be in any server level cache.
Answer: Well, now I feel stupid. Eventually it seemed to be a file permissions related issue.
I took this https://www.drupal.org/node/244924 script and modified it per server spec.
After few trials it worked...It certainly didn't seem like a permissions related but maybe they cause various situations.

Drupal node add form is empty: why?


Prove $B(a,\frac{1}{2}) \ge \frac{1}{a}$ for $a \ge 1$

Question: I would like to prove
$B(a,\frac{1}{2}) \geq \frac{1}{a}$ for $a \geq 1$,
where B represents the Beta function.
It seems to be true, but I haven't found a nice proof yet.
Tried to work with the integral formula but I couldn't get a clean picture.
Does anyone have an idea on how to prove this?
Here is a start with the Gamma function.
\begin{align*}
B(a,\frac{1}{2}) = \frac{\Gamma(a) \cdot \Gamma(\frac{1}{2})}{\Gamma(a+\frac{1}{2})} \geq \frac{1}{a}
\end{align*}
Now I multiply both sides with $a$.
\begin{align*}
a \cdot \frac{\Gamma(a) \cdot \Gamma(\frac{1}{2})}{\Gamma(a+\frac{1}{2})} \geq 1
\end{align*}
Now I use the fact that $\Gamma(a+b) \leq \Gamma(a+c)$ for $b \leq c$.
\begin{align*}
a \cdot \frac{\Gamma(a) \cdot \Gamma(\frac{1}{2})}{\Gamma(a+\frac{1}{2})} \geq a \cdot \frac{\Gamma(a) \cdot \Gamma(\frac{1}{2})}{\Gamma(a+1)} = a \cdot \frac{\Gamma(a) \cdot \Gamma(\frac{1}{2})}{a \cdot \Gamma(a)} = \Gamma(\frac{1}{2}) \geq 1
\end{align*}
Comment: What about $B\left(a,\frac{1}{2}\right)=\int_0^1\frac{t^{a-1}}{\sqrt{1-t}}dt \geq\int_0^1t^{a-1}dt$?
Comment: Write it in terms of gamma functions, multiply through by $a$ and use the functional equation for gamma. It should be obviously true then.
Comment: The most basic one: $\Gamma(a+1)=a\Gamma(a)$. Then note the monotonicity of gamma for $a\ge 1$.
Comment: I started based on your hint. What is the functional equation for gamma?
Comment: Okay, I used it by bounding $\Gamma(a+\frac{1}{2}) \leq \Gamma(a+1)$ (see above). Does it make sense?
Comment: Yes, $\Gamma(x)$ is increasing for $x\ge 3/2$.
Answer: For $a\geq 1$, we have\begin{align*}
B\left(a,\frac{1}{2}\right)&=\int_0^1\frac{t^{a-1}}{\sqrt{1-t}}dt\\
&\geq\int_0^1t^{a-1}dt\\
&=\frac{1}{a}.
\end{align*}


Any way other than Win32::OLE to call objects from dll in Perl?

Question: Win32::OLE is not thread safe. Is there a way to go around it?
Can the following typical Win32::OLE usage be replaced by any other Perl modules?
my $myWin32 = Win32::OLE->new('my_App');
my $myApp1  = Win32::OLE->GetObject("my_App");
my $myApp2  = Win32::OLE->GetActiveObject("my_App");

Comment: Are you sure it's not thread safe? The default initialization method is documented to be `COINIT_MULTITHREADED`, which "creates a multi-threaded apartment that will be shared with any other threads that repeat [the call to `CoInitializeEx`]."
Answer: You could take a look at Win32::API, but I'm not sure of its thread safety.


Por que ao arredondar a soma de dois números, o resultado é NaN?

Question: Por que ao arredondar a soma dos dois valores abaixo retorna NaN?

numero1 = '1,10';
numero1 = parseFloat(numero1.replace(/[^0-9,]*/g, '').replace(',', '.')).toFixed(2); // output: 1.10
numero2 = '2,20';
numero2 = parseFloat(numero2.replace(/[^0-9,]*/g, '').replace(',', '.')).toFixed(2); // output: 2.20
total = Math.round(numero1 + numero2); // output: NaN
console.log(total);
Comment: Depois que converte os dois números em string o operador `+` funciona como concatenador.
Comment: Não retornou NaN...
Comment: Se pressionar executar o resultado dá 3.
Comment: Provavelmente é algum problema relacionado ao ambiente em que você está executando o código.
Comment: Editada, desculpem, faltou código.
Answer: Como já disseram as outras respostas, o problema ocorre porque toFixed retorna uma string, então numero1 e numero2 serão strings. E quando você usa o operador + em strings, elas são concatenadas e o resultado é outra string.
No caso, após as chamadas de toFixed, numero1 se torna a string '1.10' e numero2 se torna '2.20'. E ao concatená-las, o resultado é a string '1.102.20':

let numero1 = '1,10';
numero1 = parseFloat(numero1.replace(/[^0-9,]*/g, '').replace(',', '.')).toFixed(2);
let numero2 = '2,20';
numero2 = parseFloat(numero2.replace(/[^0-9,]*/g, '').replace(',', '.')).toFixed(2);
console.log(numero1 + numero2); // 1.102.20

E essa string, quando passada para Math.round, resulta em NaN, já que ela não é um número válido (comportamento descrito na especificação da linguagem). Mas apenas para deixar claro, ao contrário do que afirmou outra resposta, Math.round pode sim receber strings como parâmetro, desde que elas representem números válidos:

console.log(Math.round('1.23')); // 1
console.log(Math.round('7.9')); // 8
console.log(Math.round('-1234')); // -1234
console.log(Math.round('3.02e4')); // 30200 (número em notação científica)
console.log(Math.round('0xff')); // 255 (número em hexadecimal)
console.log(Math.round('')); // 0 (OK, esse é um caso "estranho", string vazia não deveria ser um "número válido", mas o JS acha que é...)
console.log(Math.round('1.102.20')); // NaN
console.log(Math.round('123xyz')); // NaN

Arredondar ou não, eis a questão
Dito isso, a solução correta depende de vários fatores. Pois tem um detalhe importante que deve ser levado em conta: o arredondamento. toFixed, além de limitar a quantidade de casas decimais, também arredonda o valor caso necessário. Exemplos:

console.log(1.991.toFixed(2)); // '1.99'
console.log(2.999.toFixed(2)); // '3.00'

console.log(1.247.toFixed(2)); // '1.25'
console.log(1.244.toFixed(2)); // '1.24'

E no seu caso, parece que você quer primeiro arredondar os valores (limitando-os a 2 casas decimais com toFixed) e depois somá-los - e no final arredondar o resultado com Math.round. Ou seja, se numero1 for '1,247' e numero2 for '1,245', o resultado será 3:

function arredonda(n) {
    n = parseFloat(n.replace(/[^0-9,]*/g, '').replace(',', '.')).toFixed(2);
    // toFixed retorna uma string, então eu preciso converter para número de novo
    return parseFloat(n);
}

let numero1 = '1,247';
numero1 = arredonda(numero1);
let numero2 = '1,245';
numero2 = arredonda(numero2);
console.log(numero1); // 1.25
console.log(numero2); // 1.25
console.log(numero1 + numero2); // 2.5
console.log(Math.round(numero1 + numero2)); // 3

Mas e se eu não arredondasse os números, e só aplicasse Math.round no resultado final? Nesse caso o resultado seria 2:

function converte(n) {
    // não usa toFixed, retorna o número com todas as casas decimais
    return parseFloat(n.replace(/[^0-9,]*/g, '').replace(',', '.'));
}

let numero1 = '1,247';
numero1 = converte(numero1);
let numero2 = '1,245';
numero2 = converte(numero2);
console.log(numero1); // 1.247
console.log(numero2); // 1.245
console.log(numero1 + numero2); // 2.492
console.log(Math.round(numero1 + numero2)); // 2

Outra opção seria pegar somente as duas primeiras casas decimais dos números (sem arredondar) e o resultado também seria 2:

function converte(n) {
    n = parseFloat(n.replace(/[^0-9,]*/g, '').replace(',', '.'));
    // em vez de toFixed, uso matemática para pegar somente as duas primeiras casas decimais
    return Math.floor(n * 100) / 100;
}
numero1 = '1,247';
numero1 = converte(numero1);
numero2 = '1,245';
numero2 = converte(numero2);
console.log(numero1); // 1.24
console.log(numero2); // 1.24
console.log(numero1 + numero2); // 2.48
console.log(Math.round(numero1 + numero2)); // 2

Ou seja, cabe a você decidir qual abordagem usar. Não ficou claro se todos os valores que você recebe sempre tem exatamente 2 casas depois da vírgula. Se for isso, então não há arredondamento a ser feito e você nem precisaria usar toFixed(2). Bastaria usar a segunda opção acima, que só converte para número, sem arredondar nada. Mas se a quantidade de casas decimais varia e pode ser maior que 2, a escolha de uma das abordagens acima pode fazer toda a diferença no resultado final.

Aliás, o primeiro replace é desnecessário para estes casos, pois ele remove tudo que não é número nem vírgula. Mas como as strings de exemplo só tem números e uma vírgula, então esse replace não faz nada. Mas enfim, se os dados reais possuem outros caracteres, aí faz mais sentido usá-lo, senão poderia removê-lo sem problemas.

Dinheiro?
Por este comentário, dá a entender que você está trabalhando com valores monetários. Se realmente for isso, então o melhor é não usar números de ponto flutuante (leia mais sobre o assunto aqui). Em vez disso, você pode simplesmente remover a vírgula e trabalhar com a quantidade total de centavos. Depois, na hora de exibir o valor, aí você formata da maneira que achar melhor.
No caso de valores monetários, você pode inclusive usar Intl.NumberFormat para formatar o valor de uma maneira mais "bonita":

function converteParaCentavos(n) {
    // assumindo que o valor sempre tem 2 casas depois da vírgula,
    //basta remover tudo que nao é número para ter a quantidade de centavos
    return parseFloat(n.replace(/[^0-9]*/g, ''));
}

// converte tudo para centavos
numero1 = '1,24';
numero1 = converteParaCentavos(numero1);
numero2 = '1,24';
numero2 = converteParaCentavos(numero2);
console.log(numero1); // 124
console.log(numero2); // 124
console.log(numero1 + numero2); // 248

// somente na hora de mostrar, eu divido por 100 para mostrar o valor em reais
console.log(Math.round((numero1 + numero2) / 100)); // 2

// exemplo com Intl.NumberFormat
let formatter = new Intl.NumberFormat('pt-BR', {
    style: 'currency',
    currency: 'BRL',
});

// sem arredondar
console.log(formatter.format((numero1 + numero2) / 100)); // R$ 2,48
// arredondando
console.log(formatter.format(Math.round((numero1 + numero2) / 100))); // R$ 2,00
Comment: como mencionou, sim eu estou trabalhando com valor monetário, ficou clara sua resposta, deu tudo certo agora, foi uma aula tudo isso e sanou outras dúvidas que tinha, obrigado pela sua sapiência e boa vontade.
Answer: O resultado NaN é devido a utilizado do Math.round em uma string.
Quando você utiliza o método toFixed, o retorno é uma string.

numero1 = '1,10';
numero1 = parseFloat(numero1.replace(/[^0-9,]*/g, '').replace(',', '.'));
numero2 = '2,20';
numero2 = parseFloat(numero2.replace(/[^0-9,]*/g, '').replace(',', '.'));
total = Math.round(numero1 + numero2);
console.log(total);

Documentação: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
Comment: @EliseuB. Retorna um número inteiro porque [esse é o retorno de `Math.round`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round). Se não quer que "coma" os centavos, não chame `Math.round`
Comment: Mas se numero1 = '10,99' e numero2 = '21,01', os centavos são "comidos";
Comment: Não tive esse problema: https://repl.it/repls/RecursiveTenderOutcome
Comment: cara, foi uma tremenda coincidência em ter um valor redondo, mas refazendo a pergunta, se for "1,11" e "1,13", o resultado seria "2.24", mas retorna número inteiro, como no seu exemplo, e não tem representação após o .(ponto).
Comment: @EliseuB. Outra coisa, se está lidando com valores monetários, é melhor não usar `float`, e também tem como formatar sempre com os centavos. Veja na parte final da [minha resposta](https://pt.stackoverflow.com/a/440431/112052) :-)


Create a new column multiplying a column and an array with unequal lengths

Question: I have the following columns:
Date
2010-01-04  NaN         NaN         NaN         NaN         NaN
2010-01-05  0.012724    0.015659    0.000266    0.003344    0.022251
2010-01-06  0.004910    -0.020427   -0.022870   -0.014700   -0.030640
2010-01-07  -0.022239   -0.017900   -0.028223   -0.022729   -0.021563
2010-01-08  0.025978    -0.015153   -0.020648   -0.024394   -0.023600
... ... ... ... ... ...
2021-08-25  -0.000171   -0.003003   0.012596    0.008506    0.001257
2021-08-26  -0.009339   -0.004284   0.003506    -0.004533   0.011284
2021-08-27  -0.002833   0.009494    0.013068    -0.011000   -0.003862
2021-08-30  -0.018293   -0.003945   -0.005080   -0.006311   0.000387
2021-08-31  0.019848    0.013350    0.022745    0.004935    0.016115
2875 rows × 5 columns

I am trying to create a new column that will be the sum of multiplication of each row of the columns with respective weights as an output.
Weights are as follows:
array([0.12123039, 0.31162947, 0.27817099, 0.10452567, 0.18444348])

For eg.
On 2010-01-05:
New column value = (0.012724 * 0.12123039 + 0.015659 * 0.31162947 + 0.000266 * 0.27817099 + 0.003344 * 0.10452567 + 0.022251 * 0.18444348)
Answer: Use:
df['new_column'] = df.mul(weights).sum(axis=1)


Retorno de SQL em PHP converte acentuação para '?'

Question: Estou com um problema de encode, o meu retorno do Banco Oracle está fazendo os acentos em ? alguém consegui me ajudar?
Detalhe preciso converter na variável não só no Browser, porque vou usar para um outro select.
       $sqlIn = "SELECT  distinct(LOCALIDADE_NOME) , COUNT(LOCALIDADE_NOME) FROM TBL_TA
            INNER JOIN TBL_TA_EQUIPAMENTO ON CODIGO=AEQ_TA WHERE TQA_ORIGEM IN ($listaIn)
            GROUP BY LOCALIDADE_NOME";
    $RESP_QUERYa = oci_parse($SS, $sqlIn);
    oci_execute($RESP_QUERYa);
    $afetacaolista = new ArrayObject();
    while (($row = oci_fetch_array($RESP_QUERYa, OCI_BOTH)) != false) {
        $afetacao = new afetacaoBean();
        echo $teste = utf8_encode($row['LOCALIDADE_NOME']) . "
";
        }

A Saida é:
RIBEIR?O PIRES
VARZEA PAULISTA
FRANCO DA ROCHA
S?O PAULO
JUNDIAI
FRANCISCO MORATO

Já tentei varias coisas como :
    mb_internal_encoding("UTF-8");
    mb_http_output("iso-8859-1");
    ob_start("mb_output_handler");
    header("Content-Type: text/html; charset=ISO-8859-1", true);

Não Tenho como mudar a configuração do Banco nem de Tabelas.
Comment: Possível duplicata de [Dúvida com charset=iso-8859-1 e utf8](https://pt.stackoverflow.com/questions/43193/d%c3%bavida-com-charset-iso-8859-1-e-utf8)
Comment: Fiz a Edição para não duplicar e o problema permanece.
Answer: Pelo que entendi pode ser o próprio encode da conexão com o Oracle.
Você pode tentar forçar a codificação na própria conexão dessa forma:
$conn = oci_connect( $username, $pass, $conn_string, 'UTF8' );


Problems with Natural sense of rhythm. Ways to improve it

Question: At the age of 9, I started singing in a choir and quickly discovered my passion for music. I had a great voice but I soon realised that I had no sense of rhythm.
When I heard a song I wasn't even able to tap the tempo with my foot or anything, it's something I just didn't feel.
Then as a teenager after quite a bit of work on that, I was able to feel the tempo of a song.
Now I'm 19 and my rhythm became a lot better but my natural sense of rhythm is still very weak. I'll try to explain that with the best of my abilities:

When I sing a song where the instrumental has a very organised rhythm (for example Another one bites the dust by queen or Imagine by john Lennon) I am fine because there are keys or "signs" in the song that tell me when to start singing and which rhythm to adopt.
Same thing goes with playing any type of instrument
I can also play in rhythm if I improvise for I don't have a problem with tempo
Now my problem i when the instrumental is more "abstract", I can still feel the tempo but there is no signs of when to start singing or playing.
I am fine if I have a music chart because I simply have to count

Now my problem is that I don't want to have to count or study the song everytime I wanna play or sing. I've seen many people with no musical education who can sing songs with very complex rhythm without any problem.
Does any one know how I can improve that ability because unlike moste it's not innate to me.
Thank You
Comment: Can you give us an example or two of "when the instrumental is more 'abstract' "?
Comment: @Richard Well most songs to be honest. An example would be "wearing the inside out" by pink floyd
Comment: @Richard Or satisfy my soul by Bob Marley
Comment: @Sylvester To clarify, you would be fine if (for example) you had a music chart of Wearing the Inside Out or Satisfy My Soul? Or would it be difficult for you either way?
Comment: @MysteriousWhisper Yes I'd be perfectly fine with a music sheet. I just can't feel the pattern of the rhythm (if that makes any sense)
Answer: I think pulse/rhythm are things that are learned best through exposure and immersion in a kinesthetic way.
Specifically - what I'd recommend is the following (the more you make this a habit the better your rhythm gets):

When you hear a piece of music, do something physically to match the pulse - the repeated regular moment in time that tells you where you are - in "Wearing The Inside Out", listen to the ride cymbal - the metal "ting" is the pulse in the verse. Perhaps the most popular and visible is to tap your foot. You could also clap, bob your head, or breathe with the pulse. The periodicity of events in time is what organizes all of music and more complex groups of timed events (rhythm)
When you hear a "rhythm" or rhythmic idea, do something to match that as well - something you can feel strongly. For instance in the example you gave "Another One Bites the Dust" you could do a number of things to match the bass guitar repeated idea - you could tap it with your fingers or hands on a surface or your body, sizzle it with your breath, or mimic the instrument with your voice.

At first, it may be difficult to do these on their own, but try to combine them so you are both reflecting the pulse and the rhythm at the same time. The idea is to automatize your feel of both pulse and rhythm so you can then think about the fun stuff "What does this sound like?" "How am I making this sound cool or whatever else I'm going for musically?"
Once you feel these things as second nature - it is much easier to maintain a sense of pulse/rhythm when you perform something that is less familiar. It also becomes easier to recognize what elements of what you're hearing give you information: where the "pulse" is and what the "rhythm" is or is suggesting.
Continue to move as you perform - the freeness of your ability to move allows you to be comfortable in the pulse as you interact with it musically.
Hope this helps!


jquery Allow td doubleclick only when not contains input

Question: I´ve following function for table editing:
$(function () {
$("td").dblclick(function () {
    var OriginalContent = $(this).text();

    $(this).addClass("cellEditing");
    $(this).html("<input type="text" value="" + OriginalContent + "" />");
    $(this).children().first().focus();

    $(this).children().first().keypress(function (e) {
        if (e.which == 13) {
            var newContent = $(this).val();
            $(this).parent().text(newContent);
            $(this).parent().removeClass("cellEditing");
        }
    });

$(this).children().first().blur(function(){
    $(this).parent().text(OriginalContent);
    $(this).parent().removeClass("cellEditing");
});
});
});

Which works like this: http://www.ssiddique.info/demo/editable-table-using-jquery
If I doubleclick the td an input is added to the cell, unfortunately the doubleclick is also fired if I double click inside the input which results in an empty input.
How can I prevent the secong double click? Or fire doubleclick only when td not contains an input?
Thanks,
t book
Answer: Prevent the event propagating up the DOM tree. Something like the following:
$(this).find('input').dblclick(function(e){
    e.stopPropagation();
});

JSFiddle
Comment: thanks this brought me to this: $(this).children("input").length == 0 which is working.
Answer: below checks if td is empty or not:
$("td").on('dblclick',function () {
    if( $(this).html()!='' ) alert('content')
    else alert('no content')
});

here is the fiddle: http://jsfiddle.net/WSRF3/
so in your example I would opt on only execute code if td has no content:
$("td").on('dblclick',function () {
    if( $(this).html()!='' ) return; // do nothing
    // continue your code here...
});


a compact subset of uncountable ordinal space $\omega_1$

Question: It is known that the topological space $\omega_1$ is not compact. Further, $\omega_1$ has a least upper bound. Hence, by Theorem 27.1 of Munkres, every closed subset of $\omega_1$ is compact.
My question is: Is true that every compact subset of $\omega_1$ closed?
I do not know how to prove it and I also do not have a counterexample
Comment: Be aware that Theorem 27.1 of Munkres states that closed _intervals_ in ordered spaces with the lub property are closed, not every closed set. (For example, $\omega_1$ itself is closed in $\omega_1$, but is not compact.)
Answer: Yes.
Since $\omega_1$ is linear order, the order topology is a Hausdorff topology. And in a Hausdorff space every compact set is closed.


Putting python code online- confusion with my app.py script

Question: So I'm getting into the process of putting some of my first python code online and I'm a little fuzzy about some things. When we assign app to web.application(urls, globals()), what is going on exactly? Also, the line form = web.input(name="Nobody", greet=None) is referring to the two input forms in my other script called hello_form, but what is its purpose here? We're calling form.greet and form.name on the next line I see, but those should be variables created based on user input, (yet we say name = "Nobody"?).
import web

urls = (
    '/hello', 'Index'
)

app = web.application(urls, globals())

render = web.template.render('templates/', base="layout")

class Index(object):
    def GET(self):
        return render.hello_form()

    def POST(self):
        form = web.input(name="Nobody", greet=None)
        greeting = "%s, %s" % (form.greet, form.name)
        return render.index(greeting = greeting)

if __name__ == "__main__":
    app.run()

Answer: app = web.application(urls, globals())

creates a variable named app and stores the result of calling web.application() in it. In other words, you create a web application object, and store that object in app.
form = web.input(name="Nobody", greet=None)

The values specified for name and greet here are the default values - namely, those used if no user specified values are provided in the request.
Comment: @ZCJ It's blank because your browser is still submitting a value for that form (an empty string). You'd have to remove the box entirely to have the browser not submit a value.
Comment: Because it's possible to access your form processor via other means than through your form. For instance, someone could use `curl` to send an HTTP request with whatever they want in it. Defaults allow you to write robust webapps that don't fail in weird ways just because someone circumvents your page.
Comment: Thanks for the explanation! I'm not sure what I'm doing wrong but I tried breaking that second line by changing it to: `form = web.input()` and it didn't make any difference. Also in my browser if I don't type anything in the first text box it doesn't come up with "Nobody"; it's just blank.
Comment: Then why would I ever put those default values in there? I'm putting them in there because the web.input() variable called `form` exists. Since the only way they could be shown is if I don't even have that box, why would you ever need them as a default?


Set consisting of all unoriented cobordism classes of smooth closed $n$-manifolds can be made into additive group?

Question: How do I see that the set $\mathfrak{N}_n$ consisting of all unoriented cobordism classes of smooth closed $n$-manifolds can be made into an additive group?
Comment: Addition is disjoint union, inverse is the manifold itself.
Comment: Did this question suddenly pop into your mind? Were you doing your laundry and suddenly wondered that with no context at all surrounding it? There are groups of every cardinality, so trivially every set can be made into a group. Maybe the *context* surrounding your question helps in determining what the precise group law is?
Answer: A natural operation is disjoint union. If $[M]$, $[N]$ are cobordism classes of $M, N$ respectively then define the sum to be $[M] + [N] = [M \sqcup N]$, the cobordism class of the disjoint union of the two.
This is clearly associative, commutative and has identity as the null manifold class $[\emptyset]$. $[M] + [M] = [M \sqcup M]$, and as $M \sqcup M$ bounds $M \times [0, 1]$ (in the unoriented category!), $2[M] = 0$, so a cobordism class is it's own inverse.
The resulting additive group is denoted as $\Omega_n^{un}$, called the $n$-th unoriented cobordism group of a point. A classic question in topology is to compute these groups. Some examples are $\Omega_0^{un} \cong \Bbb Z/2$, $\Omega_1^{un} \cong 0$, $\Omega_2^{un} \cong \Bbb Z/2$, $\Omega_3^{un} \cong 0$, $\Omega_4^{un} \cong \Bbb Z/2 \times \Bbb Z/2$ and $\Omega_5^{un} \cong \Bbb Z/2$.


For a function $f(A)$ where $A$ is a matrix prove that the following.

Question: I have to prove that $f(P^{-1} AP) = P^{-1} f(A) P$, where $A$ is a symmetric matrix and
$$
f(x)=3x^2+2
$$
So far I have done the following:

Please verify my approach. Also is there an alternative proof? Thanks
Comment: What is $P$? And what have you tried doing so far?
Comment: What is $f$? Domain, codomain, some additional property...?
Comment: What is $P$? Also, don't you mean $P^{-1}f(A)P$?
Comment: I doubt that this is easy, or even possible, for arbitrary functions. For polynomials or functions like $\sin(A)$ or $e^A$ that prove is straight forward. What have you tried?
Comment: @nbubis  yes you are correct i made a mistake there.
Comment: @PhilippSiehr please see my approach
Comment: @ajotatxe f is a function
Comment: Again - what function?
Comment: @PhilippSiehr it can be any function .
Comment: not any function it should have at least some regularity
Answer: So it is not any function, but a specific function. And the only part missing is
$$g(P^{-1}AP) = P^{-1}g(A)P$$
for $g(x)=x^2$. Is that correct?
In detail we have:
\begin{align*}
P^{-1}g(A)P &= P^{-1}A^2P \\
&= P^{-1}AAP\\
&= P^{-1}AIAP\\
&= P^{-1}APP^{-1}AP\\
&= (P^{-1}AP)^2\\
&=g(P^{-1}AP)
\end{align*}
Comment: it doesnt has to be g(x) = x^2 ... it could be any function. I just solved for an example. can it be generalized?
Comment: Your question specifically states that $f(x)=3x^2+2$. In the general case for `any function`. Be more specific, as you have been told several times in the comments.


Ring homomorphism is injective if and only if the induced maps on localizations are injective

Question: Suppose $\phi:A\to B$ is a ring homomorphism, where $A,B$ are commutative. Then for every $p\in A$, there is an induced map $\phi_p: A_p\to B_{\phi(p)}$ on the localization defined by $\phi_p(x/q) = \phi(x)/\phi(q)$.

I would like to show that $\phi$ is injective if and only if $\phi_p$ is injective for every $p\in A$, but I have some problems.

Suppose $\phi$ is injective. If $\phi_p(x/q) = 0$, then $\phi(x)/\phi(q) = 0$. Thus there exists an $r\in \{\phi(p)^n | n \in \mathbb N\}$ such that $r\phi(x) =0$. If I could show that this implies that there exists an $s\in \{p^n | n\in \mathbb N\}$ such that $sx =0$, then this would show that $\phi_p$ is injective.
Edit: I got confused between localization at a prime and what I really wanted. Now it is easy to solve the problem.
Any help would be appreciated! Thanks!
Comment: What are your $p$'s? At first, it looks like you are localizing the powers of a single element, but then when you write the condition, it seems like you are localizing at a prime ideal (which need not be principal).
Comment: The $p's$ are any element of $A$. I am localizing the powers of a single element.
Comment: Then how did your condition become $r\not\in (\phi(p))$?
Comment: I see your point. It should be the set of all powers of $\phi(p)$.
Comment: Not only that, it should be $\in$ rather than $\not\in$. You should probably take a closer look at how the equivalence relation on the localized ring is defined again.
Comment: Thanks! I really confused between prime ideal and what I really wanted.
Comment: @Zoltan If you could post your solution as answer, it would be appreciated.
Comment: Actually,I think the question is not right. Indeed, a ring homomorphism $f:A \to B$ is injective iff the induced maps $f_p:A_{f^{-1}(p)} \to B_p$ is  injective for any prime ideal p of B.
Answer: First suppose $\phi$ is injective, and suppose that
$$\frac{\phi(x)}{\phi(q)}=\frac{\phi(x)}{\phi(p^n)}=\frac{\phi(x)}{\phi(p)^n}=0\in B_{\phi(p)}$$
This means there is some $m\in\mathbb{N}$ such that $\phi(p)^m\phi(x)=0$ in $B$.  By injectivity it follows that $p^mx=0$ in $A$ so that
$$\frac{x}{q}=\frac{x}{p^n}=0\in A_p$$
Hence, $\phi_p$ is injective for all $p\in A$.
The reverse direction follows from considering the case $p=1\in A$.


Is it possible to set GPU affinity for a mixed precision NN, with FP32 and FP16 going to different GPUs?

Question: I have a GTX 1080 and an RTX 2080. I want to train using both, but since the RTX can handle FP16 twice as fast, I'd like to set it up so that the training is multi-GPU and the RTX handles the FP16 layers and the GTX handles the FP32 layers.
Is this possible under tensorflow, pytorch, or keras?
Answer: Tensorflow
In TF, it is possible to specify for each layer on which device to be executed (GPU, CPU, or specific GPU if you have multiple GPUs ...). This is done using with tf.device('device_name') statement (you need to provide meaningful device_name). See Using multiple GPUs section.
Keras
Since this is possible in TF, that means that you can use it also in Keras, if you use TF as Keras backend (Keras is just a high-level neural networks API).
Note that in Keras there is a multi_gpu_model() function in Keras, but that only copies a whole model on multiple GPUs, you cannot specify which layer to put on specific GPU.


Nginx root not working as I expected

Question: I am trying to achieve the following:
The root of my domain http://www.paulix.local/ should server the file located at /var/www/html/main/webroot/index.php
The url http://www.paulix.local/malibushould serve the file located at /var/www/domain/malibu/webroot/index.php
The rewrite I am trying to achieve (url => script) :

/ => /var/www/html/main/webroot/index.php
/path/whatever => /var/www/html/main/webroot/index.php?/path/whatever
/malibu => /var/www/domain/malibu/webroot/index.php
/malibu/path/whatever => /var/www/domain/malibu/webroot/index.php?/path/whatever

This is my current config
server {
    listen 80;
    listen [::]:80;

    rewrite_log on;
    access_log /var/log/nginx/paulix-access.log;
    error_log  /var/log/nginx/paulix-errors.log notice;

    server_name www.paulix.local;
    root /var/www/html/main/webroot;
    index index.php;

    # location 1
    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    # location 2
    location ~ /malibu {
        root /var/www/domain/malibu/webroot;
        try_files $uri $uri/ /index.php?$args;

        # location 3
        location ~ \.php$ {
            return 200 "Malibu is $document_root$fastcgi_script_name";
        }
    }

    # location 4
    location ~ \.php$ {
            return 200 "Global $document_root$fastcgi_script_name";
    }
}

If I hit the url http://www.paulix.local, it hits location 4 and I get the following output: Global /var/www/html/main/webroot/index.php which is what I'm expecting.
PROBLEMS
If I hit the url http://www.paulix.local/malibu it also hits location 4 with the same output as above, but I was expecting it to hit location 3, the expected output being: Malibu is /var/www/domain/malibu/webroot/index.php
Lastly, hitting http://www.paulix.local/malibu/index.php hits location 3, but not with the expected output. It outputs Malibu is /var/www/domain/malibu/webroot/malibu/index.php when I'd like it to be /var/www/domain/malibu/webroot/index.php
Comment: Note that the order of location stanzas is important. Try placing the malibu one as the first one.
Answer: Based on your needs, use location /malibu { or location ^~ /malibu {instead of location ~ /malibu {.
Here you can read an understandable overview how Nginx deals with location-blocks.
edit: Sorry, I haven't seen your last edit as I wrote my answer. I think it is alias you are searching for. Just replace root in location 2 with alias and the output should be fine. (Source)
Comment: Thanks for the suggestion, and the link, but it doesn't change anything
Answer: Edit: The problem is due to a bug in Nginx
One solution is the one below, or even better this one
server {
listen 80 default_server;
listen [::]:80 default_server;
rewrite_log on;
access_log /var/log/nginx/paulix-access.log;
error_log  /var/log/nginx/paulix-errors.log notice;

server_name www.paulix.test;
root /var/www/html;

location / {
    root /var/www/html/main;
    if (-f $request_filename) {
        break;
    }

    # prevent recursion
    if ($request_uri ~ /webroot/index.php) {
        break;
    }

    #rewrite ^/$ / permanent; # do not uncomment, or face infinite rewrite
    rewrite ^/webroot/(.*) /webroot/index.php last;
    rewrite ^/(.*)$ /webroot/$1 last;

        location ~ index\.php$ {
            try_files $uri =404;
            include fastcgi_params;
            fastcgi_pass unix:/run/php/php7.0-fpm.sock;
            fastcgi_index index.php;
            fastcgi_intercept_errors on;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }

}

location /malibu {
        root /var/www/domain;

    if (-f $request_filename) {
        break;
    }

    # prevent recursion
    if ($request_uri ~ /webroot/index.php) {
        break;
    }

    rewrite ^/malibu$ /malibu/ permanent;
    rewrite ^/malibu/webroot/(.*) /malibu/webroot/index.php last;
    rewrite ^/malibu/(.*)$ /malibu/webroot/$1 last;

        location ~ index\.php$ {
            try_files $uri =404;
            include fastcgi_params;
            fastcgi_pass unix:/run/php/php7.0-fpm.sock;
            fastcgi_index index.php;
            fastcgi_intercept_errors on;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }
}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.ht {
    deny all;
}

}

Nginx root not working as I expected


Wrong /proc/self/root after unshare(CLONE_NEWNS) syscall

Question: I have ARMv7 device with linux kernel 4.4 and I have a simple test case:
/* thread.c */
#define _GNU_SOURCE
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <sched.h>

void readlink_my(const char* when)
{
    char buf[100];
    int len = readlink("/proc/self/root", buf, sizeof(buf));
    buf[len] = '\0';
    printf("%s: %s\n", when, buf);
}

void *first_func(void * ptr)
{
    readlink_my("before unshare()..");
    if(unshare(CLONE_NEWNS) == -1)
        perror("error in unshare()..\n");
    readlink_my("after unshare()..");
    return NULL;
}

int main()
{
    pthread_t first_t;
    pthread_create(&first_t, NULL, first_func, NULL);
    pthread_join(first_t, NULL);
    return 0;
}

After executing this binary I have the output:
# before unshare()..: /
# after unshare()..: /new_root

If I'm removing multithreading from test case:
/* thread.c */
#include <unistd.h>
#include <stdio.h>
#include <sched.h>

void readlink_my(const char* when)
{
    char buf[100];
    int len = readlink("/proc/self/root", buf, sizeof(buf));
    buf[len] = '\0';
    printf("%s: %s\n", when, buf);
}

int main()
{
    readlink_my("before unshare()..");
    if(unshare(CLONE_NEWNS) == -1)
        perror("error in unshare()..\n");
    readlink_my("after unshare()..");
    return 0;
}

I will get ouput without /new_root after unshare():
# before unshare()..: /
# after unshare()..: /

As I think after unshare(CLONE_NEWNS) it will copy mount namespace.
Where from did I get /new_root in first multithreading example?
Comment: If I would to guess, I would say that when the new thread is created the owner of this thread is ( probably ) root, or something like that
Comment: @kaldoran I think that it's no care who is the owner of thread. I checked this code on regular smartphone with Android 7.1 and there is no new_root in both test cases.
Answer: /proc/self refers to the initial thread of a POSIX process, use /proc/thread-self to refer to the current thread.
unshare only effects the current thread.
The symlinks under /proc/self read as relative to the root of the examining thread if possible, if not they are relative to the root of mount namespace containing the object they refer to.
The root directory of the process in question is /new_root relative to the root directory of the mount namespace.
In the threaded test case, /proc/self/root is not root directory of the examining thread as it is in a different mount namespace, nor is it a sub-directory, so it is read as relative to the root of it's mount namespace.


UHD Device Won't Build in Redhawk 1.9.0

Question: I am trying to build the UHD device, latest commit (c749987865c5e158b65f26b160e0435f34c71580), in Redhawk 1.9.0, but receive multiple build errors (see below).  I received similar error when trying to build the most recent release of the UHD Device (v2.0.2).
The readme file with the UHD device doesn't indicate the requirements for building the device or provide any other instructions.
I have 2 questions:
1) Do I need to have GNUHawk installed too?
2) If so, I guess that means I need to downgrade to Redhawk 1.8.4, since GNUHawk supposedly won't work with Redhawk 1.9.0 (http://redhawksdr.github.io/Documentation/gnuhawk/mainli2.html), correct?
In case the problem is related to my build procedure, my steps are as follows:
1) Download zip file of repo from GitHub
2) Extract file contents into REDHAWK workspace and import project
3) Right click on project name (USRP_UHD-develop-1.8), select "Build Project"
09:30:38 **** Build of configuration Debug for project USRP_UHD-develop-1.8 ****
/home/nousain/workspace/USRP_UHD-develop-1.8/cpp/build.sh all
g++ -DPACKAGE_NAME=\"USRP_UHD\" -DPACKAGE_TARNAME=\"usrp_uhd\" -DPACKAGE_VERSION=\"2.0.1\" -DPACKAGE_STRING=\"USRP_UHD\ 2.0.1\" -DPACKAGE_BUGREPORT=\"\" -DPACKAGE=\"usrp_uhd\" -DVERSION=\"2.0.1\" -DHAVE_OMNIORB4=1 -DHAVE_LOG4CXX=1 -DHAVE_BOOST=1 -DHAVE_BOOST_THREAD=1 -DEXPECTED_VECTOR_IMPL=/\*\*/     -Wall -D__x86_64__ -D__linux__ -D__OSVERSION__=2 -DHAVE_LOG4CXX=1 -DENABLE_EVENTS=1 -I/usr/local/redhawk/core/include -I/usr/local/redhawk/core/include/ossie -I/usr/local/redhawk/core/share/idl   -pthread -I/usr/include -I/usr/local/redhawk/core/include/ossie -I/usr/local/redhawk/core/include/redhawk    -g -O2 -MT USRP_UHD-USRP_UHD.o -MD -MP -MF .deps/USRP_UHD-USRP_UHD.Tpo -c -o USRP_UHD-USRP_UHD.o `test -f 'USRP_UHD.cpp' || echo './'`USRP_UHD.cpp
In file included from USRP_UHD.cpp:37:
USRP_UHD.h:26:35: error: uhd/usrp/multi_usrp.hpp: No such file or directory
In file included from /usr/include/boost/thread/future.hpp:12,
                 from /usr/include/boost/thread.hpp:24,
                 from USRP_UHD_base.h:24,
                 from USRP_UHD.h:25,
                 from USRP_UHD.cpp:37:
/usr/include/boost/exception_ptr.hpp:43: error: looser throw specifier for 'virtual boost::exception_ptr::~exception_ptr()'
/usr/include/boost/exception/detail/exception_ptr_base.hpp:26: error:   overriding 'virtual boost::exception_detail::exception_ptr_base::~exception_ptr_base() throw ()'
In file included from USRP_UHD.cpp:37:
USRP_UHD.h:393: error: 'uhd' has not been declared
USRP_UHD.h:393: error: ISO C++ forbids declaration of 'sptr' with no type
USRP_UHD.h:393: error: expected ';' before 'usrpDevice'
USRP_UHD.h:394: error: 'uhd' has not been declared
USRP_UHD.h:394: error: ISO C++ forbids declaration of 'device_addr_t' with no type
USRP_UHD.h:394: error: expected ';' before 'device_addr'
USRP_UHD.cpp: In member function 'virtual int USRP_UHD_i::serviceFunction()':
USRP_UHD.cpp:281: error: 'uhd' has not been declared
USRP_UHD.cpp:281: error: expected ';' before '_metadata'
USRP_UHD.cpp:282: error: 'usrpDevice' was not declared in this scope
USRP_UHD.cpp:282: error: '_metadata' was not declared in this scope
USRP_UHD.cpp:282: error: 'uhd' has not been declared
USRP_UHD.cpp:282: error: 'uhd' has not been declared
USRP_UHD.cpp:285: error: 'uhd' has not been declared
USRP_UHD.cpp:287: error: 'uhd' has not been declared
USRP_UHD.cpp:290: error: 'uhd' has not been declared
USRP_UHD.cpp: In member function 'bool USRP_UHD_i::singleService_transmit(IN_PORT_TYPE*)':
USRP_UHD.cpp:366: error: 'uhd' has not been declared
USRP_UHD.cpp:366: error: expected ';' before '_metadata'
USRP_UHD.cpp:367: error: '_metadata' was not declared in this scope
USRP_UHD.cpp:372: error: 'usrpDevice' was not declared in this scope
USRP_UHD.cpp:372: error: 'uhd' has not been declared
USRP_UHD.cpp:372: error: 'uhd' has not been declared
USRP_UHD.cpp:376: error: 'usrpDevice' was not declared in this scope
USRP_UHD.cpp:376: error: 'uhd' has not been declared
USRP_UHD.cpp:376: error: 'uhd' has not been declared
USRP_UHD.cpp: In member function 'virtual void USRP_UHD_i::configure(const CF::Properties&)':
USRP_UHD.cpp:431: error: 'usrpDevice' was not declared in this scope
USRP_UHD.cpp:446: error: 'usrpDevice' was not declared in this scope
USRP_UHD.cpp:454: error: 'uhd' has not been declared
USRP_UHD.cpp:454: error: expected ';' before 'clock_config'
USRP_UHD.cpp:455: error: 'clock_config' was not declared in this scope
USRP_UHD.cpp:455: error: 'uhd' has not been declared
USRP_UHD.cpp:456: error: 'uhd' has not been declared
USRP_UHD.cpp:457: error: 'usrpDevice' was not declared in this scope
USRP_UHD.cpp:459: error: 'usrpDevice' was not declared in this scope
USRP_UHD.cpp:459: error: 'uhd' has not been declared
USRP_UHD.cpp:461: error: 'usrpDevice' was not declared in this scope
USRP_UHD.cpp:461: error: 'uhd' has not been declared
USRP_UHD.cpp: In member function 'void USRP_UHD_i::init_usrp(std::string)':
USRP_UHD.cpp:473: error: 'device_addr' was not declared in this scope
USRP_UHD.cpp:473: error: 'uhd' has not been declared
USRP_UHD.cpp:475: error: 'usrpDevice' was not declared in this scope
USRP_UHD.cpp:475: error: 'uhd' has not been declared
USRP_UHD.cpp:492: error: 'uhd' has not been declared
USRP_UHD.cpp: In member function 'bool USRP_UHD_i::setupTuner(size_t, const frontend_tuner_allocation_struct&)':
USRP_UHD.cpp:693: error: 'usrpDevice' was not declared in this scope
USRP_UHD.cpp:706: error: 'usrpDevice' was not declared in this scope
USRP_UHD.cpp:724: warning: format '%d' expects type 'int', but argument 3 has type 'size_t'
USRP_UHD.cpp:730: warning: format '%d' expects type 'int', but argument 3 has type 'size_t'
USRP_UHD.cpp: In member function 'bool USRP_UHD_i::enableTuner(size_t, bool)':
USRP_UHD.cpp:761: error: 'usrpDevice' was not declared in this scope
USRP_UHD.cpp:761: error: 'uhd' has not been declared
USRP_UHD.cpp:776: error: 'usrpDevice' was not declared in this scope
USRP_UHD.cpp:776: error: 'uhd' has not been declared
USRP_UHD.cpp: In member function 'void USRP_UHD_i::updateAvaiableUsrpSeq()':
USRP_UHD.cpp:1020: error: 'uhd' has not been declared
USRP_UHD.cpp:1020: error: expected ';' before 'himt'
USRP_UHD.cpp:1021: error: 'uhd' has not been declared
USRP_UHD.cpp:1021: error: expected ';' before 'device_addrs'
USRP_UHD.cpp:1022: error: 'device_addrs' was not declared in this scope
USRP_UHD.cpp:1024: error: 'device_addrs' was not declared in this scope
USRP_UHD.cpp:1027: error: expected primary-expression before 'key'
USRP_UHD.cpp:1027: error: 'BOOST_FOREACH' was not declared in this scope
USRP_UHD.cpp:1027: error: expected ';' before '{' token
USRP_UHD.cpp: In member function 'void USRP_UHD_i::update_myDeviceSeq()':
USRP_UHD.cpp:1045: error: 'usrpDevice' was not declared in this scope
USRP_UHD.cpp:1052: error: 'usrpDevice' was not declared in this scope
USRP_UHD.cpp:1062: error: 'uhd' has not been declared
USRP_UHD.cpp:1075: error: 'usrpDevice' was not declared in this scope
USRP_UHD.cpp:1084: error: 'uhd' has not been declared
make: *** [USRP_UHD-USRP_UHD.o] Error 1

09:30:49 Build Finished (took 11s.457ms)

Answer: This is an issue in the boost header files from RHEL/CentOS 6.4. You need to patch the boost file by editing the file /usr/include/boost/exception_ptr.hpp (which requires sudo). Add the following lines starting at line 92:
~exception_ptr() throw()
{
}

Source 1
This should take care of your exception throw errors.
Additionally, you need to add the pre-requisite files and download the source code for the USRP drivers. Download the UHD source and download the dependencies as follows:
git clone https://github.com/EttusResearch/uhd.git
sudo yum -y install boost-devel libusb1-devel python-cheetah doxygen python-docutils

Next, go into your uhd folder and into host folder and generate the makefiles.
cd uhd/host
mkdir build
cd build
cmake ../
make
make test
sudo make install
sudo ldconfig

Source 2
Source 3
Now try building the USRP_UHD project. Following these steps I was able to replicate your issues and have a successful build. As for your two questions, I do not have GNUHawk installed so you do not need it to build this project.
Comment: This is only applicable for Boost versions before 1.41.0-17 (http://redhawksdr.github.io/Documentation/mainap10.html#x36-478000J.1). I have Boost 1.41.0-18 installed and those lines are already present in that file.
Comment: You are right about that. The new version of Boost actually fixes that bug.
Comment: Thanks! Your instructions worked. The only additional steps I had to take were 1) sudo yum -y install cmake (since cmake was not installed by default on my system) and 2) sudo echo "/usr/local/lib64" >> /etc/ld.so.conf (before running "sudo ldconfig") so the system could find the uhd library.

UHD Device Won't Build in Redhawk 1.9.0


number of antichains and number of downsets

Question: This question is taken from the book Introduction to Lattices and Order by Davey and Priestley. Question 14 of Chapter 1.
Definition : If $P$ is and ordered set and $Q\subseteq P$, then $Q$ is a down-set if whenever, $x\in Q$, $y\in P$ and $y\leq x$, we have $y\in Q$.
Question : Let $P$ be a finite ordered set. Let $\mathcal{O}(P)$ be the set of all down-sets of $P$. Show that for all $x\in P$,
$|\mathcal{O}(P)|=|\mathcal{O}(P\backslash \{x\})|+|\mathcal{O}(P\backslash (\uparrow x \cup \downarrow x))|$.
I suppose the hint given by the question, which says that there exists a one-to-one correspondence between elements in $\mathcal{O}(P)$ and antichains of $P$, is essential here.
If I am to denote $\mathcal{A}(P)$ as the set of all anti-chains of $P$, all I've got is $|\mathcal{O}(P)|=|\mathcal{A}(P)|$. I tried to check if it's the case that $|\mathcal{A}(P)|=|\mathcal{A}(P\backslash \{x\})|+|\mathcal{A}(P\backslash (\uparrow x \cup \downarrow x))|$. However, I really could not see any link between them.
Thus, I would like to seek your input to help me see the links here. Thank you.
Comment: Define what you mean by "down-set" here. The sense I know does not match.
Answer: HINT: Suppose that $A$ is an antichain in $P$. If $x\notin A$, then $A$ is an antichain in $P\setminus\{x\}$. If $x\in A$, then $A\setminus\{x\}$ is an antichain in $P\setminus(\uparrow\!\!x\cup\downarrow\!\!x)$.
Comment: Thank you very much! I really appreciate this 'hint'. It becomes so obvious now.
Comment: @BeerR: You're very welcome.


Triangle Inequality with Vectors

Question: If the magnitudes of vectors $\mathbf{a}$ and $\mathbf{b}$ are $5$ and $12$, respectively, then the magnitude of vector $(\mathbf{b-a})$ could NOT be
(A) 5
(B) 7
(C) 10
(D) 12
(E) 17
The triangle inequality states that $7 < ||(\mathbf{b-a})||<17$ (i.e. the sums cannot be equal to that third length!). If it was permissible for them to be equal, then it would be (A) 5. Is it like a special exception for vectors because we are dealing with magnitudes?
Comment: T.I. gives here that $7 \leq ||{\bf b} - {\bf a}|| \leq 17$, the inequalities are not strict. In fact values $17$ and $7$ are achieved when the vectors are parallel, resp., antiparallel.
Answer: When dealing with literal triangles in the plane, the inequality is strict so as to prevent degenerate triangles. To get a magnitude of $7$, draw $\textbf{b}$ so that it points east and draw $\textbf{a}$ parallel (so that it also points east). Then their difference $\textbf{b} - \textbf{a}$ is a vector of magnitude $7$ that points east. Note that the vectors don't really form a triangle (in the intuitive two-dimensional sense); it's all one-dimensional, along the same line.
Likewise, to get a magnitude of $17$, do the same thing except draw $\textbf{a}$ antiparallel (so that it points west).

Triangle Inequality with Vectors


Javascript - Como funcionam os "IF e Else" em conjunto com os "returns"?

Question: Estou com uma dificuldade de entender, por que às vezes, dependendo do local onde está inserida uma declaração "if" em um determinado bloco de uma função, ela é ignorada. E como utilizar os "retuns", quando se deseja dentro dessa expressões parar, avançar ou retornar uma determinada função ?
Por exemplo:
Nesse código abaixo, tudo acontece, como o previsto, no entanto, o cursor fica travado no input e não avança para outro campo nem com TAB nem clicando, fica travado no focus, agora no próximo exemplo :

function nome_existe() {

 if(!valida_nome()) { // caso seja inválido
 document.getElementById("input_nome_cad").focus();
 return;
 }
 var nome = document.getElementById("input_nome_cad").value;
 var xmlreq = CriaRequest();
 xmlreq.open("GET", "mysqli_select_ajax.php?nome_cad=" + nome, true);
 xmlreq.onreadystatechange = function(){
  if (xmlreq.readyState == 4 && xmlreq.status == 200){
      document.getElementById("input_nome_cad").value='';
   document.getElementById("input_nome_cad").placeholder = xmlreq.responseText;
  }
  if(document.getElementById("input_nome_cad").placeholder == "Nome já existe!"){
   document.getElementById("input_nome_cad").placeholder = "Troca o nome";
  }
 }
 document.getElementById("input_nome_cad").focus();
 xmlreq.send(null);

}

Nesse exemplo eu acrescentei um novo "if" que é ignorado, como essas verificações funcionam ?

function nome_existe() {

 if(!valida_nome()) { // caso seja inválido
 document.getElementById("input_nome_cad").focus();
 return;
 }
 var nome = document.getElementById("input_nome_cad").value;
 var xmlreq = CriaRequest();
 xmlreq.open("GET", "mysqli_select_ajax.php?nome_cad=" + nome, true);
 xmlreq.onreadystatechange = function(){
  if (xmlreq.readyState == 4 && xmlreq.status == 200){
      document.getElementById("input_nome_cad").value='';
   document.getElementById("input_nome_cad").placeholder = xmlreq.responseText;
  }
  if(document.getElementById("input_nome_cad").placeholder == "Nome já existe!"){
   document.getElementById("input_nome_cad").placeholder = "Troca o nome";
  }
 }
/*Esse acréscimo parece ser ignorado, o "else" não funciona*/
 if(document.getElementById("input_nome_cad").placeholder != "Troca o nome"){
  document.getElementById("input_email_cad").focus();
 }else{
  document.getElementById("input_nome_cad").focus();
 }
 xmlreq.send(null);

}

valida_nome();

function valida_nome(){
 var filter_nome = /^([a-zA-Zà-úÀ-Ú0-9]|\s)+$/ ;
 if(!filter_nome.test(document.getElementById("input_nome_cad").value)){
 document.getElementById("input_nome_cad").value='';
 document.getElementById("input_nome_cad").placeholder = "Nome inválido";
 document.getElementById("input_nome_cad").style.borderColor = "#ff0000";
 document.getElementById("input_nome_cad").style.outline = "#ff0000";
 document.getElementById("input_nome_cad").focus();
 document.getElementById("input_nome_cad").onkeydown = function keydown_nome(){
 document.getElementById("input_nome_cad").style.borderColor = "#999999";
 document.getElementById("input_nome_cad").style.outline = null;
    }
 return false;
 }
 return true;
}
Comment: talvez ajude se puser o `valida_nome()` na pergunta
Comment: Se você comentar o `xmlreq.send(null);` (acrescentar um `//` na frente), o `else` funciona?
Comment: vc está validando duas vezes, a primeira no if(valida_xxx) lá tem um return false ou true e ao entrar o no if você coloca um return. quando se coloca um return sem nada após ele fica como return true, então independente da sua validação inicial se entrar no if sempre será true.
Answer: As suas condições estão sendo executadas antes da requisição terminar.
O único que você precisa fazer é mover essas condições para o bloco da condição de onde a requisição termina (ex, if(xmlreq.readyState === 4...)...). Eu até reformulei só um pouco do código.
function nome_existe() {
    var input = document.getElementById("input_nome_cad")
    if (!/^([a-zA-Zà-úÀ-Ú0-9]|\s)+$/.test(input.value)) {
        input.value = ''
        input.placeholder = "Nome inválido"
        input.style.borderColor = "#f00"
        input.style.outline = "#f00"
        input.onkeydown = function() {
            this.style.borderColor = "#999"
            this.style.outline = null
        }
        input.focus()
        return
    }
    var request = new XMLHttpRequest
    request.open("GET"
           , "mysqli_select_ajax.php?nome_cad=" + input.value
           , true)

    request.onreadystatechange = function() {
        if (request.readyState === 4) {
            if (request.status === 200) {
                input.value = ''
                if (request.response === "Nome já existe!") {
                    input.placeholder = "Troca o nome"
                    input.focus()
                }
                else {
                    input.placeholder = request.response
                    document.getElementById("input_email_cad").focus()
                }
            }
            else {
                /* Erro de requisição. */
            }
        }
    }
    request.send()
}