Mocking User.Identity in ASP.NET MVC

Question: I need to create Unit Tests for an ASP.NET MVC 2.0 web site.   The site uses Windows Authentication.
I've been reading up on the necessity to mock the HTTP context for code that deals with the HttpContext.  I feel like I'm starting to get a handle on the DI pattern as well.  (Give the class an attribute of type IRepository and then pass in a Repository object when you instantiate the controller.)
What I don't understand, however, is the proper way to Mock the Windows Principal object available through User.Identity. Is this part of the HttpContext?
Does any body have a link to an article that demonstrates this (or a recommendation for a book)?
Thanks,
Trey Carroll
Answer: I've used IoC to abstract this away with some success.  I first defined a class to represent the currently logged in user:
public class CurrentUser
{
    public CurrentUser(IIdentity identity)
    {
        IsAuthenticated = identity.IsAuthenticated;
        DisplayName = identity.Name;

        var formsIdentity = identity as FormsIdentity;

        if (formsIdentity != null)
        {
            UserID = int.Parse(formsIdentity.Ticket.UserData);
        }
    }

    public string DisplayName { get; private set; }
    public bool IsAuthenticated { get; private set; }
    public int UserID { get; private set; }
}

It takes an IIdentity in the constructor to set its values.  For unit tests, you could add another constructor to allow you bypass the IIdentity dependency.
And then I use Ninject (pick your favorite IoC container, doesn't matter), and created a binding for IIdentity as such:
Bind<IIdentity>().ToMethod(c => HttpContext.Current.User.Identity);

Then, inside of my controller I declare the dependency in the constructor:
CurrentUser _currentUser;

public HomeController(CurrentUser currentUser)
{
    _currentUser = currentUser;
}

The IoC container sees that HomeController takes a CurrentUser object, and the CurrentUser constructor takes an IIdentity.  It will resolve the dependencies automatically, and voila!  Your controller can know who the currently logged on user is.  It seems to work pretty well for me with FormsAuthentication.  You might be able to adapt this example to Windows Authentication.
Comment: To me, this method is preferable to mocking controllers and principles and http contexts, etc, as each time I forget exactly which parts I need to mock and have to hunt through other tests to find suitable code to copy and paste.  In my case, the controllers take an ICurrentUserResolver interface, which has a ResolveCurrentUser() method, and the controller never needs to worry about how the current user is determined.
Comment: Thank you @JohnNelson , you saved my life
Answer: I don't know for MVC 2.0, but in newer versions you can mock the ControllerContext:
// create mock principal
var mocks = new MockRepository(MockBehavior.Default);
Mock<IPrincipal> mockPrincipal = mocks.Create<IPrincipal>();
mockPrincipal.SetupGet(p => p.Identity.Name).Returns(userName);
mockPrincipal.Setup(p => p.IsInRole("User")).Returns(true);

// create mock controller context
var mockContext = new Mock<ControllerContext>();
mockContext.SetupGet(p => p.HttpContext.User).Returns(mockPrincipal.Object);
mockContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);

// create controller
var controller = new MvcController() { ControllerContext = mock.Object };

see also How to unit-test an MVC controller action which depends on authentification in c#?
Answer: Scott Hanselman shows in his blog how to use IPrincipal and ModelBinder to make easier to test the controller by mocking IPrincipal.
Answer: Example for mocking username and SID on MVC4.
The username and SID (Windows Authentication) in the following action should be tested:
[Authorize]
public class UserController : Controller
{
    public ActionResult Index()
    {
        // get Username
        ViewBag.Username = User.Identity.Name;

        // get SID
        var lIdentity = HttpContext.User.Identity as WindowsIdentity;
        ViewBag.Sid = lIdentity.User.ToString();

        return View();
    }
}

I use Moq and Visual Studio Test Tools. The test is implemented as follows:
[TestMethod]
public void IndexTest()
{
    // Arrange
    var myController = new UserController();
    var contextMock = new Mock<ControllerContext>();
    var httpContextMock = new Mock<HttpContextBase>();
    var lWindowsIdentity = new WindowsIdentity("Administrator");

    httpContextMock.Setup(x => x.User).Returns(new WindowsPrincipal(lWindowsIdentity));

    contextMock.Setup(ctx => ctx.HttpContext).Returns(httpContextMock.Object);
    myController.ControllerContext = contextMock.Object;

    // Act
    var lResult = myController.Index() as ViewResult;

    // Assert
    Assert.IsTrue(lResult.ViewBag.Username == "Administrator");
    Assert.IsTrue(lResult.ViewBag.Sid == "Any SID Pattern");
}

Answer: To mock WindowsIdentity you can do the following:
var mockedPrincipal = new Mock<WindowsPrincipal>(WindowsIdentity.GetCurrent());

mockedPrincipal.SetupGet(x => x.Identity.IsAuthenticated).Returns(true);
mockedPrincipal.SetupGet(x => x.Identity.Name).Returns("Domain\\User1");
mockedPrincipal.Setup(x => x.IsInRole("Domain\\Group1")).Returns(true);
mockedPrincipal.Setup(x => x.IsInRole("Domain\\Group2")).Returns(false);

then use mockedPrincipal.Object to get the actual WindowsIdentity
Answer: I've changed dev environment global.asax and Web.Config for use FormsAuth for force a specific user. The username uses the same WindowsAuth format. See:
public override void Init()
    {
        base.Init();

        this.PostAuthenticateRequest +=
             new EventHandler(MvcApplication_PostAuthenticateRequest);
    }

    void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
    {
        FormsAuthentication.SetAuthCookie("Domain\\login", true);
    }

The Windows or Forms Auth shares the same login patterns.
The application will work with both Windows authentication and Form authentication.

Mocking User.Identity in ASP.NET MVC


Android Studio com problema na MainActivity

Question: Eu comecei a utilizar o Android Studio hoje, e ao criar o Projeto do Aplicativo me deparei com um problema: Eu consigo criar, porém a classe MainActivity fica cheia de erros sendo que eu não mudei nada do aplicativo.

É isso, por acaso vocês já se depararam com esse problema ?
Antes do Android Studio eu usava o Eclipse.
Obrigado!
Comment: Você usa o Gradle? se sim veja se algo muda ao clicar sobre o botão `Sync Project with Gradle Files` ([imagem](http://tools.android.com/_/rsrc/1412965828964/tech-docs/project-sync-issues-android-studio/sync.png)).
Comment: Não, não mudou.
Comment: Pela imagem deve ter algo de errado com a estrutura do diretório, algo incorreto. Tente limpar o cache indo em *File* - *Invalidate Cache*.
Comment: É não deu certo.
Comment: Amigo, tente ir em "build", depois clica em clean , clique em rebuild e depois make project . Após isso, deixa ele realizar as sincronizações, e reinicie o android studio .
Comment: Reinicie, mesmo assim não funcionou..
Comment: Ali em extends, tente estender a Activity .
Comment: Não deu certo .
Comment: Está falando que o problema pode ter sido pela incorreta configuração do daemon. @QMechanic73
Comment: Cara acho que eu não configurei um tal de Gradle, tem que configurar nas Variaveis de Ambientes ? @QMechanic73
Comment: tente mudar para extends Activity
Comment: Tenta ler o terminal, as vezes tive problema no R por erros de nomeclatura, por exemplo esse erro aconteceu comigo e sumiu logo após eu corrigir um erro de um xml que eu tinha colocado um traço ao invés de *underline* , outra vez foi corrigido logo após eu corrigir a palavra string que estava escrita "sting"
Answer: Para resolver isto, faça:

Clean project localizado em Build
Rebuild project localizado em Build, após o término do Clean Project.

Lembre-se que a classe R é criada automaticamente após o Build do seu projeto, ou seja, se algum Build seu terminou com erro, essa classe não existirá mais e você terá que dar um Build nele novamente.
Comment: Tirou nos outros erros mais a classe R ainda está com error
Comment: Gradle build finished with 101 error(s) in 15 sec
Comment: Certo, os erros são todos na classe R? Preciso que você me mostre seu `AndroidManifest.xml` e o `Build.gradle (app)`.
Comment: Também peço que dê uma olhada na `package` que você está usando em `.java/`.


OOP: Coupling the setting of a state with the showing of it?

Question: Say I have an class which has three states: full screen, windowed, and minimized. The state of my object is stored as an enumerated type,
typedef enum {
    StateFullScreen,
    StateWindowed,
    StateMinimized
} State;

If every time I change the State, I am calling two methods: setState: and showState:, should I couple these actions into one? For example, override the normal synthesized setState: method and have it depending on the state call the proper showState: method? Or should I do it the other way around having showState: call setState:?
Are either of these good programming practice when it comes to object-oriented design?
Answer: Have you considered creating a ChangeState(...) method?
It would be simple enough to create a first pass refactoring that calls the other two methods.  I'd then work through further refactorings to clean it up fully.
Comment: I voted you up, but I don't think I will go this route as seeing how I don't want either of the methods to be called without the other.
Comment: Then make them private, and call from ChangeState().
Answer: In my opinion it would be better to do all the work in setState, this is what someone using your class would expect.
I have a session class, which has statusses connecting, disconnecting, online and offline. If I call setStatus it will also call a delegate method and disconnect the session if the new status is equalto disconnecting or offline.


What is the moment of inertia of a thin equilateral triangular plate about an axis through its center?

Question: What is the moment of inertia of a thin equilateral triangular plate of mass $m$ and side $a$ about an axis through its center (perpendicular to the plane)?
I expressed $r$ as $r = \sqrt{x^2 + y^2}$, and $dm = \rho dS$  so I get:
$$I = \int r^2\, dm = \rho \int (x^2 + y^2)\, dS = \rho \int \int (x^2 + y^2)\, dx dy.$$
Now for the intervals, I expressed the height the triangle as $v = \frac{a \sqrt{3}}{2}$ and because I know the center of the triange is $\frac{2}{3}$ from the top point and $\frac{1}{3}$ from the base, my interval will be $y \in (-\frac{a \sqrt{3}}{6}; \frac{a \sqrt{3}}{3})$. For the $x$ interval it is just $x \in (-\frac{a}{2}; \frac{a}{2})$. When I evaluate the integral, I get: $$ I = \frac{1}{3}ma^2.$$
My questions are: First, is this even correct? Second, isn't there a simpler way to find the moment of inertia (using integrals)?
Thanks.
Answer: Another way is to do the integration in polar coordinates. We can focus on one sixth of the triangle, with $\phi=0$ corresponding to a midpoint and $\phi=\frac\pi3$ corresponding to a vertex and the side between them described by $r=\frac h{3\cos\phi}$:
\begin{eqnarray}
\int_0^\frac\pi3\mathrm d\phi\int_0^\frac h{3\cos\phi}r\mathrm drr^2
&=&
\frac{h^4}{4\cdot3^4}\int_0^\frac\pi3\frac{\mathrm d\phi}{\cos^4\phi}
\\
&=&
\frac{h^4}{4\cdot3^4}\left[\frac{(2+\cos2\phi)\sin\phi}{3\cos^3\phi}\right]_0^\frac\pi3
\\
&=&
\frac{\sqrt3h^4}{2\cdot3^4}\;.
\end{eqnarray}
With $h=\frac{\sqrt3}2a$ and the area $A=\frac{\sqrt3}4a^2$, and taking into account the factor $6$, this yields the moment of inertia
$$6\cdot\frac{\sqrt3}{2\cdot3^4}\left(\frac{\sqrt3}2a\right)^4\left(\frac{\sqrt3}4a^2\right)^{-1}m=\frac1{12}ma^2\;,
$$
in agreement with the accepted answer to this physics.SE question, which, by the way, shows a nice way to use symmetry to get the moment of inertia without evaluating any integrals.
From your description of your own calculation, it sounds as if you didn't take into account that the limits for the inner integral over $x$ depend on $y$.
Comment: @LaurenSin: The integral is the integral of $r^2$ over the area of $\frac16$ of the triangle (where $r$ is the distance from the centre); so multiplying it by $6\rho=6\frac mA$ yields the moment of inertia of the triangle.
Comment: @LaurenSin: No, the moment of inertia of a semicircle with respect to the centre of the circle is half the moment of inertia of the circle. The moment of inertia of a semicircle is smaller only because it's calculated with respect to the centre of mass of the semicircle, which is not the centre of the circle. Here I'm calculating the moment of inertia of a part of the triangle with respect to the centre of the triangle, not with respect to the centre of mass of the part.
Comment: Thank you. But if I count the moment of inertia of one sixth of the triangle it results in $\frac{1}{12}ma^2$ and if I multiply it by six, it would be a different number. Why did you take the whole area instead of just $\frac{1}{6}$ in your calculations?
Comment: @LaurenSin: I'm not sure I understand your question. I calculated the integral over one sixth of the area and then multiplied it by $6$ to get the total moment of inertia.
Comment: I understand you counted the integral over one sixth of area  but then you multiply it by the whole area ($A$) (or inverse area and mass). I did it separatly, like I first counted the integral and multiplied it by $\frac{1}{6}$ of the area and mass to get moment of inertia of that $\frac{1}{6}$ of the triangle. And after that I multiplied it by six. But my result is wrong and I cannot see why. And I don't understand you last equation (why there is whole area instead of just $\frac{1}{6}$ when you do the integral for $\frac{1}{6}$.
Comment: @LaurenSin: I'm still not sure what you mean. I get the impression that you may have misunderstood my previous comment, since you summarize part of it without mentioning the part "and then multiplied it by $6$". The only way I seem to be able to make sense of your comments is if you overlooked the factor $6$ in the last displayed equation.
Comment: Maybe I don't fully understand what the integral represents. Is it the distance from the axis of rotation? If so, then I guess I understand your calculations. If not, what does the integral represent? (obviously, I understand it represents just one sixth of the triangle but i mean more like is it the distance or the area or something else?
Comment: I get it now, thank you for your patience. I have a last question though. Maybe it is more for physicists but anyways. If i count moment of inertia of just the $\frac{1}{6}$ and after that mutltiply it by six, why does't it lead to the same result? For example moment of in. of a full circle is two times bigger than $I$ of half a circle. Moment of inertia of $\frac{1}{4}$ circle is four, times small than moment of inertia of a full circle. So why doesn't it work in this case when the triangle is made of 6 same parts. Why isnt the $I$ of the whole triangle six times bigger that $I$ of on sixth?


Catchable fatal error: Object of class stdClass could not be converted to string in

Question: Fiz uma requisição e no resultado trouxe $result. Mas eu queria acessar dentro da string como objeto e aparece esse erro. Vi uns erros parecidos em outras perguntas, mas pra mim não ficou claro.
echo $result;
echo "
";
echo var_dump($result);
echo "
";
echo json_decode($result);

{"response":{"dsLOGIN":{"dsLOGIN":{}}}}
string(39) "{"response":{"dsLOGIN":{"dsLOGIN":{}}}}"

Erro:

Catchable fatal error: Object of class stdClass could not be converted to string in
Comment: O que aparece se tu fizer um `print_r($result);`?
Comment: `{"response":{"dsLOGIN":{"dsLOGIN":{}}}}` -  A mesma linha do echo $result @ThiagoSantos
Comment: Em qual linha está dando o erro? Nessa: `echo json_decode($result);`?
Comment: Sim, nela mesmo. `echo json_decode($result); ` @ThiagoSantos
Comment: `json_decode($result);` retorna um Objeto PHP, e com um ECHO você tenta escrever esse Objeto como String, o que está causando esse erro.
Answer: OBJECT OF CLASS STDCLASS
Ao utilizar json_decode() você tem como resultado um Objeto, ou um Array de Objetos (Fonte) e, ao utilizar ECHO em um Objeto, causa a tentativa de conversão dele para String, ocasionando o Erro:

Catchable fatal error: Object of class stdClass could not be converted
  to string in

Para escrever um Objeto diretamente é preciso utilizar print_r() assim exibindo até mesmo suas propriedades (Fonte).
No seu caso deve funcionar apropriadamente o seguinte:
echo $result;
echo "
";
echo var_dump($result);
echo "
";
$jsonResult = json_decode($result);
print_r($jsonResult); // $jsonResult já é um Objeto
print_r($jsonResult->response) // $jsonResult->esponse também contém um Objeto

Comment: Agora, entendi. Eu estava só usando o `echo` e estava me confundindo. Obrigado!


apache user can't stat a path from CGI, but can from shell

Question: Here is a script to demonstrate:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char **argv)
{
  printf("Content-Type: text/plain\r\n\r\n");

  printf("UID, EUID = %d, %d\n", getuid(), geteuid());
  printf("GID, EGID = %d, %d\n", getgid(), getegid());

  struct stat stbuf;
  if (stat("/dev/shm", &stbuf))
    printf("stat() failed: %s\n", strerror(errno));
  else
    printf("stat() succeeded\n");

  return 0;
}

When I run this script under a sudo su -s /bin/bash apache shell, it produces:
Content-Type: text/plain

UID, EUID = 48, 48
GID, EGID = 48, 48
stat() succeeded

But when run as a CGI script by Apache/2.2, the page responds:
UID, EUID = 48, 48
GID, EGID = 48, 48
stat() failed: Permission denied

How is this possible? The location in question (/dev/shm) on this machine these permissions:
drwxrwxrwt.  2 root   root       260 Mar 29 06:52 .
drwxr-xr-x. 20 root   root      4300 Mar 28 10:31 ..

Comment: Is SELinux in enforcing mode? Find out using `sestatus`. If it is, you can find out if it is the cause of your problems by temporarily disabling it with `setenforce 0` and trying to run your script again. I'll post a complete solution if SELinux is the cause.
Comment: It is enabled. After issuing `setenforce 0`, the `stat()` call succeeds.
Comment: Is your script located in the `/var/www/cgi-bin/` directory? If it isn't, try moving it there. Then try running `restorecon -R /var/www/cgi-bin/` and `setenforce 1` to see if that properly fixes it.
Answer: This is due to selinux.
Your script is not permitted to do a stat on tmpfs_t as the httpd_sys_script_t type. This is by design. Depending on what you are trying to stat() (not just /dev/shm) can depend on what action you might want to take.
If you chcon the program to run in the label httpd_unconfined_script_exec_t this will avoid SELinux restrictions, at the cost of no SELinux protections whatsoever for the script being ran.
Comment: Right. Don't disable SELinux in this scenario. It's doing what it's supposed to do.


What is the issue with this sbt file?

Question: When I import a SBT project into intelliJ, the build.sbt file is showing lot of errors as shown in the following screenshot. Wondering what might be the issue
IDEA Version 13.1.4
I also see the following
The following source roots are outside of the corresponding base directories:
C:\Users\p0c\Downloads\recfun\src\main\resources
C:\Users\p0c\Downloads\recfun\src\test\java
C:\Users\p0c\Downloads\recfun\src\test\scala
C:\Users\p0c\Downloads\recfun\src\test\resources
These source roots cannot be included in the IDEA project model. Please consider using shared SBT projects instead of shared source roots.

Comment: Ok, I can't tell without having a real look at the project but I can tell you that I do not import. I "open" the root folder of the project. Is yours a multiproject sbt config?
Comment: Version is ok. How are you doing the import? I simply go to File > Open and select a directory with a build.sbt (or a project directory with a scala build definition).
Comment: Also, does the build work from the command line?
Comment: @fedesilva The build is working fine from command line. I actually imported the project by selecting the SBT file and not by selecting the project folder.
Comment: I am having the same issue, hopefully watching to see if an explanation/solution is found.
Answer: I think the question perhaps does not provide all the required information to answer conclusively, but I'll give it a spin anyways -
Since sbt runs correctly when invoked from the shell, we know the sbt file is fine. I use Idea for my Scala and sbt projects and I am sure the Idea sbt support works very well, but! Idea is far more restrictive than sbt when it comes to project structure. It is really easy to create a valid sbt project structure that Idea can't support very well.
Given that the source roots error indicates that the recfun/src folder is not in the project folder, it seems clear that this error is not emitted during the processing of recfun/build.sbt. The screenshot shows you have at least three different sbt files, progfun-recfun, submission and scala-recfun. Since Idea will also create projects like submission-build, and you have an assignment-build project there, something is probably broken in the project structure, not from the sbt viewpoint - there you're fine, you can build - but from the Idea viewpoint, which is more restrictive.
My suggestion to resolve this would be to change your project structure as follows. First, have a top level project with a build.sbt. Then create a sub-project for each src folder you want. Do not put a src folder in your top level project. Each sub-project needs a build.sbt as well.
Second, make sure the sub-projects build correctly with sbt when run from the shell. Arrange the sub-project build.sbt files with the proper dependencies, using this syntax:
lazy val a = ProjectRef(file("../a"), "a")
lazy val b = ProjectRef(file("../b"), "b")
lazy val root = Project(id = "c", base = file(".")) dependsOn (a, b)

(This example has three sister projects a, b and c, where c depends on a and b. The three projects are placed in directories with the same name, within the root directory. The code snippet is from the build file for c.)
Third, arrange your top level build.sbt to aggregate the sub-projects, using this syntax in the top level build.sbt:
lazy val a = ProjectRef(file("a"), "a")
lazy val b = ProjectRef(file("b"), "b")
lazy val c = ProjectRef(file("c"), "c")

lazy val root = (project in file(".")).
  aggregate(a, b, c)

Building this top level project will build each of the sub-projects a, b and c, and the dependencies established in the sub-project build files will ensure they are built in the right order.
Fourth, import the top level project into Idea, and all should be well.
You can get fancy with the file structure if you want, because the project references use relative paths, but it's usually nice to at least start simple.
I had a lot of frustration with sbt and Idea at the start, I hope this helps :)
Comment: By the way, I've seen Idea color sbt files all red like shown in your screenshot, without there being any issue with the sbt file. It sometimes indicates that there was an unrecoverable error during the import.

What is the issue with this sbt file?


Pegar data formatada em HTML5

Question: tenho o seguinte cenário.
Uma form com dois campos de data

E quando clico em pesquisar, os dados estão nesse formato

Como posso fazer para que eu pegue a data no formato "aaaa-mm-dd" ou "dd-mm-aaaa"? Sem esse dados adicionais (Thu Oct, 00:00:00 GMT-0300), alguém sabe?
Segue meu HTML
form name="relatorioPorPeriodo" class="formRelatorio">
    <input class="form-control dataini" type="date" name="data_ini" ng-model="relatorio.dataini" required>
    <input class="form-control datafim" type="date" name="data_fim" ng-model="relatorio.datafim" required>
    Pesquisar
</form>

Controller
app.controller("RelatorioPorPeriodoCtrl", ['$scope', '$http', '$window', '$rootScope', '$routeParams', 'moment', function ($scope, $http, $window, $rootScope, $routeParams, moment) {

$scope.idempresa = $rootScope.idempresa = localStorage.getItem('idempresa');
$scope.empresa = $rootScope.empresa = localStorage.getItem('empresa');
$scope.usuario = $rootScope.usuario = localStorage.getItem('usuario');
$scope.idusuario = $rootScope.idusuario = localStorage.getItem('idusuario');

$scope.pesquisaPorPeriodo = function(relatorio){
    console.log(relatorio);
}
}]);

Comment: Aconselho a utilizar a library Moment,js (https://momentjs.com/) para lidar com formatos de datas, contagens de intervalos de tempo, etc. Utilize a função ´moment().format(")´.
Comment: Sim, conheço, mas não sei como usar, pois no exemplo dado tenho que colocar a data na mão.
Comment: Como instalo ele pra usar com angular? Não dá pra instalar com npm? Ou baixar?
Comment: Package npm para Angular: https://www.npmjs.com/package/angular-moment
Answer: Utilizando a library moment.js (https://momentjs.com/);
var dataInicio = "Thu Oct 01 2015, 00:00:00 GMT-0300";
var dataInicioFormatada = moment(dataInicio).format('DD-MM-YYYY');

console.log(dataInicioFormatada);

Package npm para Angular: https://www.npmjs.com/package/angular-moment
Comment: Já importei o moment.js na index.html
Agora como coloco ele na controller?
Comment: Sim, coloquei isso:
ngular.module('fooApp')
    .controller('FooCtrl', ['$scope', 'moment', function ($scope, moment)

Mas dá pau.
Comment: Postei o meu controller na descrição.
Comment: Instalei o via CDNJS e tb não adiantou.
Podes me mostrar como fica meu controller?

Pegar data formatada em HTML5


Lighttpd: specify two http hosts with same document root?

Question: What is the best or proper way to specify two http hosts with the same document root on Lighttpd? For example, to serve a domain at example.org and www.example.org.
Given the following in the lighttpd.conf for one host:
$HTTP["host"] == "www.example.org" {
  server.document-root = "/path/to/root/example"
}

Is this a valid configuration for two hosts?
$HTTP["host"] == ( "example2.org", "www.example2.org" ) {
  server.document-root = "/path/to/root/example2"
}

Or do you have have to duplicate/repeat the $HTTP["host"] field for each?
Comment: I had a complete brain fart and wrote up a whole answer for nginx :-D  I'm not sure how to set this up in lighttpd but the correct thing to do is to pick one name to be the "canonical" hostname and redirect the "wrong" hostname to the right one with a 301 redirect.  Google's explanation is [here](https://support.google.com/webmasters/answer/44231?hl=en).
Comment: Thanks for the information. This is something to consider, but there might still be times when the two hosts are wanted, so hopefully someone can answer.
Answer: No, this does not appear to work when testing the configuration file with:
# lighttpd -t -f lighttpd.conf

I guess each $HTTP["host"] field has to be separate, with the server.document-root repeated if you want different sub-domains to serve the same site data.


Entity Framework 5 library consumers need entity framework dlls?

Question: I have a Project "Project.EntityFramework" which contains a context to my db.  When attempting to consume the context from a separate project within the same solution "Project.Business" like:
using (var db = new EntityFramework.Entities())
{
    // Code
}

I get the compiler error on "using":
Error   12  'EntityFramework.Entities': type used in a using statement must be implicitly convertible to 'System.IDisposable'   ....

Now I can F12 and drill down to the Entities, and see it is implementing IDisposable - I can make this error go away if I put reference dlls to entity framework in "Project.Business" but this is defeating the purpose of what I wanted to accomplish - not having any dependency on EF within my Business layer.
Am I doing something wrong?  Or is this just how it has to be?
Comment: If your business layer doesn't want to have any dependency to EF, then your EF project should return something that has no dependency to EF, returning `Entities` that means you will use the EF objects directly, `DbSet`, `DbContext`, `DbConfiguration`, `Database`, etc... you might want to return something more primitive, like `IEnumerable`
Answer: You're not doing anything wrong. If you want the business layer to not depend on EF, you'll need to wrap access to your DbContext class with something else. The Repository pattern is a popular one.
Comment: could you provide an example of how to accomplish this?  When I attempted to do so using an IDispoable repo, I ran into the same issue
Answer: To expand on @Spivonious' answer, here is what I did to accomplish the repository pattern on my DbContext - hopefully it's mostly implemented properly :/
public interface IFooEntity : IDisposable
{
    IEnumerable<Foo> Get();
}

public class FooRepository : IFooEntity
{
    private readonly Entities _context;

    public FooService()
    {
        this._context = new Entities();
    }

    public IEnumerable<Foo> Get()
    {
        return _context.Foo;
    }

    public void Dispose()
    {
        _context.Dispose();
    }
}

original code from question:
using (var db = new EntityFramework.Entities())
{
    // Code
}

changed to:
using (var db = new EntityFramework.Repository.FooRepository())
{
    // Code
}

this allowed my code in the separate project to use my repository rather than the context itself, allowing the business project to not have to rely on entity framework references.
Comment: Looks good, although I'd throw a ToList() on the return statement in the Get method to make the DB query run right there instead of when you enumerate it the first time. If you do want that behavior, it's customary to return IQueryable instead.
Answer: I had this same issue after adding some code and referencing a DLL with the model in it. After some head scratching I realised I hadn't referenced EntityFramework. The problem went away after adding that.


python: restarting a loop

Question: i have:
for i in range(2,n):
    if(something):
       do something
    else:
       do something else
       i = 2 **restart the loop

But that doesn't seem to work. Is there a way to restart that loop?
Thanks
Answer: You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer.
perhaps a:
i=2
while i < n:
    if something:
       do something
       i += 1
    else:
       do something else
       i = 2 #restart the loop

Comment: But there's nothing preventing i from continuing to reset to 2 indefinitely, depending on the "if something" test.
Comment: Just a reminder: with a while loop, make sure you have a termination condition that can always be satisfied.
Comment: I reckon this will terminate when i>=n
Comment: So it depends more on the if-test than the loop invariant? Is there another solution that avoids this while staying simple(because simplicity is key)? Won't there always be the same risk in any loop with the potential to restart?
Answer: Changing the index variable i from within the loop is unlikely to do what you expect. You may need to use a while loop instead, and control the incrementing of the loop variable yourself. Each time around the for loop, i is reassigned with the next value from range(). So something like:
i = 2
while i < n:
    if(something):
        do something
    else:
        do something else
        i = 2 # restart the loop
        continue
    i += 1

In my example, the continue statement jumps back up to the top of the loop, skipping the i += 1 statement for that iteration. Otherwise, i is incremented as you would expect (same as the for loop).
Answer: Here is an example using a generator's send() method:
def restartable(seq):
    while True:
        for item in seq:
            restart = yield item
            if restart:
                break
        else:
            raise StopIteration

Example Usage:
x = [1, 2, 3, 4, 5]
total = 0
r = restartable(x)
for item in r:
    if item == 5 and total < 100:
        total += r.send(True)
    else:
        total += item

Answer: Just wanted to post an alternative which might be more genearally usable. Most of the existing solutions use a loop index to avoid this. But you don't have to use an index - the key here is that unlike a for loop, where the loop variable is hidden, the loop variable is exposed.
You can do very similar things with iterators/generators:
x = [1,2,3,4,5,6]
xi = iter(x)
ival = xi.next()
while not exit_condition(ival):
    # Do some ival stuff
    if ival == 4:
        xi = iter(x)
    ival = xi.next()

It's not as clean, but still retains the ability to write to the loop iterator itself.
Usually, when you think you want to do this, your algorithm is wrong, and you should rewrite it more cleanly. Probably what you really want to do is use a generator/coroutine instead. But it is at least possible.
Answer: a = ['1', '2', '3']
ls = []
count = False

while ls != a :
    print(a[count])
    if a[count] != a[-1] :
        count = count + 1
    else :
        count = False

Restart while loop.

python: restarting a loop


Java setter method convention (is it OK to overload setters?)

Question: I have condition where the way i construct a string (finalValue) is based on the number of non null values i get in my input. So I was wondering if it is OK to over load the setter method for the string (finalValue) with one diff no of parameters  and call them based on the values i get? Is this a bad programming practice?
public void setFinalString(String a){
   this.finalString = a;
}

public void setFinalstring(String a, String b){
   this.finalString = a + " --f " + b;
}

Or I can have the method to construct the finalString based on the inputs i get and then invoke the setter (no overloading here) for the finalString.
Pls tell me is it ok to over load setters , suggest which is a better approach?
thanks
Comment: Perhaps you could post a code example?
Answer: Yes, this is definitely a bad approach, a setter is always supposed to just set the passed parameter to the encapsulated private ivar.
The other logic should be somewhere else not in the setter, although it is sometimes accepted to have restrictions when you set the parameter in your setter i.e.
public setAge(int age) {
    if (age >= 0)
        this.age = age;
    else
        this.age = 0;
}

That is as much logic as a setter should have, it definitely should never receive more than the value it is assigning to the ivar.
Answer: Perhaps you want to use a pseudo getter instead of setters?
private String a, b;
public String setA(String a) { this.a = a; }
public String setB(String b) { this.b = b; }
public String getFinalString() {
    if (a != null && b != null)
        return a + " --f" + b;
    if (a != null)
        return a;
    throw new Exception("Not enough parameters to construct final string");
}

Answer: If someone does not allow to override methods, he should put final keyword. It is about what you want to do and how you communicate ith other developers. Sometimes only way of communication is code and correct method signatures which dont allow misunderstandings.
Aproach depends on what you have, try to code in a sane way and think about how your classes should look like if some developer wants to use them and is not able to ask you questions.
If you are lucky (very lucky) he will approach same way :)


Boost::Thread linking error on OSX?

Question: So I'm going nuts trying to figure this one out.  Here's my basic setup:
I'm compiling a shared library with a bunch of core functionality that uses a lot of boost stuff.  We'll call this library libpf_core.so.  It's linked with the boost static libraries, specifically the python, system, filesystem, thread, and program_options libraries. This all goes swimmingly.
Now, I have a little test program called test_socketio which is compiled into a shared library (it's loaded as a plugin at runtime).  It uses some boost stuff like boost::bind and boost::thread, and it's linked again libpf_core.so (which has the boost libraries included remember).
When I go to compile test_socketio though, out of all my plugins it gives me a linking error:
[ Building test_socketio ]
g++ -c -pg -g -O0  -I/usr/local/include -I../include test_socketio.cc -o test_socketio.o
g++ -shared test_socketio.o -lpy_core  -o test_socketio.so
Undefined symbols:
  "boost::lock_error::lock_error()", referenced from:
      boost::unique_lock<boost::mutex>::lock()   in test_socketio.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

And I'm going crazy trying to figure out why this is.  I've tried explicitly linking boost::thread into the plugin to no avail, tried ensuring that I'm using the boost headers associated with the libraries linked into libpf_core.so in case there was a conflict there.
Is there something OSX specific regarding boost that I'm missing?  In my searching on google I've seen a number of other people get this error but no one seems to have come up with a satisfactory solution.
Edit: Figured it out, OSX comes with boost 1.40 in /usr/local/include.  Needed to put the headers for my version of boost somewhere and make sure that my plugins sees those first.
Comment: post your solution as an answer then accept it :)
Comment: Err, can you detail exactly how you solved it?
Comment: It's been about 4 years now, but it sounds like I was building my core library with a different version of boost than the system version.  I needed to put the headers for that different version somewhere and setup my include path so that my plugins saw them first.
Answer: You need to link to libboost_thread. Add the -lboost_thread switch.
Answer: When you link libpf_core.so against the static boost libraries, it's only going to get copies of the functions it actually uses. The linker doesn't bother to pull in functions that aren't referenced by the code in your library.
You need to link your test program against the boost libraries as well. You can't reliably "chain" the linkages.
Comment: Hmm that may be the problem, I tried linking libboost_thread-mt.a against the plugin as well though and it didn't help.  10.5 has a set of boost libraries included with it, I'm playing with the notion that they're conflicting somehow.

Boost::Thread linking error on OSX?


How to find all real solution to satisfy this equation without casework or bruteforce?

Question: How to find all real solution to satisfy this equation without casework or bruteforce?
a+b+c=abc
Thanks in advance!
Comment: It would more fun if you would tell us something about where you came across a problem and why you're interested in it, and it would also be nice if you would tell us what thoughts you've had about how to solve it, e.g., "I tried (...), but it didn't work."
Comment: Rahul Narain and my daughter independently came up with a much simpler method, which works for all $n$ and for both real and rational cases: http://math.stackexchange.com/questions/111040/positive-rationals-satisfying-abcd-abcd
Answer: Since $\tan\alpha+\tan\beta+\tan\gamma=\tan\alpha\tan\beta\tan\gamma$ for $\alpha$, $\beta$, $\gamma$ being three angles in a triangle, pick any triangle and take the tangents of its three angles and you'll have a solution to your equation over the reals: $(\tan\alpha,\tan\beta,\tan\gamma)$.
Comment: Since $\alpha$, $\beta$, and $\gamma$ are the three angles in a triangle, $\gamma=\pi-\alpha-\beta$, so $\tan\gamma=$ $\tan(\pi-\alpha-\beta)=$ $-\tan(\alpha+\beta)=$ $-\frac{\tan\alpha+\tan\beta}{1-\tan\alpha\tan\beta}$.  Substitute that for $\tan\gamma$ on both sides of the identity and do some manipulation and the result falls out.
Comment: Note that there are solutions such as $(0,0,0)$, $(-\sqrt{3},-\sqrt{3},-\sqrt{3})$, and $(\sqrt3,-1/\sqrt{3},-1/\sqrt{3})$ that won't be realized by taking tangents of the interior angles of a triangle.
Answer: Start with any set of three numbers $a$, $b$, and $c$, let $s=\sqrt{(a+b+c)/(abc)}$, and let $a'=sa$, $b'=sb$, and $c='sc$. Then $(a',b',c')$ is a solution. The only solution that can't be found by this method is the trivial one, $(0,0,0)$.
Comment: How are you able to derive this method?
Comment: You can easily prove it by substitution. The idea is simply that the RHS and LHS scale differently, so by picking the scaling factor appropriately, you can always get them to be equal.


Sorting dynamic ranges on multiple excel sheets

Question: When I run my macro it sorts either one tab or the other, not both.
I have a workbook in which I am importing data from other two other workbooks that are auto-generated from a report. I copy the entire sheet from the report generated worksheet and paste it into an "Import" worksheet, and I do this for both reports. I want to take the information from the Imprt worksheets, and pull out only in information I need.
I am using a macro to pull the columns that have the information required because the columns are always static. For Example:
    Dim sourceColumn As Range, targetColumn As Range, Tracker As Workbook

    Set sourceColumn = Workbooks("Book1.xlsm").Worksheets("Import1").Columns("AZ")
    Set targetColumn = Workbooks("Book1.xlsm").Worksheets("Macro1").Columns("A")

    sourceColumn.Copy Destination:=targetColumn

I repeat this code snippet until I have all of the information I want from Import1 in Macro1, and all the information I want from Import2 to Macro2, and all in the proper order (Name first, and then additional information from there). This works perfect.
Next, I want to sort each Macro worksheet so that all of the information is sorted by the names in Column A, alphabetically. Since the ranges will not always be the same length I am using the following code to set a Dynamic Range, account for the headers, sort by the names in Column A. There are never blank columns or rows being pulled that need to be accounted for.
Dim sheet1 As Worksheet, StartCell1 As Range, Selection1 As Range
Dim sheet2 As Worksheet, StartCell2 As Range, Selection2 As Range

Set sheet1 = Workbooks("Book1.xlsm").Worksheets("Macro1")
Set StartCell1 = Range("A1")

Set Selection1 = StartCell1.CurrentRegion
Selection1.Select

Selection1.Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlYes, Orientation:=xlSortColumns

Set sheet2 = Workbooks("Book1.xlsm").Worksheets("Macro2")
Set StartCell2 = Range("A1")

Set Selection2 = StartCell2.CurrentRegion
Selection2.Select

Selection2.Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlYes, Orientation:=xlSortColumns

This always pulls and populates both Macro sheets as expected. The problem I run into is that when I run the Macro once, it sorts the first tab by name, and not the second. Then when I run the Macro again, it unsorts the first tab and sorts the second tab.
I plan to pull the data from both of these Macro tabs into a main Worksheet that will be presented to my end users, and running a CountIf and various other automated calculations to show them meaningful information pulled from these reports based on their names. I need both Macro sheets to sort by name and stay sorted so that I can automate these analytics.
How to I get this Macro to sort the first tab, and them move to the second tab and sort that one too?
Comment: `Set StartCell2 = Range("A1")` this reference is relative to the  `ActiveSheet`, always consider referencing your ranges. example: `Set StartCell2 = sheet2.Range("A1")`
Answer: Try
Option Explicit

Sub test()

    Dim sheet1 As Worksheet, StartCell1 As Range, Selection1 As Range
    Dim sheet2 As Worksheet, StartCell2 As Range, Selection2 As Range

    Set sheet1 = Workbooks("Book1.xlsb").Worksheets("Macro1")
    Set StartCell1 = sheet1.Range("A1")

    Set Selection1 = StartCell1.CurrentRegion

    Selection1.Sort Key1:=StartCell1, Order1:=xlAscending, Header:=xlYes, Orientation:=xlSortColumns

    Set sheet2 = Workbooks("Book1.xlsb").Worksheets("Macro2")
    Set StartCell2 = sheet2.Range("A1")

    Set Selection2 = StartCell2.CurrentRegion

    Selection2.Sort Key1:=StartCell2, Order1:=xlAscending, Header:=xlYes, Orientation:=xlSortColumns

End Sub


High School Math: Lines and Angles

Question: I have a simple high school math questions about intersecting lines. However, I was unable to answer this question.

I thought the answer should be "D" since I really don't see the questions are giving the answer. Please help.
Comment: from the photo it seems they are parallel lines and i don't see any relation between the quantities.
Comment: If the lines are parallel, then the sum of these angles is 180 degrees. Since these lines cross, the sum of these angles is [greater than or less than??] 180 degrees. So $5x > 180$... you should be able to determine that three times a positive number is greater than two times a positive number.
Comment: This doesn't seem much like a linear algebra question...
Comment: I dont see how the line intersecting on the right implies that (5x>180), please help.
Comment: Draw a triangle.
Comment: If the lines were parallel, then any line crossing would have to sum to 180 degrees on both sides of either line, so the interior angles on the same side of the intersecting line must also sum to 180 degrees. Hence, IF the lines were parallel, 2x + 3x = 180. However, the since the lines intersect on the right, they are slightly more open than that on the left of the picture, and hence 2x + 3x > 180.
Answer: Since the lines meet to the right,
$$2x+3x>180^{\circ}\implies{}x>36^{\circ}.$$
Hence Quantity $A$>Quantity $B$, which is option A.
Comment: @kimberly, if the lines meet, a triangle is formed. The angles in this triangle are $180-2x$, $180-3x$ and a third angle $\alpha\ne0$. Since $180=180-2x+180-3x+\alpha$, we have $5x=180+\alpha > 180$,
Comment: Um.. Its just a basic rule taken for granted and is one of the things that is "impossible" to be proven.
Comment: Can you explain, why lines intersecting on the right => 2x+3x>180?
Comment: Its actually a basic rule called an axiom. Precisely it is Axiom 3 (Parallel Axiom) of Euclid's Elements.
Comment: high school math explaination please.
Answer: In laymen terms, you know that a line must add up to 180degrees. And you also know that the top line is (2x+3x) and the bottom line is (3x+2x) respectively. So 5x must be equal to 180 for a line to exist, and therefore x=36 so the quantities are the same.
Comment: $m$ and $n$ are *not* parallel; they intersect somewhere out to the right.
Answer: Suppose the points are M and N and the lines meet at P.
MNP form a triangle.
Hence, ang.PMN + PNM + MPN = 180°
Now, PMN =180°-2x°,PNM=180°-3x°
Substituting,
360°+MPN= 180 + 5x°
Or, 5x= 180+MPN
now,MPN>0 Or else m and n coincide,
Hence,5x>180
Or,x>36 .Or,quantity A > quantity B.
Answer: That is like two lines: $3x+2x=5x$. There are two angels on the left side. Just look only at them. Do not think about left angels. The angel $3x$ and the angel $2x$ are more than $180$ degrees.

High School Math: Lines and Angles


Merge tuples if their first element starts with specific string

Question: I have a kinda tricky problem that I can't figure out how to resolve, so I'll try to explain it thoroughly. My dataframe has 5 columns, here's an example row:
 title                                                                                in_id    tar_id       in           tar
[('<IN>This</IN>', 'DET', 'nsubj'), ('is', 'VERB', 'ROOT'), ('an', 'DET', 'det'), ('example', 'NOUN', 'compound'), ('text', 'NOUN', 'attr'), ('that', 'DET', 'dobj'), ('I', 'PRON', 'nsubj'), ('use', 'VERB', 'relcl'), ('in', 'ADP', 'prep'), ('order', 'NOUN', 'pobj'), ('to', 'PART', 'aux'), ('<TAR>get</TAR>', 'VERB', 'acl'), ('<TAR>an</TAR>', 'DET', 'det'), ('answer', 'NOUN', 'dobj')]    2137     2984      [1]       [12, 13]

So in the title we have a list of tuples, where the first tuple element is a word, the second is the part of speech tag, and the third is its dependency tree tag.
The in and tar columns are arrays that map to  the position of the words in the sentence that I want to mark either with 'word' or 'word' respectively.
The in_id and tar_id map to their ids.
What I want is this:
If in the in and/or tar there are more than one values (for example in the row I show tar=[12, 13], I want the words at positions 12 and 13 to become one tuple instead of being two separate tuples.
So this ('<TAR>get</TAR>', 'VERB', 'acl'), ('<TAR>an</TAR>', 'DET', 'det')
should become this:
('<TAR>get an</TAR>', 'TAR', '')
So the first elements of the 2 tuples merge, the second element gets renamed into the column name (either IN or TAR and the third element is empty.
cols = list(df.columns)[4:]
for i in range(len(df))

parsed_sent = []
for idx, row in df.iterrows():
    doc = nlp(row['title'])
    dep_sents = [(token.text, token.pos_, token.dep_) for token in doc if not token.pos_ == "PUNCT"]
    for position, tuple_ in enumerate(dep_sents):
        word = tuple_[0]
        pos_tag = tuple_[1]
        dep = tuple_[2]
        for col in cols:
          if position in row[col]:
              word = f'<{col.upper()}>{word}</{col.upper()}>'
          else:
              word = word
    tuple_ = (word, pos_tag, dep)
    dep_sents[position] = tuple_
parsed_sent.append(dep_sents)
df['title'] = parsed_sent

Answer: i think this should do. your indices start at one, it's weird and my code assumes they start at 0
the merging will happen on the first index
import re
def merge_tags(tag, indices, tuples):

    untar=re.compile(f'<{tag}>(.+)</{tag}>')

    tar_text=[]
    for i in indices:
        column,*_ = tuples[i]
        tar_text.append(re.match(untar, column).group(1))
    tar_text=' '.join(tar_text)

    for i in indices[1:]:
        del tuples[i]

    tuples[indices[0]]=(f'<{tag}>{tar_text}</{tag}>', f'{tag}', '')
    return tuples

tars=[11, 12] # in python indices start at 0
row=[('<IN>This</IN>', 'DET', 'nsubj'), ('is', 'VERB', 'ROOT'), ('an', 'DET', 'det'), ('example', 'NOUN', 'compound'), ('text', 'NOUN', 'attr'), ('that', 'DET', 'dobj'), ('I', 'PRON', 'nsubj'), ('use', 'VERB', 'relcl'), ('in', 'ADP', 'prep'), ('order', 'NOUN', 'pobj'), ('to', 'PART', 'aux'), ('<TAR>get</TAR>', 'VERB', 'acl'), ('<TAR>an</TAR>', 'DET', 'det'), ('answer', 'NOUN', 'dobj')]
print(merge_tags('TAR', tars, row))
>>> [('<IN>This</IN>', 'DET', 'nsubj'), ('is', 'VERB', 'ROOT'), ('an', 'DET', 'det'), ('example', 'NOUN', 'compound'), ('text', 'NOUN', 'attr'), ('that', 'DET', 'dobj'), ('I', 'PRON', 'nsubj'), ('use', 'VERB', 'relcl'), ('in', 'ADP', 'prep'), ('order', 'NOUN', 'pobj'), ('to', 'PART', 'aux'), ('<TAR>get an</TAR>', 'TAR', ''), ('answer', 'NOUN', 'dobj')]

you already know how to iterate over rows so i'll keep it to a minimum
row['title']=merge_tags('TAR', row['tar'], row['title'])
row['title']=merge_tags('IN', row['in'], row['title'])

Comment: I'm still not sure how to apply this to each row of dataframe and not only for 'TAR' but also for 'IN'


Bad ARP Cache static entries

Question: I have a weird issue that popped up on our network.
Once or twice a week a user (it's always a different user) would complain about not being able to communicate to our Small Business Server 2003 that handles Exchange, DNS and file sharing, essentially cutting the machine off from any sort of network communication.
When I check the ARP table on that particular server there is a static ARP entry mapped to the IP address of the workstation in question with a completely different MAC address. If I manually delete the static entry the machine is back online. The weird thing is that it's always a different machine that has this problem.
For the life of me I can't figure out what's setting these static ARP entries on the server and forcing me every time to go in and remove it manually to bring the workstation back online.
Our environment is fairly small (20 workstations and 2 servers).
Any help is appreciated.
Comment: Does the MAC address correspond to anything on your network? The first half of the MAC addreass will id the vendor.
Comment: It's been driving me so crazy that I didn't even think of finding out what the MAC address could belong to. On the surface it seemed like it is a server issue as I don't know what could compel the server to add a random static ARP entry to its table for an MAC address to an IP address that it doesn't belong to.
Answer: Try to identify if the MAC address belongs to any equipment on your network. You can lookup vendor addresses here.
Do you have a wireless access point on your network, is it secured? look for the MAC addresses of any connected devices. You can normally view these from the access point.
Do you have any virtual machines running on any of the workstations or servers?
Is it always the same MAC address that appears in the arp table?
What about the arp caches on your network switch and router ( if they let you view them) do the IP/MACs  correspond with the table on your server at the time you have an issue? Does powercycling the switch/ router make any difference?
Comment: Great suggestions. I will be looking into trying to find a pattern in the mappings and hopefully will be able to tie it to a device on the network.
Answer: Is there any chance that someone is running ettercap or similar arp cache poisoning style  attack on your network?
Comment: Anything is possible but like I mentioned, it's a fairly small network and it's just the sporadic workstation that's having the issue so it's highly unlikely, there is really nothing to be gained.

Bad ARP Cache static entries


Show progress of code executed on form submit

Question: I have a form in my site (custom module) where the user chooses some options and depending on those options, some code is executed.
The code basically executes shell commands on a remote server and at the moment, all the drupal_set_message commands are only shown after all commands are executed.
Is there any way that I can show those messages as soon as each part of the code is executed?
function mymodule_connect() {
    $host = '<my ip address>';
    $username = '<my username>';
    $password = '<my password>';

    $connection = ssh2_connect($host, 22);
    ssh2_auth_password($connection, $username, $password);

    return $connection;
}

function mymodule_form_submit(&$form, &$form_state) {

    $delete_load = $form_state['values']['delete_load'];
    $change_load = $form_state['values']['change_load'];
    $load_number = $form_state['values']['check_load'];

    if($change_load == 1) {
        # DELETE
        # perform some command

        # LOAD
        # perform other command

        drupal_set_message('Deleting. Please wait...', 'error');
        drupal_set_message('Changing load. Please wait...', 'warning');
    } elseif ($delete_load == 1 && $change_load == 0) {
        # DELETE
        drupal_set_message('Deleting. Please wait...', 'error');

        $command = "<some shell script command to send>";

        $connection = mymodule_connect();

        $stream = ssh2_exec($connection, $command);
        stream_set_blocking($stream, true);
        $output = stream_get_contents($stream);
        dpm($output);

        ssh2_exec($connection, 'exit');
        unset($connection);

    } else {
        # do nothing
    }

    # OTHER DIFFERENT SET OF COMMANDS TO SEND
    drupal_set_message('Configuring. Please wait...', 'status');

    $commands = array(
        "<some shell script command to send>",
        "<some shell script command to send>",
        "<some shell script command to send>",
    );

    $connection = mymodule_connect();

    foreach ($commands as $command) {
        $stream = ssh2_exec($connection, $command);
        stream_set_blocking($stream, true);
        $output = stream_get_contents($stream);
        dpm($output);
    };

    ssh2_exec($connection, 'exit');
    unset($connection);

    return t('Success');
}

Comment: Drupal 7 I assume?
Comment: Javascript & ajax is the answer, but I'm sure someone can get more specific than that.
Comment: Sure. Is Drupal 7
Answer: Surely you need to implement Batch API to achieve what you need, and keep the user notified for what's happening in the background.
Very similar question that will help you more. Read it carefully.
These modules will help you:

Progerss This is an attempt to implement a generic framework for keeping track of any progress
Background progress takes over the existing Batch API and runs batch jobs in a background process
Answer: As Mohammed Gomma mentioned you need to use Batch API to achieve the same. The implementation of batch api may look something like code given below:

Create Batch array
Create function to execute commands and call them using batch operation
set context message in the function created
create finish callback
function mymodule_form_submit(&$form, &$form_state) {
      $delete_load = $form_state['values']['delete_load'];
      $change_load = $form_state['values']['change_load'];
      $load_number = $form_state['values']['check_load'];

      if ($change_load == 1) {
        # DELETE
        # perform some command
        # LOAD
        # perform other command

        drupal_set_message('Deleting. Please wait...', 'error');
        drupal_set_message('Changing load. Please wait...', 'warning');
      }
      elseif ($delete_load == 1 && $change_load == 0) {
        # DELETE
        drupal_set_message('Deleting. Please wait...', 'error');

        $command = "<some shell script command to send>";

        $stream = ssh2_exec($connection, $command);
        stream_set_blocking($stream, true);
        $output = stream_get_contents($stream);
        dpm($output);

        ssh2_exec($connection, 'exit');
        unset($connection);
      }
      else {
        # do nothing
      }

      # OTHER DIFFERENT SET OF COMMANDS TO SEND
      drupal_set_message('Configuring. Please wait...', 'status');

      $commands = array(
        "<some shell script command to send>",
        "<some shell script command to send>",
        "<some shell script command to send>",
      );

      $batch = array(
        'finished' => 'batch_example_finished',
        'title' => t('Processing Example Batch'),
        'init_message' => t('Example Batch is starting.'),
        'progress_message' => t('Processed @current out of @total.'),
        'error_message' => t('Example Batch has encountered an error.'),
      );
      foreach ($commands as $command) {
        $batch['operations'][] = array('_batch_execute_command', array($command));
      };

      batch_set($batch);

      return t('Success');
    }

    function _batch_execute_command($command, &$context) {
      $connection = mymodule_connect();
      $stream = ssh2_exec($connection, $command);
      stream_set_blocking($stream, true);
      $output = stream_get_contents($stream);
      dpm($output);
      ssh2_exec($connection, 'exit');
      unset($connection);
      $context['message'] = t('Now processing %command', array('%command' => $command));
      if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
        $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
      }
    }

    /**
     * Batch 'finished' callback
     */
    function batch_example_finished($success, $results, $operations) {
      if ($success) {
        // Here we do something meaningful with the results.
        $message = t('@count items successfully processed:', array('@count' => count($results)));
        // $message .= theme('item_list', $results);  // D6 syntax
        $message .= theme('item_list', array('items' => $results));
        drupal_set_message($message);
      }
      else {
        // An error occurred.
        // $operations contains the operations that remained unprocessed.
        $error_operation = reset($operations);
        $message = t('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
        drupal_set_message($message, 'error');
      }
    }

Nested batch example:
function gamify_batch_form($form, $form_state) {
  return array(
    'submit' => array(
      '#type' => 'submit',
      '#title' => 'submit',
      '#value' => 'submit',
    ),
  );
}

function gamify_batch_form_submit($form, $form_state) {
  $batch = array(
    'finished' => 'batch_example_finished',
    'title' => t('Processing Example Batch'),
    'init_message' => t('Example Batch is starting.'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Example Batch has encountered an error.'),
  );
  $commands = array(
    'hi',
    'hello',
    'world',
    'dear',
    'world',
  );
  foreach ($commands as $command) {
    $batch['operations'][] = array('_batch_execute_command', array($command));
  };

  batch_set($batch);
}

function _batch_execute_command($command, &$context) {
  file_get_contents("https://drupal.stackexchange.com/questions/246767/show-progress-of-code-executed-on-form-submit/247718?noredirect=1#comment303466_247718");
  if($command == 'world'){
    $batch = array(
      'finished' => 'batch_example_finished',
      'title' => t('Processing Example Batch'),
      'init_message' => t('Example Batch is starting.'),
      'progress_message' => t('Processed @current out of @total.'),
      'error_message' => t('Example Batch has encountered an error.'),
    );
    $commands = array(
      'hi 1',
      'hello 2',
      'dear 3',
    );
    foreach ($commands as $innercommand) {
      $batch['operations'][] = array('_batch_execute_command', array($innercommand));
    };

    batch_set($batch);
  }
  $context['message'] = t('Now processing %command', array('%command' => $command));
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
}

/**
 * Batch 'finished' callback
 */
function batch_example_finished($success, $results, $operations) {
  if ($success) {
    // Here we do something meaningful with the results.
    $message = t('@count items successfully processed:', array('@count' => count($results)));
    // $message .= theme('item_list', $results);  // D6 syntax
    $message .= theme('item_list', array('items' => $results));
    drupal_set_message($message);
  }
  else {
    // An error occurred.
    // $operations contains the operations that remained unprocessed.
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
    drupal_set_message($message, 'error');
  }
}

Comment: Thanks. @Vishal Patil: When you call _batch_execute_command, I think you don't need the $stream. I removed it but I still have an issue. The variable $connection is not passed to the function.
Comment: You can create connection inside _batch_execute_command() instead of passing the argument. Please check updated sample code.
Comment: Thanks Vishal Patil. Now is working. I am missing just one thing. If I add a call to a new function inside "foreach ($commands as $command) {", can I add it to the batch? The thing is: for each command, if some variable is equal to something, I will have another set of commands that I need to run in a batch.
Comment: EDIT: noticed now that for that new batch, I need a value that is generated inside the first batch. So this seems a case that I need batches inside batches. Don't know if this is the best way to do it
Comment: You can try creating nested batch inside _batch_execute_command() function if the condition is matched. Check answers for nested batch example.
Comment: Progress percent may look confusing because of nested batch.
Comment: All working well now. Many many thanks Vishal. I'm just missing something that I can't find information. If I close the page or reload after I submit the form, the processes run well but I can't see the information. Is there a way to check if some process is running and view that information?


Hierarchical data in MvcContrib Grid

Question: Is it possible to show a class with a nested IEnumerable property within MvContribGrid such as...
public class ParentViewModel
{
    IEnumerable<Parent> Parents {get;set;}
}

public Class Parent
{
     public string Name{get;set;}
     public IEnumerable<Children> Children {get;set}
}

Answer: I had similar requirement, but i used ajax for Hierarchical information showing. It help me two ways. One the child information is loaded when requested. so i dont have to load all information on one go and also helped in multiple level Hierarchy.
I used Jquery Datatable along with mvccontrib grid for pagination search and for Hierarchical data expand collapse link were introduced
Updated:
In my exmple i have created first column with some concat information on first column which is required me to identify the row i have clicked. class .expand is to tell on click it should be expanded.a $.ajax call be made and information retrieved will be appended to the clicked row. expand/collapse are js method. you will see below this code.
<%Html.Grid(Model)
    .Columns(column =>
            {%>
            <% <a id="<%= c.Desc %>_<%= c.No %>" href="#" class="expand">
            <% }).Attributes(c => new Dictionary<string, object> { { "padding-left", " 5px" } });
                column.For(c => c.Date).Format("{0:dd/MM/yyyy}").Named("Date");
                column.For(c => c.Desc).Named("Description");
               }).Attributes(id => "example")
            .Empty("----------- No Ledger Details for current month/Search -----------    ").Render();%>

I used jquery datatable for pagination and search in populated rows.and also used tabletool plugin for jquery datatable which help in exporting result to csv/xls/pdf. and copy pasting my content.

For collapse/Expand
$("#example a.collapse").live('click', function (event) {
            event.preventDefault();
            $(this).closest('tr').next().slideUp().remove();
            $(this).removeClass("expand");
            $(this).addClass("collapse");
        });
        $("#example a.expand").live('click', function (event) {
            event.preventDefault();
            var parent = $(this).closest('tr');
            var linkid = $(this).attr('id');
            var parts = linkid.split("_");
            var billNo = parts[1];
            loadBillDetails(parent, billNo);
            $(this).removeClass("collapse");
            $(this).addClass("expand");
        });

        function loadBillDetails(parent, billNo) {
            var defaultParameters = "{BillNo:" + billNo + "}";
            $.ajax({
                type: "POST",
                url: '<%=Url.Action("GetBillDetails", "Order") %>',
                data: defaultParameters,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: (function (data) {
                    var str = "

";
                    str += "

BillNo	ProductName	OrderNo	RollNo	Qty	Rate
";
                    if (data.BillDetails.length > 0) {
                        for (var y = 0; y < data.BillDetails.length; y++) {
                            str += "
" + data.BillDetails[y].FinalBillNo + "	" + data.BillDetails[y].ProductName + "	" + data.BillDetails[y].OrderNo + "	" + data.BillDetails[y].RollsNo + "	" + data.BillDetails[y].Qty + "	" + data.BillDetails[y].Rate + "
";
                        }
                        str += "

";
                    }
                    else {
                        str = "
No order found.
";
                    }
                    var newRow = $(str);
                    parent.after(newRow).slideDown();
                }),
                error: (function () {
                    parent.after("
An Error has occurred.
");
                })
            });
        }

    });

Comment: @KaiCriticallyAcclaimedCooper i have upated my answer with my example
Comment: @KaiCriticallyAcclaimedCooper What?
Comment: In case you still would like to know. I used an Ajax Action link w/ the id, rendered a partial control that uses MvcContribGrid and the embedded list and displayed it
Comment: are you loading sub list at the time of mvcconttib grid is rendered
Comment: I made 2 list, one for the Parent, when you click on the parent I render another grid in another div tag using an ajax call for the children:

Hierarchical data in MvcContrib Grid


What comes after the geometric mean?

Question: The geometric mean is a multiplicative alternative to the arithmetic mean, which we could call additive mean, thereby calling the geometric mean multiplicative mean. My question is the following: what comes after the multiplicative mean (aka geometric mean)?
This is interesting in the context of the log-log-normal distribution, which is a continuous probability distribution of a random variable whose logarithm logarithm $\ln(\ln(x))$ is normally distributed. Its PDF is:
$f(x) = \displaystyle \frac{1}{\sqrt{2\pi\sigma}x\ln(x)}\exp\Bigg({\frac{-\big(\ln(\ln(x)) - \mu\big)^2}{2\sigma^2}}\Bigg) \quad x \geq 1$
Now, we could rewrite this equation as:
$f(x) = \displaystyle \frac{1}{\sqrt{2\pi\sigma}x\ln(x)}\exp\Bigg({\frac{-\big(\ln(\ln(x^{\frac{1}{e^{\mu}}}))\big)^2}{2\sigma^2}}\Bigg) \quad x \geq 1$
In this equation, $\frac{1}{e^{\mu}}$ is the parameter that I am interested in. This is a level 2 mean if we consider the additive mean (aka arithmetic mean) $\mu$ (for a normal distribution) to be a level 0 mean and the multiplicative mean (aka geometric mean) $e^{\mu}$ (for the log-normal distribution) to be a level 1 mean.
Is there a standard definition for this type of mean?
And did anyone study the sequence of means introduced here?
Comment: I don't know of anyone looking at the specific thing you're asking about, but there are a lot of different kinds of "mean".
Answer:
And did anyone study the sequence of means introduced here?

Many. Check the Generalized Mean
$$M_p(x_1,\dots,x_n) = \left( \frac{1}{n} \sum_{i=1}^n x_i^p \right)^{\frac{1}{p}} $$
in
https://en.wikipedia.org/wiki/Generalized_mean
Comment: This is off topic in this thread, I am just pinging you. Given your expertise in related subjects, perhaps you could be interested in my [question with a bounty](https://stats.stackexchange.com/questions/303887/effects-of-model-selection-and-misspecification-testing-on-inference-probabilis) on the Probabilistic Reduction approach of Aris Spanos.
Comment: @RichardHardy Richard, thanks for the pointer. I won't be able to respond on time for the bounty, things are frantic right now. But I am indeed interested in posting an answer there and will do eventually.
Answer: I think all you need is to get the arithmetic mean of log-log of your series. Here's why.
The geometric mean is basically an exponent of arithmetic mean of log series:
$$\bar y=\frac 1 n\sum_{i=1}^n y_i$$
$$\frac 1 n\sum_{i=1}^n\log x_i=\frac 1 n\log\prod_{i=1}^nx_i=
\log\left(\prod_{i=1}^nx_i\right)^{\frac 1 n}$$
$$\exp\left(\frac 1 n\sum_{i=1}^n\log x_i\right)\equiv e^{\bar x}=
\left(\prod_{i=1}^nx_i\right)^{\frac 1 n}$$
If you have the base normal distribution $\mathcal N(\mu,\sigma^2)$, which forms a lognormal distribution then the geometric mean of the lognormal series is going to give you a decent estimator $\hat\mu$. In my opinion this is the motivation for using the geometric mean. It's a good supparization of multiplicative processes such as lognormal, geometric Brownian motion etc.
Using the same logic, you can try the arithmetic mean of log-log series:
$$\hat\mu'=\frac 1 n\sum_{i=1}^n\log\log x_i$$
This will give a decent estimator $\hat\mu'$ of the mean of the base normal of your log-lognormal distribution. I won't say that it's the most optimal estimator, not sure about that, but it will be a sensible one.
Answer: The mean used for the log-log-normal distribution remains the multiplicative mean (geometric mean), like the one used for the log-normal distribution. But in the case of the log-log-normal distribution, the variable is raised to the power of the inverse of that mean, while it is simply divided by that mean in the case of the log-normal distribution.

What comes after the geometric mean?


Get many words in one search and display. in PHP

Question: I have a php script which searches a user input word and displays the result, but I need to enable it to search more than one word and to display it.
The words are saved in a database.
Now my code accepts only "word1"to be replaced to "word2".
I need to make it "word1" to be replaced to "word2" + "word3" to "word4" and as many as user types.
Here is my current PHP code:
function Search() {

    $q = "SELECT * FROM words WHERE word_title = '" . str_replace('_', ' ', addslashes($_GET['word'])) . "';";
    $res = mysql_query($q);
    while($row = mysql_fetch_array($res)) {
        $c.= '' . LNtoBR($row['word_desc']) . '';
    }
    $GLOBALS['content'].= $c;
    $GLOBALS['content'].= '';
}

I tried like this:
function Search() {

    $q = "SELECT * FROM words WHERE word_title = '" . str_replace('_', ' ', addslashes($_GET['word'])) . "';";
    $res = mysql_query($q);
    while($row = mysql_fetch_array($res)) {
        $c.= 'explode(' . LNtoBR($row['word_desc']) . '), implode(' . LNtoBR($row['word_desc']) . ')';
    }
    $GLOBALS['content'].= $c;
    $GLOBALS['content'].= '';
}

but it doesn't works like JavaScript accepts split(something).join(something); but I need to get the strings from the database and to replace all the user searched string lines with any word that is existing in my database. Thanks.
Comment: Didn't quite get you, can you be more clear on what is required?
Comment: thanks for the quick response. this is the page I am editing "http://raadso.so/translate/" just write one word like "fiican" it will replace it to"good" but i need it to replace like "fiican fiican fiican" to "good good good" and the above code is the one i used for this page script which php.
Comment: When I write more than word, it doesn't display anything. For example if I write 'fiican fiican'.
Comment: @HeroFTime this code returns only one word per search, but I need to make search more words like "good good good" to "fiican fiican fiican" thanks
Comment: I'm curious as to what the line inside the while loop, that concatenates the _string_ values `'explode(…), implode(…)'` into a variable is supposed to achieve …?
Answer: Sorry, can't make comments yet.
Use PHP str_replace for searching and replacing your words.
Also check out PHP nl2br instead of the function you are using (LNtoBR).
Comment: thanks but can't fix this yet, I will update if I get solution for it.


Why ForeignKeyId is not filled automatically in Entity Framework?

Question: Consider following model:
public class Car
{
    public virtual Company Company { get; set; }
    public virtual string CompanyId { get; set; }
}

As I know Company and CompanyId should be synced by convention. So setting Company property should lead to setting CompanyId automatically. So the following test should pass:
myCar.Company = new Company() { Id = "11" };
Assert.AreEqual("11", myCar.CompanyId);

Why is that so?
My DbContext config is:
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;

Comment: I don't think properties linked this way will update until you call `SaveChanges` on the context.
Comment: Your unit test should not expect `CompanyId` to be populated until after `SaveChanges()` is called, as others have indicated.
Comment: @BradleyUffner yep you're right. After Saving the data it's filled. Is there any way to have it set before saving changes. Or I should manually set the `CompanyId` in the setter of `Car.Company`?
Comment: @BradleyUffner I think your comment worth as answer!
Comment: I added an answer with a few extra notes for you.
Answer: If you just new up an object and add it to an entity, that doesn't mean EF has registered that object and does a fetch from the database. You would need to hit the DbContext in order to do that. You can verify this by using whatever sql profiling tool you have available.
Comment: What do you mean by hitting the database?
Comment: The kind of operation you're doing would require EF to hit the database and match up the id values between `Company`'s `Id` and `Car`'s `CompanyId`. Because that round trip never happens and EF has no hands in the operation, they're never synced.
Comment: The `Id` is not generated in database. I assign a Guid to the Id in the constructor.
Comment: That doesn't matter. EF doesn't see it as one of the objects it's tracking so it will ignore what you do with it. You could try manually registering the newed up `Company` and then assigning it to your EF-tracked entity and see if things are updated then.
Answer: When using POCOs (Plain Old Class Objects) with entity framework, "linked" properties like you describe will only update each other when SaveChanges is called on the DbContext they are attached to.  As you can see in your class definition there is actually no "physical" connection between the properties, so updating one will not update the other directly.
The link is actually maintained by your dbContext, and is only updated once changes are saved to the database.  Even then it technically isn't updating the link, but doing a complete refresh of the object from the database.
As an extra note, .SaveChanges is very aptly named.  It actually stores the original values of the properties when loaded from the db and compares them, property by property, looking for changed values so that It knows what to update.  This can be VERY CPU and memory intensive.  If you are just reading data and know that you will never update the instances you should add .AsNoTracking() to your linq query to make it no do all that.
Answer: Remove the virtual from CompanyId.
public class Car
{
    public virtual Company Company { get; set; }
    public string CompanyId { get; set; }
}

Edit: Bradley is right, you have to save the changes to view the linked property.
If you want to access the id before saving you can do this;
var comp = new Company { Id = "11" };
ctx.Companies.Add(comp);

var car = new Car {
    Id = "2",
    CompanyId = comp.Id
};
ctx.Cars.Add(car);

Remember that doing it this way you must add both comp and car to the context.
The linked property car.Company will be null.
Comment: I tested it. didn't work! Also I've added my DbContext config to the question.


Differential Equations: Laplace Transform to Solve Integral Equation

Question: I'm working through some lectures notes on Differential Equations, and in the Laplace Transform section I've encountered the following problem:
Problem
Find a solution to
$$x'(t)+\int^{t}_{0}(t-s)x(s)ds=t+\frac{1}{2}t^2+\frac{1}{24}t^4$$
I'm not really sure how we can apply the Laplace transform here; any assisstance would be greatly appreciated. Regards as always, MM.
Comment: The Laplace transform of a convolution $f\star g$ is the product of the Laplace transforms of $f$ and $g$. So ${\cal L} \int_0^t g(t-s) f(s) ds=F(s)G(s)$.
Comment: @DavidMitra: Here then, are we to assume that $g$ is the identity map (as $g(t-s)=t-s$)?
Answer: Taking the Laplace transform of the left hand side,
using the  convolution formula  on the integral (note the integral is $f\star g$ where $f $ is the identity function and and $g=x$):
$${\cal  L} \Bigl( x'(t)+\int^{t}_{0}(t-s)x(s)ds\Bigr) = s X(s)-x(0) + {1\over s^2}\cdot X(s).
$$
Taking the Laplace transform of the right hand side:
$$
{\cal L}\Bigl( t+\frac{1}{2}t^2+\frac{1}{24}t^4 \Bigr)=
{1\over s^2}+{1\over 2}{2\over s^3}+{1\over 24}\cdot{24\over s^5}.
$$
So, we have:
$$
 s X(s)-x(0) + {1\over s^2}\cdot X(s)=
{1\over s^2}+ {1\over s^3}+ {1\over s^5}.
$$
Now solve for $X(s)$ and then take the inverse transform to find $x(t)$.


How to resize a TvView?

Question: My problem consist in displaying several input options as images. But when I use only one TvVIew, it convert all the screen. If I try to specific the size it doesnt display. Also, I have to create dynamically in code the TvView because if not, it doesnt work
Comment: Please share few code snippets and output of current code along with expectations to avoid delay in answers.
Answer: I found the answer to my question  actually. I was specifying the layer type as software by mistake. That was the reason of why it couldn't be resized.

How to resize a TvView?


Probability of event at the individual level from Bayesian posterior mean distribution

Question: This is the first time I've come across this type of problem. I really appreciate any comments or suggestions.
In a Bayesian model implemented through Stan, with populations as the units of analysis (e.g., hospitals or institutions) , I have estimated a continuous parameter denoted as $\mu$. In this context:
$\mu_i \sim N(\theta, \tau^2)$
where $i$ denotes the mean for the $i^{th}$ population (for $i$ = 1,...,$k$) and $\tau^2$ represents the between-population variance. Thus, $\theta$ represents the average of true means across populations.
Based on $n$ samples from the posterior mean distribution, I want to calculate the probability that a person/individual (across all populations) has a value greather than 50.
In other words, assuming that the value for the $j^{th}$ individual in the $i^{th}$ population is represented by:
$\mu_{ji} \sim N(\mu_i, \sigma^2)$
I want to calculate Pr($\mu_{ji}>50$)
where $\sigma^2$ represents the population-specific variance, assumed to be the same for all populations for simplicity.
To compute Pr($\mu_{ji}>50$), I calculated for each sample from the posterior distribution Pr($\mu_{ji}>50$) = 1-$\Phi\left(\frac{50-\mu_{i}}{\sigma} \right)$
and obtained the median across all $k$ samples
Is this a reasonable approach?
Any suggestions are welcome.
Answer: This is a hierarchical Bayesian model, hence $\mu_{ij}$ only depends on $\mu_i$,  and
$$\mathbb P(\mu_{ji}>50|D)=\mathbb E\left[ \mathbb P(\mu_{ji}>50\big|\mu_i)|D\right]$$
where $D$ denotes the actual sample (to be distinguished from $\mu_{ij}$, which is distributed from the predictive distribution). Now,
$$\mathbb P(\mu_{ji}>50\big|\mu_i)=1-\Phi(\sigma^{-1}\{50-\mu_i\})$$
Therefore
$$\mathbb P(\mu_{ji}>50|D)=1-\mathbb E\left[ \Phi(\sigma^{-1}\{50-\mu_i\}) | D \right]$$
which can be approximated by averaging over the simulated posterior sample.
Comment: Thank so much you. Extremely clear.


Hahn-Banach Thm for Normed Space.

Question: Let $X$ be a normed Space.
For $x \in X$ define
$J(x)=\{f \in X^ * : f(x)=\|x\|^2 , \|f\|=\|x\|\}$.
Prove that $J(x)$ is not the empty set.
Comment: Can you apply Hahn-Banach or is this something you have to do with more elementary tools?
Comment: As indicated by the title, the Hahn-Banach theorem is quite helpful in proving the assertion. Which forms of the Hahn-Banach theorem are you familiar with?
Comment: possible duplicate of [Hahn-Banach Thm for Normed Space](http://math.stackexchange.com/questions/1243918/hahn-banach-thm-for-normed-space)
Comment: Not quite a duplicate, the square missing in the other question is present here. But, @Bank, please add some context to the question. What have you to build on, what have you tried so far, etc.
Answer: Define:
$$ f: \mathbb{R}x \rightarrow \mathbb{R}: ax \mapsto a\|x\|^2 $$
by the Hahn-Banach theorem there exists a $g \in X^*$ s.t. $\|g\| = \|f\|$ and $g = f$ on $\mathbb{R}x$. from this we get:
$$ \|g\| = \|f\| = \sup_{\|ax\| \leq 1} |f(x)| = \sup_{\|ax\| \leq 1} (|a|\|x\| \|x\|) = \|x\| $$
and
$$ g(x) = f(x) = f(1\cdot x) = 1\cdot \|x\|^2 = \|x\|^2 $$
thus we have proven that $g \in J(x)$.

Hahn-Banach Thm for Normed Space.


Ios .mobileconfig how to make it verified

Question: I am struggling with ios configuration profiles.
We need to apply some settings to all our company ios devices.
I've created .mobileconfig file using apple configurator tool. When I am trying to install profile via our webserver, the profile appears as Not Verified.
I found how to use openssl to sign it , the question is what certificate do I need to use as -signer key in command line ?
Do I need to use apple development certificate , or i need to issues special certificate via Verisign ?
Thanks.
Answer: The certificate you use as -signer can be obtained by making a certificate signing request (CRS) to a certificate authority (CA). You can buy commercial certificates from companies like VeriSign etc.
To create a CRS see the link below:
https://www.openssl.org/docs/HOWTO/certificates.txt
Optionally you can create a self-signed certificate using OpenSSL (which will have caveats however), see link below:
http://blog.httpwatch.com/2013/12/12/five-tips-for-using-self-signed-ssl-certificates-with-ios/


Create custom meta tag with the metatag module

Question: Just this. I need to create some metatag using the metatag module: https://www.drupal.org/project/metatag
Something like:
<meta property="og:locale" content="en_US" />
<meta property="og:type" content="website" />

I can't see how to get this in its setting.
Then after I will need to use these metatags in nodes and views.
Answer: You can either use Custom Meta module or roll your own module:
From Custom Meta project page:

The module allows you to define and manage custom meta tags. Simply
  select the Meta attribute (property, name, http-equiv) and set the
  value and content value in the format and the module will add your
  meta tags to all non-admin content for your site.

An example of writing your own module:
my_metatag.info
name = My Metatags
description = Provides my custom Metatags.
core = 7.x
version = 7.x-1.x
dependencies[] = metatag
files[] = my_metatags.metatag.inc

my_metatag.module
<?php

/**
 * Implements hook_ctools_plugin_api().
 */
function my_metatags_ctools_plugin_api($owner, $api) {
  if ($owner == 'metatag' && $api == 'metatag') {
    return array('version' => 1);
  }
}

my_metatag.metatag.inc
<?php
//
// Implements hook_metatag_info().
//
function my_metatags_metatag_info() {
  $info['groups']['my_metatags'] = array(
    'label' => t('My Custom Metatags'),
  );

  $info['tags']['my_custom_metatag'] = array(
    'label' => t('My Custom Meta Tag'),
    'description' => t('This is a custom meta tag'),
    'class' => 'DrupalTextMetaTag',
    'group' => 'my_metatags',
  );

  return $info;
}

//
// Implements hook_metatag_config_default_alter().
//
function my_metatags_metatag_config_default_alter(array &$configs) {
  foreach ($configs as &$config) {
    switch ($config->instance) {
      case 'global':
        $config->config += array();
        break;

      case 'global:frontpage':
        $config->config += array();
        break;

      case 'node':
        $config->config += array(
          'my_custom_metatag' => array('value' => 'This is a default value.'),
        );
        break;

      case 'taxonomy_term':
        $config->config += array();
        break;

      case 'user':
        $config->config += array( );
        break;
    }
  }
}

Hope that helps.
Comment: You can see some other ways to add metatags on another question "[How do I add a meta tag in inside the  tag?](https://drupal.stackexchange.com/questions/217880/how-do-i-add-a-meta-tag-in-inside-the-head-tag)" like through a template or a theme.


it is possible to pause animations?

Question: I am using the animations defined in the xml folder anim, I'm trying to make a move the item, pause, and apply another different movement.
To try to explain better, this is the code:

<code> <set>
     <translate
         android: duration = "2000"
         android: fromXDelta = "0%"
         android: fromYDelta = "0%"
         android: toXDelta = "-50%"
         android: toYDelta = "-50%"
         android: zAdjustment = "top" />
 </ set>

 <set>
     <translate
         android: duration = "2000"
         android: fromXDelta = "0%"
         android: fromYDelta = "0%"
         android: toXDelta = "50%"
         android: toYDelta = "50%"
         android: zAdjustment = "top" />
 </ set>
</code>

... I wish I could take a break before starting the second "translate"
Is it possible?
thanks
Answer: make them as two different set of animation files and add the animation1 first and then take a pause of some time and then set the second animation to your view.Else use this android:startOffset="TIME_IN_MILISEC_FOR_DELAY" in you animation declaration in xml file.
Comment: is there any way to pause and resume this animation on button click?
Answer: Maybe you could try this:
<code><set>
<translate
  android: startOffset: "1000"
  android: duration = "2000"
  android: fromXDelta = "0%"
  android: fromYDelta = "0%"
  android: toXDelta = "50%"
  android: toYDelta = "50%"
  android: zAdjustment = "top" />
</ set>
</code>
According to http://developer.android.com/reference/android/view/animation/Animation.html startOffset is the delay in milliseconds before the animation runs, once start time is reached.

it is possible to pause animations?


Hosting WPF/Surface application within WPF/Surface application

Question: I am trying to create a parent WPF/surface application which will host multiple WPF/surface applications. I am looking for some pointers of how to implement such functionality. Was reading http://msdn.microsoft.com/en-us/library/ms742522.aspx but it talks about hosting Win32 content in WPF and vice versa.
My idea is to have something similar to MDI forms where you have a main form and you can instantiate multiple child forms.
In my case, these would be different applications which will be launched using a config file and loaded within the main application.
Also, since is there a way to ensure that the main window's process memory is not hogged by the child process initiated.
Edit:
The host application will launch different applications based on what user selects. One can say its like an application launcher which are build on WPF/Surface touch SDK. Now once the application is launched the launcher goes in the background(except showing small button to bring it forward again at some point later) and when the user ends the current application launcher comes back again in foreground. The only interaction i feel which is necessary is knowing the launched application is terminated or invoking applications in a limited screen area. If someone has seen the Microsoft surface application launcher, even when the application is launched there are corner buttons which bring the app launcher to foreground.
Comment: there is a whole lot of stuff involved in replicating the surface shell's capabilities.  can you be more specific about what parts you are looking for help on?
Comment: Like i mentioned, main aim is to have a small button on top of each surface application to go back and forth to the application launcher. So aim is to launch surface applications as processes and then keep a track of them if they are closed.
Answer: I would first look at using Microsoft Prism, specifically the Modularity namespace.
Answer: Except for the "different applications" part, it sounds like a classic case for MVVM.  Are these "different applications" actually separate applications, or could they simply be separate projects within the same application?  That may simplify the choice of presentation.
I suppose you could still have a View called "Host" that presents a different app.
Of course, WPF doesn't have the concept of MDI, but you can open multiple, non-modal windows.
It really depends on what you mean by "hosting".  Does the main window need to somehow handle and/or interact with the other applications, or is it just a launching pad for other applications?
Comment: I added some more details to what I have in mind. Trying to have a launcher which would interact with the applications.
Answer: I followed this approach to solve this problem. The launcher was not hosting the application within itself but would launch a new application and hide itself.
Steps I followed:

The main launcher application will run in Kiosk mode i.e always on top/no option to close by capturing the close event/No instance shown in taskbar/no title bar/killing the explorer.exe/hiding the taskbar.
The launcher populates a horizontal listbox (data templated for UI) which lets occupied main center area of screen and can be scrolled either ways.
When user selected an item on listbox, click/tap event a separate process is launched with launcher window's visibility set to hidden and a small button(basically a window with just a button inside and size set to height/width of button) created on the either corner of the screen with always on top option.
The functionality of button is to minimize the current working application and set visibility of launcher back to visible and setting the focus to this window.
Since the process is launched by launcher, i trap the close event for the launched window to know user ended the application and then again pop up the launcher back.


In the output of ps(1) on OS X-like systems, what do processes listed in parentheses mean, and how do I kill them?

Question: username@yosemite ~ % ps wwwaux | grep java
username        48111   0.0  0.0        0      0   ??  ?E   11:54AM   0:00.00 (java)
username        91673   0.0  0.0  2432772    508 s006  R+    3:19PM   0:00.00 grep java
username        90809   0.0  0.0        0      0   ??  ?E   12:47PM   0:00.00 (java)

Every so often I will get a JVM hung like this. What do the (java) process listings mean? How do I kill them? kill -9 48111 does nothing, and AFAICT the listings stay there until I reboot.
Answer: When in doubt refer to the man page :)
$ man ps
/parenth

When printing using the command keyword, a process that has exited and
has a parent that has not yet waited for the process (in other words,
a zombie) is listed as ``<defunct>'', and a process which is blocked
while trying to exit is listed as ``<exiting>''.  If the arguments
cannot be located (usually because it has not been set, as is the case
of system processes and/or kernel threads) the command name is printed
within square brackets.  The process can change the arguments shown
with setproctitle(3).  Otherwise, ps makes an educated guess as to the
file name and arguments given when the process was created by
examining memory or the swap area.  The method is inherently somewhat
unreliable and in any event a process is entitled to destroy this
information.  The ucomm (accounting) keyword can, however, be depended
on. If the arguments are unavailable or do not agree with the ucomm
keyword, the value for the ucomm keyword is appended to the arguments
in parentheses.

Additionally:
KEYWORDS
  The following is a complete list of the available keywords and their meanings.
  Several of them have aliases (keywords which are synonyms).
  ...
  ucomm      name to be used for accounting

It would appear those are zombie processes, and instead of just returning <defunct> as the process name it's returning what was stored in some kind of accounting record.
As for killing these processes, rebooting may be the best option.  Since they lost their original PPID and become children of PPID 1 (launchd).  You can try sending a HUP signal to launchd, but don't try to send a SIGKILL or SIGTERM signal to it, or you'll crash your system.
You can verify the PPID of the zombie processes using ps -ef.
Note: having a few zombie processes shouldn't hurt anything.  The process isn't actually running anymore, it has been terminated and isn't using any system resources, other than an entry in the process table.
Comment: Yeah, the problem is these processes are holding onto some ports, (or at least Eclipse thinks so), so I can't restart my Tomcat instances without either changing the ports or rebooting, either of which are a pain when trying to develop.
Comment: That's strange.  Can you verify if the ports are actually in use, for example: `sudo lsof -P -n -i:###`.  Replace `###` with the port number.
Comment: They are not actually in use, per `lsof` as you mentioned. The only trace on the system that I can find of them is the "zombie-like" processes. This may be YASEE (Yet Another Stupid Eclipse Error) but not being able to remove those entries from the process table without a reboot smells deeper than that.
Comment: I wonder if eclipse keeps track of the PIDs, or if there's some kind of temporary PID file it's referring to that gets cleaned up on reboot.  I imagine you've tried restarting eclipse?  You can try sending HUP to PID 1 to see if it gets rid of those processes, just make sure you've saved all of your work before continuing.
Comment: For the record this is what Eclipse claims is the issue - `Several ports (52358, 62327) required by Tomcat v7.0 Server at localhost (sshd) are already in use. The server may already be running in another process, or a system process may be using the port. To start this server you will need to stop the other process or change the port number(s).`
Comment: that's a good point - I'll dig through the server config directory. Still irritating that there's apparently no way of excising those processes from the process table on OS X.
Comment: launchd will try to clear them up, but there's something preventing it from doing that.  Did you try the HUP?