Dúvida com modelagem relacional

Question: Estou montando um cadastro de imóveis, aonde estes imóveis pertencem a um endereço, que pertence a um bairro que pertence a uma cidade.
Ex tabelas:
Imoveis: id, endereco_id, etc...

Enderecos: id, nome, bairro_id, rua, numero, cep, etc...

Bairros: id, nome, cidade_id

Cidades: id, nome;

Porém, se eu quiser efetuar uma busca de imóveis em uma cidade cadastrada, como fica este relacionamento, é válido duplicar a chave dentro de Imoveis, criando uma cidade_id?
Primeira situação: Ao efetuar buscas em selects, quero listar apenas as cidades que possuem imóveis cadastrados.
Segunda situação: Selecionar a cidade e listar via ajax os bairros que possuem cadastro de imovel.
Terceira situação: buscar os imóveis e listar juntamente com eles, os respectivos enderecos, bairro e cidade.
Alguma idéia de como trabalhar melhor estes dados, e se estou no caminho certo?
Obs: Não estou pedindo as queries prontas, e sim idéias de como implementar da melhor forma este modelo relacional, aonde o cadastro de cada bairro e cidade será feito juntamente com as outras informações do imóvel, salvando de forma consistente os nomes de bairros e cidades, evitando a duplicidade do cadastro destes.
Comment: @MarceloAymone o que vai dar o desempenho é índice, e a quantidade de dados que trafega pela interface. Pode até haver diferença em separação de arquivos dependendo da forma que você organiza (para melhor ou pior inclusive), mas para se preocupar com esse tipo de ajuste, só numa aplicação imensa ou muito crítica (envolveria uma análise mais complexa do caso).
Comment: @MarceloAymone até por serem realmente entidades. Melhor cadastrar o bairro novo quando precisar, do que virar bagunça. Um lembrete: bairro é entidade de cidade, e não do cadastro geral. Isso facilita mais ainda a organização. Mesmo que dois bairros tenham nomes iguais em cidades diferentes (ou o Centro, por exemplo), tratando separadamente é conceitualmente melhor. "coincidência" não deve ser convertida em regra ;)
Comment: Minha primeira dúvida seria se você realmente precisa ter esta normalização do endereço. Tem alguma necessidade ou vantagem? Um imóvel pode estar em mais de um endereço? Existe uma razão para o endereço estar separado?
Comment: Em relação a redundância dos `id`s, talvez te interesse: http://pt.stackoverflow.com/q/22208/7261 Você pode optar por ter uma coluna `[tabela]_id` redundante ou usar `JOIN` para fazer a consulta filtrando por cidade. Na segunda situação, pode usar um `LEFT JOIN` ou `RIGHT JOIN`
Comment: @MarceloAymone Você tentou das duas formas e mediu se há ganho? Ter que acessar dados em dois lugares piora a performance. Se a tabela é menor **pode** ter ganho de performance. Mas só se todos dados estão nela. Separar pode até organizar um pouco mais, só isto. Mas é raro precisar de toda esta organização.
Comment: Não respondi porque você já obteve uma resposta. Exceto pelo endereço separado, sua modelagem está boa, é só fazer as *queries* corretamente. Na resposta tem uma boa base para fazer. Cidade e Bairro são entidades e não uma descrição, portanto você fez o correto. Aí você vai ter que ver se vai implementar alguma forma de achar bairros próximos em um raio. É bem mais complicado mas é muito útil e muitos sites do tipo implementam isto. Foi só uma ideia para você.
Comment: @bigown Um imóvel pertence a um endereço único. Está separado, porque a tabela imóvel é grande, e porque nem sempre vou chamar Endereços...Existe a questão da atualização em cascata, se remover uma cidade, ou bairro, deve ir tudo o que pertence a ele/ela junto.
Comment: @Marcelo (apenas um comentário...) para isso bastaria selecionar os campos que for usar no select, não precisaria necessariamente separar a tabela.
Comment: Mas para efeito de desempenho, quanto menor a tabela, não há melhor desempenho em `selects`?
Comment: Ok, na verdade, separar ou não endereco não seria o meu foco da pergunta e sim quanto a cidades e bairros, etc.
Comment: Havia pensado nisto @bigown, realmente é algo bem interessante buscar por proximidade. Permite ao usuário mais dinamicidade de busca, vou condensar imovel e endereco na mesma tabela e tentar seguir com bairro e cidade como entidades.
Comment: Vale uma olhada aqui: http://pt.stackoverflow.com/questions/622/qual-a-melhor-maneira-de-se-representar-um-endere%C3%A7o
Answer: Segundo comentários e aspectos expostos na pergunta, a melhor maneira de modelar suas tabelas é a seguinte:

Imoveis: id, nome, cidade_id, rua, numero, complemento, cep, bairro, ...
Cidades: id, nome, estado, ...

O estado colocado em Cidades pode ser uma tabela Estado ou então um enumerável dentro da sua aplicação, se a aplicação funcionar apenas para o Brasil.
Podemos juntar Enderecos e Imoveis dentro de uma única tabela, visto que a cardinalidade sempre será de 1 pra 1 entre essas duas tabelas, e a manutenção de dois objetos pode causar inconsistências desnecessárias.
Um cadastro de bairros pode ser interessante se forem poucas cidades, mas se torna trabalhoso considerando que seu sistema pode trabalhar com o país inteiro. Por exemplo, para cadastrar um imóvel, o bairro teria que existir primeiro. Não apenas isso, em cidades como São Paulo, não há concordância com o nome do bairro em determinadas regiões. Já vi cadastros em que um endereço aparece em até 3 bairros diferentes.
Portanto, o melhor para Bairros é utilizar uma coluna bairro, em que o nome do bairro possa ser especificado por extenso.
Para Cidades, o melhor é Imoveis referenciá-la diretamente. Você conseguirá sua pesquisa por cidade facilmente desta forma. Voltando ao problema dos bairros, o join para a pesquisa seria maior e mais complexo, além de ter o agravante do problema de dissonância entre bairros de uma mesma cidade, conforme expliquei mais acima:
select c.*, b.*, i.*
from Imoveis i
inner join Bairros b on i.bairro_id = b.id
inner join Cidades c on b.cidade_id = c.id
where c.nome like "%expressao%";

Da forma sugerida na resposta, fica:
select c.*, i.*
from Imoveis i
inner join Cidades c on i.cidade_id = c.id
where c.nome like "%expressao%";

Comment: Não pela dificuldade, o negócio do site é vender imóveis, não cadastrar com a máxima eficiência, até porque, o cadastro será pela própria imobiliária, reduzindo significativamente a chance de erro, pensei até em utilizar um webservice como busca cep, por ser mais simples, quanto a minha dúvida de normalizar ou não, as cidades e bairros, seria mais com foco de facilitar a pesquisa através de detalhes como estes.
Comment: Considerando que vou necessitar fazer uma busca de imóveis cadastrados em um determinado bairro de uma determinada cidade, e que gostaria que apenas cidades e bairros com imóveis cadastrados apareçam nesta lista, permitindo que se cadastre manualmente o bairro, como evitar duplicidade em casos de um nome de bairro mal digitado?
Eu estava pensando em fazer um botão "Adicionar bairro/cidade" em que pudesse ser salvo via ajax um novo bairro, e recarregado automaticamente no select para o usuário incluir um bairro/cidade que não existe ainda no sgbd
Comment: A maneira mais legal de fazer isso seria gravando o nome do bairro fonetizado. Por exemplo, se o usuário escrever "Cerqueira Cézar", "Cerqueira Cesar" ou então "Cerqueira César", o algoritmo fonetizaria uma única `String` para os três, evitando esses problemas de cadastro. Na pesquisa, pesquisando por qualquer uma das `Strings` de exemplo retornaria todos os resultados. [Veja esta questão](http://pt.stackoverflow.com/questions/1828/como-fazer-um-algoritmo-fon%C3%A9tico-para-o-portugu%C3%AAs-brasileiro) em que isso é tratado com mais detalhes.
Comment: Achei interessante, mas um canhão para matar moscas.
É somente um site de imobiliária com buscas por cidades, bairros, quartos, etc.
Comment: Bom, isto possivelmente é escopo para outra pergunta ;)
Comment: Estado não tem necessidade, o foco da aplicação é apenas no estado de santa catarina, com foco na região da capital e adjacentes.
Comment: Melhor ainda. O campo pode ser retirado da modelagem, então.
Comment: Não é tão difícil quanto parece. [Veja este outro link](http://sourceforge.net/p/metaphoneptbr/code/ci/master/tree/README).

Dúvida com modelagem relacional


Increment the day value from current day

Question: For example, in my case, i already has this value of array.....
   array(1) {
   [1]=>
   array(1120) {
    ["2006-02-25"]=>
     array(1) {
      [0]=>
      int(33)
    }
    ["2006-02-20"]=>
    array(1) {
      [0]=>
      int(38)
    }
    ["2006-02-28"]=>
    array(1) {
      [0]=>
      int(46)
    }

that result I've got this code
    $explodeEndDate = explode(" ",$adEndDate);
    $explodeStartDate = explode(" ", $adStartDate);

    $StartDate = $explodeStartDate[0];

    $NewStartDate = strtotime("$explodeStartDate[0]");
    $NewEndDate = strtotime("$explodeEndDate[0]");

    $timeDiff = abs($NewEndDate - $NewStartDate);

    // 86400 seconds in one day
    $NumberDays = $timeDiff/86400;

    //convert into int
    $NumberDays = intval($NumberDays);

    if(array_key_exists($NumberDays, $array[$itemType]) == false){
        $array[$itemType][$StartDate] =[$NumberDays];
    }
}

what I wanted to achieve is, in the "$StartDate" value which is for example ["2006-02-28"] , I wanted to plus it with the value of it. If we referring back to the figure above for example is
["2006-02-25"]=>
    array(1) {
      [0]=>
       int(33)

so 2006-02-25 is the plus by 33 and the result is 2006-04-01. and after that, i wanted to make the date within that range
Comment: `so 2006-02-25 is plus by 33 and the result is 2006-04-01` while 2006-02-25 is plus by 33  = 20006-03-29. don't you think so?
Comment: Use strtotime function. `date('Y-m-d', strtotime($StartDate . ' +' . $NumberDays . ' Days'));` HF
Comment: @Anant no the result should be 2006-03-29 because in 2006 month february has 29 days
Comment: @MuhammadFebrik  what i want to say that what you asked is wrong
Answer: If you want to add date so here you go:
Months:
<?php
$date = date('Y-m-d', strtotime("+33 months", strtotime('2006-02-25')));
var_dump($date)
?>

Demo.
Days:
<?php
$date = date('Y-m-d', strtotime("+33 days", strtotime('2006-02-25')));
var_dump($date)
?>

Demo
Comment: @MuhammadFebrik where you get this value. Show me your code.


Connection reset by peer while using apache as reverse proxy

Question: I've installed Transmission daemon on machine #0(Ubuntu 16.04.5, native), and Apache2(Apache/2.4.18) on machine #1(Ubuntu 16.04.5, on XCP-NG 75). Apache is now reverse-proxying transmission for adopting TLS to transmission rpc.
Wherever I connect to transmission via apache, it continues returning 'Connection reset by Peer' for few minutes interval.
I can sure this is not a problem of network, since SSH connection from My PC to machine #1, and machine #1 to machine #0 both remains stablized.
This is a config for transmission vHost.
<IfModule mod_ssl.c>
    <VirtualHost *:443>
        SSLEngine on
        SSLCertificateFile [A Certificate File]
        SSLCertificateKeyFile [A Certificate Key File]
        SSLCertificateChainFile [A Certificate Chain File]
        ServerName [Hostname]

        ProxyRequests Off
        ProxyPass / http://[Address to machine #0]:9091/
        ProxyPassReverse / http://[Address to machine #0]:9091/
        <Location "/">
            AuthType Basic
            AuthName "Transmission"
            AuthUserFile [Authentication File]
            Require valid-user
        </Location>
    </VirtualHost>
</IfModule>

Which makes this kind of problem? and how should I fix it?
Answer: I've (finally) joined the StackExchange community to help you, as nobody has answered yet.
I was facing the same issue today, and it looked definitely related to the Apache SSL info we could notice within verbose logs :

[ssl:info] [...] The timeout specified has expired: [...] SSL input filter read failed.

So a "solution" (mostly a "workaround" IMHO) is proposed here.
Here is a blog post I've written about this very setup : link.
Bye
PS : In my specific case, SetEnv nokeepalive sufficed.

TL;DR
Try adding SetEnv nokeepalive ssl-unclean-shutdown to your VHOST configuration.
Comment: Use of links in answers to cite sources is welcome. But it is no substitute for writing an answer that can be used on its own without the links. Please edit your answer to include all the necessary information. Also greetings don't belong in questions and answers on this site, only include information relevant to the question/answer.


Binary variable to multiple records of same key based on characters in another field in R

Question: I have a table of doctor visits wherein there are sometimes multiple records for the same encounter key (Enc_Key) if there are multiple diagnoses, such as:
Enc_Key | Patient_Key |   Enc_Date   | Diag
  123         789         20160512      asthma
  123         789         20160512      fever
  123         789         20160515      coughing
  546         013         20160226      flu
  564         444         20160707      laceration
  789         226         20160707      asthma
  789         226         20160707      fever

I am trying to create an indicator variable Diag_Ind based on the value of the character variable Diag, but I need to apply it for the entire encounter. In other words, if I get a value of "asthma" for Diag for a record, then I want to apply a "1" for the Diag_Ind to every record that has the same Enc_Key, such as below:
Enc_Key | Patient_Key |   Enc_Date   | Diag            | Diag_Ind
  123         789         20160512      asthma             1
  123         789         20160512      fever              1
  123         789         20160515      coughing           1
  546         013         20160226      flu                0
  564         444         20160707      laceration         0
  789         226         20160707      asthma attack      1
  789         226         20160707      fever              1

I can't seem to figure out a way to apply this binary indicator to multiple records. I have been using a line of code that resembles this:
tbl$Diag_Ind <- ifelse(grepl('asthma',tolower(tbl$Diag)),1,0)

but this would only assign a value of "1" to the single record with that Diag value, such as this:
Enc_Key | Patient_Key |   Enc_Date   | Diag            | Diag_Ind
  123         789         20160512      asthma             1
  123         789         20160512      fever              0
  123         789         20160515      coughing           0
  546         013         20160226      flu                0
  564         444         20160707      laceration         0
  789         226         20160707      asthma attack      1
  789         226         20160707      fever              0

I'm unsure of how to apply it to the rest of the records with the same Enc_Key value
Answer: We can use base R ave to check if any value in every group of Enc_Key has asthma in it
df$Diag_Ind<- ave(df$Diag, df$Enc_Key,FUN=function(x) as.integer(any(grep("asthma", x))))

df
#  Enc_Key Patient_Key Enc_Date       Diag Diag_Ind
#1     123         789 20160512     asthma        1
#2     123         789 20160512      fever        1
#3     123         789 20160515   coughing        1
#4     546          13 20160226        flu        0
#5     564         444 20160707 laceration        0
#6     789         226 20160707     asthma        1
#7     789         226 20160707      fever        1

Similar solution with dplyr
library(dplyr)
df %>%
 group_by(Enc_Key) %>%
 mutate(Diag_Ind = as.numeric(any(grep("asthma", Diag))))

#   Enc_Key Patient_Key Enc_Date    Diag    Diag_Ind
#    (int)       (int)    (int)     (fctr)    (dbl)
#1     123         789 20160512     asthma        1
#2     123         789 20160512      fever        1
#3     123         789 20160515   coughing        1
#4     546          13 20160226        flu        0
#5     564         444 20160707 laceration        0
#6     789         226 20160707     asthma        1
#7     789         226 20160707      fever        1


Alternative to Geogebra

Question: In Norwegian schools, Geogebra is widely used for plotting graphcs, calculus, algebra, etc. However, by the looks of it, it is not very commonly used, so the documentation and resources is very limited (especially on the Computer Algebra System). Is there any good alternatives to it? What is most used in other countries/professionally? This is only basic functions, like finding derivatives/extrapolating and solving polynomial equations, no 3D.
Comment: See also [these alternatives](https://readysetgeo.wordpress.com/challenges/alternatives-to-geogebra/).
Comment: For a computer algebra system, definitely go with Mathematica: http://www.wolfram.com/mathematica/ , it is very widely used and supported, a free and open source alternative that is very nice as well, is sage: http://www.sagemath.org/ . For, quick, on the go plotting, you probably already know about wolfram alpha: https://www.wolframalpha.com/ (both web and mobile app exists). For playing around with geometry like in GeoGebra I would say stay with GeoGebra actually, but otherwise: "The Geometer's Sketchpad": http://www.dynamicgeometry.com/ .
Answer: Try Mathematica: https://www.wolfram.com/mathematica/. It might be a little overpowered for what you're using it for, but I can almost guarantee it'll be sufficient.
Comment: You should perhaps mention that this piece of software is not free. It quite expensive in general, but if you can show that you are a student it's quite a reasonable price (at least for people in the first world).
Comment: Yes, I probably should have mentioned that. I honestly had forgotten, as my university pays for a copy that can be streamed from a central VM.

Alternative to Geogebra


apache2.4 with vhosts & TLS certificates: certificate for wrong vhost presented

Question: I operate a server hosting multiple virtualhosts with apache2.4.
A newly hosted domain (https://www.yachtenwelt.de) is correctly using the respective TLS certificate.
In addition, I have to ensure that the user gets redirected to exactly this domain with any given combination, so I have to cover:

http://yachtenwelt.de
http://www.yachtenwelt.de
https://yachtenwelt.de

The redirects from the non-https versions 1 & 2 works. But when I use #3, I get a certificate warning that there is a name mismatch in the TLS certificate, the reason being that the browser is presented with the TLS certificate for another vhost running on my server (https://www.4-happy-paws.de). You can check this e.g. via https://www.ssllabs.com/ssltest/analyze.html?d=yachtenwelt.de&hideResults=on
Strangely enough, if I proceed anyways, my browser (Chrome) afterwards says that the TLS certificate is the correct one issued for the two domains yachtenwelt.de as well as www.yachtenwelt.de.
vhost config file for yachtenwelt:
<VirtualHost *:80>
ServerName yachtenwelt.de
ServerAlias www.yachtenwelt.de
Redirect / https://www.yachtenwelt.de/
</VirtualHost>

<VirtualHost *:443>
ServerName yachtenwelt.de
Redirect / https://www.yachtenwelt.de/
</VirtualHost>

<VirtualHost *:443>
ServerName www.yachtenwelt.de
DocumentRoot /var/www/vhosts/yachtenwelt.de/html
<Directory "/var/www/vhosts/yachtenwelt.de/html">
    Options +FollowSymLinks
    AllowOverride All
</Directory>
ServerAdmin firstname.lastname@example.com
ErrorLog /var/www/vhosts/yachtenwelt.de/log/apache2/error.log
LogLevel emerg
TransferLog /var/www/vhosts/yachtenwelt.de/log/apache2/access.log
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/yachtenwelt.de/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/yachtenwelt.de/privkey.pem
</VirtualHost>

vhost config file for 4-happy-paws:
<VirtualHost *:80>
ServerName www.4-happy-paws.de
ServerAlias 4-happy-paws.de
Redirect / https://www.4-happy-paws.de/
</VirtualHost>

<VirtualHost *:443>
DocumentRoot /var/www/vhosts/4-happy-paws.de/html
ServerName www.4-happy-paws.de
ServerAlias 4-happy-paws.de
Alias /.well-known/acme-challenge/ /var/www/vhosts/4-happy-paws.de/html/.well-known/acme-challenge/
<Directory "/var/www/vhosts/4-happy-paws.de/html">
    Options +FollowSymLinks
    AllowOverride All
</Directory>
<Directory "/var/www/vhosts/4-happy-paws.de/html/.well-known/acme-challenge/">
    Options +FollowSymLinks
    AllowOverride All
</Directory>
ServerAdmin email@example.com
ErrorLog /var/www/vhosts/4-happy-paws.de/log/apache2/error.log
LogLevel emerg
TransferLog /var/www/vhosts/4-happy-paws.de/log/apache2/access.log
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/www.4-happy-paws.de/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/www.4-happy-paws.de/privkey.pem
</VirtualHost>

apache2ctl -S: I cropped the output, removing the other domains I'm hosting
VirtualHost configuration:
*:443                  is a NameVirtualHost
         default server www.4-happy-paws.de (/etc/apache2/sites-enabled/4-happy-paws.de.conf:7)
         port 443 namevhost www.4-happy-paws.de (/etc/apache2/sites-enabled/4-happy-paws.de.conf:7)
                 alias 4-happy-paws.de
         port 443 namevhost yachtenwelt.de (/etc/apache2/sites-enabled/yachtenwelt.de.conf:7)
         port 443 namevhost www.yachtenwelt.de (/etc/apache2/sites-enabled/yachtenwelt.de.conf:12)
*:80                   is a NameVirtualHost
         default server www.4-happy-paws.de (/etc/apache2/sites-enabled/4-happy-paws.de.conf:1)
         port 80 namevhost www.4-happy-paws.de (/etc/apache2/sites-enabled/4-happy-paws.de.conf:1)
                 alias 4-happy-paws.de
         port 80 namevhost yachtenwelt.de (/etc/apache2/sites-enabled/yachtenwelt.de.conf:1)
                 alias www.yachtenwelt.de
ServerRoot: "/etc/apache2"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/var/log/apache2/error.log"
Mutex ssl-cache: using_defaults
Mutex default: dir="/var/run/apache2/" mechanism=default
Mutex mpm-accept: using_defaults
Mutex watchdog-callback: using_defaults
Mutex rewrite-map: using_defaults
Mutex ssl-stapling-refresh: using_defaults
Mutex ssl-stapling: using_defaults
PidFile: "/var/run/apache2/apache2.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="www-data" id=33
Group: name="www-data" id=33

apache2ctl -t:
Syntax OK

Answer: Unfortunatly you can't redirect the Client, without having a valid certificate. As the TLS Handshake happens before the redirect.
Since it seems as you are using Letsencrypt the best solution would be the get a certificate with both Names. If you are using certbot you could just add the -d Domain flag multiple times.
certbot -d yachtenwelt.de -d www.yachtenwelt.de [...]
Afterwards make sure to include the Certificate in both VirtualHost directives.
<VirtualHost *:443>
ServerName yachtenwelt.de
Redirect / https://www.yachtenwelt.de/
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/yachtenwelt.de/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/yachtenwelt.de/privkey.pem
</VirtualHost>

Comment: I **do** have a valid certificate which is issued exactly as you suggest to both `yachtenwelt.de` as well as `www.yachtenwelt.de`. The only case where it doesn't work is with `https://yachtenwelt.de` where - for whatever reason - I'm presented with the certificate for a different vhost - `www.4-happy-paws.de`.

Extending your thought though could be a workaround: issue a certificate including all relevant domains:
`certbot -d yachtenwelt.de -d www.yachtenwelt.de -d www.4-happy-paws.de [...]`, however since it's different customers I'd prefer to keep the certificates separate as well.
Comment: I think I got the issue, I update the answer
Comment: Thank you so much Ben! The problem is solved now! Apparently (just guessing) apache needs the SSL Certificates when inside a SSL-enabled vhost and because I didn't specify any SSL Certificates in this specific vhost block it took it from the default :443 vhost, which in my case is `www.4-happy-paws.de`.


How can I fetch source code from synergy using Jenkins

Question: I have installed synergy plugin for Jenkins.
I want to fetch some code from synergy DB.
How can I do it using jenkins?
I have given all the details in SCM section of Jenkins like DB value, Engine, Username and password.
Comment: So what is the issue you are getting?
Comment: Started by user anonymous
Building in workspace C:\Program Files\Jenkins\jobs\test\workspace
[workspace] $ ccm start -d DB_Path -nogui -m -q -h Server_Name -n user_name -pw ******** -rc
java.io.IOException: Cannot run program "ccm" (in directory "C:\Program Files\Jenkins\jobs\test\workspace"): CreateProcess error=2, The system cannot find the file specified
 at java.lang.ProcessBuilder.start(Unknown Source)
 at hudson.Proc$LocalProc.(Proc.java:244)
 at hudson.Proc$LocalProc.(Proc.java:216)
 at hudson.Launcher$LocalLauncher.launch(Launcher.java:773)
Comment: Is the program `ccm` in the PATH of the user with which Jenkins is running? Try printing `echo %PATH%` and see what you get in console log of this job.
Comment: Thanks. I figured out the error. As I am new to Jenkins so didn't notice the option to specify ccm exe path. So I rectified this error. But next error comes as
Comment: java.io.IOException: Cannot run program "C:\Program Files\IBM\Rational\Synergy\7.1\bin" (in directory "C:\Program Files\Jenkins\jobs\test\workspace"): CreateProcess error=5, Access is denied
Answer: Well, as i stated in my comments, the reason behind the following original issue error was related to PATH:
Cannot run program "ccm" (in directory "C:\Program Files\Jenkins\jobs\test\workspace"): CreateProcess error=2, The system cannot find the file specified...

For the second issue i.e.,
Cannot run program "C:\Program Files\IBM\Rational\Synergy\7.1\bin" (in directory "C:\Program Files\Jenkins\jobs\test\workspace"): CreateProcess error=5, Access is denied

it seems you have not specified the full path to the executable as shown in the above error message.
Hopefully, changing
"C:\Program Files\IBM\Rational\Synergy\7.1\bin"
to
"C:\Program Files\IBM\Rational\Synergy\7.1\bin\executable_name.exe"
should do the trick.
Comment: Okay. Thanks a lot. Can you maybe help in the next error message as -
[workspace] $ "C:\Program Files\IBM\Rational\Synergy\7.1\bin\ccm.exe" start -d DBPath -nogui -m -q -h ServerName -n UserName -pw ******** -rc

ccm command failed
Warning: Cannot open logfile 'C:\ \ccm_ui.log'
Warning: IBM Rational Synergy startup failed.

When I run this in cmd it runs though.
Comment: Is there something in jenkins that is stopping itself to access the synergy db. Like if it is getting called remotely.
Comment: Are you running the exact same command through command line and it's working fine?
Comment: Yes it is working fine from cmd line. Just entered the password manually.
Comment: If all your commands work fine as user 'X' from command line, then try running Jenkins with the same user. This can be achieved by going to `Run > services.msc (Enter) > Jenkins > Properties > Log On (tab) > Select user and provide credentials > Restart Jenkins`
Comment: It also worked :) Thanks a lot..

But How can I disable build manager role. I just want to extract the code from synergy to my workspace. Will be of great help..
[workspace] $ "C:\Program Files\IBM\Rational\Synergy\7.1\bin\ccm.exe" set role build_mgr
ccm command failed
Warning: 'build_mgr' is not a valid role for user
Comment: Glad it worked. :) You should raise a separate question for the current issue.
Comment: Okay .. will raise it.. Thanks.. :)
Comment: As you explained yesterday of logging in Jenkins using the same X account, so is it not picking up the credentials from the synergy plugin? Cz I practically want synergy to use a particular credential(Y) but I don't want to login in into jenkins using that(Y).
Comment: Is this related to the other question that you posted yesterday?
Comment: No, this is about "Run > services.msc (Enter) > Jenkins > Properties > Log On (tab) > Select user and provide credentials > Restart Jenkins"

The credentials that I have for accessing the synergy is in a domain from which I can't loggin into jenkins. So I want to loggin into jenkins using some other credentials and want synergy to pick the credentials that I set when I configure the synergy plugin.
Comment: There are three different things: User with which you login to Jenkins, user with which Jenkins runs & user whose credentials you are providing to Synergy plugin. All these can be different users. After understanding this, let me know what you're looking for.


Dynamically calculate padding of viewPager depending on screen size

Question: I am just about to create Android application and I need to calculate left and right padding of ViewPager so I can show three fragment items in it, one to be centered and the other two to be from left and right side of the first one.
If I set some fixed values of padding it looks good on one device, but on the other I cannot see all three items, but only one OR if I set padding to be too big then my ViewPager overlap items. So I need to calculate it depending on screen size.
I have found this question but it does not solve my problem.
The arrangement of the fragments should be like on the picture
enter image description here
Can you please help me to solve this problem?
thanks in advance
Answer: you are looking for Carousel View ( so you can make your ViewPager looks like the one in the Picture)
I think there is  a lot of libraries will help you to do this ;
https://github.com/codepath/android_guides/wiki/ViewPager-with-FragmentPagerAdapter
https://github.com/clkasd/CarouselViewProject
this question would be helpful :
How to create a carousel using viewpager and fragmentStatePager Adapter
Comment: Thank you for your time and effort. I hope so that this will work. I am trying to implement this using Xamarin Android... Eventually I will let you know the outcome. Thanks again!
Comment: Hi, I have tried but unfortunately there is no "net.infratek.CarouselView.MyLinearLayout" in Android Xamarin and I cannot use this.
Do you have any other idea how can I solve the problem?
thank you!
Answer: I have tried to setup negative margins in order to display 3 fragments in viewpager, but unfortunately I didn't achieve desired look - negative margins don't work for Android Xamarin and only one fragment is shown on the screen.
So far, the only way is, depending on some constant, to set left and right padding.


double or decimal for temperature spread formula

Question: I am looking at writing an application which calculates temperatures spread in a material with an exposure (such as fire) over time.
I then need to draw the result as a heat map on the geometry of the material.
Now I wonder if I should in general go with Decimal or Double for all calculations and drawing. I have looked into both but are still unsure which to use.
I will need to compare values, including interpolated values over time. And double have as far as I understand it comparison problems due to inexact representation.
But decimal is heavy to work with.
I am leaning towards double only but at the same time more exact representation and comparison is worth a lot too.
Answer: Any finite representation of decimal numbers is bound to have the same "inexact representation" issues as a finite binary representation. Not all real numbers can be represented in finite space and going to base 10 is not going to help there.
Decimal just uses the same bits less efficiently—when talking of representing a physical simulation. On the other hand, a particular implementation of decimal numbers may allow to use more bits, but multi-precision binary floating-point implementations are available too.
The superstition that decimal floating-point libraries would somehow not be "inexact" or have "comparison problems" is widespread because these libraries can represent exactly decimal numbers, starting with 0.1. If your simulation involves coefficients that are powers of ten, then decimal would indeed be a good fit. Otherwise, decimal will not solve any of the problems inherent to the finite representation of a continuous range of numbers.
Comment: @RickardLiljeberg There is no general answer. The knee-jerk reaction is to compare up to epsilon, but this is just that: a knee-jerk reaction. If you go that route, you must accept that quantities that wouldn't be equal as reals will treated equal in your algorithm. You should compute how the initial uncertainly on inputs compounds into a final error, and choose the epsilon on this basis.
Comment: As a side-question, may I ask what is the best way to compare doubles?


Restricted Growth Function and Partition

Question: Can someone explain how do I convert from Partition to Restricted Growth Function to and vice versa? For example: how [1,1,1,2] is the RGF of {{1,2,3},{4}} partition?
I have read the definitions but I do not understand it.
Answer: The procedure is this:
First, you sort the parts in the partition by their lowest element. In the case of the partition $\{\{1,2,3\},\{4\}\}$, this is already done: the order is $(\{1,2,3\}, \{4\})$. For a more complicated example, we sort
$$
   \{ \{3,6\}, \{1,4,8\}, \{2\}, \{5,7\}\} \Longrightarrow (\{1,4,8\}, \{2\}, \{3,6\}, \{5,7\}).
$$
Second, you assign the parts labels $1,2,3, \dots$ in that order. In the case of $(\{1,2,3\}, \{4\})$, $\{1,2,3\}$ gets assigned label $1$, and $\{4\}$ gets assigned label $2$. In the case of $(\{1,4,8\}, \{2\}, \{3,6\}, \{5,7\})$, $\{1,4,8\}$ gets assigned label $1$, $\{2\}$ gets assigned label $2$, $\{3,6\}$ gets assigned label $3$, and $\{5,7\}$ gets assigned label $4$.
Some people begin at $0$ instead of $1$.
Finally, you write down the restricted growth string by writing the label of the part containing $1$, then the label of the part containing $2$, then the label of the part containing $3$, and so on. In the case of $(\{1,2,3\},\{4\})$, we write down $(1,1,1,2)$ because $1,2,3$ are all in part $\{1,2,3\}$, which has label $1$, but $4$ is in $\{4\}$, which has label $2$. In the case of $(\{1,4,8\}, \{2\}, \{3,6\}, \{5,7\})$, we write down
$$
   (1,2,3,1,4,3,4,1)
$$
because, for example, $\{1,4,8\}$ is the partition with label $1$, so we write down a $1$ in the $1^{\text{st}}$, $4^{\text{th}}$, and $8^{\text{th}}$ positions.

To convert back, you just put all integers whose positions have the same label into the same part.


3 layouts e uma activity

Question: Tenho uma actyvity_main, contendo 3 radiobuttons (cada um corresponde a um layout), e um botão. Após o usuário selecionar a opção, ele clica no botão, que faz uma chamada para outra activity, onde nela, preciso fazer com venha com o layout selecionado.

public void onClick(View view) {
        int checkeRadioButtonId = escolhaRadio.getCheckedRadioButtonId();
        switch (checkeRadioButtonId) {
            case R.id.rdb1:
                Intent opcao8 = new Intent(this, Activity_Jogo.class);
                setContentView(R.layout.layout_8);
                startActivity(opcao8);
                break;
            case R.id.rdb2:
                Intent opcao10 = new Intent(this, Activity_Jogo.class);
                setContentView(R.layout.layout_10);
                startActivity(opcao10);
                break;
            case R.id.rdb3:
                Intent opcao12 = new Intent(this, Activity_Jogo.class);
                setContentView(R.layout.layout_12);
                startActivity(opcao12);
        }
    }

Dessa maneira que estou fazendo, ele chama o layout e, após aparecer ele instantaneamente chama a activity, ficando somente a activity com seu layout padrão.
Comment: Tem de explicar melhor o que pretende. Uma coisa é certa o `setContentView()` só deve ser chamado uma vez em cada activity e deve sê-lo no método `onCreate()`.
Comment: Tem como eu chamar só uma activity, passando qual layout ela deve exibir?
Comment: Tem mas torna-se complicado gerir cada uma das Views que compõem cada um dos layouts passados. A melhor solução é usar fragments ou Activities diferentes.
Answer: A forma mais simples seria passar o resource do layout por Extras, e recuperar na próxima Activity:
public void onClick(View view) {
    int checkeRadioButtonId = escolhaRadio.getCheckedRadioButtonId();
    Intent i = new Intent(this, Activity_Jogo.class);

    switch (checkeRadioButtonId) {
        case R.id.rdb1:
            opcao10.putExtra("opcao", R.layout.layout_8);
            break;
        case R.id.rdb2:
            opcao10.putExtra("opcao", R.layout.layout_10);
            break;
        case R.id.rdb3:
            opcao10.putExtra("opcao", R.layout.layout_12);
            break;
    }

    startActivity(i);
}

No método onCreate da sua Activity_Jogo você recuperaria esse valor e usaria como contentView:
@Override
protected onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    int layout = getIntent().getIntExtra("opcao", 0);

    // Se ninguem passou um layout como parametro,
    // voce pode usar um padrao ou fechar a Activity
    if(layout == 0) {
        finish();
    }

    setContentView(layout);

    // Restante do seu processamento...
}

Comment: É uma possibilidade mas depois torna-se complicado gerir cada uma das *Views* que compõem cada um dos layouts passados. A melhor solução é usar fragments ou Activities diferentes.
Comment: @ramaral, sim, com certeza, não tinha pensado por esse lado. Minha solução só é ótima se os layouts possuem os mesmo elementos, mas com uma arrumação diferente.

3 layouts e uma activity


Unable to access tomcat server on 8080 port from Google Compute Engine VM (Windows Server 2012)

Question: I have created Virtual Machine Under Google Compute Engine and selected Windows Server 2012 R2 as OS for the server. I have installed Tomcat 8 and and it is running on 8080 HTTP port. I can access locally tomcat on browser using internal IP and localhost. But I can not able to access tomcat using external IP from my local computer.
Please help me if possible. My tomcat server configuration file of tomcat is below.
Answer: There are two common issues for this:

You need to open port 8080 on GCE's firewall in order for it to be accessible from outside GCE.
It is possible that Tomcat is only listening on the localhost. You might need to set the HTTP Connector address attribute to 0.0.0.0 so that Tomcat listens on all addresses.
Comment: Hi David thank you for you suggestion. Suggestion worked. I have configured Google Compute Engine firewall as well as Windows Server 2012 R2 firewall for tomcat port. After that I can access tomcat using external ip from my local computer.
Comment: If you felt my comment fully answers your question, you can [accept my answer](https://stackoverflow.com/help/someone-answers) to mark the question as answered and give us both a bit of reputation bump


How does 'airbreak' work on airsoft guns?

Question: I'm a rookie in the sport of Airsoft and have heard of airbreak feature installation but still couldn't figure out how it works.
It is known to be used for making the Airsoft gun more silent, but I couldn't understand exactly how.
Also it would be nice to know what are the cons as well when having it installed.
Answer: Have a look at this thread on the Airsoft forum and especially tmfreak's answer.
Basically the airbrake stops the piston smacking against the end of the cylinder.
It does reduce the speed of the projectile a little, and it isn't suitable for all airsoft guns, but worth looking at if the noise is an issue for you.
Answer: The airframe works by creating a cushion of air between the piston head which is powered forward by the main  cylinder spring and the cylinder head.
This reduces the impact of the two surfaces hitting each other and producing the distinctive crack of an airsoft gun.
It will also reduce the speed (FPS) of the projectile due to using some of the air inside the cylinder to create the cushion.


Trazer todos os resultados necessários em uma query - MariaDB

Question: Preciso reformular um pequeno sistema, que hoje, funciona mas abrindo várias conexões com o banco de dados, e quando há muitos registros, o banco de dados cai, ou quando isso não acontece, a página fica muito lenta.
Então, para contornar esse problema, estou elaborando uma query que me traga todos os resultados de uma vez só, e ai eu trato essas informações do lado PHP para melhorar o desempenho.
Só estou tendo um pequeno problema: a tabela, que chamarei de teste, pode ter múltiplas relações com teste2 ou teste3, então criei uma tabela item_teste para relaciona-las, porém as informações da tabela teste2 se repetem quando executo a query.
Segue um exemplo no SQL Fiddle
Esta é a query que estou usando:
select distinct t1.teste,
GROUP_CONCAT(t2.teste2 SEPARATOR '&') teste2 ,
GROUP_CONCAT(t3.teste3 SEPARATOR '&') teste3
FROM item_teste it
join teste t1 on t1.id_teste = it.id_teste
join teste2 t2 on t2.id_teste2 = it.id_teste2
join teste3 t3 on t3.id_teste3 = it.id_teste3
where t1.teste like '%testando%'
group by t1.id_teste;

Não sei se essa é a melhor maneira de otimizar, então, há alguma outra forma de otimizar as consultas ou estou no caminho certo?
Answer: Para não repetir as informações do teste2 (não testei mas acredito que resolva) acrescente distinct ex: group_concat(distinct t2.teste2 SEPARATOR '&')


Multiple Certificates on Exchange for OWA and EWS

Question: We are currently running Exchange 2007. All our clients access the EWS service on Outlook via the internal server name server.domain.local. For this we use a self-signed certificate from the domain's CA.
For OWA we would like to use a official certificate, as it needs to be accessible from anywhere e.g. https://owa.domain.com/
In order to access owa, we have a public IP natting (:443 and :80) to the exchange server.
How can I install a separate certificate only for owa and maybe ecp? I only can add one certificate per IP and as IIS only knows the internal IP there is no way to assign a public certificate.
Following two print-screens concerning the IIS configuration:
Answer: Basically, you should have a second NIC for this.
If another NIC is not an option, try adding a virtual IP to the NIC, and then assign the certificates.
I tried it once myself and it half worked, but didn't had enough time to do more testing.
Comment: This is incorrect. If you assign a separate NIC, it means using a different IP address. And that new IP address needs to be associated with a different WEBSITE. The OP requires ONE website, where a virtual directory (subsite of the website) needs to use a different certfificate. Doing what this answer says will not achieve this.
Comment: @Mucker you actually CAN do it. An IIS web site can have multiple bindings and each binding can be associated with a different IP address and use its own certificate. Note that I'm **not** recommending this (especially for Exchange), but it's technically possible.
Comment: @Massimo you are right, you can assign multiple IPs to the same site. I think I didn't consider this because I have never seen anyone assign 2 IPs to bind 2 certs to the same website. Also what threw me off was the extra NIC; to achieve the binding of two certs, you only need an extra IP, not an extra NIC. If you look at my answer below, this is by far the easier and better approach (getting a cert with 2 names) and this is how it's done in the industry.
Answer: Quick EDIT:
In case anyone wants to feel like correcting me... Yes you can use SNI to achieve a quasi multiple certs on one website, but I have not gone into any of these as they involve far more work than the option below. The below is what I have seen done by all IT professionals my whole career. --End EDIT
You CANNOT use two different certificates for one website. This is universal and not related to Exchange. Since Exchange leverages IIS for its web services you cannot do this. You have two options:
When you buy your new public cert add BOTH domain names. Add your external address as the primary and add your internal address as an additional SAN. This way when clients request the web services using either addresses, they will match a name on the cert. This is probably your easiest approach.
You other approach is to not use NAT and use a reverse proxy. A reverse proxy presents a web front end to outside world - in your case to listen on the external URL and use the public cert for this. Then configure the rules on reverse proxy to "proxy" any requests to this URL to come out the back end as your internal name. A reverse proxy actually creates an end-to-end encryption to the external user using the public cert, and "proxies" the traffic through to the internal side using local cert on the IIS server using the local name (it "translates" the URL from external to internal one). If you are unfamilar with reverse proxies do a google, the concept isn't that hard to get.


Cookies ou Session por JavaScript

Question: Estou trabalhando em um projeto, e o back-end (java), está totalmente separado do front-end, e eles se comunicam por REST.
Minha dúvida é, vamos começar a trabalhar na área de autenticação, e queria saber se é possível controlar a autenticação através de cookies ou session, utilizando apenas JavaScript, e se possível existir alguma referência bacana.
Comment: Você pode utilizar OAuth ou Token Authentication e utilizar o store do HTML para armazenar o token em cada navegador
Comment: Estão em inglês mas, para OAuth (http://oauth.net/code/) e HTTPAuthentication (http://www.peej.co.uk/articles/http-auth-with-html-forms.html)
Comment: Obrigado @Caputo
Comment: está usando algum framework MV* ?
Comment: @Caputo não, nenhum framework. Se for possível fazer isso sem a utilização de framework seria ainda melhor.
Comment: Valeu @Caputo, sabe alguma referencia legal sobre OAuth, ou Token Authentication?
Answer: Você não vai poder fazer a sua autenticação usando apenas Javascript. Alguma parte do processo de autenticação vai ter que ser feita no servidor, uma vez que você não pode confiar que o cliente vai executar o código que você mandou pra ele (um cliente malicioso pode fazer requisições HTTP diretamente se ele quiser).
Em primeiro lugar, vamos nos lembrar do que o nosso sistema de autenticação tem que fazer:

Associar dados à seção do usuário (nome do usuário logado, quando a seção expira, itens no carrinho de compra, etc)

Apenas o servidor pode criar uma "seção". Usuários não podem se autenticar sozinhos.

Os dados da seção não podem ser modificados pelo usuário. Por exemplo, não queremos deixar que eu me autentique como hugomg no seu site mas depois mude o campo username do cookie para EricoSouza e faça compras em seu nome.

Armazenando a seção no servidor
A maneira mais simples de manter seções é manter todos os dados no servidor. Assim, os requisitos (1) e (3) vem de graça. A idéia básica é que quando o cliente se autentica1, você gera um identificador de sessão difícil de adivinhar2 o manda para o cliente3. O cliente pode guardar o identificador num cookie4 ou onde for mais conveniente e o seervidor mantém os dados da secão numa tabela indexada por esses identificadores:
123434561234 -> nome:Erico  sessao-expira: ...
467235895637 -> nome:hugomg sessao-expira: ...

Como é difícil adivinhar o identificador de seção e como você mostra o identificador apenas para o usuário correto, seu servidor pode confiar que o usuário está autenticado se ele apresentar um identificador que está na tabela.
1 Usando usuario+senha ou chaves criptográficas ou o que você bem entender
2 Use um número aleatório bem comprido, gerado usando um gerador de números criptograficamente seguro e imprevisível. Não use um contador 1,2,3 e não use rand()
3 Use https, ou qualquer um na wifi do cliente que tiver o Firesheep instalado vai poder enxergar o identificador dele e roubar a seção.
4 Uma boa idéia é marcar o cookie como HttpOnly, por segurança extra.
Armazenando a seção no cliente
Se, por razões de performance, você não quiser ou não puder armazenar os dados de sessão no servidor você vai ter que passar essa responsabilidade para o cliente e encontrar uma forma de proibir o cliente de mexer nos dados que você passa pra ele. Uma forma de fazer isso é usando um Message Authentication Code (MAC), que é um hash dos dados da seção que só pode ser computado pelo servidor1 2.
Uma versão concreta disso é usar um cookie com dois campos: um com os dados da seção codificados em JSON e outro com o MAC computado pelo servidor:
session={"nome":"Erico","expira":""};
MAC=1253712536127354;

Os requisitos (1) vem de graça, já que os dados da seção são reenviados em toda requisição. O requisito (2) é cumprido pois apenas o servidor pode computar o MAC e o requisito (3) vale pois apesar de o usuário poder ver os campo da seção, ele não tem como alterálos pois isso exigiria recomputar o MAC.
1 O calculo do MAC usa uma chave secreta que apenas os seus servidores conhecem.
2 Assim como qualquer outra coisa criptográfica, use alguma biblioteca pronta para calgular esse hash, pois é muito fácil criar uma implementação insegura. A sugestão mais comum é usar o método HMAC com a função de hash SHA-256 ou SHA-1

Uma boa referência é essa pergunta no security.stackexchange
https://security.stackexchange.com/questions/30707/demystifying-web-authentication-stateless-session-cookies
Comment: Valeu @hugomg isso já me ajuda muito e esclareceu mais do que minhas dúvidas. É uma ótima resposta, obrigado.
Comment: tudo bem? Cara o que você me sugere na questão de "Use um número aleatório bem comprido, gerado usando um gerador de números criptograficamente seguro e imprevisível." ?
Comment: @EricoSouza: Um CSPRNG é uma coisa que vc vai querer pegar pronto em uma biblioteca ou no seu sistema operacional. Depende da linguagem que vc tiver usando (se me lembro bem em Java tem uma API SecureRandom que vc pode usar). O importante é que seja impossível para um usuário adivinhar quais os próximos números gerados usando a informação dos números que eles receberam.
Comment: cara, obrigado pela ajuda novamente, estou usando java, vou procurar essa API. Seguindo os passos que você me explicou essa é uma das partes mais importantes que ainda me falta fazer. Já consegui estabelecer a comunicação entre o servidor e o cliente, agora quero gerar a chave para fazer o gerenciamento. Obrigado.

Cookies ou Session por JavaScript


SharedPreferences with OnCreate

Question: I'm trying to achieve a goal which is adding some kind of wizard like this:
App launches for the first time > User follows wizard > Final wizard step saves some data into the SharedPreferences and continues to the activity that the user choosed > App Quits > App Relaunches > App shows activity that the user choose via the wizard data in SharedPreferences.
I know I can save data into the SharedPreferences space but how should I achieve this.
The user gets to see a view via an Android:OnClick action.
My App only has 1 main java class with different view actions like this:
public void myapp_confirmsetup(View view) {
setContentView(R.layout.activity_my_app_confirmsetup);
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("MyApp", "app_off").commit();
}

I think that from now on I only have to load the string with the OnCreate method but I'm unsure how I can do that.
Can someone push me into the right direction?
Comment: possible duplicate of [how to use getSharedPreferences in android](http://stackoverflow.com/questions/5950043/how-to-use-getsharedpreferences-in-android)
Comment: @Dharmendra No it's not I'm not trying to save login form data.
Comment: You know instead of using a string.. you it makes more sense to use a boolean instead of String.. "My_App_Status" and its value can be true or false.. why use a string if its a binary answer anyways...
Comment: I think using a string is better because I'm not only storing on and off but also which type of activity the user decided (So for example firstoption_on,firstoption_off,secondoption_on,secondoption_off).
Comment: thats bad.. bad by design.. you should change it so that it makes more sense. First_Option_State | True or false .. Second_Option_State | True or False. When designing your preferences you should try to be as clear as possible, just because you can doesn't mean you should. There are always better ways to approach these kinds of things. Also constantly comparing objects (Strings) as compared to primitives is not efficient. Its wasted CPU cycles if you don't have to do it.
Comment: Since I'm a beginning Android developer I'm unsure how to achieve that, do you have any example I should try?
Comment: There is a ton of information that is available on the dev site, just look up shared preferences. Also, I'm sure there are enough tutorials on the internet (use google) that go over this. Also make sure you know java.
Answer: use this to store the string...
    final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
    SharedPreferences.Editor editor = pref1.edit();
    editor.putString("Stringval", "xxxxxxx");
    editor.commit();

to get the value from SharedPreference use below code:-
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
String str1= pref2.getString("Stringval", null);

Comment: But I'm already storing data into the SharedPreferences If I'm not mistaking (PreferenceManager.getDefaultSharedPreferences(this).edit().putString("MyApp", "app_off").commit();) I'm looking for something like if string is then load view1 else if string is load view2 is this possible?
Answer:   final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
  String str1= pref1.getString("Stringval", null);
if(str1.equals("app_off")){
   //do something
 }else(str1.equals("app_on")){
   //do something else
 }

Comment: I think this is the thing I want, this code only gives me one problem: java syntax error misplaced constructs - Do you know why?
Comment: Maybe if you put it onCreate() ?
Comment: Did that already, found another solution based on your answer. thanks!

SharedPreferences with OnCreate


Spring-Data-JPA causes XSD validation error in Spring STS using XML configuration

Question: Eclipse/STS reports errors using Spring 3.2.1 with Spring-data-jpa together.
I have some XML configuration files with the following header:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/data/jpa
    http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

I am using Spring 3.2.1 with Spring-Data-JPA 1.3.0 and Eclipse/STS is reporting this:

Referenced file contains errors
  (http://www.springframework.org/schema/data/jpa)

This happens in every single XML configuration file that contains the data-jpa schema.
When I remove JPA from the XML config, everything is just fine.
Is my configuration wrong or what happens here?
Thanks!
Paul
Comment: I get the same thing. I suspect it's because spring 3.2 dependencies import spring-tool-3.2 and spring data xsd imports spring-tool.xsd (no 3.2 suffix). Still don't know how to fix it though
Comment: this might help http://stackoverflow.com/questions/13693065/error-in-spring-application-context-schema
Answer: Today there is not a http://www.springframework.org/schema/data/jpa/spring-jpa.xml file so you have to use http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd, but this file use http://www.springframework.org/schema/data/repository/spring-repository.xsd that does not exist too so you have to add the location of this schema in your context file:
xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/jdbc
                    http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
                    http://www.springframework.org/schema/data/jpa
                    http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
                    http://www.springframework.org/schema/data/repository
                    http://www.springframework.org/schema/data/repository/spring-repository-1.5.xsd
                    http://www.springframework.org/schema/jee
                    http://www.springframework.org/schema/jee/spring-jee-3.2.xsd"

Comment: I just came across this problem. Thanks for sharing!


Android DSP - Trouble with AudioTrack and Sub-Audible Signals

Question: I'm having some trouble getting the AudioTrack class to do what I want it to do. I'm trying to make an app that first lets the user draw a single-cycle waveform on the screen, and then outputs an arbitrary number of cycles of that waveform at an arbitrary frequency through the headphone out. For the primary use, the frequency will be below the audible range, something like 1/60Hz - 20Hz  (If anyone's familiar with Eurorack/modular synths, I'm hoping to use the headphone out as a CV source).
The problem I'm having is that the AudioTrack seems to output a highly inaccurate reproduction of the waveform  at the low end of this frequency range, even though it does output an accurate reproduction at the high end. The lower the frequency gets, the more the waveform gets 'squished' to the left on my oscilloscope. The pictures below show this phenomenon on a waveform that is supposed to start each cycle low and increase linearly to a max value, but this phenomenon happens with other waveshapes too.
So far, I have the app set up (1) to create an ArrayList to hold the data points from the user's input, (2) to convert the ArrayList into a float[] to feed to the AudioTrack, and (3) to setup the AudioTrack and write the float[] to it when needed. Since the ArrayList and float[] both maintain an accurate reproduction of the waveform, I'm pretty sure my problem is at (3), or else it's a hardware limitation of my phone/scope.
Here's the relevant code for the AudioTrack.
Method that (re)initializes the AudioTrack:
public void updateTrackForWave(Waveform wave, Context context) {
    if (wave.getInterpolatedWaveData() == null) return;

    int sampleRate = Integer.parseInt(
            ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE))
                    .getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));

    if (wave.getOutputChannel() == Waveform.OutputChannelEnum.left) {
        if (mTrackL != null) mTrackL.release();
        mTrackL = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
                AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_FLOAT,
                Float.BYTES * wave.getInterpolatedWaveData().length,
                AudioTrack.MODE_STATIC);
        mTrackL.setVolume(AudioTrack.getMaxVolume());
    } else if (wave.getOutputChannel() == Waveform.OutputChannelEnum.right) {
        if (mTrackR != null) mTrackR.release();
        mTrackR = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
                AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_FLOAT,
                Float.BYTES * wave.getInterpolatedWaveData().length,
                AudioTrack.MODE_STATIC);
        mTrackR.setVolume(AudioTrack.getMaxVolume());
    }
}

Method that plays AudioTrack:
private void playWaveOnTrack(Waveform wave, AudioTrack track) {
    if (track == null) return;

    if (track.getPlayState() == AudioTrack.PLAYSTATE_PLAYING) {
        return;
    } else {
        if (wave.isCycleMode()) track.setLoopPoints(0,
                wave.getInterpolatedWaveData().length, -1);
        else if (wave.isOneShotMode()) track.setLoopPoints(0,
                wave.getInterpolatedWaveData().length, 0);

        if (track.getPlayState() == AudioTrack.PLAYSTATE_PAUSED) {
            track.play();
        } else if (track.getPlayState() == AudioTrack.PLAYSTATE_STOPPED) {
            track.write(wave.getInterpolatedWaveData(), 0,
                    wave.getInterpolatedWaveData().length, AudioTrack.WRITE_BLOCKING);
            track.play();
        }
    }
}

It's worth noting that wave.getInterpolatedWaveData() returns the float[] from (3) above.
Anyways, any help you could spare on this would be greatly appreciated! Not sure if I've made a mistake in the code I have, or if there's some code I should add (maybe an AudioEffect of some kind?), or if I'm asking too much of my phone, or what.
PS I'm new here and to Android programming in general, so please do point out any forum norms I should be following but am not, or any alternative coding approaches I might not know about.
Pictures:
Waveform at 100Hz
Waveform at 10Hz
Waveform at 2Hz
Answer: It's a hardware limitation of your phone. In order to avoid a constant DC current flowing through each headphone speaker, they are capacitively coupled -- each channel is in series with one or more capacitors. This gives your output waveform a time constant; the average voltage level of the waveform will always tend towards 0 (GND), which makes it impossible to output DC, or even low-frequency signals.


For what g, $E(X|g(X)=0$ where $X$ is standard normal?

Question: I know if $g(X)=X^2$, the equality holds.  Is there any other $g$?  How can we generalize the case $g(X)=X^2$ (other than $g(X)=X^{2k}$?
Comment: Every even function $g$, to begin with. Or $g=\mathrm 1_B$ where $B$ is such that $E(X;X\in B)=0$. And many more.
Comment: Got it. We just need to partition the domain of $g$ in to segment where $g$ is one to one.
Comment: Hmmm.... There might be cases when this is not even possible.
Comment: Can you give me a little bit more detail to think?  How do you go about proving for the case $g$ is even?
Comment: Got something from the answer below?
Comment: Yes.  Thank you!
Answer: Let $Y=g(X)$ and let $h$ denote some measurable function such that $E(X\mid Y)=h(Y)$. Assume that $g$ is even. Then $Y=g(-X)$, hence, the distribution of $X$ being symmetric, $(-X,Y)$ and $(X,Y)$ are identically distributed. Conditional expectations only depends on distributions hence $E(-X\mid Y)=h(Y)$, that is, $h(Y)=0$.


Two forms on the same page - both submit the same

Question: I have two forms on the same page, both called with drupal_get_form('some_form_name', $product_id);. The $product_id variable is used to fill in a hidden input. (The code is in a foreach, the $product_id variable is different for every form.)
In the generated HTML, the forms are correctly built. Both have different IDs, and both hidden fields have the correct value.
However, in the submit function of this forms, with the following code:
function some_form_name_submit($form, &$form_state) {
    dsm($form_state['values']['product_id']);
}

The product id is always the same. The first generated form's product id.
After some research, I found out that the hidden input form_id is the same in both forms. Looking into that.
Is there a way to solve this?
Answer: Found the solution. The problem was that the forms had the same form_id -- some_form_name, the string passed to drupal_get_form().
I generated the string with something like drupal_get_form('some_form_name_' . $product_id); instead of passing as second argument.
However, that means I would have to define a function for each product id. To avoid this, I implemented hook_forms(), so that each form id starting with some_form_name_ would use the same callback to generate the form:
function mymodule_forms($form_id) {
    if (preg_match('/^some_form_name_\d+$/', $form_id)) {
        return array(
            $form_id => array(
                'callback' => 'some_form_name',
            ),
        );
    }
}

This way, even though each form has a different form_id, they all use the some_form_name function to generate the form.
And no problem left.
Answer: Hook_forms is an answers. There is a second way :
In your form, add in the #name of the submit, the $product_id;
like :
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('submit'),
    '#name' => $product_id,
   );

Then, in the submit callaback, you'll find in the $form_state['triggering_element'], the product_id value.
So even if you use the same form in a foreach loop, you can know witch 'submit' have been triggered.
Comment: Actually, no. I tried this, but it didn't work because the `#form_id` were the same, so the first form was picked up.
Comment: What 'it didn't work' means ? are you able to get the product_id in the $form_state['riggering_element'] in the submit callback ?
Comment: Yes, but it's the product id of the first form.
Comment: Weird, I do it very frequently. post your code.
Comment: Well, I'll try that tomorrow. It's late in there, I'll keep you in touch if I have time :)


Programmatically querying via SearchApiAcquiaSearchService

Question: I am working on a site where querying using SearchApiSolrService is successful. However, when I deploy to Acquia Cloud and attempt to access the Acquia Search using the SearchApiAcquiaSearchService I get a 403 Forbidden.
Response
<code>SearchApiException: "403" Status: Forbidden: Forbidden in SearchApiSolrConnection->checkResponse() (line 544 of ...sites/all/modules/contrib/search_api_solr/includes/solr_connection.inc).
</code>
The subscription information is correct (via Acquia Agent). Here's a piece of the code:
Code Sample
<code>$server = search_api_server_load('my_acquia_solr_server');
$index = search_api_index_load('my_base_index');
$query = new SearchApiQuery($index);
$query = ... lots of random filters here that work for SearchApiSolrService calls so ignoring ...
$solr = new SearchApiAcquiaSearchService($server);
$result = $solr->search($query);
</code>
Thoughts?
Note: If you were to replace the SearchApiAcquiaSearchService with the regular SearchApiSolrService, the non-Acquia versions of the site integrate with Solr perfectly fine.
Comment: i've also asked this question on d.o here: https://www.drupal.org/node/2771891
Answer: The solution to this (also updated on the Drupal.org node commented above) is:
To skip this part:
<code>$solr = new SearchApiAcquiaSearchService($server);
$result = $solr->search($query);
</code>
And simply do:
<code>$result = $query->execute();
</code>


html agility pack wont return any ids even though the page has ids?

Question: Why wont this code return any ids in the generic list. The web page definitely has ids in the div elements.  If I break point it, there are no ids in the property Id in DocumentNode.SelectNodes and htmlDoc.DocumentNode.SelectNodes("//div[@id]") does not work.  I am using .NET 2.0 and HtmlAgilityPack.dll 22.214.171.124.
Imports HtmlAgilityPack

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim listHtmlFound As List(Of String) = New List(Of String)
        Dim webGet As HtmlWeb = New HtmlWeb
        Dim htmlDoc As HtmlDocument = webGet.Load("http://stackoverflow.com/q/11528387/1350308")
        htmlDoc.OptionUseIdAttribute = True
        'Dim s As Object = htmlDoc.DocumentNode.SelectNodes("//div/@id").Count
        For Each div As HtmlNode In htmlDoc.DocumentNode.SelectNodes("//div")
            listHtmlFound.Add(div.Id)
        Next
    End Sub
End Class

Comment: You need to be more specific.  Is the problem that `div.Id` returns null inside the loop?  Or is the problem that `SelectNodes` returns an empty list so it never enters the loop?
Comment: sorry about that - SelectNodes does not have any id values
Comment: So, `htmlDoc.DocumentNode.SelectNodes("//div/@id").Count` is zero?
Comment: I get a nulreferenceexeption error - any ideas -- thanks
Comment: What's null?  Is `htmlDoc` null?  Is `htmlDoc.DocumentNode` null?  Or does `htmlDoc.DocumentNode.SelectNodes("//div/@id")` return null?
Comment: hi - htmlDoc.DocumentNode.SelectNodes("//div/@id") returns null, and htmlDoc.DocumentNode.SelectNodes("//div") returns lots of divs but the id property for all of them is empty
Answer: Don't you need this:
 htmlDoc.DocumentNode.SelectNodes("//div[@id]")

to select all
 nodes having an id attribute, instead of all id attributes themselves?
EDIT
If the Id property of HtmlNode doesn't work, you could always use the Attributes property: loop through that to find one with Name = "id" and use it's Value.
Comment: The documentation notes: "The document must have been parsed using the OptionUseIdAttribute set to true. " for that Id property to be filled.
Comment: Nope it does not work - even if I break point and stop and inspect htmlDoc.DocumentNode, there is no value at the id property
Comment: @Hello-World - maybe you should now update the code in your question.


Probability at least one card is hit [Texas hold'em]

Question: The cards in hand = [9][9].
The question is as follows:
What is the probability we hit at least one 9 on the flop, turn or river (so, on the next 5 cards)?
There are (50, 5) = 2.118,760 board combinations and two outs [9][9] left.
P(at least one 9) means the following:
(i) P(hitting exactly one 9);
(ii) P(hitting exactly two 9's);

And combine those probabilities.
ad (i):
p(How many boards have exactly one 9)?
(49, 5) / (50, 5) = 0.9
1 - 0.9 = 10%
ad (ii):
p(How many boards have exactly two 9's)?
(48, 5) / (50, 5) = 0.8
1 - 0.8 = 0.19%

Combining the probabilities
p(one 9) + p(exactly two 9's) * 1 - p(one 9)
= .10 + .19 * (.10)
= .119%

So the probability of hitting at least one 9 is 11.9%. Is this correct?
Comment: There is something wrong in your calculation, indeed the number of boards with exactly one 9 is $2\binom{48}{4}$ (for each 9 we can choose 4 cards among 48) and the number of boards with exactly two 9 is $\binom{48}{3}$.
Comment: Note that 11.9% is almost the probability to set at the flop $$1-\frac{48*47*46}{50*49*48}$$
Answer: With a pair of 9 in hands, the probability that a 9 not occurs on the flop, turn and river, assuming that we only know these two cards in hands, is given by
$$\frac{48}{50}\frac{47}{49}\frac{46}{48}\frac{45}{47}\frac{44}{46}$$
thus the probability that we hit at least one 9 on the flop, turn or river is
$$1-\frac{48}{50}\frac{47}{49}\frac{46}{48}\frac{45}{47}\frac{44}{46}\approx 19.2 \%$$
With a direct calculation we have that

the number of boards with one 9 is given by $2\binom{48}{4}$
the number of boards with two 9 is given by $\binom{48}{3}$

thus the probability that we hit at least one 9 on the flop, turn or river is
$$\frac{2\binom{48}{4}+\binom{48}{3}}{\binom{50}{5}}\approx 19.2 \%$$
Comment: Can your equation be reframed as 1-((48, 5)/(50, 5)) as it gives ≈ 19.18
Comment: @Bondeaux yes of course since (48,5)/(50,5) is the probability of boards without 9!
Comment: Btw, if you don't mind having a go at another problem. What should be the probability of hitting trips on a board of 5? So let's say we have in hand [K][9], what is then the chance at least two [9][9] comes on a board? Is it (48, 3)/(50, 5)?
Comment: @Bondeaux you can use a similar method to the direct method here presented, let formulate a new OP, I will answer to it!
Comment: I will, hold on please ;')!


In triple exponential smoothing, what is the proper formula for recalculating gamma (seasonality)?

Question: A pretty targeted but precise question --
In triple exponential smoothing (which there are many combinations of additive, multiplicative).
What is the proper formula for calculating the new seasonality for each observation?
I've seen two different formulas online:
$s_{t}=\gamma\left(\frac{y_{t}}{\ell_{t-1}+b_{t-1}}\right)+\left(1-\gamma\right)\left(s_{t-m}\right)
 $
[above is assuming additive trend, it would multiply the previous trend otherwise)
or
$s_{t}=\gamma\left(\frac{y_{t}}{\ell_{t-1}}\right)+\left(1-\gamma\right)\left(s_{t-m}\right)
 $
Aka in the first function, the previous trend is used in the calculation of the new seasonal factor, whereas in the second, it is omitted.
Which is correct? Thanks.
Answer: The first one should be used if there is trend. The second one assumes there is no trend. An alternative that can be used whether or not there is trend is
$$
s_t = \gamma\left(\frac{y_t}{\ell_t}\right) + (1-\gamma) (s_{t-m}).
$$
where $\ell_t$ is the level component, $s_t$ is the seasonal component and $m$ is the period of seasonality.
Comment: Thanks Rob. That makes sense --- not sure which one to use in that case --- but my models have a very low gamma parameter anyway, so there's not much difference either way. I just thought I was going crazy.


Uses of integral calculus in discrete mathematics?

Question: I have to do a project in my integral calculus class. But all the topics are too mainstream (parabolic arc calculation,archimedean approzimation of circle are,obtaining $E=mc^2\dots$
However I'm really into discrete maths right now and I would like to use integral calculus for my project in discrete mathematics?
Is this viable? What are some topics I could persue?(Things I am really into right now are combinatorial identities, graph theory,abstract algebra and category theory).
Thank you very much in advance, forgive me if this question is innapropriate.
Best Wishes.
Comment: If you cook up a function with the correct residues at the integers, you can use Cauchy's residue theorem to compute infinite sums. For example $(\pi \cot \pi z) / z^2$ has has residue $- \pi^2 / 3$ at the origin and residues $1/n^2$ at $\pm n$, so considering the square $\pm (n + 1/2) \pm \mathrm{i}(n + 1/2)$ you get $\sum_{n \ge 1} 1/n^2 = \pi^2 / 6$
Comment: You can often approximate the number of lattice points in a region by calculating the volume of the region. A famous example of this as in "Gauss' circle problem" http://en.wikipedia.org/wiki/Gauss_circle_problem . It seems to me that many combinatorial problems can be reduced to computing lattice points which in turn can be approximated into volumes (which is mentioned above). Also see http://math.sfsu.edu/beck/papers/noprint.pdf . Also, The theory of integer partitions uses some heavy duty analysis see: http://en.wikipedia.org/wiki/Partition_(number_theory)
Answer: Try with Discrete Fourier Transform . The term Fourier Transform , used in Applied Sciences and Engineering , is actually Fourier Integral .


Connected graphs, Euler circuits and paths, vertices of odd degree

Question: I already have the solved the following questions. Just need to confirm my answers.
Question 1: Prove that a connected graph G with at least two vertices is connected has an Euler circuit if and only every vertex of G has even degree.
My Solution: Let G have vertices of all even degree. (Degree $ = 2x$). Now we can travel multiple times to and away from any vertex. And as the number is even we can always use the last edge to travel to a new edge hence getting to every vertex.
Let G contain a Euler Circuit. For G to contain a Euler Circuit one needs to travel on every edge ending back at the first vertex. Let G contain a vertex with an odd degree. (Degree $= 2x + 1$). Now one can travel to and fro from that vertex but ultimately one would be trapped on that vertex / or if one starts at that vertex one won't be able to reach that vertex hence a vertex can't have a odd degree. (Contradiction). Hence all the vertices have an even degree.
Question 2: Prove that a connected graph has an Euler path if and only if it has exactly two vertices of odd degree.
My Solution: Using the first question if a Graph has vertices with even degree the Graph contains a Euler Circuit. Let G contain a Euler path. Now a graph contains a Euler path if it can travel each vertex but does not end up on the same vertex. Hence there is an additional edge (That makes two vertices have an odd degree).
Let G have two vertices that have odd degree and the rest have even degree.
Case I: If we start from an even degree vertex we will be trapped on a vertex on the odd degree vertex as ultimately we will have an edge to travel to the vertex but no edge to travel away from it.
Case II: If we start from the odd degree vertex we can travel on every edge and use the last edge of the first vertex to travel away from that vertex to the other vertex with the odd degree hence completing the Euler path.
Comment: Your reasoning is correct, but is not rigorous enough to constitute a proof. For example proposition from the first question does not work for disconnected graphs, but you don't use the assumption that the graph is connected. I know where you would like to use it, but it's not there and that's my point.
Comment: But the question already states that the graph is connected. So should we use that assumption.
Comment: You ought to give a reason why you will be able to visit every vertex of the graph. Indeed you should use the fact that the graph is connected, but that's not all. For example, let's assume that we could split $V$ into three disjoint parts $V=A\uplus B\uplus C$, so that any path between $A$ and $C$ goes through $B$. How do you know that you won't finish $B$ before $A$ and $C$, and then you won't be able to reach $C$ from $A$? It won't happen - the theorem is true - but you have to argue it can't happen (i.e. that all the vertices will be reached).
Comment: Can you actually help me with the solutions then. :)
Comment: I can, but not today. Perhaps tomorrow, certainly on Monday.
Answer: TheHint for question 1:

$(\text{Euler circuit} \Rightarrow \text{ even degrees})$ Direct the circuit, prove that for any vertex we have the in-degree equal to the out-degree, hence their sum must be even.
$(\text{Euler circuit} \Leftarrow \text{even degrees})$ One of many possible ways is to use induction on the number of edges.

Find any cycle $C$.
If it is an Euler circuit, you are done.
If it is not, remove it from the graph (the remaining part has fever edges and still even degrees).
Process each connected component separately to obtain an Euler circuit for it (we can because of inductive hypothesis).
Merge the circuits using cycle $C$.

Hint for question 2:

If you have two vertices of odd degrees, you can add a new vertex which is adjacent to both of them.
If you have an Euler path, you can add a new vertex and make it an Euler cycle.

I hope this helps $\ddot\smile$
Comment: For Q2, we can also **add a new edge $e$** connecting the vertices $v,w$ with odd degrees, so all vertices become even degree. Based on Q1, this forms a Eular Circuit, and with newly-added $e$ removed, this forms a Eular Path.


Does Drupal have some kind of Structure system?

Question: I looked all over but no result ...
I wonder if there is a Structure System for Drupal like: Spaces - Sections - Groups - Blocks - etc.
Where to use Spaces and may I have groups in spaces? The documentation is somehow messy, I'm lost. But there seems to be no good guides (like books) for a Drupal beginner.
Edit:
It takes time to find out what I need, where to install, etc.
Drupal 7 with Open Atrium 2 should be used for a Information an collaboration suite for a company. Login and all user-information and its roles comes over LDAP and active directory. So far I haven't got any problems.
But now I would like to build a user page:

I take a layout with two cols.
In the right column I have all the information read from active directory and user information.
In the left column there should be some different things.

But I would be very happy if I could understand how to build a user page with all the logged in user information automatically where user will be redirected after logged in.
I don't know how the hierarchy in Drupal works:

Do I need a space for all user who are logged in in Drupal?
And do I have groups inside a space or can I have groups without a space?

Edit:
So please don't mind if I give you this advice:
Not to explain all this modules and for what they are all for but to give specific projects and go through this from the first plane and road-map over the modules which we need till the building and setup.
So we can see it quit from the other side. Starting from a project going through drupal. And not from Drupal and for what it could be all for.
In my case I should build a company platform for all employees with there personal date from active directory (LDAP) and build up a personal page for each employee with his personal data with Drupal.
Comment: Your question is too vague. Simple concepts in Drupal are `Nodes` and `Users`. Orchestrating large websites with dynamic sections and complex business takes time to learn how to integrate various drupal modules to meet your needs. Please rephrase your question with an exact scenario you want to achieve, eg "Users should be apart of a group and content posted only to 1 group" ...
Comment: Michael, I tried to "enhance" your question by integrating your own "answer" you added to it also. Please review my attempt to enhance your question (and correct where appropriate). Pretty sure that your "answer" (which in not what is considered an "answer" on Drupal.SE ...) will soon be removed by moderators. Just trying to get you going on Drupal.SE, OK?
Comment: Welcome to Drupal Answers :) From your recent edit it's clear you're looking for a full tutorial on how to build your site - which we don't do here. As a Q+A site were building a repository of narrowly scoped knowledge, questions need to be clear and focused on a single, objectively answerable goal. Try breaking your task down into its smallest parts, and attack each individually. Then when you have a specific question about a specific part of your development, this is the place to ask. Many thanks
Answer: If you're new to Drupal, you might have a hard time getting your head around the (amazing) Panels module, and things like "context", etc. But it sounds that's part of what you're looking for. Watch the videos about Learn Page manager for more details. After you reviewed these videos, you should understand various features that come with the Panels module ... but also its challenges.
As an alternative, you may want to give it a try to see how far you can get with any (or all?) of these modules:

Display Suite (a typical alternative for using Panels).
DataTables used in combination with Views (especially because of its client side search facilities).
You might want to check also to what extend the features provided by Organic Groups module might help in your case.

Fairly sure that at some point you should also look at the Rules and Flag module.
Video tutorials

For anybody not familiar (enough/yet) with Rules, checkout the 32 (!!!) great (+ free) video tutorials Learn the Rules framework, organized in 7 chapters.
Possibly also the similar set of 8 video tutorials about the Flag module, often considered as a natural complement to the Rules module.
The amazing set of videos to Learn Organic Groups might help to better understand what Organic Groups is all about.
While you're there, why not also review the set of 30 video tutorials about the Views module.
Comment: Thanx a lot for your kindly advise.
Rules, OGs, Flags, I even don't know whether I need this or not... ;-(


Let $F_g: F(X) \to F(X)$ be a linear map such that $f \mapsto gf$. Compute the determinant of $F_g.$

Question:
Let $X =\{a,b,c\}$ and let $g : X \to \mathbb{R}$ be a function for which $g(a)=2,g(b)=4,g(c)=-1.$ Let $F_g: F(X) \to F(X)$ be a linear map such that $f \mapsto gf$ where $F(X)$ is the set of all functions $f:X \to \mathbb{R}$. Compute the determinant of $F_g.$

I have a slight problem when trying to express $F_g$ as a matrix. If I understood the problem correctly I have that $$F_g(f(a))= g(a)f(a) =2f(a) \\ F_g(f(b)) =g(b)f(b) = 4f(b) \\F_g(f(c)) =g(c)f(c) = -f(c)$$ but I would need to express this as a matrix in order to find the determinant. The fact that every linear transformation can be expressed as a matrix should apply here as well since $F_g$ is a linear map. How can I proceed with this?
Comment: As a technical point, you should have, e.g., $F_g(f)(a) = (gf)(a) = g(a)f(a)$, not $F_g(f(a))$ (which makes no sense, as the domain of $F_g$ isn't $\mathbb{R}$).
Answer: Assuming that $F(x)$ is the set of all maps from $X$ to $\Bbb R$, then a basis of $F(x)$  will be $B=\{e_a,e_b,e_c\}$, where $e_x(y)$ (with $x,y,\in\{a,b,c\}$) is $1$ if $x=y$ and $0$ otherwise. Now, $F_g(e_a)=g\times e_a=2e_a$. You also have $F_g(e_b)=4e_b$ and $F_g(e_c)=-e_c$. So, the matrix of $F_g$ with respect to $B$ is$$\begin{bmatrix}2&0&0\\0&4&0\\0&0&-1\end{bmatrix}.$$
Comment: I'm having a bit of trouble understanding where do the zeros come from for example for the first row or column?
Comment: From the fact that $F_g(e_a)=2e_2+0\times e_b+0\times e_c$.


Writing music by hand?

Question: How do you write music by hand -- without using a ruler -- and not make it look like ugly chickenscratch?
Are there exercises for writing note heads, stems and beams while making them look relatively consistent and nice but still relatively quickly?
I know music composition and engraving is often done using software nowadays. But for the purposes of quickly jotting down ideas and then quickly scanning through them to find things, I think paper is still very useful, portable, and doesn't require batteries. So what steps can I take to improve my music handwriting?
Comment: The answer to all questions is practice, practice, practice
Comment: are you writing the staff lines too, or using staff paper?
Comment: For drawing the score lines special pens exists as [this](https://www.noligraph.de/). I also saw a kind of rolling rubber stamp for the same purpose but could not find it right now. (But I don't assume it does contribute much to overall speed, since getting the right paper/booklets is also easy...)
Comment: What's the purpose and audience for your writing? When you're just trying to capture a melody before it leaves your head, chicken scratch might be more than good enough. If you're trying to write the final draft of some long finished piece so you can hand it off to other musicians, that's a different story.
Comment: Can you read your own musical handwriting? Who else is going to read it? If the answers are "yes" and "hardly anyone" I don't really think improving your handwriting is the best use of your time. If the answers to my questions are different, I'd say that is an important piece of information you might like to add to your post.
Comment: @infinitezero - certainly not *all* questions! But definitely 'How do I get to Carnegie Hall please?'
Comment: Sorry for the confusion. I meant using existing staff lines. I wouldn't try to draw those without a ruler with an expectation that it would look nice.
Comment: conscious learning through practice might be the fastest process
Answer: I think this is tricky, because it's a skill between two separate skills handwriting (letters) and drawing.
I have pretty bad hand writing, but I studied art in college and could draw pretty well.
Drawing straight lines is actually difficult!
Two things that might help:
If you hunch over to get your eyes close to the paper, move back so you see more of the full page in your center of vision. If you see more of the page edge, it can help to get your lines straight.
When drawing lines try using you elbow and shoulder more rather than your fingers and wrist. That should give you less curving motion and therefore straighter lines.
For consistency don't just write from left to right. Sketch proportially across the whole page. I try to first make equally spaced bars. First mark a bar in the middle then start adding bars splitting into quarters, etc...

Mark the first note head with just a light dash. I think getting the first beat placed consistently is more important that whether the last note head has more or less space at the end of the bar. After the first beats are set then add the other noteheads as light dashes...

After you have lightly marked noteheads, you might make quick adjustments for anything that's badly aligned. Then draw stems. Sometimes I have drawn stems from the note head so I don't have to worry about getting the line connected to the head...

When the light sketch looks good finally fill in the note heads - or just bold ovals for half and whole notes, cross the stems with beams, etc. If the note heads are a little smaller that a staff space, it should help make clear when it is on a line or space (note heads on spaces won't be touching lines.)

Basically the idea is mark out important spacing points across the page first then make the bold marks over those guide lines. I think if the spacing is consistent and proportional, then the final result is easier to read.
Answer: The answer (as others have said here) is to practise. Remember when you first went to school and you had to copy out letter shapes over and over again? You need to do the same thing with note shapes.
Do these repetition exercises by downloading blank manuscript paper from the web or buying pre-printed manuscript paper.
Use a mechanical pencil with a soft lead, because the stroke from a regular wooden pencil changes width as  the lead wears down. And pencil is correctable too.
Noteheads should be centred on a line or a space and be a slightly tilted oval, not a circle. So there's two things to practise straight away - drawing centred notes and making the noteheads a consistent size and shape. The size of the notehead should be such that if you were to draw it in a space it would just touch (not overlap at all) the lines above and below it.
Another thing to consider is which side of the notehead the stick emerges from. Upward sticks touch the right-hand side of the notehead, downward sticks touch the left-hand side. And sticks are generally an octave long. Make sure all sticks are at 90 degrees to the lines in the stave.
To make note beams look engraved (say when you join the tails of two or four eighth notes) do two lines close enough to touch, making a thicker line. Use a ruler, otherwise your doubled lines will vary in thickness!
This same technique of drawing two lines close together to make a thicker line is part of my answer elsewhere about drawing a quarter note rest by hand: https://music.stackexchange.com/a/38920/9426
You'll also need to practise note tails, for single eighth and sixteenth notes. And single eighth and sixteenth rests too. Check some existing printed music to see which lines of the stave to centre your rests on. They shouldn't move around unless you're notating several voices on one stave and the default rest position would clash with a notehead.
Also have a look at the horizontal spacing of notes within bars. For instance a whole note doesn't appear midway between the two barlines; it's always written closer to the left-hand barline.
Comment: Thanks for your thoughts.  I would just note that the traditional method to create those wide note beams, quarter rests, etc. was to use a fountain pen (or, more traditionally, a pen with a separate ink bottle) with an appropriate wide (sort of italic style) nib.  If you're not skilled with traditional pens, this probably isn't something for a beginner, but it's actually the way to create that standard "look" in a traditional manner.
Answer: By doing more of it! However, it didn't seem to help the likes of Ludwig or young Wolfgang Amadeus.
I do a lot by hand, and find it's slightly better using  wider manuscript lines. A ruler is used for bar lines, which helps keep the stems vertical.
But, thinking about most letter/word writing exercises, all they do is give the opportunity to practise over and over, which you might as well do while you're writing dots out!
Having the right sort of pen helps too - I use a medium felt tip. Or pencil, which is normally 3B or 4B. That makes changes easier too.
Answer: (I can tell you I was always punished as pupil by my teachers because of my horrible writing!) But drawing note lines is my special ability :)
Most abilities can be achieved by training and practice. But there are some hints and advice I can share. I compose today with notation software but when I am watching TV or sitting in the train or in a car I love to write music on any sheet or on a newspaper.

If you have good practice it will be very easy even to draw the note lines (staffs) in beautiful parallels.
The black notes you shouldn't draw as dots but rather as short    slashes / (bold)
the white notes you can draw as O or 0 ovals (italic) in the same diagonal inclined direction as the black notes  () -> (/)
Mind that the stems and bars are absolutely vertically and the sharps and flats have to be crossed by the referring line or are placed nicely between the lines.
The clefs and rests are also becoming readable and usual by more practice.

I would have become a great composer if my band members would have been able to read my writing about 60 years ago. But I have to agree it was difficult to recognize whether a sign was a flag of an 8th note or a rest or eventually a flat!
Of course I also use booklets (one page staffs and the other site squared) and any sheet with note lines or print my own prepared staffs which you can write with the  _ _ _ key for under-lining: ->

sometimes I also  notate only

the chord symbols or the Latin letters or
the doremi as words and the
Roman Numbers for the degrees.
I also write sometimes just the Arabic numbers like 1 2 3 4, 5 5 5
_, 5 4 3 2, 1 1 1 _

Here you will find lots of
Blank Manuscript/Staff/Music Paper
https://www.dolmetsch.com/manuscriptpaper.htm
Comment: Latin letters..?
Comment: a,b,c,d,e,e,e_,d,d,d_,e,e,e_
Answer: You don't need to draw stave lines. You can buy notebooks or notepads of manuscript paper, that is, sheets printed with staves. I like to print my own as and when needed -- the advantage of this is that I can tailor the number of staves per page to what the music needs, and the line-spacing to my eyesight (which is gradually getting worse over the years).
Comment: There are plenty of manuscript pages for downloading on the 'net. I print off, and sometimes change the % size.
Answer: I truly wonder what do you mean by ugly. Check any page with "sheet music handwriting", I found e.g. https://www.classicfm.com/discover-music/latest/composer-manuscript-handwriting/mozarts-sketchbook/ and try to see how many of these actually look neat, precise or anything? IMHO, almost none.
The goal is: develop your style. Try to see some ideas about how others handwrite, simply by looking and handwritten sheet music. I can only give my own insight:

Use printed empty sheets. This helps a lot. Start immediatelly with the standard size; if you start with larger print, you'll have to re-learn writing in smaller print.
Write noteheads+dots first, then stems, then beams, then barlines.
For multi-staff music (keyboard instruments, choirs, ensembles), write the barline across all staves, even if inappropriate in printed music. The same for the opening bracket; this helps in keeping the sheet well organized.
Use pencil with a good rubber on the other end, so that if you don't like something you wrote (either the music or the handwriting), you can easily erase. Like these:

Keep your pencil well sharpened.
Use the pencil slanted; this allow to write narrow lines for lines, and wide lines for noteheads and beams (I actually make just thick short lines for black noteheads).
Develop a good syle for rests and accidentals (as these are pretty important), but do not care much about the clefs, key (unless you use exotic keys) and other irrelevant stuff (irrelevant for easy reading I mean).
Develop your own handwriting style; do not care too much about how any "official" music looks like.
Try to play your own sheets; only that way you can know how reasonable your handwriting is, but:
Do not overthink it; once the piece is finished, you're probably gonna retype it on the computer anyway.

(Bottom line: I remember the music theory teacher bullying us over "proper" handwriting. When I got to composing myself some 10 years later, I realized how useless this was!)
Answer: As a supplement to Michael Curtis' excellent answer (with some differences), I recall that I read a book about this many years ago. But I lent it to someone, forgot to whom, and subsequently forgot the title. But there was some practical advice that I strain to remember.
On a philosophical level, it's important to accept that for writing quickly some visual sacrifices are necessary. It's not going to look like a fancy engraved score. But this is also liberating because it doesn't have to look like engraving so long as it's clear and consistent.
The primary suggestion from the book was to make the note head and stem as one combined gesture. This helps to ensure that the stems are all uniform in length and angle. There's some indication that classical composers like Mozart and Chopin did this, considering their tendency to draw curved beams.
Next, the book advised that for non-beamed notes a flag should be a short line segment rather than a curve. Making the curve consistently would be much more difficult. Also, the first flag should be part of the same single motion as the note head and stem.
Next, all stems should be on the right. That is, notes should have a 'd' or 'q' shape, rather than the 'd' and 'p' shapes which are more normal in engraving. This facilitates a more consistent left to right motion for all notes.
Next -- I'm not sure whether this was in the book or I got it from elsewhere, but it feels consistent with the other ideas -- the French-style quarter rest, which is the reverse of the standard eighth rest, is much easier to execute and is preferred.
Answer: I'll add to others here.  Practice a lot.  Plan out your measure spacing and draw barlines before notes.noyes.  It works well enough to use a pencil, but I have found that...

Using a mechanical pencil keeps line thickness consistent and you don't have to sharpen them.

Staedler makes a set of four, with sizes  0.3, 0.5, 0.7, and 0.9mm that has served me well for many years.  Their marking pens work well also, they have sets of different widths which come in handy.

for pencil lead, you should by something  fairly soft so it's easy to make dark lines.  Don't waste your time with the standard 2hb.  Look around online for 2B instead.

a small ruler, 4 to 6 inches, is handy for straight lines. If you can find a transparent one it's much easier to align things!

Writing music by hand?