How to make custom Drush commands to work on remote instance

Question: I have developed custom Drush commands that includes some shell commands all which work locally. I would like them to work also on the remote instance with aliases that have the remote settings. Here is how the shell commands are currently executed:
//executes command
function execute_command($command)
{
    drush_log(dt('COMMAND: @command', array('@command' => $command)), 'notice');
    //any shell command fore example 'cp some/source dest/dir','tar xvf some.tgz',etc
    drush_shell_exec($command);
    drush_log(drush_shell_exec_output(), 'debug');
}

So, I would like to wrap this into some Drush API so they also execute on remote instance. Is it possible? How should I make the shell commands part of my custom Drush commands to run on the remote instance when user does something like:
drush @remote-alias custom-command

Thank You
Answer: I believe the remote site also has to have the commands as well in order to execute successfully.
Comment: Oh my god! its working....ups one issue: sudo: no tty present and no askpass program specified Any idea?
Comment: Did you have to add the commands to the remote site?
Comment: yes. The Drush custom commands have to be installed on the remote instance to work
Comment: As I thought. Also, consider version controlling commands so if you change them you can issue a git pull on the remote server to keep everything in sync.
Comment: You should be able to get around your sudo problem by creating a sudoers file - tho that is off-topic for this board.


Does VMware ESx server run a operation system of its own to manage the the hardware(like a host OS) inside of VMware ESx server

Question: Does VMWare ESXi software run a host operating system in itself (bare metal hypervisor). I know that the vSphere client is used to manage the VM's created inside of the server but what about the management of other things inside of the server.
Answer: VMWare's ESXi is a bare metal hypervisor and little more, it does have a *nix-like user interface that's switched off by default that allows for some very specific operations to be carried out but it's really got nothing directly to do with the running of guest VMs and can be ignored by most users.
In terms of creating and managing guest VMs there's a number of ways to do this including a number of CLI methods, the built-in web-based interface and also the more enterprise-oriented vCenter method too.
Can I suggest VMWare's 'vSphere Install, Manage and Configure' course as a great starter in these products.
Comment: Thank you for the guidance,but can you elaborate about the unix like interface which is switched off, so how is it used and for what purpose?
Comment: There's a range of things you can do with it but most or all of them are available via the client-based CLI's - in particular the PowerCLI is very powerful and there's lots of existing scripts out there available for free to help with these things. To be honest though you really do sound like you'd benefit from some training, vSphere isn't the easiest thing to just pick up and go.
Comment: Thank you, I would look into some training courses and deeper learning about this.
Comment: Leaving the marketing bs aside, any system capable of performing actions and interacting with hardware is an OS. It might be scaled down to the bare minimum, or even pulled out into a secondary OS, like Xen's Dom0, but it's still an OS


interesting scalene triangle trigonometry problem

Question: the problem is to find the minimum value of cos(2α)+cos(2β)+cos(2γ) in a scalene triangle. So what should the value of α,β, and γ be?
I already transformed the expression using γ=180∘−(α+β) to cos(2α)+cos(2β)+cos(2α+2β)
so how can I finish the problem if this is a good way?
Thank you
Comment: Is answer is $\displaystyle \frac{3}{4}$
Answer: Given $A+B+C = \pi$ and $$\cos 2A+\cos 2 B+\cos 2C = 2\cos(A+B)\cos(A-B)+\cos 2C$$
So $$\cos 2A+\cos 2B+\cos 2C = -2\cos C\cdot \cos(A-B)+2\cos^2 C-1$$
$$ = -2\cos C\left[\cos(A-B)-\cos(C)\right]-1=-2\cos C\left[\cos(A-B)+\cos(A-B)\right]$$
$$ = -4\cos A \cos B\cos C-1$$
So $$\cos 2A+\cos 2B+\cos 2C = -1-4\cos A\cos B\cos C\geq -1+\frac{4}{8}=-\frac{3}{2}$$
Above we have used $$\cos A\cos B\cos C\leq \frac{1}{8}$$
and equality hold when $\displaystyle A=B=C=\frac{\pi}{3}$


Understanding the following summation

Question: I have come across the following in my textbook and I am a little confused by it
$$\cosh(\pi y )\cos(\pi x) = \sum_{n=0}^\infty q_n(y) \cos(n\pi x) $$
why are the following three cases the way they are?
$$q_0 = 0$$$$ q_1 = \cosh(\pi y )$$$$q_n = 0, n\geq 2 $$
how do I determine those, do I plug $n=0,1,2$ in?
for instance for $n=0$
$$\cosh(\pi y )\cos(\pi x) =  q_0(y) \ $$
but that doesn't give $q_0 = 0 $
Answer: The summation means
$$
\sum_{n=0}^\infty q_n(y)\cos(n\pi x)=q_0(y)+q_1(y)\cos(\pi x)+q_2(y)\cos(2\pi x)+\ldots.
$$
The only possibility to get a term identical to $\cosh(\pi y)\cos(\pi x)$ is setting all to 0 except for $n=1$. Only then you choose $q_1(y)=\cosh(\pi y)$ and you are done.
Comment: thanks so much, very clear explanation

Understanding the following summation


Upper bound for $u_n(z) = n^{-2}\sec (\pi z / 2n)$

Question: I've been working through past exam papers for an Analysis exam that's coming up. This question has had me tearing my hair out, and I would appreciate some help:
Use the Weierstrass M-test to prove that:
$f(z) = \displaystyle \sum^\infty_{n=1}u_n(z)$ is continuous on $\mathbb{C} \backslash \mathbb{Z}$, where $u_n(z) = n^{-2}\sec(\pi z / 2n)$.
Hint: $|\cos z | \geq |\cos (\mathrm{Re} z)|$

I understand how the M-test works, I need to find bounds $M_n > |u_n(z)|$ such that $\sum M_n$ converges. Then the sum converges uniformly, so $f$ is continuous. The difficulty in the question is that $u_n(z)$ is unbounded on the domain (which can be restricted to $\mathbb{R} \backslash \mathbb{Z}$ using the hint).
In order to use the M-test, I need to find a 'trick', and I just can't see it. I've considered things like:

grouping terms together so that they 'cancel', and become bounded. For example, $|\cos(x)| + |\cos(2x)|$ is bounded below.
trying to convert this into a geometric series via exponentials, which works for series like $\sum \cos(k\theta)$

Is it very simple, and I'm just not seeing it? This question (which has other, semi-related parts that I had no problem with) is supposedly designed to be accomplishable in around 40 minutes for studious candidates, and I have spent many times that on it.
Thank you!
Comment: I don't think you can find $M_n$ that works for all $z$, since $u_n$ is unbounded. You need to find a cover for your domain, $U_1,U_2,\dots,$ And for each $U_i$ show uniform convergence. Essentially, you want $U_i$ to be strictly bounded away from the integers.
Comment: Of course, you're right! Attempting to prove that $f$ is uniformly convergent on the whole domain is stronger than necessary to deduce that $f$ is continuous (and probably not even true?), I see that now. Well, I'm embarrassed that the answer was so simple. Could somebody please advise me what I should do with my question (submit my own answer, delete, or something else?)
Answer: Hint: When you can't prove uniform convergence on the entire domain, try showing it instead for each element in an open cover of that domain. So pick $U_1,U_2,\dots$ that cover your domain and for which you can prove uniform convergence on each $U_i$.
Comment: Thank you for this swift, clear answer to what turned out to be a rather dull question.


Como faço para o Django "enxergar" o CSS?

Question: Estou escrevendo uma aplicação Django e Python, e estou com um problema
    na parte de templates, executando localmente o Django achou a template e
    eu consegui visualisar ela através do localhost:8080/home, acontece que a
    folha de estilo (CSS) não esta sendo baixada (localizada) pelo Django,
    ele está exibindo a template em HTML apenas.
A árvore do projeto se encontra da seguinte maneira:
Library
  |_ __init__.py
  |_ admin.py
  |_ models.py
  |_ tests.py
  |_ views.py
  |_ urls.py
  |_ templates
      |_ templates
          |_ index.html
          |_ base.html
          |_ css
          |_ js
          |_ fonts

Meu settings.py:
# -*- coding: utf-8 -*-

"""
Django settings for Chameleon project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

#PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'gb)bi45$q*#()1gbf_1td3x7+7#%3zk4%&)$^f6@8bpndb$a12'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin', #Sistema de administracao Backend
    'django.contrib.auth', #Sistema de autenticao
    'django.contrib.contenttypes', #Tipos de conteudo
    'django.contrib.sessions', #Trata as sessoes
    'django.contrib.messages', #Gerencia mensagens de erro sucesso etc
    'django.contrib.staticfiles', #Gerencia arquivos estaticos (html, CSS, JavaScript)
    'Library', #Adicionando nome do projeto para criação das tabelas no DB
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'Chameleon.urls'

WSGI_APPLICATION = 'Chameleon.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'USER': '',
        'PASSWORD':'',
        'HOST': '',
        'PORT': '',
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'pt-BR'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join

Minha views.py:
# -*- coding: utf-8 -*-
#from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render_to_response

# Create your views here.
def home(request):
    return render_to_response('templates/index.html')

Meu HTML index.html:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <link rel="shortcut icon" href="">

    <title>Chameleon</title>

    <link href="css/bootstrap-responsive.css" rel="stylesheet" >
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/signin.css" rel="stylesheet">

      <form class="form-signin" role="form">

Please sign in

        <input type="email" class="form-control" placeholder="Email" required autofocus>
        <input type="password" class="form-control" placeholder="Senha" required>

          <input type="checkbox" value="remember-me"> Lembre-me

        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
      </form>

Visualizei pelo modo desenvolvedor do navegador que os 3 arquivos CSS
    não estão sendo encontrados, esta retornando 404 not found.
Meu python é o Python27 o Django é o 1.6.2
Comment: "Visualizei pelo modo desenvolvedor do navegador que os 3 arquivos CSS não estão sendo encontrados, esta retornando 404 not found." Consegues ver o caminho do CSS ai? Se sim verifica se está no sitio certo.
Comment: O caminho CSS esta correto!
Answer: Entendo que estejam faltando três coisas para resolver o seu problema:
1) Definir o caminho para os recursos estáticos
Existe uma variável que você adiciona no settings.py, chamada STATICFILES_DIRS, onde você pode adicionar os caminhos para os seus recursos estáticos (arquivos css, js, imagens, etc). Por exemplo:
# Additional locations of static files
STATICFILES_DIRS = (
   '/caminho/para/recursos/estaticos/aqui',
)

No servidor de testes isso é o suficiente, mas em produção também é necessário rodar o python manage.py collecstatic para copiar os arquivos para a pasta certa.
2) Definir o URL dos recursos estáticos
No arquivo urls.py, é necessário fazer uma modificação para que os URLs sejam reconhecidos. Assim:
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... seus URLs aqui
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

3) Adicionar prefixo para arquivos estáticos no template
Também está faltando o prefixo para arquivos estáticos no URL dos CSS.
Você pode resolver assim:
Antes:
<link href="css/bootstrap-responsive.css" rel="stylesheet">

Depois:
{% load staticfiles %}
<link href="{% static "css/bootstrap-responsive.css" %}" rel="stylesheet">

Ou usar o método mais antigo:
<link href="{{STATIC_URL}}css/bootstrap-responsive.css" rel="stylesheet">

Nesta página da documentação do Django (em inglês), estão maiores detalhes a respeito da configuração dos arquivos estáticos.
Answer: Visto que o seu projeto esteja estruturado assim:

Em resumo, como deve ficar configurado para carregar o seu CSS:
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "projeto/static"),
    # '/var/www/static/',
)

urls.py
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = patterns('',
    #suas urls
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Template
Sempre adicione no inicio do seu HTML o {% load staticfiles %}
{% load staticfiles %}
<link href="{% static "css/bootstrap-responsive.css" %}" rel="stylesheet">
<link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet">


Applied statistics vs Mathematical statistics

Question: The Help Center for this site says we can ask question about, among other things, mathematical statistics.
I am curious to find out what mathematical statistics is. And I thought it might be easier for people to explain something in contrast to another thing. So the question I put forward is,
What is mathematical statistics, as opposed to applied statistics?
Comment: **Good** statistics is both applied and mathematical.
Comment: To all those who think the original question was bad, I have rewritten it.
Answer: There are not only mathematical statistics and applied statistics, but also statistics (in general). You could say that statistics is about why and applied statistics is about how. Mathematical statistics is a branch of mathematics and generally a scientific discipline (the same as statistics). Applied statistics, on the other hand, is a term commonly used to name courses for non-mathematically oriented audience, that teach you how to apply statistical tools for the purpose of data analysis. You can find multiple applied statistics handbooks named like: "Discovering Statistics Using SPSS", "Statistics for Social Science" etc. Applied statistics is often applied by non-statisticians, e.g. researchers doing their projects. However, this doesn't mean that statisticians do not apply statistics, but rather it's applied statistics that is not interested in researching statistical theory, but rather it's applications. Statistics is concerned about statistical problems, while applied statistics about using statistics for solving other problems.
There are journals on applied statistics that promote development of statistical tools (see below).
Examples that could give you a scope on what applied statistics is:

Journal of Applied Statistics provides a forum for communication
  between both applied statisticians and users of applied statistical
  techniques across a wide range of disciplines. These areas include
  business, computing, economics, ecology, education, management,
  medicine, operational research and sociology, but papers from other
  areas are also considered. The editorial policy is to publish rigorous
  but clear and accessible papers on applied techniques. Purely
  theoretical papers are avoided but those on theoretical developments
  which clearly demonstrate significant applied potential are welcomed.
  The Journal aims for a balance of methodological innovation, thorough
  evaluation of existing techniques, case studies,speculative articles,
  book reviews and letters.

(source)
or:

The Journal of the Royal Statistical Society, Series C (Applied
  Statistics) (...) is concerned
  with papers which deal with novel solutions to real life statistical
  problems by adapting or developing methodology, or by demonstrating
  the proper application of new or existing statistical methods to them.
  (...) A deep understanding of statistical methodology is not necessary to
  appreciate the content. Although papers describing developments in
  statistical computing driven by practical examples are within its
  scope, the journal is not concerned with simply numerical
  illustrations or simulation studies. The emphasis of Series C is on
  case-studies of statistical analyses in practice.

(source)
or aims of applied statistics courses:

The MSc in Applied Statistics will aim to train you to solve
  real-world statistical problems. When completing the course you should
  be able to choose an appropriate statistical method to solve a given
  problem of data analysis and communicate your results clearly and
  succinctly. The course aims to equip you with the computational skills
  to carry through the analysis and answer the problem as presented. (...)

(source)
I didn't give here a broad review on what statistics or mathematical statistics are, but it should be self-explanatory since I given you examples on how does applied statistics differ from them.
Comment: There are plenty of things that are not scientific disciplines that one can obtain a PhD in, so whether or not applied statistics is a scientific discipline, that would not be a basis on which to decide whether one could do a PhD in it.
Comment: @Glen_b-ReinstateMonica Statistics is less a *science* than a [*formal science*](https://en.wikipedia.org/wiki/Formal_science) along with mathematics, logic, computer science, information theory, complex systems theory, game theory, etc.
Answer: If you're simply taking a book on techniques and learning how to plug things into R/SAS/STATA, you're really not doing applied statistics, imo. The best applied statistics courses/programs involve a healthy dose of theory. The difference between the two really is one of emphasis. In an applied course, you're learning to use techniques, whereas in "pure" stats courses you're learning to develop or prove things.
So in a good applied regression class, you'll see the proof that, say, the coefficients in OLS regression are the MLE, assuming the errors are Gaussian. You might remember this, along with the implication that this means the coefficients are efficient estimators, as reasons that OLS is "good." But aside from remembering this (maybe you get a question on the test worth a few points as to why OLS is "good," and you'll have to write down this fact), and maybe a homework question asking you to prove some implication of this fact, you're unlikely to use that proof again.
In a "pure" stats class, however, the proof is the class.  You might not even see how this fact is used in the "real world." You're more interested in how the proof works, because at some point in the future you might want to prove that the estimator you're developing is an MLE.
Put differently, at my university, the graduate Applied Regression course uses a fair amount of proofs in class, and you have a hard time passing if you don't know calculus and linear algebra.  But the homeworks and exams are mostly about interpreting data.  In the PhD-level GLM course, however, they never so much as download a dataset.


Não consigo deixar a barra do menu corretamente

Question:
Meu html:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Ensintech</title>
<link rel="stylesheet" href="lib/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/style-mobile.css">

Área administrativa / Docente

Área do Aluno

                Acesso Aluno

                Digite seus dados de login para acessar o sistema

            <form action="act_login.cfm" method="post" target="escondido">

                    <input type="email" class="form-control " id="email" placeholder="E-mail">

                    <input type="password" class="form-control" id="password" placeholder="Senha">

            </form>
            <button id="entrar" type="submit" class="form-control">Entrar </button>

© 2018 - Ensintech - Todos os direitos reservados

Meu css normal:
html{
    font-family: sans-serif;
}

header{
    width:100%;
    height:58px;
    background-color: #693;
    border-bottom: 6px solid #487f1e;
}

 header #logotipo{
    margin-left: 50px;
    margin-top: -50px;
    position:absolute;
 }
body{
    display: block;
    width: 100vw;
    height: 100vh;
    background:url(../img/Testing-banner2.jpg) no-repeat;
    background-size:cover;
    background-attachment: fixed;
    font-size:16px;
    overflow-x:hidden;
    margin:0;
    padding:0;
}
#centro {
    position:absolute;
    top:18%;
    left: 50%;
}
nav#menu {
    display:inline;
}
#menu ul {
    padding:12px;
    margin-left: 240px;
    background-color:#693;
    list-style:none;
    position:relative;
}
#menu ul li {
    display: inline;
}
#menu ul li a {
    color:#fff;
    padding: 2px 10px;
    display: inline-block;
    text-decoration: none;
    background:#693;
}
#menu  li a:hover {
   background-color:#487F1E;
}
header #logotipo:hover {
     background-color:#487F1E;
}
#entrar:hover{
    background-color:#487F1E;
    border-bottom: 4px solid #2c4d12;
}
div .intro{
    margin-left: 494px;
    margin-top: 258px;
}
.container p {
    text-align:center;
    margin-left: -378px;
    color:#fff;
    font-weight: bold;
}
form {
    width:29%;
    margin-left: -51px;
}
.form-control {
    width: 94%;
    height: 34px;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.42857;
    color: #555;
    background-color: #fff;
    background-image: none;
    border: 1px solid #ccc;
    }
#entrar {
    font-size:18px;
    width: 368px;
    margin-left: -50px;
    height: 42px;
    border-radius: 0;
    border-bottom: 4px solid #487f1e;
    background-color: #693;
    color: #fff;
}
#email {
    width:368px;
    border-radius:0;
}
#password {
    width:368px;
    border-radius:0;
}
#rodape {
    margin-top: 250px;
}
p.copyright{
    color:#666;
    margin-left: 115px;
    margin-top: 40px;
}
#subtitulo {
    font-weight:normal;

}

Meu css mobile:
@media only screen and (max-width: 480px)/*smartphone*/{

*{
    box-sizing: border-box;
}
html, body {
width: 100%;
height: 100%;
font-family: Arial, Tahoma, sans-serif;
}
body{
    background-image:url(../img/Testing-banner2.jpg);
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    display: block;
    font-size: 16px;
    margin: 0;
    padding: 0;
}
header{
    width:100%;
    height:121px;
    background-color: #693;
    border-bottom: 6px solid #487f1e;
}
header #logotipo {
    /*margin-left: 111px;*/
    text-align:center;
    display:none;
    margin-top: -95px;
    position: absolute;
}
.row {
    margin-right: -3px;
    margin-left: -15px;
}
#centro {
    position: absolute;
    top: 25%;
    left: 35%;
}
#menu ul{
    width: 100%;
    padding: 12px;
    margin-left: 12px;
    margin-top: 15px;
    background-color: #693;
    list-style: none;
    position: relative;
}
#menu ul li a {
    color: #fff;
    padding: 2px 10px;
    display:block;
    text-decoration: none;
    background: #693;
}
a.adm{
    margin-bottom: 11px;
    margin-top: -9px;
    margin-left: 72px;
}
a.aluno{
    margin-bottom: 11px;
    margin-top: 22px;
    margin-left: 130px;
}
#acesso {

    margin-top:-130px;

}
.container p {
    text-align: center;
    margin-left: -595px;
    color: #fff;
    font-weight: bold;
}
form {
    margin-left:-450px;
}
#email {
    width: 300px;
    border-radius: 0;
}
#password {
    width: 300px;
    border-radius: 0;
}
#entrar{
    width: 300px;
    margin-left: -450px;
}
p.copyright {
    color: #666;
    margin-left: 6px;
    margin-top: 22px;
}

}

Comment: Acredito que a classe container deveria ter a propriedade width em 100% não vejo em seu css. Cole a url do domínio em questão fica mais facíl para verificar.
Comment: Não tem url do dominio =/
Answer: O seu problema principal está nesse CSS:
div .intro{
    margin-left: 494px;
    margin-top: 258px;
}

Porém ao remove-lo o seu Form vai ficar desalinhado e vc vai precisar usar outra classe para alinha-lo novamente.
Se você remover o margin-left: 494px; a sua barra vai funcionar. Mas pelo que vi no seu CSS existem muitos outros pontos a melhor. Esses margin-left que vc usa para alinhas os elementos não é a melhor opção, Estude um pouco sobre FlexBox que vai te ajudar MUITO! https://edsonjunior.com/um-guia-visual-para-flexbox/
Com isso vc vai arrumar a Barra, mas vai ter mais trabalho para realinhar os itens do Form, isso é pq vc usou essa margens. O seu código precisa de muito trabalho para melhorar, mas não é impossível. Comece de cima para baixo e vai alinhando com Text-Aline e Margin: 0 auto; Assim não precisa de FlexBox e vc vai chegar em um resultado razoável.
Segue no Snippet um resultado "Final", sugiro vc revisar todo o código. Nem toda classe precisa repetir dentro do @media! Estude sobre isso também! (pode testar em tamanhos de telas diferentes)

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

Área administrativa / Docente

Área do Aluno

                        Acesso Aluno

                        Digite seus dados de login para acessar o sistema

                    <form action="act_login.cfm" method="post" target="escondido">

                            <input type="email" class="form-control " id="email" placeholder="E-mail">

                            <input type="password" class="form-control" id="password" placeholder="Senha">

                    </form>
                    <button id="entrar" type="submit" class="form-control">Entrar </button>

© 2018 - Ensintech - Todos os direitos reservados

Comment: meu codigo ficou assim :

header{
     width:100%;
     height:121px;
     text-align:center;
     margin:0 auto;
 }
 header #logotipo {
     display:none;
 }
 #centro {
     position: absolute;
     top: 25%;
     left: 35%;
 }
 #menu ul{
     width: 100%;
     text-align:center;
     margin:0 auto;
     margin-top: 15px;
 }
 #menu ul li a {
     display:block;
 }
 p.copyright {
     text-align:center;
     margin:0 auto;
     margin-top: 10px;
 }
}

https://prnt.sc/i1buj8

vou ter que usar flex-box mesmo ou tem alguma outra alternativa, a respeito do menu?
Comment: @FranciscoCarlosCarvalhoJr o que acontece é que quando a tela fica pequena vc também tem que tratar o tamanho dos `inputs` do `form`, eles estão com `width: 368px;` porém para o `@media (max-width: 480px)` vc poderia deixa-los com 80% da largura total, ou uns 240px de width. Vc tem que tratar melhor seu CSS nas telas pequenas. Da uma olhada no Snippet agora que eu fiz uma Edição!


Is it possible to store the array of objects as hash into the Redis?

Question: I'm using Redis with my NodeJS app. I want to store an array of objects (policies) against a key as a hash in Redis. Below is my key and value:-
Key - <tenantid>~<userid> e.g. - tenant123~john123
Value - [{ ptype: 'p', v0: 'admin', v1: '/*', v2: 'GET' }, { ptype: 'p', v0: 'viewer', v1: '/post', v2: 'GET' }]
I'm getting below error :-
err
ReplyError: ERR wrong number of arguments for 'hmset' command
args:Array(2) ["tenant123~john123", "[{ ptype: 'p', v0: 'admin', v1: '/*', v2: 'GET' }, { ptype: 'p', v0: 'viewer', v1: '/post', v2: 'GET' }]"]
code:"ERR"
command:"HMSET"
message:"ERR wrong number of arguments for 'hmset' command"
name:"ReplyError"
stack:"ReplyError: ERR wrong number of arguments for 'hmset' command
    at parseError (/var/task/node_modules/redis-parser/lib/parser.js:179:12)
    at parseType (/var/task/node_modules/redis-parser/lib/parser.js:302:14)"
__proto__:RedisError {constructor: , name: <accessor>}

Below is my NodeJS code where I'm calling hmset() to save the policies into Redis.
module.exports.updateCache = async (hashKey, ttl, obj, logger) => {
    logger.debug('Redis:: Key:', hashKey, ', Obj:', obj);
    return new Promise(function (resolve, reject) {
        myRedisClient.hmset(hashKey, obj, (err, result) => {
            if (err) {
                logger.error(err);
                reject(err);
            } else {
                myRedisClient.expire(hashKey, ttl);
                console.log('result:', result);
                resolve(true);
            }
            console.log('closing redis connection');
            myRedisClient.quit();
        });
    });
}

I tried to debug a lot but could not fix this. Is it not possible to store an array of objects against a hashkey in Redis?
Please assist. Thanks
[Update]
New code:-
module.exports.updateCache = async (hashKey, ttl, obj, logger) => {
    logger.debug('Redis:: Key:', hashKey, ', Obj:', obj);
    return new Promise(function (resolve, reject) {
        myRedisClient.hmset(hashKey, JSON.stringify(obj), (err, result) => {
            if (err) {
                logger.error(err);
                reject(err);
            } else {
                myRedisClient.expire(hashKey, ttl);
                console.log('result:', result);
                resolve(true);
            }
            console.log('closing redis connection');
            myRedisClient.quit();
        });
    });
}

Error:-
err
ReplyError: ERR wrong number of arguments for 'hmset' command
args:Array(2) ["tenant123~john123", "[{"ptype":"p","v0":"admin","v1":"/*","v2":"GET"}]"]
code:"ERR"
command:"HMSET"
message:"ERR wrong number of arguments for 'hmset' command"
name:"ReplyError"
stack:"ReplyError: ERR wrong number of arguments for 'hmset' command
    at parseError (/var/task/node_modules/redis-parser/lib/parser.js:179:12)
    at parseType (/var/task/node_modules/redis-parser/lib/parser.js:302:14)"

Answer: It is impossible.
Redis stores everything in string or in its string representation. you can't store array of objects or even object(except string) in redis.
There is no direct means to store objects - it can be done only via serialization and storing resultant byte-array.
Comment: Sorry, can share a sample code explanation serialization here please? I tried JSON.stringify(obj) but that did not work
Answer: Redis store strings so you must serialize your JSON object/array to store them, and then deserialize them when you read those keys.
module.exports.updateCache = async (hashKey, ttl, obj, logger) => {
    logger.debug('Redis:: Key:', hashKey, ', Obj:', obj);
    return new Promise(function (resolve, reject) {
        myRedisClient.hmset(hashKey, { array: JSON.stringify(obj) }, (err, result) => {
            if (err) {
                logger.error(err);
                reject(err);
            } else {
                myRedisClient.expire(hashKey, ttl);
                console.log('result:', result);
                resolve(true);
            }
            console.log('closing redis connection');
            myRedisClient.quit();
        });
    });
}

Comment: This is not working. "Getting error ERR wrong number of arguments for 'hmset' command". I tried using your solution by passing array of object but getting this error
Comment: fixed the answer, hmset, I wrote the code for hset. Docs will help you in these cases
Answer: The function hmset is deprecated as of Redis v4.0. Use hset instead.
Using your newer example, something like
myRedisClient.hset(hashKey, , 'name', JSON.stringify(obj), (err, result) => ...

could work. Failures. What was failing, the cause of the error? Pay close attention to the keyname - if this is calling a key by the same name but is a different datatype such as a set, this call would fail.


Available updates report does not list all available module updates

Question: I just noticed that the page admin/reports/updates highlights subsequent modules as I proceed with the upgrades. For example, initially the Webform and Token modules got the yellowish highlight, and then when I applied the updates to those two, refreshing the page highlighted subsequent modules, say: Date and Rules.
So, is there a particular logic in which the suggestions are made? And, can one get a COMPLETE list of update candidates at one shot?
Answer: In Drupal 7, two methods are used to fetch update information. One uses a setting update_max_fetch_time which is set to 5 seconds by default. On each cron run - whether from the server's cron or triggered by a visitor (poormanscron) - or page refresh of admin/reports/updates, this value is used. Not every module's status can be fetched within those 5 seconds, which is what you're seeing.
If you use the 'Check manually' link from the 'Available updates' page (admin/reports/updates/check), a batch operation is used instead, which should process all modules. There are however also reports that this doesn't always work correctly (Failed to get available update data for [number] projects message, you would then see the status of some modules in a grey box). You may also have to clear Drupal's cache first for this to work correctly.
The best thing to do is probably to set up a cron job to run each hour (for example). This will progressively keep the status of all modules updated.
Another workaround would be to override the update_max_fetch_time value and set it to e.g. 30 seconds (you can set $conf['update_max_fetch_time'] = 30; in settings.php, or with Drush do drush vset update_max_fetch_time 30). But if a cron run is then triggered by poormanscron, this could lead to a long page loading time.
This is from issue 952394 (still open).
Comment: Great answer. To avoid the timeout, you can also use drush pm-updatecode to check for and apply updates.  http://drupal.org/project/drush


How to get asm to jump to a variable address in c?

Question: Right now, I call the jump instruction with inline assembly in c as follows:
int register eax asm("eax") = addr; // addr is a memory address
asm("jmp *%eax");

I want to do it without having to set any other register values (e.g. I want to do is something like this):
asm("jmp *(addr)");

What is the right way to do that? That is, how can I "insert" a c variable into the asm call?
Ubuntu 12.04 64-bit, Intel x86 64-bit processor, gcc version 4.7.4.
Answer: "Assembler Instructions with C Expression Operands"
asm volatile("jmp *%0" : : "r" (addr));

Comment: **Note that it's not generally safe to `jmp` out of an inline asm statement without `asm goto` ([GCC manual](https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#GotoLabels))**.  Or at least a `__builtin_unreachable()` after the asm statement to let the compiler know that execution doesn't come out the other side, and it can't safely defer a store or something until after the asm.
Comment: This gives the following error:
`my.c:450:2: error: output operand constraint lacks '='
my.c:450:2: error: output operand constraint lacks '='
my.c:450:2: error: invalid lvalue in asm output 0`
Comment: @Sefu: Right, my bad.


Doubt about definition of coordinate ring

Question: I was trying to solve this question:

Prove that $\mathbb{A}^1$ is not isomorphic to any of its proper open subset.

One of the solutions I looked up said that the coordinate rings are not isomorphic.
I know that for a closed set $Y$ the coordinate ring is defined as $k[x_1,\dots,x_n]/I(Y)$. But how is the coordinate ring of an open set defined?
Comment: An example: The coordinate ring of $\Bbb A^1\setminus \{a\}$ is $k\left[x, \frac1{x-a}\right]$. It's isomorphic to the planar curve given by the graph of $y=\frac1{x-a}$ via projection onto the $x$-axis.
Answer: Any open set $U$ is a complement to a closed set $X\setminus U$. The coordinate ring of $U$ is then the localization $R_{I(X\setminus U)}$ of the full ring $R$ by the ideal $I(X\setminus U)$. The idea is to make all elements of $I(X\setminus U)$ invertible, thus effectively removing the areas where they are zero (as functions), which is by definition $X\setminus U$.


Lista encadeada dentro de Lista encadeada

Question: Estou com dificuldades com listas encadeadas dentro de uma lista encadeada.
O programa é um jogo de cartas em que existe uma lista duplamente encadeada de jogadores e dentro de cada nó dessa lista, uma lista (a mão) de cartas.
Não estou conseguindo adicionar uma carta à lista de cartas. Como acessar corretamente o nó do jogador e como acessar a primeira posição da lista dentro deste nó?
Minhas structs:
typedef struct Carta{
    int valor;
    char naipe;
}Carta;

typedef struct Cartas{
    Carta Item;
    struct Cartas *Prox_carta;
    struct Cartas *Primeiro, *Ultimo;
    int Tamanho_Mao;
}Cartas;

typedef struct Jogador {
    int id_jogador;
    Cartas *Primeira_mao;
    struct Jogador *Prox, *Ant;
    struct Jogador *Prim_Jogador, *Ult_Jogador;
    int Tamanho;
}Jogador;

A função para tentar adicionar cartas:
int Adiciona_Carta(Jogador *jogadores, Cartas *mao, int x, Carta carta){

    Jogador *aux;
    Cartas *novaCarta, *aux2;
    novaCarta = (Cartas*)malloc(sizeof(Cartas));
    novaCarta->Prox_carta = NULL;
    novaCarta->Item.naipe = carta.naipe;
    novaCarta->Item.valor = carta.valor;
    aux = jogadores->Prim_Jogador;

    while (jogadores->id_jogador != x){
        aux = aux->Prox;
    }
    aux2 = aux->Primeira_mao;
    mao->Primeiro = aux->Primeira_mao;
    if (aux->Primeira_mao == NULL){
        Cria_Mao_Carta(mao);
        mao->Primeiro = novaCarta;
        mao->Tamanho_Mao++;
    }
    if (carta.valor > aux2->Item.valor){
        novaCarta->Prox_carta = mao->Primeiro;
        mao->Primeiro = novaCarta;
        mao->Tamanho_Mao++;
    }
    for (aux2 ;; aux2 = aux2->Prox_carta){
        if(carta.valor > aux2->Prox_carta->Item.valor){
            novaCarta->Prox_carta = aux2->Prox_carta;
            aux2->Prox_carta = novaCarta;
            mao->Tamanho_Mao++;
        }
        if(aux2->Prox_carta == NULL){
            aux2->Prox_carta = novaCarta;
            novaCarta->Prox_carta = NULL;
        }
    }
}

Comment: me ajuda
**https://pt.stackoverflow.com/questions/412245/lista-encadeada-socorro**
Comment: me ajuda https://pt.stackoverflow.com/questions/412245/lista-encadeada-socorro
Answer: Recomendo, antes de tudo, criar uma estrutura separada pra lista.
typedef struct Conteudo{
int valor;
char naipe;
}Conteudo;

typedef struct Cartas{
    Conteudo Item;
    struct Cartas *Prox_carta;
}Carta;

typedef struct ListaCartas {
    carta *primeiro, *ultimo;
    int tamanho;
}

faz o mesmo esquema com os jogadores, fica muito mais claro que que ce tá fazendo. ficou bastante confusa sua estrutura desse jeito.
e pelo amor de deus, não fica usando aux pra tudo não, dá um nome pra variável que outra pessoa que estiver lendo seu código vá entender =/
não dá pra entender seu código da função sem saber pra onde o aux do tipoJogador foi parar, ce não especificou que que a função Cria_mao_carta faz


PCA - variables over 10 years for multiple assets

Question: I have 19 technical trading indicator variables over 10 years, for 25 different assets. I am attempting to reduce dimensionality to 2 components.
I want to plot all assets on a 2D graph against PC1 and PC2.
My questions are:

How do I achieve this, considering I have daily time series data? Surely, I must have only one observation per indicator per asset. Should I take the average of the daily data?
The indicators are a mix of prices and volumes. Many different ranges. Is it ok to normalise the entire dataset?
Comment: What makes you think that you need one observation per asset?
Comment: I can produce a variance covariance matrix using the timeseries data.
However, when calculating the component scores, if i load all daily data for each asset, I will have a score for each day. Instead, I want just one score per asset.
Comment: In this example: https://onlinecourses.science.psu.edu/stat505/node/53 , there are 329 countries, and 9 variables. Each variable for each country is represented by 1 number.
Comment: 329 countries, is that possible? Just to be sure I understood correctly: you have a certain number of daily series (25 ?), for a certain number of countries (19?) and you'd like to do some dimensionality reduction?
Answer: About question 1.:
if you want to analyse the daily time series, then you should consider a functional principal component analysis (fPCA). fPCA generalises the usual PCA for handling functional data, i.e. datasets in which the statistical unit is not a single observation but a curve or a function. I believe there are several possible variants fPCA. The book by Ramsay et al. (2009) Functional Data Analysis with R and MATLAB edited by Springer, is a great reference. The book comes with a handy $\texttt{R}$ package called $\texttt{fda}$.
About question 2.:
In case of the functional data approach I'm not sure how do you perform the standardisation, you need to check the literature. But in the yearly averaged data, yes, standardisation is always a must in PCA.


linux max disk size

Question: I have a linux server with sda to host the OS (Ubuntu 7.04, ext3 filesystem) and sdb,sdc,sdd,sde 1TB each to be on a raid 1 for saving data. I need to get rid of the raid and I wanna swap it for a 4TB disk. How can I determine which is the max disk space that is supported?
Comment: Is there a particular reason for using a 7 year old version of Ubuntu?  7.04 hasn't had security updates for years now.
Comment: unfortunately yes.
Answer: Linux is not really the limiting factor when it comes to max disk size, as long as you stick to ext3,4 or xfs. If you are running a recent main board with SATA you are good to go, since SATA has 48bit LBA to address the disk.
See http://www.tomshardware.co.uk/forum/246170-32-hard-drive-size-limit
Ext3 has some limits on max disk size, due to the chosen block size. With a block size of 4KiB the maximum file size is 2TiB and the max disk size 16TiB.
See http://en.wikipedia.org/wiki/Ext3
Another very insightful read is here:
What is the max partition supported in linux?
Comment: True. But my response applies to the given context.
Comment: Not true, block device sizes have a maximum in linux, although it is quite large.
Comment: True. (--- expansion ---)

linux max disk size


PHP - Retornar soma de colunas em data especifica // PDO

Question: Como fazer para que no retorno fetch(PDO::FETCH_ASSOC) ele some as colunas p_line_a (altura) e p_line_l (largura) que se refiram a uma data especifica.
Por exemplo: Uma pessoa que ver a soma dos inteiros dessas duas colunas referente ao dia 2016-09-20. Como fazer esse script? (PDO)
No caso ele deveria retornar a soma de 25,5...

O retorno geral, porem não somado e tbm separado...
        $bsc_user = $pdo->prepare("SELECT * FROM `tab_newprodut` WHERE `p_data`=?");
        $bsc_user->execute(array("2016-09-20"));
        $bsc_cont = $bsc_user->rowCount();
        if($bsc_cont > 0){
            while($linha = $bsc_user->fetch(PDO::FETCH_ASSOC)) {
                echo $linha['p_line_a'].' '.$linha['p_line_l'].'
';
            }
        } else {
            echo '
Nenhum registro localizado.
';
        }

1- ele precisa somar total as duas colunas p_line_a, p_line_l que se refiram ao data especificada.
2- como eu faria para imprimir (echo) isso??
Comment: Como esta sua `query` no PDO?
Comment: $bsc_line = $pdo->prepare("SELECT * FROM `tab_newprodut` WHERE `p_data` = ?");
Answer: Para retornar a soma de uma coluna você deve usar SUM na query, contudo caso você queira incluir outros campos também, você deve agrupá-los através do GROUP BY.
Exemplo 1
SELECT SUM(p_line_l) FROM tab_newprodut WHERE p_data = ?

Aqui eu estou retornando apenas a som da coluna, então não temos GROUP BY.

Exemplo 2
SELECT SUM(p_line_l), p_data FROM tab_newprodut WHERE p_data = ? GROUP BY p_data

Aqui foi necessário agrupar, pois o SUM soma vários para fornecer uma única resposta, enquanto o p_data estaria um-por-um, então usando o GROUP BY basicamente se esta dizendo que quer a soma das datas iguais.
Comment: 1- ele precisa somar total as duas colunas **p_line_a, p_line_l** que se refiram ao data especificada. 2- como eu faria para imprimir (echo) isso??
Answer: A SQL basicamente seria assim:
select (sum(p_line_a) + sum(p_line_l)) soma, p_data from items WHERE p_data = '2016-09-20'

PHP
$bsc_user = $pdo->prepare("select (sum(p_line_a) + sum(p_line_l)) soma, p_data from tab_newprodut WHERE p_data = ?");
$bsc_user->execute(array("2016-09-20"));
$bsc_cont = $bsc_user->rowCount();
if($bsc_cont > 0)
{
    while($linha = $bsc_user->fetch(PDO::FETCH_ASSOC))
    {
        echo $linha['soma'].'
'
    }
}
else
{
    echo '
Nenhum registro localizado.
';
}


What's the difference between interior and relative interior?

Question: As defined in Convex Optimization written by Stephen Boyd & Lieven Vandenberghe, both interior and relative interior seems to describe a same thing: a set that peels away its boundary points. So, what on earth is the difference between these two concepts ?
Here are the definitions of these two concepts from Convex Optimization:

interior: The set of all points interior to $C$ is called the interior of $C$

relative interior: its interior relative to the affine hull of $C$
Comment: To make your question useful for everybody, you should copy the actual definitions of those two concepts given in the book.
Answer: The relative interior of a set is the interior of the set when it is viewed as a subset of the affine space it spans.
For example, the interior of the segment connecting $(0,0)$ to $(1,1)$ in the plane is empty, but the relative interior is the open segment with those endpoints.
Comment: I downvoted since it is not enough elaborated
Comment: For any subset of $\mathbb R^n$ (or maybe more generally of a topological vector space), not just for a convex set.
Answer: I came across this question whilst studying the same textbook, but I found that Mariano Suárez-Álvarez's gracious response, whilst, of course, appreciated, to be lacking the detail I desired. Fortunately, Justin Rising posted a more elaborate answer to the same question on Quora. I have decided to copy and paste it here for the benefit of others.
Justin Rising's response to the same question on Quora:

Consider $\mathbb{R}^3$ with the standard Euclidean metric, and look
at the set of points $(x, y, 0)$ such that $x^2 + y^2 \leq 1$.  What's
the interior of this set?
A point is in the interior of a set if you
can draw a small open ball around it which is itself contained in the
set.  But for any point in our set, any open ball around any point in
it will contain points outside the $x-y$ plane, and so it has empty
interior.
That's technically correct, but it's undesirable behavior.
The relative interior of a set is obtained by looking at the affine
hull (http://en.wikipedia.org/wiki/Affine_hull) of the set, which in
this case is $\mathbb{R}^2$, and using the appropriate metric there.
So while our set has empty interior, its relative interior is the
interior of the unit disc, which is what it "really should be".
Relative interiors are a big deal in convex optimization, where you'd
really be restricting the set of problems you can solve for no good
reason if you insisted on using interiors rather than relative
interiors.
It came up in the comments, and it's worth adding to the
answer, that there are very good reasons to talk about both interiors
and a relative interiors.  The relative interior is only defined in
vector spaces; in particular, you have notions of addition and scalar
multiplication to define an affine hull.  If I were to define a
topology on the words in the dictionary, I could talk about the
interior of a set immediately, but I'd have to do quite a bit of
legwork to be able to talk about relative interiors.
Comment: According to the definition of affine hull, the affine hull of the set (x,y,0) s.t. x^2+y^2<=1 should be a a circle area on R^2 but not the entire R^2, right?
Comment: @czxttkl no dont think so. Since it includes all combinations of points thus vectors spanning entire R2. What confuses me though is what will be the relative interior, will it be outside the circle or inside the circle.
Answer: Put it simple and intuitive:
The relative interior of C is viewed from the affine space $\mathrm{aff(C)}$, and the interior of C is viewed from the whole space where C lies in, which is sometimes "bigger" than $\mathrm{aff(C)}$. E.g. in Boyd's book example 2.2: The relative of C is viewed from $\mathrm{aff(C)=R^2}$ while the interior of C is viewed from $\mathrm{R^3}$.
Inspired by the answer from Michal Adamaszek.
Answer: The interior $x$ of the set $C$ means that there exists a small ball around $x$,that is $\{y| \Vert y-x\Vert\leq r\}$  belongs to $C$. In this case, $y$ is a 3D ball while $C$ is a square plane, so  $C$ does not have interior.
The relative interior of the set $C$ is the intersection of the ball $y$ and aff $C$, so the relative interior is the set except the boundary.


Normalized integrals over shrinking tubular neighbourhoods converge to an integral on the limit submanifold

Question: $\renewcommand{\S}{\mathcal{S}}$
$\newcommand{\M}{{\mathcal{M}}}$
$\newcommand{\TM}{{T\mathcal{M}}}$
$\newcommand{\TS}{{T\mathcal{S}}}$
$\newcommand{\NS}{{\mathcal{NS}}}$
$\newcommand{\N}{\mathcal{N}}$
$\newcommand{\g}{\mathcal{g}}$
$\newcommand{\Volg}{\text{Vol}_\g}$
$\newcommand{\Vol}{\text{Vol}}$
$\newcommand{\VolgS}{\text{Vol}_{\g|_\S}}$
Let $(\M,\g)$ be a smooth $d$-dimensional Riemannian manifold, and let $\S\subset\M$ be a smooth compact $k$-dimensional oriented submanifold. Let $\NS$ be the normal bundle of $\S$ in $\M$.
For a sufficiently small $h>0$, define
$\S_h := \{ \exp_p(v) : p\in \S, v\in \NS, |v|\le h \}.$
Let $f:\M \to \mathbb{R}$ be a continuous function. I am trying to prove the following:
$$ \lim_{h \to 0} \frac{\int_{\S_h} f}{\Volg(\S_h)}=\frac{\int_{\S} f}{\VolgS(\S)},$$
where the integrals are w.r.t the Riemannian volume forms on $\S_h$,$S$ defined by $\g,\g|_{\S}$ respectively.
(Recall $\S$ is oriented).
Edit:
Let's start with the case of a $k$-cube embedded in $\mathbb{R}^d$ in the standard way. The general case should follow by an approximation argument, since "locally, everything is Euclidean".
Here is a proof for the Euclidean case:
Let's use Fubini theorem:
Suppose $\S \subseteq \mathbb{R}^k \times \{\bar 0^{d-k}\} \subseteq \mathbb{R}^d$, where $S$ is a product of $k$ intervals. Then $\S_h=S \times [-h,h]^{d-k}$.
Let $\epsilon >0$, and let $(x,y)\in S\times [-h,h]^{d-k}$.
$$\frac{\int_{\S_h} f}{\Vol(\S_h)}= \frac{\int_{[-h,-h]^{d-k}}\big(\int_{S} f(x,y) dx\big)dy }{(2h)^{d-k}\Vol(S)} =\frac{\int_{[-h,-h]^{d-k}} g(y) dy }{\Vol([-h,-h]^{d-k})} ,$$
where $g:[-h,-h]^{d-k} \to \mathbb{R}$ is defined by
$$ g(y)=\frac{\int_{x \in S} f(x,y)dx}{\Vol(S)}.$$
Since the domain is compact, $f$ is uniformly continuous, so $g$ is continuous. This implies
$$ \lim_{h \to 0} \frac{\int_{[-h,-h]^{d-k}} g(y) dy }{\Vol([-h,-h]^{d-k})}  =g(\bar 0)=\frac{\int_{x \in S} f(x,0)dx}{\Vol(S)}=\frac{\int_{\S} f}{\Volg(\S)}.$$
Comment: I don't think you want to think about partitions. I think you want to think about a local parametrization (using the exponential map) $U\times B^{n-k}(h)$ and apply Fubini's Theorem.
Comment: Can you prove it in the case of a $k$-cube embedded in $\mathbb R^n$? For small enough $h$ the exponential map along with a chart for $\mathcal S$ provides an adapted chart for $\mathcal S_h$, so you should just need to add up the integrals over such an $\mathcal S_h$-atlas using a partition of unity.
Comment: Thanks, I also thought on some approximation argument. However, I am not sure how to do this exactly, since we are localizing everything to a submanifold, not a point. (Also, I am not sure the Euclidean case is entiery trivial as well... you can see my edit).
Comment: You are right that both sides look additive when you partition $\S$ to disjoint subdomains. (However, I think that to do this rigorously you need to say something on why you can change the order of the limits: taking $h \to 0$ and taking "infinite sum" on your partitions. (You need to take finer and finer partitions of $\S$, in order to use localization, no?)
Answer: We will consider the following case :
(1) If $p:=(x,h)\in [0,l]\times [-1,1]$, then prove that
$$ \lim_r\ \frac{\int_{[0,l]}\int_{[-r,r]} f dhdx }{2rl} =\frac{T}{l},\ T:=
\int_{[0,l]} f(x,0)\ dx
$$
Proof :
Since $f$ is uniform continuous, then
for $\varepsilon$ there is $\delta$ s.t. $d(p,q)<\delta$ implies
$|f(p)-f(q)|<\varepsilon$.
Hence \begin{align*}  \frac{\int_{[0,l]}\int_{[-r,r]}
f(x,0)-\varepsilon\ dhdx }{2r}
 &<\frac{\int_{[0,l]}\int_{[-r,r]} f dhdx }{2r}
 \\&<\frac{\int_{[0,l]}\int_{[-r,r]} f(x,0)+\varepsilon\ dhdx }{2r}
\end{align*}
so that $$T-\varepsilon l <\frac{\int_{[0,l]}\int_{[-r,r]} f dhdx
}{2r} < T+\varepsilon l $$
(2) Assume that there is a cover $\{E_i\}$ for $S$ s.t.
(i) $E_i\subset S,\ 1\leq i\leq N$ is homeomorphic to closed ball,
(ii) $E_i\cap E_j$ has measure $0$, and (iii) $E_i$ have same
volumes.
(3) If $V_i(r):=\{\exp_pv|p\in E_i,\ v\perp T_pS,\ |v|\leq r\}$, then $$ \lim_r\ \frac{\int_{V_i(r)} f}{{\rm vol}\
V_i(r)} =\frac{\int_{E_i} \ T}{{\rm vol}\ E_1} $$
Note that $$ t_i(r){\rm vol}\ V_i(r) :={\rm vol}\ V_1(r) $$
 and $$ \lim_r\ t_i(r)=1$$
(4) So \begin{align*}\frac{\sum_i \ \int_{V_i(r)} f
}{\sum_i V_i(r)} &=\frac{\sum_i \ \int_{V_i(r)} f }{[\sum_i \
1/t_i(r) ]V_1(r)}\\& = \frac{1}{\sum_i \ 1/t_i(r)} \sum_i \ \frac{
\int_{V_i(r)} f }{ t_iV_i(r) }
\\&\rightarrow  \frac{1}{N} \sum_i
\ \frac{\int_{E_i} f}{{\rm vol}\ E_i }
\end{align*}
(5) More explanation on (3) : A Riemannian metric $g$ on $X:=V_i(r)$ is close to $g'=g|S +
    g_0$ where $g_0$ is a canonical metric on $\mathbb{R}^{n-k}$
    where ${\rm dim}\ S=k$.
Given $\varepsilon$ there is $r$ s.t. $$ (1-\varepsilon )d_{g'}
 \leq d_g\leq (1+\varepsilon ) d_{g'}$$
so that $$ (1-\varepsilon)^n \leq \frac{ H^n(X,d_g) }{H^n(X,d_{g'} )}
   \leq (1+\varepsilon )^n $$
   where $H^n(X,d_g)$ is a $n$-dimensional Hausdorff measure wrt a distance
  $d_g$
So
$$ \frac{\int_{(X,d_{g'} )} f  +O(\varepsilon ) \int_{
(X,d_{g'} )} f }{ {\rm vol}\ (X,d_{g'}) +O(\varepsilon ){\rm vol}\
(X,d_{g'}) } =  \frac{ \int_{(X,d_g)} f }{{\rm vol}\ (X,d_g)} $$
Comment: Thanks, Your approach is nice. However, there is something that bothers me: How do you know that $\lim_{r \to 0} \frac{\int_{V_i(r)} f}{{\rm vol}\
V_i(r)} =\frac{\int_{E_i} \ f}{{\rm vol}\ E_1}$? Isn't this assuming the result you want to prove, just for "small" base submanifolds? The $E_i$ are not "infinitesimal" after all... I guess you want to deduce this from the Euclidean case, but I don't see immediately how it follows, since the metric on your "balls" $V_i(r)$ is not a product metric, so you can't use Fubini.
Comment: I assume that $S$ is a embedded compact submanifold And in (2) we assume that ${\rm vol}\ E_i={\rm vol}\ E_1>c>0$ for all $i$ in $S$.
Comment: OK, but why that helps? I really think you want need to say something like "when $r \to 0$ the exponential map becomes "more isometric", hence the result carries through"- but I don't think this is rigorous enough: you need to estimate the difference between Euclidean and Riemannian (something like $o(r)$ or $o(r^2)$... and also, your "balls" $E_i$ are only homeomorhpic to balls, which sounds a bit weak, they are not metric balls. (You had to require this so you would be able to choose them with equal volume, which I don't think is necessary for the argument, by the way).
Comment: I add more explanation.


what kind of views should I use?

Question: I am going to download the Views module for a Drupal 7 website I am creating, but there are 2 different versions: There is the alpha3, the development snapshot, and another one that doesn't have a name I can see (it is highlighted in green). Which these three versions should I use?
Answer: It is really a personal decision on which one you should download. It is recommended to always download the one's in "Green". However views3 offers a significant improvement in the user interface and if you are just starting out in views, this might be a better choice.
A good article on choosing modules http://drupalwatchdog.com/1/1/module-selection-in-the-wild
Answer: There are two main version of View,s 2.0 and 3.0.
Drupal 6 has support for both views

6.x-2.12 with Views 2
6.x-3.0-alpha3 with Views 3
6.x-3.x-dev with Views 3 and is under development

It is recommended to use 6.x-2.12

After clarifying about drupal7:
For Drupal 7 there is Views 7.x-3.0-rc1 recommended.
Comment: I am using drupal 7
Comment: The better is to tag your question about Drupal version. Thanks :)
Comment: If you use Views 3, use the dev branch until it is stable. Using the alpha/beta/rc means you'll have bugs.
Answer: For Drupal 7, there's now an RC (Release candidate).
However, I still think that for D7 modules before the first release, the -dev version is usually your best bet. This is the case with Views as well.

what kind of views should I use?


Same MAC but different IP on router

Question: If a device has same mac address but different IP on home router,
is this some sort of error or hacking? What is going on?
I can't attach a pic so I've listed below. Computer name for second doesn't show. Just blank.
So..
Computer Name     Mac Address     IP
David            11:22:33:44:55   192.168.2.3
<code>        11:22:33:44:55   192.168.2.4
</code>
Comment: Can you clarify this? Do you have two different devices that actually have the same MAC address? This is not supposed to happen, but it is made more likely with virtual machines, bridge interfaces, and various other kinds of interfaces with made-up MAC addresses rather than burned-in MAC addresses.
Comment: No I just have 4 computers connected, but I saw 5 connections. It turns out there are 2 connections with same MAC address but different IP.
Comment: I don't think I have devices with two same mac address. I am just wondering if I was hacked(aka arp spoofing hack )
Comment: "there are 2 connections with same MAC address but different IP". It sounds like you simply have a device on your network that has 2 IP addresses. So what's the problem?
Comment: I am just wondering if I am being hacked. Never had this problem occur on router before so...
Comment: I still don't understand. When you say "Never had this problem occur", what PROBLEM are you referring to?
Comment: Like when I view on the router, I had never had instances in which there are 2 duplicate macs with different IP.
Comment: Is this simple connection error or hacking by outsiders?
Answer: Yes, it is possible to have more then one IP on one interface (with one MAC address).
There is also a bug on some Android devices, where they "forget" to renew a DHCP lease, but request a new one (and get a new IP) every now and then, while they keep an old IP address active.
Comment: So I am not being hacked? It's actually a computer, not android, I believe. Can this occur on iphone devices as well?
Comment: It can happen on every device, and because of many reasons. Try pinging the device, and/or seeing where it's connected from, to see what's there.
Comment: I see. Can this a example of arp spoofing? Meaning am I being hacked? The second connection with same Mac but diff IP has no computer name(blank).
Comment: It is possible, but it is impossible to tell just from that log data.
Comment: hmm so it's not just one instances of error?
Comment: "there are 2 connections with same MAC address but different IP". It sounds like you simply have a device on your network that has 2 IP addresses. So what's the problem?  Is this true?

Same MAC but different IP on router


Como utilizar um arquivo .JSP

Question: Sou extremamente novo na linguagem JSP, queria saber como fazer para utilizar um arquivo jsp que eu criei e exibilo por exemplo no browser, da mesma forma que faço com arquivos html, ou seja, como utilizar um arquivo jsp criado???
obs: na imagem anexada está o resultado quando abro o arquivo .jsp com o browser(que não é a saída que eu desejo).
<%! int i %>

         <title> Pagina JSP Ola Mundo</title>

    <% for(i = 0; i = 3; i++){ %>

          <%out.println("numero:"+i);%>

    <%
       }
    %>

</hmtl>

Comment: Você tem que configurar um Web Conteiner, um exemplo o Tomcat. Outra coisa já que você esta começando, procura saber mais sobre JSF. No youtube tem muitas aulas para iniciantes em JSP, JSF, nelas você consegue aprender a configurar um servidor e rodar sua primeira página com tecnologia Java
Answer: Você não consegue abrir um arquivo JSP diretamente no navegador pois ele é uma linguagem "acima" do HTML. Isso significa que você precisa de um container web para identificar os componentes JSP do arquivo e permitir a sua visualização como um arquivo HTML. O navegador não tem o suporte nativo para identificar esses componentes e é por isso que você precisa que o seu projeto que contém a JSP inclua as bibliotecas jsp-api e jstl, que são usadas pelo container web para renderizar a página.
Um exemplo mínimo de aplicação web usando JSP pode ser visto nesse link.
Answer: Instale o Tomcat :
http://tomcat.apache.org
Com o Tomcat instalado pode-se iniciar o desenvolvimento JSP. Para iniciar o desenvolvimento deve-se criar um diretório easyjava em C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\webapps (no Windows) e /usr/java/apache-tomcat-7.0 (no Linux)".
Salve o arquivo e abra o navegador de sua preferencia e digite: http://127.0.0.1:8080/easyjava/ola.jsp, conforme a Figura 1.

Como utilizar um arquivo .JSP


Jquery Cookie lib for Bootstrap modal: Uncaught SyntaxError: Unexpected Token ILLEGAL

Question: I'm trying to include a bootstrap modal and only have it appear every 7 days via jquery.cookie library. When I load the page and view the errors in console, I get the following:
Uncaught SyntaxError: Unexpected Token ILLEGAL

Here I grab the script:

Then I initiate the modal using the cookie function:

Is something wrong with my syntax? As far as I can tell everything is correct, I'm calling the latest jquery lib first in the header, then the cookie lib, then calling the jquery cookie function much later, near the footer (so I'm assuming it's not caused by a delay in the http request).
Here is the site in question: http://goo.gl/12ZvJP
Answer: You've got "smart quotes" in your code. They need to be plain old ASCII single-quote characters.
$(document).ready(function() {
    if($.cookie('pop') == null) {
        $('#myModal').modal('show');
        $.cookie('pop', '7');
    }
});

Don't edit source code in Word or any other word processor, or if you can't resist, make sure you turn smart quotes off.


For repeated observation analysis, what's the difference between fitting GLS with compound symmetry and random-intercept LMM with CS?

Question: I will refer to R and SAS examples, but this is a general statistical question.
I don't fully understand two things.
Let's assume I want to fit a model for observations repeated over time and compare if the means differ between men and women.
In SAS you can use the PROC MIXED procedure for it in 2 ways:

using a mixed model, by employing random effects - "RANDOM" statement.
using a Generalized Least Square linear model corrected for dependency and heteroscedasticity, using the "REPEATED" statement.

In R you can do the same using, for example:

nlme::lme() for a mixed model
nlme::gls() for the GLS estimated LM.

Now, in both, SAS and R cases I can define the residual covariance structure. Let's say it will be "compound symmetry".
And here I'm confused.
What does it mean to have, for example, a mixed model with "random intercept" AND select the CS (where does it apply? to random effects? to the residuals)?
from
Just having a GLS model with the CS (here I know it goes to the residuals).
What's the sense, the point to define both random effect relationships AND the residual covariance?
Exemplary code taken from the internet:
lme(weight ~ Time * Diet, BodyWeight,
                   random = ~1|Rat,
             corr=corCompSymm(form=~1|Rat))

It specifies both random intercept (for the Rat being the cluster, experimental subject) AND also the corCompSymm - CS for the residuals.
...and I even saw there are structures for the random effects itself, for example pdCompSymm(). Same in SAS - the covariance can be set for both residuals and random effects.
What's the point to specify both relationships between random effects and residuals?
Answer: To the best of my knowledge you're exactly right that these terms are redundant in this particular case. As an experimental demonstration (not "proof"):
First, lme is notoriously quiet about unidentifiable models.  It fits this model without complaint:
library(nlme)
## lme with both Rat REs and cs
m1 <- lme(weight ~ Time * Diet, BodyWeight,
    random = ~1|Rat,
    corr=corCompSymm(form=~1|Rat))

But trying to compute intervals(m1) gives

Error in intervals.lme(m1) :
cannot get confidence intervals on var-cov components: Non-positive definite approximate variance-covariance

and the compound-symmetric correlation parameter Rho is estimated as 1.2e-17, i.e. effectively zero (this is not a reliable indicator, however, as there are infinitely many combinations of Rho and among-rat variation that would give the same answer).
Fitting the two special-case models (rat RE without R-side correlation, corCompSymm in a gls model):
m2 <- lme(weight ~ Time * Diet, BodyWeight,
          random = ~1|Rat)
m3 <- gls(weight ~ Time * Diet, BodyWeight,
          corr=corCompSymm(form=~1|Rat))

Comparing the log-likelihoods of these models shows that they are all the same (up to floating-point precision: the relative difference is on the order of 1e-15) — again, not mathematical proof, but convincing evidence.

The one case where it's important to distinguish between the two special cases (R-side comp symm and rat-level intercept RE) is that if there is negative compound-symmetric correlation among observations within a group, that can only be modeled by the R-side/gls model, not by the rat-level RE (unless you are using a computational framework that allows negative RE variances ...)
Not all RE-level/correlation structures are redundant/jointly unidentifiable. For example, it could make sense to use an autoregressive model for the within-rat correlations (corAR1 in R) ...
Comment: Thank you very much, Sir! It clears my doubts entirely.
Comment: It is in general unidentifiable if we specify both the random effect and correlation structure with the same grouping. I actually tried to estimate a model with both autocorrelation in the residual variance and random effect in the intercept grouped by the subject, using another set of data with repeated measurements. Same situation happened: the estimated standard deviation of the random effect was almost zero, and/or the correlation coefficient at its boundary (-1 or 1).


Eigenvalues of VAR(1) coefficient matrix

Question: Suppose we have a VAR(1) model:
$$
\mathbf{X}_t = \boldsymbol{\Phi} \mathbf{X}_{t-1} + \mathbf{Z}_t, \hspace{10mm} \mathbf{Z}_t \sim WN(0,\Sigma)
$$
If we can keep plugging that equation into itself, we get
$$
\mathbf{X}_t = \sum_{j=1}^{\infty} \boldsymbol{\Phi}^j Z_{t-j} \tag{2}
$$
as long as the eigenvalues of $\boldsymbol{\Phi}$ have a modulus of less than $1$.
This textbook mentions that this condition in bold is sufficient to guarantee that "the coefficients $\boldsymbol{\Phi}^j$ are absolutely summable." I assume the book really means "matrices with absolutely summable components" and uses "coefficients" to mean elements of the matrix, not the matrix itself.
In other words, I am thinking
$$
\sum_{j=0}^\infty |\left[\boldsymbol{\Phi}^j\right]_{kl}| < \infty \tag{1}
$$
I understand how this implies that each component of the [vector] $\sum_{j=0}^n \boldsymbol{\Phi}^j \mathbf{Z}_{t−j}$
converges in the mean square sense.
My question is why is (1) a consequence of the eigenvalues being between $-1$ and $1$?

The way I think about it appears to be incomplete. I suppose that $\boldsymbol{\Phi}$ is diagonalizable, so
$$
\boldsymbol{\Phi}^k = \mathbf{P} \boldsymbol{\Lambda}^k \mathbf{P}^{-1}
$$
where $\boldsymbol{\Lambda}$ is the diagonal matrix of eigenvalues, and $\mathbf{P}$ is an invertible matrix of eigenvectors arranged as columns. In this case,
$$
\boldsymbol{\Phi}^j \mathbf{Z}_{t−j} = \mathbf{P} \boldsymbol{\Lambda}^k \mathbf{P}^{-1} \mathbf{Z}_{t−j}
$$
and the right hand side goes to $0$ elementwise because $\boldsymbol{\Lambda}^k \mathbf{P}^{-1} \mathbf{Z}_{t−j}$ goes to $0$ by virtue of the fact that every element in
$\boldsymbol{\Lambda}^k$ vanishes.
Notice that my intuition a.) assumes diagonalization is possible, and b.) that it doesn't have anything to do with the individual components of the matrix of a power of $\boldsymbol{\Phi}$.
Answer:
The eigenvalues of $\Phi^\intercal \Phi$ are the eigenvalues of $\Phi$ squared, and so also have moduli less than $1$. Proof here

For square $\Phi$, $\begin{Vmatrix} \cdot \end{Vmatrix}_2$ is a submultiplicative norm and
$$
\begin{Vmatrix} \Phi \end{Vmatrix}_2 = \sqrt{\max \{|\lambda| : \lambda \text{ is an eigenvalue of }\Phi^\intercal \Phi\}} := c
$$
Proof here

$\| \sum_{k=0}^n \Phi^k \|_2 \le \sum_{k=0}^n \|\Phi\|_2^k \le \frac{1}{1 - c} < \infty$ so $\left[\sum_{k=0}^n \Phi^k\right]$ is invertible and in particular has finite elements. Proof is here


Python Can't decode byte : Invalid start byte

Question: So I'm building this socket application, and it works just fine on my computer. But when i start server socket on another laptop, it just crashes with a invalid start byte error:
How do i proper encode the program to work with all laptops
This is the error i get on :
Other laptops.
My laptop.
I have tried to change the encoding, but I'm just not quite sure where i have to change it.
Class Listener:
    def __init__(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_address = (socket.gethostbyname(socket.gethostname()), 10000)
        self.sock.bind(self.server_address)
        print(f"LISTENER : {str(self.server_address[0])} port {str(self.server_address[1])}")

    def listen(self):
        self.sock.listen(1)
        while True:
            print("Connection Open")
            print("     Waiting for connections")
            self.connection, self.client_address = self.sock.accept()
            try:
                print(f"Connection from {str(self.client_address)}")
                while True:
                    data = self.connection.recv(1024)
                    if data:
                        message = str(data)
                        if not "print" in message.lower():  # This just checks if the client wants to print system information from the server
                            Validate(message)  # this checks for a command the server have to do
                        else:
                            self.connection.sendall(pickle.dumps(self.computerinfomation))
                    else:
                        self.listen()
            except Exception as e:
                print(e)

I want it to work on other laptops as well, and i just cant see why it wont.
Comment: First: edit question and use button `{}` to format code. Second: always put error message as text - and they we can copy it.
Comment: you decode bytes using `utf-8` but sender may send data in different encoding - ie. latin2, iso-8859-2, etc. I checked in Google `x91` and it is probably code in `Latin1`. You can use `str(data, encoding)` to decode in different encoding but you would have to know what encoding you have to use. So sender should send this information at start or it should encode data to `utf-8` before it sends it.
Answer: Furas came with a solution.
I changed the
message = str(data)

to
message = str(data, encoding="utf-8")

I did the same on the client side
Answer: Not going to lie. I just changed the encoding = utf-16.
Example:
df = pd.read_csv(C:/folders path/untitled.csv, encoding = "utf-16")


When is E(A*B) = E(A * E(B))?

Question: I'm looking at the documentation for the econml python package. On this page it is stated that:
\begin{split}E[Y_{i, t}^{IPS} | X, W] =~& E\left[\frac{Y_i 1\{T_i=t\}}{p_t(X_i, W_i)} | X_i, W_i\right] = E\left[\frac{Y_i^{(t)} 1\{T_i=t\}}{p_t(X_i, W_i)} | X_i, W_i\right]\\
=~&  E\left[\frac{Y_i^{(t)} E[1\{T_i=t\} | X_i, W_i]}{p_t(X_i, W_i)} | X_i, W_i\right] = E\left[Y_i^{(t)} | X_i, W_i\right]\end{split}
where $Y_i$ is some dependent variable, $T_i$ is a treatment variable, $X_i, W_i$ are covariates, and $p_t(X_i, W_i)$ is the probability that $T = t$.
I don't understand the third equality (from top line at the right to bottom line at the left). It looks like something of the form:
$$E[A*B | X] = E[A * E[B | X] | X]$$
where $A = \frac{Y_i}{p_t(X_i, W_i)}$ and $B=1\{T_i=t\}$. But unless I'm mistaken this equality does not hold in general.
Can someone explain to me why this equality holds in this case? Thanks!
Comment: $Y_i^{(t)}$ refers to the potential outcome that $Y$ would have had, if the treatment for instance _i_ had been _t_ (regardless of whether the true treatment was really _t_). In case the true treatment T is not _t_, then it is a counterfactual outcome that can never be observed.
Comment: What does "$Y_i^{(t)}$" refer to??
Answer: The issue here is not simply one of expectations, but of conditional expectation given a random variable.
I learnt this stuff a few years ago and don't remember it too well, but I'll give it a shot.
The basic intuition is when we say $E[A | X]$ we are saying what is the distribution of $A$ if we know $X$. It then is a function of $X$.
For example if $A = X + U$, $U \sim N(0,1)$ then $$E[A | X] = X + E[U|X] = X + E[U] = X$$ as $U$ is independent of $X$ and has mean 0. So the expectation of $A$ given $X$ is just $X$.
We have a few basic properties we can use:
\begin{align}
(A) && E[A|X] = E\left[E\left[A|X\right]|X\right]\\
(B) &&  E\left[B * E\left[A|X\right]|X\right] = E[ B | X] E[A|X]\\
\text{for $A$ and $B$ independent, } \; (C) && E[A * B |X] = E[A|X] E[B|X]
\end{align}
To understand these things more deeply you need to learn about sigma algebras, conditional expectation etc. See Capinski and Kopp, Measure, integral and probability, 2004 for a textbook on that. Unfortunately I can't remember it well enough to give a good intuitive explanation for why (A), (B) and (C) hold if they're not clear to you.
We can then apply these to get the result
\begin{split}
E\left[\frac{Y_i^{\left(t\right)} 1\{T_i = t\}}{p_t\left(X_i , W_i \right)} | X_i , W_i \right] & = E\left[ E\left[\frac{ Y_i^{\left(t\right)} 1\{T_i = t\}}{p_t\left(X_i , W_i \right)} | X_i , W_i \right] | X_i , W_i \right] (1)\\
& = E\left[\frac{ E\left[Y_i^{\left(t\right)} 1\{T_i = t\} | X_i , W_i \right]}{p_t\left(X_i , W_i \right)} | X_i , W_i \right] (2) \\
& = E\left[\frac{ E\left[Y_i^{\left(t\right)}| X_i , W_i \right] E\left[ 1\{T_i = t\}| X_i , W_i \right] }{p_t\left(X_i , W_i \right)} | X_i , W_i \right] (3) \\
& = E\left[\frac{ E\left[Y_i^{\left(t\right)}| X_i , W_i \right] p_t\left(X_i , W_i \right) }{p_t\left(X_i , W_i \right)} | X_i , W_i \right] (4) \\
& = E\left[E\left[Y_i^{\left(t\right)}| X_i , W_i \right] | X_i , W_i \right] (5) \\
& = E\left[Y_i^{\left(t\right)}| X_i , W_i \right] (6)
\end{split}
(1) holds by (A)
(2) holds because $p_t\left(X_i , W_i \right) = E\left[ 1\{T_i = t\}| X_i , W_i \right]$, so we can apply (B)
(3) holds by (C)
(4) holds by definition in the link you said
(5) is just cancelling numerator and denominator
(6) holds by (A)
Comment: This answer is exactly what I was looking for, thanks!
Comment: No worries at all, glad to help!

When is E(A*B) = E(A * E(B))?


POSTFIX Error: 421 4.7.0 Try again later, closing connection. (EHLO)

Question: I setting main.cf in postfix on Linux SUSE like this
inet_interfaces = localhost
inet_protocols = ipv4

masquerade_domains =
masquerade_exceptions = root
mydestination = $myhostname, localhost.$mydomain
myhostname = localhost
mynetworks_style = subnet
relayhost=[smtp-relay.gmail.com]:25

smtpd_delay_reject = yes
smtpd_helo_required = no

smtpd_client_restrictions =

smtpd_helo_restrictions =

smtp_sasl_auth_enable = no
smtp_sasl_security_options =
smtp_sasl_password_maps =
smtpd_sasl_auth_enable = no

smtp_use_tls = no

I tried to telnet smtp-relay.gmail.com 25 and it's working
Anyway, when I tried to send email with postfix in server I got the issue.
root@localhost
(host smtp-relay.gmail.com[ipv4] refused to talk to me: 421 4.7.0 Try again later, closing connection. (EHLO)

Answer: Looking at the official Google documentation looks like a "ratelimit" on their side:
 421, "4.7.0", Try again later, closing connection. This usually indicates a Denial of Service (DoS) for the SMTP relay at the HELO stage.

How many mails per minute are you sending? By experience, usually Gmail accepts 50/100 mail/minute tops.
EDIT as per comment
Well, looks like the same error appears with a wrong HELO/HELO (as I first suspected).
I just tried:
$> telnet smtp-relay.gmail.com 25
Trying 220.127.116.11...
Connected to gmail-smtp-relay.l.google.com.
Escape character is '^]'.
220 smtp-relay.gmail.com ESMTP b8-v6sm74445wrr.1 - gsmtp
helo localhost
421 4.7.0 Try again later, closing connection. (EHLO) b8-v6sm74445wrr.1 - gsmtp
Connection closed by foreign host.

So it's definitively your EHLO string.
You have myhostname = localhost in your main.cf file, you should change it with myhostname = [your server fqdn], i.e. you should have a Fully qualified domain name for your server, complete with correct DNS/rDNS entries.
Comment: I just sent only 1 email per minute or I can say 1 email per hour.
Comment: Using temporary error code on a permanent error is not very wise from Google.
Comment: @Mr Shunz, I still don't have FQDN just now maybe the process will finish on the next week, so can I use ip adress instead?
Comment: @user9111600 I just tried and it seems the error does not appear when using `helo IP.ADD.RE.SS`. Give it a try!
Comment: @ Mr Shunz, I just try with your suggestion but it still showing..  root@localhost
(delivery temporarily suspended: host smtp-relay.gmail.com[22.214.171.124] refused to talk to me: 421 4.7.0 Try again later, closing connection. (EHLO)
Comment: It showing error already: postfix: warning: valid_hostname: numeric hostname: 188.8.131.52

maybe I cannot use ip to being hostname.
Comment: @user9111600 you should definitively get a FQDN then.
Answer: I did run into this issue when using the Symfony/Mailer in my PHP Application. Which did use the SMTP relay like this:
MAILER_DSN=smtp://smtp-relay.gmail.com:587

The fix was defining the local_domain parameter:
MAILER_DSN=smtp://smtp-relay.gmail.com:587?local_domain=your-domain.com

Comment: This solution worked for me!


how to set and get cookie with compojure?

Question: Created project using lein new compojure project-name and have the server referencing (wrap-defaults project-name site-defaults).
Inside my handler I am calling controllers and passing the params to those controllers. Project structure:
handler.clj ;; ring accesses def app
controllers/app.clj ;; where route params are sent
example: (GET "/signup" {params :params} (controller-app/signup params))

So the issue I am having is I cannot figure out how to get or set cookies from the controllers file. Things I have tried:

passing cookie as a param: {cookies :cookies}. I was able to view the default cookie but could not set any data.
Use cookie-response and cookie-request. Same problem of not being able to add to the cookie.
Using the :cookie in every route possible and getting nothing back.

Any help would be much appreciated. There is not much documentation on this so unfortunately the problem has taken a fair amount of time.
Answer: Finally was able to solve it by brute force. It's no joke when people say the documentation for Clojure is pretty sparse. A couple of notes on ring:

Sessions are not what you think of when you hear sessions. It's just a signed cookie and a poorly documented one at that. Just ignore it. The few tutorials I did find constantly misspoke and used "sessions" when they meant "signed cookie". The documentation even uses cookies and sessions interchangeably. Why? I have no idea as they are completely separate methods of storing data. Sessions are a server side in memory store and cookies are a client side browser store.
:headers are needed otherwise the cookie will just download into an empty text file. Took forever to find out why this was the case.
:path has to go into the cookie body otherwise the cookie will only persist for the page where the cookie was set. You would think :path would go after :cookies and above :body. It makes no sense to me why the :path would be included in the hashmap along with the value. Again, no documentation for how or why so this took forever as well.

Now onto how to do this:
Here you pass the cookie to the controller from inside your handler. Cookies are available by default if you used "lein new compojure app-name" to create your app. I had to read the source code to figure this out.
default namespace (app-name/handler.clj) -
(ns some-namespace.handler
  [compojure.core :refer :all]
  [compojure.route :as route]
  [ring.middleware.defaults :refer [wrap-defaults site-defaults]
  [app-name.controllers.home :as home-controller))

Your app routes (app-name/handler.clj) -
(defroutes app-routes
  (GET "/" {cookies :cookie} (home-controller/home cookies)))

Here is how you set the cookie itself (app-name/controllers/home.clj).
(ns app-name.controllers.home)

(defn home [cookies]
  {:headers {"Content-Type" "Set-Cookie"},
   :cookies {"cookie-name" {:value "cookie-value", :path "/"}},
   :body "setting a cookie"})

Bottom of handler.clj using default wraps for specified routes (app-name/handler.clj)
(def app
  (wrap-defaults app-routes site-defaults ))

This was a very simple problem that turned out to be far more complex. It took me 3 days to figure all of the above out. I am new to Clojure/Ring/Compojure but this has been the worst experience I have had yet programming.
It's really a problem of just enough abstraction to become dangerous (so basically nothing is obvious). Libraries like Ring REALLY need to be better documented and over explained if wider adoption is wanted.
Anyways, I hope this helps someone.
Answer: I personally spent quite some time to making cookie reading work due to my poor understanding of destructuring in compojure.
After wrapping yout application with the wrap-cookies handler, you need to destructure cookies variable "the clojure way" and not "the compojure way" since the cookies map is not in the request params map.
Example that doesn't work :
  (GET "/read-cookie" [cookies]
   (let [name (get-in cookies ["name" :value] "")]
     (if (empty? name)
       (layout/common [:h1 "I don't read a cookie"])
       (layout/common [:h1 (str "I read a cookie : " name)]))))

Example that works :
  (GET "/read-cookie" {:keys [cookies]} ;; or {cookies :cookies}
   (let [name (get-in cookies ["name" :value] "")]
     (if (empty? name)
       (layout/common [:h1 "I don't read a cookie"])
       (layout/common [:h1 (str "I read a cookie : " name)]))))

Hope this helps,
Answer: Use wrap-cookie from ring this will add cookie key in your request map, more details are here, then with compjure you have access to the req map, and you can use it.
https://github.com/ring-clojure/ring/wiki/Cookies
Comment: Unless I am missing it there is only one example for using cookies. I was able to borrow the {cookies :cookies} part. However, the option for updating the :cookie  `{:cookies {"name" name}` doesn't seem to work.
Comment: `(wrap-defaults app-routes site-defaults)` is the default from compojure when you create a new app and is what I am using. Site-defaults already sets the wrap-cookie to true and bundles it: https://github.com/ring-clojure/ring-defaults/blob/master/src/ring/middleware/defaults.clj
Comment: This still is not working. Sessions will not persist either. I'm a little confused how something as simple as cookies is such a problem child.


Dúvida PDO SQL Injection

Question: estou me aventurando um pouco com PDO, ainda no inicio, e tenho uma dúvida referente a uma query com SQL Injection, segue ela:
<code>$insert = "INSERT INTO tabela (campo1, campo2, campo3) VALUES (:valor1,
:valor2, :valor3)";

$db = new db();
$db = $db->connect();
$stat1 = $db->prepare($insert);
$stat1->execute([
  ":campo1" => $valor1,
  ":campo2" => $valor2,
  ":campo3" => $valor3
});
</code>
Isso estaria correto?
Está funcionando sem problemas, mas é seguro?
Muito obrigado galera!
Answer: Está seguro sim, desde que você não concatene parâmetros com sua query($insert no caso) está tudo seguro

Dúvida PDO SQL Injection


bias in SVM in a balanced set - effect of sample size?

Question: I have a dataset with many subjects, and for each subject I have 100 samples for an X variable, while Y has exactly 50%/50% cases for label 1/2. I am trying to run cross-validation with SVM and found that accuracies are always below 50% despite the set being balanced.
So I made up the following simulation and changed the sample size (see two figures for 50 and 1000).  Still, I get the same below 50% bias. Changing k has an effect, and increasing the sample size also helps - but this doesn't go away - SVM keeps giving me a mean accuracy below 50%, over samples. Cost doesn't make a difference as well as far as I can tell.
Any thoughts???
Thanks,
Nitzan
<code>library(e1071)

nsamples=100
N=2000
x<-runif(nsamples,0,1)
y<-array(1:2, dim=c(nsamples))
z<-array(0,dim=c(N))

for (i in 1:N){
x<-x[sample(length(x))]
y<-y[sample(length(y))]
model=svm(x,y,
          type='C-classification',
          kernel="linear",cross=20)
z[i]=mean(model$accuracies)}

histogram(z,nint=20,xlim=c(0,100))
mean(z)
</code>
Answer: Figured this one out. The problem was that from some reason svm did not use stratification for cross validation...


How do I programatically create a context?

Question: I'm using the migrate module to move content into a Drupal site. Some of this content needs to be created as blocks and added to a region using contexts. I have the creation of blocks (actually, boxes) working using a purpose-built module, but I don't know where to begin on the context side of things - looking for something like add_block_to_context() but I cannot find anything. Any ideas?
Answer: After checking the code used in the context test units for Drupal 6:
ctools_include('export');
$context = ctools_export_new_object('context');
$context->name = 'testcontext';
$context->conditions = array('path' => array('values' => array('admin')));
$context->reactions = array('debug' => array('debug' => TRUE));
$saved = context_save($context);

You can easily code your reactions or conditions then save the context.
BTW to get all context you can use context_context_list().
Answer: The easiest way to do this, is to actually create the full context with all blocks first and then export it, using the built in export option or features.
Comment: I'm talking hundreds of blocks here, so it would be much better if I can automate this
Answer: I have fixed this issue using below codes.
Before that use context to export all values to check blocks array format or some structure.
$context = new stdClass();
$context->disabled = FALSE;
$context->api_version = 3;
$context->name = 'name-of-context';
$context->description = 'Description';
$context->tag = '';
$context->conditions = array(
'path' => array(
  'values' => array(
    'node/120' => 'node/120',
  ),
),
);
$context->reactions = array(
'block' => array(
  'blocks' => call_function_to_generate_block_array(),
),
'theme_html' => array(
  'class' => 'myclass',
),
);
$context->condition_mode = 0;
context_save($context);

Note: you can save all these values into one script file & can usedrush scr script.php command to execute it.


AuthGuard and RedirectTo not working for root path

Question: I am working on a angular application, Which has following URL Paths,

/ (root)
/courses
/courses/create
/courses/:id
/auth/login

I have added AuthGuard for all routes except auth/login. AuthGuard redirects to auth\login if not authenticated.

app-routing.module.ts
export const Approutes: Routes = [
  {
    path: '',
    canActivate: [AuthGuard],
    component: FullComponent,
    loadChildren: () => import('./pages/pages.module').then(m => m.PagesModule) // loading from pages-routing.ts
  },
  {
    path: 'auth',
    component: PlainComponent,
    children: [
      {
        path: '',
        pathMatch: 'full',
        redirectTo: 'login'
      },
      {
        path: 'login',
        component: LoginComponent
      }
    ]
  },
  {
    path: '**',
    redirectTo: ''
  }
];

pages-routing.ts
export const PagesRoutes: Routes = [
    {
        path: '',
        children: [
            {
                path: '',
                pathMatch: 'full',
                redirectTo: 'courses'
            },
            {
                path: 'courses',
                component: CourseMainPageComponent,
                data: {
                    title: 'My Courses'
                }
            },
            {
                path: 'courses/create',
                component: CourseCreatePageComponent,
                data: {
                    title: 'Create Course'
                }
            },
            {
                path: 'courses/:id',
                component: CourseShowPageComponent,
                data: {
                    title: 'Course Detail'
                }
            },
        ]
    }
];

The Problem
All routes and authGuard works fine. But when I enter the root URL \, I needed to redirect to \courses, But it's not working. Also in root URL \ AuthGuard is not redirecting me to auth\login even.

NOTE
  I don't get any run-time or compile error.
Comment: can you make your problem of  demo  in stackblitz here?
Comment: FullComponent is loading on empty route. Try to remove component and loadChildren only.
Comment: Uhh... But The FullComponent is a main layout. Then children are loading in a certain area.. Anyway lemme try
Answer: You need to change the pathMatch strategy to full in the route you are using to redirect. As per the docs,

The path-match strategy 'full' matches against the entire URL. It is important to do this when redirecting empty-path routes. Otherwise, because an empty path is a prefix of any URL, the router would apply the redirect even when navigating to the redirect destination, creating an endless loop.

Your route configuration will now look like so
export const PagesRoutes: Routes = [{
    path: '',
    children: [{
        path: '',
        redirectTo: 'courses',
        pathMatch: 'full'
    },
    // Add other routes here
    ]
}];


Using duplicity in a disaster recovery scenario

Question: I am using duplicity for backups on my Debian servers. I have successfully backed up and restored files using duplicity.
In my backup script, I have /usr/bin/dpkg --get-selections > /installed_packages_<hostname> so that I can backup the package list for an easy restore of all installed packages.
Considering all packages get the default package maintainer's version of the configuration, is it possible to tell duplicity to overwrite the destination files and folders? Essentially, is it possible to overwrite / with yesterday's full/incremental backup?
Comment: You really should handle packages with a configuration management system like Ansible/Puppet/Chef.
Comment: We use puppet. Sometimes we forgo the puppet route for a single package that doesn't need to be managed.
Answer: I suggest you restore from duplicity to a different location (probably on a different machine), then use file system tools to copy files into place. That way you can overwrite whichever you choose.
Just in case you haven't thought of it: Your strategy assumes that all packages were up-to-date when the backup was created.


Como funciona o "lookahead positivo"(?=X) combinado com o "lookbehind positivo"(?<=X)?

Question: Após responder esta pergunta, e apesar de conseguir perceber o que está ocorrendo na expressão regular da minha resposta, fiquei curioso para saber como o trecho ((?<=;)|(?=;)) funciona.
Li nesta resposta o que cada um faz, e também em outras várias fontes, mas confesso que não entendi bem como a expressão citada funciona.
Se possível, gostaria de uma explicação, pois estou tentando aprender expressão regular mas as explicações por ai são complicadas e com termos que muitas vezes eu não estou familiarizado.
Answer: Você já deve ter ouvido aquela frase que diz :

Só porque você chegou no seu objetivo não significa que esteja certo

Pois bem, o que ocorreu com sua REGEX é o seguinte, vou explicar com outra para ficar mais claro.
/((?<=t)|(?=a)).+/

Explicação

((?<=t)|(?=a)) - Grupo em que uma das ocorrências deve ocorrer, dando preferencia para a primeira (?<=t)
.+ - Qualquer coisa o máximo que conseguir e tendo no mínimo 1.

Assim poderíamos desmembrar em duas REGEX :

/(?<=t).+/ - Qualquer coisa que vier depois de t
/(?=a).+/ - Qualquer coisa que tiver a

Testes
$regex = '~((?<=t)|(?=a)).+~';

$testes = array(
    'ana',
    'tania',
    'anastasia',
    'etilico',
    'aguilherme'
    'guilherme'
);

foreach ($testes as $k => $value){
    preg_match($regex, $value, $matches);
    print_r($matches);
}

Saida
[0] => ana
[0] => ania
[0] => anastasia
[0] => ilico
[0] => aguilherme
[0] =>

Retomando a sua REGEX ((?<=;)|(?=;))
Ela é redundante, pois ambas estão verificando ; assim se existe da sentença (?=;) então também vai ocorrer (?<=;).
Contudo ha um porem, (?<=...) depende do que vem a seguir, de tal forma que se   for .+, mas a virgula vir no fim da sentença ;$, a segunda parte não vai ser completada .+, assim caindo na segunda (?=;).
Duvidas
Essa ultima explicação pode deixar um pouco confuso, qualquer duvida pergunte.
Adendo - quanto a sua duvida

O problema que tive foi com o fato de quando usava o lookahead, a virgula não era isolada e quebrada em um indice pelo split do java quando ela vinha antecedida de outra string, e o inverso ocorria quando era o lookbehind veja por isso a confusão para entender cada um.

O que ocorre é o seguinte :
Ambas as REGEX estão "explodindo" pela junção dos caracteres (esse exemplo o grupo 2), mas que (?<=;) é mais especifico que (?=;), lembrando acima:

(?<=;) - O que vier depois de ;
(?=;) - sentença que contenha ;

Assim (?<=;) vai explodir pela junção que vem depois do ; formando as palavras que você viu pontoevirgula;, delinha;.
Mas o (?=;) poderia explodir com ambos tanto o que vem antes quanto o que viria depois, contudo o split consome o caractere apos usá-lo, desta forma só ocorre a explosão pelo primeiro (que vem antes) gerando as outras palavras que você viu: ;espaco, ;QUEBRA
Comment: Já que ele não está aqui, vou responder por ele.. Bem, na verdade sua expressão não vai isolar o `;`, o que está separando ele dos outros termos é o próprio `String#split();`. Caso não tenha entendido, veja [esta](https://prnt.sc/gy9ao7) foto. Seu regex está encontrando **dois** valores em posições diferentes (nulos), no caso, o split do Java apenas irá dividi-los. Veja [este](https://image.prntscr.com/image/GbZnjeLiRKi5mOobIC8Rpg.png) exemplo (espero não ter ficado muito confuso).
Comment: O problema que tive foi com o fato de quando usava o *lookahead*, a virgula não era isolada e quebrada em um indice pelo split do java quando ela vinha antecedida de outra string, e o inverso ocorria quando era o *lookbehind* veja: https://ideone.com/yqWyjj por isso a confusão para entender cada um.
Comment: @Articuno estou meio ocupado agora, jaja explico esse efeito, mas de antemão, tem a ver com o consumo do `;`
Comment: @Articuno Editado, veja se anda ficou duvidas
Comment: Entendi sim, sem abusar da sua boa vontade, então porque os dois combinados isolam o `;`?
Comment: @Mateus exatamente isso, obrigado :D
Comment: @Mateus isso deveria ser outra resposta, complementando a do guilherme viu, entendi pela sua explicação somada a resposta dele.


Using LIKE in Count(IIF()) in MS Access, get NA count

Question: I'm attempting to get a count of NAs in a field in a table in MS Access. I have multiple NAs:

#N/A* (i.e. NAs that start with hash & "N/A" & some more text that varies.)
NaN
NA
N/A

(They all mean something different for us, so it i actually useful to have the different NAs.)
This works for one specific NA, "#N/A N/A":
SELECT Count(IIf([Short Int % Eqy Flt] = '#N/A N/A' ,0 )) AS MyTotal
FROM tblFirst250

The above returns 141, which seems correct.
This returns 0:
SELECT Count(IIf([Short Int % Eqy Flt] LIKE '#N/A' ,0 )) AS MyTotal
FROM tblFirst250

The above should return 142 because I have 141 "#N/A N/A" and 1 "#N/A Invalid Security".
Really what I am after is something that counts all of my NAs in the [Short Int % Eqy Flt] field. See my list of NAs above.
Answer: # has a special meaning [Any single digit (0–9)] when used in a Like pattern.  You can tell Access to treat it as just the normal # character by putting it inside a character range like this ... [#].
Also, I think you want to match [#]N/A followed by additional characters, so tack on a wildcard character to the end of the pattern.
SELECT Sum(IIf([Short Int % Eqy Flt] LIKE '[#]N/A*', 1, 0)) AS MyTotal
FROM tblFirst250;

I used Sum instead of Count.  But if you prefer Count ...
SELECT Count(IIf([Short Int % Eqy Flt] LIKE '[#]N/A*', 1, Null)) AS MyTotal
FROM tblFirst250;

Comment: And this answers the question of getting all of my NAs: SELECT Sum(IIf([Short Int % Eqy Flt] LIKE '[#]N/A*' OR [Short Int % Eqy Flt]  = 'N/A' OR [Short Int % Eqy Flt]  = 'NA' OR [Short Int % Eqy Flt]  = 'NaN', 1, 0)) AS MyTotal
FROM tblFirst250
Comment: I don't know.  If there is a difference, I would guess `Count` as the winner.   Try it both ways and see whether you can even notice a difference.