Evaluation in dplyr::case_when()

Question: Following an example given in the dplyr::case_when() documentation:
x <- 1:50
case_when(x %% 35 == 0 ~ "fizz buzz",
          x %% 5 == 0 ~ "fizz",
          x %% 7 == 0 ~ "buzz",
          TRUE ~ as.character(x))

I expect that the number 35 will produce "buzz" but it produces "fizz buzz"
My reasoning is that case_when() evaluates all statements one by one regardless if a previous one is true or not (since it does evaluate TRUE ~ as.character(x) which is the last one) and that 35 %% 7 is obviously 0.
What am I missing?
Comment: The statements are evaluated in order, and anything that matches against the first statement will get the first result, and will not be overridden by later results.
Comment: There are `x` values that are not divisible by 35, 5, or 7 - so there are still values left to deal with after the first 3 statements are dealt with. If you are still confused can you try to explain in more detail why you think something else should be happening?
Comment: I am still puzzled as why this last statement TRUE ~ as.character(x) is evaluated.
Comment: @Marius I was confused by this TRUE ~ as.character(x) as it seems to me it apply to the whole x. I understand that this is a way to have an "other" clause.
Comment: It would apply to the whole `x` *except* where some other case wins out.  When multiple cases are true, the first one listed "wins". So when using `TRUE ~` it's important that it be listed last, or the cases listed after it will never win.
Answer:
case_when() evaluates all statements one by one regardless if a previous one is true or not (since it does evaluate TRUE ~ as.character(x) which is the last one)

This is misleading, the output of case_when() is based on the first statement that is true.
TRUE ~ as.character(x) means that if x is not divisible by 5 or 7 then then x will be returned as a string ie for x = 5, "5" will be returned.
If x is divisible by 5 or 7, casewhen() does not evaluate subsequent cases. "fizz" and "buzz" are not passed to as.character(x) and they do not have to be because they are already character strings.
Comment: You're right that `case_when` takes the value from the first true case, but actually subsequent cases are still evaluated, as can be seen if they have side effects.  E.g., This will return `"foo"`, but you still get the warning from the second case: `case_when(TRUE ~ "foo", TRUE ~ warning("bar"))`
Comment: Similarly, this will return `2`, but afterward `x` is `3` because it was incremented twice: `x <- 1; case_when(TRUE ~ (x <- x + 1), TRUE ~ (x <- x + 1))`.  (To be clear, I'm not recommending using side-effects like this in actual code -- it's just an example.)
Comment: @TimGoodman Thanks this is a good point and I should have known. I am often caught out by setting TRUE ~ NA, instead of the appropriate NA_[class]_, even though I received an error in cases where I thought TRUE ~ was never evalutated, I did not join the dots.

Evaluation in dplyr::case_when()


Clicking or double clicking a draggable element with jQuery?

Question: I would like to be able to click or double click an element that is also draggable. How can this be done? I've tried various click(), dblclick() and other methods, none have worked so far.
I've currently got an awkward workaround comparing the milliseconds between mouseup and mousedown events, but this still requires the element to have been dragged at least one pixel.
I want to be able to click it normally like a button, without having to drag it first.
Answer: You can use short delay to prevent random dragging on just click.
$('.draggable').draggable({ delay: 200 });

Answer: Assuming that you don't mind having a child-element, to receive the clicks, of the draggable outer-element, then this approach could be taken:
$('#draggableDiv').draggable(
   {
       cancel : 'a'
   });

JS Fiddle demo.
The cancel option takes a CSS/jQuery selector to identify which element(s) should not be considered triggers for the dragging event.

Edited to address the fact that, at least in Chromium 16/Ubuntu 11.04, an element appears to be click-able double-click-able and draggable all at the same time: JS Fiddle example.
Answer: Neither of the other two solutions worked for me, the following did:
$('#draggableDiv').mousedown(function () {
    var thisone=$(this);
    setTimeout(function(){
        thisone.attr("draggable","true");
    },200);
});


What is the best method for creating an API using MVC3

Question: I am using mvc3 and I want to create an API with the site.
MVC makes it really easy to return json from the controller which I know how to do.
I want to use a subdomain for the api something like http://api.mydomain.com
I have a few questions

Do I create an area for api or just place the controller and model in the root?
How can I point to the subdomain so the url is api.mydomain.com not mydomain.com/api
What is the best way to version the api? do I just create a new controller for each version e.g. V1Controller,V2Contoller etc etc

Any suggestions would be really helpful.
Thanks for your help
Comment: MVC3 is *much* easier to use than WCF, and you have much more control over requests and responses. Save yourself the hassle and use MVC.
Comment: @xixonia Have you tried the new WCF bits? They're very easy to use and much more lightweight than a full MVC3 app for an API.
Comment: I would suggest using the new WCF Web APIs rather than MVC3 for that sort of thing. http://wcf.codeplex.com
Comment: Are you looking to also have an interactive web app on this site or just a service architecture?
Answer: I have recently used ServiceStack, I really like working with it, you should take a look
http://www.servicestack.net/


LOOCV and one-standard-error rule

Question: I have a question concerning the one-standard-error rule when doing leave-one-out cross-validation.
firstly, my summary of the one-standard-error rule:
When using cross-validation or validation the model with the lowest test error will most likely change for every time the model is fitted with another random assignment of observations to the folds. Therefore, the one-standard-error rule can be used to select the simplest model that is within one standard error of the model with the lowest test error. The rational behind the rule is that, when there is, from a statistical point of view, not much difference between the models, why not choose the simplest model
Secondly, my question:
If the above "definition" holds, then there should be no standard error when applying leave-one-out cross-validation. The reason being that, the observations assigned to the folds are always the same, so there is no variance in the cross-validation error. Therefore, I wonder why RStudio and Matlab still give standard errors when LOOCV is applied?
Comment: @whuber: if LOOCV is applied there is only one possible division, i.e., one observation per fold
Comment: What is your basis for believing "the observations assigned to the folds are always the same"?
Comment: Is the software comprehensively leaving each observation out or randomly selecting them?  (I imagine the best way to find out would be to consult the documentation for whatever functions you are using.)
Answer: Leave-one-out does have a standard deviation and also a standard error: each of the $n$ folds returns an error estimate, so you can calculate mean as well as standard deviation and standard error over the $n$ fold estimates.

You are right though, that LOO is exhaustive: it is not possible to obtain other than those $n$ surrogate models from an LOO scheme.
What you cannot do in LOO (as opposed to resampling schemes that leave out more than 1 case for each surrogate model, whether they are run exhaustively or not) is separating variance stemming from model instability from variance stemming from the tested data, as LOO confounds those influencing factors. Which might be important information e.g. for model auto-tuning.

LOOCV and one-standard-error rule


Erro ao submeter formulário com ASP MVC

Question: Estou enfrentando um problema ao submeter um formulário desenvolvido em ASP MVC. Ao clicar no botão salvar é retornada a seguinte mensagem de erro:
System.InvalidOperationException: 'Não existe item ViewData do tipo 'IEnumerable<SelectListItem>' que possui a chave 'DepartamentoSelecionado'.'

O que pode ser este erro?
O projeto está dividido em 4 arquivos principais. O primeiro é a Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace projetinho.Models
{
    public class UsuarioModel
    {
        public int Id { get; set; }

        [Required(ErrorMessage = "Um nome deverá ser informado!")]
        [StringLength(maximumLength: 50, MinimumLength = 3, ErrorMessage ="O nome deve conter no mínimo 3 e no máximo 50 caracteres.")]
        public string Nome { get; set; }

        public int Id_Departamento { get; set; }

        public List<SelectListItem> DepartamentoSelecionado { get; set; }

        public UsuarioModel()
        {
        DepartamentoSelecionado = new List<SelectListItem>();
        }
    }
}

O segundo arquivo é uma classe que irá manipular o banco de dados
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace projeto.Models
{
public class UsuarioHandler
{
    private SqlConnection con;
    private void Conexao()
    {
        string stringConexao = ConfigurationManager.ConnectionStrings["sqlServer"].ToString();
        con = new SqlConnection(stringConexao);
    }

    public bool CadastraUsuario(UsuarioModel Usulist)
    {
        Conexao();
        string query = "insert into usuario(nome, id_departamento) values ('" + Usulist.Nome + "', '" + Usulist.DepartamentoSelecionado + "')";
        SqlCommand cmd = new SqlCommand(query, con);

        con.Open();
        int i = cmd.ExecuteNonQuery();
        con.Close();

        if (i >= 1)
            return true;
        else
            return false;
    }

//FUNÇÃO QUE LISTA OS DEPARTAMENTOS NO DROPDOWN
        public List<UsuarioModel> DepList()
        {
            Conexao();

            List<UsuarioModel> listaDepartamento = new List<UsuarioModel>();

            string query = "select id, nome from departamento";
            SqlCommand cmd = new SqlCommand(query, con);

            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();

            con.Open();
            adapter.Fill(dt);
            con.Close();

            foreach (DataRow dr in dt.Rows)
            {
                listaDepartamento.Add(new UsuarioModel
                {
                    Id = Convert.ToInt32(dr["id"]),
                    Nome = Convert.ToString(dr["nome"])
                });
            }
            return listaDepartamento;
        }
    }
}

O Controllerestá definido da seguinte maneira:
using projeto.Models;
using System.Data;
using System.Web.Mvc;

namespace projeto.Controllers
{
    public class UsuarioController : Controller
    {
        [HttpGet]
        public ActionResult Cadastrar()
        {
            UsuarioHandler usuarioHandler = new UsuarioHandler();
            ViewBag.departamentos = new SelectList(usuarioHandler.DepList(), "id", "nome");

            return View();
        }

        [HttpPost]
        public ActionResult Cadastrar(UsuarioModel Usulist)
        {
            if (ModelState.IsValid)
            {
                UsuarioHandler usuariohandler = new UsuarioHandler();

                if (usuariohandler.CadastraUsuario(Usulist))
                {
                    ViewBag.Msg = "
× Cadastro realizado com sucesso!
";
                    ModelState.Clear();
                }
                else
                {
                    ViewBag.Msg = "
× Erro ao cadastrar!
";
                }
            }
            return View();
        }
    }
}

E por fim, a View
@model projetinho.Models.UsuarioModel

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            Informe o nome:
            @Html.EditorFor(model => model.Nome, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Nome, "", new { @class = "text-danger" })

            Selecione um departamento:
             @Html.DropDownListFor(model => model.DepartamentoSelecionado, ViewBag.departamentos as SelectList, new { @class = "form-control" })

            <input type="submit" value="Create" class="btn btn-default" />

}

Answer: Amigo,
Veja se isso resolve seu problema:
Na sua Model inicialize a sua Lista.
public UsuarioModel() {
     DepartamentoSelecionado = new List<SelectListItem>();
}

Comment: Bom dia, mesmo inicializando a lista na model, o mesmo erro acontece:

System.InvalidOperationException: 'Não existe item ViewData do tipo 'IEnumerable' que possui a chave 'DepartamentoSelecionado'.'
Answer: Haviam dois erros em meu código que retornavam erros no cadastro.
O primeiro estava na função que insere no banco de dados:
 public bool CadastraUsuario(UsuarioModel Usulist)
    {
    // código omitido

        string query = "insert into usuario(nome, id_departamento) values ('" + Usulist.Nome + "', '" + Usulist.DepartamentoSelecionado + "')";

    // código omitido
    }

No final da string, eu estava passando a string que selecionava o departamento. O correto é passar o ID do departamento selecionado. no caso ficou:
 public bool CadastraUsuario(UsuarioModel Usulist)
    {
    // código omitido

        string query = "insert into usuario(nome, id_departamento) values ('" + Usulist.Nome + "', '" + Usulist.Id_Departamento + "')";

    // código omitido
    }

Outro erro estava na ViewBag, dentro da View
  @Html.DropDownListFor(model => model.DepartamentoSelecionado, ViewBag.departamentos as SelectList, new { @class = "form-control" })

Eu alterei para que a model receba o Id_Departamento ao invés de receber string de listagem de Departamento (DepartamentoSelecionado) e cadastrou.
Answer: Cara, criar um método privado que popula suas viewBags e chamada na actionResult Cadastrar no verbo GET e no POST, a mensagem de erro aparece porque mesmo dando sucesso ou não ao cadastrar, a view de cadastro é chamada novamente, mas desta vez sem as viewBags populadas!
Uma viewBag tem o tempo de vida de 1 request, quando voê chamada a tela de cadastro ela é populada 1 Request, quando é feito um post (2 request) elas já não existem mais.

Erro ao submeter formulário com ASP MVC


Why is a new post not shown in the Latest Topics Block after updating Advanced Forum?

Question: I updated the version of the Advanced Forum module today. I posted a new topic and now it doesn't show on a block I have in the side bar where latest created topics always used to show up.
What can be happening?
Comment: Apparently after some hours it showed up. I'm not sure why it takes hours to show up but, I guess that's how it works...
Comment: did you run the update.php, after you updated? `www.yoursite.com/update.php`
Answer: Some problems get resolved just by being patient for a while. Some of those problems are caused by either of the following:

You should have cleared the cache.
Something required a cron job to run.

If such kinds of actions are not performed (eg because you're not aware they are needed), it is just a matter of time to get such problems resolved automagically ... as illustrated in this specific comment (last paragraph) also.


Span of sine and cosine equals span of positive and negative complex exponentials proof

Question: I need to prove that
$$
\newcommand{\C}{\mathbb{C}}
\newcommand{\span}{\text{span}_\C}
\span\{\cos(kx), \sin(kx)\}=\span\{e^{ikx}, e^{-ikx}\}
$$
This is my proof but I am not 100 % sure it's correct, mainly because I'm not sure I can just define the span of sine and cosine like I do..
My Proof
Using the fact that
$$
e^{ikx}=\cos(kx)+i\sin(kx) \quad \text{and} \quad e^{-ikx}=\cos(kx)-i\sin(kx)
$$
We can write sine and cosine as follows
$$
\cos(kx)=\frac{e^{ikx}+e^{-ikx}}{2} \quad \text{and} \quad \sin(kx)=\frac{e^{ikx}-e^{-ikx}}{2i}
$$
And then we can rewrite the span of cosine and sine using the definition (is this even correct?)
$$
\span\{\cos(kx), \sin(kx)\}=\{a\cos(kx)+b\sin(kx): k\in\mathbb{Z}, a,b\in\C\}
$$
And then substituting the formulas found above and doing some manipulations
$$
\span\{\cos(kx), \sin(kx)\}=\{\left(\frac{a}{2}+\frac{b}{2i}\right)e^{ikx} + \left(\frac{a}{2}-\frac{b}{2i}\right)e^{-ikx}: k\in\mathbb{Z}, a,b\in\C\}
$$
but now we can rewrite
$$
a':=\frac{a}{2}+\frac{b}{2i} \quad \text{and} \quad b':=\frac{a}{2}-\frac{b}{2i}
$$
and notice that $a', b'\in\C$. Therefore we obtain that
$$
\span\{\cos(kx), \sin(kx)\}=\{a'e^{ikx}+b'e^{-ikx}: k\in\mathbb{Z},a',b'\in\C\}=:\span\{e^{ikx}, e^{-ikx}\}
$$
Is this correct? I'm not sure this argument works
Answer: I think your proof is basically correct though, perhaps, too cumbersome. I'd go as follows:$\newcommand{\C}{\mathbb{C}}\newcommand{\span}{\text{span}_\C}$
$$
\begin{cases}\cos(kx)=\frac{e^{ikx}+e^{-ikx}}{2} \\{}\\ \sin(kx)=\frac{e^{ikx}-e^{-ikx}}{2i}\end{cases}\;\;\implies
\span\{\cos(kx), \sin(kx)\}\subset\span\{e^{ikx}, e^{-ikx}\}
$$
and on the other hand:
$$e^{\pm ikx}=\cos kx\pm i\sin kx\implies\span\{\cos(kx), \sin(kx)\}\supset\span\{e^{ikx}, e^{-ikx}\}$$
You can remark that all the involved coefficients are complex ones, too...
Comment: I like how you use the definition of a subset in your proof, it's really nice!


How to select best parameter for polynomial kernel?

Question: I am using LibSVM library for classification. For my problem I am using polynomial kernel and I need to select best parameters (d = degree of polynomial kernel, and C = soft margin constant). The LibSVM guide suggests for grid search for this job. In this library there exists a parameter selection tool (grid.py), but it seems to me this is implemented to tune parameters of RBF kernel (gamma). My questions are:

Is there any other good solution for selecting suitable parameters rather than Grid search?
Can anybody give me some hints / sample code for selecting parameters for polynomial kernel?
Comment: One problem is that for several kernels, the ranges that should be explored are not specified in the documentation (r for the sigmoid and polynomial kernels; d for the polynomial kernel), so even with a grid search you don't know how to setup your grid...
Answer: Grid search is a sensible procedure as @JohnSmith suggests, however it is not the only stable technique.  I generally use the Nelder-Mead simplex algortihm, which I have found to be very reliable and more efficient than grid search as less time is spent investigating areas of hyper-parameter space that give poor models.  If you are a MATLAB user, you can get my implementation of this method here.  Nelder Mead simplex methods are attractive as they don't require gradient information (I suppose you can think of the gradient of the simplex as being an approximation of the local gradient) and is very easily implemented.
Also gradient descent optimisation of the span bound is a good way of optimising the hyper-parameters, see Chapelle et al. (also investigate the other papers that Olivier has written, there are some real gems).
One advantage of grid search however is that it is quite easy to over-fit the cross-validation error (or span bound etc.) when optimising the hyper-parameters, especially if there is little data and many hyper-parameters.  This means you can get a very poor classifier if you tune the hyper-parameters to convergence, so a coarse grid search can often perform better (I have a paper in preparation on this).
Comment: does this method (Nelder–Mead method) really works good for SVM parameter search?I don't know the properties of the method, I am just a little sceptic about applying methods for local optimum search to such tasks.
Comment: yes, I use it all the time.  If you only have a couple of hyper-parameters (any more and grid search is impractical anyway) then the model selection criterion is likely to be fairly unimodal, so local minima are generally not a problem.
Comment: @Dikran Marsupial - Thanks. I've also heard that Grid search is sensitive, thats why I was curious about other options. I will try to use your procedure.
Answer: Why don't you want to use grid search? It seems to me the only stable technique for SVM parameter estimation. Of course you can use adaptive search, but it can save you not so much time, but lead you to some strange results.
And the implementation for CV procedure is pretty standart:
Divide your dataset into two parts: $X_{train}$ and $X_{test}$.
Run cycle through the parameter $d$ {
  Run cycle through $C$ {
    Train SVM with $X_{train}$, $d$ and $C$;
    Test on $X_{test}$;
    Remember the parameters, leading to the best result;
  }
}

Comment: thank you very much for the help. Actually I'm not against Grid search, I wast just wondering if there is other better solution. But your reply gives me a clear idea.
Answer: You can try using a random search algorithm to get near equivalent results as grid search with a lot less work depending on the granularity of your grid. You can read more about it at Dato Blog along with other hyperparameter tuning techniques. This method is relatively quick if you set it up to run in parallel.


Not able to access AWS DynamoDb from Lambda function

Question: Not able to access AWS DynamoDb from Lambda function.
Lambda function:
<code>'use strict';
const AWS = require('aws-sdk');
AWS.config.update({region: 'ap-southeast-2'});

const getUser = async function () {
    console.log('getUser() invoked');
    const documentClient = new AWS.DynamoDB.DocumentClient();
    const params = {
        TableName: 'Users',
        Key: {
          "UserId": "A001"
        }
    };
    console.log('params ', params);
    documentClient.get(params, function (err, data) {
        console.log('============>');
        if (err) {
            console.log('error ', err);
            return err;
        }
        console.log('success ', data);
        return data;
    });
};

exports.handler = async (event, context, callback) => {
    // TODO implement
    console.log('event ', event);
    const data = await getUser();
    console.log('=============> data ', data);
};
</code>
While testing Lambda function, data is printing undefined. it is printing params but not printing error and success.
Comment: Any errors in CloudWatch Logs?
Comment: Is your Lambda function configured to use a VPC? If so, this means it does not have Internet access unless a NAT Gateway or VPC Endpoint is provided.
Comment: No lambda function is not configured to use a VPC. I am trying in AWS management console. Do i need to configure VPC in AWS console ?
Comment: No error is being reported in CloudWatch.
Answer: you're making some confusing about callbacks and promises here, the way you have now you are not passing the data outside.
<code>const getUser = async function () {
  console.log('getUser() invoked');
  const documentClient = new AWS.DynamoDB.DocumentClient();
  const params = {
      TableName: 'Users',
      Key: {
        "UserId": "A001"
      }
  };
  console.log('params ', params);
  try {
    const data = await documentClient.get(params).promise();
    console.log('============>');
    console.log('success ', data);
    return data;
  } catch(err) {
    console.log('error ', err);
    throw err;
  }
};
</code>
to more about callback and promises check


What does the stat WHIP in baseball mean?

Question: Can someone please explain to me what the statistic "WHIP" means in the game of baseball?
Answer: The definition of WHIP or Walks plus Hits per Inning Pitched is the following per Wikipedia:
<code> WHIP = (Walks + Hits)/(Innings Pitched)
</code>
Cautionary note: While WHIP is a common statistic in fantasy baseball, it's a rather poor tool for evaluating pitchers as it fails to account for something pitchers have little control over (BABIP).
Comment: I agree it is a poor tool for evaluating in any given game.  But over a season or 10+ games your better pitchers tend to have lower WHIP
Comment: you are much better off using FIP or xFIP to evaluate pitchers even over the course of a season. It attempts to account for the randomness that exists due to BABIP (and with xFIP home runs).
Comment: @Chad this is true. However I've seen BABIP be seriously skewed for entire seasons...
Comment: For a team, league, or pitcher?
Comment: WHIP is just another stat.  you could have a WHIP < 1 and an ERA > 7 if all you give up are home runs.  WHIP ERA and IP are the 3 stats that mean the most to me.  K's are a great stat but if they do not come with a low WHIP ERA And IP then they dont mean anything.
Comment: @Chad you might want to start reading fangraphs.com then. Most of those stats are considered widely outdated (IP still means something, but without looking at the leverage index its kinda blah). WHIP and ERA are both incredibly overrated by the media.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/2786/discussion-between-wax-eagle-and-chad)
Comment: Props for mentioning BABIP. Like so many other stats, WHIP is helpful in the proper context. Not that you should ever rely on just 1 statistic to judge a player, but WHIP is probably a better stat to judge someone than, say, wins.
Answer: In addition to the popular answer above, it's also useful to note that WHIP was originally conceived of as a statistic used to score pitchers in fantasy baseball.
So while WHIP is not widely used in sabremetrics communities to help rank the usefulness of pitchers, it is a useful statistic to understand in fantasy circles as well as use as an indicator of future ERA performance.  Ex:  Lower WHIP generally coincides with lower ERA.  Since ERA is such an established stat (for legitimate reasons or not), WHIP can be used as a tool to forecast future performance of a pitcher's ERA.
Answer: WHIP stands for "walks and hits (allowed) per inning pitched." It is a measure of the rate at which a pitcher allows opposing batters to get on base.
I don't quite agree with another answerer who says it's a "poor tool" to evaluate pitchers. The "walks" or W part of the equation are entirely under control of the pitchers. What the other person meant was that HITS aren't regarded as entirely under the control of pitchers, because of fielding issues.
There are two more items that define a pitcher. Strikeouts aren't explicitly included in the WHIP formula, but they feed indirectly into the "hits" part of the equation; the more strikeouts, the fewer opportunities for hits.
The last thing is home runs, (or other extra base hits). All other things equal, a pitcher with a lower WHIP than another will give up fewer runs, but a pitcher with a low WHIP and a high home run rate (e.g. the Pittsburgh Pirates' Edinson Volquez) might still give up a lot of runs.


Is there a way to know which number of the list without index in Python?

Question: I'm solving a problem, for example
w[0]=16*5 # K is the number of terms to be added.
for n in range(1,K+1) : long_div(w,5*5,w)
Assuming that long_div(w,5*5,w) is called K times,
I would like to put the values of 16*(1/5), 16*(1/5)^3, 16*(1/5)^5... into w,
If i call w, I think it is impossible to grasp it without index. is this
possible in python?
The problem feature, function and parameter is not to be touched.
Comment: If I understood correctly, you can use `n` as index value and then put it in your formula.
Answer: You must always call functions with variables. In this case, you are calling long_div with the variable w which must be defined elsewhere.
All you need to do is replace the occurrences of w in your function call with the formula that you gave in the question. To do this, it will be easiest to create a local variable that will hold the outcome of the formula.
for n in range(1, K+1):
    f = 16 * (1/5) ** (n*2 - 1)
    long_div(f, 5*5, f)

we use the formula: 16 * (1/5) ** (n*2 - 1) here as it produces the sequence of calculations that you put in the question.
Comment: I'm not sure what you mean with "you must always call functions with variables"?
Answer: #This would solve your problem

using python 2.xxx
let us take k as 4
K = 4
let us assign the values of w to a list
w = [16*(1/5), 16*(1/5)^3, 16*(1/5)^5]
now we loop and assign them
for n in range(1,K+1):
    print long_div(w[n], 5*5 , w[n])
Comment: yikes, quite the formatting scheme you got going on


exim4 not sending email as intended

Question: I am setting up a server that needs to be able to send email from my email account that I have through my hosting provider "JustHost". I have been trying to get it to work with internet and smarthost options but I never get the email. I am trying to send the email from php but don't get any errors nor email sent. I have tried following several tutorials and can not figure it out. Basically what I want is for my server to send email from my hosting provider email account lets say email@example.com
I know the SMTP servers would be mail.testing.com I don't need to receive mail only send it. I had seen in a tutorial where they talked about ISP's block port 25 so when I try to connect to my JustHost account with telnet using the ip address of the JustHost server it never goes through on port 25 but on port 465 it is able to connect. I am not sure if this could be my problem. I see when I try to send mail from the command line in verbose mode it says retry time not reached for any host Can someone please provide me with some insight on setup or what I might be doing wrong? Thanks
Comment: It would appear that your ISP is indeed blocking port 25, so the obvious solution would be to use whatever other port JustHost allow. The most common one would be 587; I'm sure that the support staff at JustHost can help you.
Comment: (Also, if you're going to use a fake domain name, the one to use is `example.com`. Don't use any random domain that may belong to someone else, as `testing.com` does.)
Answer: If I understand well, you want this server to connect to the SMTP and send an email which is hosted with JustHost via PHP.
You will have to authenticate via PHP first, then send the email on the specific port they provide (Secure SMTP or non secure SMTP).
If we check at the web page of the thunderbird, they provide the basic informations to set up:
https://my.justhost.com/cgi/help/608
Here they use the Port 25 (non encrypted).
You could try to send an email via with the code I found on this website and which include SMTP authentication step (but you can find any other php scripts):
http://support.webecs.com/KB/a390/php-mail-script-with-smtp-authentication.aspx
Let me know if that helps or provide us more information on what you want to do.
If you need more information, try to run the script via CLI with the php-cli tools.
Comment: I had to use another comment to add another link :|

Also I found this topic in case your emails are sent with the wrong "From:":

https://my.justhost.com/cgi/help/206

exim4 not sending email as intended


$T_0$ is MVUE for $\gamma(\theta)$ and $T_1$ is an u.e. for $\gamma(\theta)$ with efficiency 0.0169. Then corr($T_0,T_1$ )?

Question: The estimator $T_0$ is MVUE for $\gamma(\theta)$ and  $T_1$ is any other unbiased estimator for $\gamma(\theta)$ with efficiency 0.0169. Then what is the correlation coefficient between $T_0$ and $T_1$ ?
Comment: See our policy on [self-study](https://stats.stackexchange.com/tags/self-study/info) questions.
Answer: There is a simple one-line proof if you know that a necessary and sufficient condition for an unbiased estimator to be UMVUE is that it must be uncorrelated with every unbiased estimator of zero.
Note that $T_1-T_0$ is an unbiased estimator of zero.
So you have $$\operatorname{Cov}_{\theta}(T_0,T_1-T_0)=0\quad\forall\,\theta\in\Theta$$
Use this to arrive at a simple expression for $\operatorname{Corr}_{\theta}(T_0,T_1)$ in terms of the efficiency of $T_1$.


Android Using same fragment multiple times - how to have different onclick actions

Question: Lets say I have a fragment MyFragment and I create myFragment1 and myFragment2. Both share the same xml layout which is just a image button. Using onClick, how can I make it so that clicking either button doesn't do the same thing?
For example, if I want myFragment1's button to go to Activity A, and I want myFragment2's button to go to Activity B.
Sample code below:
public class MyFragment extends Fragment implements View.OnClickListener{

    ImageButton myButton;
    View view;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_device, container, false);

        myButton = (ImageButton) view.findViewById(R.id.myButton);
        myButton.setOnClickListener(this);

        return view;
    }

    @Override
    public void onClick(View v){
        //do something
    }
}

From my MainActivity:
public class MainActivity extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        LinearLayout windowForMainActivity = (LinearLayout) findViewById(R.id.windowForMainActivity);

        MyFragment myFragment1 = new MyFragment();
        fragmentTransaction.add(windowForMainActivity.getId(),myFragment1);

        MyFragment myFragment2 = new MyFragment();
        fragmentTransaction.add(windowForMainActivity.getId(),myFragment2);

        fragmentTransaction.commit();
    }
}

Answer: First from your activity send data to fragment like this
Bundle bundle = new Bundle();
bundle.putString("some_value", "ActivityA");
MyFragment myFragment1 = new MyFragment();
myFragment1.setArguments(bundle);
fragmentTransaction.add(windowForMainActivity.getId(),myFragment1);

Bundle bundle2 = new Bundle();
bundle2.putString("some_value", "ActivityB");
MyFragment myFragment2 = new MyFragment();
myFragment2.setArguments(bundle);
fragmentTransaction.add(windowForMainActivity.getId(),myFragment2);

And then get the value like this
String whichActivity;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    whichActivity = getArguments().getString("some_value");
    return inflater.inflate(R.layout.fragment, container, false);
}

@Override
    public void onClick(View v){
        if(whichActivity.equals("ActivityA")){
          //code to start Activity A
        }else{
         //code to start activity B
        }
}

Answer: Since you've made the class implement the interface, when you create the Fragment, you can override the onClick.
MyFragment frag1 = new MyFragment() {
    @Override
    public void onClick(View v) {
        Intent i = new Intent(MainActivity.this, ActivityA.class);
        MainActivity.this.startActivity(i);
    }
};

MyFragment frag2 = new MyFragment() {
    @Override
    public void onClick(View v) {
        Intent i = new Intent(MainActivity.this, ActivityB.class);
        MainActivity.this.startActivity(i);
    }
};

Of course, there could be better ways to do that within the Fragment class itself using Bundle arguments, for example.


UDP receivers program priority?

Question: I have 2 identical programs running on same Linux host (Centos 7), listening to same UDP channel.  I haven't fiddle with their running priority (nice-ness).  The server is an 8-core box.  The 2 programs are running on the cpus on the same NUMA node.  It's just one starts after the other.  What determines the priority of which application will get the data first from the kernel buffer?  Is there anyways to change the priority?
Answer: From what I found you can't.
Read
Socket options SO_REUSEADDR and SO_REUSEPORT, how do they differ? Do they mean the same across all major operating systems?
basically in linux it is random if you let multiple sockets listen on the same port.

UDP receivers program priority?


Clear TextBoxes when uncheck CheckBox in Data DataGridView

Question: With this a CheckBox in a DataGridView2 in FormLoad
  Dim chk1 As DataGridViewCheckBoxColumn = New DataGridViewCheckBoxColumn()
  DataGridView2.Columns.Add(chk1)
  chk1.HeaderText = "Keuze"
  chk1.Name = "chk"

When select a CheckBox filling some textboxes
 Private Sub DataGridView2_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView2.CellContentClick
     If e.ColumnIndex = 0 AndAlso e.RowIndex >= 0 Then
         For Each row As DataGridViewRow In DataGridView2.Rows
             row.Cells(e.ColumnIndex).Value = False
         Next
     End If
     Dim senderGrid As DataGridView = sender
     Dim data = senderGrid.Rows(e.RowIndex).DataBoundItem

     If senderGrid.Columns(e.ColumnIndex).GetType() Is GetType(DataGridViewCheckBoxColumn) And e.RowIndex >= 0 Then
         TBterug.Text = DataGridView2.CurrentRow.Cells("Todo").Value.ToString()
         CBbelangrijkterug.Text = DataGridView2.CurrentRow.Cells("Belangrijk").Value.ToString()
         Id.Text = DataGridView2.CurrentRow.Cells("Id").Value.ToString()
         LBdelete.Visible = True
         LBuncheck.Visible = True
     End If

 End Sub

But when i Uncheck the CheckBox i want to Empty the TextBoxes , what do i have to add to make this work ?
I tryed this but no luck Check/Uncheck a checkbox on datagridview
Comment: Looks like the first thing you do is clear out the check mark, is that correct?
Comment: I can only select one CheckBox then it fills the TextBoxes.  Yes , first i want to uncheck it and then it has to clear the Textboxes .
Answer: If you want to allow only one selection, don't wait for another selection to be committed and take early action to prevent it. In the DataGridView control, such action can be taken by handling the CurrentCellDirtyStateChanged to call the DataGridView.CancelEdit method if the CurrentCell belongs to the target DataGridViewCheckBoxColumn and it's not currently checked but it's dirty and there are uncommitted changes.
For example:
Private Sub DataGridView2_CurrentCellDirtyStateChanged(sender As Object, e As EventArgs) Handles DataGridView2.CurrentCellDirtyStateChanged
    Dim dgv = DirectCast(sender, DataGridView)

    If TypeOf dgv.CurrentCell Is DataGridViewCheckBoxCell AndAlso
        dgv.IsCurrentCellDirty AndAlso
        Not CBool(dgv.CurrentCell.FormattedValue) Then

        Dim col = dgv.CurrentCell.ColumnIndex

        If dgv.Rows.Cast(Of DataGridViewRow).
            Any(Function(row) CBool(row.Cells(col).FormattedValue)) Then
            dgv.CancelEdit()
        End If
    End If
End Sub

Now, to reset the display and command controls before committing the changes, handle the DataGridView.CellContentClick event to clear and fill/show/enable the controls if the DataGridViewCell.EditedFormattedValue property is true, or just clear/disable/hide them if the DataGridViewCell.FormattedValue property is true.
Private Sub DataGridView2_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView2.CellContentClick
    If e.ColumnIndex = 0 AndAlso e.RowIndex >= 0 Then
        Dim dgv = DirectCast(sender, DataGridView)
        If CBool(dgv(e.ColumnIndex, e.RowIndex).EditedFormattedValue) Then
            ResetControls(dgv.Rows(e.RowIndex))
        ElseIf CBool(dgv(e.ColumnIndex, e.RowIndex).FormattedValue) Then
            ResetControls()
        End If
    End If
End Sub

Private Sub ResetControls(Optional row As DataGridViewRow = Nothing)
    If row IsNot Nothing Then
        TBterug.Text = row.Cells("Todo").Value?.ToString()
        CBbelangrijkterug.Text = row.Cells("Belangrijk").Value?.ToString()
        Id.Text = row.Cells("Id").Value?.ToString()
        LBdelete.Visible = True
        LBuncheck.Visible = True
    Else
        TBterug.Text = ""
        Id.Text = ""
        CBbelangrijkterug.Text = ""
        LBdelete.Visible = False
        LBuncheck.Visible = False
    End If
End Sub

Answer: Thanks for the answer dr.null i will take a look at it.
But for now.
Found a solution here , and made it work with a ButtonClick.
Used this chk.Value = chk.FalseValue
Check/Uncheck a checkbox on datagridview
In FormLoad
Dim CheckboxColumn As DataGridViewCheckBoxColumn = New DataGridViewCheckBoxColumn()
CheckboxColumn.TrueValue = True
CheckboxColumn.FalseValue = False
CheckboxColumn.Width = 10
DataGridView2.Columns.Add(CheckboxColumn)
DataGridView2.Rows.Add(1)
CheckboxColumn.HeaderText = "Keuze"
CheckboxColumn.Name = "chk"

And
Private Sub DataGridView2_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView2.CellContentClick
     If e.ColumnIndex = 0 AndAlso e.RowIndex >= 0 Then
         For Each row As DataGridViewRow In DataGridView2.Rows
             row.Cells(e.ColumnIndex).Value = False
         Next
     End If
     Dim senderGrid As DataGridView = sender
     Dim data = senderGrid.Rows(e.RowIndex).DataBoundItem

     If senderGrid.Columns(e.ColumnIndex).GetType() Is GetType(DataGridViewCheckBoxColumn) And e.RowIndex >= 0 Then
         TBterug.Text = DataGridView2.CurrentRow.Cells("Todo").Value.ToString()
         CBbelangrijkterug.Text = DataGridView2.CurrentRow.Cells("Belangrijk").Value.ToString()
         Id.Text = DataGridView2.CurrentRow.Cells("Id").Value.ToString()
         BTdelete.Visible = True
         BTreturn.Visible = True

     End If

End Sub

Added a Button
 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles BTreturn.Click
     For Each row As DataGridViewRow In DataGridView2.Rows
         Dim chk As DataGridViewCheckBoxCell = CType(row.Cells(0), DataGridViewCheckBoxCell)

         If chk.Value = chk.FalseValue OrElse chk.Value Is Nothing Then

         Else

             chk.Value = chk.FalseValue
             TBterug.Text = ""
             CBbelangrijkterug.Text = ""
             Id.Text = ""
             TBnieuw.Text = ""
             CBbelangrijk.Text = ""
             Id.Text = ""
             BTdelete.Visible = False
             BTreturn.Visible = False
         End If
     Next

     DataGridView2.EndEdit()
 End Sub


Extract number from string with jquery

Question: I need to extract number from string like

etc etc(5)

etc etc(-5)

I'm using this code
alert($("#example").text().match(/\((\d+)\)/)[1]);

It's work fine if the number is positive but in the case of a negative number
get error
Uncaught TypeError: Cannot read property '1' of null

please help me about that
thank's
Answer: Try this:
.match(/\((-?\d+)\)/)[1]

-? says "optional minus".
Comment: `\-?` would probably be a safer habit to develop, as the hyphen is a reserved char which is used to specify character ranges inside []
Comment: meh, just a question of taste really. I like it when rules can be boiled down to the simpler set, especially when teaching. Personally i find it better to get into the practice of knowing the reserved characters and always quoting them, as it is completely safe to do so. The fact that it is unnecessary doesn't interest me. It's easier to follow the same methodology even if it is strictly "not required". ...But i'm not here to continue a religious war :-) I have at least as much respect for your POV as my own.
Comment: @Cheekysoft: I was just [answering](http://stackoverflow.com/a/10593427/240443) that question today. The grammar inside `[]` is very different than outside; I see no reason to pollute one with artifacts of the other.
Answer: Try this instead:
alert($("#example").text().match(/\((-?\d+)\)/)[1]);

That will capture negative numbers as well.

Extract number from string with jquery


How can I revert my last choice on terminal if it shows > symbol?

Question: I'll be glad if someone can fix the title to be more appropriate since I'm pretty new to terminal.
I have an issue with terminal. Once I execute a command, if it goes to the next line, I can't close it or revert it. I assume it starts the executable or asks for more parameters using >
For example:
//Windows Machine
vagrant up

    //Vagrant Instance Unix Machine
    $ git
    >
    >
    >
    > ... it goes on like this, I can't close > so I can't execute other commands

The only solution on fixing is restarting the terminal (which means I need to restart Vagrant instance)
It happens on some commands only - not all, so I don't know what makes a difference.
For example, executing composer, I get information about Composer and terminal goes back to main state. However, if I execute things like php, git, mysql, > symbol appears and I can't return from there.
So, two basic questions;

What causes this?
How can I terminate the current command to go back main state?

Any help would be greatly appreciated.
Ps. I use both windows terminal and unix terminal and this issue happens on both.
Answer: Normally you'll see a > prompt if you've entered a command that's syntactically incomplete, for example if there's a unterminated string literal:
$ echo 'hello
> '
hello

$

It means that the shell is waiting for you to type the rest of the command, or at least enough of it to make for something that's not a syntax error.
In this example, the default prompt, $PS1, is '$ ', and the secondary prompt, $PS2, is '> '. Read the documentation for your shell (probably bash) for more information.
You can cancel the current command and get back to your primary prompt for a new command by typing Control-C.
This is all about the behavior of your shell; it has nothing to do with your terminal (almost certainly a terminal emulator), which merely provides a GUI for your shell to run in.
Comment: Thanks alot! One more thing, what if it doesn't show `>` at all and just goes to next line? For example `php` does it.
Comment: That means the `php` command is waiting for input, presumably PHP code which it will execute. Use Control-C to kill it, or Control-D to indicate an end-of-file condition (the latter will cause the PHP command to execute with empty input). The `git` command with no arguments should show a usage message and then return you to your primary prompt; did it really behave the way you describe? Are you sure `git` is *exactly* what you typed?
Comment: Okay, thank you. Going to mark this as the answer in a minute. Edit: No, I accidently typed something else. `git` shows basic documentation and works normally.


How to save Tensorflow model in S3 (as /output/model.tar.gz) when using Tensorflow Estimator in AWS Sagemaker

Question: I have a Keras model getting trained using an entry_point script and I am using the following pieces of code to store the model artifacts (in the entry_point script).
parser.add_argument('--model_dir', type=str, default=os.environ['SM_MODEL_DIR'])
args, _ = parser.parse_known_args()
model_dir  = args.model_dir
---

tf.keras.models.save_model(
      model,
      os.path.join(model_dir, 'model/1'),
      overwrite=True,
      include_optimizer=True
     )

Ideally, the model_dir should be opt/ml/model and Sagemaker should automatically move the contents of this folder to S3 as s3://<default_bucket>/<training_name>/output/model.tar.gz
When I run the estimator.fit({'training': training_input_path}), the training is successful, but the Cloudwatch logs show the following:
2020-09-16 02:49:12,458 sagemaker_tensorflow_container.training WARNING  No model artifact is saved under the path /opt/ml/model. Your training job will not save any model files to S3.

Even then, Sagemaker does store my model artifacts, with the only difference being that instead of storing them in s3://<default_bucket>/<training_name>/output/model.tar.gz, they are now stored unzipped as s3://<default_bucket>/<training_name>/model/model/1/saved_model.pb along with the variables and assets folder. Because of this, estimator.deploy() call fails as it is unable to find the artifacts in the output/ directory.
Sagemaker Python SDK - 2.6.0

Estimator code:
from sagemaker.tensorflow import TensorFlow

tf_estimator = TensorFlow(entry_point='autoencoder-model.py',
                       role=role,
                       instance_count=1,
                       instance_type='ml.m5.large',
                       framework_version="2.3.0",
                       py_version="py37",
                       debugger_hook_config=False,
                       hyperparameters={'epochs': 20},
                       source_dir='/home/ec2-user/SageMaker/model',
                       subnets=['subnet-1', 'subnet-2'],
                       security_group_ids=['sg-1', 'sg-1'])

What could I be doing wrong here?
Comment: hi @inderpartap Cheema , did you find answer for this, running into similar issue
Comment: Same issue for me.
Answer: Update:
parser.add_argument('--model_dir', type=str, default=os.environ['SM_MODEL_DIR'])

to:
parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])

will work for me.  The parser.add_argument converts hyphens to underscores, so you can reference args.model_dir still.
Sagemaker container will save the trained model in 'model-dir' and then make a zip file from this directory and upload to 's3 bucket' of location 'model_dir'.
'model-dir' is the location inside the container /opt/ml/..
'model_dir' is mapped with the 'output_path' which we define in:
tf_estimator = TensorFlow(entry_point='autoencoder-model.py', role=role,output_path=output_path,.....)

Hope this will help to resolve the isssue.


Why does Libera wear earpieces?

Question: I listen a fair amount to the Libera Children's Choir, and one of the things that I've noticed is that frequently they wear ear-pieces in one ear or the other (For instance, Joshua Madine in his right ear here on Youtube).
I did a bit of research on this, and didn't find anything about Libera in particular, but I did find this article on Quora that says that sometimes singers will wear them to basically block out extreanuous noises on stage.  This seems rather unlikely in this case, however, since they're only accompanied by a single violin and an organ.
Why do they wear earpieces?  What are they listening to?
Answer: A monitoring mix, possibly even with some reference instruments in it for intonation.  But even without such a reference, a frequent problem in acoustic stage settings is that the acoustics are built for broadcasting the sound to the audience rather than the stage.  I've sung in circumstances where we had to work with sound walls to have a chance at sensible a capella singing.  If you can't hear the other singers, common intonation is not realistic.
When you are not in control of the stage acoustics (and when you are just one of multiple acts, that's more likely than otherwise), owning a monitoring setup like that will allow you to be a dependable quality act, assuming that you are not going to stoop to playback performance (actually quite common for commercialized music shows featuring multiple artists).
Answer: I only watched for a few seconds but it's clear that it is in-ear monitoring.
It may be that there's a click track running in the earpiece to keep them in time; maybe it's to make sure they can hear the accompaniment and keep in time with that in the echo acoustic of the church; or maybe they're actually miming to a pre-recorded track, and the monitoring is to make sure they keep in time.
Big floor wedges would look incongruous in that setting, so in-ear is a good visual as well as technical choice.
Answer: I think it might be for listening to the clicks of track or also known as a metronome. It could also block out some the sound so they can focus in their voices. They might also have to have them for other reasons. But, I think it is mainly for keeping them in time!

Why does Libera wear earpieces?


Automatically Select First UITableView Textbox

Question: I have a tableview that accepts login credentials. I would like to have my app automatically select the first tableview text box upon loading or appearing. I would like the cursor to be placed in the "Email Address" field and for the keyboard to be raised automatically. I can't seem to figure this out. Anyone have any ideas? Thank you!
Comment: Use this `[emailTextField becomeFirstResponder];`
Comment: I suggest you must have static table view, you can have IBOutlets to textfield and make it the first responder in view did load or view did appear.
Answer: You have to assign the first responder to that UITextView...
For example:
[textField becomeFirstResponder]

You can do it in the viewDidAppear of the UIViewController.
Answer: - (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];

myTextField = (UITextField *)[cell viewWithTag:kMyTextFieldTag];
[myTextField becomeFirstResponder];
}


problem with hooking node add/edit form

Question: I wanted to hook node/add/patient-history form because I wanted to add ajax in that form.
Before adding Ajax I wanted to get field names correctly. So I tried this:
function ajaxify_form_patient_history_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_history_patient_id']['und'][0]['#value'] = "Hello";
  // I also tried
  $form['field_history_patient_id']['#value'] = "Hello";
}

They are not working.
I am not sure if I am taking the field names incorrectly or missing something else.
Hook name seems to be correct because this one works:
  $form['actions']['submit']['#value'] = t('Save History');

I found some similar questions on stackexchange but with no answers.
Any advice/links appreciated very much. Thank you.
Comment: You can `print_r($form)` to get to know the exact field name.
Comment: That is how I got this name. But this is not working.
Comment: Yes this seems to be proper and I have updated question reasoning why it seems to be proper. Please read the update. Thank you.
Answer: I use this in my module to prepopulate the forms with data when hooking on FORM_ALTER:
$form['field_history_patient_id'][LANGUAGE_NONE][0]['value']['#default_value'] = "whatever";

But when defining the form it is enough to do :
$form['field_history_patient_id']['#default_value'] = "whatever";

Comment: Thank you drcelus. This adds the value to the field.  But unfortunately it is not working for adding prefix and suffix. I tried this but not working. `$form ['field_username'][LANGUAGE_NONE][0]['value']['#prefiex'] = '';` I cant see the div and id added in firebug. It would be great help if you could think of a way to add prefix and suffix too. I could not. Thank you :)
Comment: I see a typo in your code "prefiex". Otherwise maybe you should issue a new question for this.
Comment: Exactly ! How foolish of me !! It was a typo. Works perfectly now :) :) But I still have doubts regarding why these things work differently in different forms.
Answer: Check Why is hook_form_alter so messy in d7?.
If you have Devel module installed, you can check your fields with dpm($form) in your hook or you can use echo '
'; print_r($form); echo '
'.
I hope this will help you to track down your element hierarchy and find out the correct attributes.
Answer: You need to set the #default_value property. $form['field_history_patient_id']['#default_value']
Comment: I have tried that already. It doesnot work. Thank you for your response though.
Comment: Strange, when I test this it works fine. Try raising your module's weight manually in the system table "UPDATE system SET weight = 20 WHERE name='ajaxify_form'"

problem with hooking node add/edit form


sending request to wso2 identity server

Question: am trying to send a request to the identity server but don't know how to do it.  I know that identity server can help you test your policy by generating a request for you within the identity server but I don't know how to do this outside the identity server.  So my question is how do I sent requests to identity server in order to have it check the request against the policy and return to me a result.  I have tried the blog at http://hasini-gunasinghe.blogspot.com/2011/12/entitlement-service-xacml-pdp-as-web.html and it is not working.  thank you
Comment: why you need to invoke the identity server? what is the functionality you expect from that.
Comment: hello, I want identity server to act as an entitlement engine but am having trouble sending requests to it, I have already uploaded the policies onto the identity server, I now need to know how to send a request to the Identity server, have it evaluate the request and send back a decision.  Identity server lets you test your policy by providing means to create a request but I would like to send a request from my computer to the Identity server. thank you
Answer: I tried the code in the blogpost and could get it worked with the following settings with WSO2 Identity Server 4.1.0 in localhost. Don't forget to give correct path to the wso2carbon.jks.
<code>import org.apache.axis2.AxisFault;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub;
import org.wso2.carbon.identity.entitlement.stub.EntitlementServiceStub;
import org.wso2.carbon.identity.entitlement.ui.client.EntitlementServiceClient;

public class EntitlementClient {

private static String serverUrl = "https://localhost:9443/services/";

private AuthenticationAdminStub authstub = null;
private static ConfigurationContext ctx;
private static String authCookie = null;
private static EntitlementServiceClient entitlementServiceClient;
private static EntitlementServiceStub stub;
//sample XACML request captured from TryIt tool of IdentityServer.
private static String sampleRequest = "<Request xmlns=\"urn:oasis:names:tc:xacml:2.0:context:schema:os\"\n" +
        "         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
        "    <Resource>\n" +
        "        <Attribute AttributeId=\"urn:oasis:names:tc:xacml:1.0:resource:resource-id\"\n" +
        "                   DataType=\"http://www.w3.org/2001/XMLSchema#string\">\n" +
        "            <AttributeValue>ABCResource</AttributeValue>\n" +
        "        </Attribute>\n" +
        "    </Resource>\n" +
        "    <Subject>\n" +
        "        <Attribute AttributeId=\"urn:oasis:names:tc:xacml:1.0:subject:subject-id\"\n" +
        "                   DataType=\"http://www.w3.org/2001/XMLSchema#string\">\n" +
        "            <AttributeValue>admin</AttributeValue>\n" +
        "        </Attribute>\n" +
        "        <Attribute AttributeId=\"http://wso2.org/claims/role\"\n" +
        "                   DataType=\"http://www.w3.org/2001/XMLSchema#string\">\n" +
        "            <AttributeValue>admin</AttributeValue>\n" +
        "        </Attribute>\n" +
        "    </Subject>\n" +
        "    <Action>\n" +
        "        <Attribute AttributeId=\"urn:oasis:names:tc:xacml:1.0:action:action-id\"\n" +
        "                   DataType=\"http://www.w3.org/2001/XMLSchema#string\">\n" +
        "            <AttributeValue>read</AttributeValue>\n" +
        "        </Attribute>\n" +
        "    </Action>\n" +
        "    <Environment/>\n" +
        "</Request>";

public static void main(String[] args) {

    try {

        //set trust store properties required in SSL communication.
        System.setProperty("javax.net.ssl.trustStore",
                "/home/pushpalanka/Servers/wso2is-4.1.1/repository/resources/security/wso2carbon.jks");
        System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");

        //initialize authentication admin stub
        EntitlementClient remoteEntitlementClient = new EntitlementClient();
        //login using authentication admin stub providing valid credentials
        remoteEntitlementClient.login("admin", "admin");
        //initialize entitlement service stub with obtained authentication cookie
        remoteEntitlementClient.initEntitlementClient();
        //invoke EntitlementService by passing the XACML request and obtain the authorization decision
        String decision = entitlementServiceClient.getDecision(sampleRequest);
        //print the authorization decision
        System.out.println(decision);

    } catch (Exception e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }

}

public EntitlementClient() {
    try {
        ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
        String authEPR = serverUrl + "AuthenticationAdmin";
        authstub = new AuthenticationAdminStub(ctx, authEPR);
        ServiceClient client = authstub._getServiceClient();
        Options options = client.getOptions();
        options.setManageSession(true);
        options.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, authCookie);
    } catch (AxisFault axisFault) {
        axisFault.printStackTrace();
    }
}

public String login(String username, String password) throws Exception {
    //String cookie = null;
    boolean loggedIn = authstub.login(username, password, "127.0.0.1");
    if (loggedIn) {
        System.out.println("The user " + username + " logged in successfully.");
        authCookie = (String) authstub._getServiceClient().getServiceContext().getProperty(
                HTTPConstants.COOKIE_STRING);
    } else {
        System.out.println("Error logging in " + username);
    }
    return authCookie;
}

public void initEntitlementClient() throws AxisFault {
    entitlementServiceClient = new EntitlementServiceClient(authCookie, serverUrl, ctx);
}
</code>
}
Reference - http://hasini-gunasinghe.blogspot.com/2011/12/entitlement-service-xacml-pdp-as-web.html

sending request to wso2 identity server


Ocultar TabBar e Mostrar UIToolbar

Question: No meu projeto eu tenho uma TableView dentro de navigation controller
(TabBar > Navigation Controller > TableView Controller)
Quando aciono o botão Editar a TabBar está sendo ocultada e mostrando o Toolbar, porém ele não está ajustando no rodapé.
Como posso ajustar isso ?
Estou usando Storyboard e Swift.
Answer: Para dar hidden na TabBar
Adicione está linha no ViewDidLoad() do swift :
self.tabBarController?.tabBar.hidden = true

Para mostrar o UiToolBar
E no ViewDidLoad() tente isto aqui também
toolBar.barStyle = UIBarStyle.Black
       self.view.addSubview(toolBar)

Exemplo :
import UIKit

class ViewController: UIViewController {

var toolBar = UIToolbar(frame:CGRectMake(0, 524, 320, 44))

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tabBarController?.tabBar.hidden = true

        toolBar.barStyle = UIBarStyle.Black
       self.view.addSubview(toolBar)

    }
}

Ocultar TabBar e Mostrar UIToolbar


What is speed of using keysSortedByValueUsingComparator method on a NSMutableDictionary

Question: I have a NSMutableDictionary that I want to print out as key: value in sorted order (where the keys are such that key with lower value is printed first).
To do this, I am using the keysSortedByValueUsingComparator: method of NSDictionary like below.
Does anyone know if the underlying implementation uses a quick sort like approach and achieves O(N*logN) or is it comparing every object with every other object leading to O(N^2) complexity?
Example:
NSMutableDictionary *hashTable = [[NSMutableDictionary alloc] init];
....
code that adds a bunch of Objects to the hashtable dictionary with key = NSString and value = NSNumber object
....
NSArray * sortedKeys = [hashTable keysSortedByValueUsingComparator:^(id  _Nonnull obj1, id  _Nonnull obj2) {
           if ([obj1 integerValue] > [obj2 integerValue])
           {
               return (NSComparisonResult)NSOrderedDescending;
           }

           if ([obj1 integerValue] < [obj2 integerValue])
           {
               return (NSComparisonResult)NSOrderedAscending;
           }

           return (NSComparisonResult)NSOrderedSame;
       }];

for (NSString *nextKey in sortedKeys)
{
   NSLog(@"%@: %@",nextKey,hashTable[nextKey]);
}

Comment: The only relevant question is: is it fast enough for my app?  I think it's safe to assume that Apple programmers are not complete idiots, and don't use a bubble sort for this method.
Comment: @Yvette, exactly why I voted to close.
Answer: It appears to use a merge sort - which of course is O(n log n). Other sorting methods are known to use quicksort.
How to guess: Place a breakpoint inside your comparator block and read the stack trace when it gets hit. In your code you'll see the comparator is being called by CFSimpleMergeSort. It's a good guess that is a merge sort unless Apple programmers have an interesting naming scheme!
Maybe how to find out for sure: The main NS collections are toll-free bridged to their CF counterparts, and CF source is available from Apple's open source site. Search for CFArray.c, CFDictionary.c etc. and you'll find the source. This will not include all the NS methods, hence the "maybe find out", but it shows how these types work.
HTH
Comment: On a previous WWDC Apple explained they are using various strategies to sort arrays. I wouldn't draw conclusions from _one_ example.
Comment: @gnasher729 - That is true. A few different data set sizes (10, 1000, 1000000) were used to see if the algorithm was changed and it appeared not to be – that is *not* definitive in anyway of course, but it is a reasonable guess they are sticking with merge sort here. Looking at Apple's open source, for those types it is available, will be definitive.


What is/how do I get the Device Tree Compiler?

Question: I am trying to program a Xilinx zc706 board, which involves building a Linux kernel and setting up the bootloader. I am following the workflow given here.
The first step after downloading stuff involves making the device tree compiler, which I need to get UBoot, which I need to start up linux. I obtained the source for DTC off github, but when I went into the SDK shell, moved to the directory, and entered "MAKE", I got an error:

sed: -e expression #1, char 1: unknown command: `''
-x was unexpected at this time.
"       " LEX convert-dtsv0-lexer.lex.c
process_begin: CreateProcess(NULL,flex -oconvert-dtsv0-lexer.lex.c convert-dtsv0-lexer.1, ...) failed.

and then followed with some other stuff saying files could not be found, presumably because this first thing failed.
I have no idea how to read this error, it's gibberish to me. Can someone explain either what's wrong with this build, or how I can get either the DTC or UBoot I would need to run a Zynq chip?
Answer: It looks like you're making things much harder on yourself by doing manually what PetaLinux will do automatically for you.  Unless you're a die-hard Linux purist and want to build your embedded Linux system from scratch, you should stop reading after the first paragraph of the link you posted and head to the PetaLinux wiki page.
Follow the steps in the PetaLinux Tools Reference Guide to get your project up and running.  It will handle building u-boot, rootfs, linux kernel, and device tree compiler for you (petalinux-* commands) and you can focus on developing your application.


line integral, then mass of the line

Question: I have a line is lying along the curve parameterized at $x = 5cos (t), y = 5sin (t), z = 2t$ for $0≤t≤\pi$.
What is the mass of the wire if its mass density is given by$ ρ (x, y, z) = z?$
I have tried this for a long time, cant seem to figure out the correct answer, im sure its simple tho.
How do i calculate the mass of this wire, and how do i calculate it the correct way?
Comment: What about the previous one? I suggest to solve at least one problem. Can you proceed by the hints?
Comment: yeah im trying, but still cant get it right. how do i do it completly? so i can try to backtrack it and then figure out what i did wrong/right ish.
Comment: please try to solve and show your work here, I will take  alook to it.
Comment: I've tried a lot. and im not sure how to type it all in here aswell, im new here. could u please show me instead then i can se what i did wrong
Comment: you should use https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: as an alternative you can upload a pic of your work
Answer: HINT

consider the parametrization $((x(t),y(t),z(t))\quad t\in [0,\pi]$
set up and calculate the line integral $\int_L \rho ds=\int_{0}^{\pi} z(t)\sqrt{x'(t)^2+y'(t)^2+z'(t)^2}dt$

line integral, then mass of the line


Show that $c^2 = d^2 = ab$ in an Argand diagram

Question: I have the following question.

Let $A$ and $B$ be two points on the unit circle $∣z∣$ $=$ $1$ in the Argand diagram. Let $C$ and $D$ be
the midpoints of the minor arc and the major arc of AB on the unit circle. Denote by $a, b, c, d$
the complex numbers representing $A, B, C, D$ respectively.
The question is to show that $c^2 = d^2 = ab$

I am new to complex numbers. I figure out that C and D will be on the same line but this information seems to be useless. Any hint to approach this question? Do i need to convert $A,B,C,D$ into polar form?
Answer: I think your intuition is correct to write the numbers in polar form. That way, if
\begin{equation*}
a = e^{i\theta_{a}}\hspace{1pc} \mbox{ and }\hspace{1pc} b = e^{i\theta_{b}},
\end{equation*}
then $c$ and $d$ (on the minor arc and major arc, respectively) are such that
\begin{equation*}
c = e^{i\frac{\theta_{a}+\theta_{b}}{2}}\hspace{1pc} \mbox{ and }\hspace{1pc} d = e^{i\frac{\theta_{a}+\theta_{b}}{2}}e^{i \pi }
\end{equation*}
where I have used that multiplication by $e^{i\pi}$ rotates $c$ by an angle $\pi$ (so you're absolutely correct that $C$ and $D$ are on the same line). Then
\begin{equation*}
c^{2} = e^{i(\theta_{a}+\theta_{b})}\hspace{1pc} \mbox{ and }\hspace{1pc} d^{2} = e^{i(\theta_{a}+\theta_{b})}e^{i 2\pi} = e^{i(\theta_{a}+\theta_{b})}
\end{equation*}
(because $e^{i2\pi} = \cos{(2\pi)} + i\sin{(2\pi)} =1$) and
\begin{equation*}
ab = e^{i(\theta_{a}+\theta_{b})}.
\end{equation*}
This works analogously if $c$ and $d$ are on the major arc and minor arc, respectively.
Answer: Another way to conduct the proof is to start with a simple specific situation and then generalize it.  Since $ \ C \ $ and $ \ D \ $ are midpoints of the minor and major arcs $ \ \widehat{AB} \ \ $ on the unit circle, then $ \ \overline{CD} \ $ is a diameter of the circle (as you observed) and the perpendicular bisector of the chord $ \overline{AB} \ \ . \ $  If we position $ \ \overline{CD} \ $ on the $ \ x-$axis, then $ \ c_0 \ = \ 1 \ $ and $ \ d_0 \ = \ -1 \ \ . \ $  The endpoints of the perpendicular chord $ \ \overline{AB} \ $ are then the complex conjugates $ \ a_0 \ $ and $ \ b_0 \ = \ \overline{a_0} \ \ . \ $  It is then plain that $ \ c_0^2 \ = \ d_0^2 \ = \ a_0b_0 \ = \ a_0 \overline{a_0} \ = \ 1 \ \ . \ $  (This is the "trivial" case.)
If we now position $ \ C \ $ instead so that it is represented by $ \ c \ = \ \alpha \ + \ i·\beta \ \ , \ $ with $ \ c \overline{c} \ = \ \alpha^2 + \beta^2 \ = \ 1 \ \ , \ $ this has the effect of rotating all of these points on the unit circle by an angle $ \ \theta \ $ given by $ \ \tan \theta \ = \ \frac{\beta}{\alpha} \ \ $ (with appropriate quadrant adjustments).  We then have $ \ d \ = \ (-1)·(\alpha \ + \ i·\beta) \ \ , \ \ a \ = \ a_0·(\alpha \ + \ i·\beta) \ \ $ and $ \ b \ = \ \overline{a_0}·(\alpha \ + \ i·\beta) \ \ . \ $  The equation becomes
$$ c^2 \ = \ (\alpha \ + \ i·\beta)^2 \ \  = \ \ (-1)^2·(\alpha \ + \ i·\beta)^2 \ \ = \ \ d^2 \ \  $$
$$  = \ a_0·(\alpha \ + \ i·\beta)·\overline{a_0}·(\alpha \ + \ i·\beta) \ \ = \ \ ab \ \ = \ \ a\overline{a_0}·(\alpha \ + \ i·\beta)^2  = \ \ (\alpha \ + \ i·\beta)^2 \ \ .  $$
[Since $ \ c \ = \ e^{ \ i \ · \ \theta} \ \ , \ $ we can also write this in the more succinct form
$$ c^2 \ \ = \ \ ( \ e^{ \ i \ · \ \theta} \ )^2 \ \ = \ \ e^{ \ i \ · \ 2 \theta} \ \ = \ \ ( \ -e^{ \ i \ · \ \theta} \ )^2 \ \ = \ \ d^2 $$
$$  = \ a_0·e^{ \ i \ · \ \theta}·\overline{a_0}·e^{ \ i \ · \ \theta} \ \ = \ \ ab \ \ = \ \ a\overline{a_0}·(e^{ \ i \ · \ \theta})^2  = \ \ e^{ \ i \ · \ 2 \theta} \ \ ,  $$
akin to kandb's argument.
(We may also write $ \ d \ = \ e^{ \ i \ · \ [\theta + \pi]} \ \Rightarrow \ d^2 \ = \ e^{ \ i \ · \ 2·[\theta + \pi]} \ = \ e^{ \ i \ · \  [2 \theta + 2 \pi]} \ = \ e^{ \ i \ · \   2\theta  }·e^{ \ i \ · \   2\pi } \ = \ e^{ \ i \ · \   2\theta  } \ · \ 1 \ \ . ) \ ]  $
You are right that one definitely wants to make use of polar form and the concept of complex multiplication as rotation in the Argand plane in some way: a general argument writing $ \ a \ , \ b \ , \ $ and $ \ c \ $ entirely in "Cartesian form" is spectacularly tedious.


Derivation of Double (Brown) Exponential Smoothing

Question: I am learning the double (Brown) exponential smoothing. Comparing to the simple exponential smoothing, the Brown exponential smoothing smooths the output sequence $Y_t$ twice, such that
\begin{align}
S^{(1)}_t &= \alpha Y_t + (1-\alpha)S^{(1)}_{t-1}\\
S^{(2)}_t &= \alpha S^{(1)}_t + (1-\alpha)S^{(2)}_{t-1}
\end{align}
I tried to derive its equivalent smoothing equations via level and trend functions
\begin{align}
L_t & = 2S^{(1)}_t - S^{(2)}_t\\
T_t &= \alpha \left(S^{(1)}_t - S^{(1)}_{t-1}\right) + (1-\alpha)T_{t-1}
\end{align}
where $Y_{t+1} = L_t + T_t + e_{t+1} = S^{(1)}_t + \frac{1}{\alpha} T_t + e_{t+1}$.
But I failed, can anyone help me to derive smoothing equations from the double exponential smoothing? many thanks!
Comment: Those aren't the level and trend functions corresponding to Brown's exponential smoothing; check the Wikipedia page https://en.wikipedia.org/wiki/Exponential_smoothing.
Comment: Thank you, I corrected it.
Answer: OK, I think I proved it. Here is the answer:
Let us define first smoothing function $S^{(1)}_t$ such that
\begin{equation}
S^{(1)}_t :=\alpha Y_t + (1-\alpha)S^{(1)}_{t-1} = \alpha \sum_{i=0}^\infty (1-\alpha)^i Y_{t-i} = \mathbb{E}\{Y_t\},
\end{equation}
where $Y_t$ are observed outputs.
If we exponentially smooth the $S^{(1)}_t$ again, we yield second smoothing function $S^{(2)}_t$, such that
\begin{equation}
S^{(2)}_t :=\alpha S^{(1)}_t + (1-\alpha)S^{(2)}_{t-1} = \alpha \sum_{j=0}^\infty (1-\alpha)^j S^{(1)}_{t-j}= \mathbb{E}\left\{S^{(1)}_t\right\}.
\end{equation}
Now if outputs $Y_t$ can be discribed using following linear function:
\begin{equation}
Y_{t\pm k} = L_t \pm kT_t + e_{t\pm k}
\end{equation}
and
\begin{equation}
\mathbb{E}\{Y_{t\pm k}\} = L_t \pm kT_t,
\end{equation}
where $L_t$ and $T_t$ are called level and trend function at time $t$, respectively.
Then, we could derive the relationship between smoothing functions and level/trend function
\begin{equation}
S^{(1)}_t =  \alpha \sum_{i=0}^\infty (1-\alpha)^iY_{t - i} = \alpha \sum_{i=0}^\infty (1-\alpha)^i (L_t - iT_t) + \underbrace{\alpha \sum_{i=0}^\infty (1-\alpha)^i e_{t-i}}_{\mathbb{E}\{e_t\}=0}
\end{equation}
you should convince yourself that
\begin{equation}
\alpha \sum_{i=0}^\infty (1-\alpha)^i \times i = \frac{1-\alpha}{\alpha} \quad \text{and} \quad \alpha \sum_{i=0}^\infty (1-\alpha)^i = \sum_i w_i = 100\%
\end{equation}
hence
\begin{equation}
S^{(1)}_t =  L_t - \frac{1-\alpha}{\alpha} T_t
\end{equation}
Similarly, we have
\begin{equation}
S^{(1)}_{t-j} =  \alpha \sum_{i=0}^\infty (1-\alpha)^i (L_t - (i+j)T_t) = L_t - jT_t - \frac{1-\alpha}{\alpha} T_t.
\end{equation}
For the second smoothing function $S^{(2)}_t$, we have
\begin{align}
S^{(2)}_t &=  \alpha \sum_{j=0}^\infty (1-\alpha)^jS^{(1)}_{t-j}\\
&= \alpha \sum_{j=0}^\infty (1-\alpha)^j \left(L_t - jT_t - \frac{1-\alpha}{\alpha} T_t\right) = L_t - 2\frac{1-\alpha}{\alpha}T_t.
\end{align}
Finally, it yields
\begin{equation}
\left\{\begin{matrix}L_t = 2S^{(1)}_t - S^{(2)}_t \\ T_t = \frac{\alpha}{1-\alpha}\left(S^{(1)}_t - S^{(2)}_t\right)\end{matrix}\right.
\end{equation}
By substituting
\begin{equation}
S^{(2)}_t = S^{(1)}_t - \frac{1-\alpha}{\alpha}T_t
\end{equation}
into the second smoothing equation about $S^{(2)}_t$, we found that trend function $T_t$ also follows exponential decays
\begin{equation}
T_t = \alpha\left(S^{(1)}_t - S^{(1)}_{t-1}\right) + (1-\alpha) T_{t-1},
\end{equation}
This is exact the second smoothing function that Robert R. Brown was introduced in his original paper "Exponential Smoothing for Predicting Demand". BTW, in his original paper, Robert R. Brown derived this second smoothing function about $T_t$ using the linear least squares.
Therefore, the forcasted outputs can be written as
\begin{equation}
\mathbb{E}\{Y_{t + k}\} = L_t + kT_t = S^{(1)}_t + \frac{1-\alpha}{\alpha} T_t + kT_t = S^{(1)}_t + \frac{1}{\alpha}T_t + (k-1)T_t.
\end{equation}
Answer: I think one of advantages of using exponential smoothing functions
\begin{equation}
S^{(1)}_t :=\alpha Y_t + (1-\alpha)S^{(1)}_{t-1} = \alpha \sum_{i=0}^\infty (1-\alpha)^i Y_{t-i},
\end{equation}
and
\begin{equation}
T_t = \alpha\left(S^{(1)}_t - S^{(1)}_{t-1}\right) + (1-\alpha) T_{t-1},
\end{equation}
is that it makes more easier/convenient to prove the equivalency between Brown's double exponential smoothing and ARIMA(0,2,2) model.
Because
\begin{equation}
Y_t = L_{t-1} + T_{t-1} + e_t  = S^{(1)}_{t-1} + \frac{1}{\alpha}T_{t-1} + e_t,
\end{equation}
we have
\begin{align}
S^{(1)}_t &= \alpha \left(S^{(1)}_{t-1} + \frac{1}{\alpha}T_{t-1} + e_t\right) + S^{(1)}_{t-1} - \alpha S^{(1)}_{t-1}\\
(1-\mathcal{L})S^{(1)}_t & = S^{(1)}_t - S^{(1)}_{t-1} =T_{t-1} + \alpha e_t
\end{align}
and
\begin{align}
T_t &= \alpha \left(T_{t-1} + \alpha e_t\right) + T_{t-1} - \alpha T_{t-1}\\
(1-\mathcal{L})T_t & = \alpha^2 e_t.
\end{align}
Thus, we have
\begin{align}
(1-\mathcal{L})Y_t &= (1-\mathcal{L})\left(S^{(1)}_{t-1} + \frac{1}{\alpha}T_{t-1} + e_t\right)\\
 & = T_{t-2} + 2\alpha\mathcal{L}e_t + (1-\mathcal{L})e_t,
\end{align}
and
\begin{align}
(1-\mathcal{L})^2Y_t &= (Y_t-Y_{t-1})- (Y_{t-1}-Y_{t-2}) \\
&= (1-\mathcal{L})T_{t-2}+2\alpha(1-\mathcal{L})\mathcal{L}e_t + (1-\mathcal{L})^2e_t \\
 & = \left[1-(1-\alpha)\mathcal{L}\right]^2e_t,
\end{align}
which is an ARIMA(0,2,2) model.


compiled python library works on one computer but not on another

Question: I have written a python interface to c++ code.I have two different computers running ubuntu 11.04 with the same packages (python 2.7.1, numpy 1.5.1, gcc 4.5.2). Let's call them A and B.
The code compiles and links without errors on both computers. However, on A, the code seems to enter an infinite loop somewhere in the middle of the c++ code (The CPU is working, but the program never ends). If I copy this very same shared library to computer B, it works without any problems.
I can reproduce this with small changes to the code, different parameters etc. I have used valgrind, but there are no memory leaks / accesses to memory that was not allocated before etc. The code does not depend on anything but libraries installed by the package management system, so these are identical.
Does anyone have any plausible explanation where this might come from?
Other than the following (that I have checked):

A and B run the same libraries/packages of everything
The underlying c++ library has no outside dependencies except for boost::function and STL
Everything is cleanly compiled from scratch using the same build system/compiler
environment variables are the same
Comment: You need to step through the program on both computers at once using `gdb` or something, and see where they begin to differ.
Comment: How different are the computers? And is the program multi-threaded? It could be a timing issue if one computer is slower than the other, and you say you can reproduce the failure on the other computer with a few parameter changes. It sounds to me like the code may not be that robust.
Comment: Problem: The computers are in two different locations and cannot be moved to one.
Comment: @ltn100 no multithreading. The computers are fairly comparable (A: Intel Pentium D dual core at 2.6 Ghz, 3Gb ram, B: Intel E5200, dual core at 2.55 Ghz, 4Gb ram)
Comment: So? sit at one and `ssh` / `vnc` into the other.
Comment: If the code is looping and using a function call you should be able to track it using "strace" on the process.
Comment: Are both computers running the _exact_ same OS version? I ask this because it might just be that the `gcc`/`glibc` for each has had slightly different patches applied to it.
Answer: Which compiler was used to build python on your machine ? This is a crucial point for Python extensions. If you use a different compiler anything bad can happen.
Comment: gcc 4.5.2 was used on both computers for both python and the library.
Answer: Even if you are not multithreading (as in defining multiple threads) there may be a SMP problem: if a memory location is volatile, context switches and CPU scheduling may cause the program to 'not' see the actual changes.

Did you try to compile without any optimizations (-O0 on gcc).
Are there any variables that could be volatile and ought to be marked as such (think of device inputs, zero copy buffers, mmaps).

Even if you're not (explicitely) doing any threading, I'd not be surprised if Python's garbage collection runs on a separate thread anyway.
Comment: as far as I know, Python's GC is synchronous and not run in a separate thread.
Answer: Different computers might have different processors/architecture. Ideally, you would compile Python on the other computer as well. Do this and you'll know if the problem was copying the libraries over, or if it's something on your code, or if it's an environment configuration thing.
Comment: I started with this approach (building the library on each computer). Then, when the library failed to work on computer A, I copied it over to computer B and found that it worked there. (Libraries compiled on B work on B, too). This was just to test whether there is something wrong with the build process.


Unity Ads with Mediation causes Android builds to fail

Question: When I install "Advertisement with Mediation (ver. 1.5.0)" in a project, I can no longer build for Android.
This applies to new, empty projects as well as legacy projects.
The following error message appears:
"…It looks like there are a few files missing from Assets\Plugins\Android. You can fix this by resolving dependencies again…"
When I click Resolve, the build process starts right away and hangs. I have to force quit Unity. If I don't click Resolve, the build hangs up on building the first scene in the project and I have to force quit.
Nothing at all happens via Assets -> Mobile Dependency Resolver -> Android Resolver -> Force Resolver.
I am using Unity 2021.3.13.
Does anyone know what is occurring and how to fix it?
I attempted to resolve as stated in the pop up and it causes Unity to hang. I attempted to resolve beforehand and it appears to do nothing.
I attempted to delete my library folder and it had no effect on reimport.
I attempted to export the project, and the project hangs.
Comment: Same issue. All attempts to use different Editor versions on Windows & macOS failed :(
Answer: I have a similar issue with both Unity Ads with Mediation and the newer Ironsource Ads Mediation(com.unity.services.levelplay). When I run Assets -> Mobile Dependency Resolver -> Android Resolver -> Resolve I get the following error on the console:
Win32Exception: ApplicationName='C:\Users\D\Documents\app\Test\Temp\PlayServicesResolverGradle\gradlew.bat', CommandLine='--daemon -b "C:\Users\D\Documents\app\Test\Temp\PlayServicesResolverGradle\PlayServicesResolver.scripts.download_artifacts.gradle" "-PANDROID_HOME=C:/Program Files/Unity/Hub/Editor/2021.3.14f1/Editor/Data/PlaybackEngines/AndroidPlayer\SDK" "-PTARGET_DIR=C:\Users\D\Documents\app\Test\Assets\Plugins\Android" "-PMAVEN_REPOS=https://android-sdk.is.com/;https://maven.google.com/" "-PPACKAGES_TO_COPY=com.ironsource.sdk:mediationsdk:7.2.5;com.google.android.gms:play-services-ads-identifier:17.0.0;com.google.android.gms:play-services-basement:17.2.1" "-PUSE_JETIFIER=0" "-PDATA_BINDING_VERSION=4.0.1"', CurrentDirectory='C:\Users\D\Documents\app\Test\Temp\PlayServicesResolverGradle', Native error= The system cannot find the file specified.
The file gradlew.bat doesn't exist. I found a gradlew.bat here: https://github.com/googlesamples/unity-jar-resolver. I copied the file into: C:\Users\D\Documents\app\Test\Temp\PlayServicesResolverGradle and then I could run the the resolver from Unity.
But it leads to this questions: Why does Unity MobileDependencyResolver not create gradlew.bat? It does create gradlew, the gradle start up script for Unix. Why the Unix script and not the Windows script?
Answer: For anyone having this problem, seems like the "gradlew.bat" file is not been created in the Temp folder, so I've downloaded it from here:
https://github.com/googlesamples/unity-jar-resolver/blob/master/gradlew.bat

and placed on the Temp\PlayServicesResolverGradle folder, but I still don't know why this is happening and how to permanently fix it, but at least you will be able to install and configure the ads Mediation, I did it here and worked.
Answer: Advertisement with Mediation is not being properly supported by Unity anymore post IronSource merger. They suggest using Ironsource's mediation platform. We use AdMob given I already know how to deal with its obvious bugs.
Answer: What David Laing mentioned helped me. I didn't realize the gradlew.bat needed to be dragged into the appropriate folder as I thought the Edit -> Preferences -> Gradle Installed with Unity address needed to be corrected.
That being said. This is where you can find the official gradle distributions:
https://services.gradle.org/distributions/

Find the gradle-8.3-rc-4-src.zip or the most recent edition. The important part is the "SRC.zip" as that contains the actual gradlew.bat file The others are documents and an SHA file.
Extract the file to your desired location.
Open the folder that was extracted.
Copy gradlew.bat NOTE:: MAKE SURE IT'S THE "WINDOWS BATCH FILE" FILE TYPE NOT THE "FILE" type as there are 2 files with the exact name in the folder.
Paste the gradlew.bat file to the first folder path it mentions where the gradlew.bat file is missing.
Launch or cause Unity to compile again, and the android resolver should now work.


why is wrong with 'if [ $# > 0 ] ; then'?

Question: why does it still produce output in the third command?
$cat sh.sh
#!/bin/sh
echo $#
if [ $# > 0 ] ; then
    base=`basename $1 .c`
    echo $base
fi
$ sh sh.sh a.c
1
a
$ sh sh.sh
0
.c

I use this file:/usr/share/doc/opencv-doc/examples/c/build_all.sh to build the c examples for opencv packages,but failed with similar errors.
Comment: If your shebang says `#!/bin/sh` you're not really using Bash. If you want to use `>` and double parentheses as codaddict mentions, then you need `#!/bin/bash`. Then you can do `if (( $# > ))`.
Answer: You need to use -gt in place of >.
You can use > if you are using double parenthesis construct.
Comment: Thanks,so this is a bug in opencv-doc package.At least the first line should be changed to `#!/bin/bash` or **>** to **-gt**.
Answer: You should use -gt(Greater than) in your condition, not >. Look at man test for more information.
if [ $# -gt 0 ] ; then
    base=`basename $1 .c`
    echo $base
fi

Answer: Remember that [ is a command. /usr/bin/[ , to be exact. It is linked to the command /usr/bin/test
So, [ $# > 0 is identical to test $# > 0, i.e., redirect test $#'s output to the 0 file.
If you're using bash ... now that's a different story altogether :-)
Comment: `[` is a builtin in several shells in addition to Bash, but you're correct that it is a *command*. `/usr/bin/[` (and `/usr/bin/test`) exists mostly for backwards compatibility for shells that don't include it. It can also be used when you're not really using a shell, for example in the `-exec` clause of a `find` command.


Prove the integral inequality

Question: $$\frac{\pi}{4}-\frac{1}{2}\le \int_0^1{\frac{\arcsin x}{1+x^8}}\le \frac{\pi}{2}-1$$
I can say that I have close to zero experience with integral inequalities. I've searched for couple of theorems most of them involving monotonous function on $[0,1]$. Arcsin is increasing in this case and the other one is decreasing. You could say we have a product of increasing and decreasing function on this interval however I didn't find any theorems that cover this case. Also this integral doesn't seem to have elementary function.
Another thing I noticed is that most of the theorems cover only 1 part of this inequality; either $\le or \ge$ so my guess is we need some type of combination or perhaps find a new integral that is equal to $\frac{\pi}{4}-\frac{1}{2}$ and another that is equal to $\frac{\pi}{2}-1$.
What's the correct approach when we need to prove that the value of certain integral is in a provided interval?
Answer: For the bound on the right,
$$
\int_0^1{\frac{\arcsin x}{1+x^8}}\,dx\leq \int_0^1\arcsin x\,dx=\frac\pi2-1.
$$
For the bound on the left,
$$
\int_0^1{\frac{\arcsin x}{1+x^8}}\,dx\geq\frac12\,\int_{0}^1{{\arcsin x}}\,dx=\frac12\,\left(\frac\pi2-1\right)=\frac\pi4-\frac12.
$$
Comment: There is a problem with my second estimate. I have edited, to an easier argument.
Comment: I thought of the same thing moment before you posted for that first part. Thanks!

Prove the integral inequality


Postfix - do not list domain example.com in BOTH mydestination and virtual_alias

Question: I have a server with two domains. I get the warning as mentioned in the title:
do not list domain example.com in BOTH mydestination and virtual_alias
Although I receive the above warning, it works just fine without problems. But I want to know how to fix it.
The reason for having the domain in both places is because I want to implement catchall - all email sent to @domain.tld should go to the mail account of that domain.
Now, if I don't put the domain in mydestination, the server refuses to accept email for that domain because it does not want to be an open relay. If I don't put the catchall alias into the virtual alias table, the catchall doesn't work (obviously).
So what is the correct solution? I have tried to read the stuff on http://www.postfix.org/VIRTUAL_README.html#virtual_alias, but I just can't seem to make my setup work any other way.
(PS: I am using webmin/virtualmin to manage my website, and when I try to configure it with the built-in configuration tools it comes up with the same solution I have manually. So it seems even webmin doesn't know a better way to do this...)
Answer: The default for mydestination is:
$myhostname, localhost.$mydomain, localhost

Try setting it to
localhost.$mydomain, localhost

instead. I had a similar warning, and making this change doesn't impact mail delivery on my server for the domain in question. If you're still having problems, you should probably post your main.cf and virtual_alias settings.
Comment: OH that's right! I had $myhostname set to my domain, so it appeared twice! No wonder I couldn't grep for it!
Answer: You don't need the domain listed in in virtual_alias_domains for it to be looked up in the virtual_alias_map.
From the virtual(5) man page:

The  optional  virtual(5)  alias  table rewrites recipient addresses for all local, all virtual, and all remote  mail destinations. [emphasis added]

virtual_alias_domains is a list of domains that addresses MUST be looked up and found in the virtual alias map.
Answer: My solution was the following:

Remove example.com from mydestination
Replace the virtual alias firstname.lastname@example.com to mainuser with an alias to localmailbox@localhostname (localhostname being anything in mydestination)

What I learned was that Virtualmin creates so called "virtual alias domains" by specifying the domain name in the virtual alias tables. Postfix documentation states that in this case local mailboxes can't be a (direct) target.
Comment: After HOURS of bumping my head to the wall, the solution is this! When I changed the "username' to "username@localhost" everything worked!
Answer: I changed this on a busy Virtualmin Ubuntu 20.04 mail server, I did:
Before:

mydestination = $myhostname, localhost.our-main-domain.com, , localhost

After:

mydestination = localhost.our-main-domain.com, , localhost

This caused a catastrophic failure as ever message started to bounce. For now I'm going to have to live with the warning, although it's truly annoying when doing complex troubleshooting.
This whole issue is really confusing because actually on my system I don't even find anything virtual_alias_domains but rather something called virtual a file  on the disk which appears to have this 'alias'.
Comment: virtual_alias_maps is generally set to and defined it /etc/postfix/virtual file


std::bind a std::shared_ptr parameter won't increase use_count

Question: The following code:
#include <stdio.h>
#include <memory>
#include <functional>

struct Foo{
    Foo():
        m_p(std::make_shared<int>())
    {}
    Foo(const Foo &foo)
    {
        printf("copy\n");
    }
    std::shared_ptr<int> m_p;
};

void func(Foo foo)
{}

int main()
{
    Foo foo;
    std::function<void (void)> f = std::bind(func, foo);
    printf("use count : %ld\n", foo.m_p.use_count());
    f();
}

got result:
copy
copy
use count : 1
copy

Since Foo is copied, I thought m_p's use_count should be 2.
I am using clang++
Apple LLVM version 5.0 (clang-500.2.79)
I compile the code in debug mode.
Answer: There are two issues with your code.
First, your copy constructor isn't copying m_p:
Foo(const Foo &foo):
    m_p{foo.m_p}
{
    printf("copy\n");
}

Second, your bind results in a temporary which is immediately discarded; you should capture it (e.g. into an auto):
auto bar = std::bind(func, foo);

Comment: @user1429171 First: it *would*, if you hadn't provided your own copy constructor that prevents the default one from being generated; second: the copy constructor is invoked, but the destructor is invoked as well, decrementing the use count (it isn't a high water mark).
Comment: I know these issues. First, copy constructor will call the member's copy constructor by default. Second, temporary variable will cause the copy constructor invoke twice.
Answer: the results of std::bind are not stored in a variable and are immediately discarded.


Prove that each tree has at most one perfect matching

Question: I need help with the following proof:

Prove that each tree has at most one perfect matching.

We know that: perfect matching = covers each vertex just once.
So the proof itself I tried to prove by controversy:

the so-called I assume that some tree has two perfect matchings.
Let there be perfect matchings on the tree $T = (V,E)$ (let's call these matchings $M$, $M'$)
Next, consider a graph on vertices from the set $V$ (so-called all vertices of the tree $T$), which are also vertices $M\cup M'$
If, but $M$ and $M'$ are perfect matchings (so-called cover all vertices), then each element of this new graph is either a vertex that belongs to $M$, $M'$ or a cycle.
But $T = (V, E)$ is a tree and cannot contain a cycle (Dispute) $\Rightarrow\ M = M'$.

And here I assumed that the claim was proved, but during the follow-up check I was criticized for the following:

the vertices located in $M\cup M'$ are all vertices of the tree (It probably made sense to consider all edges of $M\cup M'$)… in this case, however, the components will be only paths (The cycle by definition cannot be, because $T = (V, E)$ is a tree)… so if we have paths, what next? (Dispute is not visible!)

Couldn't anyone please advise me how to reformulate this proof correctly, or if it can be done differently and better? Thank you for any advice.
Comment: I would solve it by mathematical induction on the number of edges. Not by contradiction.
Comment: It perhaps simpler to consider the subgraph $(V,M\Delta M')$ where $M\Delta M' = (M\setminus M')\cup(M'\setminus M)$. Possible degrees in this subgraph are 0,1,2.  But if both $M'$ and $M'$ are perfect, only 0 or 2 are possible. But inside a tree, 2 is impossible.
Answer: Your reasoning is difficult to understand, but the idea is correct. It seems to me that the reasoning could be as follows. I'll tell you very briefly:
In fact, let for some tree $T$ there exist two perfect matchings $M$ and $M'$ and let an edge $e\in M$, but $e\notin M'$. Let $e=x_1x_2$. Since $M'$ is a perfect matching, then there exists an edge $e'\in M'$ and $e'=x_2x_3$.
We have $x_1x_2x_3$ is a path in which the edges from $M$ and $M'$ alternate: $x_1x_2\in M$, $x_2x_3\in M'$.
Now we choose a path of maximal length in the tree $T$, in which the edges of $M$ and $M'$ alternate. Let it be $x_1x_2,\ldots,x_s$ and $x_1x_2\in M$. Since $M'$ is a perfect matching there exists an edge $x_1x_0\in M'$ and $x_0\neq x_i$, since $T$ has no cycles. This, however, contradicts the maximality of the chosen path.