How to set HttpPost endpoint from jquery, in asp.net application

Question: I am trying to get an Fine Uploader jQuery example to work. Basically it is just a way to upload files from client page to the webserver.
There is an example on how to set up the file stream on the server side on the project's GitHub page.
How do I from script call this HttpPost endpoint? The simple jQuery example looks like this:
$(document).ready(function () {
      $('#jquery-wrapped-fine-uploader').fineUploader({
        request: {
          endpoint: 'WhatToWriteHere??'
        },
        debug: true
      });
    });

So what do you type in the endpoint? I suppose it would be something like Namespace.Namespace.ClassName.UploadMethod(), but I've been fiddling along time with it, but cant get it to work. When debugging with Firebug, I get the following error(s):
405 Method Not Allowed
[FineUploader] xhr - server response received for 0
The HTTP verb POST used to access path '/FineUploaderTest/Uploadfolder' is not allowed.

Any idea?
Answer: You could write a generic HttpHandler to handle the file upload:
public class UploadHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        var request = context.Request;
        var formUpload = request.Files.Count > 0;

        var xFileName = request.Headers["X-File-Name"];
        var qqFile = request["qqfile"];
        var formFilename = formUpload ? request.Files[0].FileName : null;

        var filename = xFileName ?? qqFile ?? formFilename;
        var inputStream = formUpload ? request.Files[0].InputStream : request.InputStream;

        var filePath = Path.Combine(context.Server.MapPath("~/App_Data"), filename);
        using (var fileStream = File.OpenWrite(filePath))
        {
            inputStream.CopyTo(fileStream);
        }

        context.Response.ContentType = "application/json";
        context.Response.Write("{\"success\":true}");
    }

    public bool IsReusable
    {
        get { return true; }
    }
}

and then:
$(document).ready(function () {
    $('#jquery-wrapped-fine-uploader').fineUploader({
        request: {
            endpoint: '/uploadhandler.ashx'
        },
        debug: true
    });
});

Comment: Make sure that the name of the handler is correct. Also if you have a virtual directory name in the url make sure you have specified it. You could use the `ResolveUrl` method to set the path to the handler in a correct way: `endpoint: '<%= ResolveUrl("~/uploadhandler.ashx") %>'`.
Comment: Thanks alot for your help.
Ive tried to add the generic handler you suggested, and changed the endpoint to the handlers file name, but it still doesent work.

When i debug with Firebug, I now get the error:
[FineUploader] Processing 1 files or inputs...
[FineUploader] Sending upload request for 0
[FineUploader] xhr - server response received for 0
HTTP Error 404 - Not Found.

So it seems it cannot find the handler..


Angular unit test click method isn't appearing to be clicked

Question: This seems like it should be simple, but I'm having trouble verifying that a click handler is invoked on my component.
header.component.ts
import { Component, EventEmitter, OnInit, Output } from '@angular/core';

@Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
    @Output() hamburgerToggle = new EventEmitter<void>();

    constructor() {}

    ngOnInit(): void {}

    hamburgerClicked(): void {
        this.hamburgerToggle.emit();
    }
}

header.component.html

        <button (click)="hamburgerClicked()" class="btn btn-link btn-sm order-first order-first header-toggle" id="sidebarToggle" href="/">
            menu
        </button>

header.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { HeaderComponent } from './header.component';

describe('HeaderComponent', () => {
    let component: HeaderComponent;
    let fixture: ComponentFixture<HeaderComponent>;

    beforeEach(async () => {
        await TestBed.configureTestingModule({
            declarations: [HeaderComponent]
        }).compileComponents();
    });

    beforeEach(() => {
        fixture = TestBed.createComponent(HeaderComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('clicking the toggle button invoke our click handler', () => {
        const fixture = TestBed.createComponent(HeaderComponent);

        const clickSpy = spyOn(component, 'hamburgerClicked');
        const toggleButton = fixture.debugElement.query(By.css('#sidebarToggle'));
        toggleButton.triggerEventHandler('click', toggleButton);

        fixture.detectChanges();

        expect(clickSpy).toHaveBeenCalledTimes(1);
    });
});

The error message given is:
Expected spy hamburgerClicked to have been called once. It was called 0 times.
I've also tried this inside an async block, but received the same result:
fit('clicking the toggle button invoke our click handler', fakeAsync(() => {
    const fixture = TestBed.createComponent(HeaderComponent);

    const clickSpy = spyOn(component, 'hamburgerClicked');
    const toggleButton = fixture.nativeElement.querySelector('#sidebarToggle');
    toggleButton.click();

    tick();
    fixture.detectChanges();

    fixture.whenStable().then(() => {
        expect(clickSpy).toHaveBeenCalledTimes(1);
    });
}));

I've been at this for hours and can't figure out what I'm missing.  Any help is much appreciated.
Answer: You create a new fixture(component instance) in each test case. But you spy the component which created in beforeEach. So, you are triggering the click event on each new component instance, they are not the same component.
You should add a spy, query DOM element, and trigger the click event on the same component instance.
Remove the below statement in each test case will work:
const fixture = TestBed.createComponent(HeaderComponent);

header.component.ts:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { HeaderComponent } from './header.component';

fdescribe('HeaderComponent', () => {
  let component: HeaderComponent;
  let fixture: ComponentFixture<HeaderComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [HeaderComponent],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(HeaderComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('clicking the toggle button invoke our click handler', () => {
    const clickSpy = spyOn(component, 'hamburgerClicked');
    const toggleButton = fixture.debugElement.query(By.css('#sidebarToggle'));
    toggleButton.triggerEventHandler('click', toggleButton);
    expect(clickSpy).toHaveBeenCalledTimes(1);
  });

  it('clicking the toggle button invoke our click handler', () => {
    const clickSpy = spyOn(component, 'hamburgerClicked');
    const toggleButton = fixture.nativeElement.querySelector('#sidebarToggle');
    toggleButton.click();
    expect(clickSpy).toHaveBeenCalledTimes(1);
  });
});

unit test result:
Chrome 80.0.3987.87 (Mac OS 10.13.6): Executed 2 of 17 (skipped 15) SUCCESS (0.1 secs / 0.045 secs)
TOTAL: 2 SUCCESS
✔ Browser application bundle generation complete.
✔ Browser application bundle generation complete.

Comment: This was exactly it.  Thanks so much!


Como criar webservice utilizando PHP e REST?

Question: tenho pesquisado bastante sobre webservices ultimamente e gostaria da ajuda de vocês para saber como eu posso construir um webservice utilizando REST e PHP.
Escolhi PHP porque estou mais familiarizado com a linguagem, e o REST porque durante as minhas pesquisas vi que era o padrão mais utilizado atualmente e mais simples de se fazer.
Antes de mais nada, já vi esse link sobre webservice que é bastante informativo por sinal: Duvidas no web service , mas que não sanou completamente minha dúvida. Minha dúvida na verdade é o que eu preciso fazer para meu projeto ser considerado um webservice?
Por exemplo, criei uma plataforma em PHP que faz as consultas no banco de dados e mostra esses dados na tela (em uma página php/html) para o usuário dependendo da requisição que ele faz. Isso é considerado um webservice? O que diferencia isso de um webservice e o que eu posso mudar nele para torná-lo um webservice? Como eu aplico o REST nisso?
Se possível, deixem tutoriais que ensinem como fazer ou trechos de código. Agradeço muito a colaboração de todos.
Answer: É uma pergunta antiga mas vale a pena responder. Vamos por partes:

Minha dúvida na verdade é o que eu preciso fazer para meu projeto ser
  considerado um webservice?

Geralmente você utiliza webservices quando você quer permitir interoperabilidade (basicamente comunicação) entre diferentes plataformas (por exemplo, windows, linux, ios) escritos em diferentes linguagens. É claro que para permitir isso deve haver um formato de mensagem entendido por ambos (comumente json ou xml).
Basicamente você cria uma aplicação (com alguma linguagem do lado servidor, por exemplo, php, asp, ruby, python, etc.) mas em vez de retornar conteudo em html, css, e javascript, você retorna o conteudo, digamos "bruto", sem nenhuma formatação. Por exemplo, você define uma url (http://www.meusite.com/listarUsuarios), em vez de retornar uma pagina html, cheio de tags e estilos css, são retornados apenas os dados dos usuarios em texto plano, comumente json ou xml. Em json poderia ser algo assim: [{nome: 'usuario 1', idade: 20}, {nome: 'usuario 2', idade: 30}]. Em vez de retornar algo como

.....
Então quando você está criando seu webservice você não estaria se preocupando com a apresentação (estilização), ou como isso vai ser apresentado para o usuario em um aplicativo. A aplicação cliente é que iria se preocupar em como os dados do webservice consumido seriam graficamente apresentados. É claro que o criador do webservice poderia muito bem criar uma aplicação cliente, em html e javascript, ou um app para android. (nativo ou hibrido).

Por exemplo, criei uma plataforma em PHP que faz as consultas no banco
  de dados e mostra esses dados na tela (em uma página php/html) para o
  usuário dependendo da requisição que ele faz. Isso é considerado um
  webservice?

Não. Pois entre outras coisas não há interoperabilidade (até é possivel com muito esforço). Se alguem quiser criar um aplicativo android nativo (escrito em java) para acessar essa url, e mostrar o conteudo, com elementos nativos do android (ListView, TextView, etc.) não seria tarefa facil receber um documento html (sem estrutura bem definida, ele teria que olhar) e procurar as informações relevantes (os dados retornados pela consulta sql no banco, sem nada de formatação html) no meio de varias tags html.
Você até poderia ter essa pagina que lista as informações em html, mas ela será uma aplicação consumindo o webservice que retorna apenas os dados tal qual foram retornados pela consulta sql.

Como eu aplico o REST nisso? Se possível, deixem tutoriais que ensinem
  como fazer ou trechos de código

No imasters há um bom tutorial mostrando como se constroi o webservice (aplicação do lado servidor).


Prop.test alternative

Question: I want to test if the proportion estimated by (600/100000) is less than 0.6.

With prop.test(600, 100000, p=.6, alt="greater", correct=FALSE), p-value = 1.
With prop.test(600, 100000, p=.6, alt="less", correct=FALSE), p-value < 2.2e-16.

So I suppose that to test the hypothesis of (600/100000) less than .6, I have to use "greater" as alternative. Right?
Answer: prop.test(600, 100000, p=.6, alternative = "less", correct=FALSE)

    1-sample proportions test without continuity correction

data:  600 out of 1e+05, null probability 0.6
X-squared = 147015, df = 1, p-value < 2.2e-16
alternative hypothesis: true p is less than 0.6
95 percent confidence interval:
 0.000000000 0.006415277
sample estimates:
    p
0.006

Comment: Also binom.test(600, 100000, p = 0.6, alternative="less")

Prop.test alternative


Can I use fixed effects regression with non-time-variant treatment?

Question: I have data on a number of units, some of which have received treatment and some of which haven't. Binary outcome data was collected for each unit at multiple times. The model is therefore
$$\text{logit}(y_{it}) = \beta_0T_i + \beta_1U_i$$
where $T_i$ is treatment and $U_i$ is the unit indicator (i.e., unit fixed effect). I would like to measure the contribution of treatment on my outcome outside of any unit-specific effects. The outcome $y_{it}$ varies within units but the treatment does not.
Can I still use fixed effects regression?
Comment: My answer should clear things up, but in short $T_i$ will be absorbed by the unit fixed effects.
Comment: When you say $U_i$ is a *unit* indicator, do you mean a series of dummies for all units, in which case this is representing the *unit* fixed effects?
Comment: Yes, that's what I mean.
Answer: Unfortunately, $T_i$ will be dropped.
According to your specification, $T_i$ is time-constant. Say you're observing individuals $i$ over time. In all periods $t$, any individual $i$ is either in the treatment group or they're not. Thus, there's no within-person time variation to exploit. The $i$-level fixed effect removes all time-invariant heterogeneity across $i$, which invariably includes a dummy variable denoting group membership.
Your equation is estimable so long as there's observations of each $i$ before and after some shock (i.e., treatment). In that case, you'd interact $T_i$ with a second term demarcating before versus after the event. But if there's no time $t$ where a shock hits some units and not others, then you cannot proceed with this approach.
In short, you'd have to drop the unit fixed effect to achieve something estimable, or at the very least exploit some timing impact where some treatment/stimulus varies across $i$ and $t$.


Stomping after a table tennis serve or follow through?

Question: I often see a lot of veterans stomp their feet after hitting the ball.
Why would one want to stomp after hitting the ball?
Is this purely a stylistic issue? Or does it improve ones follow-through?
You can see an example here.
Comment: @Kevin http://www.youtube.com/watch?v=uwz_-2DchRE&feature=related
Answer: Some players stomp during the serve to hide the sound of the racquet hitting the ball. The sound of the contact can often clue a receiver into the pace and spin of a serve.
Other players merely stomp as a natural motion as they try to impart spin onto the ball.
Comment: This is the correct answer IMO. By stomping people disguise the actual sound of  the actual moment the ball is served.
Comment: I agree in that it's to hide how (hard) you hit the ball to try to hide the pace and spin of the ball.
Answer: Although I can't verify this, it could be for balance purposes. I know that in tennis (related sport), when you come into net to hit a volley, good technique states that you should "stomp" with your (assuming a right-handed player) left foot for a forehand volley and stomp with your right foot for a backhand volley because it helps you mentally and physically hit your shot with a firm wrist and be on balance like you need to be.
Comment: This is not correct, it has to do with hiding the sound of the spin...
Answer: It is stylistic.
The fact that the people you refer to stomp after they hit the ball shows that it isn't improving anything. Also, research shows (I'll find it for you if I can) that your legs to not effect the way your arms move, so it won't help follow-through. It's all in your head :-)
Comment: My wife played table tennis extensively and once traveled to Europe with the US college team, I believe. She has told me that the stomp often serves to distract an opponent from reading the spin of your serve. Also I disagree that you legs do not affect your arms. Your legs and core are the platform for all upper body action. Look at the clean and jerk; It seems like your arms would lift the weight, but the momentum drive comes from the legs.
Comment: Please try to. i'd love to read thi research you speak of.


Chopin: marche funèbre bar 15 impossible place

Question: Chopin sonata #2 Opus 35:

Look at the left hand: Db from small octave and F from 1-st octave. Neither I, nor anybody of my acquaintances can stretch the hand so far.
My idea was to replace F 1-t octave to F small octave. But this is a hack of course. How do professionals play it? It can't be made for the people with huge hands only.
Comment: *Rachmaninoff has entered the chat.*
Comment: You'd be surprised how many people's hands span a 10th. For example, transcriptions by ear of Tom Brier's solo piano works consistently have 10ths in them.
Comment: @user4035 - The upper note is an F, so that span is still a 10th (a major 10th, to be precise).
Comment: @Dekkadeci I made a mistake: it's not D, but Db, so it's not 10th, but 11th. And even worse as it includes additional stretching from a black key to white. Sorry, forgot about the key signature. My hand stretches 10th.
Comment: Have you checked against other sources? Possibly it's a typo and should be an F in the bass
Comment: i can play it. dont forget, chopin wrote stuff which which was too big for his hands but ok for hands of his pupils.
Comment: "i can play it." - most people can't. Yesterday played this with my piano teacher, we used arpeggiato with an accent upon the last F note. Sounded quite well and fitted with the right hand chord.
Answer: This does not seem to be a typo, as evidenced by a clear D♭ in the bass on page 14 of the autograph manuscript:

On page 14 of Kullak's "instructive edition" found here, the editor suggests fingering the chord 5–3–1 and rolling the chord to get all three pitches:
Comment: This is the answer. Many romantic composer notate chords that most people cannot reach, and the answer is to either simplify or roll them.
Comment: Yes, roll it. It is sonorous and emphasizes the crescendo even more.
Answer: I won't talk about if it's transcribed correctly or not, because I don't know the piece...
However, the part you've mentioned is actually 'only' a 10th.
There are a lot of people who can reach a 10th in certain key signatures, me included:

This 10th for example is very easy for me to reach, in the key of C I could even get it up to an 11th:

If you can't reach a 10th, just roll the chord/notes from low to high. There are people with small hands who can't even reach an octave. They also just roll the chords. Of course in this situation the sustain pedal might be helpful to not lose the lower notes after you rolled them ;)
If done properly it still sounds good, just a bit different.
Comment: Sorry, it's not D, but Db. I fixed the question. I can reach 10 as you did between white keys, but not black Db - white F.
Comment: I concur with the roll
Answer: It is probably a typo. But if it isn't (which I doubt) then you might have to flick your wrist, basically rolling the chord (though its not marked and wouldn't make sense in the context of the song). Its a fun technique to practice, especially when you nail the notes, but difficult in the beginning. Check out Chopin - Etude Op. 10 No. 5, which has a lot of those. Liszt also has some huge rolled arpeggios in his La Campanella.
Comment: It's not a typo, it's in the autograph manuscript


If two linear functionals are such that the kernel of one is contained in the kernel of the other, then they are proportional

Question: Let $V$ be a vector space over $K$ and let $f,g \in V^*$ and satisfy $\ker f \subseteq \ker g$. Show there exist such $c \in K$ so that $c \cdot f =g$
How to approach this problem ?
Comment: See [this](http://math.stackexchange.com/questions/60460/ker-t-subset-ker-s-rightarrow-s-rt-when-s-and-t-are-linear-functionals) or  [this](http://math.stackexchange.com/questions/158173/linear-dependence-of-linear-functionals).
Answer: Here is an elementary proof, with your notations. If one among $f,g$ is $0$, then choose $\lambda = 0$. If $f\not = 0$ and $g\not = 0$, then you have in fact equality of the kernels as both are hyperplanes, note $H$ this hyperplane. Let $e\in H$, and $D$ the line generated by $e$, which is a supplementary subspace of $H$ in $V$ as $f$ and $g$ are non zero linear forms. Now look at $\varphi = f(e) g - g(e) f$. This $\varphi$ is equal to zero, as it is zero on $H$ and on $D$ (being zero on $e$.) Then $\lambda = \frac{g(e)}{f(e)}$ will do the job. (Note that $f(e)$ is non zero as $e\in H$.)
Remark 0. Caracterization of non zero linear forms on $V$. The following are equivalent, for a subspace $H$ of $V$ :

there is a non zero linear form $l$ on $V$ such that $H$ is $l$'s kernel
$H$ has a supplementary subspace in $V$ that is a line (meaning by that : that is of dimension $1$
the quotient $V/H$ is on dimension $1$
$H$ is maximal (for the inclusion) in the set of strict subspaces of $V$

More conceptual proof, as this has nothing to do with the dual $V^{*}$ of $V$, as it is quite general and it has to do with factorization. What you want to prove results from the following more general fact :
Let $E,F,G$ be three vector spaces over $k$, and $f : E\to F$ and $g : E \to G$ linear such that $\textrm{Ker}(f)$ contains $\textrm{Ker}(g)$. Then, there exist $h : G \to F$ linear such that $h\circ g = f$. (The inverse is trivial.)
Take $y\in\textrm{Im}(g)$ and write it $y = g(x)$ for a $x\in E$. Set $h_1 (y) = f(x)$. This is well defined, as if $x'$ is another element of $E$ such that $y=g(x')$, then $x-x'$ is in the kernel of $g$ which is included in the kernel of $f$ so that $f(x) = f(x')$. So we have defined a map $h_1 : \textrm{Im}(g)\to F$ such that $h_1 \circ g = f$ on $\textrm{Im}(g)$, and $h_1$ is linear by construction. (Same argument than the one used to check that it is well-defined.)
Now, take a subspace $H$ of $G$ such that $\textrm{Im}(g)\oplus H = G$, extend $h_1$ to $G = \textrm{Im}(g)\oplus H$ in a linear map equal to $h_1$ on $\textrm{Im}(g)$ and $0$ on $H$. We have obviously $h\circ g = f$. $\square$
Now, in your case, $h$ will be a linear map from $k$ to $k$, so that it is an homothety of ratio $\lambda$ for some $\lambda \in k$, and this $\lambda$ is the one you are looking for.
Remark 1. In this above construction, I switched notation, as kernel of my $g$ is included in the kernel of my $f$, whereas in your notation, it's the opposite. But that's not an issue. Note that the existence of $H$ is unsured by Zorn's lemma, which is not used in the elementary proof my answer is beginning with.
Remark 2. You have a version of this with images, namely : if $\varphi : A \to B$ and $\psi : C\to B$ are linear such that image of $\varphi$ is included in the image $\psi$, then there exists a linear $\delta : A \to C$ such that $\psi \circ \delta = \varphi$. Here also in general, you need Zorn's lemma.
Comment: In this case, there is no need in Zorn's lemma, since the quotient $V/\mathrm{ker} f$ is $1$-dimensional.
Comment: Yes, typo, not finished to edit
Comment: Ah ok sorry, I see, forgot "not".
Comment: Done. Corrected ;-)
Comment: I am curious to know why people downvote this. But, is it important to know why average people do this or that ?...


How to design the feature "unread message count" in a chat application with firebase

Question: To count the unread message, I created a count field and it works like this :

set count_unread = 0
If new_message : count_unread++

If user join chat room : set count_unread = 0
If user already in chat room, I have a listener to listen database change, then show the message in screen and set count_unread = 0

But, as you know, Firebase charge on every read/write command. So, if this user already in the chat room, every new message will create 2 writes ( set count_unread +1 and set count_unread=0 ). Is there any way to optimize it ?
Comment: See https://stackoverflow.com/questions/52126744/how-to-structure-nosql-messages-to-get-unreads-by-1-query/52129025#52129025, and other from here: https://stackoverflow.com/search?q=%5Bfirebase%5D+unread+message+count for some ideas. But the trade-off you're describing is pretty much the same for all of them.
Comment: Not sure the logic is clear and without understanding the code, any answers would be a guess. For me, if I'm in a chat room and messages are being added, the count_unread would be incrementing for ME only and if there are multiple users, the number of uread messages would be different for each so they would each have their own counter. Then, as I read the message, MY count_unread would decrement. So I dont see where you would have two writes.
Answer: Yes, you can optimize your Firebase Realtime Database usage by reducing the number of read and write operations that you perform. Here are a few suggestions:
<code>Use Firebase Cloud Functions to update the unread message count for each user when new messages are added to a chat room. This way, you can avoid having to perform multiple read and write operations for each user in real-time. Instead, you can use Cloud Functions to calculate the unread message count based on the existing messages in the chat room, and update the count for each user only when new messages are added or deleted. This approach can help reduce the number of read and write operations you need to perform on the database, and improve the overall performance of your app.

Use Firebase's built-in transaction support to update the unread message count atomically. When you need to increment the unread message count, you can use a transaction to ensure that the count is incremented atomically, without any race conditions or conflicts with other clients. This approach can help reduce the number of write operations you need to perform on the database, and ensure that the unread message count is always accurate.

Consider using Firebase's Firestore database instead of the Realtime Database. Firestore has built-in support for server-side increment operations, which can help reduce the number of read and write operations you need to perform on the database. You can use Firestore's FieldValue.increment() method to atomically increment the unread message count without having to read the existing value first. This can be a more efficient approach if you have a large number of users and chat rooms, and need to update the unread message count frequently.
</code>
I hope these suggestions help you optimize your Firebase usage and reduce the number of read and write operations you need to perform on the database.


Wireguard VPN connection not resolving local host names

Question: I have setup a Wireguard VPN on my raspberry pi and I can connect to it via client app on my mobile phone. I can access the internet though the phone and I confirm that the phone is using the same IP of the raspberry pi, so the VPN is working for the outer internet.
But I have a local webserver on my Pi, which I can access on the pi using a direct internal IP (192.168.1.50), using raspberrypi.local hostname, or by using a custom host defined in /etc/hosts file.
However, in the phone and over VPN I can only access that local webserver over the internal IP: raspberrypi.local or any other hostname defined in /etc/hosts does not work.
How can I resolve this?
Answer: I've indirectly solved this issue by installing Pi-Hole, setting up local hosts there and enabling it as the DNS server for all my clients. Now I can access my home network via VPN with local hostname resolution + added benefit of DNS level ad blocking.
Pi-Hole and Wireguard VPN play very nice with each other (Pi-Hole detected Wireguard and offered to do all configurations by itself).
Answer: I have a hostname that I can resolve as "hostname.local" while I am connected directly to my LAN.
When I am connected via wireguard, I can only reach the hostname by appending a period (or dot) after the hostname: i.e. "hostname."
While connected through wireguard:
ping hostname.local    (doesn't work)
ping hostname.         (works)

Answer: On my home network, my Vodafone router handles resolving the .local (and .broadband) hostnames, which works at home because my devices use the router as their DNS server.
So, to get this working on my Wireguard client, I just had to manually set the DNS server to my router's IP address in Wireguard settings (DNS servers on Android)
Screenshot of the Wireguard interface settings on Android
Pinging my Raspberry Pi (with hostname rpi) worked when using rpi, rpi. and rpi.broadband. While rpi.local didn't work when connected from my phone, the .local TLD often doesn't resolve properly on Android anyway, so this was expected.


How to create a local IIS site with encrypted wwwroot using EFS on Vista

Question: I'm preparing a laptop to take with me while travelling, so all my user data is encrypted using EFS in case someone decides to steal it. I also need to set up a couple of local sites for development with IIS. If I turn off encryption on the wwwroot of a site, IIS can serve it just fine. However, I really would like to be able to use encryption here as well.
I've tried these steps: http://support.microsoft.com/kb/243756
When I try to view the local site in IE, I get a login dialog as expected, but it doesn't accept my credentials, although this is the account I use to encrypt the served files. Has anyone tried this and got it to work?
Answer: Cross posted from SO:
EFS and IIS really don't play nicely together.  The IIS services (typically) runs under "Network Service" which doesn't have access to your user account's EFS decryption key.
You have two options with IIS:

Run "IIS Admin Service" and "World Wide Web Publishing Service" as your personal account, along with running any web site's anonymous user as this account.
Flag the InetPub directory as Never Encrypt.

#1 is obviously the best bet for security/encryption purposes, but its going to be a challenge to set up the appropriate rights for your account to run these services.
You might want to consider just using Visual Studio's built in web server (Cassini) which gets aroung the encryption problem since it runs as your personal account, but it does have some of its own issues.


How to add drives to HPE raid and convert to raid 5

Question: This is similar to this question:
HP G8 migrate RAID0 to RAID1 with CLI commands
But different enough that I think it is worth asking as a new question.
I have a Gen 10 HPE server with the P408i-a RAID controller.
Currently it just has a single disk, which it is treating as a 1 disk RAID0 array.
I want to add two more disks to it, and convert the result to a RAID5 array.
From ssacli, I can see "add" and "modify" options, but it isn't that clear how to combine this to do what I want.
In particular, under the help for the "add" command, it says "adding physical drives is the same as expanding an array", which to me implies that as soon as I run the "add", it will start a conversion to a 3 disk RAID0, which isn't what I want.
If I add the new drives as spares, and then run the modify command, will that work (i.e. will it work out it needs to absorb the spares to do the conversion)?
Comment: to be honestly, i would make a backup of the server or by an additionally of one ore two disk and create it from scratch
Answer: As the server was running VMware ESXi, backing up and restoring would have been very time consuming. What I ended up doing, which worked for me, was the following three HPE commands (after inserting the new drives), with many hours of waiting in between as it completed the operation.
<code>/opt/smartstorageadmin/ssacli/bin/ssacli ctrl slot=0 ld 1 add drives=allunassigned forced
</code>
(wait for several hours as RAID0 array reshapes)
<code>/opt/smartstorageadmin/ssacli/bin/ssacli ctrl slot=0 ld 1 modify raid=5
</code>
(wait for several hours as RAID0 array changes to RAID5)
<code>/opt/smartstorageadmin/ssacli/bin/ssacli ctrl slot=0 ld 1 modify size=max forced
</code>
Because "give the usable space to the visible drive" is a separate stage from "reshape the RAID array", the OS didn't see the intermediate state where the array appeared as a 3 disk RAID0 array.
I then followed the process at this link to get the VMware layer to see the additional space, which worked without needing any reboots:
https://michlstechblog.info/blog/esxi-expand-datastore-from-command-line/
Comment: you can accept your own answer if its solved
Answer: Was unable to add to, but following Michael's steps worked for me as well.
Allowed me to go from a 600GB x2 in RAID 0 to a 600GB, 600GB, 2TB SSD's in RAID 5.
(Yes I know I'm not getting the full capacity)
Comment: Friends don't let friends use R5 - it's dangerous dude, nobody's used it for a decade, please use R1/10 or R6/60 - you should see how many people come here all the time because R5 has killed their data.
Comment: @Chopper3 luckily this is my homelab infra, and all important stuff is backed up to internet, and also replicated to my other server at my parents with RAID 5 :D
Comment: Please don't add "thank you" as an answer. Once you have sufficient [reputation](https://serverfault.com/help/whats-reputation), you will be able to [vote up questions and answers](https://serverfault.com/help/privileges/vote-up) that you found helpful. - [From Review](/review/late-answers/512453)


Means Adjusted Continuous Variable

Question: I am trying to replicate a study that uses "means adjusted unemployment rates" as an explanatory variable in a regression analysis. What exactly does this mean? I want my explanatory variable to remain continuous whereas everything I am finding describes an "adjusted mean" as in a singular calculation and usually in reference to descriptive statistics.
Any information is much appreciated.
Comment: Hi, welcome to Cross Validated! Could you provide a quote or example reference where this term is used?
Comment: All it says is "UR is means adjusted rate of unemployment in year t and state s."

I'm wondering how you means adjusted the continuous variable UR?
Comment: Where does it say this? Can you give us the reference?
Answer: "Means adjusted unemployment rate" is going to be a number just like "unemployment rate". It is adjusted by something, probably related to income (if the source does not provide details, that's a bad sign). There will be a MAUR for each time t and state s, just as there is a UR for each time and state.

Means Adjusted Continuous Variable


Implications of trying multiple tests for an analysis

Question: Let's say I have a fixed set of data containing one variable. I'm interested in whether the variable shows a difference between two conditions. Now I perform a test and determine a p-value somewhere above my desired alpha. Being disappointed, I iterate over multiple different alternatives of tests for the same hypothesis and find that one test gives a p-value below my alpha.
This seems to be some kind of "fishing expedition", but not of the kind that a Bonferroni correction is supposed to fix: I'm always testing the same hypothesis. Still, somehow my gut feeling tells me this is fishy. What is generally considered appropriate here? Do the fishing and report it in the paper? Go with the first p-value? Calculate the mean p?
Comment: You are right that this is widely regarded as dubious, but how dubious? You would not fault yourself for trying different hammers or screwdrivers before deciding on the best for a job. How far is this similar?  On the strictest interpretation, one should specify the tests to used in advance and use only those tests. That's admirably puritan, but I'd guess it's minority practice.  In what I read, I often think about a test that has been used as just another kind of exploratory data analysis, especially when I would tend to favour a different test or no test or all (e.g. a graphical approach).
Answer: Often these different tests test subtly different hypotheses. For example, many tests that are used to check for normality/Gaussianity of a distribution actually look at very specific deviations from normality (e.g. no skewness) and tests differ with respect to what quantity they exactly look at. So I would start with finding out what the difference is between these tests and decide which hypothesis is the one that is really of interest to you.
If the different tests really test the same null hypothesis and result in different $p$-values, that it is an issue of power. Typically, there is a literature comparing these tests, and you can just look up which test best applies to your situation.
Having said that, my first guess would be that your different tests actually test similar but not the same hypotheses. In general, once you understand where the differences between tests come from, the choice becomes pretty obvious.
Comment: Re 2nd paragraph: two different tests can be of the same null hypothesis but have different power against different alternatives. Even if you're not a Puritan, you can't allow yourself too much latitude in choosing/devising a test against an alternative suggested by looking at the data. So I think that's wrong.
Answer: There's no need to assume that different null hypotheses are being tested to use the Bonferroni correction. (See Cox & Hinkley (1974), Theoretical Statistics, 3.4 (iii) for a derivation & discussion of its application to multiple tests of the same null hypothesis—your question involves optional stopping rather than choosing the lowest p-value for a fixed no. tests, but I'm assuming that wasn't the important point.) If you really were going to keep on performing arbitrary tests until you get a p-value you like, a multiple-testing correction would seem more relevant than it usually does. Bear in mind that any sample is extreme in some respect, so you can always find a test that will reject the null hypothesis at an $\alpha$ of your choosing. In practice using a test statistic that's obviously post hoc or outré will excite suspicion (see Witztum et al. (1994), Equidistant Letter Sequences in the Book of Genesis, Statistical Science, 9, 3).
As to what to report: there is a distinction between exploratory & confirmatory analyses. Real analyses often have elements of both. Best to simply tell the truth about what you did, & let your readers decide for themselves whether they're bothered or not by multiple testing.
Comment: Here is the same answer, with slightly different background:
http://stats.stackexchange.com/a/63416/6961


Remote Video Editing Server

Question: Okay, so here is the dilemma
We have three people, two in California, one in Australia. The person in Australia has several server machines that we all need to use. we are recording gaming videos, and we need to get all of the footage all in one place, and the editor, me, does not have the greatest disk space. In addition to that, our guy in Australia needs to edit as well, and sending 100GB of data from two people to Australia, and then from two people to me is massively inefficient and slow and a disgusting idea.
What would be the best way of setting this up? the most obvious choice is just setting up a remote desktop server that we can all access, and having an FTP server running on it. But would that be the BEST way? is there a better way for us to connect to this server and use only one program? with the lowest latency possible? Also, if the program at all matters, I would prefer Adobe Premier but Sony Vegas would also work, but if we could get a good way of setting this up with any other program i would be willing to learn.
I apologize for this being such a specific question, but if any community could get me a better solution to this than remote desktop, it would be this community.
Answer: If you're running a Microsoft server at your remote location I would look into setting up RemoteFX.
I have not used it myself but the idea is that you can utilize the remote server's graphics card during remote sessions. This would allow you to use whatever video editing software you wish and keep the data on the remote machine to be stored and edited in one location.
It requires a bit of setup but this is the only solution I have come across at this time.
UPDATE: (Not enough rep yet to comment.)
Adobe Premiere would need to be installed on the server running RemoteFX.
RemoteFX simply allows the use of the host's video hardware so programs will run normally as if they were on your desktop at home except you're using the remote systems video hardware. Once remotely logged into the server you could run Adobe Premiere like you would on your desktop computer.
Cheers.
Comment: Could we get some information about how to set up adobe premier with using this? I really have no idea. I'm new to remote desktop entirely, and my friend is new to RemoteFX. What would i need to do to specifically make it work with Adobe Premiere
Answer: I'd set up a NAS system at each location.  Set up replication between them, and after the initial 100GB synchronisation, you're only copying deltas (y'know, the difference between files).
The problem (or rather, the expense) is that you'll want to have reasonably fast storage at each node, so probably SAS disks, with an optional SSD Tier 1 caching layer.
For that kind of performance, I recommend you take your business case to a major storage vendor, ideally one who already has experience in the graphics/video/motion field.
I'd recommend Hitachi Data Storage, or SGI.  They'll be able to figure out a storage solution that will be a good fit for you, and better than something you've hacked together out of coconuts and string.
-- Source? I worked in VFX and know lots about storage.
Comment: I think this idea would be the most professional, but i feel that it is beyond what we need. the whole point is that A) I cant get new hardware, Ive been trying to upgrade my now 6 year old computer for 2 years. However it still runs decent. and B) we really just want to use what we have available. i believe Devin's answer will work, but i have to take a look.

Remote Video Editing Server


Not Getting Alarm on Boot Completed

Question: In my code i added all the permissions for Boot Completed  on Android manifest file..I logged My broadcast receiver,after reboot the control is going in to broadcast receiver But the alarm is not firing up.Actualy i want is a activity is launched after triggering alarm..In normal case(Before Shut down) i am getting the alarm and launched the activity..after reboot it is not happening...
this is my Boadcast receiver
public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Log.d("hai", "inside onreceive");
    try {
        if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {

                    Calendar cal = new GregorianCalendar();
                    cal.setTimeInMillis(System.currentTimeMillis());

                    cal.set(Calendar.HOUR_OF_DAY,9);
                    cal.set(Calendar.MINUTE,49);
                    cal.set(Calendar.SECOND, 0);
                    cal.set(Calendar.MILLISECOND, 0);

                    Intent intent1 = new Intent(context,
                            AlarmLauncher.class);
                    intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent1.putExtra("alarm_message", "feathersoft Rules!");
                    // In reality, you would want to have a static variable
                    // for the request code instead of 192837
                    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent1,PendingIntent.FLAG_CANCEL_CURRENT);
                    Log.d("hai",
                            "alarm set");

                    // Get the AlarmManager service
                    AlarmManager am = (AlarmManager) context
                            .getSystemService(context.ALARM_SERVICE);
                    // am.set(AlarmManager.RTC_WAKEUP,
                    // cal.getTimeInMillis(), sender);
                    am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                            sender);
                    Log.d("hai",
                            "Alarm Alert:Inside the boot completed broadcast receiver......");

                Log.d("hai",
                        "Alarm Alert:Inside the boot completed broadcast receiver......");
            }
        }

    }catch (Exception e) {
            Toast.makeText(
                    context,
                    "There was an error somewhere, but we still received an alarm",
                    Toast.LENGTH_SHORT).show();
            e.printStackTrace();

        }
    try {

    if(intent.getAction().equals(null))
        {

                SharedPreferences sp = context
                        .getSharedPreferences(
                                BigBirdConstants.nameOfPreference,
                                context.MODE_PRIVATE);
                String alrm = sp.getString(
                        BigBirdConstants.pref_myflight_alarm_time, "hello");
                Log.d("hai", alrm);
                Intent newIntent = new Intent(context, AlarmLauncher.class);
                newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                System.out.println("boot completed");
                // newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(newIntent);
            }
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

This is my alarm dumpsys after reboot
$ dumpsys alarm
 dumpsys alarm
  Current Alarm Manager state:

  Realtime wakeup (now=1334031884759):
 RTC_WAKEUP #2: Alarm{460a6c88 type 0 com.android.providers.calendar}
  type=0 when=1334110692157 repeatInterval=0 count=0
  operation=PendingIntent{45dea300: PendingIntentRecord{460a6c10 com.android.p
roviders.calendar broadcastIntent}}
RTC_WAKEUP #1: Alarm{460eb1d0 type 0 com.google.android.gsf}
  type=0 when=1334073656706 repeatInterval=566387000 count=0
operation=PendingIntent{45d0d9c8: PendingIntentRecord{4606f3c0 com.google.an
droid.gsf broadcastIntent}}
  RTC_WAKEUP #0: Alarm{4610cd88 type 0 com.google.android.gsf}
    type=0 when=1334032080140 repeatInterval=1800000 count=0
    operation=PendingIntent{46057dc0: PendingIntentRecord{4610cd10 com.google.an
droid.gsf broadcastIntent}}
  RTC #1: Alarm{45ed7b10 type 1 android}
    type=1 when=1334082600000 repeatInterval=0 count=0
    operation=PendingIntent{45dd2c10: PendingIntentRecord{45e81c08 android broad
castIntent}}
  RTC #0: Alarm{461bf460 type 1 android}
    type=1 when=1334031900000 repeatInterval=0 count=0
    operation=PendingIntent{45cceb98: PendingIntentRecord{45f2b3e0 android broad
castIntent}}

  Elapsed realtime wakeup (now=527752):
  ELAPSED_WAKEUP #2: Alarm{46169c28 type 2 android}
    type=2 when=25881048 repeatInterval=0 count=0
    operation=PendingIntent{45d0c358: PendingIntentRecord{45cc99b0 android broad
castIntent}}
  ELAPSED_WAKEUP #1: Alarm{4610dc40 type 2 com.google.android.gsf}
    type=2 when=995077 repeatInterval=0 count=0
    operation=PendingIntent{460dd5c8: PendingIntentRecord{4610dbc8 com.google.an
droid.gsf broadcastIntent}}
  ELAPSED_WAKEUP #0: Alarm{46011b68 type 2 com.google.android.apps.maps}
    type=2 when=970384 repeatInterval=900000 count=0
    operation=PendingIntent{45f9f478: PendingIntentRecord{45fea1d0 com.google.an
droid.apps.maps startService}}
  ELAPSED #1: Alarm{460da648 type 3 android}
    type=3 when=2557073343 repeatInterval=0 count=0
    operation=PendingIntent{45f84d38: PendingIntentRecord{45e34428 android broad
castIntent}}
  ELAPSED #0: Alarm{4609a418 type 3 android}
    type=3 when=727667 repeatInterval=0 count=0
    operation=PendingIntent{45f7da98: PendingIntentRecord{45e39420 android broad
castIntent}}

  Broadcast ref count: 0

  Alarm Stats:
  com.bigbird.Activity
    20ms running, 1 wakeups
    1 alarms: flg=0x10000004 cmp=com.bigbird.Activity/.AlarmLauncher
  com.google.android.gsf
    47ms running, 1 wakeups
    1 alarms: act=com.google.android.intent.action.GTALK_RECONNECT flg=0x4
  android
    22819ms running, 3 wakeups
    1 alarms: act=com.android.internal.policy.impl.PhoneWindowManager.DELAYED_KE
YGUARD flg=0x4
    8 alarms: act=android.intent.action.TIME_TICK flg=0x40000004
    2 alarms: act=android.content.syncmanager.SYNC_ALARM flg=0x4
$

Answer: I got the problem
in the pending intent i am used the activity to be launched..thats the fault..in pending intent u should use your Broadcast receiver as intent...
if (sp.getBoolean(BigBirdConstants.pref_alarm_set, false)) {
                String alrm = sp.getString(
                        BigBirdConstants.pref_myflight_alarm_time, "hello");
                String alrmtime[] = new String[2];

                    alrmtime = alrm.split(":");

                    Calendar cal = new GregorianCalendar();
                    cal.setTimeInMillis(System.currentTimeMillis());
                    /*
                     * Integer.parseInt(alrmtime[
                     * 0])
                     */
                    /* Integer.parseInt(alrmtime[1]) */
                    cal.set(Calendar.HOUR_OF_DAY,11);
                    cal.set(Calendar.MINUTE,13);
                    cal.set(Calendar.SECOND, 0);
                    cal.set(Calendar.MILLISECOND, 0);

                    Intent intent1 = new Intent(context,
                            AlarmReceiver.class);
                    intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent1.putExtra("alarm_message", "feathersoft Rules!");
                    // In reality, you would want to have a static variable
                    // for the request code instead of 192837
                    PendingIntent sender = PendingIntent.getBroadcast(context, 192837, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
                    Log.d("hai",
                            "alarm set");

Not Getting Alarm on Boot Completed


How to get most similar words to a document in gensim doc2vec?

Question: I have built a gensim Doc2vec model. Let's call it doc2vec. Now I want to find the most relevant words to a given document according to my doc2vec model.
For example, I have a document about "java" with the tag "doc_about_java". When I ask for similar documents, I get documents about other programming languages and topics related to java. So my document model works well.
Now I want to find the most relevant words to "doc_about_java".
I follow the solution from the closed question How to find most similar terms/words of a document in doc2vec? and it gives me seemingly random words, the word "java" is not even among the first 100 similar words:
docvec = doc2vec.docvecs['doc_about_java']
print doc2vec.most_similar(positive=[docvec], topn=100)

I also tried like this:
print doc2vec.wv.similar_by_vector(doc2vec["doc_about_java"])

but it didn't change anything. How can I find the most similar words to a given document?
Answer: Not all Doc2Vec modes even train word-vectors. In particular, the PV-DBOW mode dm=0, which often works very well for doc-vector comparisons, leaves word-vectors at randomly-assigned (and unused) positions.
So that may explain why the results of your initial attempt to get a list-of-related-words seem random.
To get word-vectors, you'd need to use PV-DM mode (dm=1), or add optional concurrent word-vector training to PV-DBOW (dm=0, dbow_words=1).
(If this isn't the issue, there maybe other problems in your training setup, so you should show more detail about your data source, size, and code.)
(Separately, your alternate attempt code-line, by using doc2vec["doc_about_java"] is retrieving a word-vector for "doc_about_java" (which may not be present at all). To get the doc-vector, use doc2vec.docvecs["doc_about_java"], as in your first code block.)
Comment: Thank you! This is how I train: doc2vec = Doc2Vec(documents = tagged_documents, vector_size = dimensionality, window = 8, min_count = 5, workers = 4, epochs = epochs). According to https://radimrehurek.com/gensim/models/doc2vec.html dm=1 is the default parameter so I assume that the training is in PV-DM mode. Should I specify dm=1 explicitely?
Comment: Also I guess that word vectors have been trained, because print doc2vec.wv.most_similar("java", topn=10) gives me [(u'java/j2ee', 0.4498763680458069), (u'java.', 0.40088707208633423), (u'java/', 0.37919291853904724), (u'java/java', 0.3360544443130493), (u'jpa/hibernate', 0.3188815116882324), (u'java/jee', 0.31387391686439514), (u'jsps', 0.30111759901046753), (u'andgenuinely', 0.2981807589530945), (u'sti-f-06', 0.2916569113731384), (u'-jpa', 0.2886544466018677)]
Comment: Yes, since `dm=1` is default, you don't need to specify it, & you should be getting both doc- and word- vectors. And, your check of most-similar for word `'java'` confirms word-training happens. Are you sure your probe `'doc_about_java'` is a good example of a doc about java? Are results for `doc2vec.wv.similar_by_vector(doc2vec.docvecs['doc_about_java']` totally-unrelated? Are you using a small/thin dataset or very few training passes? Are you sure as much training as you expect is happening – especially that `tagged_documents` works as a restartable iterable & logs show expected progress?
Comment: The results for words similar to the docuement are totally unrelated: they look like noise of some very rare tokens, completely unrelated to java. The document about java is very representative. The dataset is quite big. When I train the process consumes almost 64G of RAM. You gave me some hints. I will increase the number of training passes and will check logs (if I find them :-)
Comment: I'd also double-check that the `most_similar()` doc-vec results are as strong as you think, and some other representative docs, to see if it's a general problem or just within some idiosyncratic docs.


dont cancle interstitial AD with backbutton

Question: is it possible to make a interstitial (ad from admob) not Cancelable with the back button?
I only want that the user can cancle the ad just with the cross.
Thanks :)
Answer: Once the interstitial is shown it is out of your hands. The Activity that shows the interstitial controls whether the back button event will be consumed or not.


Cannot access $node on Computed field

Question: I'm using computed field for my content types, but when I used $node, in Display Code, it doesn't display anything :
global $node;
$display_output = l("Apply", "apply_form?job_offer=".$node->nid);

Comment: What version of the module do you have?
Answer: First of all, you are supposed to write to $entity_field[0]['value']. Second problem is that fields operate on entities, not nodes, so you need to use $entity instead. You can always use Devel module and dpr($entity) to see what's in it.
node id should be in the entity field if it is a node. In which case you can load it with node_load().
Comment: node id should be in the entity field if it is a node. In which case you can load it with `node_load();`
Comment: Thank you, some example here : https://drupal.org/node/149232
Comment: @Bibix glad you found it :) hope it works for you now.

Cannot access $node on Computed field


Need to Loop thru a firebaseArray and returning 1 object

Question: I am trying to access data returned in a firebase array and return 1 of these objects - my firebase array is returning 3 objects and I want to be able to loop through these 3 objects and compare data. Really not sure what to do:
its the function getNewsDetail is the problem.
angular.module('news.services', ['ionic', 'firebase' ])
.factory('NewsItems', ['$firebaseArray', function($firebaseArray){
  var newsRef = new Firebase ('https://xxxx.firebaseio.com/newsitems');

    var theNewsItems = [$firebaseArray(newsRef)];
    //alert($firebaseArray(newsRef).length)
    return{
    getNewsItems: function(){
        return $firebaseArray(newsRef);
    },
    getNewsDetail: function(newsID){
        for(var i = 0; i < theNewsItems.length; i++){
            if(theNewsItems[i].id == parseInt(newsID)){
                return theNewsItems[i];
            }
        }
        return null;
    }
    };

}]);

Including Firebase layout:
      newsitems
          -KIip4vmlntvakLoBAXA
                 Detail: "Detail Y"
                 Title: "Title X"
                 id: 0
          -KIipATckNU1WzEhkY9-
                Detail: "Come down and play with us"
                Title: "New Players Welcome"
                id: 1
          -KIipHiM2NYlh_BgG8UM
               Detail: "story 3"
               Title: "title 3"
               id: 2

Answer: When you want to use a single object from Firebase in an AngularJS view, you use $firebaseObject. So:
getNewsItems: function(){
    return $firebaseArray(newsRef);
},
getNewsDetail: function(newsID){
    return $firebaseObject(newsRef.child(newsID);
}

Firebase is intelligent enough in its loading of the data that it won't reload it, if it already has it in memory.
Comment: Thanks Frank I think is close to what I want but not exact - I've added my firebase layout so it probably makes more sense. E.G. if I pass in an id of 2 I would expect the last newsItem on the list to be returned.


SNMP implementation

Question: Have to work on the snmp implementation to check the status of the different parameters of a device. Am new to this and kinda confused with the steps. How do I function with the mib's and is there any need of xml parsing?
Comment: You might start from an existing SNMP library of the programming language you use. That should make you able to write a real question.
Answer: Generally there is no need for XML parsing. The steps depend on whether you are writing an SNMP agent or an SNMP manager and what SNMP framework you are using, assuming you're not writing everything from scratch.
Assuming you are working on the agent, the steps are usually these:

If you are creating a new MIB, you need to create the text file that defines the objects in the MIB, see http://net-snmp.sourceforge.net/wiki/index.php/Writing_your_own_MIBs as a starting point
Once you have a MIB (either one that you wrote in step 1, or an existing MIB you downloaded), you use a MIB compiler to generate code from that MIB
The generated code will typically contain stub functions that you need to fill in for getting and setting MIB object values

See http://www.net-snmp.org/wiki/index.php/Tutorials for information on how to implement a MIB for the net-snmp agent code base.
Comment: Would be good to know whether you're implementing things on the manager or agent side, what framework and language you're using

SNMP implementation


Problems with the english language in a logical statement (plural implies distinctness)

Question: I don't want to make this to general because I think I would make a mistake then but I think one can generalize this idea for every uniqueness/injectivity proof:
The claim is:
$V$ vector space over $F\wedge B$ basis of $V$ $\Rightarrow\forall v\in V\exists !(B_v,c):B_v\subseteq B\wedge B_v \text{ finite }  \wedge c:B_v\rightarrow F\backslash\{0\}\wedge v=\sum_{b\in B_v}c(b)b$
My first question is what is the actual logical definition of $\exists!$ ?
To prove the uniqueness I think we have to show the implication
$\exists(B_v,c),(\bar{B_v},\bar{c}):B_v\subseteq B\wedge B_v \text{ finite }  \wedge c:B_v\rightarrow F\backslash\{0\}\wedge \bar{B_v}\subseteq B\wedge \bar{B}_v \text{ finite }  \wedge \bar{c}:\bar{B_v}\rightarrow F\backslash\{0\}\wedge \big((B_v,c)=(\bar{B_v},\bar{c})\vee (B_v,c)\neq(\bar{B_v},\bar{c})\big)\wedge v=\sum_{b\in B_v}c(b)b=\sum_{b\in \bar{B}_v}\bar{c}(b)b\Rightarrow (B_v,c)=(\bar{B_v},\bar{c})$
But I don't know how we would transcribe this statement to English because in my head I think about:
If we have two pairs that are in the solutionset (i.e that fulfill desired qualities) and the pairs might be different or equal then the pairs are equal
The problem I have here is that if I say two pairs then I automatically think about two different pairs. So how can we reformulate the statement, i.e. what are we proving here in English? How can I express it?
Comment: $\exists !$ means "There is exactly one"
Comment: No I mean the logical definition of $\exists!$ only using $\forall,\exists,\wedge,\vee$ and statementvariables
Comment: Ah!  OK, I showed some ways to do that in my Answer
Comment: What you are "thinking in your head" is exactly the way to think about it, and write it. A mathematician reading "two pairs" would  are _not_ automatically think they are different. English is _much_ better than formal logic for this kind of argument.
Answer: $\exists !$ means "There is exactly one", so that expresses uniqueness right there.
Without using $\exists !$, you can use several strategies:
First, we can express that there is one .. and no other one. So, you would get something like:
$\exists c (bla \ bla \ bla (c) \land \neg \exists c' (c' \not = c \land bla \ bla \ bla(c')))$
We can also say that there is one with the property, and everything that has the property must equal that first one:
$\exists c (bla \ bla \ bla (c) \land \forall c' ( bla \ bla \ bla(c') \to c'  = c))$
Finally, we can use this structure:
$\exists c \forall c' (bla \ bla \ bla (c') \leftrightarrow c'  = c))$
See how this last one works?  When $c'  =c$, the right side holds true, and hence we must have $bla \ bla \ bla (c')$, and since $c'=c$ we thus have $bla \ bla \ bla (c)$. And for any $c' \not = c$, the right side is false, and ehnce the left side should be false too, and hence we have $\neg bla \ bla \ bla (c')$ for any $c' \not = c$
Comment: Another common rendering of $\exists! x, \phi(x)$ is $(\exists x, \phi(x)) \wedge (\forall x \forall y, \phi(x) \wedge \phi(y) \rightarrow x = y)$.
Comment: It looks like that none of those templates fit to the proof that I did. I think what I did is more combinatoric, it does not really make sense what I wrote: $\exists c(\text{bla bla bla}(c))\wedge \exists c'(blablabla(c'))\Rightarrow c=c'$ or is this also equivalant to those definitions you have proposed?


Cloning a JS TreeModel tree

Question: I need to clone a tree I made using TreeModel.js.
What I exactly need to do is duplicating it, make changes to it and check if the number of nodes decreased. If it did, revert to the original tree. Here's a small example of what I do so far to duplicate it, which is not correct:
var tree = new TreeModel();
var root = tree.parse({
    id: 0,
    name: "Root",
    children: [{id: 1, name: "1", children: []},{id: 2, name: "2", children: []}]
});

console.log(root)
var dup = tree.parse(root)
console.log(dup)

Here's a Fiddle. You'll see the difference between the trees by looking at the console:
Node {config: Object, model: Object, children: Array[2], isRoot: function, hasChildren: function…}
Node {config: Object, model: Node, children: Array[2], isRoot: function, hasChildren: function…}

Is there any way to properly clone such a structure? I looked for cloning JS object but still, I can't find a way for cloning this object exactly (such as the prototypes of properties like the model...)
Answer: You can deep clone the model of the first tree and parse it again to get a second tree.
Taking on your example:
function deepCopy(obj) {
    // You can also use the jquery extend method here
    return JSON.parse(JSON.stringify(obj));
}

var dup = tree.parse(deepCopy(root.model));

Important: If you do not deep clone the model, and just parse it again, you'll end up with the same underlying model shared by both trees which will certainly cause inconsistencies.
Comment: You're the one who wrote this library right? Then, is there a difference with simply doing: `tree.parse(root.model);`?
Comment: Fantastic. Thank you so much for both the library and this answer. ;-)
Answer: I finally came to a solution that may help anyone with the same problem:
var tree = new TreeModel();
var root = tree.parse({
    id: 0,
    name: "Root",
    children: [{id: 1, name: "1", children: []},{id: 2, name: "2", children: []}]
});

console.log(root)
var dup = tree.parse(root.model)
console.log(dup)

The parse function takes a model as parameter and the model of root seems to work fine.
EDIT: this solution may bring inconsistencies since the 2 trees are based on the same model. JNS's solution is more appropriate.
Answer: Why not trying a jQuery deep copy?
var dup = jQuery.extend(true, {}, tree)

I tried your fiddle but it doesn't seem to work.
Comment: I think I found this solution: var dup2 = tree.parse(root.model)

*Edit: ok , you found it as well :)
Comment: Did you check the console? That's where I can check the structure.
Yes, I tried a deep copy but still, I can't get an exact replica. Have a look at the console in this updated Fiddle: http://jsfiddle.net/pvzb9vd2/5/
Comment: Yeah, I realized only too late that you were not writing in the "log" div but on the console. And I agree, that's not the same object really.
Answer: https://github.com/mrluc/owl-deepcopy  this worked for me.
newTree = deepCopy(tree)

Cloning a JS TreeModel tree


Export complex tables from a node.js app hosted in the cloud to excel files

Question: we are trying to implement an export feature to our web app.
Our app generates large tables of data, and we want the User to be able to simply export its table into newly created xlsx files:

Format must be kept (so no export in CSV)
Subtotals and totals included in the tables must be written down in Excel as a Sum formula ;

What would you use to perform that task ?
Do you think the Office Javascript for Excel API could be used to create, read and write into Excel files from a Node.js app hosted in the cloud ?
If not, could you please detail why not ?
Regards
Answer: Thanks Eddyvaub for your question, I am sorry office.js currently do not provide API to export tables to an external workbook, I would suggest that you could submit your request in uservoice and upvote for this feature for Excel online at https://officespdev.uservoice.com/forums/224641-feature-requests-and-feedback?category_id=163563
Comment: Thanks for your answer. I would also strongly recommend to use the sheetjs library which is great.


What could be a reason to not use bracket classes in C++?

Question: It's often needed to accomplish the following task: change the state of something, do action, then change the state back to original. For example, in Win32 GDI it's needed to change background color, then do some drawing, then change the color back.
It can be either done directly:
COLORREF oldColor = SetBkColor( deviceContext, newColor );
drawStuff( deviceContext );
SetBkColor( deviceContext, oldColor );

or via a bracket class that would do the forward change in the constructor and the backward change in the destructor:
CBkColorSwitcher switcher( deviceContext, newColor );
drawStuff( deviceContext );
//once control reaches end of block the switcher is destroyed and the change is reverted

The advantage of a bracket class is obvious - if an exception is thrown in between the changes the change is reverted correctly. What are the disadvantages?
Answer: This is in fact a well known and widely used C++ idiom known as RAII. Win32 APIs are C APIs and their implementation patterns are different. If you are programming in C++, it is better to handle resource allocation and deallocation using the RAII idiom, by writing thin wrappers on the C API or better re-use existing, well-designed C++ replacements. Java programmers can look upon RAII as a replacement for the finally clause.
Comment: Java programmers can think of the finally clause as a technical kludge to mimic the effects of the more elegant RAII technique. finally moves responsibility from the designer to the user which leads to more potential errors as the user needs to be as skilled as the designer to be correct. With RAII the user is protected and the responsibility of correctness falls on the designer.
Answer: A couple of disadvantages, you need to write more code, you end up creating more objects.
You have no control over the use of it. Use it wrong and you lose the benefits. e.g.
CBkColorSwitcher * switcher = new CBkColorSwitcher(......)

That said, I think the advantages far outweigh the disadvantages and would prefer the bracket class approach
Comment: @Glen: jalf points out your assertion of more code is wrong. You add 6 lines for a class with a constructor/destructor. Then subtract 1 line for each use. Thus as long as it is used 6 time or more no extra code.
Comment: @Glen: Using something incorrectly will always loose any advantages. Just like forgetting to use the C functions in pairs. So this is not a real reason. Note using NEW like that is always wrong (exception safety). in modern C++ pointers are always wrapped in a smart pointer.
Comment: The extra effort spent on writing the C++ wrappers are paid off in terms of less number of bugs created by the more verbose and error prone C code.
Comment: I disagree with having to write more code.  More braces, yes.  But the number of set/restore lines are reduced by a factor 2 in the final code.
Comment: It's often not more code. If you have to do the same thing more than a couple of times, being able to reuse the class saves code. It also ensures that your change gets reverted if an exception is thrown. Without it, you'd have to write a try/catch just to revert to the initial state.
Comment: @xtofl You have to write more code because you have to create the class, add a constructor, destructor, etc.  Using it results in less code in you method where you're doing the work, but it's another class you have to maintain, hence more code.  Like I said though, it's worth the overhead.
Comment: @Vijay  I agree about the usefulness of RAII but the OP didn't ask if  RAII was better or not, they asked what are any possible disadvantages to using it
Comment: Yes, I agree you answered the question well. I just pointed out how even that 'disadvantage' can in the long run, turn beneficial.
Answer: I consider this a best practice. I don't see any disadvantages (except maybe readability?)
Answer: The disadvantages I see are that (at least in the example you gave):

It is less clear as to what you are actually doing unless the reader of the code understands the responsibility of the bracket class.
The cost of creating the bracket class
Writing the code to implement the bracket class will take longer than a version without it.

Having said this, using RAII is the "correct" way to do this and the benefits far outweigh the disadvantages.
Answer: One disadvantage is that you usually actually have to define a new class which tends to be a bit of an overhead.
That aside it's (another) very common RAII example and is, in general, a very good approach.
Edit: If, instead of writing a class you just have a function, you can use shared_ptr to execute an arbritary code block on exit from a scope. I think it's probably a bit too cute for most applications though.
Comment: Alexandrescu's ScopeGuard<> may be a slightly more readable and expressive alternative
Comment: `shared_ptr` with custom deleter is usually used as a way to manage handles as such. To execute arbitrary code, `ScopeGuard` is indeed a better suited option.
Comment: Look at the link. `shared_ptr` can take a custom deleter. You can (ab)use it (and perhaps bind) to "delete" a void pointer by executing an arbritary function. On leaving a block scope, the custom deleter will be called.
Comment: Do you mean using the RAII properties of the shared_ptr?  Can you elaborate on that?
Comment: @Phil Nash: I agree, I was trying to find an example of something the countered the "writing a new class is a fair amount of overhead" point and `shared_ptr` abuse sprang to mind first.
Answer: I'm nitpicking here, but:

Code size, your code will be bigger because of the exception handler.
You need to write a lot of class to handle all sort of switches.
Bigger stack.
Always preforming code on all exceptions, even if its not need (for example you just want the application to crash)
Comment: In C/C++, an object cannot have a size of 0 bytes, by definition of "object" in the respective specifications. I.e. for no type T, `sizeof(T)` can ever be 0. Of course, if no-one actually observes that size in any direct or indirect way, the compiler can optimize as described by Charles. In practice, all C++ compilers I know will optimize a typical stateless scope guard class into a pair of constructor and destructor calls (and often inline them as well).
Comment: which exception handler? The stack size is pretty insignificant. An object with no state will typically take only one byte.
Comment: @jalf I'm talking about the code that the compiler inserts in order for the dtor to be called no matter what. as for your other comment, as I said I'm nitpicking and anyway I don't know how you come up with that object with no state takes a single byte.
Comment: Technically an object should have an address even if its size 0 bytes, however if nobody takes its address a compiler can (and will) not perform any instruction to allocate storage for it and just call the destructor (or even add inline code for the destructor) at the points where the 'object' would be destroyed.


Test site speed

Question: I am test driving an Akmai CDN architecture and before committing to buy, I would like to gauge the real performance gain from the acceleration feature.
What would be the best MO for doing speed tests from different locations around the world?
I would like to test the page load speed and not just the server response time.
I would like to test speed from as many edge locations as possible.
I do not mind a paid service as well, if it is optimal.
Thank you!
Comment: Gomez, Websitepulse or pingdom.
Comment: this is exactly what [watchmouse.com](http://www.watchmouse.com) provide. :)
Answer: Some of the tools I've used to gauage site speed have been the following
Pingdom's Load Time test; http://tools.pingdom.com/fpt/ and Pingdom in general as a service.
Blitz.io; http://blitz.io/
And finally Load Impact (I can't attach another URL, .com)
They all can provide multi location checks and both have flavours of free/paid tests.

Test site speed


glRotatef is backing to central position

Question: I'm having some issues with glRotateF. The problem is the following:
i'm drawing 3 lines that represent a Cartesian coordinate system, they represent the point of view of a camera.
This camera can rotate its point of view. When it rotates, it sends a message with the angles and the axis that had rotated.
My app gets this message and sends it to a method, this method gets the axis that was rotated and its angle and sends it to this method:
So far everything is working, the problem starts after this.
if I send a message to rotate the angle X on any angle and angle Z on any angle too, it just rotates the z axis.
In Debugging I noticed that first it rotated the X angle in the given angle, but when it rotates the Z in the angle, it goes back to the original position and then it rotates Z, losing the X's rotation.
Like this example:
Initial position:

rotate X on 90º:

rotate Z on 90º (What should be):

rotate Z on 90º (What is really happening):

What i want is rotate x and then z without lose x rotation.
This is how i call to rotate an axis:
openGl.rotateX((float) x);
openGl.rotateZ((float) z);

The method rotateX and rotateZ
public void rotateX(float grau) {
    mCubeRotation = grau;
    eixoX = 1.0f;
    eixoY = 0.0f;
    eixoZ = 0.0f;
    surfaceView.requestRender(); // line to call onDrawFrame
}

public void rotateZ(float grau) {
    mCubeRotation = grau;
    eixoX = 0.0f;
    eixoY = 0.0f;
    eixoZ = 1.0f;
    surfaceView.requestRender(); // line to call onDrawFrame
}

This is the code of rotation:
@Override
public void onDrawFrame(GL10 gl) {

    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    gl.glLoadIdentity();

    gl.glTranslatef(0.0f, 0.0f, -8.0f);

    // When i rotate x eixoX equal 1 and the other axis is 0.
    // When i rotate z eixoZ equal 1 and the other axis is 0.
    gl.glRotatef(mCubeRotation, eixoX, eixoY, eixoZ);

    mCube.draw(gl);

    gl.glLoadIdentity();

    lock = false;
}

if someone help me,  I will appreciate.
Answer: Your rotate methods are explicitly clobbering the global eixo* variables set by the "other" rotate method, and your draw method is resetting the rendering state matrix via glLoadIdentity, so that is why you only ever get a single rotation.
In general you can't do what you're trying to do with three simple variables and a single call to glRotatef on top of an identity matrix; rotation doesn't concatenate that neatly unless your rotations are trivial  because you need to order them correctly (applying two rotations around world-space X then Y is not the same thing as two rotations around world-space Y and then X - ordering matters). This is especially true across frames where you generally want to start from an arbitrary starting rotation. In general you want to apply a series of glRotatef calls on top of an existing matrix to generate the rotation incrementally.
Slightly off topic - if you have any choice here I would really suggest switching to use OpenGL ES 2.x and maintaining the complete translation matrix locally in your application. The OpenGL ES 1.1 API is old and relatively inefficient, and it's push/pop matrix stack assumes a very specific way of writing a scene graph rendering engine; OpenGL ES 2.x and shaders is the way forward and available on all modern devices.


PHP Code for Subscribe Block

Question: <form action="mailer.php" method="post" novalidate>
<input  value="Your Name"  name="NAME"    class="autoclear name-newsletter"     >
<input  value="Your Email"  name="EMAIL"  class="email-newsletter"     >
<input  value="Your Phone"  name="PHONE"  class="phone-newsletter"   >
<input type="submit" value="submit" name="subscribe"  class="button-newsletter">
 * We will not forward your email address to any third party.
</form>

I want to just set up a php to send an email with the information above, not a subscribe
Comment: Do you want to send the email to yourself or to the email from the form?  If you want to send the email to the address in the form, you will most certainly be attacked and your page will be turned into a relay for spammers.
Comment: So, what's the problem you are having?
Answer: The example below will send the email, but you should add captcha, and possibly other forms of security to prevent the form from being spammed.
Taken from PHP.net
<?php
$success = '';

$to      = 'email@example.com';
$subject = 'Newsletter Subscriber';
$message = 'Name:  '.$_POST['NAME']."\r\n".
           'Email: '.$_POST['EMAIL']."\r\n".
           'Phone: '.$_POST['PHONE'];
$headers = 'From: email@example.com' . "\r\n" .
           'Reply-To: email@example.com' . "\r\n" .
           'X-Mailer: PHP/' . phpversion();

if(mail($to, $subject, $message, $headers)) {
  $success = "Success! Your email has been sent!";
}

?>

Comment: How do i make it show a success your email has been sent on the same page instead of redirecting?
Answer: You can use the mail function documented by php here:
http://php.net/manual/en/function.mail.php
Execute the mail function on mailer.php using the post data.
EDIT
This code should work (Place it in mailer.
<?php
$message = 'Name:  '.$_POST['NAME']."\n".
           'Email: '.$_POST['EMAIL']."\n".
           'Phone: '.$_POST['PHONE'];

mail($to, $subject, $message)
?>

Comment: I can just want to send the name email and phone number to my email can you please provide of what the php script should be I am fairly new and am I a visually learned having a hard time

PHP Code for Subscribe Block


Best practices for mounting Sun SAN NFS on Linux (Debian Squeeze)

Question: Anyone got bestpractices for how to mount a nfsshare from Sun(Oracle) Unified Storage?
We run the usual hard and nfs4 on debian squeeze.
We run our VMs through this NFS share with Xen.
When our SAN on friday losed a disk and started resilvering(rebuilding), all the nfs shares stailed and one of our Dom0 crashed quite bad with the nfs share making a lot of vms go down.
Is there any mount options which makes this more seamlessly errorful?
Answer: I don't know much about Debian and neither about NFSv4.
But if the mount options are still the same as with NFSv3 my favorites (for any nfs-client-mount an any os) are:

hard (so keep retrying without exponential backoff of retry times)
bg (keep trying in the background without stopping anything "behind" the mount)
intr (if you really want - you can kill the mount without rebooting your client)

rsize and wsize are tuned up to reasonable sizes per default nowadays - look at your lokcal man-page.
I used to use "wsize=32768,rsize=32768" to get better tranfer rates before that.
You also have to take care on the nfs-server-side (if NFSv4 is still the same here as NFSv3):

First start all NFS-Services
Last start the Service-IP for the NFS-Services

Else the client will try to reconnect against an empty "nfs-service" and will fail instead of retry.
BTW - what has SAN to do (in this case) with Sun Unified Storage? What happened when you "lost" your SAN? Why did the rebuild process break things? Was the storage not redundant?
Comment: FWIW, Linux no longer supports the intr option. From nfs(5): "The  intr  / nointr mount option is deprecated after kernel 2.6.25.  Only
SIGKILL can interrupt a pending NFS operation on these  kernels and  if specified,  this mount option is ignored to provide backwards compatibility with older kernels."
Answer: I was having a similar problem with XenServer not long ago and I did some research on it. Apparently for some reasons XenServer uses soft mounts with relatively short short timeout for their NFS mounts. Some, people suggested modifying the mount script directly on xen server, since mount options are not configurable in any other way. Apparently thisis the only way. We do not have this problem anymore since we 100% on vmware now and it is more resilient to NFS slowdowns.
The actual problem however lays with reduced write performance of underlaying storage  and it highly depends on your RAID controller (i.e. how much performance degrades during rebuilds). You can try to play with priority settings of array rebuilds, however it made no difference on my controller (Adaptec 5085). You can potentially improve the situation a little by buying more memory for the NFS server. This way NFS daemon will write only journal entry but it will keep data in the FS cache till better times, but again it may or may not help depending on your situation.
I also noticed that this problem more often occurs on storage with parity (i.e. RAID-5 and RAID-6), so we try to use mirrored storage for our virtual machines whenever possible.


PHPMYADMIN ,,Error in Processing Request Error code: 200 Error text: OK

Question: Using PhpMyAdmin with PHP and MySQL stack in Ubuntu I encounter the problem:

1146 – Table 'phpmyadmin.pma_table_uiprefs' doesn't exist

TO solve this I added:
<code>$ Cfg ['Servers'] [$ i] ['table_uiprefs'] = 'pma_table_uiprefs';
</code>
Changed to:
<code>$ cfg ['Servers'] [$ i] ['pma__table_uiprefs'] = 'pma__table_uiprefs';
</code>
in  config.inc.php file after that I've got the problem like:

Error in Processing Request
Error code: 200
Error text: OK

How can I solve this?
Comment: can you please post code from config.inc.php? have you checked database and db table exists?
Comment: config.inc.php have only this code
$ Cfg ['Servers'] [$ i] ['table_uiprefs'] = 'pma_table_uiprefs';

Changed to: $ cfg ['Servers'] [$ i] ['pma__table_uiprefs'] = 'pma__table_uiprefs';
Answer: looks like your config has been modified put this in /var/www/phpmyadmin/config.inc.php and also change password below if you set something else blank
<code>$cfg['blowfish_secret'] = 'a8b7c6d'; /* YOU MUST FILL IN THIS FOR COOKIE AUTH! */

/*
 * Servers configuration
 */
$i = 0;

/*
 * First server
 */
$i++;
/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'config';
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
/* Select mysql if your server does not have mysqli */
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
$cfg['Servers'][1]['user'] = 'root'; //edit this line
$cfg['Servers'][1]['password'] = 'XXXX'; // your password
</code>
and comment this line for now
<code>//$ cfg ['Servers'] [$ i] ['pma__table_uiprefs'] = 'pma__table_uiprefs';
</code>
Comment: Adding this solves the error but  It don't allow me to perform any operation .
Comment: what errors are you getting? is it something related to permission? not sure try restart apache
Comment: Ya , I have set password set and AllowNoPassword is true.
Comment: Restarting still not worked , it still not allowing me to perform operation inside localhost/phpmyadmin.
Comment: do you get message "operation not permitted"? can you please paste message!!!  try change permission /etc/phpmyadmin/apache.conf
Comment: I did not got any message like that but I can not click and select the database and change table or neither can add new table but when I take  it to new tab with right click new tab I can drop Table.
Comment: there are so many free tools available on ubuntu for using mysql  and to get problem details you are facing now.  use other than phpmyadmin and post error details here
Answer: For some reason I did all the tutorials I found, and it didn't work for me, I use XAMPP, but at the end of watching so many videos, uninstalling program 1 and again and again, it occurred to me to open xampp from another browser and no longer it gave me the error, so I started deleting all the Cookies from my Chrome browser and it started working again. that worked for me.


Compare date field columns to restrict difference in days between the two

Question: I have an ad space website, where a person can place an advert, but for a maximum of 30 days.
To do this, I have a date field with a calendar popup and collect an end date on field. So it's one field collecting both dates. I need to validate the input of the end date by comparing it to the first field (start date).
I have the field validation module installed, but I'm not sure how to configure it.
How do I configure it? Or is there a better way to do this?
Answer: The field validation module does what you want, the interface description can be confusing.

On your Manage fields screen click the validate action link for your relevant date field.
For your field you want to add a Date range2 validation rule.
Name your rule in Rule name to a memorable description.
For column select value2 to validate your end date.
For Cycle of date select global so you can validate against time relative to the start date.
For Maximum date set it to "+30 day" (or any strtotime() compatible relative string) so that the end date is, at most, 30 days from the start date.
Set your your Custom error message.
Click Save rule.
Comment: Thank you very much, that did the trick! Yeah, interface is a bit confusing. Thanks for your help.


differential equation particular solution

Question: I need help with this calculus problem:
Find the particular solution of the differential equation
$e^y\frac{dy}{dx}=e^{−9x}$,
such that $y=7$ when $x=0$
I got $-\ln(\frac{e^{-9x}}{9}-\frac{1}{9}-e^7)$
But its wrong can someone work through the problem and show me what I did wrong ?
Comment: This equation is separable, try integrating both sides of the following,
$e^ydy = e^{-9x}dx$
Answer: $e^y = -\frac 19 e^{-9x} + C\\
e^7 = -\frac 19 + C\\
C = e^7 + \frac 19\\
e^y = -\frac 19 e^{-9x} + e^7 + \frac 19$
And, I think you had something close to this.
$y = \ln (-\frac 19 e^{-9x} + e^7 + \frac 19)$
Now, how do what to simplify that?
$y = \ln (-e^{-9x} + e^7 + 1) - \ln 9$
There are other operations we an perform, but I don't think it gets much simpler than that.
Comment: but its still saying this solution is wrong. i mean i dont know what else to try, you got the same answer i did just more simplified
Comment: @google What is saying this is wrong? You can plug this into wolfram alpha and it gets the same answer as all three of us.
Comment: Your answer has a negative sign in front of the logarithm.  Mine has it inside.
Answer: Hint
$$e^y\frac{\mathrm d y}{\mathrm d x}=e^{-9x}\implies e^d\mathrm d y=e^{-9x}\mathrm d x\implies \int e^y\mathrm d y=\int e^{-9x}\mathrm d x.$$
Comment: i did this, and i still got the wrong answer
Answer: Fortunately, this is a separable equation.
$$\frac{dy}{dx}e^y=e^{-9x}\Rightarrow e^ydy=e^{-9x}dx\Rightarrow \int e^{y}dy=\int  e^{-9x}dx\Rightarrow e^y=\frac{-e^{-9x}}{9}+c$$
Then, with the boundary condition $y(0)=7$ we get
$$e^7=\frac{-1}{9}+c\Rightarrow c=e^7+1/9 $$
Yielding the IVP solution:
$$e^y=\frac{e^{-9x}}{-9}+e^7+\frac{1}{9}\Rightarrow y(x)=\ln(e^7+\frac{1-e^{-9x}}{9})$$
Answer: $e^y \frac{dy}{dx} = e^{-9x}\Rightarrow e^y = -\frac{1}{9} e^{-9x} + C \Rightarrow y = \ln (-\frac{1}{9}e^{-9x}+C)=C (\ln 9-9x) \Rightarrow C = \frac{7}{\ln 9} $
Comment: Not the same 'C's but both constant anyway


Family of graphs where each vertex has a constant number of independent neighbors

Question: A question for graph theory experts. Consider a graph $G$ with $n$ vertices that has the following property: each vertex in $G$ has at most $c$ independent neighbors for some constant $c$.
Do the graphs with the above property have a name? Have they been studied? Obviously for $c=1$ , $G$ has to be a collection of cliques.
Any help will be appreciated.
Comment: Maybe you will find something on these links : [Glossary of Graph Theory - Wikipedia](https://en.wikipedia.org/wiki/Glossary_of_graph_theory) and [Gallery of named graphs - Wikipedia](https://en.wikipedia.org/wiki/Gallery_of_named_graphs)
Answer: For $c=2$, these are the claw-free graphs, which have been well-studied; the motivation for looking at these is that any line graph is claw-free.
In general, the graphs you describe could be called the (induced) $K_{1,c+1}$-free graphs. I don't think there's a more concise name.


Multivariate random walks in BUGS

Question: I want to jointly estimate a very simple MV-Normal two-dimensional AR[1] process,
$[x_t,y_t]=[x_{t-1},y_{t-1}]+\text{[Bivariate Gaussian error]}$, in BUGS. But the syntax has been impossible to figure out. Here's the problem part of the code:
<code> ## transition model (aka random walk prior)
 for(i in 2:NPERIODS1){
    mu.vector[i,1:2]<-vector[i-1,1:2]
    vector[i,1:2]~dmnorm(mu.vector[i,1:2], omega[1:2,1:2])
    }
</code>
The compiler throws up a "Expected a multivariate node" error. Looking through some examples, there doesn't seem to be any easy way to introduce a structured mean or covariance variables for the multivariate normal function. How should I proceed?
Edit:  Changed omega[,] to omega[1:2,1:2] for clarity.
Answer: Have you tried replacing omega[,] with omega[1:2,1:2]? I haven't got BUGS here but IIRC that's what it expects inside dmnorm.
Comment: Darn. Googling the syntax just now turned up BUGS code for a VAR model [here](http://www.wiley.com/legacy/wileychi/raymer/supp/Chapter12_appendix.pdf); it's purported to work :) maybe a clue in there...
Comment: Doesn't help, unfortunately. Having isolated different parts of the code, I'm pretty sure the issue is that it's not reading the mean vector as I want it to.
Comment: Thank you! Googling for working BUGS code is always difficult, due to the unfortunate name of the language. Statisticians make this mistake a lot, I mean, R?!
Answer: Even though this is over a year late, for posterity I think it should be answered since I stumbled onto this thread with essentially the same question. The problem is that in BUGS the <- assignment operator is only defined on scalars. So, the appropriate code is
<code>## transition model (aka random walk prior)
for(i in 2:NPERIODS1){
    for(j in 1:2){
        mu.vector[i,j]<-vector[i-1,j]
    }
    vector[i,1:2]~dmnorm(mu.vector[i,1:2], omega[1:2,1:2])
}
</code>
I'm not entirely sure why it doesn't give a model-check error, so maybe there is a valid way to use <- with vectors/matricies/arrays, but not here at any rate.
Answer: I disagree with @guy since the "<-" assignment works for matrices.
I think you have to "fill" the matrix mu.vector starting from the first line, you cannot start from the second line. Then type :
<code> for(i in 2:NPERIODS1){
    mu.vector[i-1,1:2]<-vector[i-1,1:2]
    vector[i,1:2]~dmnorm(mu.vector[i-1,1:2], omega[1:2,1:2])
    }
</code>
I'm not sure because I haven't used WinBUGS since a couple of years. Another possibility is that it does not allow operations on the indices inside the brackets "[...]". If that holds true, then define a vector j such that j[i]=i-1 and type
<code>   for(i in 2:NPERIODS1){
        mu.vector[j[i],1:2]<-vector[j[i],1:2]
        vector[i,1:2]~dmnorm(mu.vector[j[i],1:2], omega[1:2,1:2])
        }
</code>
By the way your code is incomplete (how is vector[1,] defined ?..). Hence this is difficult to help ! The error is possibly due to wrong dimensions when you load initial values or data.
Comment: Perhaps I was loose with how I phrased it, but it doesn't always do what one would expect it to do. I ran into it by attempting to do
    A[k, 1:J, 1:J] <- B[1:J, 1:J] * c,
and it returned the same error. All the index suggestions you made held in my particular example, and this is completely analogous to the correct syntax for an array of Wishart random variables, A[k, 1:J, 1:J] ~ dwich(B[1:J, 1:J], df). Regardless of how "<-" operator works, my suggestion should fix it.
Comment: @guy The multiplication of a vector/matrix by a scalar does not work, but the assignement such as in the OP works.

Multivariate random walks in BUGS


Concept on "best constant's loss" in vowpal wabbit's output, and the stated rule of thumb in tutorial

Question: I am trying to understand vowpal a bit more and came across this statement on the Linear Regression tutorial. (https://vowpalwabbit.org/tutorials/getting_started.html)
"At the end, some more straightforward totals are printed. The best constant and best constant's loss only work if you are using squared loss. Squared loss is the Vowpal Wabbit default. They compute the best constant's predictor and the loss of the best constant predictor.
If average loss is not better than best constant's loss, something is wrong. In this case, we have too few examples to generalize."
Based on that context, I have 2 related questions:

Is the best constant's loss based on the loss of the null model in linear regression?
Is the general rule of thumb for "average loss" not being better than "best constant's loss" applicable to all loss functions (since the statement does state that the "best constant" only works for the default squared loss function)?

Thanks in advance for any responses!
Answer: Is the best constant's loss based on the loss of the null model in linear regression?
If by null-model you mean the model which always predicts the best-constant, then yes.
Is the general rule of thumb for "average loss" not being better than "best constant's loss" applicable to all loss functions?
Yes. If by always using the same prediction (some best constant applicable to a given loss-function) you are doing better than the learned model, it means that the learned model is inferior to the simplest possible model. The simplest model for a given loss-function, is always predicting the same (best constant) result, ignoring the input-features in the data.
One of the most common cases for a learned model being inferior to the best-constant model, is a too small data-set. When the data-set is small, the learning process didn't have a chance to fully converge yet. This is also known as under-fitting.
How is the best constant calculated (for completeness)?
In the case of linear-regression (least-squares hyperplane, the vw --loss_function squared, which is the default) the best constant is the simple average (aka mean) of the labels. This minimizes the squared-loss.
In the case of quantile-loss (aka absolute-error, vw --loss_function quantile) the best constant is the median of the labels and it minimizes the sum-of-distances between the labels and the prediction.
Comment: Thank you @arielf for the extra complete answer! That really helps with framing my understanding!
Comment: What is the best constant model for logistic loss?


Is NER necessary for Coreference resolution?

Question: ... or is gender information enough?
More specifically, I'm interested in knowing if I can reduce the number of models loaded by the Stanford Core NLP to extract coreferences. I am not interested in actual named entity recognition.
Thank you
Answer: According to the EMNLP paper that describes the coref system packaged with Stanford CoreNLP, named entities tags are just used in the following coref annotation passes: precise constructs, relaxed head matching, and pronouns (Raghunathan et al. 2010).
You can specify what passes to use with the dcoref.sievePasses configuration property. If you want coreference but you don't want to do NER, you should be able to just run the pipeline without NER and specify that the coref system should only use the annotation passes that don't require NER labels.
However, the resulting coref annotations will take a hit on recall. So, you might want to do some experiments to determine whether the degraded quality of the annotations is problem for whatever your are using them for downstream.
Answer: In general, yes.  First, you need named entities because they serve as the candidate antecedents, or targets to which the pronouns refer.  Many (most?) systems perform both entity recognition and type classification in one step.  Second, the semantic category (e.g. person, org, location) of the entities are important for constructing accurate coreference chains.