Complex roots of a polynomial

Question: Consider the equation: $(x-2)^6 + (x-4)^6 = 64$
This equation has two real roots $a, b$ and two pairs of complex conjugate roots $(p, q)$ and $(r, s)$.
Is $p + q = r + s$ or $pq=rs$?
The trivial real roots of the equation are $(2,4)$.
My question is, when there are two complex conjugate pairs of a polynomial, do the magnitude of the roots have any sort of relation? Is trivially trying to find them by substituting $x=a+ib$ (with $a=1$ in this case so that there remain no imaginary part on the LHS) the only method? This approach leads to an equation of the sixth degree in $b$.
Answer: Remark: if you want  $p+q=r+s$  and $pq=rs$ to hold simultaneously, then you cannot have 2 distinct complex conjugate pairs. This is because if
$$p = a+bi, \ q=a-bi$$ and
$$r = c+di, \ s=c-di,$$
then
$$p+q=r+s \implies a=c,$$
and
$$pq=rs \implies a^2+b^2=c^2+d^2,$$ and so $b=\pm d$.
Comment: So which one of the conditions is applicable for the equation, and how?
Comment: @SatD Is the original question that you posted the whole question, or is it part of something else? When we use "and" in math we usually want both conditions to hold, and in this case they can't, unless the complex roots have multiplicity 2.
Comment: I apologize for the 'and'. It's an 'or'.
Comment: @SatD I think you changed the wrong "and" to an "or". You should change the one between the equations, not the pair of points.
Answer: Let's substitute $y = x-3$. Then, the equation becomes:
$$(y+1)^6+(y-1)^6 = 64$$
Expanding the left side using the Binomial Theorem and doing a bit of simplification gives us:
$$(y^6+6y^5+15y^4+20y^3+15y^2+6y+1)+(y^6-6y^5+15y^4-20y^3+15y^2-6y+1) = 64$$
$$2(y^6+15y^4+15y^2+1) = 64$$
$$y^6+15y^4+15y^2-31 = 0$$
We know that $x = 2$ and $x = 4$ are roots of the original equation, so $y = \pm 1$ are roots of the new equation. Hence, $y^2-1$ is a factor of $y^6+15y^4+15y^2-31$. Factoring this out gives us:
$$(y^2-1)(y^4+16y^2+31) = 0$$
So the complex roots are the roots of $y^4+16y^2+31$. By completing the square, we have:
$$y^4+16y^2+31 = 0$$
$$y^4+16y^2+64 = 33$$
$$(y^2+8)^2 = 33$$
$$y^2+8 = \pm\sqrt{33}$$
$$y^2 = -8\pm\sqrt{33}$$
$$y = \pm i \sqrt{8\pm \sqrt{33}}$$
Therefore, the complex roots to the original equation are $x = 3 \pm i \sqrt{8\pm \sqrt{33}}$.
By setting $p = 3+i\sqrt{8+\sqrt{33}}$, $q = 3-i\sqrt{8+\sqrt{33}}$, $r = 3+i\sqrt{8-\sqrt{33}}$, $s = 3-i\sqrt{8-\sqrt{33}}$, we see that $p+q = 6 = r+s$ but $pq = 17+\sqrt{33} \neq 17-\sqrt{33} = rs$. Therefore, $p+q=r+s$ is true while $pq=rs$ is false.
Comment: If I only have paper and pen in the exam, how do I find the roots?
Comment: ^Oh, are you just trying to find the roots of the polynomial? Your question sounded like you wanted to know if there were any special relationships between the roots.
Comment: I believed that there existed a special relationship WHICH would give me the roots. The main question is finding which is correct, P+Q = R + S or PQ = RS
Comment: Ahh, so the problem asked you which of the two relationships were true for that specific polynomial, and you wanted to know how to figure that out. The second part of your question made it seem like you wanted to know if either relationship held for an all polynomials with 2 pairs of complex conjugate roots. I'll edit my answer so that it answers your actual question.

Complex roots of a polynomial


I have 2 problems with conditional probability, involving coins and dice

Question: Hi I have these problems:
A coin is tossed three times. What is the probability that exactly two heads
occur, given that
(a) the first outcome was a head?
(b) the first outcome was a tail?
(c) the first two outcomes were heads?
(d) the first two outcomes were tails?
(e) the first outcome was a head and the third outcome was a head?

Which I have done it like:
T1 T2 T3

H  H  H
H  H  T
H  T  H
H  T  T
T  H  H
T  H  T
T  T  H
T  T  T

I put all the outcomes, then by counting them by hand:
p(2H|T1=H)=2/4
p(2H|T1=T)=1/4
p(2H|T1=H,T2=H)=1/2
p(2H|T1=T,T2=T)=0
p(2H|T1=H,T3=H)=1/2

Is this correct? Then, is there another way of doing it? Counting by hand just feel wrong, there must be a formal way.
Then:
A die is rolled twice. What is the probability that the sum of the faces is
greater than 7, given that
(a) the first outcome was a 4?
(b) the first outcome was greater than 3?
(c) the first outcome was a 1?
(d) the first outcome was less than 5?

Again counting, this really feels so wrong, I'm expecting some formula to get them.
p(sum>7|D1=4)=3/6
p(sum>7|D1>3)=12/18
p(sum>7|D1=1)=0/6
p(sum>7|D1<5)=6/24

Am I correct? Thanks.
Comment: Your answer to `p(2H|T1=T)` is wrong (I didn't check any after that).
Answer: That is the correct "long" way to do it. Essentially any combinatorics problem could be solved this way with enough ink and paper or computing power. This seems a bit like homework, so I'll get you started in the right direction without giving the answer away completely. You've got a bunch of conditional probabilities $P(A|B)$ that you need to calculate. Use Bayes Theorem to write
$P(A|B)=\frac{P(A \mbox{ and } B)}{P(B)}$
Now finding these probabilities should be straightforward from the distribution of 3 coin flips. (Hint, it starts with a "B".)
Also, be careful to think about your joint probabilities (the "and"s). For example, the event of getting 2 heads and getting a heads on both the first and second flip is the same thing as getting a heads on both the first and second flip, which is straightforward to calculate.
Comment: Think of P(T1=H) as the probability of getting 1 heads in 1 flip. What you're getting from matlab is the probability of 1 heads in 3 flips. See the difference?
Comment: Yes I see it now, that is 4/8 the denominator, and the numerator, how?
Comment: Edited the question with another, well is kind of homework self-study.
Comment: The trick is to get the event A and B to mean something that you know how to calculate the probability for using the binomial distribution. For example, $p(2H|T1=H)$ can be written as $p(2H \mbox{ and } T1=H)/p(T1=H)$. Now the bottom one is easy to find, right? The top one, 2 heads and toss one is heads, can be thought of as the union of the event that toss one is heads, toss two is heads, and toss three is tails and the event that toss one is heads, toss two is tails, and toss three is heads. Computing these two probabilities is straightforward and adding them up gives you the numerator.
Comment: I don' get it, how? p(T1=H)=4/8 because we are fixing T1, isn't it? Then how do I get p(2H and T1). And how do i calculate p(T1=H) with the binomial is giving me 3/8, in matlab as binopdf(1,3,.5). :)


Creating a new root certificate with new key length on windows ad certificate services

Question: Due to new corporate guidelines I need to update the root certificate of my CA so the key length is 4096bits (Currently 2048bits).
My CA is AD integrated and currently running on our DC.
So now I am stuck at the point where I am not finding any kind of information if a simple "reenrollment" of the template of this CA is possible.
I have already had a look at this microsoft learning page but it looks like there is not really an explanation for what I need to do.
Do I need to recreate the CA?
Comment: The key length for issued certificates is normally specified in the configuration file when creating a request. The key length of the root CA is normally specified when setting up the CA. Sounds like you need to"renew"/ re-create your root CA certificate with a 4096 bit key length.
Comment: Hey, thanks for the feedback! It seems that not so much information are available out around my specific case. Yesterday I spended some time and got snapshots of my AD-Controllers where I tested the scenario "recreate the CA" and it worked pretty well.
Comment: So now I am going to schedule a maintenance for the upcomming week where the operation will be executed on the open heart ;D
Answer: In case someone will ever face the same problem I faced here is the solution without reinstalling the role.
Especially this article helped me: https://www.scriptinghouse.com/2022/09/how-to-renew-root-certificate-of-microsoft-ca-with-a-longer-validity-period.html
I just created a new capolicy.inf with the increased key length and afterwards prolonged the certificate of my CA.
Kind Regards
Bad Santa
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Extrema of a $\sigma$-additive function are attained.

Question: I've written down a proof for the following theorem which appears in Loeve's book of probability (page 86). I believe I'm missing something because Loeve's proof is much more complicated but I can't see where is my mistake:

If $\phi$ is $\sigma$-aditive function on a $\sigma$-field, then there
  exist sets C and D of the $\sigma$-field such that $\phi(C) = sup \ \phi(B)$ and $\phi(D) = inf \ \phi(B)$.

So, here is my proof: (we can assume that $\phi$ is finite)
Let's consider a sequence $A_n$ such that $\phi(A_n) > sup \ \phi(B) - 1/n$ for each $n \in \mathbb{N}$ which exist by the definition of supremum.
Let's take $A_n'=A_n\setminus\cup_{k=1}^{n-1}A_k'$ clearly $A_n'$ are disjoint and $\sum_{k=1}^{N}A_n'=A_N$.
It follows using $\sigma$-aditivity that:
$\phi(\cup_{k=1}^\infty A_k)=\phi(\sum_{k=1}^\infty A_k') = \sum_{k=1}^\infty \phi(A_n')= \lim_{N} \sum_{k=1}^N \phi(A_k')= \lim \phi(\sum_{k=1}^N A_k') = \lim \phi(A_N) \ge sup \ \phi(B)$
where the last equality follows taking limits in the first inequality of the proof.
Can you see any mistakes?
Comment: Where do you define B? Is it just some set in the $\sigma$-field?
Answer: That $A_N =\sum_{k=1}^N A_k '$ is only true if the $A_n$ form a non-decreasing sequence. In general, you will only have $\sum_{k=1}^N A_k ' = \bigcup_{k=1}^N A_k$, where the set on the right might be very different from $A_N$.
Also, there are typos in your definition of $A_k '$.


Probability and Stats (loaded coin)

Question: Smith is offered the following gamble: he is to choose a coin at random from a large collection of coins and toss it randomly.The proportion of the coins in the collection that are loaded towards a head is $p$. If a coin is loaded towards a head, then when the coin is tossed randomly, there is $\frac{3}{4}$ probability that a head will turn up and a $\frac{1}{4}$ probability that a tail will turn up. Similarly, if the coin is loaded towards tails, then there is a $\frac{3}{4}$ probability that a tail will turn up and a $\frac{1}{4}$ probability that a head will turn up. If Smith tosses a head, he loses \$$100$, if he tosses a tail, he wins \$$200$. Find the probability value $p$ for which Smith's gain is $0$ when taking the gamble.
Comment: This looks like a homework question. Will you please share what you have tried, or what you think the procedure should be? That way we know how to best answer your question.
Comment: You introduced $p$ as a proportion of coins; then in the end you call it a probability value. Presumably the missing link between the two is that the distribution for chosing a coin is implicitly assumed to be uniform?
Answer: I'm assuming the coins that are not loaded towards heads are loaded towards tails.  Write out the expected gain in terms of p, set it to 0, and solve.
Compute the expected gain in terms of P(heads) and P(tails), the overall probability of flipping heads, or tails, respectively.

 Expected gain = P(heads)(-100) + P(tails)(200).

We can then compute P(heads) and P(tails) in terms of p, the percentage of coins biased towards heads.

 P(heads) = (3/4)p + (1/4)(1-p)

P(tails):

 P(tails) = (1/4)p + (3/4)(1-p)

Now just solve for p:

 0 = (-100)[(3/4)p + (1/4)(1-p)] + 200[(1/4)p + (3/4)(1-p)]

Probability and Stats (loaded coin)


Minha aplicação MVC 5 insere no banco de dados, mas a view não exibe a lista de registros

Question: Aparece o seguinte erro: O item de modelo inserido no dicionário é do tipo'System.Collections.Generic.List`1[SistemaHome.Models.Usuario]', mas esse dicionário requer um item do tipo 'SistemaHome.Models.Usuario'.
Já pesquisei por aqui mesmo sobre o erro e a solução de alterar na view para List ao invés de IEnumerable não resolveu. Eu consigo inserir no banco, porque a minha Action e View de Create funcionam,  porém a Index não.
Minha Controller:
namespace SistemaHome.Controllers
{
    public class UsuariosController : Controller
    {
        private Banco db = new Banco();
    // GET: Usuarios
    public ActionResult Index()
    {
        return View(db.Usuario.ToList());
    }

    // GET: Usuarios/Details/5
    public ActionResult Details(int? id)
    {
        Usuario usuario = new Usuario();

        if (id > 0)
        {
            usuario = db.Usuario.Find(id);

            if (usuario == null)
            {
                throw new Exception("O registro " + id + " não foi encontrado");
            }
        }
        return View(usuario);
    }

    // GET: Usuarios/Create
    public ActionResult Create()
    {
        var user = new Usuario();

        return View();
    }

Minha View Index:

Meu Model:
[Table("Usuario")]
    public partial class Usuario
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Usuario()
        {
            HistoricoProposta = new HashSet();
        }
    [Key]
    [Display(Name ="Código do Usuário")]
    public int IDusuario { get; set; }

    [Required]
    [StringLength(100)]
    [Display(Name ="Nome Completo")]
    public string Nome { get; set; }

    [Required]
    [StringLength(50)]
    [Display(Name ="CPF")]
    public string CPF { get; set; }

    [Required]
    [Display(Name ="Data de Nascimento")]
    [DataType(DataType.Date)]
    public DateTime Nasc { get; set; }

    [Required(ErrorMessage = "Informe um usuário válido", AllowEmptyStrings = false)]
    [StringLength(40)]
    [Display(Name ="Login")]
    public string Login_Nome { get; set; }

 //   [Required(ErrorMessage = "Senha Incorreta", AllowEmptyStrings = false)]
    [DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
    [StringLength(10, MinimumLength = 4)]
    [Display(Name ="Senha")]
    public string Senha { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<HistoricoProposta> HistoricoProposta { get; set; }
}

Minha classe de conexão com o Banco:
  public partial class Banco : DbContext
    {
        public Banco()
            : base("name=Banco")
        {
        }
    public virtual DbSet<Categoria> Categoria { get; set; }
    public virtual DbSet<Fornecedor> Fornecedor { get; set; }
    public virtual DbSet<HistoricoProposta> HistoricoProposta { get; set; }
    public virtual DbSet<PerfilUsuario> PerfilUsuario { get; set; }
    public virtual DbSet<Proposta> Proposta { get; set; }
    public virtual DbSet<StatusTabela> StatusTabela { get; set; }
    public virtual DbSet<Usuario> Usuario { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Categoria>()
            .Property(e => e.Tipo)
            .IsUnicode(false);

        modelBuilder.Entity<Fornecedor>()
            .Property(e => e.RazaoSocial)
            .IsUnicode(false);

        modelBuilder.Entity<Fornecedor>()
            .Property(e => e.Cnpj)
            .IsUnicode(false);

        modelBuilder.Entity<Fornecedor>()
            .Property(e => e.Cidade)
            .IsUnicode(false);

        modelBuilder.Entity<PerfilUsuario>()
            .Property(e => e.PerfilTipo)
            .IsUnicode(false);

        modelBuilder.Entity<Proposta>()
            .Property(e => e.NomeProposta)
            .IsUnicode(false);

        modelBuilder.Entity<Proposta>()
            .Property(e => e.Descricao)
            .IsUnicode(false);

        modelBuilder.Entity<Proposta>()
            .Property(e => e.ValorProposta)
            .HasPrecision(18, 0);

        modelBuilder.Entity<Proposta>()
            .Property(e => e.LocalArquivo)
            .IsUnicode(false);

        modelBuilder.Entity<StatusTabela>()
            .Property(e => e.StatusNome)
            .IsUnicode(false);

        modelBuilder.Entity<Usuario>()
            .Property(e => e.Nome)
            .IsUnicode(false);

        modelBuilder.Entity<Usuario>()
            .Property(e => e.CPF)
            .IsUnicode(false);

        modelBuilder.Entity<Usuario>()
            .Property(e => e.Login_Nome)
            .IsUnicode(false);

        modelBuilder.Entity<Usuario>()
            .Property(e => e.Senha)
            .IsUnicode(false);

Como posso resolver isso? Alguém pode me ajudar?
Comment: Pode ajustar o código? Ele está desformatado dentro da tag de script. Aproveita e coloca para nós a sua view da index.
O que estou entendendo é que você está colocando somente o IEnumerable...
Mas precisa colocar a sua classe em Lista. um exemplo: @model List
Comment: Coloquei uma imagem da minha view index. Sobre sua sugestão eu testei, porém não resolveu... @VainerCesario
Answer: Tente forçar a o retorno de um IEnumerable.
var usuarios = db.Usuario.ToList();
return usuarios.AsEnumerable();

Answer: Neste comando você não está buscando do banco o seu modelo.
Você está pegando a instância do modelo de usuários e dando um ToList().
public ActionResult Index()
{
    return View(db.Usuario.ToList());
}

Você precisa fazer uma consulta.
public ActionResult Index()
{
   return View(db.Usuario.FindAll().ToList());
}

Na tua view, que tu postou a foto vai ficar no topo a lista desse teu Model:
@model List<SistemaHome.Model.Usuario>

Comment: muito obrigada pela dica, porém não funcionou. Eu refiz a minha aplicação novamente mantendo o código original e o sistema funcionou. Acredito que tenha sido um bug do próprio VS, porque o erro que ele estava passando era algo que estava declarado corretamente.


How do you solve the equation $0.5^x = 2^x + 3$?

Question: I need help with the following problem: $0.5^x = 2^x + 3$
I know the answer is -1.72, but I have to explain step by step how to solve it and I'm not sure how. I know you're supposed  to take the log of each side, but I don't know what to do with the 3. How do you solve this problem?
Answer: Rewrite the left-hand side to $\frac{1}{2^x}$, and then set $y=2^x$. This gives you a quadratic equation in $y$, which you can solve; finally $x=\log_2 y$.
Answer: The equation is $1/2^x=2^x+3$ which gives $2^{2x}+3.2^x-1=0$
Let $a=2^x$ then $a^2+3a-1=0$. Solve for $a$, take the positive root, and solve for $x$ by setting $x=\log_2(a)$.
Answer: $0.5^x=2^x +3$
$(\frac{1}{2})^{x}=2^x + 3$
$\frac{1}{2^{x}}=2^x + 3 $ $/2^x$
$1= 2^2x + 3* 2^x$
Now you make substitution, in these exercises method that is often used.
$y=2^x$
Our eqation looks like this:
$1=y^2 +3y$
$y^2 +3y-1=0$
$y=\frac{-3\pm \sqrt{9+4}}{2}$
$y=\frac{-3\pm \sqrt{13}}{2}$
$y_{1}=\frac{-3-\sqrt{13}}{2}$  or $ y_{2}=\frac{-3+ \sqrt{13}}{2}$
As we defined y= 2x, we know that it can not be negative number,so y1 is incorrect, and we continue only with y2.
$y=2^x$
$2^x=\frac{-3+ \sqrt{13}}{2} /\log_{2}$
(log2(2x)=x)
$x=\log_{2}\frac{-3+\sqrt{13}}{2}$
put it in calculator and you get :
x= -1.723
Comment: Welcome to Math Stackexchange! Did you know that you can type your math by surrounding it by `$` symbols?
Answer: you should be knowing $0.5^x=\left(\frac 12\right)^{x}=\frac 1{2^x}$, hence
$$0.5^{x}=2^x+3$$
$$\frac 1{2^x}=2^x+3$$
$$(2^{x})^2+3\cdot 2^x-1=0$$
Now, solving the quadratic equation in terms of $2^x$ as follows
$$2^x=\frac{-3\pm\sqrt{(3)^2-4(1)(-1)}}{2(1)}=\frac{-3\pm\sqrt{13}}{2}$$
But $2^x>0\ \ \forall\ \  \ x\in \mathbb{R}$ hence $$2^x=\frac{-3+\sqrt{13}}{2}$$
$$\ln 2^x=\ln\left(\frac{-3+\sqrt{13}}{2}\right)$$
$$x\ln 2=\ln\left(\frac{\sqrt{13}-3}{2}\right)$$
$$x=\color{red}{\frac{\ln\left(\frac{\sqrt{13}-3}{2}\right)}{\ln(2)}}$$


Why the regression coefficient for normalized continuous variable is unexpected when there is dummy variable in the model?

Question: I am doing a numerical experiment about linear regression modeling with presence of both continuous and categorical variables. As done in classical regression modeling practice, the categorical variable is firstly converted to several dummy variables, and part of which are retained for further modeling.
The model the numerical experiment followed is:
$$y=\beta_0 + \beta_1 x_2 + \beta_2 z + \varepsilon$$
where $\beta_0=0.8$, $\beta_1=-1.2$, $\beta_2=1.3$. The first covariate $x$ is uniformly distributed, i.e. $x \sim U(0, 1)$. The second covariate $z$ is a dummy variable, for which I drew from a standard normal distribution and convert it to a dummy variable by comparing it with 0, i.e. $z \in \{0, 1\}$ (please see the MATLAB code given below). The error term $\varepsilon$ is drawn from a standard normal distribution.
For comparison, the first covariate $x$ was transformed into a newly uniform distribution $x_2 \sim U(1.2, 3)$.
Then I obtained the response y using the model above (note: The model used $x_2$ but not $x$ when producing $y$). And linear regression was conducted between $y \sim x + z$, and $y \sim x_2 + z$ in MATLAB. I did many experiments, and visualize the results as shown by the figure. I found that when the model is $y \sim x_2 + z$, the coefficient $\beta_1$ can be correctly estimated, but not as expected when the model is $y \sim x + z$. For $\beta_2$, regression of both the two models can give correct estimates.
My question is: when we do linear regression, whether should we normalize the data? What is the theoretical explanation for the results of the experiments above?
The following is my MATLAB code:
clear;
clc;

nbpt = 50;
res1 = zeros(nbpt, 1);
res2 = zeros(nbpt, 1);
N = 1000:1000:50000;
for inbobs = 1:nbpt
   nbobs = N(inbobs);
   ntrial = 100;
   temp1 = [];
   temp2 = [];

   for i = 1:ntrial
       x = rand(nbobs, 1);
       m = 1.2;
       n = 3;
       x2 = 1.8*x + m;

       z = randn(nbobs, 1);
       z = z > 0;

       a = 0.8;
       b = -1.2;
       c = 1.3;
       y = a + b*x2 + c*z + randn(nbobs, 1);

       X1 = [ones(nbobs, 1), x2, z];
       [b1, bint1, r1, rint1, stats1] = regress(y, X1);

       X2 = [ones(nbobs, 1), x, z];
       [b2, bint2, r2, rint2, stats2] = regress(y, X2);

       temp1 = [temp1; b1(2)];
       temp2 = [temp2; b2(2)];

  end
  res1(inbobs, 1) = mean(temp1);
  res2(inbobs, 1) = mean(temp2);
end

figure;
subplot(1, 2, 1);
plot(N, res1, 'o-');ylim([-4, 4]);
subplot(1, 2, 2);
plot(N, res2, 'o-');ylim([-4, 4]);
axis tight;

Answer: Thank you for providing a MRE. Forgive me if I try to answer without directly working with it. It's been a while since I used Matlab, and never for stats.
Looking at your code, I see that you define the variable x2 from x1 with
m = 1.2;
x2 = 1.8*x + m;

Thus, the only difference between the two regression equations is
$$y = \beta_0 + \beta_1 x + \beta_2 z + \eta$$
and
$$\begin{align}
y' & = \beta_0' + \beta_1' x + \beta_2' z + \eta \\
& = (\beta_0 + 1.2) + 1.8\beta_1' x + \beta_2' z + \eta
\end{align}$$
So, if the regression is done correctly, you should get the same value for  $\beta_2$, and
$$\beta_0' - \beta_0 = 1.2$$
$$\beta_1'/\beta_1 = 1.8$$
If this is not what you are seeing, then you might have a mistake in your code.
Also, the fact that one of your plots looks constant and the other random is a bit suspect.
Here is a simple version in R. Please tell me if you think I have done the same simulation you intended to:
set.seed(1234)

N = 10000
b_0 = 0.8
b_1 = -1.2
b_2 = 1.3

x1 = runif(N, 0,1)
x2 = runif(N, 1.2, 3)

z = rnorm(N)>0

y1 = b_0 + b_1*x1 + b_2*z + rnorm(N)
y2 = b_0 + b_1*x2 + b_2*z + rnorm(N)

lm(y1 ~ x1 + z)
#>
#> Call:
#> lm(formula = y1 ~ x1 + z)
#>
#> Coefficients:
#> (Intercept)           x1        zTRUE
#>       0.784       -1.203        1.344

lm(y2 ~ x2 + z)
#>
#> Call:
#> lm(formula = y2 ~ x2 + z)
#>
#> Coefficients:
#> (Intercept)           x2        zTRUE
#>      0.7987      -1.1970       1.3120

Created on 2020-07-22 by the reprex package (v0.3.0)
Comment: Thank you. You help me solve my puzzle. The relation for the intercept term should be $\beta_0^{'} = \beta_0 + 1.2\beta_1$. For the R code you provided, both the response variables should be y2 in the function 'lm'. From the experiments above, we see the normalization matters, probably making the estimate of coefficients not equal to the expected one. So should I normalize the continuous covariate to [0, 1] before linear regression?
Comment: The relation you give for the betas implies some very complex differences between the models, far beyond what it sounds like you are wanting to test. I suggest you read up on linear regression and the inherent assumptions. Two important requirements in linear regression are that the variables are independent and that the errors are normally distributed. You should also read up on how to calculate betas for different "levels" of categorical variables. You should not have to normalize anything prior to doing linear regression.
Comment: Thank you. I will read it.


serving html remotely from mac os x

Question:
TL;DR: simple HTTP server is accessible locally, but how can I make it available remotely in order to view the served files from another computer on the network?

I'm using a zero-configuration command line HTTP server to serve up a web site (a directory containing an index.html file).
I use either python -m SimpleHTTPServer or the node.js http-server (installed from npm).
Accessing the web site locally is fine. If I serve the site on port 8090, then I can see it at localhost:8090 as expected.
But I'm unable to access it remotely, and herein lies my problem. I'd like the web site to be accessible on my network. (I have to be on VPN to access the server.)
If I try to telnet to the port, I get telnet: connect to address 192.168.122.215: Connection refused.
Btw, port 8080 is already being used by Jenkins, which is why I'm using 8090 (not sure if that makes any difference).
I've seen https://stackoverflow.com/questions/14469267/node-js-on-mac-access-a-node-js-web-server-from-another-computer, but it doesn't help. When I run the command http-server . -p 8090 I get Starting up http-server, serving . on: http://0.0.0.0:8090, which I believe means it should be accessible remotely.
I'm not really very familiar with networking/ports/etc so any guidance is greatly appreciated. I assume it's something to do with the port not being open, or some firewall setting, but this is alien to me.
Is what I'm trying to do possible? Can anyone help me make this web site available remotely on the network? Thanks for reading!
Answer:
Run netstat -lpn and verify that the web server port you want to use is in deed running on 0.0.0.0 instead of localhost.  If it's not then we need to edit the configs to listen on "*" and then restart the web server daemon.
If you have a firewall on your machine, just for a few minutes here to troubleshoot, turn it completely off so that we can eliminate it as a source of our problem.  If we find that firewall is the problem we can make sure the right rules are in there for the port your working on.
Comment: Thanks for your reply. It turns out I was being a complete muppet, which is very embarrassing. I have an `alias` for connecting via SSH so never type in the IP when connecting, and then I was getting my IP addresses mixed up. I spent ages trying to figure out what was wrong, and in the end it turned out to be my brain that was at fault. Anyway, it was when I ran `netstat` that I noticed the Local Address, then checked my `alias` and realised my mistake. So it was your question that led me to the solution.
Comment: 17 years doing web development, and I still find my self doing completely idiotic things.. It never ends, keeps you humble lol

serving html remotely from mac os x


Can't load FXML in Clojure using FXMLLoader

Question: I'm trying to implement the basic JavaFX example shown here: http://docs.oracle.com/javafx/2/get_started/fxml_tutorial.htm .  I was able to get the basic stuff working (programmatically creating the gui) and using css, but I'm having trouble with the FXMLLoader.
The java version is this:
@Override
public void start(Stage stage) throws Exception {
   Parent root = FXMLLoader.load(getClass().getResource("fxml_example.fxml"));

    stage.setTitle("FXML Welcome");
    stage.setScene(new Scene(root, 300, 275));
    stage.show();
}

I'm not a Java expert, but I don't think an FXMLLoader object is instantiated ie. there is not a new FXMLLoader(); statement.  So where is the load coming from?
When i try the following clojure code:
(ns jfxtwo.core
  (:gen-class
   :extends javafx.application.Application)

  (:import (javafx.application Application)
           (javafx.fxml FXMLLoader)
           (javafx.scene Parent Scene)
           (javafx.stage Stage)))

(defn -main []
  (javafx.application.Application/launch jfxtwo.core (into-array String [])))

(defn -start [this primaryStage]
  (let [loc (clojure.java.io/resource "fxml_example.fxml")
        root (.load FXMLLoader ^java.net.URL loc)
        scene (Scene. root 300 250)]
    (.setScene primaryStage scene)
    (.show primaryStage)))

...i get Caused by: java.lang.IllegalArgumentException: No matching method found: load for class java.lang.Class .
So I put a dot after the FXMLLoader to create an instance: (FXMLLoader.) I get this: ClassCastException java.net.URL cannot be cast to java.io.InputStream
So this tell me I'm onto something since one of the load methods for FXMLLoader supports an InputStream.  I tried forcing the compiler to know the resource is a java.net.URL because that's one of the supported overloads for FXMLLoader.load, by placing the call to (clojure.java.io/resource...) directly in the call to (.load...) but it still doesn't like it (I knew it was a long shot).  I also tried type-hinting, (.load (FXMLLoader.) ^java.net.URL loc) and (.load (FXMLLoader.) #^java.net.URL loc), but no dice; it still tries to use the java.io.InputStream version of load.
There is also the getClass() call in java which I think is getting the superclass of Application, but I'm not sure what to do with that in clojure-land.
Any ideas on how to load the fxml file?
After that, the java code has @FXML annotation for allowing the FXML into private class members.  Is this necessary in clojure (java code breaks when I remove it)?  The @Override annotation doesn't seem to be used in clojure.
thanks
Answer: Given the Java syntax, the load method being called here appears to be a static method of the FXMLLoader class. To call static methods in Clojure, you need to use (ClassName/methodName args...) syntax:
(FXMLLoader/load ...)

(Just checked: FXMLLoader has both static and instance load methods with multiple signatures. You'll want to call the same method the Java code does; static methods will be called with the FXMLLoader.load syntax in Java, instance methods -- someFXMLLoaderInstance.load.)
As for the getClass method call, it's target is implicitly this in Java; in Clojure, you'll have to make the target explicit ((.getClass this)).
Comment: Thanks, using static method worked.  However when I tried  `(.getResource (.getClass this) "fxml_example.fxml")` directly instead of `clojure.java.io/resource` it returned nil and the load failed.  That's fine I'll stick with what works.
Answer: I was able to work around my problem by creating the FXMLLoader separately from setting the location.
(defn -start [this primaryStage]
  (let [loc (clojure.java.io/resource "fxml_example.fxml")
        fxmlloader (FXMLLoader.)]
    (.setLocation fxmlloader loc)
    (let [root (.load fxmlloader )
          scene (Scene. root 300 250)]
      (.setScene primaryStage scene)
      (.show primaryStage))))


Android custom Application class with set up at manifest don't work with ClassCastException

Question: I don't know what is problem, because in my other projects it is work. I'm use custom application class and register it in my manifest file:
package ru.jooogle.sunshine.admin_pc.sunshine_reborn;

import android.app.Application;
import android.content.Context;
import ru.jooogle.sunshine.admin_pc.sunshine_reborn.model.network.NetworkService;

    public class SunshineApplication extends Application {
        private NetworkService networkService;

        public static SunshineApplication get(Context context) {
            return (SunshineApplication) context.getApplicationContext();
        }

        public NetworkService getNetworkService() {
            if (networkService == null) {
                networkService = new NetworkService();
            }

            return networkService;
        }
    }

And manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="ru.jooogle.sunshine.admin_pc.sunshine_reborn">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name=".SunshineApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".SunshineActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

In Activity onCreate i do:
SunshineApplication sunshineApplication = SunshineApplication.get(this);

and i get ClassCastException:
java.lang.ClassCastException: android.app.Application cannot be cast to ru.jooogle.sunshine.admin_pc.sunshine_reborn.SunshineApplication

I don't know what is it, help, please.
Comment: Please post the entire Java source file for `SunshineApplication`.
Comment: I post all code that's my project of SunshineApplication
Comment: You are missing the `package` line and the `import` statements, at minimum. Since those may be the source of your problem, I suggest that you edit your question and put in the complete contents of `SunshineApplication.java`.
Comment: I added full text now
Comment: one required change getApplication instead of getApplicationContext
Comment: Ok, but i created now new project where i use this code, and it work. I don't know what is it
Comment: That is very strange. It is as if your `android:name` in the `` element is being ignored. If you have not done so already, clean the project (e.g., from the Android Studio main menu). You might also look at the merged manifest to confirm that your `android:name` attribute is in there and is not somehow being replaced.
Comment: thanks, but i does it, not work. May be this is android studio bag
Comment: I found solution, friends. Thanks
Answer: I'm  found solution. In this project i use experimental feature buildCach in gradle.properties :
android.enableBuildCache=true

if comment this line and rebuild project, problem gone


C# Diferença entre BeginAccept e AcceptAsync

Question: Qual a diferença entre as duas formas assíncronas? Qual tem melhor performance tratando de sockets e manipulação de milhares de conexão simultaneamente?
Exemplo para BeginXXX: http://msdn.microsoft.com/en-us/library/5w7b7x5f(v=vs.110).aspx
Exemplo para XXXAsync: http://msdn.microsoft.com/en-us/library/system.net.sockets.socketasynceventargs.aspx
Comment: É interessante porque li na documentação que o Async é uma melhoria em relação ao Begin.
Comment: Resposta no Stackoverflow em Inglês: http://stackoverflow.com/questions/24174423/c-sharp-socket-performance-with-net-4-5-async-vs-async-vs-begin
Answer: Nenhuma. Uma foi feita para atender um "padrão" de programação assíncrona e o outro outra.
Veja: http://msdn.microsoft.com/en-us/library/jj152938(v=vs.110).aspx
A primeira "Begin" é para atender a APM (Asyncronous Programming Model) e a segunda (BlahBlahBlahAsync) para atender a TAP (Task-based asyncronous pattern). A de Tasks é mais nova e mais simples de usar.
Em tempo, no meu blog: http://ericlemes.com você acha exemplos de socket server com ambos os cenários e algumas explicações sobre os ganhos obtidos com I/O assícrono em geral.
Answer: Em questão de performance, ambos são iguais, a conexão é feita usando sempre a classe "Socket".
Porém no exemplo do BeginXXX, é uma solução mais simples, usando a forma básica do uso de Async.
No exemplo do XXXAsync é um exemplo baseado em eventos, este exemplo é mais completo porque nesse exemplo ele já espera até 100 conexões simultâneas como pode ser visto nessa linha:
<code>listenSocket.Listen(100);
</code>
Para descrição do que você precisa, você poderia usar qualquer uma dessas soluções, porém a do XXXAsync já está mais próxima e preparada para o que você quer, repare que ele já é um exemplo de um servidor, basta implementar o a ações desejadas.
Agora, dependendo do que você for fazer, e de quem for consumir, você pode eliminar diversas preocupações da camada de rede usando WCF ou até mesmo WebAPI. Mas ai vai depender dos requisitos do projeto.


Delete directory from private folder programatically?

Question: I'm using D8, and am writing a cron task to remove old backups from my private files directory. The backups are generated in private://db_backups/date-of-backups/backup.gz. The following code is properly deleting the actual backup files, but it is not removing the parent date directory. I am not receiving any errors in the drupal or server logs, so I'm a bit lost as to what's causing the failure.
function custom_changes_cron() {
    drupal_set_message(t('Custom cron function has run.'), 'status');
    $private_path = PrivateStream::basePath();
    $interval = strtotime('-430 hours');
    foreach(glob($private_path . '/backup_db/*' , GLOB_ONLYDIR) as $folder) {
        if (filemtime($folder) <= $interval ) {
            $files = glob("$folder/*"); // get all file names
            foreach($files as $file){ // iterate files
              if(is_file($file))
              unlink($file); // delete file
            }

            // Have tried both of the following
            rm_dir($folder);
            drupal_rmdir($folder);
        }
    }
}

Comment: Why not kill the whole tree?  http://stackoverflow.com/questions/3349753/delete-directory-with-files-in-it
Comment: I'm thinking there is some other file in there (hidden) or directory that is preventing the main directory from being removed.
Answer: Note that glob('*') ignores all hidden files by default. This means it does not return files that start with a dot (e.g. .file).  If you want to match those files too, you can use {,.}*  as the pattern with the GLOB_BRACE flag. This will include the special cases . and .. so you need to exclude those by using {,.}[!.,!..]*.
So in summary, try the following:
$files = glob("$folder/" . '{,.}[!.,!..]*',GLOB_MARK|GLOB_BRACE);

As a sidenote: you mention you tried using rm_dir. I assume you mean rmdir?
Comment: Thanks, that did indeed do the trick. I didn't see any hidden files in there when I checked manually, but I also had the feeling that this may have been the culprit. I also did mean `rmdir` and not `rm_dir`. Using `file_unmanaged_delete_recursive` as suggested by Jigar also worked without the need for manually deleting the files, but I wanted to award you the bounty since your answer may be more widely applicable to people who come across it.
Answer: Interesting. Did you try using the following functions? I think one of them should work:

file_unmanaged_delete_recursive
drupal_rmdir

Make sure that PHP has permission to delete the directories. To test this, delete the contents of one of the backup directories manually and then try one of the above functions on it - this will help you understand whether the directory deletion is causing the problem or something else inside the directory.
Alternatively, you can set up a server-side cron in a shell script if you are considering that.
BTW, I notice you are using drupal_set_message() - it will not work from within a cron due to some session-specific reasons. Use \Drupal::logger('custom')->debug('Description'); - the message will appear in the Reports > Recent log messages menu.
Hope it helps!
Comment: Thanks for the input! PHP did have the proper permissions, and `drupal_rmdir` was not working for me, probably because of some hidden files that I was missing. `file_unmanaged_delete_recursive` worked without needing to manually iterate through the files in the folders. That being said, I awarded the bounty to the other answer since they addressed the issue with my specific code. Your suggestion would probably be the way to go in general, though.


Delete everything after a certain line in bash

Question: I was wondering if there was a way to delete everything after a certain line of a text file in bash. So say there's a text file with 10 lines, and I want to delete every line after line number 4, so only the first 4 lines remained, how would I go about doing that?
Comment: simplest is `head -4 oldfile > newfile`, then `mv newfile oldfile`.  That's not "in place", but not sure what that would be necessary anyway.
Comment: post the input example
Comment: What do you mean input example? There would be a file with a lot of lines, named say file.txt, and I just want to trim all text after a certain line.
Answer: You can use GNU sed:
sed -i '5,$d' file.txt

That is, 5,$ means the range line 5 until the end, and d means to delete.
Only the first 4 lines will remain.
The -i flag tells sed to edit the file in-place.
If you have only BSD sed, then the -i flag requires a backup file suffix:
sed -i.bak '5,$d' file.txt

As @ephemient pointed out, while this solution is simple,
it's inefficient because sed will still read the input until the end of the file, which is unnecessary.
As @agc pointed out, the inverse logic of my first proposal might be actually more intuitive. That is, do not print by default (-n flag),
and explicitly print range 1,4:
sed -ni.bak 1,4p file.txt

Another simple alternative, assuming that the first 4 lines are not excessively long and so they easily fit in memory, and also assuming that the 4th line ends with a newline character,
you can read the first 4 lines into memory and then overwrite the file:
lines=$(head -n 4 file.txt)
echo "$lines" > file.txt

Comment: Note that on *BSD (including OS X), `sed -i '5,$d' file.txt` will use `'5,$d'` as the backup suffix and `file.txt` as the expression, which is not what you want. There is no simple portable way to perform an in-place `sed` without creating backup files.
Comment: Thanks, this answered my question.
Comment: The logical contrary version of this answer seems more intuitive:  `sed -ni.bak '1,4p' file.txt`
Answer: Minor refinements on Janos' answer, ephemient's answer, and cdark's comment:

Simpler (and faster) sed code:
sed -i 4q file

When a filter util can't directly edit a file, there's
sponge:
head -4 file | sponge file

Most efficient for Linux might be truncate -- coreutils sibling util to fallocate, which offers the same minimal I/O of ephemient's more  portable, (but more  complex), dd-based answer:
truncate -s `head -4 file | wc -c` file

Answer: If I don't know the line number, merely the line content (I need to know that there is nothing below the line containing 'knowntext' that I want to preserve.), then I use.
sed -i '/knowntext/,$d' inputfilename

to directly alter the file, or to be cautious
sed '/knowntext/,$d' inputfilename > outputfilename

where inputfilename is unaltered, and outputfilename contains the truncated version of the input.
I am not competent to comment on the efficiency of this, but I know that files of 20kB or so are dealt with faster than I can blink.
Comment: This is great, but please note that the line containing "knowntext" will also be removed.
Answer: The sed method that @janos is simple but inefficient. It will read every line from the original file, even ones it could ignore (although that can be fixed using 4q), and -i actually creates a new file (which it renames to replace the original file). And there's the annoying bit where you need to use sed -i '5,$d' file.txt with GNU sed but sed -i '' '5,$d' file.txt with BSD sed in order to remove the existing file instead of leaving a backup.
Another method that performs less I/O:
dd bs=1 count=0 if=/dev/null of=file.txt \
    seek=$(grep -b ^ file.txt | tail -n+5 | head -n1 | cut -d: -f1)

grep -b ^ file.txt prints out byte offsets on each line, e.g.
$ yes | grep -b ^
0:y
2:y
4:y
...

tail -n+5 skips the first 4 lines, outputting the 5th and subsequent lines
head -n1 takes only the next line (e.g. only the 5th line)
After head reads the one line, it will exit. This causes tail to exit because it has nowhere to output to anymore. This causes grep to exit for the same reason. Thus, the rest of file.txt does not need to be examined.
cut -d: -f1 takes only the first part before the : (the byte offset)
dd bs=1 count=0 if=/dev/null of=file.txt seek=N

using a block size of 1 byte, seek to block N of file.txt
copy 0 blocks of size 1 byte from /dev/null to file.txt
truncate file.txt here (because conv=notrunc was not given)

In short, this removes all data on the 5th and subsequent lines from file.txt.
On Linux there is a command named fallocate which can similarly extend or truncate a file, but that's not portable.

UNIX filesystems support efficiently truncating files in-place, and these commands are portable. The downside is that it's more work to write out.
(Also, dd will print some unnecessary stats to stderr, and will exit with an error if the file has fewer than 5 lines, although in that case it will leave the existing file contents in place, so the behavior is still correct. Those can be addressed also, if needed.)
Comment: A simpler way than `seek=$(grep -b ^ file.txt | tail -n+5 | head -n1 | cut -d: -f1)` is `seek=$(head -n4 file.txt | wc -c | tr -d ' ')`
Answer: Using GNU awk (v. 4.1.0+, see here). First we create a test file (NOTICE THE DISCLAIMER):
$ seq 1 10 > file     # THIS WILL OVERWRITE FILE NAMED file WITH TEST DATA

Then the code and validation (WILL MODIFY THE ORIGINAL FILE NAMED file):
$ awk -i inplace 'NR<=4' file
$ cat file
1
2
3
4

Explained:
$ awk -i inplace '   # edit is targetted to the original file (try without -i ...)
NR<=4                # output first 4 records
' file               # file

You could also exit on line NR==5 which would be quicker if you redirected the output of the program to a new file (remove # for action) which would be the same as head -4 file > new_file:
$ awk 'NR==5{exit}1' file  # > new_file

When testing, don't forget the seq part first.


Generate random unix timestamp

Question: How I can generate random unix timestamp in specific times. For example get random unix time  mean between today and tomorrow.
Comment: maybe you can find something useful here: http://stackoverflow.com/questions/363681/java-generating-random-number-in-a-range
Answer: long randomEpoch = epoch1 + Math.abs(new Random().nextLong()) % (epoch2-epoch1);

where epoch1 and epoch2 are the two times.
Comment: very good! I did: new Date(Math.abs(new Random().nextLong()) % new Date().getTime()) to get a random date between 1/1/1970 to today
Answer: Get the needed range by generating two timestamps. Subtract the difference (absolute value). Get a random number between 0 and 1. Multiply the difference by the random number. Add the result to the earlier timestmap.
Answer: This code specifically gets a random time between today and tomorrow.
public Date randTime(){
    Date now = new Date();
    Date today = new Date(now.getFullYear(), now.getMonth(), now.getDay(), 0, 0, 0, 0);
    return new Date(today.getTime() + (long)(Math.random() * 86400000));
}

Comment: I think you mean `(long)(Math.random() * 86400000)`
Comment: Indeed. milliseconds, not seconds XD

Generate random unix timestamp


Gulp + Bower - Como importar os componentes instalados pelo Bower para meu projeto final

Question: Estou começando a gerenciar meus componentes com Bower e estou com uma dúvida:
Utilizo o Gulp para executar tarefas como compilar meus arquivos less, concatenar javascripts, só que como os componentes do Bower ficam dentro do bower_components não sei como posso organizar o gulpfile.js do meu próprio projeto para importar os arquivos que os componentes usam sem precisar de muito trabalho manual.
Existe algum paradigma de organização / importação de tais componentes?
Espero ter sido claro. Obrigado.
Answer: Eu não utilizo Bower, mas o Gulp te permite designar mais de um path para buscar os arquivos onde tarefas serão executadas, logo, você poderia fazer algo como:
// gulpfile.js
// ...

gulp.task('minha-task', function() {
    return gulp.src(['path/meus/scripts/*.js', 'path/bower_components/**/*.js'])
        .minhasTasks() //...
});

A linha:
return gulp.src(['path/meus/scripts/*.js', 'path/bower_components/**/*.js'])

chama um array (neste caso, com 2 paths) e vai rodar sua task em qualquer arquivo achado dentro desses dois locais.
Note que eu adicionei ** no path onde ficariam os componentes importados com o Bower, porque desta forma mesmo que eles estejam divididos por subpastas, o Gulp ainda conseguiria identificá-los e rodar os seus arquivos .js.
Answer: Você pode criar uma tarefa para copiar determinado arquivo para o destino desejado. No caso de JS, também pode utilizar o gulp-concat para concatenar todos os arquivos JS e no projeto final ter apenas um arquivo.js com tudo concatenado e minificado.


Implementing vector (dynamic array) in C - functions and main file

Question: This is a memory allocation program: I have to complete a given code (main and function file) given a header that has to implement the C++ vector functions in C. Here is the expected output (but of course the code has to be generalized enough not to just copy the output):

Vector vc1 now contains 5 characters (capacity=8): ciao
Vector vc2 now contains 9 characters (capacity=16): ciaociao
Vector vc2 now contains 11 characters (capacity=16): ciao--ciao
Vector vi1 now contains 10 integers:  0 1 2 3 4 5 6 7 8 9
Vector vc2 now contains 21 characters (capacity=32): ciao-0123456789-ciao
Vector vc2 now contains 5 characters (capacity=8): ciao
Vector vd1 now contains 10 doubles (capacity=16):  9.5 8.5 6.5 5.5 3.14159 4.5 3.5 2.5 1.5 0.5
Vector vd1 now contains 1 double (capacity=2):  6.28318
Vector vi1 now contains 2 integers (capacity=4):  0 9

I can only modify the code between the "TO BE DONE START" and "TO BE DONE END". I need to modify both the function file and the main file in order to make the program work.
Here is the function file (vector.c), and what I've already done is commented on the side with "THIS IS WHAT I'VE ADDED":
#include "vector.h"

void fail(const char* msg){
    fprintf(stderr,"\nERROR: %s\n\n",msg);
    exit(1);
}

void * check_a(void*p){
    if ( p == NULL )
        fail("check_a(): NULL pointer");
    return p;
}

vector_type v_create_empty(char type){
    vector_type my_v = (vector_type)check_a(malloc(sizeof(struct vector_struct)));

    my_v->e_sz = (type == V_INT ? sizeof(int) : type == V_DOUBLE ? sizeof(double) : 1);

    my_v->e_type = type;
    my_v->no_e = my_v->cur_cap = 0;
    my_v->e_array = NULL;
    return my_v;
}

void v_destroy(vector_type my_v){
    if ( my_v == NULL )
        return;

/*** TO BE DONE START ***/
    free(my_v->e_array);          //THIS IS WHAT I'VE ADDED
/*** TO BE DONE END ***/

    free((void*)my_v);
}

void* v_at(vector_type v, iterator i) {
    if ( v == NULL )
        fail("v_at() Error: no such vector");
    if ( i == iterator_end )
        i = v->no_e -1;
    if ( i < 0 || i >= v->no_e )
        fail("v_at() Error: no such element in this vector");

/*** TO BE DONE START ***/
    else                           //THIS IS WHAT I'VE ADDED
    v->e_array[i];
/*** TO BE DONE END ***/

}

void v_push_back(vector_type v, void* new_val){
    if ( v->no_e >= v->cur_cap ) {
        /*** need to expand the array ***/
        v->cur_cap += (v->cur_cap)? v->cur_cap : 2;

/*** TO BE DONE START ***/

/*** TO BE DONE END ***/

    }
    /*** copy new_val into the array at end position (v->no_e) ***/

/*** TO BE DONE START ***/
      v->e_array[v->no_e] = e_array      //THIS IS WHAT I'VE ADDED
    v->e_array[v->e_sz++] = e_array;
/*** TO BE DONE END ***/

    (v->no_e)++;
}

void v_pop_back(vector_type v){
    if ( v == NULL )
        fail("v_pop_back(): no such vector");
    if ( v->no_e == 0 )
        return;
    if ( --(v->no_e) < ((v->cur_cap)>>1) ) {
        /*** reallocate a smaller array ***/
        (v->cur_cap) >>= 1;

/*** TO BE DONE START ***/                      //THIS IS WHAT I'VE ADDED (but I'm lost on this one)
//    for (int i = 0; i < v->no_e - 1; i++) {
//        v->e_array[i] = v->e_array[i + 1];
//        v->e_array[i + 1] = NULL;
//    }
//   v->no_e--;
/*** TO BE DONE END ***/

    }
}

void v_insert_n(vector_type v,iterator start_i,unsigned n,void* new_val){
    char tmp[v->e_sz];
    int i;
    unsigned to_move;

    if ( n==0 ) /*** nothing to insert ***/
        return;
    if ( v == NULL )
        fail("v_insert_n(): no such vector");
    if ( start_i == iterator_end )
        start_i = v->no_e;
    if ( start_i < 0 )
        fail("v_insert_n(): bad iterator");

    /*** a zero element of suitable size ***/
    memset((void*)tmp,0,v->e_sz);

    if ( start_i >= v->no_e ) {
        /*** want to append past the end ***/
        /*** fill the possible gap with zero elements... ***/
        while ( start_i > v->no_e )
            v_push_back(v,(void*)tmp);
        /*** ...then append new elements at end ***/
        for (i=0; i<n; i++)
            v_push_back(v,new_val);
        return;
    }

    /*** want to insert at intermediate position ***/
    /*** expand the array by appending zero elements ***/
    /*** then move some elements towards end to make room ***/

    to_move = v->no_e - start_i;

    for (i=0; i<n; i++)
        v_push_back(v,tmp);

    for (i=0; i<to_move; i++)
        memcpy (
            v->e_array + (v->no_e-1-i) * v->e_sz,
            v->e_array + (v->no_e-1-i-n) * v->e_sz,
            v->e_sz);

    /*** now copy new elements in the room ***/
    for (i=0; i<n; i++) {

/*** TO BE DONE START ***/

/*** TO BE DONE END ***/

    }
}

void v_erase_range(vector_type v,iterator start_i,iterator end_i){
    int i, j;

    if ( v == NULL )
        fail("v_erase_range(): no such vector");
    if ( start_i == iterator_end )
        start_i = v->no_e-1;
    if ( end_i == iterator_end )
        end_i = v->no_e;
    if ( start_i < 0 || start_i >= v->no_e || end_i < 0 )
        fail("v_erase_range(): bad iterator");
    if ( start_i >= end_i ) /*** nothing to erase ***/
        return;

    for ( i = start_i, j = end_i ; j < v->no_e ; i++, j++ )
        memcpy(
            v->e_array + (v->e_sz) * i,
            v->e_array + (v->e_sz) * j,
            v->e_sz);

    /*** call v_pop_back() to actually erase elements ***/
/*** TO BE DONE START ***/

/*** TO BE DONE END ***/

}

This is the main file I've got to modify:
#include "vector.h"

#include <stdio.h>
#include <stdlib.h>

int main(){
    vector_type vi1, vd1, vc1, vc2;
    char c1;
    int i1;
    double d1;

    vi1 = v_create_empty(V_INT);
    vd1 = v_create_empty(V_DOUBLE);
    vc1 = v_create_empty(V_CHAR);
    vc2 = v_create_empty(V_CHAR);

    c1 = 'c'; v_push_back(vc1,(void*)&c1);
    c1 = 'i'; v_push_back(vc1,(void*)&c1);
    c1 = 'a'; v_push_back(vc1,(void*)&c1);
    c1 = 'o'; v_push_back(vc1,(void*)&c1);
    c1 = 0; v_push_back(vc1,(void*)&c1);

    printf("Vector vc1 now contains %d characters (capacity=%1d): %s\n",
           vector_size(vc1),vector_capacity(vc1),vector_string(vc1));

    for ( i1 = 0, c1 = vector_char_at(vc1,i1) ; c1 ; i1++, c1 = vector_char_at(vc1,i1) )
        v_push_back(vc2,(void*)&c1);
    for ( i1 = 0, c1 = vector_char_at(vc1,i1) ; c1 ; i1++, c1 = vector_char_at(vc1,i1) )
        v_push_back(vc2,(void*)&c1);
    v_insert_n(vc2,iterator_end,1,(void*)&c1); /*** inserting 0 at the end ***/

    printf("Vector vc2 now contains %d characters (capacity=%1d): %s\n",
           vector_size(vc2),vector_capacity(vc2),vector_string(vc2));

    c1 = '-'; v_insert_n(vc2,vector_size(vc1)-1,2,(void*)&c1);

    printf("Vector vc2 now contains %d characters (capacity=%1d): %s\n",
           vector_size(vc2),vector_capacity(vc2),vector_string(vc2));

    for ( i1 = 0 ; i1 < 10 ; i1++ )
        v_push_back(vi1,(void*)&i1);

    printf("Vector vi1 now contains %d integers: ",vector_size(vi1));
    for ( i1 = 0 ; i1 < vector_size(vi1) ; i1++ )
        printf(" %1d",vector_int_at(vi1,i1));
    printf("\n");

    for ( i1 = 0 ; i1 < vector_size(vi1) ; i1++ ) {
        c1 = '0' + vector_int_at(vi1,i1); /*** converting decimal number to char ***/
        v_insert_n(vc2,5+i1,1,(void*)&c1);
      }

    printf("Vector vc2 now contains %d characters (capacity=%1d): %s\n",
           vector_size(vc2),vector_capacity(vc2),vector_string(vc2));

    v_erase_range(vc2,2,3+vector_size(vc1)+vector_size(vi1));

    printf("Vector vc2 now contains %d characters (capacity=%1d): %s\n",
           vector_size(vc2),vector_capacity(vc2),vector_string(vc2));

    v_destroy(vc1); v_destroy(vc2);

    for ( i1 = vector_size(vi1)-1 ; i1 >= 0 ; i1-- ) {
        d1 = 0.5 + (double)(vector_int_at(vi1,i1));
        v_push_back(vd1,(void*)&d1);
      }
    d1 = 3.14159192; /*** approximation of Pi ***/
    v_insert_n(vd1,5,1,(void*)&d1);
    v_erase_range(vd1,2,3);

    printf("Vector vd1 now contains %d doubles (capacity=%1d): ",
           vector_size(vd1),vector_capacity(vd1));
    for ( i1 = 0 ; i1 < vector_size(vd1) ; i1++ )
        printf(" %lg",vector_double_at(vd1,i1));
    printf("\n");

    d1 = vector_double_at(vd1,8) + vector_double_at(vd1,9); /*** d1 = 1.5+0.5 = 2.0 ***/
    v_erase_range(vd1,0,4); /*** erase first 4 elements **/
    vector_double_at(vd1,0) *= d1; /*** 2*Pi at index 0 ***/
    v_erase_range(vd1,1,iterator_end); /*** erase all elements but the first ***/

    printf("Vector vd1 now contains %d double (capacity=%1d): ",
           vector_size(vd1),vector_capacity(vd1));
    for ( i1 = 0 ; i1 < vector_size(vd1) ; i1++ )
        printf(" %lg",vector_double_at(vd1,i1));

/*** TO BE DONE START ***/ //NOT SURE ABOUT HERE
    d1 = vector_double_at(vd1,8) + vector_double_at(vd1,9) + vector_double_at(vd1,10) + vector_double_at(vd1,11); // d1 = 6.0+0.2+0.08+0.003+0.008 = 6.2838
/*** TO BE DONE END ***/

    v_erase_range(vi1,1,9); /*** erase elements 1,...,8 ***/
    printf("Vector vi1 now contains %d integers (capacity=%1d): ",
           vector_size(vi1),vector_capacity(vi1));
    for ( i1 = 0 ; i1 < vector_size(vi1) ; i1++ )
        printf(" %1d",vector_int_at(vi1,i1));
    printf("\n");
    v_destroy(vi1);

    exit(0);
}

This is the header file:
#ifndef vECTOR_h
#define vECTOR_h

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

typedef int iterator;
#define iterator_begin 0
#define iterator_end -1

typedef struct vector_struct {
    size_t e_sz;
        char e_type;

#define V_INT 1
#define V_DOUBLE 2
#define V_CHAR 3

    unsigned no_e;
    unsigned cur_cap;
    void* e_array;

}* vector_type;

#define vector_size(v) ((v)->no_e)
#define vector_capacity(v) ((v)->cur_cap)

#define vector_int_at(v,i) (*((int*)v_at(v,i)))
#define vector_double_at(v,i) (*((double*)v_at(v,i)))
#define vector_char_at(v,i) (*((char*)v_at(v,i)))
#define vector_string(v) ((char*)v_at(v,0))

extern void* check_a(void*);
extern void fail(const char*);
extern vector_type v_create_empty(char);
extern void v_destroy(vector_type);
extern void* v_at(vector_type, iterator);
extern void v_push_back(vector_type,void*);
extern void v_pop_back(vector_type);
extern void v_insert_n(vector_type,iterator,unsigned,void*);
extern void v_erase_range(vector_type,iterator,iterator);

#endif

Thanks in advance for any possible help!
Comment: This is way too much code. You should reduce the amount of code to a smaller example and actually mention that you want help with `v_pop_back`. Anyway, you are supposed to allocate a new array the size of `cur_cap` (which has been halfed at that point). You can either use `realloc` for that or you `malloc` then `memcpy` the `e` first element and free the old memory . Btw. e has also already been decreased you don't need to change it) first elements.
Comment: Would this v_pop_back function be correct? `/*** TO BE DONE START ***/ realloc((void*)v, v->cur_cap) /*** TO BE DONE END ***/ ` Thank you for the help, I'll edit the question to make reduce the code!
Comment: I'm sorry I made a mistake, I've ment to say: /*** TO BE DONE START ***/ v=realloc((void*)v, v->cur_cap) /*** TO BE DONE END ***/
Comment: it's more like `v->e_array = realloc(v->e_array, v->cur_cap*v->e_sz);`. I get the feeling from some of the other code-snippets that you don't really understand the purpose of all the data members. Maybe try and do the exercise together with other students, ask you tutor some questions or re-read the other material.
Answer: inside V_AT() Return return (v->e_array+i*v->e_sz); //return element
void* v_at(vector_type v, iterator i) {
    if ( v == NULL )
        fail("v_at() Error: no such vector");
    if ( i == iterator_end )
        i = v->no_e -1;
    if ( i < 0 || i >= v->no_e )
        fail("v_at() Error: no such element in this vector");
/*** TO BE DONE START ***/
    return (v->e_array+i*v->e_sz); //return element
/*** TO BE DONE END ***/

}

Similarly at V_push_back:
void v_push_back(vector_type v, void* new_val){
    if ( v->no_e >= v->cur_cap ) {
        /*** need to expand the array ***/
        v->cur_cap += (v->cur_cap)? v->cur_cap : 2;
/*** TO BE DONE START ***/
        v->e_array = check_a(realloc(v->e_array, sizeof(void*) * v->cur_cap));
        //allocate memory
/*** TO BE DONE END ***/

    }
    /*** copy new_val into the array at end position (v->no_e) ***/
/*** TO BE DONE START ***/
    if(v->e_type==V_CHAR){
        memcpy(
              v->e_array +(v->no_e)*v->e_sz,
              new_val,
              v->e_sz
              );
    }else{
        v->e_array = check_a(realloc(v->e_array, v->e_sz * v->cur_cap));
        memcpy(
              v->e_array +(v->no_e*v->e_sz),
              new_val,
              v->e_sz
              );
    }
/*** TO BE DONE END ***/

    (v->no_e)++;
}


Loop em Carousel

Question: Estou fazendo um Carousel, que recebi a ajuda de amigo daqui. Mas agora surgiu um pequeno problema, no exemplo existem 6 imagens, e ao chegar na última ele para. Queria saber como eu faço para que ao chegar na última, ele volte para a primeira, tipo um loop.
Comment: Fala @Carlos giovani casilo, naum testei mas acredito que, supondo que vc sabe o numero de imagens que tem na lista da sua matriz, se fizer algo tipo isso nesta linha `imageView.setImageResource(mResources[position==nrLista?0:position]);` funcionaria para voce
Answer: Tive uma ideia de fazer desta forma, porém existe outras maneiras de fazer.
Main
public class MainViewPage extends AppCompatActivity {

    ViewPager mViewPager;

    int[] mResources = {
            R.mipmap.imagem1,
            R.mipmap.imagem2,
            R.mipmap.imagem3,
            R.mipmap.imagem4,
            R.mipmap.imagem5,
            R.mipmap.imagem6
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.carousel);

        mViewPager = (ViewPager) findViewById(R.id.pager);

        CarouselAdapter mCustomPagerAdapter = new CarouselAdapter(this, mResources);
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setAdapter(mCustomPagerAdapter);

    }
}

Adapter
public class CarouselAdapter extends PagerAdapter {

    private Context mContext;
    private LayoutInflater mLayoutInflater;
    private int[] mResources;

    private int pos = 0;

    public CarouselAdapter(Context context, int[] resources) {
        mContext = context;
        mResources = resources;
        mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((RelativeLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View itemView = mLayoutInflater.inflate(R.layout.item_carousel, container, false);

        ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
        imageView.setImageResource(mResources[pos]);

        container.addView(itemView);

        if (pos >= mResources.length - 1)
            pos = 0;
        else
            ++pos;

        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((RelativeLayout) object);
    }

}

 XML
Neste caso do XML, já está adaptado com o CardView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_gravity="center|center_horizontal"
        card_view:cardElevation="8dp"
        card_view:cardCornerRadius="8dp"
        android:layout_centerInParent="true">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"/>

    </android.support.v7.widget.CardView>

</RelativeLayout>

Screenshots

Dê uma olhada neste projeto InfiniteViewPager, que também tem ajudará a ter mais alguma ideia de como fazer. Abaixo segue um exemplo:
Comment: Muito obrigado, vou testar agora mesmo.
Comment: Funcionou perfeitamente, muito obrigado mesmo.
Comment: @carlosgiovanicasilo existe outras variações de como resolver isso. Depois de mais uma pesquisada para melhoria. Abs

Loop em Carousel


Which MySQL data type to use for scheduling? (Part 2)

Question: Part 1: Which MySQL data type to use for scheduling?
In Part 1 of my question, I asked which MySQL data type to use for, say, scheduling movies at a cinema. When scheduling a movie, you need to know the date (e.g. Jan 1, 2011) and time (e.g. 9:00 am). Please don't discuss part 1 of my question here.
Here's my part 2: what if I wanted to store a cinemas daily hours of operation? For example:

Monday, 9am - 9pm
Tuesday, 9am - 5pm
etc.

What is a good way to represent this in the database? Keep in mind that, in this case, the date does not matter (e.g. I don't need to know what date the particular Monday is on). I only case about days of the week and times of the day.
Here's how I would probably do it:
TABLE: schedule
- schedule_id
- day (ENUM: 0, 1, 2, 3, 4, 5, 6)
- start_time (INT)
- end_time (INT)

start_time and end_time would represent the number of minutes since midnight. So, 0 for midnight, 1 for 12:01 am, 2 for 12:02 am, and so on.
Am I approaching this right? Suggestions?
Answer: As I said in my answer to your first question, in my opinion a person should use the datatype that better fits and describes the reality. In this case I would like to use Time type for the start_time and end_time fields.
Instead for the day field I would like to use numbers from 1 to 7.
Comment: First because we are men and not computers, so we usually start from 1 and not 0. The second and more important reason is that so you can have the same index that will be returned from functions like this: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofweek
Comment: Hi Aurelio, I'm just careful not to get into data types I don't fully understand. So, in my proposed table design, you suggest I just replace the 2 `INT`s with `Time`? The ENUM for `day` is OK?
Comment: @StackOverflowNewbie I update my answer. Anyway, yes...I would like to change INT to TIME since that datatype better describes your needs.
Comment: Why do you prefer 1-7 instead of 0-6?
Comment: I like your second reason. Thanks!


ASP Classico: Como substituir o caractere "TRAVESSÃO" por "TRAÇO"?

Question: estou com um problema - ao utilizar um componente para PDF - acabei tendo um erro de "Out of Range" na hora de gerar o documento PDF.
pelo erro e linha descobri onde estava o problema - e identifiquei que o erro era pq o usuario cadastrou um "TRAVESSÃO" no campo buscado.
ao trocar o "TRAVESSAO" por "TRAÇO" - tudo voltou ao normal.
Obviamente o erro no componente ocorre pq ele nao identifica o "TRAVESSAO" como um caractere de "Tabela" - ja q ele inclusive nao faz parte do teclado padrao.
Em milhares de cadastros foi a primeira vez q tive esse problema - mas como é comum os clientes usarem o traço para separar as informacoes do campo, (e acredito que o problema ocorreu pq o CORRETOR ORTOGRAFICO trocou automaticamente o traço pelo travessao) - queria uma solucao para o problema.
Essa solucao é simples..
basta verificar o dado enviado no cadastro e trocar o TRAVESSAO por TRAÇO usando o comando "REPLACE"
REPLACE(texto, "TRAVESSAO", "TRAÇO")

minha duvida é - como eu informo o "TRAVESSAO" no codigo - ja q ele nao existe no teclado.
valeu!!
Comment: Sem saber que tipo de caractere é esse TRAVESSÃO fica muito difícil. Já pensou em fazer o inverso? Por ex: Filtrar apenas os caracteres aceitáveis na busca.
Comment: Travessão no Windows AltGr + Num- ou Alt + CTRL + Num- (ou Alt + 0151)  OBS: Num- é a tecla de "menos" no painel das teclas numéricas assim como 0151 também. No meu teclado funcionou Alt + 0151  olha ele ai   — é maior que o Meia-risca –  ou - (tracinho)
Answer: Travessão no Windows   AltGr + Num- ou   Alt + CTRL + Num- ou   Alt + 0151
OBS: Num- é a tecla de "menos" no painel das teclas numéricas assim como 0151 também. No meu teclado funcionou Alt + 0151 olha ele ai — é maior que o Meia-risca – ou - (tracinho).
No Mac OS X   Alt + hífen
REPLACE(texto, "—", "-")

Eu já usei muitos replaces em asp assim: REPLACE(texto, chr(151), "-") Traço pode ser chr(150) ou chr(45)
           glifo    Unicode          HTML    TeX         Windows    Mac OS
hífen        -      U+2012 (8210)   nenhum    -        Alt + 0045
meia-risca   –      U+2013 (8211)   –   --       Alt + 0150   Option + -
travessão    —      U+2014 (8212)   —   ---      Alt + 0151   Shift + Option + -

Alguns teclados não tem painel das teclas numéricas, como fazer?

Copie o Travessão — e cole-o no seu código!!

Wikipédia
Comment: Oi @leo-caracciolo, primeira obrigado pela ajuda!! Era isso mesmo que precisava! Meu teclado não tem o alfnum e por algum motivo usando o Chr(151) no replace ele nao estava fazendo a troca. Mas deu tudo certo usando o caracter direto. Obrigado!! Daniel


problem in variables scope in PHP

Question: I wrote this code
require('Database.class.php');

     function get_info (){

        $db = new Database($config['server'], $config['user'], $config['pass'], $config['database'], $config['tablePrefix']);
        $db->connect();

        $sql = $db->query('SELECT * FROM ja_cat');
        while ($options = $db->fetch_array($sql)) {

            $cat[].=" ".$options['title'];
        }
        $db->close();
        return $cat;

then I get this Mysql error
Mysql Error : No database selected .
but when I put the require instruction inside the function it's work fine
Answer: My guess is Database.class.php creates some variables that are probably global in scope that it relies upon. If you require it inside the function and it works, that supports that theory. Is that your class? Can you change it? Can you post it?
Basically $config needs a global qualifier inside the function.
Comment: here it is http://www.ricocheting.com/scripts/php_mysql_wrapper.php  , Andrew solved the problem
Comment: Ya he wrote out the reason and I wrote out the fix, I suppose I should have elaborated as to the WHY behind my HOW.
Answer: Make this the first line IN your get_info() function:
global $config;

Also, you may want to define $db outside of the function at the start of the code and then close the connection at the end, instead of having to re-connect multiple times.
Answer: You have to import the global variable $config into the scope of the function:
function get_info() {
    global $config;
}

Comment: You guys just don't see the problem? Isn't it?

problem in variables scope in PHP


Why does ~0b1 print out -2 in Python 2.7?

Question: I'm (somewhat) familiar with one's complement but I could use a refresher with regards to Python 2.7.
Why does ~0b1 print out to -2?
I understand that a one's complement converts 1s to 0s and vice versa. I expected ~0b1 to print 0b0 or 0.
Does print automatically convert byte literals to some form of int?
Any help is appreciated.
Comment: That isn't a *byte literal*. That is *another type of `int` literal that let's you express your `int` in binary*. So there is no conversion because *it was always an `int`*.
Comment: @juanpa.arrivillaga Thanks for the comment. That explains a bit.
Comment: So, in other words, `0b10000`, `0x10`, and `16` are all literals for the same `int` object. by default, when an `int` is printed to a screen, it's decimal representation is printed.
Answer: 0b1 is just another way of writing 0b0000...01 (integer 1). With ~ you'll get the bit-wise complement 1 -> 0 and 0 -> 1 (including the sign bit) so you get:
0b111....10

which is -2.
Comment: Your answer, combined with the top answer at this question (http://stackoverflow.com/questions/8305199/the-tilde-operator-in-python) really helped me understand what was happening.

Thank you!


Mount job output data as input data for another job in Floydhub

Question: I'm trying to follow documentation here, here and here for Floydhub to use the output of a job as the input data for another job. The 1st and 2nd job are related to 2 different projects.
It's unable to locate my file.
No such file or directory: '/output/lemmatized_json.json'

Project 1:
This project outputs data at the end of the script.
import os
if not os.path.exists('output'):
    os.makedirs('output')

with open('output/lemmatized_json.json', 'w') as out_file:
    json.dump(data, out_file)

Then its available inside /files for that project,

in the /output directory.

Project 2:
Now I run the second project where I want to access that previously saved data.
I run the project with.
floyd run --cpu2 --env default \
--data me/projects/lemmatize-json-positions/6/:model \
--message 'train embedding' 'python train_embedding.py'

And try to access the data inside it with the following code.
file = open('/output/lemmatized_json.json')

But I get the above errer No such file or directory: 'No such file or directory: '/output/lemmatized_json.json'.
And I'm not sure what I'm missing.
Answer: I just needed,
file = open('/model/output/lemmatized_json.json')


ERROR => ERROR => SMTP-AUTH: Authentication to smtp.gmail.com:587 failed

Question: I am trying to send an email using below command but i am getting below error:
Command executed:
/usr/bin/sendemail -v -f "email@example.com" -u "Re : Alerts Script" \
   -t "$EMAILS" -s "smtp.gmail.com:587" -o tls=yes -xu "firstname.lastname@example.com" \
   -xp "Password" -m "$Msg"

I tried with port 25, Still same error getting.
If i use 465 port getting below error

ERROR => smtp.gmail.com:465 returned a zero byte response to our query.

/usr/bin/sendemail -v -f "email@example.com" -u "Re : Alerts Script" \
  -t "$EMAILS" -s "smtp.gmail.com:587" -o tls=yes -xu "firstname.lastname@example.com" \
  -xp "Password" -m "$Msg"

Email should go for given email id's
Answer: I had faced the same issue and could resolve it. You can use the tls auto, 587 port command. Able to successfully send an email using Gmail SMTP.
/usr/bin/sendemail -f "firstname.lastname@example.com" -u "Re : Alerts Script" -t "$EMAILS" -s "smtp.gmail.com:587" -o tls=auto -xu "email@example.com" -xp "Password" -m "$Msg"

Also, you have to apply couple of settings in Gmail.

Enable IMAP
Allow less secure app
Review suspicious activity and mark 'That's me' to allow communication.
Comment: I had all that enabled and it still wasn't working. However, for some reason when I logged in to Gmail from a browser on that same server (Windows) it started working.
Comment: I second that comment. sendEmail worked for me as soon as I have made a successful login with a browser from the same machine.
Answer: To resolve this error for me in Windows (should work in any OS), I had to go into my Gmail account/Security/App Passwords on the web and generate a 16-digit password for App:"Mail" and Device:"Windows Computer" (you can create a custom device too) to give special access to the device where I was running SendEmail.
Per Google: "App passwords let you sign in to your Google Account from apps on devices that don't support 2-Step Verification."
Then I used that 16-digit password in SendEmail instead of my gmail password and it finally went through.
c:\sendemail\sendemail -o tls=yes -t recipient@email.*** -m Title HELLO -f [myaccount]@gmail.com -s smtp.gmail.com:587 -xu [myaccount]@gmail.com -xp **************** -l C:\sendemail\logfile.txt

Answer: Also in windows you need to add sendEmail to your firewall.
Comment: and how can you do that? Good approach, but please write a detailed and clear answer.
Comment: I did not have to add SendEmail to my firewall on my Windows device to resolve this issue. See my answer below for what worked for me.


Trocar icone do botão Actionbar

Question: tenho este layout com este botão de coração , tem como dentro do evento de click deste botão eu trocar o icone

tava querendo trocar o coração ai por este coração quando clicar

a resposta abaixo resolveu mais gerou um problema
Você precisa sobrescrever os métodos onCreateOptionsMenu e onOptionsItemSelected
1) Reter o MenuItem desejado:
private MenuItem menuCoracao;
...
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.seu_menu, menu);
    menuCoracao = menu.findItem(R.id.id_do_seu_menu);
    return super.onCreateOptionsMenu(menu);

}
2) Detectar o click do menu e alterar o ícone:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.id_do_seu_menu) {
        menuCoracao.setIcon(R.drawable.seu_drawable);
    }
    return super.onOptionsItemSelected(item);
}

eu tentei usar no onCreate assim
meuCoracao.setIcon(R.drawable.ic_action_favorite_v);

deu este erro
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{praias.android.makerapp.com.praias/praias.android.makerapp.com.praias.MainActivity}: java.lang.NullPointerException

Answer: Você precisa sobrescrever os métodos onCreateOptionsMenu e onOptionsItemSelected
1) Reter o MenuItem desejado:
private MenuItem menuCoracao;
...
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.seu_menu, menu);
    menuCoracao = menu.findItem(R.id.id_do_seu_menu);
    return super.onCreateOptionsMenu(menu);
}

2) Detectar o click do menu e alterar o ícone:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.id_do_seu_menu) {
        menuCoracao.setIcon(R.drawable.seu_drawable);
    }
    return super.onOptionsItemSelected(item);
}

Comment: tem como eu iniciar esse meuCoração no onCreate?
tentei usar ela fora do onOptionItemSelected e não funcionou

Trocar icone do botão Actionbar


Como alterar um arquivo de commit antigo no git?

Question: Tenho um arquivo no qual acabei colocando uma senha real em um commit antigo e agora gostaria de alterar este arquivo para não deixar exposto.
Encontrei um post aqui no stack mas acho que deve estar desatualizado, é de 2015.
No post pede para usar o comando:
git rebase --interactive b6f925df^

Depois altere pick para edit nos commits que desejo modificar.
Este é o problema, não consegui fazer essa alteração de pick para edit. Quando executo o comando rebase, abre um editor mas não consigo fazer nada deste editor.
Alguém pode me dar uma força?
Comment: Meu palpite é que esse editor seja o [Vim](https://web.mit.edu/6.005/www/fa14/tutorial/git/config.html). Se for, basta digitar `i` para entrar no modo de inserção, editar o que precisa, depois `ESC`, e `:x`. Ou você pode [configurar o Git para usar outro editor](https://stackoverflow.com/q/2596805)
Answer: O git possui uma instrução chamada log o mesmo tem o seguinte proposito mostra os logs de confirmação e listar os commits que são alcançáveis seguindo os parent links.
Cada commit que foi descrito a modificação pode ser recuperada.
$git log

commit 4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx18e7 (HEAD -> master)
Author: alguen <firstname.lastname@example.com>
Date:   Mon Oct 15 08:06:47 2018 -0400

     info

commit 4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx84ee (tag: 1.0.00)
Author: alguen <email@example.com>
Date:   Mon Oct 15 07:52:39 2018 -0400

    alts - add

O git sempre armazena uma hash do commit "commit 4xxxxxxxxxx" o commit do topo é inalterável pois foi o ultimo; para alterar  o primeiro tem que pegar a segunda hash do segundo commit( sempre um commit abaixo para alterar o de cima)
A uma instrução parecida com reset que possui funções para recuperar.
soft: volta ao commit do arquivo e estara em statement com a modificação
pronta
mixed : vai retornar antes do statement voltara para modifeid
hard: mata todo o commit e tudo que foi feito nele
uso:
git reset --soft 4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx84ee

ao utilizar git status    sera apresentado as modificações assim refaze-la
Answer: Tente fazer o seguinte:

    git checkout --orphan latest_branch

    git add -A

    git commit -am "commit message"

    git branch -D master

    git branch -m master

    git push -f origin master

Fonte: https://pt.stackoverflow.com/questions/401836/como-deleto-um-commit-do-histórico-do-github
Dica: Eu mantenhos dados sensiveis fora do repositório do git e faço um import deles quando compilo o código ou via parâmetro. Veja se a linguagem na qual está trabalhando aceita isto.


Degree of the composition

Question: I am trying to prove that if $f: S^1 \rightarrow S^1$ is a homeomorphism, $f(1)=1$ then $deg(f)= \pm1$.
I noticed that if it holds that $deg([g \circ h])=deg([g]) \cdot deg([h]) (*)$ then the claim follows easily, but I'm not sure if $(*)$ holds and if it does how to prove it. I found some similar posts and they were using the fact $(g \circ h)_*=g_* \circ h_*$ but I'm not sure if this helps with the definition I am using for a degree or how to use it in order to prove $(*)$.
The definition of the degree is the following: For a closed path $\alpha: I=[0,1] \rightarrow S^1$ there is a unique lift $\alpha'$ for which $\alpha'(0)=0$ then $deg(\alpha)=\alpha'(1)$. Then, for $f: S^1 \rightarrow S^1$  define $deg(f)=deg(f \circ p)$ where $p:I \rightarrow S^1$ with $p(t)=e^{i2 \pi t}$
I also know that $deg:\pi_1(S^1,1) \rightarrow \mathbb{Z}$ is a group isomorphism, where on the LHS is the fundamental group of $S^1$ where the operation is $[f_1] \cdot [f_2]=[f_1*f_2]$ where $*$ represents the concatenation of paths $f_1,f_2:I \rightarrow S^1$
(Notation follows Rotman's book:'An introduction to Algebraic Topology')
Edit: The comments suggest that $(*)$ holds , but I'm still not sure how to prove it.
Comment: $\deg(f)$ is the image of $1 \in \Bbb Z$ in the induced map $f_\ast: H^1(S^1) \to H^1(S^1) \simeq \Bbb Z$. This determines $f_\ast$ completely.
Comment: That fact plus $(g \circ h)_\ast = g_\ast \circ h_\ast$ does the rest.
Comment: $\ast$ holds and is the way to show this fact.
Comment: @HennoBrandsma Is $H^1(S^1)$ the fundamental group of $S^1$? And why $deg(f)$ is the image of $1 \in \mathbb{Z}$ in $f_*$? The theorem I know that holds true regarding deg is: $deg: \pi_1(S^1,1) \rightarrow \mathbb{Z}$ is a group isomorphism where on the left is the fundamental group of $S^1$
Comment: Yes I meant $\pi_1(S^1,1)$ in fact. The first homotopy (or homology) group. Which happen to be the same here.
Comment: @HennoBrandsma I'm still not sure as to why $deg(f)$ is the image of $1 \in \mathbb{Z}$ in $f_*$
Comment: I think it follows from the unique lifting
Comment: @HennoBrandsma Can you write the exact statement that you mean when you say that $deg(f)$ is the image of $1 \in \mathbb{Z}$? Because $f_*:\pi_1(S^1,1) \rightarrow \pi_1(S^1,1)$ with $f_*([g])=[f \circ g]$ and $deg:\pi_1(S^1,1) \rightarrow \mathbb{Z}$
Comment: $f_\ast(1)$ is a member of $\Bbb Z$ where $1$ is the homotooy class of the identity as a generating member of $\pi_1(S^1, 1)$. Its image under $f_\ast$ is homotopic to some $ z^k: S^1\to S^1$. This $k$ is the degree.
Answer: I would mention the things that I think would give the above result without looking for the fact that $\deg$ is multiplicative.
let us suppose that $S^{1}$ is a subset of $\mathbb{C}$. Also it is easy to see that $S^{1}$ is homeomorphic to $\Bbb R /  \Bbb Z$. with the homeomorphism defined by :
$$  g : \Bbb R / \Bbb Z \rightarrow S^{1} \\
     g([t]) = e^{2\pi i t}\\
$$
with this homeomorphism, one easily sees that every closed loop can be interpreted as a map from $S^1 \text{ to } S^{1}$. And vice versa.
On the other hand, there is a notion of covering space. A covering space for a topological space $X$ is a triple $(E,p, F)$. Where $F$ is a discrete topological space and p is a continuous map from $E$ to $X$ s.t. for all $x$ in $X$, there exists a $U \subset X$ open and $x \in U$ such that $p^{-1}(U) \simeq U \times F$. A lift always is defined with respect to a covering in a way that it always commutes with the initial map via the covering map($p$). So in our case, $E =\Bbb R$ and $p : \Bbb R \rightarrow S^{1}$ with
$p(t) = e^{2\pi i t}$ and $F$ is $\Bbb Z$. Now for a closed path $\gamma$,$\gamma(1) = 1$, let $\tilde{\gamma}$ be its lift. then $\deg(\gamma):= \tilde{\gamma}(1) - \tilde{\gamma}(0)$. it is clear that the degree is an integer and can be seen that it is independent of the lift of $\gamma$. Now for a map $f : S^{1} \to S^{1}$ the degree defined above is the degree of the map as a closed path defined from $[0,1]$. In our case case $f$ is homeomorphsism so the degree of $f$ as a closed path must be $\pm 1 $, other wise every point of $S^{1}$ would have more than $1$ inverse image.
Answer: Since you speak about a lift of a path, it seems that you know the covering projection $\exp: \mathbb R \to S^1, \exp(t) = e^{2\pi i t}$. However, you should mention that you only consider maps $f : S^1 \to S^1$ such that $f(1) = 1$ (basepoint preserving maps). This assures that $\alpha_f = f \circ p$ has a lift  $\alpha'_f$ which maps $0$ to $0$. We have $\alpha'_f(1) \in \mathbb Z$.

solution:

If $f$ is a homeomorphism, then it maps $U  = S^1 \setminus \{1\}$ homeomorphically onto itself. Moreover $p$ maps $(0,1)$ homeomorphically onto $U$, and therefore $\alpha_f$ does the same. $U$ is evenly covered with sheets $V_k = (k,k+1)$, $k\in \mathbb Z$. Since $\alpha'_f((0,1))$ is a connected subset of $\exp^{-1}(U)$, it must be contained in some $V_k$. But $e_k : V_k \stackrel{\exp}{\to} U$ is a homeomorphism such that $e_k \circ \alpha'_f \mid_{(0,1)} =  \alpha_f \mid_{(0,1)}$. Hence $\alpha'_f \mid_{(0,1)} : (0,1) \to V_k$ is a homeomorphism. Since $\alpha'_f(0) = 0$, we must have $k = 0$ or $k=-1$. But then clearly $\alpha'_f(1) = 1$ if $k = 0$ and $\alpha'_f(1) = -1$ if $k = -1$. Thus $\deg f = \pm 1$.

solution:

We know that $\deg : \pi_1(S^1,1) \to \mathbb Z$ is a group isomorphism. The homotopy class $\deg^{-1}(n)$ is represented by $\mu_n : S^1 \to S^1, \mu_n(z) = z^n$. Let $f, g : S^1 \to S^1$ with $\deg f = n $ and $\deg g = m$. Then
$$[f \circ g] = [f] \circ [g] = [\mu_n] \circ [\mu_m] =  [\mu_n \circ \mu_m] = [\mu_{n\cdot m}]$$
because $(\mu_n \circ \mu_m)(z) = \mu_n(\mu_m(z)) = \mu_n(z^m) = (z^m)^n = z^{n\cdot m} = \mu_{n\cdot m}(z)$. We conclude
$$\deg([f \circ g]) = \deg([f] \circ [g]) = \deg \mu_{n\cdot m} = n \cdot m = \deg [f] \cdot \deg [g] $$
which suffices to prove your claim.
Comment: @WalterWhite If we have maps $\phi, \phi' :A \to B, \psi, \psi' :B \to C$, then if $\phi \simeq \phi'$ and $\psi \simeq \psi'$ we get $[\psi  \circ \phi] = [\psi' \circ \phi']$. Thus  $[\psi] \circ [\phi] = [\psi \circ \phi]$ is well-defined, and that is what I used in my proof. Your equation is of course also true, but it only says that $\deg : \pi_1(S^1,1) \to \mathbb Z$ is a group homomorphism which we already know. Note that the operation $([f],[g]) \mapsto [f \circ g]$ has nothing to do with the group multiplication in $\pi_1(S^1,1) $.
Comment: You can also directly argue that $f \simeq \mu_n$ and $g \simeq \mu_m$ implies $f \circ g \simeq \mu_n \circ \mu_m$.
Comment: I'm still processing your answer, but I'm not sure about the second solution because in the fundamental group $\pi_1(S^1,1)$ the operation is $[f_1] \cdot [f_2]=[f_1*f_2]$ where * is the concatenation and I'm interested in the $deg([f_1 \circ f_2])$
Comment: @WalterWhite $f \circ g$ denotes the composition $S^1 \stackrel{g}{\to} S^1  \stackrel{f}{\to} S^1$. I computed the degree of this composed map. If $f$ is a homeomorphism with inverse $f^{-1}$, then $1 = \deg id = \deg (f \circ f^{-1}) = \deg f \cdot \deg f^{-1} $. This is only possible if $\deg f =\pm 1 $.
Comment: What I mean is that for example I dont see why the equality $[\mu_n] \circ [\mu_m]=[\mu_n \circ \mu_m]$  holds. Instead, the equality that holds is $[\mu_n] \cdot [\mu_m]=[\mu_n * \mu_m]$ where * is the concatenation of paths and $\cdot$ is the operation in $\pi_1(S_1,1)$(unless I  understood something wrong)
Comment: I think I got it, that's where I was confused all along. Thank you very much for your time

Degree of the composition


Lemma 3.2.4 in high dimensional probability: expectation of inner product of isotropic random vectors

Question: Lemma 3.2.4 in the book high dimensional probability states that for two independent isotropic random vectors in $\mathbb{R}^n$(this means $EXX^T = I_n$), we have $E\langle X,Y\rangle^2 = n$, where $\langle X,Y\rangle = X^T Y$.
To prove this, we compute $E(E(\langle X,Y\rangle^2\mid Y))$. We get $E(\langle X,Y\rangle^2\mid Y) = \Vert Y\Vert_2^2$, and $E( \Vert Y\Vert_2^2) = n$.
What I don't understand is where the assumption of independence was used. The law of total expectation doesn't require the assumption of independence, so to me it seems the proof would be fine without the assumption of independence of $X$ and $Y$.

Vershynin, Roman, High-dimensional probability. An introduction with applications in data science, Cambridge Series in Statistical and Probabilistic Mathematics 47. Cambridge: Cambridge University Press (ISBN 978-1-108-41519-4/hbk; 978-1-108-23159-6/ebook). xiv, 284 p. (2018). ZBL1430.60005.
Comment: Set $Y=X$. If no independence assumption were necessary, the two assertions of the lemma would contradict each other.
Answer: We need independence for $E(<X,Y>^2|Y) = \left|Y\right|_2^2$. In particular, for $\phi(x,y)$ and $g(x) = E(\phi(x,Y))$, $E(\phi(X,Y)|X) = g(X)$ if $X$ and $Y$ are independent.


Passing parameters between auxiliary outlets

Question: I currently have an auxiliary outlet which only outputs data inside a specific area of my application. This is due to the fact that I want to manipulate the data without changing the dashboard state. My problem is, how do I pass parameters between components inside my auxiliary outlet? This is what I have.
manage-clients.component.html

<button [routerLink]="[{ outlets: {agentSidebar: ['details', police._id]}}]">View</button>

From the html above, I'd like to navigate to path /details with param police._id. The code  below is my app.routing.ts file.
app-routing.ts
{ path: 'manage-clients', component:ManageClientsComponent, canActivate: [AuthGuard], data: {permission: {only:["agent"]}}, outlet: 'agentSidebar'},
 { path: 'details/:_id', component:DetailsComponent, canActivate: [AuthGuard], data: {permission: {only:["agent"]}}, outlet: 'agentSidebar'},

However, the code above displays an error in my web console like so:
URL Segment: 'manage-clients'
Error: Cannot match any routes.

How would I change my code to properly route this in order to pass the parameter between both components inside an auxiliary outlet?
Comment: If you want the details route to react to the url: 'manage-clients/details/1234 it should be below int the children array of manage-clients. But I'm not used to use the outlet property in the route definitions. Sorry. My last comment was just a suggestion to be able to se what routes the routeLink creates
Comment: Is this correct? ['details, police._id']
Should it not be ['details', police._id]
Comment: @JensAlenius hey there, good catch but it was just a typo. I'll edit my question for clarification!
Comment: If you change from a button tag to an anchor tag you will see what url it will navigate to, in the left bottom of the browser, when you hover into the link. That often helps me. When you see what route it will goto. An anchor is better to use when it comes to navigation and routing
Comment: @JensAlenius The issue is that if I route the path from from the auxiliary outlet to the primary outlet instead, the route works but it will display it within the primary outlet which I do not want. Any thoughts? I think the solution may be that I need to set child routes within my auxiliary route to have a proper routing.
Comment: It's alright. I'll try to set child routes within the auxiliary outlet and see where it goes.
Answer: I don't really get your setup but if the manage-client is the parent route. Then you can add
  <router-outlet></router-outlet>

In it's html and remove any outlet from the route conf.  Skip the outlet name if it's only one
Any child route will be injected at that place
The routeLink will be relative to beneath 'manage-client' so if you write it like
  Style it like a button<\a>

It should point at manage-client/details/1234