How do I log in a user?

Question: I want to log in Drupal 8 users from an external PHP file. I am trying the following code.
<code>use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
use Drupal\user\UserInterface;
//$autoloader = include('/vendor/autoload.php');
$autoloader = require_once __DIR__ . '/vendor/autoload.php';
$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);

// ID of the user.
// REPLACE WITH WHATEVER ID YOU WANT TO LOGIN AS;
$uid = 100;
$user = Drupal\user\Entity\User::load($uid);

// This is required to call user_login_finalize here.
$kernel->prepareLegacyRequest($request);
user_login_finalize($user);

$response->send();

$kernel->terminate($request, $response);
</code>
When I run it, I get the following error.

TypeError: Argument 1 passed to user_login_finalize() must implement interface Drupal\user\UserInterface, null given, called in /var/www/html/stocksee/public_html/component/login.php on line 22 in user_login_finalize() (line 554 of core/modules/user/user.module).

Please help me.
Answer: I'd say in this specific case the error message looks like saying that $user is NULL. You need to validate that User::load returns a valid UserInterface because if the $uid passed to the method is not found, it will return NULL, which is the value you are getting. Try with a valid uid like 1, see what happens and move ahead from there.
Comment: Well, but that's a completely different error message from the one you exposed in your question. This second error you are mentioning is happening due to the fact that you are invoking the function user_login_finalize from the external PHP file, which doesn't have bootstrapped the Drupal's User module found in its core. In your case I'd consider to use the API to perform the login. Something similar to this https://drupal.stackexchange.com/questions/185494/how-do-i-programmatically-log-in-a-user-with-a-post-request#221045. Please remember to vote answers if you find them useful.
Comment: @sourabh Please don't post code in comments - instead, edit your question, and make it reflect what you're asking. If it's a different question from your original one, or would invalidate this answer, please post it as a new question
Comment: I already tried but I am getting error "Error: Call to undefined function user_login_finalize() in main() (line 45 of login.php)." @jbarrio
Comment: Yes, that is a different error, and it's not caused from changing the user ID to load the user entity. If you get an _Error: Call to undefined function user_login_finalize()_ error, you get it even with the code shown in the question.
Comment: use Drupal\Core\DrupalKernel;
use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
$autoloader = require_once '/component/autoload.php';
$kernel = new DrupalKernel('prod', $autoloader);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$uid = 1;
if(isset($uid)) {
  $user = User::load($uid);
  user_login_finalize($user);
  $user_destination = \Drupal::destination()->get();
  $response = new RedirectResponse($user_destination);
  $response->send();
}
Comment: Please check the above code

How do I log in a user?


Office 365 SSO external DNS redirect

Question: I have ADFS and office 365 completely set up and configured for SSO, using an ADFS server and ADFS proxy.
For internal users, I have IIS configured on the adfs server to redirect companynamemail.com to http://Outlook.com/owa/companyname.com so that the users, instead of having to go through portal.microsoftonline.com, type in thier user name, click the link, and then login, they just go to companynamemail.com, and it performs the SSO
I'm trying to find a way for external users to have a similar expeirence, I know that they will have to login because they arent authenticated through the domain, but I want thier portal to be companynamemail.com. I tried using the adfs proxy to do the http redirect, but it forwards without allowing them to login and gives an error.
I'm thinking about writing the redirect into the default website, but I'm wondering if I can do it with a redirect or a/cname record.
Answer: This is pretty simple...
If your public DNS host provides forwarding you can simply create the base A record and have it forward to portal.microsoftonline.com.
If you don't have this ability just setup a simple new website on your public facing web servers or even proxy servers that hosts that domain name.  Once you have that you can setup the IIS Rewrite Module to redirect requests to the Microsoft portal and it should do what you want.
We did this as well to provide a "customized" URL for users to access, not to mention any laptops could store the URL and it would work internally and externally, just with different authentication mechanisms.
Sample Rewrite:
https://login.microsoftonline.com/login.srf?wa=wsignin1.0&whr=<YOUR FEDERATION SERVER>&wreply=https:%2f%2foutlook.com%2fowa%2foffice365.com%2f?exsvurl=1&ll-cc=en-US

Comment: unless I am mistaken, A records can only point to an IP, so it would have to be a CNAME, and the url for SSO is http://Outlook.com/owa/companyname.com and a cname cant point to subdirectories like that.
Comment: I have it working using a auto redirect off of the default website on the proxy server. And I'm thinking that that is the only way to successfully accomplish what I'm trying to do.
Comment: Yes, it is. The Redirect from the DNS host is a feature of the DNS host and host specific in most cases.
Comment: @MattBear No problem, O365 for Enterprises is a beast to get going, it took me about 6 months to fully research and test the entire product before rolling it out to our pilot users.
Comment: I'm coming into a kind of reverse enviroment, o365 was set up prior to my arrival, with no local AD. And I'm under a time constraint to get us up to date.
Comment: actually, it looks like a cleaner way of doing is is to just use Outlook.com/owa/companyname.com on the redirect, for both external and internal.
Comment: @MattBear That may be correct. We implemented well before Outlook.com was handling O365 traffic. I was an early beta tester.
Comment: I just talked with my contact on the o365 SSO support team, he told me that they just recently added in silent redirect. So it is new.

Office 365 SSO external DNS redirect


Obter valor do campo Mongo como Variavel?

Question: Senhores, estou usando esse codigo no Meteor:
var teste = Orders.findOne({name : 'Day'}).day;

Para Obter o valor day nesse registro:
{_id: "HzoGFKRmYzmH8Yx6A", name: "Day", day: "Jan 27th 18"}

Ele da um erro, mas resgata o valor que eu quero, existe alguma forma de resgatar esse valor sem esse erro?
Comment: Onde estás a executar este (`var teste = Orders.findOne({name : 'Day'}).day;`) comando, no server-side ou client-side?
Answer: O findOne é uma instrução assíncrona, portanto a forma correta de acessar o resultado da consulta é no callback, dessa forma:
Orders.findOne({name : 'Day'}, function(err, day){
    if (!err){
        let teste = day; // aqui a variavel teste recebe o retorno da consulta
    }
});

Comment: mano, obrigado pela resposta, mas continua dando erro, foi esse erro aqui:
            Exception in template helper: Error: Match error: Failed Match.OneOf, Match.Maybe or Match.Optional validation
    at exports.check (http://localhost:3000/packages/check.js?hash=eab389b8683d2f0b47a9d511894c2082fc6155a9:65:15)
    at Mongo.Collection._getFindOptions (http://localhost:3000/packages/mongo.js?hash=337de4ed4979262aa9b84177742e90e72b1e1e1c:344:7)
Comment: está usando meteor? esse parece ser um outro problema..
Comment: eh, estou usando Meteor, essa instrucao eh dentro de uma helper....sua resposta parece certa mesmo e deveria funcionar....estranho ne....
Comment: De uma olhada [nesse](https://stackoverflow.com/questions/26104937/meteor-match-error-failed-match-oneof-or-match-optional-validation-websocket) post
Comment: dei uma olhada la, mas nao consigo achar o problema....esta tudo subscrito e publicado corretamente, pois uso outras instrucoes semelhantes em outros arquivos, ta ligado...
Comment: essa nao da erro : Orders.find({name : 'Day'},{limit : 1 }, function(err, day)                                                          mas nao executa a funcao que coloco.....tava vendo que eh referente algo ao findOne
Comment: Perdao, acredito que dei uma resposta para partindo do principio que estava usando mongoose. tente `var teste = Orders.find({name : 'Day'},{limit : 1 })` somente. Entao na linha de baixo exibir o valor de teste.
Comment: essa funciona sem erro, mas me devolve o cursor (o registro todo), eu quero so o campo day, que esta inserido nesse registro.... agradeco demais sua disponiblidade meu irmao
Comment: como mostrado nesse registro: {_id: "HzoGFKRmYzmH8Yx6A", name: "Day", day: "Jan 27th 18"}
Comment: `var teste = Orders.find({name : 'Day'},{limit : 1, fields: {'day':1} })` tente assim Neto
Comment: mano, da certo sim, mas ele retorna o cursor, o registro Json. Eu queria que ele me retornasse so o valor do field.....o engracado eh que no console no navegador da certo, mas no meteor nao funciona.....mesmo que eu negue o aparecimento dos outros campos, ele continua retornando como Json
Comment: olha essa aqui, era pra funcionar, mas da undefined:                                                                                var teste = Orders.find({name : 'Day'}, {limit : 1}).fetch();
var teste2 = teste.day;

console.log(teste2);
Comment: O que te impede de fazer [isso](https://jsfiddle.net/18urx8wL/)?
Comment: porque eu vou usar o valor adquirido como busca de outro find, ai ele nao vai aceitar dessa forma....
Comment: Pode testar isso tb: `var teste = Object.values(Orders.find({name : 'Day'},{limit : 1, fields: {'day':1} }))[0];`
Comment: tambem nao deu, retorna cursor....pense velho kkkkkkkk
Comment: Me mostra a forma que vai usar em outro find
Comment: Orders.find({orderDate: teste, userId: Meteor.userId()}).fetch();
Comment: Cara, ja tentou `Orders.find({orderDate: teste['day'], userId: Meteor.userId()}).fetch();`?
Comment: nada, isso ta mto estranho mano, era pra funcionar...mas o console continua dando undefined e nao dando certo.....esse resultado vem de um prompt que pergunto ao usuario o dia da ordem que ele quer ver....vc saberia uma outra forma de passar as informacoes do events para o helper, sem precisar inserir no db ??? porque estou fazendo isso, insiro no banco com o events, depois resgato com o helper
Answer: Mano, essa funciounou:
Orders.find({name : 'Day'}).fetch().forEach(function(day){
            var day = day.day;
        console.log(day);
Answer: Cara... pra mim funciona sem erro. Mas por via de sintax, coloque o nome do campo da sua coleção entre aspas simples e o valor a ser buscado em aspas duplas, assim:
let teste = Orders.findOne({'name': "Day"}).day;
console.log(teste);


can't play sounds with different frequency in the same scenario

Question: In the same game scenario i tried to play several sounds:one music file sound and some sound effects(like lasers hitting a ship or launching a torpedo).These work well with the classic setting values of pygame.mixer.So i typed :
pygame.mixer.init(22050, -16, 2, 4096)

However i want to play a sound file when this scenario starts(a voice) and after many tries it seems this sound should be played at a frequency of 30000 to be just right.So i want to play all the sounds in the scenario at the 22050 frequency,except this one, which i want to play at the right 30000 frequency and i can't do that in the same time.Here's what i tried:
pygame.mixer.init(30000, -16, 2, 4096)
die = pygame.mixer.Sound('die.ogg')
die.set_volume(0.40)
die.play(0)
pygame.mixer.quit()
pygame.mixer.init(22050, -16, 2, 4096)
pygame.mixer.music.load('Sounds/through space.ogg')
pygame.mixer.music.play(-1)

This doesn't play the 'die.ogg' sound file.Or,if i delete the lines:
pygame.mixer.quit()
pygame.mixer.init(22050,-16, 2, 4096)

the other sounds dont play well.Should i remove the 'die' sound object and his frequency or is there another way to keep playing all the sounds well?
Answer: You should open your sounds in audio editing software. (Audacity is free).  Most of the time you could drag-and-drop but there is usually a file>import option.
Import a single file.  File>Bounce or File>Export the same file and carefully look at the options. You should be able to choose file format, sample rate, and bit depth.  After you have these set the way you want, finish your bounce.
Repeat this process for each individual sound file, using the same bounce settings each time.
This is the cleanest solution.  You will know your sample rates.  If your program is expecting 44,100Hz (44.1k) sample rate and only gets a 30k recording, it will be played back too fast.


Finding kurtosis of signal

Question: I have a signal (Y) with 200000 samples. I plotted probability density function (PDF) of the signal and the Gaussian distribution that has the same values of Mean and Standard deviation of original signal. The kurtosis of signal (Y) is 3.12. Looking to the signal shows that Normal distribution using same values of Mean and Standard deviation has higher peak than signal (Y). Can I say this signal has Leptokurtic distribution because it has of 3.12 grater than 3? If yes why PDF plotting shows higher peak for the normal distribution?
I used to find kurtosis
k = kurtosis(Y)

For Normal distribution
Gaussian=(1/sqrt(2*pi*var(Y)))*exp(-(U-mean(Y)).^2/(2*var(Y)));

Should any signal that has kurtosis > 3 will have Leptokurtic distribution
Comment: You want to test it statistically. You can test for normality if you are interested in it, not only for excess kurtosis
Comment: @Hard Core. Thank you. Can you explain more?
Answer: It's better to avoid outdated terminology like "leptokurtic distribution". Why is kurtosis of this distribution important to you? Your plot seems quite close to a normal density ... but we don't know your ultimate goal, so cannot judge what is important for you. Look in this few posts about kurtosis to see if you are really interested: Should we teach kurtosis in an applied statistics course? If so, how?,  what is the meaning of 'tail' of kurtosis?  and  How is the kurtosis of a distribution related to the geometry of the density function?
If you want a test of normality you could look into Is normality testing 'essentially useless'?
For testing kurtosis, I would try bootstrapping (with 20000 observations that could work well). A visual version of that is a Cullen and Frey graph, for an example see Is my data gamma distributed?, which can include on the plot bootstrapped values of kurtosis, and can be very informative.
Answer: Higher kurtosis does not imply a higher peak, as was noted in 1945. But people have ignored this fact for decades and decades, writing in books, articles, and web pages that higher kurtosis means a higher peak. They still make this mistake.
"Peakedness" in general is also incorrect as a descriptor of kurtosis.
With regard to the OP, the differences in kurtosis are so small as to hardly warrant a mention.
References:
Kaplansky, I. (1945), "A Common Error Concerning Kurtosis," Journal of the American Statistical Association, 40, 259. But the "height" misinterpretation also seems to persist.
Westfall, P.H. (2014).  "Kurtosis as Peakedness, 1905 – 2014. R.I.P." The American Statistician, 68, 191–195.

Finding kurtosis of signal


Most likely dice sequence given weights and switching probabilities

Question: An occasionally dishonest casino uses two kinds of dice: a fair die that has $\frac16$ probability of rolling any number, and a loaded die that has $\frac12$ probability to roll a $6$ and a $\frac1{10}$ probability to roll each of the remaining numbers. The probability that the casino switches from the fair to loaded die is $0.1$ and the probability of switching back from loaded to fair is $0.05$. What is the most likely sequence of dice used if you observe the following numbers: $$4,6,6,6.$$ Assume the casino always starts with the fair die. Show your work.
Comment: Indeed, show your work. We're not just going to give you the answer.
Comment: Welcome to math.SE! Please consider taking the time to read the [faq] to familiarise yourself with some of our common practices. In addition, [this page](http://meta.math.stackexchange.com/q/5020/8348) should give you a start at learning how to typeset mathematics here so that your posts say what you want them to, and also look good. As this question appears to be homework, please consider reading [this page](http://meta.math.stackexchange.com/q/1803/8348) for information about asking _effective_ homework-related questions. Cheers!
Answer: Hint:
There are $8$ different possibilities for the sequence of dice types ($\text{F}$ is fair, $\text{L}$ is loaded):
$$\text{FFFF}, \text{FFFL}, \text{FFLF}, \text{FFLL}, \text{FLFF}, \text{FLFL}, \text{FLLF}, \text{FLLL}$$
Let $A_i$, with $1 \leq i \leq 8$ denote the event that the sequence of dice is the $i^{th}$ of the $8$ configurations above. Find the probability $P(A_i)$ for each $i$.
Let $B$ be the event that the numbers shown are $4$, $6$, $6$, and $6$. Find $P(B)$. You have to be a bit careful at this step. $P(B)$ isn't just $(1/6)^4$ since switching the dice is possible.
Now you can use Bayes' Theorem to find $$P(A_i \mid B) = \frac{P(B \mid A_i) \cdot P(A_i)}{P(B)}$$
for each $1 \leq i \leq 8$.

Intuitively, I'd guess it's one of $\text{FFFF}$ or $\text{FLLL}$. You might be able to just apply Bayes' Theorem to those two cases; whichever gives the higher $P(A_i \mid B)$ is your answer.
It shouldn't be any of the others because switching multiple times is unlikely, and switching later in the sequence makes the second and/or third $6$ less likely.
Answer:
So the most probable dice sequence is $\{Fair, Fair, Fair, Fair\}$. (T = Fair, F = Loaded)


Loop when the output for each iteration is a data.frame

Question: I want to do the looping for the following data. The output for a single iteration is a data.frame. My code is:
Data <- structure(list(v = c(15L, 15L, 15L, 15L, 16L, 16L, 16L, 17L,
17L, 18L, 19L, 19L, 19L, 20L, 20L, 21L, 21L, 22L, 22L, 25L, 25L
), b = c(35L, 70L, 42L, 35L, 20L, 48L, 16L, 68L, 68L, 51L, 57L,
57L, 57L, 95L, 76L, 70L, 21L, 77L, 77L, 100L, 30L), r = c(7L,
14L, 14L, 14L, 5L, 15L, 6L, 16L, 20L, 17L, 9L, 12L, 18L, 19L,
19L, 10L, 5L, 14L, 21L, 12L, 6L), k = c(3L, 3L, 5L, 6L, 4L, 5L,
6L, 4L, 5L, 6L, 3L, 4L, 6L, 4L, 5L, 3L, 5L, 4L, 6L, 3L, 5L),
    lambda = c(1L, 2L, 4L, 5L, 1L, 4L, 2L, 3L, 5L, 5L, 1L, 2L,
    5L, 3L, 4L, 1L, 1L, 2L, 5L, 1L, 1L)), .Names = c("v", "b",
"r", "k", "lambda"), class = "data.frame", row.names = c(NA,
-21L))

library(AlgDesign)
BIB <- list()
for(i in 1:nrow(Data)){
BIB[[i]] <- data.frame(optBlock(~., withinData = factor(1:Data[i, "v"]), blocksize = rep(Data[i, "k"], Data[i, "b"]))$Blocks)
dimnames(BIB[[i]]) <- list(1:Data[i, "k"], paste("Block", 1:Data[i, "b"], sep = " "))
}
BIB

Is there an easy way to accomplish the same task?
Answer: BIB <- list()
for(i in 1:nrow(Data)){
BIB[[i]] <- data.frame(optBlock(~., withinData = factor(1:Data[i, "v"]), blocksize = rep(Data[i, "k"], Data[i, "b"]))$Blocks)
dimnames(BIB[[i]]) <- list(1:Data[i, "k"], paste("Block", 1:Data[i, "b"], sep = "_"))
}

print(BIB)


Minimum of $\sum\limits_{k=0}^n { n \choose k} (1-x)^{n-k} x^k a_{n-k}b_k$ over $x \in [0,1] $

Question: Given
\begin{align}
f(x)=\sum_{k=0}^n { n \choose k} (1-x)^{n-k} \cdot x^k \cdot a_{n-k} \cdot b_k
\end{align}
Find
\begin{align}
\min _{x \in [0,1] } f(x)
\end{align}
We can assume that $a_k$ and $b_k$ are positive and monotone increasing sequences.
Note, that I am not interested in the minimizer $x^{*}$ but rather a minimum value of $f(x^{*})$.
EDIT
Based on the comments of A.S., we can redefine the problem:
Given
$$\begin{align}
g(x)=\sum_{k=0}^n { n \choose k} (1-x)^{n-k} \cdot x^k \cdot c_k
\end{align}$$
for some $c_k>0$, find
$$\begin{align}
\min _{x \in [0,1] } g(x)
\end{align}$$
This problem is related to the question I posted here.
Comment: it is $b_k$ and not $b_n$, isn't it?
Comment: The problem is that I know very little about convex optimization and combinatorics. I am afraid you have to wait for another one. I was just interested.
Comment: It looks like a hybrid between Bernoulli and Cauchy product. *Looks* easy, but I can't make sense of it right now.
Comment: Note that you can replace $a_{n-k}b_k$ by an arbitrary positive sequence $c_k$.
Comment: is $x \in [0,1]$ or is $x \in (0,1)$. If it's the latter then 0 is the minimum value which is achieved when $x = 0,1$.
Comment: @Michael Menke: Note that $0^0 = 1$.
Comment: ah, you are correct, i missed that it started at 0.
Comment: @Exodd Yes, thank you. Will correct.
Comment: The function seems to be convex, but I cannot see why.
Comment: @FriedrichPhilipp I think so too. But even if it is convex. Do you think it is easy to find the minimum?
Comment: @FriedrichPhilipp thanks for being interested. Click like
Comment: @GyroGearloose Typo corrected. Thanks I will look the ideas about Bernoulli and Cauchy product. Please let me know we you have any other ideas.
Comment: @ A.S. ok. Will add to the question.
Answer: The function $g$ is a linear combination of Bernstein polynomials. As these polynomials are a basis of the space of polynomials, your question is equivalent to asking for the minimum value of an arbitrary polynomial of degree $n$, which is impossible to answer in this general form.
For Bernstein polynomials you can obtain upper and lower bounds of the function values from the coefficients $c_k$:
$$
\min_k c_k \le g(x) \le \max_k c_k \quad\forall x\in[0,1].
$$
The proof of this is simple:
$$
g(x) =\sum_{k=0}^n {n \choose k}(1-x)^{n-k}x^kc_k
\le \max_k c_k \cdot \sum_{k=0}^n {n \choose k}(1-x)^{n-k}x^k
= \max_k c_k \cdot 1,
$$
which also shows that the bound is sharp if the $c_k$'s are all of the same value.
Comment: Could your problem be casted as a problem on Bezier curves ?  http://mathworld.wolfram.com/BezierCurve.html  For example with control points at $(k,c_k)$ or $(k,{n \choose k}c_k)$ in order to have a global "positive trend"
Comment: Thanks a lot I will look into  Bernstein polynomials.   Are the bounds you propose the tightest on Bernstein polynomials?
Comment: The bound is sharp if the $c_k$ are all the same, then $g$ is constant.
Comment: @JeanMarie Thanks for the reference. Let me check.
Comment: @JeanMarie liked your approach. I read the through your reference. I am not sure if this can be done. Could you put some of your thoughts in an answer so we can discuss it?
Answer: This is by no means an answer, but obviously more than a comment.
I have begun to make some trials with Matlab.
Here is my modest program with a graphical result.

clear all;close all;hold on;
n=5;C=rand(1,n);
D=linspace(0,1,n);
E=C+i*D;plot(E,'color','r');
t=0:0.01:1;s=1-t;M=0;
for k=0:n-1;
    M=M+nchoosek(n-1,k)*(t.^k).*(s.^(n-1-k))*E(k+1);
end;
plot(M)
I have assumed WLOG that all $c_k \in [0,1]$ but nothing else about the $c_k$s (the fact that this sequence is the product of two sequences, one increasing, the other decreasing seems to have a very moderate impact...). In red, the control "arm", with vertices the control points with coordinates $(c_k,k/n)$. Only the abscissas are interesting. In this case, the abscissa of the minimum abscissa of the (blue) curve is strongly influenced by $c_3$, the smallest of all $c_k$s.
Comment: what dies variable $i$ stand for?
Comment: It's the i of complex numbers (i^2=-1). It was slightly easier to work with complex numbers. But of course, all this can be written with two coordinates.


PPTP traffic logging

Question: I am running pptpd on a Centos 5 machine but I didnt set up any logging.
In case of an abuse, I need to determine which of my users did the bad things, meaning I need to log all the traffic. I may have up to 20 users which will use the VPN connection at least 3 hours per day.
Is tcpdump a solution ?
Answer: I have no experience with pptpd, but I do have pptp running on a CentOS machine which acts as a client connecting outward to a DrayTek router.
So, I would imagine, that for each connected user, there will be a corresponding ppp network interface created on the server to service that user. You could setup some iptables rules which log all packets from these ppp interfaces. The the final thing you have to correlate (log) from pptpd is the times when specific users were assigned particular IP addresses. This would then allow you to log the traffic and link it to the corresponding VPN user (even easier if you force VPN users to be assigned a static IP).
You would need to make sure you apply the logging rules in each direction, on the FORWARD chain most likely (to record traffic destined to other hosts on the VPN network, that is routed by the VPN server). Add INPUT and OUTPUT chains if you want to include logging for the server itself (the + denotes all ppp interfaces):
iptables -A FORWARD -i ppp+ -j LOG
iptables -A FORWARD -o ppp+ -j LOG

And obviously, you can tailor the above iptables rules to be more protocol specific, if you are wishing to monitor particular types of traffic.
Using tcpdump to capture PCAPs on a per interface basis would prove a nightmare to implement. You would need to invent some radical way of having a tcpdump process fork and die for each ppp interface that is created and deleted, as users log in and log off. I cannot think of a nice way to do that, and it seems a bit of an overkill anyway to be trying to log the packet contents across each session. Better to have further security measures on the devices they may possibly be connecting to on the private network itself.
Answer: I had to implement something similar, but only to the level of logging bandwidth per hour. What I did was set static IPs in chap-secrets for each incoming connection, then added some rules to iptables to count the data.
iptables -N vpn2fw
iptables -N fw2vpn
iptables -A INPUT  -i ppp+ -j vpn2fw
iptables -A OUTPUT -o ppp+ -j fw2vpn

iptables -A vpn2fw -s 10.0.0.100/32
iptables -A fw2vpn -d 10.0.0.100/32

Note that these rules are abstracted from my shorewall configuration and may not be exactly correct.
Obviously changing 10.0.0.100 to the IP of the user's PPTP session. Then I wrote the following script which is run by a cronjob every minute (note, needs gawk):
#!/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin

function getUsage {
        local PARSE=""
        while [ $# -ne 0 ]; do
                PARSE="$PARSE$(iptables -nvx -L $1 && iptables -Z $1)"
                shift;
        done

        echo "$PARSE" | gawk '
        {
                        if ($7 ~ /10\.0\.0\.1\d*/) user=$7
                else    if ($8 ~ /10\.0\.0\.1\d*/) user=$8
                else    next;

                out[user] += $2
        } END {
                for(user in out)
                        printf("%s %d\n", user, out[user]);
        }'
}

function getUser {
        cat /etc/ppp/chap-secrets | awk '{if ($4 == "'$1'") print $1}'
}

function logUsage {
        local DATE="$1"
        local TYPE="$2"
        local DATA="$3"
        local IFS=$'\n'

        if [ "$TYPE" == "RX" ]; then
                local QUERY="INSERT INTO vpn_usage (user, date, rx) VALUES ('%s', '%s', %d) ON DUPLICATE KEY UPDATE rx=rx+VALUES(rx)"
        else
                local QUERY="INSERT INTO vpn_usage (user, date, tx) VALUES ('%s', '%s', %d) ON DUPLICATE KEY UPDATE tx=tx+VALUES(tx)"
        fi

        for LINE in $DATA; do
                USER=$(getUser $(echo $LINE | cut -d' ' -f1))
                test -z "$USER" && continue;
                printf "$QUERY\n" "$USER" "$DATE" "$(echo $LINE | cut -d' ' -f2)" | mysql -u root bandwidth
        done
}

DATE="$(date '+%Y-%m-%d %H:00:00')"
TX="$(getUsage vpn2fw)"
RX="$(getUsage fw2vpn)"
logUsage "$DATE" "TX" "$TX"
logUsage "$DATE" "RX" "$RX"

After that I installed MySQL and created the following table:
CREATE TABLE `vpn_usage` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user` varchar(50) CHARACTER SET latin1 NOT NULL,
  `date` datetime NOT NULL,
  `rx` bigint(20) unsigned NOT NULL DEFAULT '0',
  `tx` bigint(20) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `user` (`user`,`date`)
) ENGINE=InnoDB AUTO_INCREMENT=190 DEFAULT CHARSET=utf8

PPTP traffic logging


Eu tenho que entrega essa pergunta e eu já tentei e não consegui responder. Sobre Vetor

Question:
Crie um vetor de 10 posições e digite números inteiros aleatoriamente. Depois digite um número e caso ele esteja no vetor, guarde a posição dele para mostrar ao final do programa. Senão mostre a mensagem ao final do programa "NÚMERO NÃO ENCONTRADO".
Comment: edita a pergunta e coloca o que voce tentou até agora
Answer: Se eu ainda me lembro algo de visualg é assim
<code>    algoritmo
    var
numerodesejado : inteiro
posicaodesejada : inteiro
i: inteiro
    numeros: vetor[1..10] de inteiro
    inicio
    posicaodesejada <- 0
    numerodesejado <-10
    vetor[1] <-5
    vetor[2] <-10
    vetor[3] <-15
    vetor[4] <- 20
    vetor[5] <- 25
    vetor[6] <-30
    vetor[7] <-35
    vetor[8] <-40
    vetor[9] <-45
    vetor[10] <-50
      para i de 1 ate 10  faca
        se vetor[i]= numerodesejado entao
         posicaodesejada <- i

        fimse
      fimpara
    se posicaodesejada > 0 entao
    escreval ("A posição desejada é ", posicaodesejada)
    senao
    escreval ("POSICAO NÃO ENCONTRADA!")
    fimse

    fimalgoritmo
</code>


How can a sh script determine if it was started as a cron job as opposed to interactive or background?

Question: I'd like to use the same scripting for cron and interactive, just wondering if there was a universal way over UNIX/Linux systems to easily make this determination.
Answer: You can try to return the name of the parent process with something like this: -
ps -ocommand= -p $PPID | awk -F/ '{print $NF}' | awk '{print $1}'

For me this returned konsole when I ran this interactively.
or you could script in some logic to handle situations.
while getopts cm opt
do
case $opt in
        c)
                ##  Do crontask
        ;;
        m)
                ##  Do manual
        ;;
        esac
done

Now when executing the script you can pass an option as an attribute like so :-
/use/local/bin/example.sh -m
/use/local/bin/example.sh -c

Comment: This one looks like the most universal.
Comment: I know that I did not ask this, but cron (in RHEL) also runs at jobs.  So there it doesn't look like there is a way to distinguish at jobs from cron jobs in cases.
Answer: there is no universal way at all. using interactive/noninteractive shell detection or tty detection is not reliable either, as other cases than cron can have these characteristics. just add a variable in your cron entry. say you need to run test.sh, then use this instead.
$ RUNENV=cron ./test.sh
cron
cat ./test.sh
#!/bin/sh
echo $RUNENV

This is fairly easy and reliable, if you control the cron setup.
Comment: I like this but it will not work on all UNIX/Linux systems.  SunOS for one.
Answer: I don't know how portable this is, but on Linux you can run tty and check whether the output is a tty.
$ tty
/dev/pts/2
$ crontab -e
* * * * * echo $(tty) >> /home/paulo/cron_tty
[Wait a minute...]
$ cat /home/paulo/cron_tty
not a tty

Note that the tty will also not be set if the script is running non-interactively from something other than cron, but since you said you want to distinguish cron from interactive, that shouldn't be an issue.
Other than that, possibly the most robust solution is to add a switch to your script, telling it whether it is running from cron or not, as suggested in a Stack Overflow question.


How to convert the following SQL query to Linq?

Question: How to convert following SQL query to Linq?
select day(Ser_CallDate) as OrderDate, count(*) TotalCall
from ServiceCalls
where month(Ser_CallDate) = MONTH(getdate()) and year(Ser_CallDate) = YEAR(getdate())
group by day(Ser_CallDate)

Please help me, thanks
Answer: var result = ServiceCalls
        .Where(s => s.Ser_CallDate.Month == DateTime.Now.Month
            && s.Ser_CallDate.Year == DateTime.Now.Year)
        .GroupBy(s => s.Ser_CallDate)
        .Select(g => new {
                OrderDate = g.Key,
                TotalCall = g.Count()})
        .ToList();


Trivial second homology group

Question: Let $\Omega\subset\mathbb{R}^3$ be a an open bounded set.
Let us consider the following statement:

every closed surface in $\Omega$ is the boundary of a suitable
  subdomain $D\subset\Omega$.

How is this statement related to Homology or Cohomology theories? I am not at expert at all about algebraic topology, it's a matter of curiosity. I'm sorry if the question does look too much naive.
Comment: I don't know whether it's fine: *you're* the one with the question. Since there are about 200 different kinds of homology theory, you'll also have to tell us which one, and what coefficients you're using. It sure *looks* as if this is pretty much straight from the definition of singular homology, although I don't know what "domain" means in your context.
Comment: By $\mathbb{H}^2(\Omega)$, do you mean the second cohomology group? Singular? deRham? Something else entirely? And if you meant cohomology, what coefficients? If you'd written a subscript of $2$, this would be nearly the definition.
Comment: Sorry, unfortunately I just studied the De Rham Cohomology, so I didn't know the notation for homology. Is it fine now?
Comment: Singular homology with integer coefficients
Comment: It is a question of algebraic topology, not algebraic geometry
Answer: This follows from standard forklore in differential topology (maybe due to Thom or Poincare??):
Let $M^n$ be a smooth orientable $n$-manifold, then any homology class of codimension 1 or 2, that is, an element in $H_{n-1}(M^n)$ or $H_{n-2}(M^n)$, can be represented by the fundamental class of a submanifold.
Comment: Poincare used this for codimension 1 in one of his proofs of duality.  But his argument for it was terrible,and this is one reason he shifted from (something vaguely like) singular homology to simplicial.

Trivial second homology group


Will choosing whether to display a component in render() using props/state result in a redraw every time?

Question: Are the following two equivalent performance wise? Will the first example cause Component1 and Component2 to be re-rendered every time MyComponent's props are updated?
import React from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { selectShowComponent1, selectShowComponent2 } from './selectors';

@connect(createStructuredSelector({
  showComponent1: selectShowComponent1,
  showComponent2: selectShowComponent2,
}))
class MyComponent extends React.PureComponent {
  static propTypes = {
    showComponent1: React.PropTypes.bool,
    showComponent2: React.PropTypes.bool,
  };

  render() {
    const { showComponent1, showComponent2 } = this.props;
    return (

        {showComponent1 ? (<Component1>shown 1</Component1>) : ''}
        {showComponent2 ? (<Component2>shown 2</Component2>) : ''}

    );
  }
}

export default MyComponent;

import React from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { selectShowComponent1, selectShowComponent2 } from './selectors';

@connect(createStructuredSelector({
  showComponent1: selectShowComponent1,
  showComponent2: selectShowComponent2,
}))
class MyComponent extends React.PureComponent {
  static propTypes = {
    showComponent1: React.PropTypes.bool,
    showComponent2: React.PropTypes.bool,
  };

  render() {
    const { showComponent1, showComponent2 } = this.props;
    return (

        <Component1 renderMe={showComponent1}>shown 1</Component1>
        <Component2 renderMe={showComponent2}>shown 2</Component2>

    );
  }
}

export default MyComponent;

Comment: second approach will render both of components and just inside those components you will manage what to show. First approach, from the other hand, will mount new component every time something will change in your props.
Answer: The first one will re-render every time, whereas the second one won't. The reason is dynamically generated components (in this case, dynamic cos they're the result of a ternary operator) get given a new key each time they're returned from the dynamic context. And this key is what React uses internally to uniquely identify components.
So I believe if you gave them explicit keys:
    {showComponent1 ? (<Component1 key="1">shown 1</Component1>) : ''}
    {showComponent2 ? (<Component2 key="2">shown 2</Component2>) : ''}

Then in theory that should stop them being re-rendered, but that's not ideal as manually assigning keys in some scenarios may mean the component may not re-render when you actually want it to.
Comment: Thank you for your reply. The keys, are they "scoped" within each component? Could I get conflicts if I use the same keys in multiple components? ie, if I have a list in the header component and the keys for the items are 1, 2, 3, ... and then another list in the footer with items assigned the same key values, will they conflict?
Comment: They only need to be unique with regard to their siblings (i.e. the level below their parent).


Dynamic Addition of Option Menu tKinter Python

Question: I'm quite new to python. I have a requirement where I have to read a data file and based on the number of records inside the file, I have to create the same number of option menus related to that data. But option menu's options can be fetched from simple list. Please find the code below.
import tkinter as tk
from tkinter import *

root=tk.Tk()
root.title("GridAssign")

Grids=('Grid1','Grid2','Grid3','Grid4','Grid5')
file=open(Datafilepath,"r")
ing=file.read().splitlines()
print (len(ing))

variable = StringVar(root)
variable.set(Grids[0])

for i in range(len(ing)):

  label = tk.Label(root,text=ing[i])
  label.grid(row=i,pady=3,sticky=W)
  w=OptionMenu (root, variable, *tuple(Grids)))
  w.grid(row=i,column=2,pady=3,sticky=E)

root.mainloop()

The above code is able to give me n number of option menus but if I choose one value in one option menu other option menu's value also changes. Can someone please let me know how to achieve this.
Thanks,
Santty.
Answer: This is happening because each of your OptionMenu are using the same StringVar.  So naturally when one OptionMenu makes a change to that StringVar, the other menus also reflect that change.
To prevent this you can use a separate StringVar for each menu:
import tkinter as tk
from tkinter import *

root=tk.Tk()
root.title("GridAssign")

Grids=('Grid1','Grid2','Grid3','Grid4','Grid5')
file=open(Datafilepath,"r")
ing=file.read().splitlines()
print (len(ing))

variable_dict = {}

for i in range(len(ing)):
    variable = StringVar(root)
    variable.set(Grids[0])
    variable_dict[i] = variable

    label = tk.Label(root,text=ing[i])
    label.grid(row=i,pady=3,sticky=W)
    w=OptionMenu (root, variable, *tuple(Grids)))
    w.grid(row=i,column=2,pady=3,sticky=E)

root.mainloop()

You can then access each of the StringVars through the dictionary variable_dict
Comment: Thanks a lot for your quick response.Will try it out.


OWA website down in sbs2003

Question: Suddenly and inexplicably the Outlook Web Access site on one of the SBS 2003 sites I manage is down. To my knowledge, nothing has changed on the server and we've rebooted it to see if the site comes back up. It doesn't.
It doesn't work from inside or outside the network. Web browsers give a "cannot display the web page" style error. The most information I've been able to glean is from Chrome which states: Error 107 (net::ERR_SSL_PROTOCOL_ERROR): Unknown error. I don't know if that's a false clue however.
I have very limited (read: none) skills at troubleshooting IIS. Can anyone point out some useful tips?
Cheers,
Mike...
Comment: Do you call the site using ISA Server as web proxy? http://www.edugeek.net/forums/internet-related-filtering-firewall/47614-isa-2006-ie7-ssl-problems.html
Comment: No, I don't. No ISA here.
Answer: This could be a problem with the certificate associated to the OWA web site. Can you check the certificate on that server?
Comment: Oh wow. That was it. I checked the assigned cert on the Default Web Site and it was missing. I reassigned it and all is okay. Whew! Thanks!
Comment: I can. How shall I do it? :)

OWA website down in sbs2003


Simulated Annealing vs. Basin-hopping algorithm

Question: I was planning to use Simulated Annealing algorithm (scipy.optimize implementation) to optimise my black-box objective function, but the documentation mentions that the method is

Deprecated in scipy 0.14.0, use basinhopping instead

and proposes to use Basin-hopping algorithm instead. Does it mean that this algorithm outperforms Simulated Annealing in all cases? Why is it claimed to be more performant than SA?
Comment: According to the No Free Lunch theorem, there is *no such thing* as an algorithm that outperforms any other algorithm "in all cases". It might be better for a a very practical subset of problems, but over the entire universe of problems, Simulated Annealing, Basin Hopping, and even random selection perform equally well.
Comment: Did you read the discussion [here](https://github.com/scipy/scipy/issues/9484) ?
Comment: def simulated_annealing(...):
scipy.optimize.dual_annealing(..., no_local_search=True,...)
Comment: Thanks @RobertLong. I did not read it but it does not seem to answer the question why the latter algorithm has better performance. Interestingly, as menionted in the discussion, there exists another, more performant version of SA:  [Dual Annealing](http://scipy.github.io/devdocs/generated/scipy.optimize.dual_annealing.html#scipy.optimize.dual_annealing)
Comment: @JamesBowery You should do more than just turn off the local search, at least if you want to recover the Boltzman visiting distribution. That's the point of my answer
Answer: The reason for Simulated Annealing to be Deprecated is not because Basin-hopping outperform it theoretically. Is because the specific implementation done for Simulated Annealing in the library is a special case of the second.
If you want to use a Simulated Annealing  algorithm I recomend you to use scipy.optimize.dual_annealing instead, but with $'visit'=q_v=1, \, 'acept'=q_a=1$ (this recover Classical Simulated Annealing, i.e. the temperature decreases logarithmically). Other parameter election leads to more sophisticated Annealing processes, like $'visit'=q_v=2, \, 'acept'=q_a=1$ (which recover the Fast Simulated Annealing, i.e. the temperature decrease up to inverse).
Observation: As @JamesBowery points out in his comment you should turn of the local optimizer.
Comment: The 'visit' parameter for dual_annealing can be (1, 3] via the [docs](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.dual_annealing.html#scipy.optimize.dual_annealing). I tried 1.0 and got a divide-by-zero error. Make sure you're slightly greater than 1, and the default is 2.62
Comment: @mightypile Yes, you are right. I customary use a modification by https://github.com/Yarapy/Copula_Cosimulation/blob/main/dual_annealing.py where they fix this problem; however I see that modifications of the original library have been made last year. I hope they fixed this problem there too


Why do people use a microphone to record an electric guitar

Question: I'm looking to start getting into recording - electric guitar specifically. Although I've noticed people place a microphone in front of the amp's speaker. Wouldn't it be easier to use a male to male audio cable and plug that into an amp.
I thought about doing it like this:
Guitar -> Effects Pedal(s) -> Amp -> Computer
Sorry if I'm not getting something, I'm just getting into this.
Answer: Yes, in a way it would indeed be "easier", as long as there is a line output on the amp.
The reason for using a microphone when recording an amplified electric guitar is that the speaker is a significant part of the sound, not to mention the room (although to a lesser extent). Even the microphone is part of the sound!
(Of course you don't have to use a mic to get a good sound. You could even plug the guitar directly into the recording interface. As long as it sounds good...)
Comment: Thanks for the answer, I'm not sure which route to take, I have a bad amp Marshall MG15CF, and am recording in a small bedroom (about 5m x 5m). Which would you recommend - bearing in mind sound quality is my main priority. Also what role does an audio interface play? Thanks :)
Comment: Try everything! Experimenting is the way to go. Only you can be the judge. "Sound quality" can be very subjective... The audio interface does make a difference, but as long as you don't get excessive noise or strange artifacts I wouldn't worry about it to begin with.
Comment: Anyway I'm aiming for a nirvana type grunge sound so I guess after the distortion quality doesn't matter as much, also could explain where the interface fits in, and suggest a good beginner interface, Thanks.
Comment: To add to your point about the room making a difference, I've often pointed the speakers at a corner with a mic inbetween to get some interesting reverb effects.
Answer: There are many different ways to record your electric guitar in your home studio.  In the old days, the only way to record an electric guitar was by placing a microphone in a position where it could pick up the sound of the guitar amp.
Today, many guitar amplifiers have line outputs that will facilitate sending the signal from the amp directly to your recording interface.  In fact, you don't even have to have an amplifier at all to record an electric guitar.  There are many amp simulators that can digitally reproduce the sound of any number of different type amplifiers - including all the effects you can imagine.
You can also plug your guitar into an interface or a direct box and input a dry signal into your computer and use your DAW to process the dry signal and add effects such as reverb, distortion, delay, and many others using your software.
But what all of this new fangled digital amp simulation software is trying to do is emulate the sound that the old vintage amplifiers were capable of producing.  So if you own one of the older vintage amplifiers (like one of the amps the simulators attempt to reproduce the sound of) you can achieve some very good results if you position a good microphone in the right spot to capture the sound of the amplifier.
If you do have a really good amplifier and you want to mic it, you should use a good instrument mic like a Shure SM 57 or Sennheiser e906.  Attach it to a stand designed for the task at hand and point the mic towards the speaker cone either perpendicular or at an angle.  You will get a different sound depending on the angle of the mic and whether it is closer to the center of the speaker cone or the edge.  You have to try different positions until you get the sound you like best.
Most folks making a low budget home studio type recording are able to get more than satisfactory results with a direct input of the guitar through some type of simulator or effects module that can connect to their computer.
If you have an old vintage tube amplifier and want to capture the authentic sound, and you have a good quality instrument mic, feel free to experiment with miking the cabinet.
Answer: Partly the reason people do it is because it used to be the only way.
However a mic'd up amp sounds SO good recorded, particularly if you stick a couple mics on there and really catch the sweet spots.
Thirdly, the same guitar, played by the same player can sound massively different through different amps. So the reason why you mic up an amp is because THAT is the sound you're trying to capture. That warm, tube sound is largely the amp/speaker and not the guitar/player.
If you really don't want to or can't then I recommend Ik Multimedia's Amplitube software.


Laravel/Eloquent belongsToMany returning all records

Question: Mostly a beginner of Eloquent here. I have got a working many to many relationship between two models: Venue and Category.
Venue.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Venue extends Model
{
    public function categories()
    {
        return $this->belongsToMany('App\Models\Category');
    }
}

Category.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function venues()
    {
        return $this->belongsToMany('App\Models\Venue');
    }
}

I need to return a JSON object containing the venue and the related categories as a sub-property. However, using $venue->with('categories') returns a Builder object – which can't be converted to JSON – and using $venue->with('categories')->get() returns me a huge object containing all the venues (or so I think they are) in the DB.
What's the correct way to do this?

Edit 03/27/2017: After accepting the answer below, I'm still curious why eloquent returns that huge array of Venue objects. If somebody knows, please leave an answer anyway!
Answer: Use the first() method:
$venue = Venue::where('name', $name)->with('categories')->first();

If $venue is already has specific venue, use the load() method to lazy eager load related data:
$venue->load('categories');

Comment: @Alan then instead of using load, just create this property with something like `$venue->list = $venue->categories()->pluck('name', 'id')`
Comment: @Alan you can use pluck after you `load()` the relationship. For example, `$list = $venue->categories->pluck('name', 'id')`
Comment: Thanks, `load()` is exactly what I needed. Any chance it can be used in conjunction with `pluck()` to get a nice object with ids as keys?
Comment: That assigns the plucked array to a variable. I wanted to pass that array as a sub-property, so `venue.categories` is just an array containing just key and value instead of a full object.


Numerical Analysis converging sequence question

Question:
Show that the sequence $p=10^{-2n}$ converges to zero with order $2$.
How many steps, $n$, will it take before this sequence is within $10^{-8}$ of zero?
Construct a sequence that converges with order $4$.
Answer: For (1) and (3), you need to use the definition:
Definition: We say that the sequence converges with order $q$ to $L$ for $q>1$ if
$$ \lim_{k\to \infty} \frac{|x_{k+1}-L|}{|x_k-L|^q} = \mu \,\big|\; \mu > 0.$$


How to find the interval of existence of this Bernoulli Equation?

Question: Question: $\frac{dy}{dx} - y + 2 = xe^x (y-2)^{1/3}$ with initial conditions $y(0) = 3$
My solution: $y(x) = (2xe^x - 6e^x +Ce^{\frac23 x})^{\frac 32} + 2$
Using the initial condition I found $C=7$. Now when I plot my answer I get a function that looks like it is asymptotically increasing as $\lim_{y \to \infty} $. But it seems like the interval of validity is $(-\infty, \infty)$.
How should I approach this?
Answer: A differential equation is Bernoulli when can be written as $y'=a(x)y+b(x)y^{\alpha}$ and $\alpha\in \mathbf{R}$ so a priori I do not see how the title it relates with the differential equation.
On other hand, for the context: in the following, I will consider real value root. So the domain of $x\mapsto x^{1/3}:=\sqrt[3]{x}$ and $x\mapsto x^{2/3}:=\sqrt[3]{x^{2}}$ is all real set. $^{(1)}$
Setting $f(x,y)=xe^{x}(y-2)^{1/3}-2+y$ wich is continuous everywhere and $f_{y}(x,y)=\frac{e^{x}x}{3(y-2)^{2/3}}+1$ which is continuous everywhere except on the line $y=2$. Then a rectangle can be drawn about the initial point $(0,3)$ in which $f$ and $f_{y}$ are continuous. Therefore, by  Picard–Lindelöf theorem the initial value problem has a unique solution in some interval about $x=0$.
I have checked your solution and I think it works. So I will only answer your question about the existence interval of the solution.
Considering your definition of  $y(x)$ and using the definition $^{(1)}$, then $y(x)$ can be written as $$y(x)=\sqrt[3]{(2xe^{x}-6e^{x}+7e^{\frac{2}{3}x})^{2}}+2,$$
which is well-defined over all real set. Therefore, the interval of validy is $]-\infty,+\infty[$.


Is there a process to run a task daily

Question: I have business logic that interfaces with Drupal entities (in this case, users), and we need to generate reports off these records daily at a preset time. It would be easy for me to generate this data on-demand, but the requirements ask for a daily report.
I'm wondering if its possible in D7 to have the system schedule a specific cron task to run at a preset task over the time cron is expected to run (which right now, is every 3 hours). Another option I am considering is to have a Contrib Drush script that simply runs using the OS'es crontab/launchd. Which one makes the most sense?
Answer: I had to do something similar recently. The extremely simple answer I came up with was to simply keep track of the last time the function was run with a db variable.
So, in psudo code, I ended up doing something like this:
<code>function hook_cron(){
  $now = new DateTime(date(DATE_ISO8601));
  $last_checked = new DateTime(variable_get('last_checkedvar', date(DATE_ISO8601, '0')));
  $diff = $now->diff( $last_checked );

  if ($diff->days >= 1){
    //do your stuff
  }
}
</code>
Works well for me. And it also doesn't interfere with any of the other cron tasks I have running on my site.

Is there a process to run a task daily


customized login block

Question: I made a template for the login block on the main page. It works.
Here is user-login.tpl.php code:
<?php
    $elements = drupal_get_form('user_login_block');
?>

Login

<?php
print drupal_render($elements["form_id"]);
print drupal_render($elements['name']);
print drupal_render($elements['pass']);
?>

             Forgot password

       <input type="submit" name="" value="Log in" />
       Sign up

<form> and
 tags were added around my template code, breaking the layout. Now the block doesn't float: left.
Here is the rendedered HTML:
<form action="/node?destination=node" method="post" id="user-login-form" accept-charset="UTF-8">

Login

<input type="hidden" name="form_id" value="user_login_block" />

  Login *
 <input type="text" id="edit-name--2" name="name" value="" size="15" maxlength="60" class="form-text required" />

  Password *
 <input type="password" id="edit-pass--2" name="pass" size="15" maxlength="60" class="form-text required" />

             Forgot password

       <input type="submit" name="" value="Log in" />
       Sign up

</form>

How to remove extra
 and put the form inside
? I tried that manually, but then I get 2 forms.
Comment: Can you show the rendered html for that image in your question?
Comment: Added the code.
Answer: You could alter the form on the theme layer to wrap the form in a div...
/**
 * Implements hook_form_alter().
*/
function YOURTHEME_form_alter(&$form, &$form_state, $form_id) {

    //dsm($form_id);

    if ($form_id == 'YOURFORMID') {
        // add prefix and suffix to form
        $form['#prefix'] = '
';
        $form['#suffix'] = '
';
    }
}

customized login block


What is the difference between projective space and weighted projective space?

Question: I know their definitions but I don't really know what the differences are conceptually. I know that $\mathbb{C}P^n$ can be thought of as the complex lines through the origin of a complex Euclidean space but I don't know how that differs from weighted projective space.
I've been reading about weighted projective space here: https://arxiv.org/pdf/1108.1938.pdf
Theorem 2.1 states without proof that they have the same cohomology. Can anyone provide intuition for this? I have only a loose understanding of cohomology.
Answer: Here is the first step of the proof, taken from the paper by T. Kawasaki, "Cohomology of Twisted Projective Spaces and Lens Complexes".
The idea is to use the covering $p : \Bbb P^n \to \Bbb P(a_0, \dots, a_n)$, $[x_0: \dots : x_n] \mapsto [x_0^{a_0}: \dots :x_n^{a_n}]$. If $G$ is the deck group of the covering (the product of $\mu_{a_i}$, where $\mu_k$ is the group of $k$-th roots of unity), then we get an homeomorphism $\Bbb P^n/G \cong \Bbb P(a_0, \dots, a_n)$. Now there is a theorem by Borel saying that for a finite group $G$ acting on a space $X$ the pullback $$ \pi^* : H^{\bullet}(X/G, S) \to H^{\bullet}(X,S)^G $$
is an isomorphism as long as $|G|^{-1} \in S $. So it doesn't work for integer coefficients but at least it gives you the result for $\Bbb Q$, or even the localisation $\Bbb Z_a$ where $a = \prod a_i$. This is getting technical after this so I'll stop here.
On the other hand, it is always instructive to see example by hand. So let $X = \Bbb P(1,1,n)$ be the projective space. If we look at space of functions of degree $n$, by definition it is $x^n,x^{n-1}y, \dots, y^n, z$. (A degree $n$ monomial $M$ means that $t \cdot M = t^nM$). We get an embedding $$ f : \Bbb P(1,1,n) \to \Bbb P^n, (x,y,z) \mapsto (x^n:\dots:y^n:z)$$
This is exactly the (projective) cone over $(0:0: \dots :1)$ of the Veronese curve $ (x^n:\dots:y^n:0)$. If it was an affine cone it would be contractible, but projective cones are not and in fact they have an interesting cohomology. Let $Y$ be this cone, $X$ be our Veronese curve curve and $p = (0:0: \dots : 0:1)$. Then, we use Mayer-Vietoris in the following way : $U$ is the complement of the $p$ and $V$ is the intersection of a a small ball around $p$ with $Y$, notice $V$ is contractible and $U$ retracts on $X \cong \Bbb P^1$. The Mayer-Vietoris sequence gives
$$ H^0(Y) \to H^0(U) \oplus H^0(V) \to H^0(U \cap V) \to H^1(Y) \to H^1(U) \to H^1(U \cap V) \to H^2(Y) \to H^2(U) \to H^2(U \cap V) \to H^3(Y) \to H^3(U)  \to H^3(U \cap V) \to H^4(Y) \to 0  $$
Since $H^1(U) = H^3(U) = 0$ the interesting part of the sequence becomes
$$ H^1(U \cap V) \to H^2(Y) \to H^2(U) \to H^2(U \cap V) \to H^3(Y) $$
Now I'll skip details since this is already a bit long : to understand $U \cap V$ we can image that we get a $D^*$-bundle over $X$, homotopically equivalent to a $S^1$-bundle with positive Euler class. A very close look at the Gysin sequence gives : $H^3(U \cap V) = \Bbb Z$, $H^1(U \cap V) = 0$ and that the map restriction map $H^2(U) \to H^2(U \cap V)$ is zero. If you believe it (or better check it) it follows that $\Bbb P (1,1,n)$ has the additive cohomology of $\Bbb P^2$, despite its conical singularity ! I should say this is pretty surprising.
Finally let me give you a quick application of weighted projective space. Say you have a curve $f(x,y,z) = 0$ in $\Bbb P^2$, maybe you want to look at the cyclic cover $w^n = f(x,y,z)$. This equation does not make sense until you go in a weighted projective space.


Erro 500 ao usar Slim Framework com Twig

Question: Estou desenvolvendo um simples website, com Slim Framework e Twig para template engine, só que esta retornando o erro 500 no navegador, esse é o conteúdo do meu arquivo index.php (na raiz do projeto):
require_once './vendor/autoload.php';

// Create container
$container = new \Slim\Container;

// Register component on container
$container['view'] = function ($c) {
    $view = new \Slim\Views\Twig('app/views', [
        'cache' => 'app/storage/cache'
    ]);
    $view->addExtension(new \Slim\Views\TwigExtension(
        $c['router'],
        $c['request']->getUri()
    ));

    return $view;
};

// Create app
$app = new \Slim\App($container);

// Routes
$app->get('/', function() use ($app) {
    $app->render('index.twig', ['app' => $app]);
})->name('home');

// Run app
$app->run();

a minha estrutura de pastas está assim:
app
  |__views
  |__storage
           |__cache
vendor
     |__twig
     |__slim
     |__psr
     |__composer
assets
     |__css
     |__js
     |__img
     |__fonts

Segui as instruções nesse exemplo: http://www.slimframework.com/docs/features/templates.html
Gostaria de renderizar a view "home", mas apenas retorna:

Erro 500
Comment: verifiquei o log do apache e esta escrito isso: ```Class 'Slim\\Container' not found```
Comment: No arquivo principal coloque, `ini_set('display_errors', true); error_reporting(E_ALL);`
Comment: Como está seu arquivo .htaccess? O erro pode está nele.
Comment: tá sem .htaccess
Answer: Pelo inicio do seu código parece que você está utilizando o Slim Framework v3, mas pela forma que criou a route, ali é a forma do v2.
Vou presumir que está usando o Slim v3.
Como está sem .htaccess, primeiro crie ele:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

Caso não esteja usando apache pode encontrar os códigos para outros webservers em http://www.slimframework.com/docs/start/web-servers.html
Altere seu código da route para:
// Routes
$app->get( '/', function ( $request, $response, $args ) {
    return $this->view->render( $response, 'index.twig', [ 'app', $this ] );
} )->setName( 'home' );

Houve mudanças consideráveis entre o Slim v2 e o Slim v3, destacaram as principais na documentação em http://www.slimframework.com/docs/start/upgrade.html
Complemento
Para habilitar o debug no Slim v3, adicione ao container
$container['settings']['displayErrorDetails'] = true;

Ainda estou estudando um pouco essa nova versão, mas espero ter ajudado.


Is it possible to do a groupby on the result of a groupby?

Question: I don't think I need to share the entire dataframe, but basically, this is the line of code in question (with pandas already imported, of course)
divstack = df[df['Competitor']=='Emma Slabach'].groupby(['Division','Stack'])['Time'].min()

The output is :
>>> divstack
Division  Stack
6U F      3/3/03     2.66
          3/6/03     4.81
          Cycle     13.89
7-8 F     3/3/03     2.41
          3/6/03     2.68
          Cycle      7.71
9-10 F    3/3/03     2.13
          3/6/03     2.75
          Cycle      6.94
Name: Time, dtype: float64

I already grabbed Emma's fastest time is 2.13, thanks to this line of code:
emma = df[df['Competitor']=='Emma Slabach'].groupby(['Competitor'])['Time'].min()
and the output is:
>>> emma
Competitor
Emma Slabach    2.13
Name: Time, dtype: float64

But how would I go about modifying the first line of code from earlier to specifically obtain the Division and Stack (along with Time) of when her fastest time occurred? (Division 9-10F and Stack 3/3/03).
I don't think a function is necessary, but is there a way I can perform another groupby on top of that first groupby output (divstack) I got, to further "minimize" and get her fastest time?
Or could I input emma somewhere in divstack to obtain which division/stack that time occurs?
I need to store the division, stack, and time into divstack
Answer: Given divstack, you can retrieve the full MultiIndex entry with .loc and min():
divstack.loc[divstack.eq(divstack.min())]

Division  Stack
9-10 F    3/3/03    2.13
Name: Time, dtype: float64

Comment: Thanks! Btw do you know why the name of the `Time` column isn't present both in your code and my original code?
Comment: You're welcome!  When you apply an aggregation function on a single variable, you get a `Series` as output.  It's only one vector, so it doesn't get referenced by name, the way you would in a multi-column data frame.  It's still called `Time`, though, as you can see in the output.  You can also check this with `divstack.name` (you'll see that's equal to `'Time'`).
Answer: I think you're looking for the idxmin function
https://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.core.groupby.DataFrameGroupBy.idxmin.html
result = df.loc[df.groupby('Competitor').Time.idxmin()]

should give you what you want for every competitor. Just filter then for Emma if you need: result.loc[result.Competitor == 'Emma Slabach']
In [6]: df = pd.DataFrame([['Emma Slabach', '6U F',  '3/3/03', 2.66], ['Emma Slabach', '7-8 F', '3/3/03', 2.41], ['Roger', '6U F', '3/3/03', 3.80]], columns=['Competitor', 'Div
   ...: ision', 'Stack', 'Time'])

In [7]: df
Out[7]:
     Competitor Division   Stack  Time
0  Emma Slabach     6U F  3/3/03  2.66
1  Emma Slabach    7-8 F  3/3/03  2.41
2         Roger     6U F  3/3/03  3.80

In [8]: df.loc[df.groupby('Competitor').Time.idxmin()]
Out[8]:
     Competitor Division   Stack  Time
1  Emma Slabach    7-8 F  3/3/03  2.41
2         Roger     6U F  3/3/03  3.80

Comment: Confused as to how you would filter for Emma though? When I tried `df.loc[df.groupby(['Competitor']=='Emma Slabach').Time.idxmin()]` I'm getting `KeyError: False`
Comment: And there's other columns in the data frame as well, but I specifically need Division, Stack, and Time
Comment: @zainy I just updated my answer: name the groupby result, and then filter result for Emma. Is that more clear ?
Comment: you can groupby only by columns. You can't groupby by expressions (I'm not sure what it would mean). `['Competitor']=='Emma Slabach'` is an expression, not an existing column in the dataframe
Comment: Yeah that makes sense, thank you. Just looking into how I'd delete some columns in the output
Comment: then just select the wanted columns like this: `result.loc[result.Competitor == 'Emma Slabach'][['Division', 'Stack', 'Time']]`
Comment: But the good thing about `result` like in my answer is that you fully leverage the groupby, and get the fastest time for every participant, which is really powerful.
Comment: Thanks! Question: I know we're using idxmin and loc, but is it possible to remove the index while using them?


Dialogflow update context in the console

Question: I have a requirment where I want to append the parameter to context in the frontend screen.
I can do it via webhook as :
1. Get Context Param1 and Parameters Param1
2. Append Context Param1 with Parameters Param1
3. Set Context

But is it possible to do it from the frontend? We can access the context variable using #contextA.variableB. But can we write groovy or some other expression in the Argument section like $variableB+#contextA.variableB ?
I hope you got my ask, let me know if the question is not yet clear, I will try to give brief example as well.
Thanks in advance.
Answer: No.
Through the console alone, context parameters are set to the value of the parameters set from the sample phrases.
If you need to set context parameters to something else, you need to use fulfillment. You can use the built-in fulfillment editor, but you'll need to use something.
Comment: okay thanks. Yes, Google Dialgflow team should come up with something :P
Comment: yes, even that created dialogflow firebase/cloud function in the backend. so ideally both are same.


How can I save all of the images in a Word 2007 document as separate files?

Question: How can I save all of the images/figures in a Word 2007 document as separate files?  Right now I have to save each one separately.  And I can't even save them from within Word -- I have to copy them to PowerPoint and then save them since there doesn't seem to be any way to save them from within Word.
[Note that the trick shown at TechRepublic (http://blogs.techrepublic.com.com/itdojo/?p=135) does not work.  It doesn't work because all of my images are cropped and this trick produces uncropped images.
Similarly, saving as an HTML file doesn't work because the image files linked to in the HTML document are uncropped.]
Answer: Could you not just save the entire document as a full html file? Then open up the folders it creates, they should be saved in there somewhere because they have to be linked into the html.
Comment: This doesn't work for the same reason that the TR trick doesn't work: The separate files are uncropped.


Non model-theoretic, constructive proof that it is valid to introduce new unique constants in a first order theory with equality

Question: I'm currently reading through Mendelson's `Introduction to Mathematical Logic', and one of the proofs has left me dissatisfied.
In general, I am fine with seeing metamathematical results proven using model theory, so long as they are not too fundamental - i.e. if I feel that one could develop a theory without these results that is sufficiently strong to in principle be later used as a metatheory to prove said results in. This is why I am fine with the completeness theorem being proved using model theoretic tools, as I believe that one can develop set theory without it to the point that one could then use that set theory as a metatheory in which model theoretic results can be proved.
I run into a problem with this view in chapter 2.9. of Mendelson's book, however, as a result is proved using model theory that I view as being absolutely funadamental. Proposition 2.28 of this chapter essentially states that if $K$ is a first order theory with equality, and $\vdash_K (\exists ! u)\beta(u, x_1, \dots , x_n)$, then the theory $K^*$ obtained by adding to $K$ a new function letter $f$ of $n$ arguments along with the proper axiom $\beta(f(x_1, \dots, x_n), x_1, \dots , x_n)$ and instances of other logical axioms that need be amended is in a sense `equivalent' to $K$. There is an effective procedure which shows that any theorem provable in $K^*$ is also provable in $K$ (and vice versa, of course).
I view it as fundamental that one may introduce new constants whenever one has shown unique existence, without adding strength to a theory, but the proof this book uses for this is model theoretic and non-constructive.
The author acknowledges this later on, stating that Kleene gives a constructive syntactical proof in his 1952 text `Introduction to metamathematics' but I cannot easily get a hold of this book in order to see the proof.
I am wondering here if anyone would be able to give the proof, or at least an outline, or direct me to where I can find a proper, syntactical proof of the theorem in Mendelson's book. I would like to at least be able to view the page of Kleene's book in which the result is proved, and if it looks good enough I'll buy the text (since I imagine the proof will rely on earlier lemmas I'd need to dig into), but so far I haven't be able to find a preview of the page.
Comment: See George Tourlakis, [Lectures in Logic and Set Theory. Volume 1: Mathematical Logic](https://books.google.it/books?id=AHvoluqx7uoC&pg=PA112) (2003): **Ch.I.7. Defined Symbols**, page 112-on: **Th.I.7.1 Metatheorem (Elimination of Defined Symbols: I)** and **Th.I.7.3 Metatheorem (Elimination of Defined Symbols: II)**
Answer: To be precise in what follows, here are what I am assuming are the axioms:

$(\beta\rightarrow (\alpha\rightarrow \beta))$
$((\alpha\rightarrow \beta)\rightarrow ((\alpha\rightarrow (\beta\rightarrow \gamma))\rightarrow (\alpha\rightarrow \gamma)))$
$(((\alpha\rightarrow \bot)\rightarrow \bot)\rightarrow \alpha)$
$(\forall x (\varphi\rightarrow \psi) \rightarrow (\varphi\rightarrow \forall x \psi))$ whenever $\varphi$ and $\psi$ are wffs, $x$ is a variable, and $x$ is not free in $\varphi$
$\forall x \varphi(x)\rightarrow \varphi(y)$ whenever $\varphi(x)$ is a wff with free variable $x$, $y$ is a variable or constant, and no free occurence of $x$ in $\varphi(x)$ is within the scope of a $\forall y$
$(t=t)$ whenever $t$ is a term
$((x=y)\rightarrow (\varphi \rightarrow \psi))$ whenever $x$ and $y$ are variables or constants, $\varphi$ and $\psi$ are wffs, and $\psi$ is obtained by substituting $y$ for some free occurrences of $x$ in $\varphi$.

Along with the rules of inference given by Modus Ponens and Generalization.
The main tool to use after this is the Deduction Theorem, which I assume if fundamental enough that you're familiar with it.
Something additional I will assume you'll be fine with is the fact that if $\Phi$ is a consistent set of sentences in a signature $\sigma$, then expanding $\sigma$ with new constants (giving, say, $\sigma'$) still leaves $\Phi$ consistent.  Basically, the proof is that we can transform any proof of $\bot$ from $\Phi$ over $\sigma'$ into a proof of $\bot$ from $\Phi$ over $\sigma$ by replacing any newly-used constants with unused variables.
This same idea is used to show that if $\Phi \vdash \exists x \varphi(x)$ then $\Phi \cup \{\varphi(c)\}$ is consistent (over the new language), where $c$ is some new constant.  Indeed, suppose for the sake of a contradiction that $\Phi \cup \{\varphi(c)\} \vdash \bot$, so that by the Deduction Theorem we have $\Phi \vdash (\varphi(c) \to \bot)$.  Take the proof of $\varphi(c) \to \bot$ and turn it into a proof of $\varphi(x) \to \bot$, using the fact that relative to $\Phi$ there isn't anything special about the constant $c$ and so replacing it with any other constant or variable shouldn't affect the validity of the proof.  By generalization, we find that $\Phi \vdash \forall x (\varphi(x) \to \bot)$.
Now, $\Phi \vdash \exists x \varphi(x)$ by hypothesis.  $\exists x \varphi(x)$ is the same as $\neg \forall x \neg \varphi(x)$, or $((\forall x (\varphi(x) \to \bot))\to \bot)$.  But we've shown that $\Phi \vdash \forall x (\varphi(x) \to \bot)$, and so by Modus Ponens we have $\Phi \vdash \bot$, contradicting the assumed consistency of $\Phi$.
At this point we can prove your result (though what we've done above is remarkably close). Suppose $\Phi \vdash \exists u \varphi(u,x_1,\ldots, x_n)$ for every $x_1,\ldots, x_n$.  Then we can choose for $x_1,\ldots, x_n$ a constant symbol $c_{x_1,\ldots, x_n}$ and add $\varphi(c_{x_1,\ldots, x_n},x_1,\ldots, x_n)$ to $\Phi$. From the above, the resulting theory is consistent.
Now add a function symbol $f$ and add the sentences $f(x_1,\ldots, x_n)=c_{x_1,\ldots, x_n}$ to $\Phi$. Now all we need to do is show that the resulting theory is consistent. But this follows almost immediately from the same kinds of arguments from above: if we have a proof of $\bot$, we can just replace any instance of $f(x_1,\ldots, x_n)$ with $c_{x_1,\ldots, x_n}$ to get the necessary contradiction.
Comment: This seems to work, so thank you, might need to puzzle over some small bits but I think that's just an issue on my end
Comment: Correct me if I'm wrong, but I think you've only proved that the new system is consistent, not that there is a transformation F between K and $K^*$ such that if one can prove $F(\Phi)$ in $K^*$ then one can prove $\Phi$ in K. Mendelson's theorem implies, I believe, that the new theory $K^*$ is no stronger than K.
Comment: If you have access to Mendelson's book it might be a good idea to see which theorem I am referring to, as I gave mostly a synopsis in my question
Comment: @Nethesis Ah, I missed that aspect of your question.  I don't have access to Mendelson's book, but I would imagine you can finagle up some such $F$ in the same way that we can transform any proof using $f(x_1,\ldots, x_n)$ with $c_{x_1,\ldots, x_n}$, and then do similarly with any use of $c_{x_1,\ldots, x_n}$ and a formula involving $\exists u \varphi(u,x_1,\ldots, x_n)$, but I don't have the time to flesh that out.
Comment: It is okay, in retrospect I should have added more detail. I managed to find Kleene's proof so the problem's been sorted.
Answer: I have managed to track down Kleene's book, the proof is very complex comparatively, but seems sufficient. I've decided to post a few pictures of his proof for anyone who later looks, hopefully this is allowed, if not I'll take them down:
https://i.stack.imgur.com/KTm9N.jpg
If any future readers see this, know that you may need to actually get ahold of the book in order to fully follow the proof, though what is given there is pretty well written in my opinion. At the very least it may convince you to get the book, or be satisfied that a syntactic proof exists.


How to get an integral type which represents integers from -512 to +511? How to get an integral type which represents integers from -256 to +256?

Question: I'm a beginner in C#.
I'm looking for an integral type to represent integers from -512 to +511
(512 = 2^9)
and also an integral type to represent integers from -256 to +255
(256 = 2^8)
I have found the integral type sbyte which represents integers from -128 to +127
(128 = 2^7)
but it's not what I'm looking for.
Comment: http://msdn.microsoft.com/en-us/library/exx3b86w.aspx
Answer: short (an alias for System.Int16) will cover all these use cases.
It has a range from -32768 to +32767.
Answer: Any integral type 2 bytes or larger will allow these numbers. short (16-bit) is the smallest of these.
In programming; we don't define data types based on range, but on how much memory they use. The sizes are always in whole bytes, and some power of 2. Then we pick a data type with a large enough range (presumably the smallest necessary to save memory, though memory is cheap now).
A list of integral types can be found on MSDN.


How To Set Up Shure BLX4/SM58 And What Other Components Are Needed

Question: So I've just bought a Shure BLX4/SM58 but am stuck when it comes to setting up. And of course it does not work by itself and needs some sort of stereo or PA system to make the sound work, so what cheap option do u suggest for this and how to overall set it up. Any information would be greatly appreciated.
Comment: Don't take this the wrong way, but... you bought 300 quid's worth of kit without having the faintest idea what to do next???
Comment: @Tetsujin well, some people will spend £300 (or even £3,000) on an item of clothing, and then never wear it because they don't like the colour! Humans are not renowned for being logical.
Comment: I wonder why SE "bumped" this old question...  The main question is vague and the secondary question is an off-topic product recommendation request.  Hopefully OP figured it out in the meantime.
Answer: The channel-matching between mic and receiver is fully described in the printed manual.  If you've lost yours, here's a download.
https://pubs.shure.com/guide/BLX/en-US
Yes, you'll need a PA system to run it through.   Same as you would if you'd bought a mic with a cable.  They come in all sizes!  Maybe the venue you'll be performing in has one that they'll let you plug into.  What sort of work are you thinking of doing?
Comment: If you're only recording, why did you buy a wireless mic?
Comment: Thanks for the info, so as a cheap alternative could I connect the BLX4 receiver into a stereo speaker via an aux lead for the time being until upgrading to a PA having blown budget on mic itself as I can control the volume on that or do u know of an affordable PA? All this is for a band I have started with my mates which we upload covers and originals on to YouTube.
Comment: It was only cause I was recommended by a friend to buy this as our WHOLE band is electric so it would save space and could also be used for performances outside of recording where we would be required to bring our own equipment, so would an aux Cable be ok?!
Comment: Not sure how having a mic, receiver, power supply and cable saves space over having just a mic and cable!  But yes, you can connect it into just about anything which includes an amplifier and a speaker.
Comment: JKidd: it might help if you added more context. So you sing in a band? Do you have a rehearsal room? Does that rehearsal room have a PA system, or any general-purpose amps (keyboard amp etc.) that have spare inputs? What kinds of amps are your bandmates using?


Maximum likelihood estimator for variance in two linear models

Question: I am learning MLE's at my inference class and this is a problem I came accross.
Consider two simple linear models.
$y_{1j}=\alpha _1+\beta_{1}x_{1j}+\epsilon_{1j}$ and
$y_{2j}=\alpha _2+\beta_{2}x_{2j}+\epsilon_{2j}$  , $ j=1,2,...,n>2$ where $ \epsilon_{ij}$~$N(0,\sigma^2)$  ,
$\epsilon$ are independent and identically distributed.
Obtain the maximum likelihood estimators of $\sigma^2$.
For this can I use only one equation of the two .
Can I find with only using $y_{1j}=\alpha _1+\beta_{1}x_{1j}+\epsilon_{1j}$  and would it be the same answer I would get had I used the other equation
Comment: Cross posted here: http://www.talkstats.com/showthread.php/56616-Maximum-likelihood-estimator-in-linear-model
Comment: We welcome HW questions, @sam_rox, but we treat them differently. Please tell us what you understand thus far, what you've tried & where you are stuck, & we'll try to provide hints to get you unstuck. To better understand the process, you should read the [wiki](http://stats.stackexchange.com/tags/self-study/info) for the `[self-study]` tag.
Comment: Talkstats is outside the SE system, @Dason. In some sense it seems inconsiderate that it's posted in multiple places, & this fact isn't mentioned, but it isn't really against any rule that I know of.
Comment: @gung : Even in that post the problem still remains unsolved. I know how to solve this if there was a single equation of the form $y_{ij}=\alpha _i+\epsilon_{ij}$.  There Since $y_{ij}$ has  a normal distribution I computed $E(y_{ij})$ and$ V(y_{ij})$ and fould likelihood function.But here there are two equations and although $y_{1j}$ and $y_{2j}$ are normally distributed how can I find expected and variance values.Should I consider only one of those given equations and take it's expected and variance
Comment: @gung: .Or as was in the post http://www.talkstats.com/showthread.php/56616-Maximum-likelihood-estimator-in-linear-model should I take $ E(y_{1j})=E(y_{2j}) $and construct a likelihood function as given there.
Comment: sam - thanks for including your thoughts, but they'd probably be better edited into the post
Comment: You need to use all the data. One way is to write the pair of equations as a single multiple regression via dummy variables. A second way you could approach it is simply to write the likelihood in terms of the errors.
Comment: @Glen_b : If i write the likelihoods in term of errors since error are independent I could multiply the two distributions for $\epsilon_{1j}$ and $\epsilon_{2j}$ to get the joint p.d.f right
Comment: @gung I never said it was formally against any rules - just pointing out that I noticed the cross post.  If it got answered there that might influence if people want to answer it here or not.
Comment: sam: yes, but since those two $j$'s aren't connected, if you're doing it that way I'd write the likelihood for the two sets of $\epsilon$s and multiply those.
Comment: @Glen_b  :that means $L(\epsilon_1)*(L\epsilon_2)$.Without having j for both equations I should have something like j for one equation and k for the other
Comment: Yes, but those likelihoods run over all j and k
Answer: Estimators do not exist "out there", and we are in the search of determining the "best" way to "find" them. As functions, they may have the same general structural form, but their results, the estimates, depend on the input that we will give them.
The OP states two different models. In order for these models to have any relation to estimation, they must be accompanied each by its own sample of observations, which is presumably the case. Then by applying maximum likelihood estimation, we will obtain one estimate, if we use only the one sample, another estimate if we use only the second sample, and yet a third estimate, if we use both samples. And all will be "maximum likelihood" estimates, each being the argmax of a different log-likelihood, since in each case the conditioning sample will be different.
Since the assumption is that all $\epsilon$'s are i.i.d. random variables, the two samples can be pooled, and the joint density / likelihood be written as the product of $n+n$ marginal normal densities. Then take logarithms etc.
Can we say anything about which of the three MLE's is "better" to use? Of course this requires defining a criterion against which the three MLE's will be judged (eg. Mean Squared Error-MSE). Instinctively, we would go with the one that uses both samples as one (larger sample).
Finally, an interesting and instructive option one could consider, is to see what would happen (in terms of estimator properties), if one obtained the two MLE's separately from the two samples, and consider some combination of them. Under the assumed normality, the finite sample distribution of the variance estimators is known. A related post to this option (but not in a regression context) is this one.


How to replace data in html form with JavaScript

Question: I have created an HTML form with three fields. Field A for input text, and fields B and C for number input.
I created a function to calculate B i C, and to output data from A,B and C onto the page.
How can I make it so that field A must be filled in, and fields B and C must be a positive value?
HTML:
<!DOCTYPE html>

    <title>Tax calculator</title>
    <meta charset="UTF-8">

        Field A:<input id="name" type="text">
        Field B:<input id="tBas" type="value">
        Field C:<input id="tRat" type="value">
        <button id="calc">Calculate !</button>

JavaScript:
function calculate() {
    var name = document.getElementById('name').value;
    var base = parseFloat(document.getElementById('tBas').value);
    var rate = document.getElementById('tRat').value;

    var taxPayer = ("First and last name: ") + (name);
    var taxIncome = ("Income for taxation: ") + ((base).toFixed(2));
    var taxRate = ("Tax rate: ") + (rate) + ("%.");
    var taxToPay = ("You need to pay: ") + ((base * rate / 100).toFixed(2));

    document.getElementById('name').innerHTML = taxPayer;
    document.getElementById('income').innerHTML = taxIncome;
    document.getElementById('rate').innerHTML = taxRate;
    document.getElementById('result').innerHTML = taxToPay;
}

document.getElementById('calc').addEventListener('click', calculate);

Comment: For field B and C `type="value"` to  `type="number" min=0` ; Use required for field A
Comment: _"How to apply in JS..."_ - Why JavaScript? Those input elements should be in a form and then just use the built-in form validation.
Comment: Because I attend course and haven't yet passed unit consider built-in form validation...
Answer: You don't need to use JS for this trick
To have the input filled set it as
<input id="name" type="text" required>

Then to have an positive value
<input id="tBas" type="number" min=0 >

Answer: To check if a field is filled, you can just compare his value to "".
To check if a field has a positive value, you can use parseInt to cast your value (which is a string) into an integer and then compare it to 0 > 0.
Something like that should do the trick !

function calculate() {
  var name = document.getElementById('name').value;
  var base = parseFloat(document.getElementById('tBas').value);
  var rate = document.getElementById('tRat').value;

  if (name != "" && parseInt(base) > 0 && parseInt(rate) > 0) {
    var taxPayer = ("First and last name: ")+(name);
    var taxIncome = ("Income for taxation: ")+((base).toFixed(2));
    var taxRate = ("Tax rate: ")+(rate)+("%.");
    var taxToPay = ("You need to pay: ")+((base*rate/100).toFixed(2));

    document.getElementById('name').innerHTML = taxPayer;
    document.getElementById('income').innerHTML = taxIncome;
    document.getElementById('rate').innerHTML = taxRate;
    document.getElementById('result').innerHTML = taxToPay;
  }
}

document.getElementById('calc').addEventListener('click', calculate);
<!DOCTYPE html>

        <title>Tax calculator</title>
        <meta charset="UTF-8">

          Field A:<input id="name" type="text">
          Field B:<input id="tBas" type="value">
          Field C:<input id="tRat" type="value">
          <button id="calc">Calculate !</button>

Comment: This is it. Thank you ! After your help I added this:else {
alert("Must fill First and last name !!! Must fill positive value for income !!!");
   }
Answer: IDs should be uniq. You should use another id to you div#name.
For instance, into your html code:

And then, into your script
document.getElementById('div_name').innerHTML= taxPayer;


while using d3js my json file didn't read got error

Question: XMLHttpRequest cannot load file:///C:/Users/HP/Desktop/tree.json. Cross         origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
my code is
<!DOCTYPE html>

        <meta charset="utf-8">

and json
{
    "name": "Clifford Shanks",
    "born": 1862,
    "died": 1906,
    "location": "Petersburg, VA",
    "parents": [{
        "name": "James Shanks",
        "born": 1831,
        "died": 1884,
        "location": "Petersburg, VA",
        "parents": [{
            "name": "Robert Shanks",
            "born": 1781,
            "died": 1871,
            "location": "Ireland/Petersburg, VA"
        }, {
            "name": "Elizabeth Shanks",
            "born": 1795,
            "died": 1871,
            "location": "Ireland/Petersburg, VA"
        }]
    }, {
        "name": "Ann Emily Brown",
        "born": 1826,
        "died": 1866,
        "location": "Brunswick/Petersburg, VA",
        "parents": [{
            "name": "Henry Brown",
            "born": 1792,
            "died": 1845,
            "location": "Montgomery, NC"
        }, {
            "name": "Sarah Houchins",
            "born": 1793,
            "died": 1882,
            "location": "Montgomery, NC"
        }]
    }]
}

Answer: in your code you have  d3.json( " tree.json", function(error, json) which use HTTP GET method.
This error is because you are just opening html documents directly from the browser you need a HTTP Web Server to serve your json file
to run without server by avoid Get Request

var json  = {
    "name": "Clifford Shanks",
    "born": 1862,
    "died": 1906,
    "location": "Petersburg, VA",
    "parents": [{
        "name": "James Shanks",
        "born": 1831,
        "died": 1884,
        "location": "Petersburg, VA",
        "parents": [{
            "name": "Robert Shanks",
            "born": 1781,
            "died": 1871,
            "location": "Ireland/Petersburg, VA"
        }, {
            "name": "Elizabeth Shanks",
            "born": 1795,
            "died": 1871,
            "location": "Ireland/Petersburg, VA"
        }]
    }, {
        "name": "Ann Emily Brown",
        "born": 1826,
        "died": 1866,
        "location": "Brunswick/Petersburg, VA",
        "parents": [{
            "name": "Henry Brown",
            "born": 1792,
            "died": 1845,
            "location": "Montgomery, NC"
        }, {
            "name": "Sarah Houchins",
            "born": 1793,
            "died": 1882,
            "location": "Montgomery, NC"
        }]
    }]
}

var margin = {
                top: 0,
                right: 320,
                bottom: 0,
                left: 0
            },
            width = 960 - margin.left - margin.right,
                height = 500 - margin.top - margin.bottom;

            var tree = d3.layout.tree()
                .separation(function(a, b) {
                return a.parent === b.parent ? 1 : .5;
            })
                .children(function(d) {
                return d.parents;
            })
                .size([height, width]);

            var svg = d3.select("body").append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                var nodes = tree.nodes(json);

                var link = svg.selectAll(".link")
                    .data(tree.links(nodes))
                    .enter().append("path")
                    .attr("class", "link")
                    .attr("d", elbow);

                var node = svg.selectAll(".node")
                    .data(nodes)
                    .enter().append("g")
                    .attr("class", "node")
                    .attr("transform", function(d) {
                    return "translate(" + d.y + "," + d.x + ")";
                })

                node.append("text")
                    .attr("class", "name")
                    .attr("x", 8)
                    .attr("y", -6)
                    .text(function(d) {
                    return d.name;
                });

                node.append("text")
                    .attr("x", 8)
                    .attr("y", 8)
                    .attr("dy", ".71em")
                    .attr("class", "about lifespan")
                    .text(function(d) {
                    return d.born + "–" + d.died;
                });

                node.append("text")
                    .attr("x", 8)
                    .attr("y", 8)
                    .attr("dy", "1.86em")
                    .attr("class", "about location")
                    .text(function(d) {
                    return d.location;
                });
           ;

            function elbow(d, i) {
                return "M" + d.source.y + "," + d.source.x + "H" + d.target.y + "V" + d.target.x + (d.target.children ? "" : "h" + margin.right);
            }


Angular filter for currency to allow typing negative numbers

Question: I have a directive that filters currency by adding a decimal point as the user types.
My problem is that it will not allow negatives. It would be nice to allow a user to type a '-' sign and have it always appear at the beginning of the number, or type a '+' and have it disappear.
Needs:

Format decimal field as user types
Field must be a number
Must allow negatives -
Allow 0.00 as a number input

Check out my  Plunker here . It has input = number but does not allow negative numbers:
app.directive('format', ['$filter', function ($filter) {
    return {
        require: 'ngModel', //there must be ng-model in the html
        link: function (scope, elem, attr, ctrl) {
            if (!ctrl) return;

            ctrl.$parsers.unshift(function (viewValue, modelValue) {
                var plainNumber = viewValue.replace(/[^-+0-9]/g,'');

                // use angular internal 'number' filter
                plainNumber = $filter('number')(plainNumber / 100, 2).replace(/,/g, '');

                // update the $viewValue
                ctrl.$setViewValue(plainNumber);

                // reflect on the DOM element
                ctrl.$render();

                // return the modified value to next parser
                return plainNumber;
            });
        }
    };
}]);

Comment: Is there a reason you're not using the [built in currency filter](https://docs.angularjs.org/api/ng/filter/currency)? *edit: I see your other question [here](http://stackoverflow.com/questions/38062482/money-formatting-directive-in-angular). The demo on angular's currency filter DOES add the 0s to the input. I don't understand why it's insufficient for you.
Comment: in fact, looking at your post history, you have asked the same question **4!** times.  Asking more than once isn't going to make it more likely to get an answer, and in fact it makes it harder for others who might have a similar issue.
Comment: and to echo what @adamdport stated, how exactly is this question different from the first question you asked?  the built in currency filter does indeed satisfy ***all*** of the requirements that you have asked about from both questions, unless you aren't using it correctly.
Comment: @jenryb Your code was good, it just needed a small modification to work correctly. Check answer for details.
Comment: @Claies sorry for the duplicates. I think I was asking too much in the first so I broke it down here. I think I should have been more clear about why the ng-currency filter wasn't working. It does NOT fulfill my requirements, as adamdport found once trying the plunkers I've supplied. There is a chance I'm not using it to its full potential, in that case please supply an answer with an example.
Comment: you mention in one comment on one post that you want to start at the hundredths place with the filter.  In none of your questions where you list requirements do you list that.  If that is an additional requirement, you should update the single question that is still open and add the additional requirement.  that being said, your best approach would be to study the source for the currency filter, and recreate that filter with the additional requirements. https://github.com/angular/angular.js/blob/master/src/ng/filter/filters.js#L7
Comment: @Claies, gotcha. Edited the original to be more clear. Also added a bounty to it if you're interested.
Answer: This will do exactly what you want it to do:
var app = angular.module('App',[]);

 app.controller('MainCtrl', function ($scope) {

});

 app.directive('format', ['$filter', function ($filter) {
 return {
            require: 'ngModel', //there must be ng-model in the html
            link: function (scope, elem, attr, ctrl) {
                if (!ctrl) return;

                ctrl.$parsers.unshift(function (viewValue, modelValue) {
                    var plainNumber = viewValue.replace(/[^-+0-9]/g,'');
                    var newVal = plainNumber.charAt(plainNumber.length-1);
                    var positive = plainNumber.charAt(0) != '-';
                    if(isNaN(plainNumber.charAt(plainNumber.length-1))){
                      plainNumber = plainNumber.substr(0,plainNumber.length-1)
                    }
                    //use angular internal 'number' filter
                    plainNumber = $filter('number')(plainNumber / 100, 2).replace(/,/g, '');
                    if(positive && newVal == '-'){
                      plainNumber = '-' + plainNumber;
                    }
                    else if(!positive && newVal == '+'){
                      plainNumber = plainNumber.substr(1);
                    }
                    plainNumber.replace('.', ',');
                    //update the $viewValue
                    ctrl.$setViewValue(plainNumber);
                    //reflect on the DOM element
                    ctrl.$render();
                    //return the modified value to next parser
                    return plainNumber;
                });
            }
        };

}]);

Just remove the type="number" from:
<input ng-model="amount" format="number" />

Comment: One more thing, do you know how I could change the period to a comma? Also the directive won't let me clear the field, do you know why?
Comment: Check edit for comma and for clearing, you cannot because the number filter causes it to format to a decimal number all the time
Comment: Why you remove best answer?
Comment: Sorry, mistake. I put it back. Using your answer plnkr.co/edit/zUT4cyqtbs3Xn7J7oapj?p=preview I still cannot put in a negative as the first entry. Also the change for the comma is not working.