How to run 2 services during 'docker run'?

Question: I have a Dockerfile that creates an image with Apache/php and redis inside.
I am aware that it should be splitted in 2 containers. But I whant to know if it is possible to start apache and redis during the run process.
For now I could run in two different ways:

docker run --rm -p 80:80  -p 6379:6379 -v $MY_FULLPATH:/var/www/html -e REMOTE_HOST=$REMOTE_HOST  my_img  redis-server
docker run --rm -p 80:80  -p 6379:6379 -v $MV_FULLPATH:/var/www/html -e REMOTE_HOST=$REMOTE_HOST  my_img  apache2-foreground

If I run using the first method I must open the terminal to manually start apache.
If I run using the second one I must start REDIS manually.
By the documentation : "If you list more than one CMD then only the last CMD will take effect." I know that only "redis-server" will be working at the start.
So Is there a way to set booth automatically? .
This is my Dockerfile:
FROM php:5-apache

## Update apt-get
RUN apt-get update

RUN apt-get install -y figlet

RUN figlet MV_Docker_Build

## UTILITIES
RUN figlet vim
RUN apt-get install -y vim
RUN figlet wget
RUN apt-get install -y wget
RUN figlet CURL
RUN apt-get install -y curl

## APACHE2  basic installation
RUN figlet APACHE2
RUN apachectl -M
RUN a2enmod rewrite
RUN a2enmod expires
RUN service apache2 restart
RUN apachectl -M

## ====================================================================== > PHP modules

## Note: when installing from php5 for some modules we need to copy from php5/mods-available to local/etc/php/conf.d and create a simbolic link
RUN figlet PHP_MODULES
RUN php -m

RUN apt-get install -y php5-common

RUN apt-get install -y php-calendar
#RUN cp /etc/php5/mods-available/calendar.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/calendar.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/calendar.so

#RUN docker-php-ext-install calendar

RUN docker-php-ext-install bcmath

RUN apt-get install -y php5-mhash
#RUN cp /etc/php5/mods-available/mhash.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/mhash.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/mhash.so

RUN apt-get install -y php5-intl
RUN cp /etc/php5/mods-available/intl.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/intl.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/intl.so

RUN apt-get install -y php5-mcrypt
RUN cp /etc/php5/mods-available/mcrypt.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/mcrypt.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/mcrypt.so

RUN apt-get install -y php5-redis
RUN cp /etc/php5/mods-available/redis.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/redis.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/redis.so

RUN apt-get install -y php5-mysql
RUN cp /etc/php5/mods-available/mysql.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/mysql.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/mysql.so

RUN cp /etc/php5/mods-available/opcache.ini /usr/local/etc/php/conf.d

RUN apt-get install -y php5-gd
RUN cp /etc/php5/mods-available/gd.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/gd.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/gd.so

RUN apt-get install -y php5-gdcm
RUN cp /etc/php5/mods-available/gdcm.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/gdcm.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/gdcm.so

RUN apt-get install -y php5-vtkgdcm
RUN cp /etc/php5/mods-available/vtkgdcm.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/vtkgdcm.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/vtkgdcm.so

RUN apt-get install -y php5-ldap
RUN cp /etc/php5/mods-available/ldap.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/ldap.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/ldap.so

RUN apt-get install -y php5-xsl
RUN cp /etc/php5/mods-available/xsl.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/xsl.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/xsl.so

RUN apt-get install -y php5-tidy
RUN cp /etc/php5/mods-available/tidy.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/tidy.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/tidy.so

RUN apt-get install -y php5-xmlrpc
RUN cp /etc/php5/mods-available/xmlrpc.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/xmlrpc.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/xmlrpc.so

RUN apt-get install -y php5-pgsql
RUN cp /etc/php5/mods-available/pgsql.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/pgsql.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/pgsql.so

RUN cp /etc/php5/mods-available/mysqli.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/mysqli.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/mysqli.so
RUN cp /etc/php5/mods-available/pdo.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/pdo.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/pdo.so
RUN cp /etc/php5/mods-available/pdo_mysql.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/pdo_mysql.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/pdo_mysql.so
RUN cp /etc/php5/mods-available/pdo_pgsql.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/pdo_pgsql.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/pdo_pgsql.so
RUN cp /etc/php5/mods-available/readline.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/readline.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/readline.so

#RUN apt-get install -y php5-snmp
#RUN cp /etc/php5/mods-available/snmp.ini /usr/local/etc/php/conf.d && ln -s /usr/lib/php5/20131226/snmp.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/snmp.so

RUN figlet PHP_MODULES
RUN php -m

## ====================================================================== > End of PHP modules

## ====================================================================== > REDIS
RUN figlet REDIS
RUN apt-get install -y telnet redis-server
RUN apt-get install -y redis-server

## ====================================================================== > NPM
RUN figlet NPM
RUN apt-get install -y npm

## ====================================================================== > COPYING php.ini
RUN figlet COPYING__php.ini
RUN cp /etc/php5/cli/php.ini /usr/local/etc/php/
RUN ls -l /usr/local/etc/

## ====================================================================== > XDEBUG
# XDEBUG EXTENSION FOR PHP | DOCUMENTATION => https://xdebug.org/docs/remote
#
# install xdebug and enable it. This block of code goes through the installion from source and compiling steps found
# on the xdebug website
# https://xdebug.org/docs/install
RUN figlet INSTALLING__XDEBUG
RUN cd /tmp \
    && wget http://xdebug.org/files/xdebug-2.5.4.tgz \
    && tar -xvzf xdebug-2.5.4.tgz \
    && cd xdebug-2.5.4 \
    && phpize \
    && ./configure  \
    && make \
    && cp modules/xdebug.so /usr/local/lib/php/extensions/no-debug-non-zts-20131226/

RUN figlet INSIDE_no-debug-non-zts-20131226/
RUN ls -l /usr/local/lib/php/extensions/no-debug-non-zts-20131226/

#https://stackoverflow.com/questions/47596381/how-to-setup-an-variable-env-inside-dockerfile-to-be-overriden-in-a-docker-conta?noredirect=1#comment82150863_47596381
# ADD xdebug configurations
RUN figlet SETTING__XDEBUG__php.ini
RUN { \
        echo '[xdebug]'; \
        echo 'zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20131226/xdebug.so'; \
        echo 'xdebug.remote_enable=1'; \
        echo 'xdebug.remote_port=9000'; \
        echo 'xdebug.remote_autostart=1'; \
        echo 'xdebug.remote_handler=dbgp'; \
        echo 'xdebug.idekey=dockerdebug'; \
        echo 'xdebug.profiler_output_dir="/var/www/html"'; \
        echo 'xdebug.remote_connect_back=0'; \
        echo 'xdebug.remote_host=$REMOTE_HOST'; \
    } >> /usr/local/etc/php/php.ini

RUN figlet XDEGUB__IN__php.ini
RUN cat /usr/local/etc/php/php.ini

## ====================================================================== > COMPOSER

RUN figlet Escape_SUDO
RUN exit

RUN figlet Install__COMPOSER
RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" \
    && php -r "if (hash_file('SHA384', 'composer-setup.php') === '544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" \
    && php composer-setup.php \
    && php -r "unlink('composer-setup.php');" \
    && mv composer.phar /usr/bin/composer

RUN composer

## ====================================================================== > PhpUnit

RUN figlet PhpUnit
RUN curl https://phar.phpunit.de/phpunit-5.6.0.phar -L -o phpunit.phar
RUN chmod +x phpunit.phar
RUN mv phpunit.phar /usr/local/bin/phpunit

RUN figlet COPYING_entrypoint.sh
COPY entrypoint.sh /usr/local/bin/
RUN figlet Permission_entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh

ENTRYPOINT [ "entrypoint.sh" ]

# EXPOSE - PORTS
RUN figlet EXPOSE_PORTS
EXPOSE 80
#EXPOSE 6379
EXPOSE 9000
#CMD ["apache2-foreground","redis-server"]

#ADD run.sh /run.sh
COPY run.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/run.sh
CMD ["/bin/sh", "-c", "/run.sh"]

This is the run.sh
#!/usr/bin/env bash
exec apache2-foreground &
exec redis-server &

This is entrypoint.sh
#!/bin/bash
set -e

# Check if our environment variable has been passed.
if [ -z "${REMOTE_HOST}" ]
then
  echo "REMOTE_HOST has not been set."
  exit 1
else
  sed -i.bak "s/\$REMOTE_HOST/${REMOTE_HOST}/g" /usr/local/etc/php/php.ini
fi

exec "$@"

Answer: You can start more than one process a couple of ways:

Start them as a service
Start them trough a cron job (@reboot)
Start processes in backgound

UPDATE after your Dockerfile post
Before I'll try to answer a couple of pointers:

Every time you enter a RUN command in the Dockerfile it will create a new layer and it makes the image bigger and the build slower.
This container clearly tries to do too much. A container should do 1 thing and 1 thing good.

Having said that, I think I have a solution :-)

remove the run.sh
change your entrypoint to this:

    #!/bin/bash
    set -e
    # Check if our environment variable has been passed.
    if [ -z "${REMOTE_HOST}" ]
    then
      echo "REMOTE_HOST has not been set."
      exit 1
    else
      sed -i.bak "s/\$REMOTE_HOST/${REMOTE_HOST}/g" /usr/local/etc/php/php.ini
    fi
    echo "Starting redis"
    exec redis-server &
    exec "$@"

and The end of your Dockerfile to this:

    RUN figlet EXPOSE_PORTS
    EXPOSE 80
    #EXPOSE 6379
    EXPOSE 9000
    CMD ["apache2-foreground"]

rebuild and have fun :-)
Screenshot of my running console
Comment: Hi Ivonet, I followed your suggestion but it is not working. I have created a run.sh file. Inside I used `#!/usr/bin/env bash exec apache2-foreground & exec redis-server &` . Inside Dockerfile `ADD run.sh /run.sh ...` your code. And I am running `docker run --rm -p 80:80  -v $MY_FULLPATH:/var/www/html -e REMOTE_HOST=$REMOTE_HOST  my_img apache2-foreground` It only starts apache. What am I missing?
Comment: have you build your image again? I've added some extra lines to the post
Comment: yes I did. In fact I have destroyed it. It starts apache or REDIS, depending in what I call during `docker run ...`.
Comment: leave of the argument at the end
Comment: if I leave of the end argument the container exits just after created. I just check inside the container and this is what I found inside run.sh => `root@48b993e1b824:/var/www/html/App/codedeploy# vi run.sh

#!/bin/sh
service apache2 restart`. It seems that redis-server is not being saved during the build process
Comment: You have to create this shell script outside of your container and ADD it.. It might be a good idea if you edit your question and provide the complete Dockerfile
Comment: yes... this is what I am doing. I have the file inside the same level as my Dockerfile. I will post my Dockerfile.
Comment: After use COPY I can see `#!/usr/bin/env bash
exec apache2-foreground &
exec redis-server &` But still not working. I must start apache or REDIS manually
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/160968/discussion-between-ivonet-and-zwitterion).


Login php retornando sempre vazio

Question: Estou fazendo uma aplicação e tenho o seguinte problema: Eu cadastro um usuário, ele mostra no banco, ao tentar logar, mesmo preenchendo os campos corretamente, a SESSION['em_branco'] retorna sempre no index.php e ainda mais... aparece os seguintes erros:
Notice: Undefined index: usuario in C:\wamp64\www\app\php\login.php on line 4
Notice: Undefined index: senha in C:\wamp64\www\app\php\login.php on line 5
ARQUIVO LOGIN.PHP
    <?php
require '../config/conexao.php';

$usuario = $_POST['usuario'];
$senha = $_POST['senha'];

if (isset($usuario) && !empty($usuario) && isset($senha) && !empty($senha))
{
    $sql = "SELECT * FROM users WHERE USUARIO = :usuario AND SENHA = :senha";
    $query = $con->prepare($sql);
    $query->bindValue(":usuario", $usuario);
    $query->bindValue(":senha", md5($senha));
    $query->execute();

    if ($query->rowCount() == 1)
    {
        $user_logged = $query->fetchAll(PDO::FETCH_ASSOC);

        print_r($user_logged);

        $_SESSION["nome_usuario"] = $user_logged["USUARIO"];

        $_SESSION["logado"] = true;

        header('Location: ../pages/timeline.php');
        exit();
    }
    else
    {
        $_SESSION['nao_autenticado'] = true;
        header('Location: ../index.php');
        exit();
    }
}
else
{
    $_SESSION['em_branco'] = true;
    header('Location: ../index.php');
    exit();
}

$con = null;
?>

ARQUIVO INDEX.PHP
<?php session_start(); ?>
<!DOCTYPE html>

    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>

    <link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">

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

    <meta charset="utf-8">
    <title>EAC | LOGIN</title>

WELCOME

HAVE FUN AS YOU NEVER HAVE FUN WHILE STUDYING

LOG IN

            <?php if(isset($_SESSION['nao_autenticado'])) { ?>

Usuário ou senha inválidos.

            <?php } unset($_SESSION['nao_autenticado']); ?>

            <?php if(isset($_SESSION['em_branco'])) { ?>

Preencha todos os campos.

            <?php } unset($_SESSION['em_branco']); ?>

            <form class="logForm_form" action="php/login.php" method="post">

                <input class="mb-4" type="text" placeholder="Usuario" name="usuario">
                <input class="mb-4" type="password" placeholder="Senha" name="senha">

                  <input type="checkbox" id="remember" name="scales">
                  Remember me

                Forgot your password?

              <button class="btn btn-primary mb-2" id="btnLogin">LOGIN</button>
              REGISTER
              CONVIDADO
            </form>

Espero ansiosamente que alguém me ajude, grato desde já.
Comment: Nao deveria ter ```type=submit```  no botao LOGIN?
Comment: Não é necessário pois é o único button dentro do formulário, sendo assim ja é um submit, os outros são apenas links estilizados de botões.
Answer: Creio que o erro é por não haver nenhum botão type="submit", sendo assim, os dados do formulário podem não estar passando corretamente para o arquivo que recebe os dados, fazendo com que
$variável = $_POST['campo'];
não receba nenhum valor e dê erro.
Tenta colocar SUBMIT no botão LOGIN
Comment: Não funcionou, Jerfeson
Comment: Hoje mais cedo posso tentar refazer seu código aqui para lhe ajudar, se você quiser é claro. Vc ainda vai querer?
Comment: Acho que sei onde está seu erro. Tenho 8p% de certeza. Não é nada no php pelo que creio
Comment: Quero ajuda sim, é um projeto pessoal de importância.
Comment: Onde seria esse erro?
Comment: Olá, Jeferson, conseguiu achar algo?
Answer: Consegui resolver, além de retirar a $_SESSION que cuida dos campos vazios eu substitui ela por um REQUIRED na tag input HTML, isso fez com que nao houvesse erros na query, na session e está funcionando perfeitamente.
Obs: botao não necessita de submit quando é o único do formulário, ou seja, por sua vez, automaticamente já é um submit.

Login php retornando sempre vazio


Convergence of a sequence in $\mathbb R^n$ with a special property

Question: Hi folks, I'm trying to prove (or find a counterexample) of this statement:
Let $(x_k)$ be a sequence in $\mathbb R^n$
 such that  $(x_k - x_{k+1})\to0$,
show that $(x_k)$ converge.
Answer: $x_n = \sum_{k=1}^n\dfrac1{k}$.
Also,
I think you should use
different letters
for the dimension
($\mathbb R^n$)
and index
($x_n - x_{n+1}$).
Comment: that's true. thanks for the tips!


Custom language negotiation module not working

Question: I'm writing a custom module to allow the use of language a language suffix (of the form -eng or -fra) rather than the standard prefix.
I'm using the language's configured prefix and have a number of functions in place.
I've implemented hook_language_negotiation_info, and have a language selector, switcher and rewriter in place.
Paths with the suffix are working except that urls aren't being updated with the suffix when they're printed in the menus, or other places.
I confirmed that the rewriter callback is being called by placing a dsm() call in the function and it seems to be taking "node/45" and returning "page/45-eng" based on the alias.  That aliased path works, but a url to "node/45" prints returns "page/45"
<code>function custom_lang_language_negotiation_info() {
 return array(
    'custom_language_provider' => array(
      'callbacks' => array(
        'language' => 'custom_lang_language_getter',
        'switcher' => 'custom_lang_language_switcher_url',
        'url_rewrite' => 'custom_lang_url_rewriter',
      ),
      'file' => drupal_get_path('module', 'custom_lang') . '/custom_lang.inc',
      'weight' => -10,
      'types' => array(LANGUAGE_TYPE_CONTENT, LANGUAGE_TYPE_INTERFACE, LANGUAGE_TYPE_URL),
      'name' => t('Custom path suffix'),
      'description' => t('Determine the language from the URL suffix.'),
      'cache' => 0,
    ),
  );
}
</code>
Thoughts or something I can try?
I may be missing something in the way urls are generated or maybe the path is being reverted somewhere.
Answer: I did the configuration with yml file.. try this solution
https://www.drupal.org/node/2775809#comment-11502283
It worked for me.


Como obter o diretório que o programa está sendo executado?

Question: Tenho uma aplicação rodando na plataforma Windows. Em um dos meus métodos preciso capturar o diretório onde esta rodando a aplicação, qual a maneira correta de se fazer isso?
Answer: Você pode estar capturando o diretório usando _getcwd .
Pode armazena-lo em uma variável e chamar assim que precisar.
getcwd é uma função POSIX é compilado por todas as plataformas compatíveis com POSIX.
você só vai precisar incluir os cabeçalhos Unist.d em UNIX e direct.h no Windows
Um Exemplo:
#include <stdio.h>
#ifdef WINDOWS
   #include <direct.h>
   #define Define_CurrentDir _getcwd
#else
   #include <unistd.h>
   #define Define_CurrentDir getcwd
 #endif

        char LOCAL_DIR[FILENAME_MAX];

         if (!Define_CurrentDir(LOCAL_DIR, sizeof(LOCAL_DIR)))
             {
             return errno;
             }

        std::cout << "Diretorio: " << LOCAL_DIR;

Answer: Para o sistema Windows você pode utilizar a função GetModuleFileName() passando ao parâmetro hModule um valor nulo. Algo como isso(não testado):
#include <iostream>
#include <Windows.h>

using namespace std;

int main ()
{   wchar_t buffer[MAX_PATH];
    GetModuleFileName(NULL, buffer, MAX_PATH) ;
    std::cout << buffer << std::endl;
    cin.get();

}

Outros sistemas operacionais:

Mac OS X: _NSGetExecutablePath()
Linux: readlink /proc/self/exe
Solaris: getexecname()
FreeBSD: se tiver o procfs pode usar readlink /proc/curproc/file - FreeBSD não tem procfs por padrão. Uma outro modo é usar a função getprogname() em conjunto com outra função, realpath().

Referências: Fonte¹ e Fonte²


How to evaluate likert items with quantiative (numerical) data

Question: While testing some software I had users fill up a survey which asks questions in Likert type item(1-5) about the 3 different states of the software. These states were: one without aid, one with aid in a particular format and one with aid in another format. This was conducted on the same group of individuals in a "try this, then this, then this, now answer the survey" format.
The survey consisted of 20 questions each of which were independent variables.
How do I go about analysing this data? While searching for answers I noticed some persons saying that I can just represent this data using bar charts to get the point across but I have doubts about this.
The software itself also collected information on the performance of users for a more objective approach. However this data is formatted into 3 groups. I originally thought about using a paired sample t-test to compare it with the following:

Without aid - Aid with 1 format
Without aid - Aid with the 2nd format
Aid with 1 format - Aid with the 2nd format

in order to determine if there was a significant difference. Would this t test be valid for comparisons like this in this scenario? Is there another option?
This is an example of the data where the values are scores for each format:

Without aid
Aid(format 1)
Aid(format 2)

5
6
7

Finally would you advise attempting to apply analysis to both the qualitative (likert) and quantiative data in order to link the two? Like for example Spearmans correlation. If yes what in particular would you suggest?
P.S: I'm a bit new to statistical analysis so I'm still learning about various tests.
The goal is to test a hypothesis that the inclusion of these formats do help the user.
Comment: I have two comments: you are using the term Likert scale incorrectly. You're confusing the item and the scale. This is a common mistake, check Wikipedia. Second, you didn't write what your goal is. A graphic presentation? Testing statistical hypotheses?
Comment: @DanielDostal Yeah its actually a likert type item and not the interval scale. The goal is to test a hypothesis  that including the formats does make a difference
Comment: Do you want to evaluate the entire test as a whole, or examine each item separately?  What I mean by that is whether the items measure the same thing, and can therefore sum to one aggregate score, or whether you are interested in the information from each item separately.
Comment: I'm interested in individual items. I think I can better articulate those and point out key information. Some categories for the survey would be things like "Helpfulness, Cumbersomeness" etc. From there I'd try to point out any difference between the formats
Answer: In my opinion, you have two choices. Either you assert that item scores are quantitative (metric) variables (which is not quite true) and use, say, a paired t-test.
The second option is that you treat the item scores as ordinal categories and model them using ordinal regression. A proportional odds model with mixed effects works very nicely here.
You need to reformat the data so that each respondent has three rows. The columns are person (levels 1 to n), aid (levels 0,1,2), and 20 columns item1, item2... item20. Then I recommend using library ordinal in R environment. You will model each item separately (so you will create 20 models).
You can use this code:
<code>#let's create toy dataset as I don't have your original data
n = 50 #number of respondents
set.seed(2)
data = data.frame(person = rep(1:n, each = 3),aid = factor(0:2))
data$item1 = factor(rbinom(n*3, 4, as.numeric(data$aid)/4)+1)
data$item2 = factor(rbinom(n*3, 4, as.numeric(data$aid)/4)+1)
#...items 3 to 19
data$item20 = factor(rbinom(n*3, 4, as.numeric(data$aid)/4)+1)

#this is how your data look like
data

#use this library
library(ordinal)

#model the first item
fit = clmm(item1 ~ aid + (1|person), data=data, link = "logit")

#results
summary(fit)

#clearer results with odds ratios
cbind(oddsRatio = exp(coef(fit)), coef(summary(fit)))[-(1:4),]

#repeat for item 2, 3... 20
</code>
Comment: I'm leaning a bit more on the paired t-test. I dont understand your comment "Either you assert that item scores are quantitative (metric) variables (which is not quite true)...". They are quantitative as they essentially keep track of user actions but it does not have a fixed interval
Comment: Item scores are ordinal. This means that level 1 is less than level 2, level 2 is less than 3, etc. But it is not necessarily true that the distance between levels 1 and 2 is the same as between 2 and 3. Thus, mean and standard deviation are likely to be meaningless numbers, so the t-test is not a reliable tool here.
Comment: However, if you're going to use a t-test, you won't be the first or last to work with item scores as metric variables. In fact, it's a pretty common (bad) habit.
Comment: So from this should I conclude that using t -test would invalidate the hypothesis? I originally thought, based on readings, that if the mean average of scores collected for the  unformatted version was higher than any of the other formats it would fail to reject the null hypothesis. With this info it seems all of this is also wrong


JAXB moxy Error: Invalid parameter type encountered while processing external metadata via properties Map

Question: I followed this example to implement moxy in my project. However I am getting the following error and have not been able to find a solution yet.
<code>   Exception in thread "main" Local Exception Stack:
   Exception [EclipseLink-50019] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.JAXBException
   Exception Description: Invalid parameter type encountered while processing external metadata via properties Map.  The Value associated with Key [eclipselink-oxm-xml] is required to be one of [Map<String, Source>], where String = package, Source = handle to metadata file.
    at org.eclipse.persistence.exceptions.JAXBException.incorrectValueParameterTypeForOxmXmlKey(JAXBException.java:245)
    at org.eclipse.persistence.jaxb.JAXBContextFactory.getXmlBindingsFromProperties(JAXBContextFactory.java:330)
    at org.eclipse.persistence.jaxb.JAXBContextFactory.createContext(JAXBContextFactory.java:115)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:128)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:249)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:372)
    at blog.bindingfile.Demo.main(Demo.java:13)
</code>
I am new to jaxb and moxy, any help towards getting my moxy setup is appreciated.
Answer: Use instance of Source, it is in the error message:
<code> Value associated with Key [eclipselink-oxm-xml] is required to be one of [Map<String, Source>], where String = package, Source = handle to metadata file.
</code>
example:
<code> ...
 javax.xml.transform.Source source =
   new javax.xml.transform.stream.StreamSource("mypackage-metadata.xml")
 map.put("example.mypackage", source);
 ...
</code>


How to suppress echos in makefile?

Question: I have the following PHONY target in Makefile
install:
        echo /usr/bin/shelldecrypt must be writable
        cp shelldecrypt /usr/bin

When I run the target it displays the command it is executing
prompt> make install
OUTPUT IS

    echo /usr/bin/shelldecrypt must be writable
    /usr/bin/shelldecrypt must be writable
    cp shelldecrypt /usr/bin

OUTPUT AS I WOULD LIKE IT

    /usr/bin/shelldecrypt must be writable
    cp shelldecrypt /usr/bin
Answer: you could add "@" before your command to surpress that echo
install:
        @echo /usr/bin/shelldecrypt must be writable
        cp shelldecrypt /usr/bin

How to suppress echos in makefile?


GoodData: Audit Trail Akin To Salesforce.com's Field History Reporting

Question: I'm beginning the process developing a dataset that will help me track changes made to records in our MySQL backend.  More specifically, I want to be able to report on the original record value, the new record value and the timestamp for when the change occurred.  Here is an example:

Record X = 20.
A change is made to Record X on March 26th so it no longer = 20.
As of March 26th, Record X = 30.

In this scenario, the original record value (for Record X) was 20, the new record value = 30 and the change occurred March 26th, 2014.
I considered taking daily snapshots and storing the snapshot data in GoodData's warehouse.  This would allow me to make daily comparisons of the record values.  The problem with this approach is that our consumption of warehouse storage space will increase dramatically and at a very fast rate.  I would prefer to track this data only when changes occur (incrementally).  I don't know exactly how to get started here.  Can someone point me in the right direction?
Answer: from what I see the best approach for you if you are going to use CloudConnect is to create a query to your MySQL database (use DB Reader component) to select data that has been changed from the last upload (from yesterday). Then you can use the incremental loading to get data into the GoodData. And have some kind of snapshot-id or snapshot-date connected.
Can you share some more details about your use case? What exactly you would like to track finally? What is being shown in dashboard?
Thanks for asking! Regards,
JT


Where do I add a jQuery UI in Drupal 7?

Question: I have a view where I want to use the jQuery UI slider.
For the moment, I've just put the following in my template.php:
<code>drupal_add_library('system', 'ui.slider');
</code>
This doesn't feel right.
Is there a better place to put something like that, or at least do a check so it only get loaded when it is needed?
Answer: Ok, you can use preprocess functions for views.

Drupal 6 - Add Javascript to a View
Programmatically set a css class of a view
Using views preprocesses to add css and js to a view

Where do I add a jQuery UI in Drupal 7?


For $f(x): y=\sqrt{x-1}$, is it possible for the range to include negative values?

Question: For $f(x): y=\sqrt{x-1}$, I have deduced that the domain for $x$ cannot include negative values, for negatives values for $x$ in this equation will cause the total value inside the square root sign to be negative (Thus, $x\geq 0$). However, I have argued my teacher that it is possible to have a negative value for y, since the square root of any value can equal a positive or negative value. (Ex: If $x=5$, $y=\sqrt{x-1}$ is equal to $y=\sqrt{4}$ and therefore $y=\pm 2$). I also have explained that if we have another take on it and rearrange the equation to become $y^2=x-1$, $y$ can definitely be a negative value, for it is squared and will not cause the value of $x$ to become negative. My teacher still thought I was wrong, so it'd be much appreciated if you give your take on this.
Comment: Possible duplicate of [Square roots -- positive and negative](https://math.stackexchange.com/questions/26363/square-roots-positive-and-negative)  also see [this](https://math.stackexchange.com/questions/2803851/why-is-sqrtx2-x-instead-of-pm-x), [this](https://math.stackexchange.com/questions/1448885/square-root-confusion), and  [this](https://math.stackexchange.com/questions/1569629/is-sqrtx-always-positive).
Comment: Hint: can a square root be negative?
Comment: (No, not when talking about principal square roots, which is what we usually do.)
Answer: This is just a terminology error. The definition of $\sqrt x$ is the non-negative number that when squared equals $x$, a number we will call $a$. Now, the solutions of $x=a^2$ are $a$ and $-a$. The square root of a number squared is equal to that number, but the converse, the statement when a number squared is equal to a second number, that first number is the square root of the second, is false. To make an analogy, all squares are rectangles, but not all rectangles are squares. $a=\sqrt x$ is always a solution of $x=a^2$, but a solution of $x=a^2$ is not necessarily the square root of $x$. The reason is simply to make $y=\sqrt x$ a function, and make it a lot easier to work with. The reason why squaring to get the other equation does not work is because the squaring property of equality can change the domain of a function, as it does here, so the original domain must carry over.


como posso resolver este erro em python unsupported operand type(s) for +: 'NoneType' and 'NoneType'

Question: #Validador de notas v1.1 (BETA)
import time

print('[            +            ]')

NomeAluno = (input('Digite o nome do aluno >> '))

Nota1 = print('Digite a primeira nota.')
float(input('Nota 1 >> '))
Nota2 = print('Digite a segunda nota.')
float(input('Nota 2 >> '))
Nota3 = print('Digite a terceira nota.')
float(input('Nota 3 >> '))
MediaAluno = Nota1 + Nota2 + Nota3 / 3

if MediaAluno == MediaAluno >= 6:
    time.sleep (4)
    print('O(a) aluno {} Tem a média de {}, ele(a) está aprovado(a) <<✔>>'.format(NomeAluno, MediaAluno))
else:
    print('O(a) aluno {} Tem a média de {}, ele(a) está precisando de nota ou está reprovado(a). . .'.format(NomeAluno, MediaAluno))

print('[            +            ]')

Answer: Considere rever o conceito de variáveis em python. Além disso, print é uma função de saída.
Segue a solução:
import time

print('[ + ]')

NomeAluno = (input('Digite o nome do aluno >> '))

print('Digite a primeira nota.')
Nota1 = float(input('Nota 1 >> '))

print('Digite a segunda nota.')
Nota2 = float(input('Nota 2 >> '))

print('Digite a terceira nota.')
Nota3 = float(input('Nota 3 >> '))
MediaAluno = Nota1 + Nota2 + Nota3 / 3

if MediaAluno == MediaAluno >= 6:
    time.sleep (4)
    print('O(a) aluno {} Tem a média de {}, ele(a) está aprovado(a) <<✔>>'.format(NomeAluno, MediaAluno))

else:
    print('O(a) aluno {} Tem a média de {}, ele(a) está precisando de nota ou está reprovado(a). . .'.format(NomeAluno, MediaAluno))

print('[ + ]')

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Is there an efficient way to dermine whether a node can be viewed by all users?

Question: I am trying to use the Drupal node access API to determine whether a node is subject to an access restriction. That is: I want to make sure that the node can be viewed by any authenticated user (provided the authenticated user is granted the right to view published content).
The function node_access('view, $node, $account); returns TRUE if the user object $account can access $node, and FALSE otherwise, so I can get the correct result stored in $view_for_all with the following snippet of code:
$accounts = entity_load('user');
$view_for_all = TRUE;
foreach ($accounts as $account) {
  if (!node_access('view', $node, $account)) {
    $view_for_all = FALSE;
    break;
  }
}

However, looping through all accounts will be very slow if there are, say, 50000 users. I am looking for a more efficient way to do this.
Comment: Isn't this a duplicate of [How to debug permissions?](http://drupal.stackexchange.com/questions/17214/how-to-debug-permissions)? Also, if it's supposed to be available to all logged-in users, why not to simply grant permission to authenticated role?
Comment: I say not a dup as this is a specific case and not generic permissions debug.
Comment: @Mołot, no I am not trying to *debug* permissions. This is for a production site. The use case is that I only want to allow a certain field to be populated if there are *no* view access restrictions imposed on the node the field is attached to. I.e. want to check this, and not show the field in the form if there is some sort of access restriction on the node. I don't own the node, so can't know what sort of node access modules the admin has enabled.
Comment: As you both can see, I just asked, not voted.
Answer: If you are needing to check node_access records, then you may be able to examine them similarly to how devel_node_access does.  In the end, all nodes have grants added to the node_access table, so if there are grants that deny or restrictively add access, then you can probably see it there.
Another option would be to have a dummy account that is an authenticated user, and used as the test case.  This will fail, of course, if you need to detect grant rules that deny access to authenticated users who would otherwise be entitled.  It's a sticky situation.
The hardest part about this question is that it seems as though you are looking for a general solution to a specific problem, and I'm not quite sure that a general solution exists.
Answer: This is surely impossible. Modules can decide on the fly which nodes are visible. https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_access/7


How to get the parameters from a URL and a route that is not the current one?

Question: Route from a custom module :
custom.route:
  path: /the/{id}/path

Hypothetical url : /the/53/path
The goal is the get the id value ("53").

So far, I managed to get the route name from the url with
$url = "/the/53/path";

$route_provider = \Drupal::service('router.route_provider');
$found_routes = $route_provider->getRoutesByPattern($url);

In $found_routes, I can find the "custom.route" route name.
Now, I need to find the parameters value, but I can't achieve it.

use Drupal\Core\Routing\RouteMatch;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;

/**
 * Returns the parameters of a given URL.
 *
 * @param string $url
 *   The URL.
 * @param string $route_name
 *   The name of the route.
 *
 * @return array
 *   An array of parameters for the URL.
 */
function getUrlParameters(string $url, string $route_name): array {
  // Create a URL object from the given URL string.
  $url_object = Url::fromUri('base:/' . ltrim($url, '/'));

  // Create a request object from the URL object.
  $request = \Drupal::requestStack()->getMasterRequest();
  $request = $request->duplicate();
  $request->setMethod('GET');
  $request->attributes->set('_route', $route_name);
  $url_object->mergeOptions(['query' => $request->query->all()]);
  $request->server->set('REQUEST_URI', $url_object->toString());

  // Use the route matcher to get the route matching the URL.
  /** @var \Drupal\Core\Routing\RouteMatchInterface $route_match */
  $route_match = RouteMatch::createFromRequest($request, \Drupal::service('router'));

  // Return the parameters of the URL.
  return $route_match->getParameters()->all();
}

Comment: What is your use case? I can't help but think there is likely a better way to do this
Comment: I create a controller page on a specific route. It loads a block that uses url parameter. However, I want my user to be able to create a node with the same url (to override it) and add the specified block in a paragraphs. This way, my client can configure his meta tags and add the content he wants. But the block looses it's context. So I want to reverse engineer this part.
Answer: You can use the router.no_access_checks service for this.
$router = \Drupal::service('router.no_access_checks');
$parameters = $router->match($url);

It works on both path aliases as well as unaliased paths. Example for a specific node with id 5 and an alias of article/routing-in-drupal:
$router = \Drupal::service('router.no_access_checks');
$url = 'node/5';
$parameters = $router->match($url);
// $parameters['node']->id() gives 5

$url = 'article/routing-in-drupal';
$parameters = $router->match($url);
// $parameters['node']->id() gives 5

Comment: This is a good answer but it takes the parameters of the path alias and not from a specific route.
Comment: @JFK I don't believe that, and just tested it and can confirm that it gives the route parameters (maybe assuming that they have been setup correctly). Can you maybe add your full route declaration to the question?
Comment: Heres the context. I created a controller page on a specific route. It loads a block that uses the url parameter. However, I want my user to be able to create a node with the same url (to override it) and add the specified block in a paragraphs. This way, my client can configure his meta tags and add the content he wants around the block. But the block looses it's context. In this case, $router->match($url) will return the node parameters and I want the module's route params instead.
Comment: TBH this sounds like a strange approach, without sufficient detail it's a bit difficult to judge, but this might be an [XY-problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) here.


Let $C$ be compact sets. $\bigcap_{i \in K} (C_i)=\emptyset \Rightarrow \exists F \subseteq K \; \text {finite} | \bigcap_{i \in F} (C_i) = \emptyset$

Question: I made a mistake while proving the theorem in the title, however, I don't see where.
Here's the theorem:

Let $C$ be closed and limited subsets of $\Bbb{R}$. Then $\bigcap_{i \in K} (C_i) = \emptyset \Rightarrow \exists F \subseteq K \; \text {finite} | \bigcap_{i \in F} (C_i) = \emptyset$

Proof (proceeds by finding equivalent problems).
$$\Bbb{R} - \bigcap_{i \in K} (C_i) = \Bbb{R} \Rightarrow \exists F \subseteq K \; \text {finite} | \Bbb{R} - \bigcap_{i \in F} (C_i) = \Bbb{R}$$
$$\bigcup_{i \in K} (\Bbb{R} - C_i) = \Bbb{R} \Rightarrow \exists F \subseteq K \; \text {finite} | \bigcup_{i \in F} (\Bbb{R} - C_i) = \Bbb{R}$$
Let $O_i = \Bbb{R} - C_i$. Note that $\forall i \in K. \, O_i$ is open and unlimited subset of $\Bbb{R}$
$$\bigcup_{i \in K} (O_i) = \Bbb{R} \Rightarrow \exists F \subseteq K \; \text {finite} | \bigcup_{i \in F} (O_i) = \Bbb{R}$$
And the last is false since if we take $\forall i \in \Bbb{N}. \, O_i = (-\infty , i), B = \bigcup_{i \in \Bbb{N}} (O_i) = \Bbb{R}$ but there are no finite subsets of N which generates R in that way.
I cannot.find the flaw in my proof. Can you please help me with that?
Comment: (1) Changing your question after receiving an answer is in very poor taste. Even more so when you're doing so without interacting with the people who bothered to answer your question at first. (2) Changing "compact" to "closed and bounded" is not really a change, since on the real line a set is compact if and only if it is closed and bounded.
Comment: I'm sorry, I would not have changed the question if I've seen answers but I hit the edit button without refreshing the page, and on my outdated smartphone browser autorefresh does not work. :-(. I apologize, but when I saw the answer, I had already edited it. (2) What I wanted to clearify is the fact that all the $C_i$ are subsets of R...
Answer: The problem is that the complement of $(-\infty,i)$ is $[i,\infty)$ which is closed but it is not compact.
What you have shown is that the requirement of compactness is necessary, and that closure is not enough to conclude that if the intersection is empty, then a finite intersection is already empty.
Comment: So, as far as I've understood, the counterexample is wrong, because the sets have an infinte complement, but the proof has no problem per se.
Comment: The word "infinite" is a bit awkward here. After all, $[0,1]$ is infinite too. Unbounded fits better. Non-compact is even better.
Answer: For example you cannot take $ O_i = (-\infty,i) $ as an example because theese $ O_i $ are not the complement of a compact subset of $ \mathbb{R} $.
A proof would be as follows: Fix a $ C_1 $. Since $ \bigcap_{i \in K} C_i = \emptyset  $ we have $ \forall x \in C_1 : \exists 1 \neq i \in K : x \notin C_i $. Hence $ \{ C_i^C \}_{i \in K} $ is an open covering of $ C_1 $ and we can choose $ i_1 , ... , i_n \in K$  with $ C_1 \subset \bigcup_{j=1}^{n} {C_{i_j}}^ C.$ Which implies $ C_1 \bigcap_{j=1}^{n} C_{i_j} = \emptyset $.


Using a 'default' trait in FactoryGirl to avoid unnecessary association creation

Question: Is it possible to define a default trait in FactoryGirl? If I define a factory like this (where both question_response belongs_to question):
factory :question_response do
  question
  work_history

  trait :open do
    question { FactoryGirl.create :question, question_type: 'open' }
  end
end

When I do FactoryGirl.create :question_response, :open it will first create a default question and then create another inside the trait, which is an unnecessary operation.
Ideally I'd like to do this:
factory :question_response do
  work_history

  trait :default do
    question { FactoryGirl.create :question, question_type: 'yes_no' }
  end

  trait :open do
    question { FactoryGirl.create :question, question_type: 'open' }
  end
end

And then doing FactoryGirl.create :question will use the default trait, but it doesn't seem to be possible.
Answer:
When I do FactoryGirl.create :question_response, :open it will first create a default question and then create another inside the trait

It's not true. if you specify the trait with question, it will overwrite the factory behavior before creation so that it does not create a default question.
I checked it with FactoryGirl v4.5.0
Comment: Thanks, you are quite right! I've just verified this myself. I wonder this was added to factory girl recently...
Answer: Just in case someone else is looking for 'default trait' scenario, this was discussed with examples in https://github.com/thoughtbot/factory_bot/issues/528#issuecomment-18289143
Basically, you can define trait with defaults and then use it for different factories. And then you can use appropriate factory with needed configuration.
For example:
FactoryBot.define do
  trait :user_defaults do
    email { Faker::Internet.unique.email }
    username { Faker::Internet.unique.username }
    password { "test1234" }
  end

  factory :with_admin_role, class: User do
    user_defaults

    after(:create) do |user, _|
      user.add_role :admin
    end
  end

  factory :with_readonly_role, class: User do
    user_defaults

    after(:create) do |user, _|
      user.add_role :readonly
    end
  end
end

Answer: Your trait is creating a 2nd record because you have a block that is creating a record:
trait :open do
  question { FactoryGirl.create :question, question_type: 'open' }
end

Instead, you can do define a trait on question that has the question type set, and then have your question_response use that question with the open trait as its default.
factory.define :question do
  trait :open do
    question_type 'open'
  end
end

factory.define :question_response do
  association :question, :open
end


Rename a snapshot in Hyper-V WMI V2 from C#

Question: I am trying to rename a Hyper-V snapshot (checkpoint) using root\virtualization\v2. None of the standard methods like ModifySystemSettings or ModifyVirtualSystem of Msvm_VirtualSystemSnapshotService or Msvm_VirtualSystemManagementService has been helpful so far.
Powershell Rename-VMSnapshot can do the job however I am not sure it is using WMI.
Any idea?
Answer: Here is what worked for me:
<code>//
// Rename last snapshot to desired name
//
using (ManagementBaseObject inParams = vmms.GetMethodParameters("ModifySystemSettings"))
{
    ManagementObject setting = null;

    ManagementObjectCollection settings = vm.GetRelated(
        "Msvm_VirtualSystemSettingData",
        "Msvm_MostCurrentSnapshotInBranch",
        null,
        null,
        "Dependent",
        "Antecedent",
        false,
        null
        );

    foreach (ManagementObject instance in settings)
    {
        // Usually only one, but loop through to the end to get latest one

        if (setting != null)
        {
            if (string.Compare(
                    (string)instance["CreationTime"],
                    (string)setting["CreationTime"],
                    true) > 0
                )
            {
                // Get latest one since there could be duplicates
                setting = instance;
            }
        }
        else
        {
            setting = instance;
        }
    }

    setting["ElementName"] = snapshotName;

    inParams["SystemSettings"] = setting.GetText(TextFormat.WmiDtd20);

    using (ManagementBaseObject outParams = vmms.InvokeMethod("ModifySystemSettings", inParams, null))
    {
        // What this does is get Job managementObject and check JobState to be JobCompleted.
        this.ProcessSnapshotMethodResult(outParams, "rename");
    }
}
</code>
Comment: I created sub function as ProcessSnapshotMethodResult() to wait for the async call ModifySystemSettings to complete. It also checks the result of async call. It is similar to ValidateOutput mothod in common utilities introduced in MSDN here:[link](http://msdn.microsoft.com/en-us/library/hh850032(v=vs.85).aspx)
Comment: setting.GetText(TextFormat.WmiDtd20); -> do you know how to write this part of code in the Microsoft.Management.Infrastructure with CimInstance instead of ManagementObject?


Submit DS record to parent zone in DNS

Question: I have setup DNSSEC for my domain shabdiznet.com and checked it at http://dnssec-debugger.verisignlabs.com/shabdiznet.com the only problem is

No DS records found for shabdiznet.com in the com zone

as you may see . also i found same old question Adding DS record to parent in DNS without answer to my question because i already finished the https://dlv.isc.org/ .
How to Submit DS record to .com zone ? (with sample please)
Comment: You should submit them to registrar for your domain. http://www.internetsociety.org/deploy360/resources/dnssec-registrars/
Answer: To submit your DS record to your parent zone (com), you will need to do it via your registrar (who then provisions it to the registry -- Verisign).
Your registrar appears to be Onlinenic. I'm not sure if they support DS record provisioning; you will have to contact them. If they don't, you would have to transfer your domain to a registrar that actually does. GoDdady does, but there are others but check with them before you make the jump. The other thing you could try is to convince Onlinenic to manually submit the DS record for you (even if they don't support it in their web interface.) If they agree to do it, that might be ok if you're not planning on rolling over your KSK for a long time and are reasonably confident that you can keep it safe.

Submit DS record to parent zone in DNS


My json file is being cut off at the end at ~250 000 chars when using json simple

Question: I wrote a program to parse Minecraft map images into json so they can be used by a plugin to write into the world. My program runs without fault each time and doesn't throw any errors. However, when I open the json file, it seems to be cut off at the end. Can anyone provide any clarification on this?
Full code:
import com.google.gson.JsonArray;
import org.bukkit.Material;
import org.json.simple.JSONObject;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args){
        List<Color> colors = new ArrayList<Color>();
        String[] s = new String[]{"127 178 56","247 233 163","199 199 199","255 0 0","160 160 255","167 167 167","0 124 0","255 255 255","164 168 184","151 109 77","112 112 112","64 64 255","143 119 72","255 252 245","216 127 51","178 76 216","102 153 216","229 229 51","127 204 25","242 127 165","76 76 76","153 153 153","76 127 153","127 63 178","51 76 178","102 76 51 ","102 127 51","153 51 51","25 25 25","250 238 77","92 219 213","74 128 255","0 217 58","129 86 49","112 2 0","209 177 161","159 82 36","149 87 108","112 108 138","186 133 36","103 117 53","160 77 78","57 41 35","135 107 98","87 92 92","122 73 88","76 62 92","76 50 35","76 82 42","142 60 46","37 22 16"};
        for(int i = 0; i < 51; i++){
            String[] sl = s[i].split(" ");
            int r = Integer.parseInt(sl[0]);
            int g = Integer.parseInt(sl[1]);
            int b = Integer.parseInt(sl[2]);
            Color c = new Color(r,g,b);
            colors.add(c);
        }
        Material[] mats = new Material[]{Material.SLIME_BLOCK,Material.SANDSTONE,Material.COBWEB,Material.REDSTONE_BLOCK,Material.BLUE_ICE,Material.IRON_BLOCK,Material.BAMBOO,Material.WHITE_WOOL,Material.CLAY,Material.COARSE_DIRT,Material.STONE,Material.WATER,Material.OAK_LOG,Material.QUARTZ_BLOCK,Material.ORANGE_WOOL,Material.MAGENTA_WOOL,Material.LIGHT_BLUE_WOOL,Material.YELLOW_WOOL,Material.LIME_WOOL,Material.PINK_WOOL,Material.GRAY_WOOL,Material.LIGHT_GRAY_WOOL,Material.CYAN_WOOL,Material.PURPLE_WOOL,Material.BLUE_WOOL,Material.BROWN_WOOL,Material.GREEN_WOOL,Material.RED_WOOL,Material.BLACK_WOOL,Material.GOLD_BLOCK,Material.DIAMOND_BLOCK,Material.LAPIS_BLOCK,Material.EMERALD_BLOCK,Material.PODZOL,Material.NETHERRACK,Material.WHITE_TERRACOTTA,Material.ORANGE_TERRACOTTA,Material.MAGENTA_TERRACOTTA,Material.LIGHT_BLUE_TERRACOTTA,Material.YELLOW_TERRACOTTA,Material.LIME_TERRACOTTA,Material.PINK_TERRACOTTA,Material.GRAY_TERRACOTTA,Material.LIGHT_GRAY_TERRACOTTA,Material.CYAN_TERRACOTTA,Material.PURPLE_TERRACOTTA,Material.BLUE_TERRACOTTA,Material.BROWN_TERRACOTTA,Material.GREEN_TERRACOTTA,Material.RED_TERRACOTTA,Material.BLACK_TERRACOTTA};

        try {
            BufferedImage image = ImageIO.read(new File("image/image.png"));
            JSONObject obj = new JSONObject();
            for(int y = 0; y<128; y++) {
                JsonArray lines = new JsonArray();
                for(int x = 0; x<128; x++) {
                    Material blockmat = null;
                    for(int i = 0; i < mats.length; i++) {
                        if (image.getRGB(x, y) == colors.get(i).getRGB()){
                            lines.add(String.valueOf(mats[i]));
                        }
                    }
                }
                obj.put(y,lines);
            }
            FileWriter file = new FileWriter("image.json");
            file.write(obj.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Answer: Alright, I figured out that using the flush method on the FileWriter object seems to fix what i was doing.
So instead of
FileWriter file = new FileWriter("image.json");
file.write(obj.toJSONString());

I use
FileWriter file = new FileWriter("image.json");
file.write(obj.toJSONString());
file.flush();

Comment: Nope, correct solution is `file.close();`. Actually, correct solution is `try (FileWriter file = new FileWriter("image.json")) { file.write(obj.toJSONString()); }`, i.e. using try-with-resources.


Determine multivariable function is differentiable or not

Question: Hi guys I have exercise on differentiability of multivariable function.I have found the partial derivatives of x and y but I do not know how to go further.
Let $f(x,y)=xy+\frac{1}{xy}$ .
 Show that the function f is differentiable at point (5,6)
Answer: Since you have computed the partial derivatives, you are basically done. They are continuous, right?! So, $f$ is differentiable.
Or you can say that the functions $(x,y)\mapsto x$ and $(x,y)\mapsto y$ are differentiable, which implies that $(x,y)\mapsto xy$ is differentiable, which implies that $(x,y)\mapsto\frac1{xy}$ is differentiable. Since your function is the sum of two differentiable functions, it is differentiable.
Comment: I have found $fx=y-\frac{1}{x^2y}$ and  $fy=x-\frac{1}{xy^2}$ How can I know they are continuous?
Comment: They are obtained from continuous functions using arithmetic operations. Isn't that enough?
Comment: Thanks I got it


Allocate pseudo TTY in Upstart configuration file

Question: We would like to use Upstart to manage a Java process and run it as non-root using sudo. We are on RHEL 6 which means that Upstart is too old to allow us to explicitly specify a user hence the use of sudo.
However, the Sudo configuration file specifies Defaults requiretty which means we can't run sudo -u to launch the command as a non-root user. We get the following error
sudo: sorry, you must have a tty to run sudo
Is there a way to get Upstart to allocate a pseudo TTY so that sudo will allow us to launch this process? The sudoers file is set according company policy and we are unable to change it.
Answer: You don't need to - and shouldn't - use sudo to change users in an init script. Use su or better, runuser instead. The runuser command should be available from RHEL 5 and will do the right thing with respect to SELinux contexts, etc.
runuser -u username -g groupname command arguments


Ansible fetch file from remote and keep on control node?

Question: Let's say I have this compile role and it's last task fetches the compiled binaries from a build server.
- name: "fetch release tar"
  fetch:
    src: "{{ project_path }}/rel/{{ app_name }}/releases/{{ app_version }}/{{ app_name }}.tar.gz"
    dest: "~/releases/"
    flat: yes

Once this role completes, Ansible seems to clean up the release directory, presumably because these files are temporary? Is there a way fetch can make this permanent?
Answer: Tilde expansion is handled by the login shell (bash, zsh, ksh, etc.). Ansible does not perform any tilde expansion on its own, so using one in the dest parameter as you have results in undefined behavior.
You should either hardcode a full path for your destination, or as an alternative you can make use of the expanduser filter that was added in Ansible 1.5 to perform this tilde expansion inside your playbook.


How do I format text I am copying from Google Document in Google App Script?

Question: I am trying to copy formatted text from one document and paste it into another. I want to take the entirety of one document and add it to another via Google App Script.
The call body.getText() satisfies my use case but gets the text as a string, not formatted.
It would be great to be able to copy formatted text from one document to another.
EDIT:
Taking the advice I currently wrote some more code. Following the other answer almost exactly, I am still only getting the text and not the formatting too.
  for(var i = 0; i < numElements; ++i) {
  var element = copyBody.getChild(i)
  var type = element.getType();
   if (type == DocumentApp.ElementType.PARAGRAPH)
   {
     var newElement = element.copy().asParagraph();
     newBody.appendParagraph(newElement);
   }
   else if(type == DocumentApp.ElementType.TABLE)
   {
     var newElement = element.copy().asTable();
     newBody.appendTable(newElement);
   }
   else if(type == DocumentApp.ElementType.LIST_ITEM)
   {
     var newElement = element.copy().asListItem();
     newBody.appendListItem(newElement);
   }
    else{
    Logger.log("WRONG ELEMENT")
    }
  }

Comment: "Almost" - Henrique's function doesn't resort to using `.asParagraph()`, etc. Try with plain `.copy()`. The script in my answer works as-is.
Answer: This answer covers it.
You need to iterate through the elements of the source document, appending each to the destination doc. You don't copy Text versions of paragraphs, etc., instead you copy the whole element including formatting etc.
Script
Since Documents now support programmable UI elements, here's a script based on Henrique's previous answer (above), that includes a Custom Menu to drive the merge of documents. You may optionally include page breaks between appended documents - useful if you are trying to create a multi-chapter document.
This script must be contained in a Document (or no UI for you)!
/**
 * The onOpen function runs automatically when the Google Docs document is
 * opened.
 */
function onOpen() {
  DocumentApp.getUi().createMenu('Custom Menu')
      .addItem('Append Document','appendDoc')
      .addToUi();
}

/**
 * Shows a custom HTML user interface in a dialog above the Google Docs editor.
 */
function appendDoc() {
  // HTML for form is rendered inline here.
  var html =
      ''
  +   '<form id="appendDoc">'
  +     'Source Document ID: <input type="text" size=60 name="docID">
'
  +     'Insert Page Break: <input type="checkbox" name="pagebreak" value="pagebreak">'
  +     '<input type="button" value="Begin" '
  +       'onclick="google.script.run.withSuccessHandler(showOutput).processAppendDocForm(this.parentNode)" />'
  +   '</form>'
  +   '
'
  +   '

'

  DocumentApp.getUi().showDialog(
    HtmlService.createHtmlOutput(html)
               .setTitle('Append Document')
               .setWidth(400 /* pixels */)
               .setHeight(150 /* pixels */));
}

/**
 * Handler called when appendDoc form submitted.
 */
function processAppendDocForm(formObject) {
  Logger.log(JSON.stringify(formObject));
  var pagebreak = (formObject.pagebreak == 'pagebreak');
  mergeDocs([DocumentApp.getActiveDocument().getId(),formObject.docID],pagebreak);
  return "Document appended.";
}

/**
 * Updates first document in list by appending all others.
 *
 * Modified version of Henrique's mergeDocs().
 * https://stackoverflow.com/a/10833393/1677912
 *
 * @param {Array} docIDs      Array of documents to merge.
 * @param {Boolean} pagebreak Set true if a page break is desired
 *                              between appended documents.
 */
function mergeDocs(docIDs,pagebreak) {
  var baseDoc = DocumentApp.openById(docIDs[0]);
  var body = baseDoc.getBody();

  for( var i = 1; i < docIDs.length; ++i ) {
    if (pagebreak) body.appendPageBreak();
    var otherBody = DocumentApp.openById(docIDs[i]).getBody();
    Logger.log(otherBody.getAttributes());
    var totalElements = otherBody.getNumChildren();
    var latestElement;
    for( var j = 0; j < totalElements; ++j ) {
      var element = otherBody.getChild(j).copy();
      var attributes = otherBody.getChild(j).getAttributes();
      // Log attributes for comparison
      Logger.log(attributes);
      Logger.log(element.getAttributes());
      var type = element.getType();
      if (type == DocumentApp.ElementType.PARAGRAPH) {
        if (element.asParagraph().getNumChildren() != 0 && element.asParagraph().getChild(0).getType() == DocumentApp.ElementType.INLINE_IMAGE) {
          var pictattr = element.asParagraph().getChild(0).asInlineImage().getAttributes();
          var blob = element.asParagraph().getChild(0).asInlineImage().getBlob();
          // Image attributes, e.g. size, do not survive the copy, and need to be applied separately
          latestElement = body.appendImage(blob);
          latestElement.setAttributes(clean(pictattr));
        }
        else latestElement = body.appendParagraph(element);
      }
      else if( type == DocumentApp.ElementType.TABLE )
        latestElement = body.appendTable(element);
      else if( type == DocumentApp.ElementType.LIST_ITEM )
        latestElement = body.appendListItem(element);
      else
        throw new Error("Unsupported element type: "+type);
      // If you find that element attributes are not coming through, uncomment the following
      // line to explicitly copy the element attributes from the original doc.
      //latestElement.setAttributes(clean(attributes));
    }
  }
}

/**
 * Remove null attributes in style object, obtained by call to
 * .getAttributes().
 * https://code.google.com/p/google-apps-script-issues/issues/detail?id=2899
 */
function clean(style) {
  for (var attr in style) {
    if (style[attr] == null) delete style[attr];
  }
  return style;
}

Edit: Adopted handling of inline images from Serge's answer, with handling of image size attributes. As the comments indicate, there have been problems with some attributes being snarfed in the append, thus the introduction of the clean() helper function and use of .setAttributes(). However, you'll note that the call to .setAttributes() is commented out; that's because it too has a side-effect that will remove some formatting. It's your choice about which annoyance you'd rather deal with.
Comment: Hi Mogsdad, I tested your code out of curiosity mainly because I liked the html construction from within the script but I get an error showing up in the popup panel : Google Drive encountered an error. If reloading the page doesn't help, please report the error. Is it a momentary failure ? does it work for you  ?
Comment: The script service just burped... I saw the same for a few minutes. (Did you authorize the script first?)
Comment: I am in the same boat for the service. I thought getActiveSection() was a deprecated method.
Comment: Yeah, but it still works. I'd changed the `getActiveSection()` to `.getBody()` for the "baseDoc" so I could get autocomplete to work further on while I played, but missed the second instance. I've updated it here, but can't touch the real script to test currently since the service is down.
Comment: I copied and pasted your code verbatim and currently the formatting is not coming over exactly. For example, the header is not in the same font. The bulleted list is also not bulleted just indented.
Comment: You're right - not everything survives. I've got a bullet list that ends up with numbers. And the second time the same doc is appended the numbering continues rather than starting from 1. Various font changes are all making it, including Header 1 with a non-standard font. It might have to do with what element the format changes are applied to, e.g. specific text within a paragraph vs the whole paragraph. (Maybe a deeper copy of elements is needed?)
Comment: I added the possibility to get inlineImages copied as well, I'll post the relevant part of code in a new answer for comfort.
Comment: @Mogsdad The documentation says that it returns a "deep copy" [link](https://developers.google.com/apps-script/reference/document/body#copy())
Comment: The deep copy seems true, but there's a problem when that copy is appended. One google bug found: I've compared the attributes of the "list items", and they match before appending the new element; `GLYPH_TYPE=BULLET`. AFTER appending, the attributes on the new element CHANGED, `GLYPH_TYPE=null`, same happens with `GLYPH_TYPE:NUMBER`.
Comment: I tried appending the attributes hastable that comes back from the `getAttributes()` call but they are not in correct format to set them in the `body.appendTable()` call.
Comment: That's [Issue 2899](https://code.google.com/p/google-apps-script-issues/issues/detail?id=2899). Workaround is to remove the null attributes, let's see if that works.
Answer: here is a slight improvement to Mogsdad script to get inline images copied as well.
The only issue is that if an image has been resized it is not keeping this new size in the copy, images are shown in their original size... No idea right now how to solve that .
function mergeDocs(docIDs,pagebreak) {
  var baseDoc = DocumentApp.openById(docIDs[0]);
  var body = baseDoc.getBody();

  for( var i = 1; i < docIDs.length; ++i ) {
    if (pagebreak) body.appendPageBreak();
    var otherBody = DocumentApp.openById(docIDs[i]).getBody();
    var totalElements = otherBody.getNumChildren();
    for( var j = 0; j < totalElements; ++j ) {
      var element = otherBody.getChild(j).copy();
      var type = element.getType();
      if (type == DocumentApp.ElementType.PARAGRAPH) {
        if (element.asParagraph().getNumChildren() != 0 && element.asParagraph().getChild(0).getType() == DocumentApp.ElementType.INLINE_IMAGE) {
          var blob = element.asParagraph().getChild(0).asInlineImage().getBlob();
          body.appendImage(blob);
        }
        else body.appendParagraph(element.asParagraph());
      }
      else if( type == DocumentApp.ElementType.TABLE )
        body.appendTable(element);
      else if( type == DocumentApp.ElementType.LIST_ITEM )
        body.appendListItem(element);
      else
        throw new Error("According to the doc this type couldn't appear in the body: "+type);
    }
  }
}

you can test it on this doc ID : 1E6yoROb52QjICsEbGVXIBdz8KhdFU_5gimWlJUbu8DI
(Execution succeeded [43.896 seconds total runtime]) !!! be patient !
this code comes from this other post
Comment: Serge, I figured out the image resize problem, and updated the code in my answer.
Comment: Now... maybe you can fix the form handling in mine, so it gives progress feedback!
Comment: I'm not comfortable enough with html service, in UiApp I'd do it in seconds with a clientHandler and an animated gif but I still have a lot to learn with this new 'way of thinking' I can read your code but I'm not yet able to write it ;-)  (one good point : the opposite would be even worse, right ? ^^)


how to check from JavaScript if loaded page has ASP.NET authentication cookie?

Question: It looks like JavaScript does not have access to authentication cookies ('ASP.NET_SessionId', '.ASPXFORMSAUTH')
in the http headers I can see cookies but document.cookie object does not have them.
Answer: You could create a WebMethod which uses the following code to return a true/false value:
<code>[WebMethod]
public bool IsAuthenticated()
{
    return HttpRequest.IsAuthenticated;
}
</code>
Call this from javascript using jQuery or MSAJAX.
Comment: From a technical standpoint, this does not actually tell if the "loaded page" is authenticated.  It tells if the AJAX request is authenticated.
Comment: The reason why I want to check in javascript it is because I do not want to go to the server (performance issue, I have 3 000 000 requests daily)
Answer: ASP.NET session cookies are HTTP-only by default (and rightfully so).  If you need to find out if the user is authenticated in Javascript, putting a HiddenField on the page and setting its value to 0 or 1 based on your authentication token is a much better solution.
Comment: the page is from cache - same for everybody but cookies are unique.
I need to check cookies before i will make ajax request to the server to load user-specific content. and I do not want to go to the server if user does not have auth cookies.
Comment: Well, if you switch to cookieless session you can solve this problem :)


Centos7: Firewalld port 80 not being blocked

Question: Why am I able to telnet to my machine on port 80 when I do not have http or port 80 opened and there are no services listening on port 80?
sudo firewall-cmd --list-all --zone=public

public (active)
  target: default
  icmp-block-inversion: no
  interfaces: em1
  sources:
  services: dhcpv6-client ssh
  ports: 12345/tcp
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

I've tried to remove the port but it says it's not in the active zone, so shouldn't my telnet connections be rejected?
sudo firewall-cmd --zone=public --remove-port=80/tcp
Warning: NOT_ENABLED: '80:tcp' not in 'public'

I've double checked and I do not have iptables service running, only firewalld is running. I'm still not understanding why iptables command exists or why the iptables file is updated with firewall-cmd commands.
I even tried the "old school" method of just dropping all incoming traffic with:
sudo iptables --policy INPUT DROP
But still telnet to port 80 comes through.
Comment: `sudo iptables --policy INPUT DROP` this by itself doesn't actually block anything and only changes what happens last to packets that do not match any rule in the current firewall. - But please take a step back - how do you *"telnet to my machine on port 80"* ? Because you wouldn't be the first one to forget that their `host.example.com` FQDN isn't directly associated with the server itself and directs to for example a load balancer or CDN such as cloudflare... And what happens when you actually write out a HTTP request in your telnet session? Also: https://serverfault.com/a/1109720/984089
Answer: First of all you need to find if there are really some services which listen in port 80. For this run, as root or with sudo:
netstat -nlp | grep :80

Second, try to list all zones to see in what zone is port 80 added:
firewall-cmd --list-all-zones

An third, in Centos 7, firewalld acts like a front-end for iptables, that's why you still have the iptables command.


Are conic sections obtained from a cone or a double cone?

Question: According to Wikipedia,

In mathematics, a conic section (or simply conic) is a curve obtained as the intersection of the surface of a cone with a plane.

However most of the images actually show a double cone instead of a cone and it makes sense to me since a hyperbola has two components.
So is it true that despite its name and definition, conic section is actually an intersection of a plane with a double cone?
Comment: If you really want to make a hard distinction between "cone" and "double cone", then, yes: a conic section requires the latter. However, it's quite common to refer to a double cone simply as a "cone". (Context should make the usage clear.) Consider, for instance, the characterization of [quadric surfaces](https://en.wikipedia.org/wiki/Quadric).
Comment: You only need double cone for a hyperbola with two branches. You can form a circle, ellipse, parabola with single side of a cone.
Answer: There's a very general definition of "cone" which is the following.
Let $\cal C$ be a (closed, regular) curve in $\Bbb R^3$ and let $P$ a point not in $\cal C$. Then the cone through $\cal C$ with vertex $P$ is the ruled surface made of all lines $QP$ as $Q$ varies in $\cal C$.
When $\cal C$ is a circle with center $C$ and $P$ is chosen so that $PC$ is orthogonal to the plane containing $\cal C$ you get what you call "double cone".
You really need double cones if you want your section to be an hyperbola, which is made of two disconnected parts, lying on different "parts" of the double cone.
General cones are a basic example of flat surfaces (they can be flattened out isometrically on a plane).
Also note that if you let $P$ move far away from $\cal C$ the lines $QP$ tend to become parallel and will if you let $P$ "go to infinity". In this sense cylinders are degenerate cones (the vertex of a cylinder being "at infinity")
Answer: Cone/Plane Intersection scenario
A full cone consists of two nappes/sheets.
Only when the inclinations of cone generator semi-vertical angle $ \alpha$  is more  than sectioning plane angle $\beta$ to the cone axis we get the hyperbola as a real disjuncted double curve.
A parabola or ellipse is produced by intersection when
 $ \alpha  < \beta$ on a single nappe.
In this case we are not concerned with generality when  only one cone is partaking and resulting in an intersection.


IKev2 VPN Event ID 20209 - Server Authentication

Question: I have made only one certificate for VPN access with ikev2. Within 2 days i got event id 20209, even though I didn't tried to connect. The certificate is still with me and no one else has access to it. But event viewer states that
<code>A connection between the VPN server and the VPN client 184.108.40.206 has been established, but the VPN connection cannot be completed. The most common cause for this is that a firewall or router between the VPN server and the VPN client is not configured to allow Generic Routing Encapsulation (GRE) packets (protocol 47).
</code>
This IP has been flagged for VPN BruteForce attempts at many sites.
I just want to know how did the manage to connect without certificate?
Answer: The list of RRAS event IDs ends on 20208, but according to Netsurion EventTracker, 20209:

This event is logged when a connection between the VPN server and the
  VPN client has been established but the VPN connection cannot be
  completed.

This is not an event of a successful VPN connection, but a failed connection attempt. It could be the lack of the correct client certificate or a different connection type altogether. This is not something you should worry about. Notice that a connection must be established to negotiate the VPN tunnel even if it fails: it doesn't refer to a successful VPN connection.


Getting hp-snmp-agents on HP ProLiant DL360 on Lenny working

Question:
Possible Duplicate:
System load by HP-SNMP-Agents is high

After receiving our HP ProLiant DL360 I'd like to integrate the machine into our Munin system and thus enable ProLiant specific information to be exposed via SNMP.
I'm running Debian Lenny with kernel 2.6.26-2-vserver-amd64 . I've followed http://downloads.linux.hp.com/SDR/getting_started.html and the HP repository has been added to /etc/apt/sources.list.d/HP-ProLiantSupportPack.list .
Setting up Lenny SNMP itself is not a problem, I configure it to have a public v1 community string to read all data and it works. I install hp-snmp-agents and run hpsnmpconfig and it adds additional lines to the top of /etc/snmp/snmpd.conf :
dlmod cmaX /usr/lib64/libcmaX64.so

snmpd gets restarted.
Via lsof I can see that libcmaX64 was loaded and is used by snmpd, put I do not get any additional information out of snmp. I use snmpwalk -v 1 -c public ... and I can see many OIDs but I do not see the new ones I'd expect, most notably temperatures, fan speed and such.
The OIDs I'm expecting are e.g. 220.127.116.11.18.104.22.168.220.127.116.11.4.1 , this is from the existing munin plugins from http://exchange.munin-monitoring.org/plugins/snmp__hp_temp/version/1 .
snmpd[19007]: cmaX: Parsing shared as a type was unsucessful
snmpd[19007]: cmaX: listening for subagents on port 25375
snmpd[19007]: cmaX: subMIB 1 handler has disconnected
snmpd[19007]: cmaX: subMIB 2 handler has disconnected
snmpd[19007]: cmaX: subMIB 3 handler has disconnected
snmpd[19007]: cmaX: subMIB 5 handler has disconnected
snmpd[19007]: cmaX: subMIB 6 handler has disconnected
snmpd[19007]: cmaX: subMIB 8 handler has disconnected
snmpd[19007]: cmaX: subMIB 9 handler has disconnected
snmpd[19007]: cmaX: sent ColdStarts on ports 25376 to 25393
snmpd[19007]: cmaX: subMIB 10 handler has disconnected
snmpd[19007]: cmaX: subMIB 11 handler has disconnected
snmpd[19007]: cmaX: subMIB 14 handler has disconnected
snmpd[19007]: cmaX: subMIB 15 handler has disconnected
snmpd[19007]: cmaX: subMIB 16 handler has disconnected
snmpd[19007]: cmaX: subMIB 21 handler has disconnected
snmpd[19007]: cmaX: subMIB 22 handler has disconnected
snmpd[19007]: cmaX: subMIB 23 handler has disconnected
snmpd[19007]: cmaX: subMIB  1 will be sent on port 25376 to hp Advanced Server Management_Peer
snmpd[19007]: cmaX: subMIB  2 will be sent on port 25376 to hp Advanced Server Management_Peer
snmpd[19007]: cmaX: subMIB  3 will be sent on port 25376 to hp Advanced Server Management_Peer
snmpd[19007]: cmaX: subMIB  5 will be sent on port 25376 to hp Advanced Server Management_Peer
snmpd[19007]: cmaX: subMIB  6 will be sent on port 25376 to hp Advanced Server Management_Peer
snmpd[19007]: cmaX: subMIB  8 will be sent on port 25376 to hp Advanced Server Management_Peer
snmpd[19007]: cmaX: subMIB  9 will be sent on port 25376 to hp Advanced Server Management_Peer
snmpd[19007]: cmaX: subMIB 10 will be sent on port 25376 to hp Advanced Server Management_Peer
snmpd[19007]: cmaX: subMIB 11 will be sent on port 25376 to hp Advanced Server Management_Peer
snmpd[19007]: cmaX: subMIB 14 will be sent on port 25376 to hp Advanced Server Management_Peer
snmpd[19007]: cmaX: subMIB 15 will be sent on port 25376 to hp Advanced Server Management_Peer
snmpd[19007]: cmaX: subMIB 16 will be sent on port 25376 to hp Advanced Server Management_Peer
snmpd[19007]: cmaX: subMIB 21 will be sent on port 25376 to hp Advanced Server Management_Peer
snmpd[19007]: cmaX: subMIB 22 will be sent on port 25376 to hp Advanced Server Management_Peer
snmpd[19007]: cmaX: subMIB 23 will be sent on port 25376 to hp Advanced Server Management_Peer
snmpd[19007]: cmaX: subMIB 18 handler has disconnected
snmpd[19007]: cmaX: subMIB 18 will be sent on port 25393 to cpqnicd
snmpd[19007]: NET-SNMP version 5.4.1

This doesn't look particular bad for me, it's just informational I guess.
I've compared the walking OID output with and without the module and there's no difference in the OID served back at all. Are there any other prerequisites I'm missing?
I've also noticed that from the time I installed hp-snmp-agents it adds a lot of additional daemons and that my load suddenly jumps to 1. I've uninstalled the package for now. Is this expected behavior?
Load spike http://h30499.www3.hp.com/hpeb/attachments/hpeb/bsc-431/18582/1/load.jpg
Answer: I'm experiencing the same, my load also stays put at 1 after starting the agents.
I've found a solution in this thread, which reduces the load back to at least 0.6:
http://forums13.itrc.hp.com/service/forums/questionanswer.do?admit=109447627+1295820132076+28353475&threadId=1332334
Also make sure you have different community strings for the various options. Otherwise you'll keep seeing 'error in subcontainer' messages in /var/log/net-snmpd.log

Update: I'd asked about the same question before finding yours (just with a completely different title); System load by HP-SNMP-Agents is high You'll find the answer there. Quoting:

In short, you'll want to stop the HP management agents with
  /etc/init.d/hp-snmp-agents stop. Edit the exclude line in
  /opt/hp/hp-snmp-agents/cma.conf from:
exclude
to
exclude cmasm2d cpqriisd cmarackd
Start your agents again with /etc/init.d/hp-snmp-agents start
Comment: You're more likely to get an "answered" tag if you just post the solution here.  Also, if this ground is already covered, it's entirely reasonable to vote to close this question as a duplicate.


How do I check by default a checkbox from a checkboxes control after an AJAX call

Question: I have the next form which behavior is:

When you select an option from select control, different checkbox are load on checkboxes control.
When you check/uncheck checkbox a message is showed on the botton with info about select value and checkbox clicked.

Everything works fine, but is impossible check by default a checkbox from checkboxes control after ajax function.
Any idea?

namespace Drupal\drupal_miseries\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\Checkboxes;

class CheckboxesAjax extends FormBase {

    protected $values = [
        'select' => [
            '1' => 'Value1',
            '2' => 'Value2',
        ],
        // Options when select 1 is selected
        'checkboxes_v1' => [
            '1' => 'checkbox1',
            '2' => 'checkbox2',
        ],
        // Options when select 2 is selected
        'checkboxes_v2' => [
            '3' => 'checkbox3',
            '4' => 'checkbox4',
        ],
        // Default values for checkboxes
        'checkboxes_df' => [
            // Default value when checkboxes_v1 is showed
            '1' => ['1' => '1', '2' => '0'],
            // Default value when checkboxes_v2 is showed
            '2' => ['3' => '0', '4' => '1'],
        ],
    ];

    public function getFormId() {
        return 'drupal_miseries_checkboxesajax';
    }

    public function selectAjaxCallback(array &$form, FormStateInterface $form_state) {
      return $form['container'];
    }

    public function checkboxesAjaxCallback(array &$form, FormStateInterface $form_state) {
      $checkbox = $form_state->getTriggeringElement();
      $select = $form_state->getValue('select');

      $form['status']['mensaje'] = [
          '#markup' => 'Select: '.$select.' '.$checkbox['#title'].' clicked.'.'',
      ];

      return $form['status'];
    }

    public function buildForm(array $form, FormStateInterface $form_state) {
      $form['select'] = [
        '#type' => 'select',
        '#title' => $this->t('Select form control'),
        '#options' => $this->values['select'],
        '#default_value' => key($this->values['select']),
        '#ajax' => [
            'callback' => [$this, 'selectAjaxCallback'],
            'wrapper' => 'checkboxes_wrapper',
        ],
      ];

      $form['container'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'checkboxes_wrapper'],
      ];

      $form['container']['checkboxes'] = [
        '#type' => 'checkboxes',
        '#title' => $this->t('Checkboxes form control from select @select',
          [ '@select' => empty($form_state->getValues()) ?
              $this->values['select'][key($this->values['select'])] : $form_state->getValue('select') ]),
        '#options' => empty($form_state->getValues()) ?
          $this->values['checkboxes_v1'] :
          $this->values['checkboxes_v'.$form_state->getValue('select')],
        '#default_value' => empty($form_state->getValues()) ?
          $this->values['checkboxes_df']['1'] :
          $this->values['checkboxes_df'][$form_state->getValue('select')],
        '#ajax' => [
            'callback' => [$this, 'checkboxesAjaxCallback'],
            'wrapper' => 'status',
        ],
      ];

      $form['status'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'status'],
      ];

      return $form;
    }

    public function submitForm(array &$form, FormStateInterface $form_state) {

    }
}

Comment: https://drupal.stackexchange.com/questions/188730/how-can-i-implement-ajax-form-submission/188752#188752
Answer: Thanks @IvanJaros, i have read it and i think i'm doing everything fine but i can't understand why is not working.
I have modify selectAjaxCallback to solve this problem:

public function selectAjaxCallback(array &$form, FormStateInterface $form_state) {
      $select = $form_state->getValue('select');

      foreach ($this->values['checkboxes_df'][$select] as $key => $value) {
        $form['container']['checkboxes'][$key]['#checked'] = $value;
      }
      return $form['container'];
    }

This code works, but i'm not sure if it's the right way to solve this problem.
Thanks.


What does it mean to have an F-value of .000 and Sig. of 1.000 (in SPSS)?

Question: We conducted this very simple 2x2 Between Subjects Factorial Design Experiment, where the DV were their answers to a classic insight problem. Since there is only one correct answer to the problem, the values for the DV were either 1 if the answer was correct and 0 if it was not.
The results I got was an F-value of .000 and Sig. (p value) of 1.000 for one variable and the interactio n. Is there something wrong with my data? Perhaps the DV shouldn't have been dichotomous? What do you suggest I do?
Comment: Are you using ANOVA for binary data?
Comment: Yes, it turned out that way since the responses (the DV) is either right (1) or wrong (0). Should I have used another test? Or should I change my scoring so it would not be binary?
Comment: According to [this nice article](http://oralpathol.dlearn.kmu.edu.tw/case/Journal%20reading-intern-08-12/statistical%20use-review-BJOMFS-2008.pdf), there are also methods how to test differences between groups when we have only nominal variables (in your case binary). So either try to get interval data suitable for ANOVA or try to use any other test.
Comment: @MiroslavSabo Answer please! I want to upvote (=
Answer: Ok, so either to get interval data or you can use any technique that is applicable when working with nominal variables (since binary is only a special case). In this article, tutorial on how to choose the most appropriate test is available together with examples so you can compare your situation to any from that article.
In summary, Cochran, McNemar and chi-square tests are widely used when testing group differences with nominal instead of at least ordinal variables.
Comment: I have found similar question, maybe it will be [helpfull](http://stats.stackexchange.com/questions/5935/anova-on-binomial-data).
Comment: I solved it again manually by using Chi-Square, the thing is, the observed and expected frequencies all ended up to be equal, which means the chi-square value is zero. I am beginning to seriously worry about the appropriateness of everything. But the data we got was definitely equal across conditions for both variations of one of the variables.
Comment: Ok, could you in detail describe the data again? And also your hypothesis? Maybe something is wrong.
Comment: And attach also table, please.
Comment: The design is 2 (Close-Other vs Distant-Other) x 2 (Negative Emotion vs Neutral Emotion). Our hypothesis is that respondents under the Close-Other--Neutral Emotion would more likely be able to answer the insight problem, with the Distant-Other--Negative Emotion as least likely to be able to answer the given insight problem. So for the DV, its either they were correct or not.

             Close      Distant     Total
Neutral       4           4          8
Angry         2           2          4
Total         6           6          12
Comment: sorry, the table.
Comment: Chi statistic is zero for such a table, so this is correct. But note that chi-square test can be applied only if expected values are at least 5 in significant part of cells. It is not this case. You have very small dataset, I am not sure whether such a small data can be tested. Also, chi-square test may be wrong choice for such data
Comment: I see. Perhaps we need to consider redoing everything. Thanks so much for your help. But just to be sure, having a zero chi-square value would mean that there is no association between the variables, am I correct?
Comment: Yes, if the test is appropriate for any situation, then small values of statistics indicate that we cannot reject null hypothesis (about no association between variables). Note that we cannot prove null hypothesis, we can only reject or not to reject it.


TCP Handshake and TCP RTT when using VPN

Question: From my server I'm measuring the TCP RTT and I was wondering what would be the difference between clients that use VPN compared to non-VPN clients.
So in the case of a non-VPN client the TCP session is established directly with the customer, which means that I'm actually measuring the RTT of the full path. What is happening with clients who connect through a VPN server?
Does the VPN server maintain two separate TCP sessions, one with the VPN client and one with HTTP server, or it just changes the IP headers and there's only one TCP session between the HTTP server and the client? In the first case the TCP RTT would measure only a partial latency, which would be misleading.
For example, if a client is using NordVPN to connect to my server, is the TCP RTT that I observe the RTT to the NordVPN server or to the client?
Answer: Normally VPN encapsulates TCP. From the client TCP gets to the VPN server and is routed on. So there is even no TCP connection to the VPN server.


update query not working

Question: The below query is throwing:

Msg 8152, Level 16, State 2, Line 1 String or binary data would be
  truncated. The statement has been terminated.

update table1
set cust_line1_name = c.cust_line1_name
from table1 d
inner join dbo.table2 c
on c.cust_nbr = d.cust_id
and c.bus_grp_id = d.bus_grp_id

table1
 cust_line1_name - varchar(24)

table2
 cust_line1_name - nvarchar(140)

I checked whether any data which is having length greater than 24 is getting updated but there is no such data
SELECT LEN(c.cust_line1_name), c.cust_line1_name
from table1 d
inner join dbo.table2 c
on c.cust_nbr = d.cust_id
and c.bus_grp_id = d.bus_grp_id
WHERE  LEN(c.cust_line1_name)> 24

The above query is returing zero result. The issue is in SQL server 2008
Could someone help
Comment: I think you have missed a link between table1 and tables d and c
Comment: Do you have any triggers on this table?
Answer: Converting to varchar from nvarchar is going to lose the data that isn't able to be converted. Anything in a foreign language from table2.cust_line1_name (nvarchar(140)) would not fit into your varchar 24
The correct course of action:
if table1 column has data:

Add a nvarchar(140) column to table 1
Copy data from current varcahar(24) column
Drop varchar(24) column
Rename the new nvarchar(140) column to old column name

If the table1 column has no data just drop it, and make your new column for populating with data from table2 the same size and data type as the one in table2.
Answer: make a change in the condition and then it works fine.
Query is:
UPDATE table1
        SET cust_line1_name = c.cust_line1_name
        FROM table1 d INNER JOIN dbo.table2 c
        ON c.cust_nbr = d.cust_id
        AND c.bus_grp_id = d.bus_grp_id
        AND  LEN(c.cust_line1_name)<= 24

Answer: update table1
set cust_line1_name = left(c.cust_line1_name, 24)
from table1 d, dbo.table2 c
Where c.cust_nbr = d.cust_id
and c.bus_grp_id = d.bus_grp_id

Answer: You have missed the link between your update table (table1) and two tables in from clause:
Your query:
update table1
set cust_line1_name = c.cust_line1_name
from table1 d
inner join dbo.table2 c
on c.cust_nbr = d.cust_id
and c.bus_grp_id = d.bus_grp_id

You must add a WHERE condition to decide how you want to update your table1
For example, you can add
WHERE table1.id = d.id

Because d is the same table (table1)
Otherwise, how you have written your query, you have tried to put in a scalar field a list of rows (result of join between d and c table)
Comment: i added where still it is not working
update table1
set cust_line1_name = c.cust_line1_name
from table1 d
inner join dbo.table2 c
on c.cust_nbr = d.cust_id
and c.bus_grp_id = d.bus_grp_id
WHERE c.cust_nbr = d.cust_id
Comment: @Thomas: No, you're wrong, not c.cust_nbr = d.cust_id, but you must link table1.cust_id = d.cust_id

update query not working


Duvidas Abstract Factory

Question: Estou com esse exercicio para fazer porem não estou conseguindo fazer a implementação
Utilizando o Padrão Abstract Factory, implemente em java clientes dos produtos Gerenciador de Processos e Gerenciador de Memoria , para os Sistemas Operacionais Linux, Mac , e Windows
Ate agora so consegui fazer Isso, estou com muitas duvidas de como terminar esse codigo  :
public class FabricaWindows implements FabricadeGerenciador {

@Override
public void Gerenciadordeprocesso() {
    // TODO Auto-generated method stub

}

@Override
public void Gerenciadordememoria() {
    // TODO Auto-generated method stub

}

public class FabricaLinux implements FabricadeGerenciador {

@Override
public void Gerenciadordeprocesso() {
    // TODO Auto-generated method stub

}

@Override
public void Gerenciadordememoria() {
    // TODO Auto-generated method stub

}

}

public interface FabricadeGerenciador {
void Gerenciadordeprocesso();
void Gerenciadordememoria();
}

public interface Gerenciadordememoria {

}
public interface Gerenciadordeprocesso {

}

Answer: O problema da sua implementação são os retornos dos métodos. O AbstractFactory é um padrão que serve justamente para criar objetos, nesse caso uma família de objetos. Portanto os métodos void Gerenciadordeprocesso(); e void Gerenciadordememoria(); deveriam possuir retornos. O correto seria:
public interface FabricadeGerenciador {
    Gerenciadordememoria Gerenciadordeprocesso();
    Gerenciadordeprocesso Gerenciadordememoria();
}

Com isso, seu código seria utilizado da seguinte forma:
public static void main(String args[]) {
    FabricadeGerenciador fabrica = new FabricaWindows();
    Gerenciadordememoria gerenciadorMemoria = fabrica.Gerenciadordememoria();
    Gerenciadordeprocesso gerenciadorProcesso = fabrica.Gerenciadordeprocesso();
}

Dicas:

Os métodos do AbstractFactory são métodos de criação, portanto seria interessante utilizar nomes mais apropriados, por exemplo, criarGerenciadorMemoria.
Nome de método em java deve começar com letra minúscula e deve seguir o padrão de nomenclatura camel case. Ou seja, o nome Gerenciadordeprocesso está fora do padrão. O correto seria gerenciadorDeProcesso.
Nome de classe e interface segue parecido com o camel case, só que o nome deve começar com letra maiúscula. Esse padrão é chamado de pascal case. Ou seja, ao invés de Gerenciadordememoria, deveria ser GerenciadorDeMemoria .

Duvidas Abstract Factory


Why are there module files like [modulename].pages.inc?

Question: I start to learning moding Drupal and I have a look for the current ones. There are files like [modulename].pages.inc or [modulename].api.inc and I can't find why it exists? I read that base files are only [modulename].module, [modulename].info, [modulename].install in Drupal book.
Can somebody explain me these files or post names all this kind files?
Answer: It's just a convention used for separating logic out of the main .module file.
The [modulename].pages.inc file typically contains page callback functions (those defined in hook_menu()). Since these functions aren't used in every page request there's no point including them, so they're auto-included from the file property defined in hook_menu() when needed.
You'll probably come across [modulename].admin.inc too, which typically contains callback functions for admin pages.
[modulename].api.php is another convention that Drupal core uses (and subsequently a lot of contrib modules use) to show examples of the hooks they provide, and usually how to use them.
There are other [modulename].[group].inc files that can be auto-included when another module implements hook_hook_info():

Normally hooks do not need to be explicitly defined. However, by declaring a hook explicitly, a module may define a "group" for it. Modules that implement a hook may then place their implementation in either $module.module or in $module.$group.inc. If the hook is located in $module.$group.inc, then that file will be automatically loaded when needed. In general, hooks that are rarely invoked and/or are very large should be placed in a separate include file, while hooks that are very short or very frequently called should be left in the main module file so that they are always available.
Comment: Doing this can help with the memory footprint, as files  are only loaded if they are actually needed for a particular request.