What is the scale of A # Minor / B flat minor? What does it look like in tab?

Question: What is the  Guitar chord - lead  scale  of   A#  Minor /  B flat minor? I'd like to see what this scale looks like in tablature.
How do I play it?
Comment: If you know what the notes are for A minor, merely sharpen each of them. If you know the scale of B minor, flatten each of them!
Comment: @Tim im not getting   im newly  learning guitar
Comment: Can you clarify what it is you want to know? Your question doesn't make a lot of sense. What do you mean by "lead scale"? A scale to play lead guitar with? A sharp minor and B flat minor *are* scales. And many chords can be built with them, not just one.
Comment: @trw im talking about  lead scale
Comment: i mean  tab  @trw..
Comment: You want to see what the A sharp/B flat minor scale looks like in tab?
Comment: yes    yes  exactly @trw
Comment: Why do you need this? It's not something a beginner usually has to play in - A#/Bbm. Even with editing, your question isn't clear.
Comment: May I ask - with full  respect: What sense does it make to ask for the a#- (b-) minor scale pattern before learning a-minor tab? would agree with The comment of Tim to transpose up the a- minor scale (or the b-minor down).

Then I thought there would be a problem with open strings in the first "position". But there are other bends to start with, e.g. the 5th.

I think it would be better to understand the tuning system of a guitar and the pattern of any major scale in general.
Comment: This question is currently discussed on [meta](https://music.meta.stackexchange.com/questions/3274/what-sense-does-it-make-to-ask-for-the-a-b-minor-scale-pattern-before-learn).
Answer: Bbm chord

x13321

Bb minor pentatonic scale
You mention playing "lead". The most common "lead" scale in rock and blues is the minor pentatonic scale. A pentatonic scale is a scale with 5 tones. You can play other scales over a minor chord, but minor pentatonic is probably the place moost rock/blues players will start.
This one chord form and one scale isn't the full story about playing in Bb minor. It's just the basic starting point. When you get comfortable with it, you can try branching out to other chord voicings and other scales.

  1 2 3 4

E-5-----7-
B---3---4-
G-7---1---
D-4---5---
A-1-----3-
E-5-----7-

Generally, you should refer to Bb minor instead of A# minor. It's a technical issue about 5 flats in Bb minor rather than 7 sharps in A#. It's a lot easier to read notation and handle common chord changes for Bb minor.
Comment: Just for other people's education, A pentatonic scale is **not** the same as the full natural, melodic, or harmonic minor scales.
Comment: @jasmine, I added a note about the scale.
Comment: Do you find it a little odd that a beginner is already at A#/Bb in their playing?
Comment: Seemed a bit odd. I figured it was for a song they heard.
Comment: what is  meaning  of  pentatonic ?
Comment: thanks u  @MichaelCurtis   let  me  try  in guitar
Comment: Sorry Michael, but that diagram is a bit confusing. You're using natural minor scale degrees to show pentatonic note positions? I've never seen that before! If that's the case, the 2 doesn't belong and you're missing a 4. (Both on the B string.)
Comment: @trw, thanks, I corrected the B string. Otherwise I put the scale degrees `1 b3 4 5 b7` on the strings. You can think of that as natural minor - and pentatonic as a gapped scale - or you can think of those numbers as the intervals above the tonic.
Comment: I've seen all kinds of labels on the strings. Identifying scale root and degrees or intervals is fairly common.
Comment: +1 It made sense after I studied it for a moment. It couldn't be finger numbers. :)
Comment: @jasmine, I can add an explanation if you don't know how to read those tab diagrams, let me know
Answer: There are many ways to play the B♭ minor scale on the guitar. Assuming you want the natural minor scale, this is one example of how to play it, shown in standard tablature:
——————————————————————————————-6-8-9-
————————————————————————-6-7-9——————-
————————————————————-6-8————————————-
—————————————-6-8-10—————————————————
———————-6-8-9———————————————————————-
—-6-8-9——————————————————————————————

If you want to end with B♭, don't play the last two notes.
Note that there are other minor scales besides natural minor.
A♯ and B♭ are enharmonic notes, keys, and chords, so you would play them the exact same way. B♭ is by far more common because it's more practical in standard notation.
It would be beneficial if you learned the shape of the scales on the guitar. You could then play that scale with any tonic note by shifting it up and down the fretboard.
The diagram below shows the spacing between the notes of the major and natural minor scales. (The "blue" notes, which are not part of those scales but often used in blues and rock music, are shown in blue.) The red notes are major roots. The green are minor roots. The yellow are other pentatonic notes. The gray are other additional diatonic notes. There are no fret numbers because this diagram can be seated at any fretboard position.
Answer: I suggest you learn what spacing is between the notes on a minor scale.  3 minor types are natural, harmonic, and melodic. These are available online many times over. Half steps are single frets two frets are whole steps. Sound them out. Ride up one string to find the pitches and compare that with convenient fingerings in one position. Theres nothing like self discovery. I will tell you the natural minor is down 1 and a half steps from the relative major using same notes.


Fitting a 2D transform to a set of points

Question: I'm digitising some hand-drawn maps.  My method is to scan the map, import it into an SVG editor and trace over the features.  I then mark some datum points on the SVG, with metadata to indicate that they are datum points.  Then I find those same datum points on Google Maps to get their location in decimal lat/long and add those values to the metadata.  Note that the hand-drawn map is not necessarily oriented so that the Y axis points North.
So now I have two lists of vectors: $A$ is an 2xN matrix with the datum coordinates in SVG coordinates as $(x, y)$ and $B$ is a 2xN matrix with the datum coordinates as $(lng, lat)$.
I now want to find a rotation, scale and translation that will map coordinates from one space to the other, so that I can then transform the actual features on the map to lat/long.
I found this method which uses SVD to obtain a rotation and translation matrix, but I'm not sure how well the SVD step will work when there is a scale involved as well.  To summarise the method:

Let $A_c$ and $B_c$ be the centroids of $A$ and $B$ (ie the arithmetic mean along each column).
Calculate the covariance matrix $H=(A-A_c)(B-B_c)^T$.
Do the SVD -- $U, S, V = SVD(H)$.
The rotation matrix is then $R = VU^T$.
The translation is $t=B-RA$

Can I then just calculate the scale as the mean along each column $S = \overline{B_c / (RA_c)}$ (where / is element-wise division)?  And then re-evaluate the translation as $t=B-diag(S)(RA)$?  Or does the scale need to be taken into account in the SVD somehow?
Answer: The same website that you linked has an article that explains the inner workings of OpenCV's estimateRigidTransform function. I believe that's what you are looking for to compute the scale.
http://nghiaho.com/?p=2208
Assuming uniform scale (no shear), solve for [a, b, c, d] using 2 points:
$$\begin{bmatrix} x_1 & -y_1 & 1 & 0 \\ y_1 & x_1 & 0 & 1 \\ x_2 & -y_2 & 1 & 0 \\ y_2 & x_2 & 0 & 1 \end{bmatrix} \begin{bmatrix} a \\ b \\ c \\ d \end{bmatrix} = \begin{bmatrix} x'_1 \\ y'_1 \\ x'_2 \\ y'_2 \end{bmatrix}$$
Where:
$$a = \cos(\theta)s$$
$$b = \sin(\theta)s$$
$$c = tx$$
$$d = ty$$
If you have 3 or more points, a simple least square solution can be obtained by doing a pseudo-inverse:
$$\begin{matrix} Ax & = & b \\ A{^T}Ax & = & A^{T}b \\x & =& (A{^T}A)^{-1}A{^T}b \end{matrix}$$


UIPageViewController Atualizar Conteudo e Bounce

Question: Possua uma Página em meu aplicativo que trabalha com UIPageViewController, nela eu implemento o UIPageViewControllerDataSource. Assim eu possuo uma lista de itens que são listados em varias views, o problema é que quando eu atualizo esta lista, os itens funcionam perfeitamente, consigo navegar em todos os itens, inclusive os novos. O problema é que o Bounce (bolinhas de baixo) ficam o valor antigo, ou seja, se possuía 5 paginas antes e agora 6 continua 5 bolinhas. Não achei na documentação nenhum comando que atualize essa informação. Segue abaixo parte da minha class que trata do UIPageViewControllerDataSource.
func loadPageView() {
    self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController;
    self.pageViewController.dataSource = self;
    self.pageViewController.delegate = self;

    let startVc = self.viewControllerAtIndex(0) as ContentViewController;
    let viewsControllers : [ContentViewController] = [startVc];

    self.pageViewController.setViewControllers(viewsControllers, direction: .Forward, animated: true, completion: nil);

    self.pageViewController.view.frame = CGRectMake(0, 30, self.view.frame.width , self.view.frame.size.height - 70);
    self.addChildViewController(self.pageViewController);
    self.view.addSubview(self.pageViewController.view);
    self.pageViewController.didMoveToParentViewController(self);
}

func viewControllerAtIndex(index: Int) -> ContentViewController {
    if((ExercicioDataSource.listaExercicios.count == 0) || (index >= ExercicioDataSource.listaExercicios.count)){
        return ContentViewController();
    }

    let vc : ContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ContentViewController") as! ContentViewController;
    vc.dataContent = ExercicioDataSource.listaExercicios[index];
    vc.index = index;

    return vc;
}

// UI Page View Data Source

func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
    let vc = viewController as! ContentViewController;
    var index = vc.index as Int;

    if(index == 0 || index == NSNotFound){
        return nil;
    }

    index -= 1;
    return self.viewControllerAtIndex(index);
}

func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
    let vc = viewController as! ContentViewController;
    var index = vc.index as Int;
    if(index == NSNotFound){
        return nil;
    }

    index += 1;

    if(index == ExercicioDataSource.listaExercicios.count){
        return nil;
    }
    return self.viewControllerAtIndex(index);
}

func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
    return ExercicioDataSource.listaExercicios.count;
}

func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
    return 0;
}

Answer: Olá! Provavelmente ele não está recebendo dados automaticamente do page view controller através do delegate; portanto, sempre que adiciona uma página nova, ele não detecta as mudanças. Uma pergunta: se você deletar um VC, ele continua constando como 5 ao invés de atualizar para 4 bolinhas? Poderia postar o código inteiro incluindo viewDidLoad e variáveis definidas? De qualquer forma, tente esse método:
Antes de tudo, faça o outlet do Page Control (bolinhas) no código.
@IBOutlet weak var pageControl: UIPageControl!

Agora...

No PageViewController:

Defina o protocolo:
protocol PageViewControllerDelegate: class {

    //chamado quando o número de páginas for atualizado:
    func pageViewController(pageViewController: UIPageViewController,
        didUpdatePageCount count: Int)

    //chamado quando o index for atualizado
    func pageViewController(pageViewController: UIPageViewController,
        didUpdatePageIndex index: Int)

}

Defina uma variável conforme o novo delegate PageViewController:
weak var pageDelegate: PageViewControllerDelegate?

Adicione no viewDidLoad():
pageDelegate?.pageViewController(self,
            didUpdatePageCount: ExercicioDataSource.listaExercicios.count)

No ContentViewController:

Adicione a extensão:
extension ContentViewController: TutorialPageViewControllerDelegate {

func pageViewController(pageViewController: UIPageViewController,
    didUpdatePageCount count: Int) {
        pageControl.numberOfPages = count
    }

    func tutorialPageViewController(tutorialPageViewController: TutorialPageViewController,
        didUpdatePageIndex index: Int) {
         index = vc.index
    }

}


Como usar o Vagrant ou o Packer em ambiente de produção?

Question: Estou começando a estudar o Vagrant junto ao Chef e já percebi que ele é ótimo para ambiente de desenvolvimento, facilitando muito a vida quando se é bem configurado, porém ele não monta um ambiente seguro o suficiente para ser reproduzido em produção, pelo menos eu não encontrei formas de deixa-lo seguro em produção ainda. O que quero saber é se é possível e o q devo fazer para manter 100% de semelhança entre meus ambientes de desenvolvimento, teste e produção e ainda desfrutar das facilidades do Vagrant e Chef?
Comment: Acredito que você tenha que configurar o box para deixa-lo igual a produção, dai o box vc configura como linux mesmo, no arquivo Vagrantfile não sei se vai dar pra colocar todas config. Mas seja mais especifico com o que você quer fazer.
Comment: é que no meu servidor de produção eu usao senha no linux e no mysql, e dou as permissoes necessarias. No caso da senha do linux eu posso troca-la por ssh. No vagrant daria pra eu associar minha chave ssh? pq o vagrant cria uma pasta compartilhada com o hospedeiro e é ae que esta a falha de segurança que impede o uso em produção. Estou correto em afirmar isso?
Comment: Tava pensando aqui, qual é o proposito exato de usar Vagrant na produção? Voces montam muitos servidores por dia?
Comment: nao, sao poucos, o vagrant em producao serviria para duas coisas creio eu. 1 - manter a igualdade do server de desenvovimento, testes e producao e manter a evolucao destes servidores sempre alinha. tudo isso ao alcance de um vagrant up
Comment: Eu não consegui ficar satisfeito com o Vagrant para produção. Hoje eu uso vbox, a mesma imagem, faço deploy no servidor local e produção. Faço isso a anos e sinceramente, não mudaria isso por nada.
Comment: vbox seria o virtual box? Se eu entendi bem vc cria uma VM no virtual box na mão mesmo e depois a usa tanto em dev como em prod?
Answer: Sinceramente, eu acho que o uso do vagrant e mais para homomlogação, tendo em vista a questão da segurança, organização  (particionamento de disco) da so, hardering  e o uso da virtualização (bare metal) como o provider do virtualbox. Eu como sysadmin, uso mais para gerar um simulação do cenário de produção, rodando via vagrant  3-6 vms com diferentes sistemas operacionais como está em produção, de acordo com o projeto. Aí posso alterar algum quesito, seja na interconexão, ou versões e etc, que sei que vai roda em produção, e para fazer o deploy de fato em produção, uso o docker. Assim, na so em homologação pelo vagrant, usamos o docker que isola somente a aplicação ( o filé ) e jogar para o servidor em produção sem nenhuma problema de compatibilidade.


OpenVPN WARNING: Failed running command (--client-connect): could not execute external program

Question: I've just configured OpenVPN on my server and it has been working fine till i changed it to work in chroot mode.
This is the main configuration file vpn.example.com.conf:
local w.x.y.z
port 1194
proto udp
proto-force udp
dev tun

ifconfig-ipv6 wwww:xxxx:yyyy:zzzz::1 wwww:xxxx:yyyy:zzzz::2

ca /etc/openvpn/easy-rsa3/easyrsa3/pki/ca.crt
cert /etc/openvpn/easy-rsa3/easyrsa3/pki/issued/vpn.example.com.crt
key /etc/openvpn/easy-rsa3/easyrsa3/pki/private/vpn.example.com.key

dh /etc/openvpn/easy-rsa3/easyrsa3/pki/dh.pem

topology subnet

server 10.8.0.0 255.255.255.0
server-ipv6 wwww:xxxx:yyyy:zzzz::/64

ifconfig-pool-persist ipp.txt

push "redirect-gateway def1 bypass-dhcp"
push "dhcp-option DNS w.x.y.z"
push "dhcp-option DNS z.w.x.y"
push "dhcp-option DNS 184.108.40.206"

push "route-ipv6 wwww:xxxx:yyyy:zzzz::2/64"
push "route-ipv6 wwww::/3"

push "redirect-gateway def1"

tls-crypt /etc/openvpn/easy-rsa3/easyrsa3/ta.key

tls-cipher TLS-ECDHE-RSA-WITH-AES-256-GCM-SHA384

tls-version-min 1.2

auth SHA512

crl-verify /etc/openvpn/easy-rsa3/easyrsa3/pki/crl.pem

cipher AES-256-GCM

compress lz4

user nobody
group nogroup

verify-client-cert require

remote-cert-tls client

username-as-common-name

plugin /usr/lib/openvpn/openvpn-plugin-auth-pam.so openvpn
script-security 2

client-connect /etc/openvpn/scripts/connect_.sh
client-disconnect /etc/openvpn/scripts/disconnect.sh

management /run/openvpn/openvpn.sock unix pw-management-file

keepalive 10 120

persist-key

persist-tun

status /var/log/openvpn/status.log

log-append /var/log/openvpn/openvpn.log

verb 3

explicit-exit-notify 1

max-clients 5

To configure chroot i just:

Created openvpn user by running useradd openvpn -d /etc/openvpn.

chown -R openvpn:openvpn /etc/openvpn.

Changed all paths in the config file into relatives ones.

Added openvpn ALL=(ALL)  NOPASSWD: /sbin/ip to /etc/sudoers

Added the following directives chroot /etc/openvpn, iproute unpriv-ip, user openvpn,  group openvpn.

cat unpriv-ip
#!/bin/sh
/usr/bin/sudo /sbin/ip $*

Also edited rsyslog config to create an extra socket into openvpn chroot directory.

Lastly simplified connect_.sh script to:
#!/bin/bash
/bin/echo 'a'
exit 0

When i run openvpn --config vpn.example.com.conf and try to connect i see WARNING: Failed running command (--client-connect): could not execute external program but if u run su - openvpn i can successfully run ./scripts/connect_.sh script
The following is the output when running openvpn from command line and before any client tries to connect:
cd /etc/openvpn/
root@we:/etc/openvpn# /usr/sbin/openvpn --config conf.d/vpn.example.com\[easy-rsa3+chroot\].conf --verb 3
Fri Dec  8 19:45:01 2017 OpenVPN 2.4.0 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Jun 22 2017
Fri Dec  8 19:45:01 2017 library versions: OpenSSL 1.0.2g  1 Mar 2016, LZO 2.08
Fri Dec  8 19:45:01 2017 MANAGEMENT: unix domain socket listening on /run/openvpn/openvpn.sock
Fri Dec  8 19:45:01 2017 NOTE: the current --script-security setting may allow this configuration to call user-defined scripts
Fri Dec  8 19:45:01 2017 PLUGIN_INIT: POST /usr/lib/openvpn/openvpn-plugin-auth-pam.so '[/usr/lib/openvpn/openvpn-plugin-auth-pam.so] [openvpn]' intercepted=PLUGIN_AUTH_USER_PASS_VERIFY
Fri Dec  8 19:45:01 2017 Diffie-Hellman initialized with 4096 bit key
Fri Dec  8 19:45:01 2017 Outgoing Control Channel Encryption: Cipher 'AES-256-CTR' initialized with 256 bit key
Fri Dec  8 19:45:01 2017 Outgoing Control Channel Encryption: Using 256 bit message hash 'SHA256' for HMAC authentication
Fri Dec  8 19:45:01 2017 Incoming Control Channel Encryption: Cipher 'AES-256-CTR' initialized with 256 bit key
Fri Dec  8 19:45:01 2017 Incoming Control Channel Encryption: Using 256 bit message hash 'SHA256' for HMAC authentication
Fri Dec  8 19:45:01 2017 TUN/TAP device tun0 opened
Fri Dec  8 19:45:01 2017 TUN/TAP TX queue length set to 100
Fri Dec  8 19:45:01 2017 do_ifconfig, tt->did_ifconfig_ipv6_setup=1
Fri Dec  8 19:45:01 2017 unpriv-ip link set dev tun0 up mtu 1500
Fri Dec  8 19:45:01 2017 unpriv-ip addr add dev tun0 10.8.0.1/24 broadcast 10.8.0.255
Fri Dec  8 19:45:01 2017 unpriv-ip -6 addr add wwww:xxxx:yyyy:zzzz::1/64 dev tun0
Fri Dec  8 19:45:01 2017 Could not determine IPv4/IPv6 protocol. Using AF_INET
Fri Dec  8 19:45:01 2017 Socket Buffers: R=[8388608->8388608] S=[212992->212992]
Fri Dec  8 19:45:01 2017 UDPv4 link local (bound): [AF_INET]w.x.y.z:1194
Fri Dec  8 19:45:01 2017 UDPv4 link remote: [AF_UNSPEC]
Fri Dec  8 18:45:01 2017 chroot to '/etc/openvpn' and cd to '/' succeeded
Fri Dec  8 18:45:01 2017 GID set to openvpn
Fri Dec  8 18:45:01 2017 UID set to openvpn
Fri Dec  8 18:45:01 2017 MULTI: multi_init called, r=256 v=256
Fri Dec  8 18:45:01 2017 IFCONFIG POOL IPv6: (IPv4) size=252, size_ipv6=65536, netbits=64, base_ipv6=wwww:xxxx:yyyy:zzzz::1000
Fri Dec  8 18:45:01 2017 IFCONFIG POOL: base=10.8.0.2 size=252, ipv6=1
Fri Dec  8 18:45:01 2017 ifconfig_pool_read(), in='client1,10.8.0.2,wwww:xxxx:yyyy:zzzz::1000', TODO: IPv6
Fri Dec  8 18:45:01 2017 succeeded -> ifconfig_pool_set()
Fri Dec  8 18:45:01 2017 IFCONFIG POOL LIST
Fri Dec  8 18:45:01 2017 client1,10.8.0.2,wwww:xxxx:yyyy:zzzz::1000
Fri Dec  8 18:45:01 2017 Initialization Sequence Completed

That's the output when a client tries to connect:
Fri Dec  8 18:47:44 2017 66.666.66.66:64191 TLS: Initial packet from [AF_INET]66.666.66.66:64191, sid=1c8b367d eb08e85e
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 VERIFY OK: depth=1, C=FF, ST=ZZZ, L=SomeCity, O=Some Text, OU=String, CN=String CA, firstname.lastname@example.com
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 Validating certificate key usage
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 ++ Certificate has key usage  0080, expects 0080
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 VERIFY KU OK
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 Validating certificate extended key usage
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 ++ Certificate has EKU (str) TLS Web Client Authentication, expects TLS Web Client Authentication
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 VERIFY EKU OK
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 VERIFY OK: depth=1, C=FF, ST=ZZZ, L=SomeCity, O=Some Text, OU=String, CN=String CA, email@example.com
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 peer info: IV_VER=2.4.4
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 peer info: IV_PLAT=mac
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 peer info: IV_PROTO=2
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 peer info: IV_NCP=2
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 peer info: IV_LZ4=1
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 peer info: IV_LZ4v2=1
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 peer info: IV_LZO=1
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 peer info: IV_COMP_STUB=1
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 peer info: IV_COMP_STUBv2=1
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 peer info: IV_TCPNL=1
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 peer info: IV_GUI_VER="net.tunnelblick.tunnelblick_4920_3.7.4a__build_4920)"
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 PLUGIN_CALL: POST /usr/lib/openvpn/openvpn-plugin-auth-pam.so/PLUGIN_AUTH_USER_PASS_VERIFY status=0
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 TLS: Username/Password authentication succeeded for username 'client' [CN SET]
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 Control Channel: TLSv1.2, cipher TLSv1/SSLv3 ECDHE-RSA-AES256-GCM-SHA384, 4096 bit RSA
Fri Dec  8 18:47:47 2017 66.666.66.66:64191 [client1] Peer Connection Initiated with [AF_INET]66.666.66.66:64191
Fri Dec  8 18:47:47 2017 client1/66.666.66.66:64191 MULTI_sva: pool returned IPv4=10.8.0.2, IPv6=wwww:xxxx:y:zzzz::1000
Fri Dec  8 18:47:47 2017 client1/66.666.66.66:64191 WARNING: Failed running command (--client-connect): could not execute external program
Fri Dec  8 18:47:48 2017 client1/66.666.66.66:64191 PUSH: Received control message: 'PUSH_REQUEST'
Fri Dec  8 18:47:48 2017 client1/66.666.66.66:64191 Delayed exit in 5 seconds
Fri Dec  8 18:47:48 2017 client1/66.666.66.66:64191 SENT CONTROL [client1]: 'AUTH_FAILED' (status=1)
Fri Dec  8 18:47:53 2017 client1/66.666.66.66:64191 SIGTERM[soft,delayed-exit] received, client-instance exiting

Comment: Check out the `script-security` configuration option.
Comment: As you can see, script-security is set to 2 and the script just execs echo command. Thanks anyway.
Comment: Can you include the full log entry in your question?
Comment: Just did it. :)
Answer: As my script was using bash i needed to move bash and all dependencies into chroot:
cp -v /bin/bash /etc/openvpn/bin

So run ldd /bin/bash and move all dependencies into chroot directory:
linux-vdso.so.1 =>  (0x00007fff1fbe5000)
libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007f86fcbbc000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f86fc9b8000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f86fc5f1000)
/lib64/ld-linux-x86-64.so.2 (0x000055a1be46b000)

Answer: In my case, the problem was simple: I didn't have the shebang in my script:
#~/bin/bash

Comment: You mean `#!/bin/bash` or [better](https://linuxize.com/post/bash-shebang/) `#!/usr/bin/env bash`.


Differential equation for the logistic map

Question: From the Wikipedia article on the logistic map I find the following definition as a recurrence relation:
$$x_{n+1} = rx_n(1 - x_n) \tag{1} $$
Then, in another article, I see how to derive from this the closely related logistic function. This begins by rewriting the recurrence in $(1)$ as a differential equation:
$$x' = rx(1 - x) \tag{2} $$
And the solution to $(2)$ is the function
$$x(t) = \frac{1}{1 + e^{-rt}} \tag{3} $$
When I compare the graphs of $(1)$ and $(3)$ I see that they are not the same, and this does not appear to be a problem with the scaling of the graph.
Why does evaluating $(3)$ at $n$ not give me $x_n$ (the value of $x$ after $n$ iterations) in $(1)$? Is solving the recurrence different to solving it's differential equation?
Comment: Yes, the recurrence and the differential equation are very different.
Comment: For one thing, the left side in (1) is $x_{n+1}$, the **value** of the population at the next iteration, while the left side in (2) is $x'(t)$, the **rate of change** of the population at time $t$.
Comment: Yes, and the solution to (2) gives the *value* of the population at time $t$. It is these functions (and graphs) I am comparing.
Comment: How exactly did you plot those and for what value of r
Answer: If you want a discrete approximation to the solution of the differential equation (2), you could take (the Euler approximation with step size $h$)
$$x_{n+1} = x_n + h r x_n (1 - x_n)$$
This can be written as a scaled version of (1):
$$ y_{n+1} = (1 + hr) y_n (1 - y_n) $$
where $x_n = y_n (1+hr)/(hr)$.
Comment: Thanks, but really I want a continuous approximation of equation (1). I thought this is what I was getting with (3).
Comment: Just reverse the steps to go from the $y$ equation to the $x$ differential equation.
Comment: Of course, there's no hope of a good approximation unless (1) is in the region of parameter space where the nonzero fixed point is stable.
Answer: The delay logistic equation shows a similar behavior like the logistic map up to the first bifurcation : http://demonstrations.wolfram.com/DelayLogisticEquation/
Higher number of cycles can be achieved with multiple delays  :

https://arxiv.org/pdf/1211.7022.pdf - Stability and Hopf Bifurcation
Analysis of the Delay Logistic Equation
https://www.researchgate.net/publication/319977097_Unbounded_and_blow-up_solutions_for_a_delay_logistic_equation_with_positive_feedback


Which tools simplify administration tasks with Docker containers?

Question: Context: My task is to administer a virtual machine with about 5 web services for a small workgroup. I plan to run all services in Docker containers. An additional nginx Docker container should redirect requests to the different services.
Problem: I do not have much experience with DevOps and plan to use basic bash scripts and Docker Compose to administer the setup.
Question: Which tools simplify this administration task (updating, backup, exchanging containers, changing port directives)?
Answer: A single virtual machine with 6 Docker containers does not require any tool. Adding tooling to the mix really just increase the complexity level of your installation and turns a simple thing into a monster.
A few Shell scripts is all you need at that size.
Answer: While what ETL says in his answer is more or less true, I still think there some value in some tooling to ale life raider.
What I've found is Portainer, which would let you do most of what you want with a nice web interface.


drupal multilingual frontpages different templates

Question: I am building multilingual site using 3 languages.
English is default and 2 other used wit prefixes. www.example.com/fr/.../cs/
I would like to create custom landing page on www.example.com using different template than other landing pages with prefixes.
So www.example.com (which is English language) would only be plain page (custom template) with links to www.example.om/fr (with default template page) and to www.example.com/cs (default template)
Would be something like this possible?
Thank you
Comment: Which (major) version of Drupal are you using for the site?
Comment: Sorry I forgot to mention - it is drupal 6
Answer: Create a custom template file for the English landing page first (for example: page-customfront.tpl.php) then add the following code into your theme template.php file:
function mytheme_preprocess_page(&$variables) {
  global $language;
  if (drupal_is_front_page() && $language->language == 'en') {
    $variables['template_file'] = 'page-customfront';
  }
}

This should do the trick (assuming English will remain the default language with no prefix). Don't forget to switch out mytheme in the function name with your actual theme name.
As for the language links you could use the following code:
<?php
$langs = language_list();
foreach ($langs as $lang) {
  if ($lang->enabled) {
    if ($lang->language == 'en') continue;
    print l($lang->native, '<front>', array('language' => $lang));
  }
}
?>

This should go into page-customfront.tpl.php in the place where you want the links to appear. If you are familiar with creating custom modules or don't mind learning it would probably be preferable to turn this code into a function, add it your module file, enable the module and then just call the function from page-customfront.tpl.php.
Comment: To my knowledge you can't make www.example.com independent. I would suggest adding a second custom English language with "en" prefix, which would get you the result you want. The original English would then only be used for www.example.com while the other English would act as the actual English language of the site. I've used this approach myself a lot (for a different purpose though) and it works well. If necessary you could also switch the roles of the custom and original English languages.
Comment: Ok I will try that and let you know today. I am planning to add more languages in the future - all with prefixes, english language as well. Now I don't use it for customers - that is why I don't need prefix. What would I need to do to have www.example.com as a custom template with links to default templates with language prefixes? Thank you very much for answer.
Comment: This solution worked perfectly. Would you be so kind and tell me somution for my second quiestion? Thank you very much
Comment: Added the answer to your second question in my post. Hope it helps.
Comment: Hi,I added the second code inside the page-customfront.tpl.php but it shows only 2 other languages and not english. I need it to show all available languages so the customer can choose from them. Why is it better to make custom module and to avoid such code with links to be put into page? Thank you
Comment: `if ($lang->language == 'en') continue;` in the code means that English is skipped as it would just link to the page the user is already on. You could modify it to make it link to a different page or add a custom English language with a prefix that would be used as the actual English version of the site. About where the code is: it's just good habit to not put a lot of php code into template files, but nothing to really worry about even if you do.
Comment: Thank you for your kind answers. Maybe I didn't explained what I want to achieve well because of my bad english. I would like to be www.example.com to be independent from any language. Would that be possible? From this site I would like to have links to individual language pages with prefixes. I applied a patch that enables to set different frontpage for all languages. What I try to achieve is exactly the same as http://www.biovea.com/
Comment: Is it the right way how to do that written as the last answer in this article? http://stackoverflow.com/questions/3203794/translating-strings-in-drupal-with-no-english-default-in-the-code So I just upload any other language that would serve for the www.example.page? Do I get it correct? I searched for an english translation but since it is default there is none available for download.
Comment: The accepted answer written there is the right way. You don't need any English translations since the custom language will use the default Drupal language (English) already. Reread my previous comment and try things out - you're making a simple thing unnecessarily complicated for yourself. If you still get stuck after all this create a new question and explain your problem there.
Comment: Well, that was what I asked- you suggested to add second custom english language. How to do that? I understand what you mean but nobody in no forum explains how to do that. Thank you for your patience.
Comment: Same place where you normally add languages. Path would be like this: "www.example.com/admin/settings/language/add". Click on "Custom language" on the bottom part.
Comment: That is exactly what I wanted to achieve. Thank you for patience and kind answers.


What happens when you inhale helium and then play a trumpet?

Question: We all know the silly effect that inhaling helium has on speaking and singing, where some wacky speed-of-sound physics makes our voices sound unnaturally and ridiculously high-pitched.  A student asked me today what would happen if the same thing was tried blowing into a trumpet.  What would the result be?
I was not comfortable instructing kids to try it out, as I'm sure deliberately inhaling helium must violate some sort of school safety rule.  But it could make an interesting special effect and I'm intensely curious.  Has anyone actually tried it?
Comment: You'll also find that if, having drunk a fizzy drink, you burp into the instrument while playing it that the pitch drops. This is because the speed of sound in Carbon Dioxide is significantly slower (267 m/s) than in air (343 m/s). Sound travels much faster in Helium (1007 m/s).  See this table for the speeds in various gases: https://pages.mtu.edu/~suits/SpeedofSoundOther.html
Comment: There's enough of a density difference between cold air and warm air that a cold instrument will be noticeably off pitch until it warms up.
Comment: Random idea: Write a piece that instructs the wind and brass players to breathe helium while playing certain passages.
Comment: @Divide1918 you are evil!
Comment: And insist that it be played in tune.
Answer: OK, I'll do your Googling for you :-)
(There's one for trumpet too, but I thought a Helium Tuba might be even more fun.)

In the video, a tuba player uses a modified mouthpiece to inject helium into his mouth while playing.  On a sustained note, the pitch rises by nearly an octave while the helium is being injected;  once the helium is no longer being injected, the pitch slowly falls back to the expected pitch over the course of a few seconds.  Melodies become quite difficult to play since the resonances of the instrument are constantly changing, and the player even has some difficulty with scales.
Answer: In addition to Laurence's answer: it's worth to note that the reason why the pitch of a wind instrument changes is different from why the voice sounds differently with helium.
In a wind instrument the source of sound is a vibrating air column, and the frequency is proportional to the speed of sound, see https://en.wikipedia.org/wiki/Acoustic_resonance#Resonance_of_a_tube_of_air . As the speed of sound in Helium is almost 3 times larger than in air, in pure helium the pitch would be almost an octave and a fifth higher than in air.
On the contrary, in human voice the source of the sound are vibrating vocal folds, and their vibration frequency doesn't depend on the gas medium. However the wavelength in helium does change, and it affects how various frequencies interact with your throat and mouth resulting in a different timbre. See this question for more detailed explanations: https://physics.stackexchange.com/questions/122353/why-does-our-voice-sound-different-on-inhaling-helium
Finally, while helium itself is harmless, there are indeed safety considerations when breathing it, especially from a pressurized container, including risk of asphyxiation, mechanical damage and others, see e.g. https://www.healthline.com/health/inhaling-helium . Insides of balloons are often coated with talcum powder which (in large amounts/regular exposure) can cause lung issues.
Comment: "_the reason why the pitch of a wind instrument changes is different from why the voice sounds differently with helium_" -- in the case of the voice it is vocal chords, and in the case of a trumpet it is the lips that are the source of vibrations; then the cavity resonances are dependent upon the properties of the gaseous medium and the nature of the cavities. What is different between these two cases?
Comment: @exnihilo good question (actually it would made a good separate question). In Tuba indeed the primary source of vibration is a reed formed by the musician's lips, but it is coupled to the the pipe of the instrument, so the frequency of vibration is determined by the length of the pipe. Human voice is more of a free reed instrument like harmonica. Cavities in vocal tract can absorb various frequencies, but they are not coupled (at least not via air impedance) to the vocal folds and don't change the frequency which they vibrate.
Comment: It's not quite that simple -- with practice you can "force" a pitch that is not a harmonic of the musical instrument's length/bore profile.  The combination of vocal cords and mouth is less dependent on the "length" because it's such a short length & relatively wide bore.  Compare with a brass player warming up with just the mouthpiece, where the pipe length is pretty much irrelevant, being a small fraction of the wavelength


TObjectList and destructor custom class

Question: i use custom class TFrame in TObjectList. TFrame contain ListBoxItem and record's.
Еheir parent can only be TListBox.
  TFrame = class
    ListboxItem: TListBoxItem;
    Name: string;
    PosStart,
    PosEnd : integer;
    Max: TData;
    Min: TData;
    Sqrt: TData;
    constructor Create (ListBox: TListBox);
    destructor Destroy;
  end;

destructor TFrame.Destroy;
  begin
    ListboxItem.destroy;
  end;

how to write a destructor for correct deletion with ObjectList.Delete(i)?
Now if ill try to delete - i have visible items with exception message.
Ty much!
Comment: What exception exactly? Please provide a [mcve] and the complete error message
Answer: Your destructor needs to override the base class destructor
destructor Destroy; override;

Otherwise it won't be called by Free.
And you should also call the inherited destructor.
destructor TFrame.Destroy;
begin
  ListboxItem.Free;
  inherited;
end;

Also, use Free rather than calling a destructor directly so that your code is protected against nil references.
There may well be other bugs in the code we can't see.

TObjectList and destructor custom class


$L^1$ cannot be embedded into Sobolev $H^{-\frac{n}{2}}(\mathbb{R^n})$

Question: I have managed to show that:
(a) The Dirac function $\delta_0 \notin H^{-\frac{n}{2}}(\mathbb{R^n})$, and
(b) $\eta_{\varepsilon}(x)= \varepsilon^{-n} \eta(\frac{x}{\varepsilon})$ converges to $\delta_0$ in $\mathscr{S}'$ when $\varepsilon \rightarrow 0^+$, in which $\eta \in C_0^{\infty} (\mathbb{R}^n)$ and $\int \eta =1$.
How can I show $L^1$ cannot be embedded into $H^{-\frac{n}{2}}(\mathbb{R^n})$ from (a) and (b)? This might be a one-step thing, yet I am not quite familiar with all those embedding stuffs.
Any hints or introductions of theorems to be used will be greatly appreciated. Thanks!
Answer: The family $\{\eta_\epsilon\}_{\epsilon>0}$ is uniformly bounded in $L^1$. If $L^1$ was continuously embedded in $H^{-n/2}$ then along a sequence $\epsilon_n\to 0$, it would converge weakly in $H^{-n/2}$ to some $\eta \in H^{-n/2}$. In particular then, $\eta_{\epsilon_n}\to \eta$ in $\mathscr S'$. But this contradicts (a) when you take into account uniqueness of limits in $\mathscr S'$.


Picard group in different settings

Question: Picard group is a recurring notion that I've been seeing very often recently recently. For projective varieties, Picard group is the divisor class group. For Dedekind domains, it is the ideal class group. For rings, Picard group can be defined on its algebraic line bundles. In the Wikepedia page, it says it can be defined for any ringed space. Or even more generally, it can be defined for any symmetric monoidal category. But I have yet to find a good exposition to link these together.
So my questions are:

How does one see that the Picard groups in the cases of divisor class groups, ideal class groups and line bundles are related?
Follow up to (1.), what are some examples (using the relation of Picard groups in different settings) that allow us to understand a number theoretic problem geometrically, or a geometry problem arithmetically?
Are there results or properties of Picard groups in the general settings (ringed spaces or symmetric monoidal categories) that turn out to be significant when we examine it in the more specific settings?
Answer: Let's correct a misconception first, before moving on to the rest of the question: it is not true that the Picard group is the divisor class group on an arbitrary projective variety. The condition that the Picard group and divisor class group coincide for a general scheme is that our scheme be factorial - see for instance here. This condition exactly tells us that Weil divisors and Cartier divisors coincide, so the divisor class group and the Picard group coincide.
In general, the Picard group is the group of isomorphism classes of invertible objects for the monoidal structure. In most cases in algebraic geometry, this means invertible sheaves under tensor product: this covers all three scenarios in your question (1). The equivalence of divisors and line bundles on factorial schemes has already been mentioned in the first paragraph. For the second paragraph, fractional ideals in a Dedekind domain $D$ are exactly the invertible sheaves on $\operatorname{Spec} D$.
As far as examples of using the Picard group, computing intersection numbers is a big one. One can do an incredible amount of geometry this way, see for instance Hartshorne chapter 5 on algebraic surfaces. Unsurprisingly, this generalizes to the whole topic of intersection theory, which you can get a lot done with. We also can say a lot with tools developed from the Picard group when studying abelian varieties. Briefly, the Jacobian variety of a curve $C$ is the connected component of the identity in the Picard group, and this concept gets a ton of use in that field. I'm sure there a wealth of examples from number theory, but I am less familiar with that area and do not have a good one to give.
As far as your final question, I'm not sure about specific insights one gets when zooming in from the very abstract picture to a more elementary picture (perhaps someone else will chime in and enlighten us). It seems to me to be more the case that invertible objects are useful in lots of situations, and the Picard group and it's generalizations are a good way to keep track of this information.

Picard group in different settings


Ajuda para configurar WAMP Server

Question: Estou com um problema no WAMP server, onde não consigo acessar meu projeto pelo LocalHost quando clico diretamente no nome do projeto, apenas se digitar "localhost/nome_do_projeto".
Alguém tem alguma dica para poder configurar?
Answer: Dentro da pasta WWW do wamp, você vai encontrar um arquivo chamado índex.php, abra-o.
Na linha 338 você vai encontrar o seguinte
$projectContents .= '
'.$file.'
';

Se não achar pesquisa por $projectContents no editor de sua preferencia para você achar a linha certa, pois dependendo da versão pode alterar a linha.
Para acertarmos esse problema devemos adicionar a frente de HTTP:// a palavra localhost, pois essa linha é a responsável por montar a url no navegador, pois da maneira que está o wamp monta a url somente com o nome do seu projeto por exemplo,  sendo que desta forma não abrirá nosso arquivo, mostrando erro de pagina inexistente.
Então para solucionarmos esse problema devemos deixar essa linha dessa forma:
$projectContents .= '
'.$file.'
';

Prontinho, seu localhost já deverá estar acessando seus trabalhos pelo clique na pasta.
Agora na pasta wamp/scripts/ temos um arquivo chamado refresh.php, abra-o e na linha 651 você irá encontrar o seguinte comando:
$myreplacesubmenuProjects .= 'Type: item; Caption: "'.$projectContents[$i].'"; Action: run; FileName: "'.$c_navigator.'"; Parameters: "// '.$projectContents[$i].'/"; Glyph: 5';

Para corrigir, devemos fazer o mesmo à frente de // desta maneira:
$myreplacesubmenuProjects .= 'Type: item; Caption: "'.$projectContents[$i].'"; Action: run; FileName: "'.$c_navigator.'"; Parameters: "//localhost/'.$projectContents[$i].'/"; Glyph: 5 ';

Reinicie os serviços do wamp só por garantia e, se tudo ocorrer bem, seus projetos poderão ser acessados através do localhost.
Comment: Qual o problema que esta dando quando tu tenta acessar o projeto?
Comment: Tava um pouco diferente mas consegui. Deu certinho. Obrigado
Comment: Precisando estamos aqui :D

Ajuda para configurar WAMP Server


Prolog Finding Kth element in a list

Question: I am trying write a predicate in prolog to find Kth element in a list.
Example:
?- element_at(X,[a,b,c,d,e],3).
X = c

my code as follows
k_ele(X,[X|_],1).
k_ele(X,[_|T],Y) :- Y > 1,Y is Y - 1, k_ele(X,T,Y).

But no use, I found solution on Internet as
element_at(X,[X|_],1).
element_at(X,[_|L],K) :- K > 1, K1 is K - 1, element_at(X,L,K1).

Which is same as my logic except they used one extra variable K1.
What is wrong with my code, why I need another variable ?
Comment: In prolog, variables aren't "assigned" as they are in many other languages you're more familiar with. Variables are "unified" (as @dasblinkenlight says in his answer) - which means Prolog seeks to find values for the variables that make the statement they are in true. No value of `Y` makes `Y is Y - 1` true, so it will always fail. `K1 is K - 1` will unify `K1` to the value of `K -1` if `K` is already defined. Once a variable is unified, it cannot be changed in a clause.
Answer: The reason your code does not work is that unification is not an assignment. When you say
Y is Y - 1

you are trying to unify a value of Y with the value of Y-1, which is mathematically impossible. This is roughly the same as saying 4 is 3 or 1001 is 1000. The entire condition fails, leading to the failure to find the element in the list.
The fixed solution that you have found on the internet introduces a separate variable K1, which is unified with K - 1. This is very much doable: K1 gets the value to which K-1 evaluates, the condition succeeds, and the clause moves on to the recursive invocation part.
Answer: Because variables in prolog are write-once critters. Having been [assigned|unified with|bound to] a non-variable value, it ceases to be variable. It is henceforth that value. Unlike more...conventional...programming languages, once bound, the only way to reassign a prolog variable is to backtrack through the assignment and undo it.
It should be noted, though, that a variable can be unified with another variable: Given a predicate something like
foo(X,Y) :- X = Y .

and something like
shazam(X,Y) :- bar(X,Y) , X = 3.

will result in both X and Y being 3. Having been unified, X and Y are both the same variable, albeit with different names.
Answer: I imagine you're working with the exercises from this link:
http://www.ic.unicamp.br/~meidanis/courses/problemas-prolog/
Note, in my opinion the original solution is not the best either.
For example, a query:
element_at(X,[a,b,c],Y).

would crash, even if there are 3 solutions:

X = a, Y = 1;
X = b, Y = 2;
X = c, Y = 3;

I believe writing in an alternative way:
element_at(H, [H | _], 1).
element_at(H, [_ | T], N) :- element_at(H, T, NMinus1), N is NMinus1 + 1.

would give better results. It's less efficient as one can not apply the last call optimization, but the logic becomes more general.
Comment: s(X) for your answer. Efficient? No. Inspiring? Most definitely. Thanks!

Prolog Finding Kth element in a list


GLFW/GLEW C++ (atioglxx.dll)

Question: So...
For the past couple days I have been writing an OpenGL program using GLFW and GLEW, and everything has been going mostly alright, until today. My program just crashes and tells me that there's an "access violation":

First-chance exception at 0x549E12F0 (atioglxx.dll) in OpenGLProject.exe: 0xC0000005: Access violation reading location 0x28F98511.
Unhandled exception at 0x549E12F0 (atioglxx.dll) in OpenGLProject.exe: 0xC0000005: Access violation reading location 0x28F98511.
The program '[7712] OpenGLProject.exe' has exited with code 0 (0x0).

I have Googled around a lot for an answer, or at least something similar, but to no avail. I don't think that the problem is my drivers, but it very well could be. But I believe that it is just my bad programming that is the problem here.
main.cpp:
#define UTIL_HEAD
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <math.h>

#define GL_HEAD
    #define GLEW_STATIC
    #include <glew.h>
    #include <glfw3.h>

#include "shaders.h"

const GLuint width = 800, height = 600;
GLuint renderer;

int kill() {
    std::cout << "Stopping!";

    //glDeleteVertexArrays();
    //glDeleteProgram();
    //glDeleteVertexArrays();

    glfwTerminate();
    return -1;
}

void windowInit() {
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
}

void shaderInit() {
    renderer = compileShaders();
    GLuint vao;

    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
}

void renderInit() {
    const GLfloat color[] = { (float)sin(glfwGetTime()) * 0.5f + 0.5f,
                              (float)cos(glfwGetTime()) * 0.5f + 0.5f,
                              0.0f, 1.0f };

    glClearBufferfv(GL_COLOR, 0, color);
}

int main() {

    windowInit();

    GLFWwindow * window = glfwCreateWindow(width, height, "Test", nullptr, nullptr);

    if (window == nullptr) {
        std::cout << "Failed to create GLFW window" << std::endl;
        kill();
    }
    glfwMakeContextCurrent(window);

    glewExperimental = GL_TRUE;
    if (glewInit() != GLEW_OK) {
        std::cout << "Failed to initialize GLEW" << std::endl;
        kill();
    }

    shaderInit();

    glViewport(0, 0, width, height);

    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        renderInit();
        glUseProgram(renderer);
        glDrawArrays(GL_POINTS, 0, 1);
        glfwSwapBuffers(window);
    }
    kill();
    return 0;
}
#ifndef UTIL_HEAD
    #define UTIL_HEAD
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <math.h>
#endif

Shader.hpp:
#ifndef UTIL_HEAD
    #define UTIL_HEAD
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <math.h>
#endif

#ifndef GL_HEAD
    #define GL_HEAD
    #define GLEW_STATIC
    #include <glew.h>
    #include <glfw3.h>
#endif

const char * fragment_shader_source;
const char * vertex_shader_source;

void loadVertexShader() {

    std::ifstream vertex("./shader_vtex.glsl");
    std::string vertex_shader_read;

    std::string vline;
    if (vertex.is_open()) {
        while (std::getline(vertex, vline)) {
            vertex_shader_read = vertex_shader_read + vline + '\n';
        }
        vertex.close();
    }
    else {
        std::cout << "error: (critical) unable to open vertex shader!" << '\n';
    }
    vertex_shader_source = vertex_shader_read.c_str();
}

void loadFragmentShader() {

    std::ifstream fragment("./shader_frag.glsl");
    std::string fragment_shader_read;

    std::string fline;
    if (fragment.is_open()) {
        while (std::getline(fragment, fline)) {
            fragment_shader_read = fragment_shader_read + fline + '\n';
        }
        fragment.close();
    }
    else {
        std::cout << "error: (critical) unable to open fragment shader!" << '\n';
    }
    fragment_shader_source = fragment_shader_read.c_str();
}

GLuint compileShaders() {

    GLuint vertex_shader;
    GLuint fragment_shader;
    GLuint program;

    loadVertexShader();
    loadFragmentShader();

    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex_shader, 1, (const GLchar**)vertex_shader_source, NULL);
    glCompileShader(vertex_shader);

    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(vertex_shader, 1, (const GLchar**)fragment_shader_source, NULL);
    glCompileShader(fragment_shader);

    program = glCreateProgram();
    glAttachShader(program, vertex_shader);
    glAttachShader(program, fragment_shader);
    glLinkProgram(program);

    glDeleteShader(vertex_shader);
    glDeleteShader(fragment_shader);

    return program;
}

You can find additional code (shaders, etc.) for this project at GitHub.
Thanks in advance for any help given!
Comment: `while (std::getline(vertex, vline))` Ugh. Why do people do this when loading files? Do they honestly think that this is a good way to load an entire file? Do a Google search about it; you'll find [plenty of alternatives](http://stackoverflow.com/a/2602258/734069), even on this very site.
Comment: Sorry... I'm relatively new to C++ and this is the only way I thought of to read the file. I'll figure out a better solution!
Answer: There is a problem with the shader loading: You only store the .cstr() pointer but not the string object. When then loadVertexShader method (or the loadFragmentShader method) goes out of scope and the vertex_shader_read object is deleted. When this happens the stored pointer points to an invalid memory address.
To fix the problem, you can, for example, store the string object itself instead of the pointer. But for a better design I would suggest to avoid global variables for such purpose anyhow.
Comment: Side-side-note:There is actually a VAO bound in this code (it's in `shaderInit()`).
Comment: Ok. I moved the content of the two functions into the body of compileShaders() since they were only called once, and it eliminates the use of global variables. But I still cant seem to figure out how to get the value of the variable which the pointer points to without the variable dying and taking the pointer with it. Any advice?

GLFW/GLEW C++ (atioglxx.dll)


How do I get a parent-group alias as token for the Pathauto module?

Question: When a user sets his groups alias to lets say "mynewgroup" you can view the group at www.example.com/mynewgroup.
How to set pathauto presets to create www.example.com/mynewgroup/mynewgroupcontent as a path for a newly created group-content?
I can not find a token for parent's group alias.
I can only find [group_content:gid:entity:url] - but this provides full path and not only the alias.
Answer: Not possible at the moment (unless you make it yourself), there is an issue in the module's issue queue though that also has a patch that might work:
https://www.drupal.org/node/2774827


Weighted sum of Dirichlets is Dirichlet

Question: I am studying Sethuraman's paper on the Dirichlet process and having difficulty showing a lemma.  He states: Let $\boldsymbol\gamma=(\gamma_1,...\gamma_k)$ and $\gamma=\sum_j \gamma_j$ and let $\beta_j=\frac{\gamma_j}{\gamma}$, $j=1,2,...,k$. Then, $\sum_j \beta_j\mathcal{D}_{\boldsymbol\gamma+e_j}=\mathcal{D}_{\boldsymbol\gamma}$
In this lemma $\mathcal{D}_{\boldsymbol\gamma}$ is the Dirichlet distribution with $\boldsymbol\gamma$ as the parameters and $e_j$ is a vector of 0s with a 1 in the jth position.
Sethuraman says proofs of this lemma are found in many standard text books, including Wilks (1962).
I am trying to prove this lemma. I have not found it in any textbooks and cannot find a copy of the Wilks book.
I have tried it many ways. Notably, by expressing the Dirichlets as gammas and  for k=2.
Answer: Look at the densities.  By virtue of the definition of the Dirichlet distribution, on the right hand side the density (in variables $\mathbf x = (x_1,x_2,\ldots,x_k)$ with $x_1+x_2+\cdots+x_k=1$) is proportional to
$$F_\gamma(\mathbf x) = \frac{x_1^{\gamma_1-1}\cdots x_k^{\gamma_k-1}}{\Gamma(\gamma_1)\cdots\Gamma(\gamma_k)}.$$
On the left hand side, because $\Gamma(\gamma_j+1)=\gamma_j\Gamma(\gamma_j),$ the density for term $j$ is proportional to
$$\gamma_j\frac{x_1^{\gamma_1-1}\cdots x_k^{\gamma_k-1}}{\Gamma(\gamma_1)\cdots\Gamma(\gamma_k)}\frac{x_j}{\gamma_j}  = x_jF_\gamma(\mathbf x ).$$
(The initial $\gamma_j$ comes from the coefficient $\beta_j$ in the linear combination -- ignoring the common factor of $1/\gamma$ -- while the final $\gamma_j$ in the denominator comes from the preceding $\Gamma$ identity.)
Summing over all $j$ produces $x_1+x_2+\cdots+x_k = 1$ times $F_\gamma(\mathbf x).$  Because both distributions necessarily are normalized to have unit integrals and are proportional to the same function of $\mathbf x$, they are equal, QED.
Comment: I have been interpreting $\mathcal{D}$ being distributed Dirichlet, but you are right! $\mathcal{D}$ is actually the Dirichlet distribution itself! Makes so much more sense now. (I must change my question so I am not saying $\mathcal{D}\sim Dir$.)

Weighted sum of Dirichlets is Dirichlet


Does Wikipedia explain gradient boosting in wrong way?

Question: Wikipedia's geral Gradient Boosting is:

Friedman's Gradient Boosting is:

Why wikipedia's gradient boosting fit h_m through pseudo-residuals while friedman uses line 4 to fit h? My question is not about he uses least squares to fit h_m but he does that fitting B.h(x,a) to pseudo-residuals instead h(x,a) to pseudo-residuals.
Are wikipedia's gradient boosting  and Friedman's Gradient Boosting the same?
Comment: One observation: in the Wikipedia version, if the class of weak learners $\mathcal{H}$ is closed under scaling (i.e. if $h \in \mathcal{H}$ then $\beta h \in \mathcal{H}$ for any scalar $\beta$, which is true for common classes like trees), then the two formulations are equivalent. Not sure if this is the intended resolution to your question; I am also curious about this difference between the two formulations.
Comment: Agreed with @angryavian; (+1) many other authoritative sources from 00's on boosting (e.g. Hastie et al. ESEL (2008), Buhlmann & Hothorn (2007)) as well as newer references (e.g. Murphy's MLPP (2012), Schapire & Freud F&A B (2012), Efron & Hastie's CASI (2016)) don't use $\beta$ as they assume the learner is flexible enough. I think it was just a case of somewhat over-jealous notation that was dropped soon afterwards.
Comment: @angryavian changing βh to h should we change p_m.h to h? another question is what happens with β after line 4?
Comment: @usεr11852 Friedman has started to use h instead βh in decision trees sections but he hasnt commented the why of that. I'm looking for references to use wikipedia's gradient boosting in general way not limited to decision trees.
Answer: Responding to your comments, and bringing it back to my original comment:
Line 4 of Friedman's algorithm can be viewed as "finding the best function $g \in \mathcal{G}$ that fits the pseudo-residuals via minimizing $\sum_i [\tilde{y}_i - g(x_i)]^2$," with $\mathcal{G}$ containing all functions of the form $g(\cdot) := \beta h(\cdot; a)$.
Once you find the optimal $g(\cdot) = \beta_m h(\cdot; a_m)$ (via the optimal $a_m$ and $\beta_m$ from Line 4), you can do line 5-6 either by throwing away $\beta_m$:

(5) $\rho_m = \arg \min_\rho \sum_{i=1}^N L(y_i, F_{m-1}(x_i) + \rho h(x_i,; a_m))$

(6)$F_m(x) = F_{m-1}(x) + \rho_m h(x; a_m)$

or by keeping $\beta_m$:

(5') $\rho'_m = \arg \min_{\rho'} \sum_{i=1}^N L(y_i, F_{m-1}(x_i) + \rho' \underbrace{\beta_m h(x_i; a_m)}_{g(x_i)})$

(6')$F_m(x) = F_{m-1}(x) + \rho'_m \underbrace{\beta_m h(x; a_m)}_{g(x)}$

These two approaches are actually equivalent since the optimizers of (5) and (5') are related by $\rho_m = \rho'_m \beta_m$.
The second approach is written in a form more similar to what Wikipedia is doing, since you can write steps 4-6 using only $g$ and $\mathcal{G}$.
So basically, the formulation in Friedman's "Algorithm 1" is the same as Wikipedia's, except the class of weak learners is not $\mathcal{H} = \{h(\cdot; a) \mid a \in \mathcal{A}\}$, but rather $\mathcal{G} = \{\beta h(\cdot; a) \mid \beta \in \mathbb{R}, a \in \mathcal{A}\}$.
In the special case where $\mathcal{H}$ is closed under scaling (i.e. $h \in \mathcal{H}$ implies $\beta h \in \mathcal{H}$ for any scalar $\beta$; this is true for classes like trees), then $\mathcal{H} = \mathcal{G}$ and there is no discrepancy between Wikipedia and "Algorithm 1."
Comment: i got it what you meant but im still in doubt about line 4 notation, Does Friedman take $\mathbf{a}$ and $\beta$ to into $\mathbf{a}_m$ ? can't this adulterate the dimension of $\mathbf{a}$?
Comment: @DaviAmérico Line 4 is an optimization simultaneously w.r.t both $a$ and $\beta$. Friedman throws away $\beta$ and keeps the optimal $a$ (denoted $a_m$). I'm not sure what you mean by "adulterate the dimension."
Comment: i meant:
$(\mathbf{a}_m)_{m x 1}=(\mathbf{a}_{optimum},\beta_{optimum})_{(m+1) x 1}$

but he really does:

$(\mathbf{a}_m,\beta_m)_{m x 1}=(\mathbf{a}_{optimum},\beta_{optimum})_{(m+1) x 1}$

and

$\rho_{m}=arg min_{\rho} \sum_{i=1}^N L(y_i,F_{m-1}(x_i)+\rho h(x_i,\mathbf{a}))$

where $\rho=\rho^{'} \beta_m$

i'm still wondering if his notation at line 4 is right
Comment: @DaviAmérico $(a_m, \beta_m) = (a_{opt}, \beta_{opt})$ is correct. The point of my answer above is to show that getting $a_m$ right is the main point of line 4, because if $a_m$ is correct, then you can replace $\arg\min_{\rho} \sum_i L(y_i, F_{m-1}(x_i) + \rho h(x_i, a))$ with $\arg\min_{\rho} \sum_i L(y_i, F_{m-1}(x_i) + \rho (c h(x_i, a)))$ for any scalar $c$; either way $\rho_m$ will be the same.
Comment: see (Haihao Lu, Sai Praneeth Karimireddy, Natalia Ponomareva,Vahab Mirrokni) they do what you do and see (Buhlmann and Hothorn 2007) page .7 is commented about ignoring the line search at line 5 and the why to do that in page 36.
Comment: If you're still interested I've tried to proof that a regression tree is closed under scaling in my last post.


Pegar índice de uma div com classes iguais usando mouseover() Jquery

Question: Tenho várias divs com a mesma classe e preciso de uma função que, quando eu passar o mouse em alguma delas, com mouseover() pegue o índice dela
Comment: O gajo que respondeu a isto fez magia, continuo a pensar que esta pergunta é de baixa qualidade.
Comment: Ajuda se você mostrar o código...
Comment: Obrigado pela atenção, já obtive resposta
Comment: Marque a resposta, então. Não deixe a pergunta aberta.
Answer: Quando diz posição eq() seria a index do elemento?
Caso seja, você pode usar .index()
$(element).mouseover(function(){
    alert($(this).index());
});

Criei um pequeno exemplo, caso seja isso:

$(function(){
    $("div").mouseover(function(e){
       console.log($(this).index());
    });
});
div {
    width: 60px;
    height: 60px;
    margin: 10px;
    float: left;
    border: 2px solid blue;
}

https://jsfiddle.net/leonardorodrigues/0qon0aa8/
Comment: Exato Leonardo, era isso que eu precisava! Muito obrigado!!
Comment: @GustavoSantana, marque as respostas que ajudaram. Não abandone as perguntas.


Como fazer um ScheduledExecutorService lançar uma nova tarefa enquanto a anterior ainda não terminou?

Question: Eu estou implementando um scheduler para rodar algumas threads no meu sistema em intervalos x de tempo. O grande problema é que se a thread 1 ainda não terminou de rodar, a 2 não começa, mesmo o seu tempo tendo chegado.
No exemplo abaixo eu "forcei" esse erro, pois estava desconfiado que isso poderia estar acontecendo.
Thread
package backgroundProcesses;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimerTask;

public class MinhaThread implements Runnable {

    @Override
    public void run() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        System.out.println("FOI, COMEÇOOU A THREAD: " +  sdf.format(cal.getTime()));
        int i = 0;
        while(i < 1000000000) {
            int a = 1;
        }

        System.out.println("CHEGOU AO FIM");
    }

}

Executor
package backgroundProcesses;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class ExecutorThreads implements ServletContextListener {

     private ScheduledExecutorService scheduler;

     @Override
    public void contextInitialized(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
        scheduler = Executors.newScheduledThreadPool(4);
        scheduler.scheduleAtFixedRate(new MinhaThread(), 0, 10, TimeUnit.SECONDS);
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
        scheduler.shutdownNow();
    }

}

Estou rodando a aplicação em um simples TomCat, não uso TomcatEE.
Resultado Desejado:

Ao iniciar o programa, a primeira thread será criada. 10 segundos depois, apesar da primeira thread ainda estar no loop, a segunda thread também é criada e começa a rodar.
Comment: @CarlosHeuberger na realidade, eu quero uma nova instancia da classe "MinhaThread ". Ou seja, vão ter 2 "MinhaThread " rodando ao mesmo tempo. Talvez eu esteja errando ai?
Comment: @CarlosHeuberger entendi!! Você poderia me dar um exemplo breve dessa solução como resposta? Em paralelo vou dar uma procurada aqui e ver se consigo resolver também.
Comment: @CarlosHeuberger Vou tentar, obrigado!
Comment: @CarlosHeuberger Implementei sua solução funcionou, minha única preocupação é: O fato de criar uma thread para chamar outra thread pode me causar algum problema? Ou a "outra thread" tendo como única função chamar o "minha thread" irá fazer a chamada e "morrer", portanto não existe problema?
Answer: Não é possível e isso é salientado na documentação.

If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.
Se a execução da tarefa demorar mais do que o seu período, as execuções subsequentes poderão começar mais tarde, mas não serão executadas simultaneamente.

Uma possível abordagem(1) é o scheduler usar um outro Executor para executar a tarefa "demorada/longa".
@WebListener
public class Executor implements ServletContextListener {

    private ScheduledExecutorService scheduler;
    private ExecutorService executorService;

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        // TODO Auto-generated method stub

        executorService = Executors.newCachedThreadPool();
        scheduler = Executors.newScheduledThreadPool(4);

        scheduler.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                executorService.submit(new MinhaThread());
            }
        }, 0, 10, TimeUnit.SECONDS);

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
        scheduler.shutdownNow();
    }

}

Quando o scheduler dispara, a tarefa MinhaThread é executada recorrendo a um Executor do "tipo" CachedThreadPool.
newCachedThreadPool() cria um Executor que usa uma thread pool. Novas threads são criadas se necessário ou as anteriormente criadas são utilizadas se disponíveis.
Nota: O nome da classe MinhaThread deveria ser MinhaTarefa ou MyTask.
(1)Mais ou menos o sugerido pelo CarlosHeuberger no seu comentário.
Comment: muito obrigado pela resposta!! Vou testar e dou um feedback
Comment: Alterei para sua solução, funcionou de acordo!
Answer: A solução proposta pelo @Carlos Heuberger realmente funcionou:
Main thread
package backgroundProcesses;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimerTask;

public class MinhaThread implements Runnable {

    @Override
    public void run() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        System.out.println("FOI, COMEÇOOU A THREAD: " +  sdf.format(cal.getTime()));
        int i = 0;
        while(i < 1000000000) {
            int a = 1;
        }

        System.out.println("CHEGOU AO FIM");
    }

}

Thread Secundária
package backgroundProcesses;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class OutraThread implements Runnable {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("ENTROU NA THREAD SECUNDARIA");
        new Thread(new MinhaThread()).start();

    }

}

Executor
package backgroundProcesses;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class Executor implements ServletContextListener {

     private ScheduledExecutorService scheduler;

     @Override
    public void contextInitialized(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
        scheduler = Executors.newScheduledThreadPool(4);
        scheduler.scheduleAtFixedRate(new OutraThread(), 0, 10, TimeUnit.SECONDS); //roda a qualidade a cada 5 minutos.
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
        scheduler.shutdownNow();
    }

}

Console:
ENTROU NA THREAD SECUNDARIA
FOI, COMEÇOOU A THREAD: 11:54:33
ENTROU NA THREAD SECUNDARIA
FOI, COMEÇOOU A THREAD: 11:54:43
ENTROU NA THREAD SECUNDARIA
FOI, COMEÇOOU A THREAD: 11:54:53
ENTROU NA THREAD SECUNDARIA
FOI, COMEÇOOU A THREAD: 11:55:03
ENTROU NA THREAD SECUNDARIA
FOI, COMEÇOOU A THREAD: 11:55:13
ENTROU NA THREAD SECUNDARIA
FOI, COMEÇOOU A THREAD: 11:55:23

Eu vou deixar a pergunta aberta para ver se alguma outra solução venha à aparecer, mas por hora irei implementar essa aqui.
Comment: Essa implementação parece-me errada. Pode aparentemente funcionar porque o teste não decorre com o tempo necessário para o evidenciar(causado pela razão da sua pergunta). Note que a cada 10 segundos a `OutraThread` está a definir um `scheduleAtFixedRate` que executa `MinhaThread` a cada segundo.
Comment: @ramaral Editei a classe "OutraThread", é assim que estou fazendo no momento, o que acha?
Comment: Julgo que funcionará. No entanto é preferível usar `Executors.newCachedThreadPool()`, já que ele reaproveita Threads criadas quando disponíveis.
Comment: @ramaral legal! vou alterar meu código!


How is the optimal probability cut-off in a ROC defined by the R package Epi?

Question: The plot below was created by R package Epi::ROC for a binary classification problem. There is an optimal cut off or threshold for the classification probability at which sensitivity and 1-specifitiy are balanced in some optimal way (called ps3 in the plot). My question is how this point is defined mathematically in this case and if there are other ways to define it.
Answer: Epi::ROC defines optimal cut-off as a point for which sum of Sensitivity and Specificity is maximized.
See, that Sensitivity and Specificity play similar roles here. But, in general, they don't have to. Sometimes were are more interested in finding highly sensitive test and don't care  about Specificity that much (or vice versa). This is the case when we know that False Positive result is much (or less) "bad" than False Negative.
Then we need other expression to maximize. It can be some weighted average of Sensitivity and Specificity.
I never found any general guidelines of how to determine desired balance between Sensitivity and Specificity (that, of course, doesn't mean it doesn't exist). I read a few articles in which authors calculated cost of False Positive and False Negative result of test and derived weights from it. But, I think it is rarely doable...


Outputting multiple content fields all wrapped in a div

Question: I'm trying to wrap multiple field items in an HTML container.
So let's say I have "Blog" content type. I have field1, field2, field3, field4 and field5 for this content type.
I want to output field2, field3 and field4 wrapped together in a DIV.
I've been Googling and tinkering for the past 3 hours and I haven't gotten anywhere.
Any help out there?
Drupal 7, Zen subtheme.
I read this and didn't have any luck here either:
Wrapping multiple cck fields into a single div tag for theming?
Answer: Multiple ways to achieve this.

By creating a node tpl file for that particular content type.
By creating view.
But i think the best and easiest way is creating group in manage display. Check field group module.

Procedure to create group.

Go to structure->content types->content(ex-blog)->manage displays.
Add a new group of div type.
Drag the required field like field2 , field3 etc under it.

Print in tpl file.
It will be easy to find out if you will update the code snippet of node--case-study.tpl.php file.
I think you need to first check by printing
echo '
';
print_r($content);

and use this for

  <?php print($content['field1']); ?>

 <?php
    print($content['field2']);
    print($content['field3']);
    print($content['field4']);
 ?>

Comment: Noting that unlike @PapaBear, I could (with the field group module) output extra HTML to the actual page by making and configuring the field group in Manage Display (though I only tried this in an 8 site). Noting this in case the comment raises doubts for other users as it did for me.
Comment: Thanks but the field group module doesn't actually output any extra HTML to the actual page. Creating a view won't allow me to wrap multiple fields in a DIV to my knowledge and I'm struggling with the node.tpl.php method.
Comment: ok can you let me know what problem you are facing with node.tpl.php.
Answer: Create a empty file with name [node-ContentType.tpl.php] for your content_type node template file and place it at sites/all/themes/your_theme/templates. Flush all caches.
In this file you have the access $node variable which contains the all fields in that node. Now wite your custom html to breakdown your fields into differnt divs.

  <?php print $node->field1[0]['value']; ?>

 <?php print $node->field2[0]['view']; ?>
 <?php print $node->field3[0]['view']; ?>
 <?php print $node->field4[0]['view']; ?>

  <?php print $node->field5[0]['value']; ?>

For further parameters details, try this.
Comment: I tried this and I receive this error:

Notice: Undefined offset: 0 in include() (line 11 of C:\xampp\htdocs\drupal\sites\all\themes\cp\templates\node--case-study.tpl.php).

If it helps to know I also have a page--case-study.tpl.php, not sure if these might be conflicting.


Probability My Opponent Has a Specific Scrabble Letter Mid-Game

Question: How does one calculate the probability that an opponent would have a specific letter mid-game?
For example: my opponent would have to have a T in his rack in order to hit the Triple Word Score off the word I am considering playing. There are 50 tiles still in the bank (so, that doesn't include the 7 tiles currently on each of our racks.) There are 7 Ts total in the game (I'm actually playing Words With Friends), 2 Ts have been used on the board and I have 1 T in my rack, leaving 4 Ts unaccounted for. So how would I approach calculating the odds that my opponent currently has 1 or more of the remaining 4 Ts on his rack?
Thank you!!!
Comment: The answers given assume that the contents of your opponent's rack are random. Strictly speaking, this isn't really true unless your opponent cleared their rack on their last turn. To give a fully correct answer to this question, you need to know a lot about your opponent's strategy...
Comment: I hope you can clear your bench!
Answer: I don't think you can get a definite probability out of that without some very strong assumptions about your opponent's playing style.
The other answers basically assume that the tiles you can't see are distributed randomly between the bank and your opponent's rack. This assumption doesn't seem to be warranted here -- which tiles your opponent holds will depend to some degree on which ones he prefers to play.
Suppose, for example, that your opponent follows a strict strategy of holding on to any T tile he gets until he can hit that particular triple-word field with it. (I grant you that's a somewhat strange strategy, but it's possible within the rules of the game). In that case, if any of the Ts currently on the board were played by your opponent, he'll have another one ready with probability 1.
Even if you don't remember who played what, an opponent who tends to hold on to his T's will be more likely to have one than an opponent who doesn't like holding T's and attempts to play them as soon as he can.
And then there's the question of how many chances to play a T your opponent has had (and recognized) recently, which your description of the state of the game doesn't say anything about at all ...
Comment: @ncmathsadist: The probability the the opponent holds a T _now_ certainly depends on how likely the opponent would have been to play a T if he had one in the _previous_ turns. That does need an assumption about the opponent's playing style.
Comment: If I could post a photo of the board I would, but I didn't care as much about the game as I did about realizing I didn't know how to approach the problem I created for myself from it - someday I hope to become a math teacher and I want to incorporate games into the classroom as much as possible!
Comment: Whilst that is true, the OP's question did ask about the probability of the possession of a T.  This entails no assumption about the opponent's play.  OP did not ask the odds of the T being actually played, as the opponent might have a bench-clearer elsewhere on the board and he'd likely prefer that.
Comment: @Jane: The unknown state of the board is not the real problem, just some icing on top. What's important is that the opponent has had chances to make strategic decisions that influence the probability, and his strategy is _unknown but not random_. This is not an uncommon situation to end up in: We have a nice pretty _model_ of the world that we can calculate things about, but we _don't know_ how well that model matches reality. Dealing with those situations is arguably a much better learning experience (for you or your eventual students) than any particular computation method.
Answer: There are 57 tiles unbeknownst to you, seven on your opponent's bench and 50 in the boneyard.  There are 4 "loose" Ts.
$$P(\hbox{oppponent has > 0 Ts}) = 1 - P(\hbox{ opponent has no Ts}).$$
The opponent has 7 tiles. There are ${57\choose 7}$ possible holding of tiles for him and ${53\choose 7}$ that are T-less. Can you do the rest?
Comment: So, would it be 1- (53/57)^7 = about 40%?
Comment: The other answer completed the calculation.  About 40% is right.
Comment: I care more about the approach than the right answer, is multiplying the probability of T-less tiles times itself 7 times a valid approach or did I just get lucky that it happened to be close?!
Comment: At this stage, you use a little accuracy. But it's easy to get into dangerous waters. Since the calculation is simple, you should unroll the binomials.
Comment: Thank you, I completely forgot how to work with binomials, but I will start searching online now to re-learn them :)
Answer: There are $50+7=57$ letters whose place is unknown to you at the moment (they might be in the bank, they might be in his rack), out of which $4$ are "interesting" and you know he has $7$ letters in his rack.
The binomial coefficient $\binom{57}{7}$ tells you the total number of possible racks he can have (you "choose" $7$ out of $57$ tiles). Out of these, $\binom{53}{7}$ are good for you; they don't put any of the "interesting" letters in his rack. The ratio of these two quantities is the probability that he has no "interesting" letter at all in the rack; and if you subtract it from $1$, you'll get the probability he has at least one.
Putting it together and evaluating yields $$\frac{\binom{53}{7}}{\binom{57}{7}}=\frac{220.127.116.11.49.48.47}{220.127.116.11.53.52.51}=\frac{18.104.22.168}{188.8.131.52}\approx 58\%$$
So, he has about $42\%$ chance of having at least one T in the rack.


Filesystem Hierarchy Standard - Where to put sourceable functions?

Question: I have a few bash scripts running system checks. These scripts source configuration options from a file /etc/healthchecks/config.
Along with the config file, I have a shared functions file. The scripts should be able to source that file and run the functions therein.
Based on the Filesystem Hierarchy Standard, where should I put the shared functions file? It's not a configuration, so it doesn't seem like it belongs in /etc, but it's also not being executed so /usr/bin seems incorrect. Maybe /usr/lib?
Answer: You should put your healthchecks executables in /usr/local/bin or in /opt/bin. If you see your folder /opt is empty, means your linux distribution doesn't use it. So, the suitable place would be /usr/local.
/usr/local and /opt are where every "manual" package/program must be placed. /usr is for packages managed by package managers (i.e, dpkg). /opt is the "standard place" for manual packages according to FHS, but debian distros use /usr/local instead.
For configuration files, they must be placed on /usr/local/etc, since /etc is for configuration files of automatic packages and other system programs.
The correct place for your shared functions is then /usr/local/share (/usr/share is for shared files of automatic packages). Every file which is designed to be read-only and independent of the arquitecture belongs to /usr/share or /usr/local/share (if they are own by "automatic" or "manual" packages).
/usr/lib is for dynamic and static binary libraries (.so or .a), and not for "interpreted" libraries/functions.
Usually, interpreters have different subfolders in /etc/share/ for each version, and inside each version folder, different folders for scripts, locales, tests, samples and so on.
If some day you create an official repository for your package healthchecks, you could migrate your /usr/local/healthchecks contents to /usr/healthchecks and /etc/healthchecks.
Comment: I went ahead and deleted my answer because 1) yours covers the topic well enough, and 2) `libexec` technically isn't part of the FHS yet. It's present in the [3.0 draft](http://comments.gmane.org/gmane.linux.lfs.beyond.devel/21616) and [Redhat's Overview of the FHS](https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Storage_Administration_Guide/s1-filesystem-fhs.html), but isn't technically part of the FHS yet. (use it if you want, basically)
Answer: I generally try to keep site specific things outside of these reserved system areas.  You might consider using your own top-level directory hierarchy as when using system areas special site files can easily get lost or forgotten during system evolution.  Another possibility could be /usr/local/etc.....


Alter the "From" address contact form

Question: I'm trying to alter the email and change the default "From" address to a different email address.
function mymodule_mail_alter(&$message){
   $message['from'] = 'firstname.lastname@example.com';
}

When I test send a test email through my site Contact Form.  The email "From" address is still using the default site email not the one I altered in my module.
Is there another way to make this work?
Thanks for your help.
Answer: I ran into this issue myself. I got it to work in the following way:
function mymodule_mail_alter(&$message){

  $message['from'] = "email@example.com";
  $message['headers']['From'] = 'Name TO SHOW <email@example.com>';
  $message['headers']['Sender'] = $message['headers']['Return-Path'] = $message['from'];
}

However, like you,  I thought adding $message['from'] = 'firstname.lastname@example.com'; is the way to go and I think it should -Perhaps other folks can chime in and let us know if this is a bug?
In any case, it seems drupal does more processing and checks to verify the from email address and if it does not pass all the checks it sets it to the sitemail, or the mail library just use the other headers. Note I think this behavior may differ based on which mail library you are using. In my case, and I presume in yours, its PhpMail.php.
The solution above worked but I am not sure if it's the most appropriate or if it would work for others who are using different mail managers..
Comment: `$message['headers']` is what gets used by default (using the default PhpMail plugin) for all the mail headers, including the 'From' header. `$message['from']` is ignored by default. This is as designed. It *is* possible that a different mail plugin might not do the same thing, but it's safest to just assume all plugins do the same thing as the default plugin.

Alter the "From" address contact form


How to check if a View was cached?

Question: Is there a simple way to check (example: see from UI or browser developer tools) if a rendered View was retrieved from cache or just generated on the page load?
This would need to work for every view display, like a View Content pane embedded in a Panels page.
Would this need custom code or is there a module or any-other-simple-way for this?
Thanks
Answer: Caching only works for anonymous users (people who are not logged in).
So, a simple test would be to add new content to your view or make a change to your view. Ex: change your view title.
On another browser have your page open, but as anonymous. If your view doesn't change, it means the cache worked.
The View will NOT change to anonymous users until you clear the cache.
Comment: Caching only works for anonymous users: THAT IS OT TRUE.
For the rest.. well, it is something trivial which I knew, but of course not what I was asking for. I can't change anything on every single view, save it, check if it changed, and then revert every changed view and save..

How to check if a View was cached?


What is this sound, instrument? (Rheingold, Wagner)

Question: I am currently composing something and I really want to have this sound in my piece. It sounds like a small hammer hammering on metal.

It starts at 1:08:07 (Verwandlungsmusik, Rheingold)
What is this and is it an instrument at all?
Comment: maybe a brake drum?
Comment: @Legorhin I admit I never heard of it. https://www.youtube.com/watch?v=VCK9fZuuTnw Are you talking about this one? Because it sounds different
Comment: try https://youtu.be/uZbJ1Ajzt5Q instead
Comment: @Legorhin. ok it sounds already nearer. Could Wagner have used it 150 years ago?
Comment: The brake drum was invented in 1900 so no, the original music wouldn't have referred to that specific thing to hit with a stick.
Comment: More things to hit than you can ever know what to do with - [SoundIron Rust](https://soundiron.com/products/rust-1) [there's a 1, 2 & 3]
Answer: Wagner actually specified in the score for 18 anvils to perform this section. Since the scene is moving down to Nibelheim (and later back up from Nibelheim) where the Nibelungs are hard at work smithing the titular gold, Wagner wanted to represent this sound as accurately as possible.
If you're looking for the specific instruments used in this specific recording, I'm not sure I can help. But the intent was for these to be 18 anvils.
For another rendition, here is the famous Solti recording with Vienna.
Comment: @NickQuant There are 3 anvil instruments included in EastWest Quantum Leap Symphonic Orchestra, a great library in general. I'm not sure how easy it is to import the PLAY engine into Sibelius (I use Cubase).
Comment: Thank you! Yes, I also wanted to have the sound of the anvil. There is no chance, that I will get it easily in my Sibelius, right?
Comment: Unfortunately I don't have Sibelius, so I can't address that. But hopefully someone else can!
Comment: I meant if you know, whether I can find those sounds somewhere else in some VST
Answer:
It sounds like a small hammer hammering on metal.

Good ear;  while Wagner originally called for anvils, modern productions use metal hammers on heavy pieces of scrap metal to create this effect.  Here's the Victoria Symphony, using I-beams and manhole covers, and the Halle Symphony using steel plates and I-beams.  I once played with a group that used brake drums for the same effect;  you can hear the recording here.
Comment: @NickQuant:  I actually played trombone in that group, not percussion.  I remember that I played the piece, but not much more.
Comment: Thank you for the links! Do you play in the "Lord of the rings" part as well?
Comment: The interesting thing is that a brake drum, though loud and metallic, is a poor substitute for an anvil sound.  Actual anvils create a high pitched "ping" sound, while brake drums produce a lower pitched "clank".  Absent a blacksmith lending us an actual anvil, we used spare counterweights from our stage's fly system.  They were nice and thick (a couple inches), which gave that high ping sound.
Answer: One good substitute for an anvil that I have found is the "double-shoulder railroad tie plate":

(image source)
If you're a little resourceful, you can find these discarded by the hundreds near old rail lines. Clean up the rust and paint it if you like.
Put it on a firm support resting on the shoulders (i.e., upside-down). You can control the amount of "ring" by striking it directly above the shoulders, or farther away. A small ball-peen hammer makes a good striker.
Answer: Yes, the piece is scored for anvils. It's the Nibelungs forging their gold. In the Met's documentary, "Wagner's Dream" there is a shot of the orchestra playing the anvils. As part of their production of The Ring, the Met offered this section as a downloadable ringtone. Hummm. Perhaps it was the original Ring-tone?
Tom Hayes


Almost sure convergence of a product of random variables

Question: Let $X_1, X_2, ...$ be a sequence of random variables such that:
$X_i = \begin{cases} 1 &\mbox{with probability } p = 1-1/n^2 \\
2 & \mbox{with probability } p = 1/n^2 \end{cases} $
and let $Y_n=\Pi_{i=1}^n X_i $. Show that $Y_n$ converges almost surely to some random variable $Y$.
I already know several methods of proving a.s. convergence to a constant. However, I do not know how to establish convergence to a non-constant random variable except for definition which does not seem to work in this case.
Answer: The $Y_n$'s fail to converge exactly when infinitely many of the $X_i$s are $2$. By Kolmogorov's zero-one law, the probability of this happening is either $0$ or $1$.
However, since $\sum_{n=1}^\infty n^{-2}$ is finite (see the Basel problem), from some point the probability that there's even one more $2$ in the sequence of $X_i$s will be less than $1$ -- so the probability that there's infinitely many of them cannot be $1$. Therefore it has to be $0$.
Define the random variable $Y$ to be the limit of the $Y_i$s in outcomes where they converge, and $42$ otherwise. Then the $Y_i\to Y$ almost surely.

Instead of the slightly handwavy "from some point" argument, one can also show similarly that the probability of the $Y_i$ sequence being precisely $(2,2,2,2,\ldots)$ is at least $e^{-(\pi^2/3-2)}$ (because $\log(1-1/n^2) \ge -2n^2$ for all $n\ge 2$). Since this sequence converges, "the $Y_i$s converge" has positive probability, and again thanks to Kolmogorov's 0-1 law, this positive probability must be $1$.


I need to have a img vertical centered in a div, how?

Question: for the reference: Check this:
    http://jsfiddle.net/blackvibes/mVYwd/
I'm creating a website for mobile (it's pretty sure not the best way to do it.. but anyway) I'm using percentages all the way, since it should be relatively equal in size on any mobile (portrait) screen.
I've tried numberous things, such as:
#header img {
vertical-align:middle;
padding-top: auto;
padding-bottom: auto;
margin-top: auto;
margin-bottom: auto;

}
But I still can't get it working.
The only thing that will be in that div is that single image, which presents the school logo.
Thanks in advance!
Answer: remove width and height from img tag and
#header{text-align:center;}

Answer: Use your image as the background of your #header id:
#header img {
    background:url(your_image.jpg) center center no-repeat;
}


select dropdown displays utf-8 characters but not displaying chinese characters

Question: The coding is done in cakephp.
There is a variable defined called types which stores an array populated from the database itself.
The site is in chinese, so the database stores utf-8 characters.
When we are trying to display the dropdown, it does not display the chinese characters
but the utf-8 characters.
If I do a print_r of the that variable types, it prints out the chinese characters but does not display the same in the dropdown.
Answer: Do you have following in your layout.. if not then try adding it:

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />

Hope it helps
Comment: for option value it displays the correct chinese characters but between the option tags it does not like e.g displays utf-8 format
Comment: are you getting the values from database..?
Comment: try using normal select tags instead of using cakephp's input tag for select, and it might solve your problem.


How to track the state or activity on the app

Question: I am making an ipad app and i want that when user performs any activity in app it must be recored or stored like in my app there are video and catalogues so if user open videos section and watches any video that should be stored as user watched video at this and then move to catalog etc like this any idea how to implement this thing.
Answer: You have to use sqlite or coredata to save the name of videos watched by user.
You can add a record to your table(watchedVideo table)when user clicks on a particular video from videos list.
And then show the list of video in table(watchedVideo table) in ur catalogue screen.
Comment: its just video i know we can do this what about other things mean what evere screen he visits or button clicks all should be recorded


Minimize $F[u(\cdot)]=\frac{1}{2}\int_0^1f(u'(x))dx$

Question:
Let $C^2\ni f:\mathbb{R}\rightarrow\mathbb{R}$ be a strictly convex function and $F$ be the functional defined by $$F[u(\cdot)]:= \frac{1}{2}\int_0^1f(u'(x))dx,$$ acting on functions in the set $\mathscr{A}:= \{u:[0,1]\rightarrow\mathbb{R}:u\in C^1, u(0)=A,u(1)=B\}$.
What is the minimizer of $F$ on $\mathscr{A}?$

I've reduced the problem to $f'(u'(x))=2a$ where $a\in\mathrm{R}$ using Euler-Lagrange. However, I don't know how to solve this differential any further. I have a feeling I should be using the fact that $f$ is strictly convex, but I don't know how it would help.
Any advice on how to proceed would be appreciated! Please don't spoil the answer :)
Answer: Since $f$ is strictly convex, $f^\prime$ is strictly... what?
What does that tell you about $u^\prime$? What does that tell you about $u$?