Need example : D7 + XPath parser to import (mediawiki) XML - xpath parser settings?

Question: I've installed XPath/Feeds/D7, but I don't know how to configure XPath parser settings.
Maybe someone can help me to set it right.
I just want to inject <title> and <text xml:space="preserve"> to my node.
I need help to configure my XPath Parser settings : admin/structure/feeds/edit/my_import/settings/FeedsXPathParserXML
I've the following XML structure :
<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.3/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.3/ http://www.mediawiki.org/xml/export-0.3.xsd" version="0.3" xml:lang="fr">
  <siteinfo>
    <sitename>Site Name</sitename>
    <base>http://domain.net/index.php/StartPage</base>
    <generator>MediaWiki 1.15.5-1~bpo50+1</generator>
    <case>first-letter</case>
    <namespaces>
      <namespace key="-2">Media</namespace>
      <namespace key="-1">Special</namespace>
      <namespace key="0" />
      <namespace key="1">Chat</namespace>
      <namespace key="2">user</namespace>
      <namespace key="3">Chat user</namespace>
      <namespace key="4">domain.net</namespace>
      <namespace key="5">Chat domain.net</namespace>
      <namespace key="6">files</namespace>
      <namespace key="7">Chat files</namespace>
      <namespace key="8">MediaWiki</namespace>
      <namespace key="9">Chat MediaWiki</namespace>
      <namespace key="10">Model</namespace>
      <namespace key="11">Chat model</namespace>
      <namespace key="12">help</namespace>
      <namespace key="13">Chat help</namespace>
      <namespace key="14">category</namespace>
      <namespace key="15">Chat category</namespace>
    </namespaces>
  </siteinfo>
  <page>
    <title>Drush</title>
    <id>579</id>
    <revision>
      <id>1637</id>
      <timestamp>2012-05-25T14:51:51Z</timestamp>
      <contributor>
        <username>admin</username>
        <id>1</id>
      </contributor>
      <comment>/* Install Drupal with Drush */</comment>
      <text xml:space="preserve">Drush is a command line utility.

=Install Drupal with Drush=
To install drupal with drush :
 drush site-install standard --db-url=mysql://username:pass@localhost/databasename

[[category:Drupal]]</text>
    </revision>
  </page>
  <page>
    <title>Memcache</title>
    <id>586</id>
    <revision>
      <id>1287</id>
      <timestamp>2012-02-12T17:43:32Z</timestamp>
      <contributor>
        <username>admin</username>
        <id>1</id>
      </contributor>
      <comment>Do it under Debian</comment>
      <text xml:space="preserve">=Install=
==Debian==
===Memcache Server===
To install :
 aptitude install memcached

Read and change ''/etc/memcached.conf''.
===PHP5 / PECL===
Install memcache PECL :
 php5-memcache
or
 pecl install memcache

Restart Apache.

===Drupal===
* InstallMemcache module in Drupal.
* Change ''settings.php'' :
<source lang="php">
$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['memcache_key_prefix'] = 'site_prefix';
</source>

Read : http://drupal.org/node/1131458

[[category:Linux]]

[[category:Drupal]]</text>
    </revision>
  </page>
</mediawiki>

Optional task : How can I convert "=" to
, "==" to
, space before start of line to
, [[category:xyz]] to Tags, etc ... ?
Comment: While I understand that you are doing this within the context of a Drupal module, your question is really about XPath, and has nothing to do with Drupal. I call off-topic. Your "optional task" however, should be opened as a separate question. I could actually write up something on that myself. I'll try and find the time for that later. :)
Comment: I don't completely agree, as the Feeds module has its own logic on top of XPath, so perhaps it's borderline, but maybe not OT. As for the optional task, [Feeds Tamper](http://drupal.org/project/feeds_tamper) could probably be of use.
Comment: @Countzero : Thank you, I'll gonna test Feeds Tamper.
Answer: Context should be : //Mediawiki/page,  Title field should be title and Text should be revision/text.
Comment: It work great, thank you !! I think it can help everyone who want to import XML content to Drupal.


Como acessar a versão de um arquivo .exe com JavaScript?

Question: Gostaria que me ajudassem a resolver um pequeno problema.
Preciso acessar a propriedade chamada "versão" no meu arquivo, e sei que isso é feito em Javascript. Mas não sei qual tag usar, ou o que fazer para chegar a isso. Como posso fazer isso?
Comment: Um arquivo tipo .txt, .doc, imagem/*? Arquivos desse tipo?
Comment: Não.. um arquivo .exe
Comment: Através de Javascript não é possível. Tudo que você consegue acessar é o tamanho, tipo, data da última modificação e o nome, veja https://w3c.github.io/FileAPI/#dfn-file
Comment: você poderia indicar algo possível para verificar  a versão dele?
Comment: a claro.. mas de preferência uma que faça ligação com WebDesing
Comment: Existem perguntas no [so], por exemplo https://stackoverflow.com/questions/16524899/getting-file-creation-date-and-author-in-javascript-or-html?rq=1, que mostram que não é possível.
Answer: Através de JavaScript somente, não existe uma maneira de acessar a versão de um arquivo .exe.
Se você está usando File(), de acordo com a própria W3C, os únicos valores retornados de um determinado arquivo são:

A sequência de bytes;
O tamanho do arquivo;
O nome do arquivo;
O tipo de arquivo;
A data de última modificação;

Como dito nos comentários também, reforçando a resposta:

[...] Nem mesmo o path fica exposto [...]

Pelo comentário já subintende-se que você não consegue descobrir nem o caminho real que foi realizado o upload. Essa questão da privacidade do usuário, é levada realmente muito a sério pela W3C.
Pode ler mais sobre nessa outra pergunta relacionada: Como descobrir por qual pasta o usuário realizou upload?
Comment: Sim @JeffersonQuesado, eu fiz uma pergunta assim a muito tempo https://pt.stackoverflow.com/q/187157/66203, e recebi uma resposta explicando. No próprio [pt.so] mostra C:/fakepath na hora do upload.
Comment: Bem antiga @JeffersonQuesado, uma das minhas primeiras xD.
Comment: Só para deixar claro, nem mesmo o path fica exposto. Ele fica escondido debaixo de um fakepath
Comment: ótimo pergunta, por sinal
Comment: Alguém acha possível fazer a mesma coisa porém em outra linguagem.. tipo php?
Comment: @Alis com PHP acredito que seja possível. Dê uma olhada no [`stat()`](http://php.net/manual/pt_BR/function.stat.php)
Comment: Poderia ceder mais algumas dicas?


Cheap electric guitar - fix or replace?

Question: TL:DR version:  cheap guitar needs work.  Fix it or replace it?
Hi - After many years of wishing I could just magically be able to do it, I've finally decided it's time to learn to play guitar.  Around 18 months ago someone bought me an electric strat-style guitar so this week I hit youtube fairly intensively and got the truss rod adjusted, the action set, the pickup heights set, etc etc.  After all that (and bear in mind I can play at most 5 chords, 6 if you gimme a minute to get the F) it sounds.... ok'ish.
It's really rather noisy (not the good noise, the bad noise) with the volume / gain turned up, and awfully 'twangy' sounding.  Furthermore I've found that I have a couple of high spots on some higher frets (same note across multiple frets), and one of the bridge pickup height adjustment screws doesn't - half the pickup appears to be floating.  To be fair a bit of research indicates that it's a £70 guitar - I'm not fussed about price but thats just to indicate the components probably arn't top notch.    Don't misunderstand - it actually doesn't sound half bad if I get the knobs in the right place but I'd like to know that as I learn I can make it sound good, rather than be hampered by equipment from the get go.  I'm sticking it through a Vox Amplug2 AC30 or my PC running Guitar Rig 5 (it came with an amp - that just appears to be a box that only makes a 'brrrrrpppppppt' noise).
So, the question.  I need to spend some money but I'm not willing to splurge.  Should I level the frets, put some decent (budget) pickups in (Ironstone?  Wilkinson?), add some shielding, maybe change the pots and caps, or should I just go get a new guitar?  The latter option would ideally be something like the Epiphone Les Paul Special II - only £140 but with excellent reviews and apparently a great starter.  If I can make my cheapy-strat into something I'll enjoy playing I'll do the work (assuming I don't arse it up) but I don't want to buy pickups, a crowning file, pots etc only to find it still sounds like crap no matter how much I improve.  However, I don't want to blow more money than necessary on something that I may well give up on in 2 months.
Sorry this is a bit long but I really would value the opinion of folks who actually know what they are talking about!
Thanks!
Edit:  I'm not trying to get to professional level equipment - I just want a beginner plank that doesn't handicap be by being partially broken.  I'm really looking to know if the improvements I've listed will a). do the job, and b). are doable for someone with no real experience.
Comment: The edit to your question makes it opinion based and therefore outside the guidelines for questions on this site.  Which guitar is best for you is very subjective and I would encourage you to play several to see which one you like best overall.  I would also encourage you to edit the question again and remove the question about specific equipment recommendations.  Good luck.
Comment: Do you have any sentimental connection with this axe?. I still have the first axe I bought and have upgraded it a few times even though it probably would have been cheaper just to buy something new.
Comment: No real sentimentality.  Can't get enough of a tune out of it currently to get all misty eyed!
Comment: Are you insterested in learning more about modifying, making, or fixing guitars? If yes, then you might keep it as something to do some learning on. If you don't want to DIY, then replacing it will keep your sanity intact better and for longer.
Answer: You might find that the faulty spots on the high frets don't impede your practice very much. After all, there are plenty of notes that work, which you can use to practice most pieces of music. :)
Since you set up the truss rod, you probably checked the intonation.
One major difference between Strat and Tele on the one hand, and Les Paul on the other is the scale. Les Paul has a shorter scale than Strat and Tele. Because of the difference in scale, the string widths and/or tensions are also different. They play differently and sound differently.
About the twang, my suggestion is to first try and see if you can cheaply get your current setup to a decent level that will allow you to practice effectively. As @Andy suggested, plug your guitar into a setup that works. If you don't know a player that has such a setup, another way would be to take your guitar to your local music store, pick up a guitar from the store that works well (for example a regular Fender American Strat for a thousand dollars), plug it into a couple of amps for 100 or 150 dollars, and find the amps that work ok. Then, into the same amp and the same cable, plug your guitar.
If it sounds decent, then your guitar is not responsible for the twang. If it does not, then:
 - There might be a ground connection problem in your guitar. This is fixable with a bit of soldering. (Some people solder, I don't.)
 - If your guitar has some exotic brand name that no one has heard of, it might have an unusual impedance. In this case it will not work well with regular guitar amps (which have "Hi-Z" inputs for regular electric guitars). But it might work well if you directly plug it into a "line" input in a mixer (as opposed to a Hi-Z input - many mixers have both), a line input in an active speaker like those used for keyboards, or a guitar amp for electroacoustic guitars. (However, in this case, most electric guitar effects pedals, which have Hi-Z inputs, might not work properly well your guitar. Do you plan on using effects pedals?)
If you find that your guitar works well with some Hi-Z setups OR Line setups (only in the case you don't need effects pedals), then you can use your guitar for practice.
Selecting what amp / mixer / computer interface to buy (how do you currently connect your guitar to your computer?) / how expensive / fixing your current setup / just buying a new cable, is a different issue. You can still buy something wrong.
There is nothing wrong about playing a cheap neck and body and a cheap pickup, as long as the quality is sufficient, the intonation is ok, your overall setup works fine etc.
Buying expensive pickups for a cheap guitar is a bit of a gamble though, in my opinion, because you might find afterwards that what you actually wanted was better neck and body. And even if you "recycle" your new pickups later when you buy a new guitar, expensive guitars already come with expensive pickups, so you would have two pairs.
Answer:
However, I don't want to blow more money than necessary on something that I may well give up on in 2 months.

Hmmm. Sounds like my first electric guitar apart from the high frets. (An Epiphone Strat copy from the 1980s, funnily enough. Weedy single coil pickups and a trebly bridge humbucker.)
I'd suggest:

fix the pickup height with blutak or tape. (The uglier it looks the better.)
if the high frets are near the top of the neck (above say the 15th fret?) see if raising the action a bit fixes it. (You don't need a super-low action... in my amateur opinion.)
You've only been practicing seriously for a week? I'd say stick with it for at least a month of regular practice before you commit to buying the new guitar.

Possibly try tapping the high frets down with a hammer, it might just work if you're lucky. (You must have a block of wood between!)
Final point: if you do decide your existing guitar is that cr*p, keep it cheap without upgrades as a "second guitar".  Then at the end of your first public gig, destroy it thoroughly and comprehensively. I can guarantee the people there will turn up for your second!
Edit: oh and bear in mind the current amplification arrangements may be a major cause of the sound problems. If you happen to know a player with a decent amp with a nice big speaker, you might find it sounds better... then you'll know something else useful.
Answer: You can end up spending a great deal of money upgrading the components of your entry level guitar.  Fret work is expensive, the tuning gears may not be the best quality, the pickups may not be first class and more.  But no matter how much you spend, it will still have a neck that might not be perfectly straight (could be twisted or bowed), and the finish may not be the highest quality.  And just because you spend a ton of money upgrading the parts, the value of the guitar will not go up nearly as much as what you spend!
So I would either keep your current guitar as a backup/practice guitar and spend the money on a new guitar that is already set up to play optimally and sounds the way you want it to.
Learning to play guitar can be challenging and frustrating.  Having a guitar that you enjoy playing because it feels comfortable to play and sounds good to your ears will make a huge difference in terms of providing encouragement in the face of the pain and frustration.  It sounds like you are not happy with your current guitar and I don't know if new components will change that as much as a new guitar.
Once you get a new guitar, you can sell your current guitar or keep it as a practice guitar - or just hang it on the wall in your music room for decoration.  I like having a beater guitar that I can use for practicing mundane drills such as scales - or when I'm simply trying to master a particular lick.  That way I'm not always wearing down the frets on my better guitar.
As you shop for a new guitar, be sure to try out several different models to see which one feels and sounds best to you.  What you like may be completely different than what I like.  Every guitarist has a different opinion on what feels best to them in terms of the neck, type frets, nut width, location of controls etc.  Every guitarist has a different opinion on what sounds best to them depending on their playing style and the type of music they play.  Every guitarist has a different opinion on what looks best to them.  Be sure you find a guitar you are happy with in terms of feel, playability, visual appeal, and sound.
Good luck with your new purchase and have fun on your journey towards becoming an expert guitarist ;-)!
Answer: A lot of guitarists fall into either the Strat. camp or the Les Paul camp. It's interesting that you have a Strat type of guitar already, but would prefer to maybe get a new Les Paul type. The two are very different in many ways, which is why some prefer one over the other - none is superior, just different. So my reasoning is that if you really liked the style and playability of the original 'Strat', why would you want to replace it with a Les Paul?
As Rockin says, go ahead and purchase the new instrument, at least then you can get on with learning to play. After a while, dust off the original, and fettle it, armed then with more knowledge of what you actually want from a guitar. Or, just hang it on the wall - they look good there, even if they don't play well!

Cheap electric guitar - fix or replace?


Cannot start httpd service with SSL

Question: Have an issue where I have installed new certificates on Centos 5 and modified the conf file for the following lines:

SSLCertificateFile /etc/pki/tls.certs/name.crt
SSLCertificateKeyFile /etc/pki/tls/private/name.key
SSLCACertificateFile /etc/pki/tls/certs/group.ca-bundle

But everytime i start the httpd service i get the following:
>     sudo service httpd start
>     Starting httpd: Apache/2.2.15 mod_ssl/2.2.15 (Pass Phrase Dialog)
>     Some of your private key files are encrpyted for security reasons.
>     In order to read them you have to provide the pass phrases.
>     Server servername.co.uk: 443 (RSA)
>     Enter pass phrase:
>     OK: Pass Phrase Dialog successful.                     [FAILED]

(Only have basic knowledge with CentOS, so please excuse me for my stupidity in advance!)
So question is what is failing? And where can i find the relevant logs to tell me this?
Comment: Is there any extended information about this in the Apache logfiles?
Comment: Have take a look at almost every logs in /var/log folder but don't even see any logs created for them. This server has been handed down with zero documentation unfortunately!
Comment: Enable debug logging and check if any of the debug logs contain any interesting data.
Comment: Have enabled the debug option but cannot see any logs being recorded. At a complete loss here!
Comment: What if you run the httpd binary manually? With `httpd -e debug`
Comment: @pkhamre thank you, exactly what i was looking for. Gave me a module location error and a phsyical file was missing. If you add this to the answers below, happy to tick it correct.
Comment: Np, answer submitted :)
Answer: Run the httpd binary manually with the debug-loglevel to see if you can get any more information from it.
httpd -e debug
Answer: Two possible solutions:

Use certificate pass phrase from certificate
Add pass phrase to your apache configuration - see https://httpd.apache.org/docs/2.2/mod/mod_ssl.html#sslpassphrasedialog
Comment: OP quoted: "OK: Pass Phrase Dialog successful.". So I would assume that this problem has nothing to do with the pass phrase.
Comment: I am using the pass phrase, that is entered correctly as you can see from the above output. Placing pass phrase in apache config file is a massive security risk for the certs.

Cannot start httpd service with SSL


Aplicação JavaFx com icone no system tray

Question: Estou criando uma aplicação JavaFX para realizar consultas em uma base de dados e salvar arquivos XML.
A aplicação irá rodar em tempo integral na máquina que esteja em funcionamento.
A aplicação possui uma interface visual criada usando JavaFX, para configurar os parâmetros das consultas a serem realizadas. Porém não preciso desta interface para deixar as consultas rodando.
Como posso deixar um icone na system tray para abrir a interface visual para configurar os parametros.
Answer: Segue um exemplo de uma classe para exibir o tryIcon:
<code>import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Jonathan CR
 */
public class IconSys {

    public static void main(String[] args) {
        final TrayIcon trayIcon; // declarando uma constante do tipo TrayIcon
        frmMenu menu = new frmMenu();
        // Aqui vamos testar se o recurso é suportado
        if (SystemTray.isSupported()) {

            //declarando uma variavel  do tipo SystemTray
            SystemTray tray = SystemTray.getSystemTray();

            //declarando uma variavel  do tipo Image que contera a imagem tray.gif
            Image image = Toolkit.getDefaultToolkit().getImage("src\\personal.png");

            //Criamos um listener para escutar os eventos de mouse
            MouseListener mouseListener = new MouseListener() {

                public void mouseClicked(MouseEvent e) {

                }

                public void mouseEntered(MouseEvent e) {

                }

                public void mouseExited(MouseEvent e) {

                }

                public void mousePressed(MouseEvent e) {

                }

                public void mouseReleased(MouseEvent e) {

                }

            };

            // Criamos um ActionListener para a ação de encerramento do programa.
            ActionListener exitListener = new ActionListener() {

                public void actionPerformed(ActionEvent e) {

                    System.exit(0);

                }

            };

            // Criamos um ActionListener para a exibir uma mensagem na tela ao clicarmos
            //em um item do menu.
            ActionListener mostramsglistener = new ActionListener() {

                public void actionPerformed(ActionEvent e) {

                    JOptionPane.showMessageDialog(null, "Meus Programas JCR.", "JCR", JOptionPane.INFORMATION_MESSAGE);

                }

            };
            ActionListener prog1listener = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    try {
                        String caminho = menu.prog1;
                        Runtime.getRuntime().exec("cmd.exe /c start " + caminho);
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(null, "Caminho do aplicativo não encontrado!");
                        Logger.getLogger(IconSys.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            };
            ActionListener prog2listener = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    try {
                        String caminho = menu.prog2;
                        Runtime.getRuntime().exec("cmd.exe /c start " + caminho);
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(null, "Caminho do aplicativo não encontrado!");
                        Logger.getLogger(IconSys.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            };
            ActionListener gadgedlisner = new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    try {
                        frmGadget frmGad = new frmGadget();
                        frmGad.setVisible(true);
                    } catch (Exception e) {

                    }
                }
            };

            //Criando um objeto PopupMenu
            PopupMenu popup = new PopupMenu("Menu de Opções");

            //criando itens do menu
            MenuItem mostramsg = new MenuItem("Exibir Informação");
            MenuItem prog1 = new MenuItem("Controle de Estoque");
            MenuItem prog2 = new MenuItem("Controle de Despesas");
            MenuItem gad = new MenuItem("Gadget");
            MenuItem defaultItem = new MenuItem("Sair");

            //na linha a seguir associamos os objetos aos eventos
            mostramsg.addActionListener(mostramsglistener);
            prog1.addActionListener(prog1listener);
            prog2.addActionListener(prog2listener);
            gad.addActionListener(gadgedlisner);
            defaultItem.addActionListener(exitListener);

            popup.add(mostramsg);
            popup.addSeparator();
            popup.add(prog1);
            //popup.addSeparator();
            popup.add(prog2);
            popup.addSeparator();
            popup.add(gad);
            popup.addSeparator();
            popup.add(defaultItem);

            trayIcon = new TrayIcon(image, "Programas Jonathan CR", popup);

            ActionListener actionListener = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //adicionar form aki

                    menu.setVisible(true);
                    //trayIcon.displayMessage("Action Event", "Um Evento foi disparado", TrayIcon.MessageType.INFO);
                }

            };

            //Na linha a seguir a imagem a ser utilizada como icone sera redimensionada
            trayIcon.setImageAutoSize(true);

            //Seguida adicionamos os actions listeners
            trayIcon.addActionListener(actionListener);

            trayIcon.addMouseListener(mouseListener);
            //Tratamento de erros
            try {

                tray.add(trayIcon);

            } catch (AWTException e) {

                System.err.println("Erro, TrayIcon não sera adicionado.");

            }

        } else {

            //Caso o item  System Tray não for suportado
            JOptionPane.showMessageDialog(null, "recurso ainda não esta disponível pra o seu sistema");

        }
    }
}
</code>


Expor um objeto ( baseado no request ) para toda aplicação

Question: Opa, não sei se é possivel fazer oque quero, mas vamos lá:
Tenho uma api em lumen que basicamente ler um header especifico do request e faz parse num arquivo YAML e transforma isso num array, só que como eu uso isto em varios controllers e classes diferentes eu fiz um função que recebe este header e  retorna o array, porem estou tendo que repetir isto em todo controller / classe, oque eu quero é:
Transformar essa "função" em algo global que eu possa chamar de qualquer método / classe tipo assim:
public function verifyemail(Cliente $cliente) {
  $email = $cliente->email
}

Onde cliente é a função que me retorna o array.
Tipo como o app() que eu posso usar em qualquer lugar:
app()->environment() == 'development'

Acho que fui claro, se não, me perguntem.
Comment: Acredito que toda classe que você define no Laravel tem acesso aos seus `helpers`, logo, você obteria os dados do `header` ao pegar todos os dados da requisição usando o `helper` [`request`](https://laravel.com/docs/5.7/helpers#method-request).
Comment: Caso o Lumen não dê suporte ao `helper` `request`, você pode passar o `helper` `app` no construtor da classe pelo `Service Provider` e salva-lá na classe. Há também a possibilidade de apenas adicionar um [`binding`](https://laravel.com/docs/5.7/container#binding) no `AppServiceProvider`, assim você não precisa criar um `Service Provider`. Depois, use `app(ClasseComAFunção::class)` para obter uma instância da classe no seu `Controller`, [documentação](https://lumen.laravel.com/docs/5.6/container).
Comment: Não é só você criar a função em um arquivo separado e depois dar um `include` nos arquivos?
Comment: Mas digo usando alguma feature do laravel / lumen, igual uma vez que li sobre Services Providers mas nao consegui entender direito
Comment: Já pensou em adicionar esse método num `Controller` personalizado e depois alterar todos os `Controllers` a seguir para herdar dessa classe. Ou apenas crie uma nova classe e adicione essa função de forma estática para essa classe, e adicione ele em algum [Service Provider](https://lumen.laravel.com/docs/5.6/providers) caso queira torna-lo um singleton.
Comment: A questão é esse Service provider pode depender de request ? pq esta minha logica depende do header que recebo no request
Answer: acho q nesse caso a melhor solução é colocar esse método no arquivo Controller.php e então todos os outros controllers da sua aplicação que extendem essa classe podem usar essa metodo normalmente.
Answer: Cria em App/Helpers um Helper da maneira que precisa exemplo:
<?php

namespace App\Helpers;

class ClienteHelper
{

    // Sua função estática
    static function verifyEmail(Cliente $cliente)
    {
         $email = $cliente->email
    }
}

Aí você poderá chamar de qualquer parte do código assim:
return ClienteHelper::verifyEmail($cliente_xpto);


Powershell behaves differently in VS Code terminal than normal terminal

Question: I have a script that pulls data from a web API like so:
$wc = New-Object System.Net.WebClient
$response = $wc.DownloadString("https://example.com")

$parser = New-Object Web.Script.Serialization.JavaScriptSerializer
$thing = $parser.DeserializeObject($response)

I am using VS Code as my IDE to write it and I use the PowerShell plugin's Integrated Console to test the script. When I run there, everything goes well. When I try to run the script (on the same machine) using the windows powershell program (launched as admin from the start menu) I get the following error:
PS C:\repo> .\script.ps1

New-Object : Cannot find type [Web.Script.Serialization.JavaScriptSerializer]: make sure the assembly containing thi
type is loaded.
At C:\repo\script.ps1:15 char:11
+ $parser = New-Object Web.Script.Serialization.JavaScriptSerializer
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand

Is there a reason why this dependency cannot be resolved from the normal powershell terminal? Is VS Code setting up a different environment that I do not know about?
I am using Powershell V3.0 and I have .NET V4.0 installed on my machine.
EDIT
The output of $PSVersionTable is the same from both environments:
Name                           Value
----                           -----
PSVersion                      3.0
WSManStackVersion              3.0
SerializationVersion           18.104.22.168
CLRVersion                     4.0.30319.42000
BuildVersion                   6.2.9200.16398
PSCompatibleVersions           {1.0, 2.0, 3.0}
PSRemotingProtocolVersion      2.2

EDIT2
Adding Add-Type -AssemblyName System.Web.Extensions to the top of the script seems to make it run from the normal terminal. However, I would still like to know why it is able to run without this in VS Code. Is there an initialization script that runs when the Plugin is loaded?
Comment: When you say "PowerShell in VS Code", are you saying about ordinary PowerShell instance, which you run in VS Code terminal, or are you saying specifically about "PowerShell Integrated Console" (the terminal provided by the same process, which is also running PowerShell language server for VS Code)?
Comment: The integrated console
Answer: "PowerShell Integrated Console" terminal provided by special PowerShell process, which is also used to host PowerShell language server and provide editor services to VS Code. To do the job of hosting language server, it can load additional assemblies, which are not loaded by default.
To inspect which assemblies already loaded in the process, you can use following command:
[AppDomain]::CurrentDomain.GetAssemblies() | % FullName

Is there an initialization script that runs when the Plugin is loaded?

Yes, it is. How otherwise it would know, that it need to start language server? Simple way to inspect how instance of PowerShell was started is to use:
[Environment]::CommandLine

command.
Comment: Makes sense, thanks for the info and detailed answer.


How to use JNA with java to detect clicks

Question: If I try to write the code below, I get the following error
Exception in thread "main" java.lang.UnsatisfiedLinkError: Error looking up function 'SetWindowsHookEx': the specified procedure is not found.
at com.sun.jna.Function.<init>(Function.java:252)
at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:620)
at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:596)
at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:582)
at com.sun.jna.Library$Handler.invoke(Library.java:248)
at jdk.proxy1/jdk.proxy1.$Proxy0.SetWindowsHookEx(Unknown Source)
at tester.test.main(test.java:38)

I'm using machine translation, so this English text could be wrong.
Also, since this is my first time asking this question, it would be great if you could tell me where I could improve.
I wrote this code thinking that the message would appear in the console when clicked.
But I got an error that I don't understand.
package tester;

import com.sun.jna.Native;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;

public class test {
    public interface User32Ext extends User32 {
        User32Ext INSTANCE = Native.load("user32", User32Ext.class);

        int WM_LBUTTONDOWN = 0x0201;
        int WM_RBUTTONDOWN = 0x0204;

        WinUser.HHOOK SetWindowsHookEx(int idHook, HOOKPROC lpfn, WinDef.HINSTANCE hMod, WinDef.DWORD dwThreadId);

        WinDef.LRESULT CallNextHookEx(WinUser.HHOOK hhk, int nCode, WinDef.WPARAM wParam, WinUser.MSLLHOOKSTRUCT lParam);

        boolean UnhookWindowsHookEx(WinUser.HHOOK hhk);
    }

    public static interface HOOKPROC extends WinUser.LowLevelMouseProc {
    }

    public static void main(String args[]) {
        User32Ext user32 = User32Ext.INSTANCE;
        HOOKPROC hookProc = (int nCode, WinDef.WPARAM wParam, WinUser.MSLLHOOKSTRUCT lParam) -> {
            if (nCode >= 0) {
                if (wParam.intValue() == User32Ext.WM_LBUTTONDOWN) {
                    System.out.println("L");
                } else if (wParam.intValue() == User32Ext.WM_RBUTTONDOWN) {
                    System.out.println("R");
                }
            }
            return user32.CallNextHookEx(null, nCode, wParam, lParam);
        };

        WinUser.HHOOK hhk = user32.SetWindowsHookEx(WinUser.WH_MOUSE_LL, hookProc, null, 0);

        if (hhk == null) {
            System.err.println("Failed to set up a hook.");
            System.exit(1);
        }
        WinUser.MSG msg = new WinUser.MSG();
        while (User32.INSTANCE.GetMessage(msg, null, 0, 0) != 0) {
            User32.INSTANCE.TranslateMessage(msg);
            User32.INSTANCE.DispatchMessage(msg);
        }

        user32.UnhookWindowsHookEx(hhk);
    }
}

Comment: Check out JNativeHook, they did this for most OSs: https://github.com/kwhat/jnativehook
Comment: thx. ill try it
Comment: How do I detect right clicks with javanativehooks?
Answer: It is not much different from registering and creating any other handler.
First you need to create the handler in an appropriate class implementing a NativeMouseListener (the libraries are in org.jnativehook.*):
public void nativeMouseClicked(NativeMouseEvent e) {
    if (e.getButton() == NativeMouseEvent.BUTTON2) {
        // do something
    }
}

(you can add nativeMousePressed and nativeMouseReleased as well like this at this point)
Secondly you need to register the handler:
    try {
        GlobalScreen.registerNativeHook();
        GlobalScreen.addNativeMouseListener(new YourClass());
    } catch (Exception e) {
        e.printStackTrace();
    }

I have only showed the part of the code which helps you going forward from this point. If you have questions - just ask please.
Comment: Thank you all. Resolved.
I don't know if it was my mouse driver, but NativeMouseEvent.BUTTON2 was right click on my mouse.
Comment: Your welcome. Yeah it was late yesterday - I mixed Button2 and Button3 up :-)
Please consider accepting the answer as it helped you. Thx.


Enviar e-mail em nome do cliente

Question: Tenho um sistema que serve a vários clientes e que envia e-mails a seus usuários (clientes dos meus clientes).
Hoje eu uso uma conta de e-mail própria (do meu domínio), e na composição do e-mail eu informo o nome e e-mail do cliente.
Com isso, tenho dois problemas:

Estes e-mails vão para a caixa de spam.
O destinatário não pode
responder o e-mail, pois ele não irá para o remetente indicado, e
sim a minha conta.

Qual seria a melhor forma de enviar estes e-mails? Obrigo o cliente a configurar uma conta de e-mail própria (correndo o risco de estourar seu limite de envio diário)?
Obs: Envio o e-mail usando javax.mail
Comment: Sugestão: use um serviço como o [SendGrid](http://sendgrid.com/) ou o [MailChimp](http://mailchimp.com/).
Answer: O ideal é ter uma conta específica para o sistema enviar os e-mails, como visto por aí: firstname.lastname@example.com, mas na verdade o endereço não faz tanta diferença. O importante é contratar um plano adequado que suporte o volume de e-mails esperado.
Geralmente os e-mails de empresas são enviados através da mesma hospedagem que eles contratam para o site, que acaba limitando a quantidade de e-mails para os planos básicos. Consulte a empresa responsável sobre a capacidade atual e pergunte por planos para aumentar a capacidade.
Outra alternativa é utilizar outro serviço específico para os e-mails. Mesmo com o domínio de um site associado pelo DNS a uma hospedagem específica, é possível redirecionar o envio e recebimento para endereços diferentes, geralmente através do painel de controle ou mesmo solicitando ao suporte da hospedagem. Dessa forma, você fica livre para contratar um serviço confiável de e-mails sem alterar o funcionamento do site da empresa.
Comment: O problema é que os clientes insistem que o remetente da mensagem tenha o seu domínio, pois é o domínio que seus usuários conhecem.
Comment: Não há problema em enviar é-mails com o domínio dos usuários. Entretanto, se o serviço de e-mail que eles usam é ruim, eles vão ter que trocar. Os limites de envio de e-mails de hospedagens geralmente são especificados em contrato. Faça uma consulta na empresa responsável pelos e-mails.
Comment: @NilsonUehara Reformulei a resposta. Veja se ajuda um pouco mais.
Comment: Entendi. então a solução é mesmo autenticar/enviar o e-mail pelo servidor do cliente.
Comment: @NilsonUehara Isso depende do serviço contratado. Por exemplo, o serviço da Amazon citado na resposta do Emerson não usaria a autenticação no servidor do cliente. Mas se for uma hospedagem "comum", aí sim seria a autenticação SMTP tradicional usando as credenciais do cliente.
Answer: Em primeiro lugar, seu servidor precisa estar bem configurado ou será considerado como spammer até que o esteja. Isso ocorre por causa da Sender Policy Framework (SPF). Isso deve ser feito a nível de servidor.
Existem diversos locais que explicam como enviar e-mail de várias linguagens, então vou me focar em resolver seu problema principal, e não como fazer na linguagem.
Solução de envio direto de seus servidores
Configure seu servidor para trabalhar atender as exigências de Sender Policy Framework. Isso não é trivial, e você será responsável por ver reclamações de SPAM, ou mesmo com ele configurado poderá ter o IP banido.
Esta solução tende a dar mais trabalho se a quantidade de envio de e-mails é enorme e ao mesmo tempo.
Solução de envio via gateways de e-mail pagos que garantem entrega
Caso você não consiga configurar SPF, uma opção viável é contratar serviços de gateway de email, como Amazon Simple Email Service (Amazon SES), que liberam dados de acesso (por exemplo, dados de SMTP que você poderia enviar de qualquer lugar) e farão o serviço pra você.
Esta solução tende é mais simples que configurar SPF, porém é mais cara. Permite enviar grande quantidade de e-mails com menos dor de cabeça.
Solução simples e funcional para poucos e-mails
Crie uma conta do Gmail, habilite SMTP e configure seu framework para enviar como se fosse por essa conta do Gmail. Funciona muito bem e é a mais barata e fácil de garantir que seus e-mails vão chegar em 100% do tempo, porém requer que você não envie MUITOS emails ao mesmo tempo.
Caso use o Google Apps for Business o email será exatamente o do domínio do cliente, porém a cota gratuita hoje em dia não permite muitas contas diferentes, porém é suficiente para pequenas empresas.
Comment: Se entendi bem, na forma "robusta" eu teria que configurar o servidor de e-mails de cada cliente de forma que eles aprovem que meu servidor enviem e-mails em nome deles. É isso?
Comment: Bem, na prática o servidor que vai entrar em contato com resto do mundo deve ter SPF bem configurado. Seu servidor não precisa exigir SPF de seus clientes para receber e-mail deles, mas Google, Hotmail, e afins, exigem. E mesmo com SPF, envio de e-mails em massa vai exigir uma aplicação que agende e divida a carga de trabalho, ou mesmo com SPF enviar milhares de e-mail em uma hora **vai fazer e-mails entrarem na caixa de SPAM** se seu IP não for previamente confiável.
Answer: Note que temos alguns atributos na mensagem como o From, onde você pode setar o email do cliente. Já em relação a configurações do servidor, não sei como ajudar no momento.
// File Name SendHTMLEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendHTMLEmail
{
    public static void main(String [] args)
    {
        // Recipient's email ID needs to be mentioned.
        String to = "firstname.lastname@example.com";

        // Sender's email ID needs to be mentioned
        String from = "firstname.lastname@example.com";

        // Assuming you are sending email from localhost
        String host = "localhost";

        // Get system properties
        Properties properties = System.getProperties();

        // Setup mail server
        properties.setProperty("mail.smtp.host", host);

        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties);

        try{
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field of the header.
            message.setFrom(new InternetAddress(from));

            // Set To: header field of the header.
            message.addRecipient(Message.RecipientType.TO,
                new InternetAddress(to));

            // Set Subject: header field
            message.setSubject("This is the Subject Line!");

            // Send the actual HTML message, as big as you like
            message.setContent("
This is actual message
",
                "text/html" );

            // Send message
            Transport.send(message);
            System.out.println("Sent message successfully....");
        }catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}

Comment: Isso é o que eu faço atualmente, ou seja, eu me autentico em meu mailserver e envio com o remetente do cliente. E é por isso que as mensagens acabam caindo no spam.
Comment: Hummm entendi agora

Enviar e-mail em nome do cliente


Restful web services Documentation

Question: I am looking for complete and updated documentation for Restful web services.
For example, for the user login, we have to post the following data.
POST: http://example.com/user/login?_format=json
Content-type: application/json
Data: { "name": "admin", "pass": "myPassword" }
Response: 200 OK

This will properly log in via cookie authentication, and return a result similar to this.
    {
      "current_user": {
        "uid":"1",
        "roles":["authenticated"],
        "name":"admin"
      },
      "csrf_token":"abc123",
      "logout_token":"def456"
    }

How do I log out the user I just logged in with?
I found RESTful Web Services module overview, but I still don't understand how to log out.
Using the following request gets back a 403 Forbidden error.
POST: http://example.com/user/logout?_format=json
Content-type: application/json
Data: { "name": "admin" }

What am I missing?
Comment: They are the same URLs you normally use on Drupal, so the one to log out is user/logout, and the one to see the profile of the user #1 is user/1.
Comment: Thanks @kiamlaluno, Can you please tell me how can I logout using RestWS. I have tried several ways but no one is working.
Comment: Core REST modules are not the same as the RestWS contrib module.
Comment: hi @visabhishek, which drupal 8 version you are using.
Answer: As per documentation you can do like this.
Logout
GET http://example.com/user/logout
Content-type: text/html
200 - OK

Note: Do not pass "?_format=json" it is not accepting.
Comment: I am using Drupal 8.3.1.

Thanks vijay above code is working fine, How can I get success message or any return value after logout.
Comment: No visabhishek, currently drupal not providing any logout message for REST, Even it's return type is "text/html". Base on return status code you need to show message from client side.

Restful web services Documentation


Spring Autowired and Builder annotations

Question: I have a spring AppUser class that has an @Autowired annotated field (FriendList) as so:
@Getter
@Setter
@Builder
@Document(collection = "app_users")
@Component
public class AppUser {

  @Id
  @NotBlank(message = ErrorConstants.ANDROID_USER_ACCOUNT_MANAGER_ID_IS_NULL)
  private String androidUserAccountManagerId;

  @NotBlank(message = ErrorConstants.NULL_NAME)
  private String name;

  private Friend bestFriend;

  @Autowired
  @Setter(AccessLevel.NONE)
  private FriendList friendList;

  private boolean manualBestFriendOverride;

  public Optional<Friend> getFriend(String friendName) {
    return friendList.getFriend(friendName);
  }

  public void calculateBestFriend() {
    if (!manualBestFriendOverride) {
      bestFriend = friendList.calculateAndReturnBestFriend();
    }
  }
}

The idea was that every time a new AppUser was created, it would @Autowire the same default friendList to start from scratch.
The AppUser is being created in the WebController method:
  @PostMapping("/{androidUserAccountManagerId}/setNewAppUser/{appUserName}")
  public void setNewAppUser(
      @NotNull @PathVariable String androidUserAccountManagerId,
      @NotNull @PathVariable @Pattern(regexp = "^[A-z]{2,20}$", message = "Incorrect name format!")
          String appUserName) {
    databaseQueryClass.save(
        AppUser.builder()
            .androidUserAccountManagerId(androidUserAccountManagerId)
            .name(appUserName)
            .build());
  }

However, I am getting a null pointer exception thrown from when the friendList field is being called in other methods. Essentially the autowiring doesn't seem to be working in conjunction with the AppUser builder.
After some reading, it seems this is bad practice to call new or build and autowire a field in the class being instantiated, due to IoC and Dependency Injection being sorted by Spring.
My question is, how do I get round this design wise? Is this possible to do? Or should I stop trying to autowire a field in the new instance I have to create? Alternatively is there a way that I can autowire the new user when this endpoint is hit?
Thanks for your help in advance.
The FriendList class for context:
@ToString
@EqualsAndHashCode
@Builder
public class FriendList {

  @NotNull private List<Friend> listOfFriends;

  public Optional<Friend> getFriend(String friendName) {
    return listOfFriends.stream().filter(o -> o.getName().equals(friendName)).findAny();
  }

  public Friend calculateAndReturnBestFriend() {
    if(listOfFriends.isEmpty()){
      return null;
    }

    java.util.Collections.sort(listOfFriends);
    return listOfFriends.get(0);
  }

  public boolean addToFriendList(String friendName) {
    if (getFriend(friendName).isPresent()) {
      return false;
    }
    return listOfFriends.add(
        Friend.builder().name(friendName).meetingDates(new TreeSet<>()).meetUpNumber(0).build());
  }
}

EDIT (Sorry I missed this context...)
I have a bean defined in an AppConfig class:
@Configuration
public class AppConfig {

  @Bean
  @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  public FriendList getFriendList() {
    return FriendList.builder().listOfFriends(new ArrayList<>()).build();
  }
}

Answer: Regarding your @Autowired issue, is fine to use a new operator or a builder, as long as you let spring container manage that new bean for you.
For example you could do something like:
@Configuration
public class AppConfig {
    @Bean
    public FriendList firendList() {
        return FriendList.builder()
                      //...
                    .build());
    }
}

And afterwards use it like so : @Import(AppConfig.class)
Please note, that the above will work only if the FriendList is created at the beginning like a default value with all the available information at that point. And also it will only work on the AppUser component that is managed by spring.
If you create the AppUser using builder in the controller, you need to @Autowired the FriendList in the controller and set it on builder.
On another note if the Friends are dynamically created, and let's say for the sake of the example that if at the beginning you have 10 friends and after 1 hour you will have another 10 friends and you need to see all 20 of them, then you need another approach.
Easiest way will be store in the Database the friends and just fetch each them each time and set them on the AppUser. Or retrieve them from a Cache Map.
You can also use @Autowired in that scenario, but is more complicated and you will need to autowire directly a list of Friends:
@Autowired
private List<Friend> friends;

And each Friend should be created dynamically.
Something like this
Friend friend = new Friend();
context.registerBean(Friend.class, () -> friend);  //context here is an ApplicationContext type aka Spring Container.

Also check this example with ObjectProvider from here.
Comment: Sorry I missed some context so I have edited above. I do already have a bean defined in the AppConfig. However, I am missing the @Import(AppConfig.class). Where does this come in and why do I need it?
Comment: The bean currently is created at the beginner with an empty ArrayList of friends. When you say it will only work on the AppUser component that is manager by Spring, why is that? Could I not slightly change the design and autowire it in the WebController and then inject it through the builder?
Comment: Sorry, I am slightly confused by your comments. Are you saying that I should not be autowiring a field in a class I am creating with a builder? And that I should be autowiring in the WebController and passing into the builder?
Comment: On your other note, I am dynamically creating friends and adding to the friendList but only when another endpoint is hit i.e. createNewFriendForAppUser which takes an AppUser id and a new Friend name. Additionally the database holds the AppUsers, which has several fields including FriendList and BestFriend. Does this design currently make sense? I was wondering if I should create another table in the database for friends that have an AppUser Id. Or a friendList table that has an AppUser Id.
Comment: So I have implemented the Autowiring in the WebController class where the AppUser is created. This autowired friendList will be added to each AppUser when created with builder. Does this not mean that due to Java's pass by reference, the friendList will be the same for every AppUser? Because I only have 1 WebController so the FriendList field is created by Spring once, however if I put in the AppUser, this is created each time I create an AppUser with the the builder?
Comment: So if you **Autowired** the FriendList in WebController where AppUser is created, if you set the value in the controller in a new AppUser, it will use the same object. Yes it's pass by reference that's why. And you're right if you Autowire it directly in the  AppUser it will be a new list each time, since you're not letting Spring to handle the creation of the AppUser and that's why you can't autowire it.
For @Import check here: https://mkyong.com/spring3/spring-3-javaconfig-import-example/.
If you found it useful please add a thumbs-up and an accept to the answer, it will help me too :)


Load CKeditor with Simplified Toolbar on dynamically created page element

Question: Drupal 6
ckeditor 3.6.4
I have page that loads the text area dynamically, so I am using
<code>  CKEDITOR.replace('textarea-id');
</code>
Which works, but it is bringing in the full toolbar. I would prefer that the simplified toolbar is used, but it would also be acceptable to use the toolbar I have defined if loading the simplified is not possible. Least desirable would be to hard-code the toolbar, but I consider that a last resort. How do I accomplish this?
I have tried
<code> CKEDITOR.replace('textarea-id',
    {
        toolbar : 'myprofile'
    });
</code>
Which throws  js error:
Type x is undefined
, I think related to the fact that it cant load the profile. Suggestions?
Answer: For better or worse, this is how I did it:
http://joe-riggs.com/blog/2012/11/drupal-ckeditor-load-configuration-settings-on-dynamic-page/
Comment: Just this one line works for me: **CKEDITOR.replace('textarea-id');**
Comment: That worked for me too, in the since that it would load a ckeditor on the text area. The problem was that it would always load the 'Default' toolbar and the not the custom one I defined along with my plugins.

I was able to inspect the ckeditor javascript objects and I could see that my defined profile was not instantiated. I feel like there could have been a better way to do it within ckeditor but I couldn't figure out how.
Answer: This is an example to load custom buttons in the Ckeditor toolbar:
<code>CKEDITOR.replace('textarea-id');

CKEDITOR.config.toolbar = [
   ['Bold','Italic','Underline','SpellChecker','TextColor','BGColor','Undo','Redo','Link','Unlink','-','Format'],
   '/',   ['NumberedList','BulletedList','JustifyLeft','JustifyCenter','JustifyRight','Font','FontSize'],
    ] ;
</code>
Comment: The whole point was to use a profile that I had saved in the admin panel. I suppose if you want to modify the code every time you add a button or plugin, then this would work too


Retornar em horas a diferença entre duas datas em JAVASCRIPT

Question: Acabo de ver esta pergunta aqui no Stack Overflow que mostra como resolver meu problema mas em PHP. Gostaria de saber como posso calcular a diferença entre 2 datas e mostrar isso em horas. ex:
var d1 = new Date('2015-12-21 00:00:00').toTime();
var d2 = new Date('2015-12-19 00:00:00').toTime();
var df = Math.abs(d1-d2);

//?? agora preciso saber como retornar "48:00:00"

Alguém tem uma luz?
Answer: > df/1000/60/60

df dividido por 1000 (para retornar o número de segundos), divido por 60(para retornar o número de minutos), dividido por 60 (para retornar o número de horas).
Se quiser em dias, divida por 24, ai você vai ter 2 (dias), como resultado.
Comment: ok, que eu devo chegar a fazer o calculo. mas tinha entendido que havia um método melhor que esse...
Answer: Vê se este código te ajuda:
data1 = new Date('2014/01/01');
data2 = new Date('2014/04/01');
var diferenca = Math.abs(date1 - date2); //diferença em milésimos e positivo
var dia = 1000*60*60*24; // milésimos de segundo correspondente a um dia
var total = Math.round(diferenca/dia); //valor total de dias arredondado
var emHoras = Math.round(total*24); // valor total em Horas
console.log(emHoras);

Ele calcula a diferença em horas.
Comment: sim ele calcula mas vai me dar um valor inteiro sobre quantas horas. preciso saber também para minutos e segundos porque nesse sistema será feito um controle de SLA
Answer: Galera pra resolver meu problema, acabei criando uma função assim:
function timeDiff(d1, d2) {
    var d1 = new Date(d1).getTime();
    var d2 = d2 || new Date().getTime();
    var df = Math.abs(d1 - d2);
    var td = {
        d: Math.round(df / (24 * 60 * 60 * 1000)), //dias
        h: Math.round(df / (60 * 60 * 1000)), //horas
        m: Math.abs(Math.round(df / (60 * 1000)) - (60 * 1000)), //minutos
        s: Math.abs(Math.round(df / 1000) - 1000)
    };
    var result = '';
    td.d > 0 ? result += td.d + ' dias ' : '';
    td.h > 0 ? result += ('0' + td.h).slice(-2) + ':' : '00:';
    td.m > 0 ? result += ('0' + td.m).slice(-2) + ':' : '00:';
    td.s > 0 ? result += ('0' + td.s).slice(-2) : '00';
    return result;
}

Essa função vai pegar a data que vc enviar (em formato padrão para data yyyy-mm-dd hh:mm:ss) e calcular a diferença entre a primeira e a segunda data. NOTA: na função coloquei para que se enviada somente uma data, ele calcule usando a data atual para facilitar o serviço na minha aplicação...


Effect or Predictor(s), is it always clear which is which?

Question: How does one determine if a variable is an effect or a predictor if all the variables are measured and none or manipulated or otherwise fixed? For example, does reduction in vascular diameter cause increased amyloid accumulation or does amyloid accumulation drive changes in vascular diameter?
There's no way to explicitly model this question if what one has is just data from brains, as far as I know, but I don't know much.
Answer: There are several questions here to be disentangled. They sometimes have the same answer, but far from always.
What do you want to predict? Sometimes the interest is in predicting an outcome from predictor variables, as when the interest is in predicting the growth rate of an economy, the level or discharge of a river, or children's heights as they grow. But often the interest is reversed. If a skeleton is found, our idea is that skeletons grow as people do, and so that age and getting older are causal, but in practice we may use bone length to predict age, which is unknown but of great interest.
What is considered a response or outcome? Here language may vary, but very often there are detailed ideas (in science, engineering, medicine, social science, and so forth) about how something varies in terms of associated causal mechanisms, processes, behaviour, or whatever analysis appeals to people in a field. Thus wheat yield might be a response to temperature, rainfall, soil nutrients, labour and materials inputs, and so on, but most of these would not usually be considered to be affected by wheat yield. (On the other hand, a growing crop can deplete nutrients.) Sometimes time is of central concern in that causes supposedly precede effects in time and that is indeed often how causes and effects are distinguished. But people and organisms can engage in anticipatory behaviour, as when presents are bought or made before the time of giving, or animals prepare for seasonal changes.
Is there a experimental set-up? Typically controlled variables are regarded as causal, say temperature or pressure in chemistry or engineering, and consequences, say output of products, as the outcome or response variable.
Are variables on the same footing? Variables may be loosely or even strictly regarded as having the same status. Height and weight might be considered thus, or students' performance on several different examinations. Nothing is absolute here: examination performance might be analysed in terms of measures of ability, student effort, personal or family background, and so forth, but the examinations themselves might not be independent, as when one examination follows another quickly, and many students don't revise enough for the second.
Are there feedback loops? The presence of a feedback loop can throw doubt on which of two variables is cause and which effect and one good answer may be neither.  The analysis may then depend on the time scale of interest. At any moment a land surface may be considered fixed and to determine or at least influence the rate at which it changes, as when the movement of sediment is predicted from slope or other topographic measures. But wait long enough (geological time) and the land surface itself changes as a result of those sediment movements.
Comment: What do I want to predict? Both.
What is considered a response or an outcome? Either.
Is there an experimental setup? No. Pure observation.
Are variables on the same footing? Yes.
Are there feedback loops? Probably.
Comment: Opinion varies. If there are two variables, and only two, some would advocate what is variously called the reduced major axis, the SD line, and several other things. Errors in variables is another key term.
Comment: Alas, I have covariates...
Comment: I think there is work on your case, but finding the software may be hard and I'm now beyond my knowledge on this.  Your comments add key detail that should be edited into your question so that other people can read a fuller version.


How to insert a data point at a time to a pandas dataframe?

Question: It might be non-pythonic (if yes, let me know also) but I am running a function that produces only one data point at a time, and I would like to add those points to my dataframe. The reason for this is that for each row, I have 252 rows (in another dataframe) that I will input in a function, and will return me a single number.
I am using this method:
data.loc[row, 'ColumnA'] = some integer

but it appends the rows/values at the end of the dataframe, when I want to create a new column and populate it a data point at a time. So, for example, if I have this column in a dataframe:
Column A
NaN
NaN
NaN

and I run this:
data.loc[0, 'ColumnA'] = 10

I would like to see:
Column A
10
NaN
NaN

Thank you!
Comment: It sounds like your dataframe's row index may not be the sequence 0, 1, 2, ...? Can you paste the output of `print(data)` or at least `data.head()`?
Comment: is there a reason you want to append to the dataframe one point at a time? It would probably be better to run the function on all values and add it as a column in a vectorized fashion...
Comment: @Ben I reset my index and it worked, thanks!
Answer: Have a look at the .at function on a dataframe
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.at.html
It can be used to look at and change the value using a row/column pair
df.at[row, column] = value
So your code would look like
data.at[row, 'columnA'] = 10


How to change DB active config storage of an installed site to config file storage?

Question: The default.settings.php says

/**
 * Active configuration settings.
 *
 * By default, the active configuration is stored in the database in the
 * {config} table. To use a different storage mechanism for the active
 * configuration, do the following prior to installing:
 * - Override the 'bootstrap_config_storage' setting here. It must be set to a
 *   callable that returns an object that implements
 *   \Drupal\Core\Config\StorageInterface.
 * - Override the service definition 'config.storage.active'. Put this
 *   override in a services.yml file in the same directory as settings.php
 *   (definitions in this file will override service definition defaults).
 */
# $settings['bootstrap_config_storage'] = array('Drupal\Core\Config\BootstrapConfigStorageFactory', 'getFileStorage');

I have added above code to my settings.php and this is the piece of code I have added in services.yml before install.

services:
  config.storage.active:
    class: Drupal\Core\Config\FileStorage
    factory_class: Drupal\Core\Config\FileStorageFactory
    factory_method: getActive
    public: false

How can I change the DB config storage to file config storage after site install? We have config_db.module to change it form file storage to DB storage. Do we have a module to change it from DB storage to file storage?
Answer: Here are the steps I followed:
1) Export settings to your current $config_directories['sync'] directory (by default it is defined in settings.php and it is something like 'sites/default/files/config_VerYlonGkEY0123/sync')
$ drush cex

2) Create these directories (should be writable):
config/
  active/
  staging/
  sync/

3) Copy/paste all files from $config_directories['sync'] to config/active/
4) Add the new settings to settings.php
$config_directories = array(
  CONFIG_ACTIVE_DIRECTORY => DRUPAL_ROOT . '/config/active',
  CONFIG_STAGING_DIRECTORY => DRUPAL_ROOT . '/config/staging',
  CONFIG_SYNC_DIRECTORY => DRUPAL_ROOT . '/config/sync',
);

$settings['bootstrap_config_storage'] = array('Drupal\Core\Config\BootstrapConfigStorageFactory', 'getFileStorage');

5) Add this to service.yml (in the same directory as the settings.php):
services:
  config.storage:
    class: Drupal\Core\Config\CachedStorage
    arguments: ['@config.storage.active', '@cache.config']
  config.storage.active:
    class: Drupal\Core\Config\FileStorage
    factory: Drupal\Core\Config\FileStorageFactory::getActive

6) Export the settings to sync:
$ drush cex sync

Than you should have the settings in config/sync :)


Error when running a DQN pygame script in Google Colab

Question: When I am running a DQN script using Pygame on Google Colab it is throwing error -

pygame.error: No available video device

I am trying to run this GitHub repo on Google Colab. pong_neural_network_live
Installed the Pygame using following code-
import os
!git clone https://github.com/ntasfi/PyGame-Learning-Environment.git
os.chdir('PyGame-Learning-Environment')
!pip install -e .
!pip install pygame
os.chdir('/content')

On trying to initialize and run the following code it
import pygame
pygame.init()
pygame.display.list_modes()

I get

error: video system not initialized

PS: I also enabled third party cookies in Google Chrome.
Answer: Colab is run in the cloud. It cannot send display to a window on your computer. So, you cannot use Pygame. Or you need some clever hacking like VNC.
Answer: There is a way to run pygame in Colab with some limitations.
Fool the system to think there is a video device
Capture the pygame screen and copy it to another interface compatible with Colab like OpenCV or matplotlib
Use output library to clear the cell.
Not the most elegant way, but it gets it done.
Take a look at this notebook I created: (https://colab.research.google.com/drive/1xtiBrGeRHmXY3KSOixkZBf_rJIgBImJu?usp=sharing)
Please notice there are limitations:
Can't read inputs from keyboard or mouse
Can't play audios
In my case I was interested to use pygame for animation purposes so I wasn't too fuzzed about it.
Comment: Thanks. That's a smart way to do it. Though there are limitations and will not be a full fledged solution anyway.


Principal component/Partial least-squares regression: can we use test data to calculate the factors?

Question: I would like to make a PC/PLS regression and assess the resulting model's predictive power.
The strategy is the classical splitting into training/validation/test sets, and using training/validation sets to fit the model and test set to assess the prediction performance.
My question is, can I use the whole data set to calculate the PCA if I then use only training & validation sets to fit the model parameters (i.e., regression weights and number of PCA components)?
Performing PCA on the whole data set would mean peek at the test set and might be considered cheating. However, if the data set is small one might not get an accurate estimate of the statistical structure in the data unless the whole set is considered, in which case it could be seen as legitimate (?)
I couldn't find any discussion of this over the web, so any pointers would be appreciated.
Thanks!
Answer:
can I use the whole data set to calculate the PCA if I then use only training & validation sets to fit the model parameters (i.e., regression weights and number of PCA components)?

No, this may lead to very overoptimistic test results.
For the data sets I typically work with (spectroscopic data sets, wide matrices wrt. the number of independent specimen/patients; classification) I've seen the number of misclassifications being underestimated by an order of magnitude when using the whole data set to calculate the loadings.
I think of it this way: the PCA/PLS projection reduces (for my data) 100 - 1000 variates to maybe 10, i.e. 10 $\times$ 100 - 1000 coefficients are calculated. The regression (or in my case classification) calculates only maybe 10 more coefficients. Thus, I'd intuitively expect that the more crucial (and difficult) step is to get the loadings. Thus, independence of test and training data is crucial for the step of loading calculation / validation of the calculated loadings.
Here's my recommendation: do it both ways and have a look at the difference. Maybe even report the results here.
Comment: Hi! Thanks a lot for your answer.
I like your argument - thinking of it that way, it seems obvious indeed that getting the loadings is the most important step.

I've already tried doing it both ways: not surprisingly, calculating the loadings on the whole data sets yields slightly better results.

The reason I'm asking the question is that it seems to me that both ways of doing it could be justified, and because I haven't been able to find a formal discussion of this topic, I'm wondering what other people would think of it.
Comment: In the case of PLS, calculating the loadings involves the dependent variable, which clearly violates independence of the test set. In PCR, it involve only the predictors, so I can't see why it is wrong, although it would likely not be considered best practice.

I'm happy to report the results here as soon as I can find the time.
Comment: @wawrzeniec: The independent variables (don't be mislead by "independent" here, it does not mean these are independent in the way you need for independent test cases) also contain information about the problem. As you say, the PCA may *benefit* from including these cases. This is a very strong point that testing on cases that did not enter the model calculations in *any* way (not for the centering, not for the loadings, not for the regression, not for model selection, etc.) is needed.


How to unify a pair of atomic formulas?

Question:
Unify the pair of  atomic formulas $p(a,x,f(g(y))),\ p(z,h(z,u),f(u))$.

Attempt following the alogrithm described below.
We have
\begin{align}
\begin{aligned}
a &=z\\ x &=h(z,u)\\ f(g(y))&=f(u)
\end{aligned}
\implies
\begin{aligned}
z&=a\\ x&=h(z,u)\\ f(g(y))&=f(u)
\end{aligned}
\end{align}
Now here I could apply 3. to get $g(y)=u$ and hence $u=g(y)$.
And I don't know how to proceed from here.
The thing is I'm confused on how the algorithm works, $u$ and $z$ variables have another occurrence in $x=h(z,u)$ so we should use step 4. but I don't understand what  this means

"If $x$ occurs in $t$ and $x$ differs from $t$".

For the example above we have $z=a,$ i.e. $t=a$, thus $z$ occurs in $a$ means $z=a$?
Also, what does step 3 mean?

"If the outermost function symbols of $t$
   and $t'$  are not identical, terminate the
  algorithm and report not unifiable".

Outermost respect to what? Note that there is no problem when there is just one function.

Algorithm 10.15 (Unification algorithm) (See Ben-Ari page 190)
Input: A set of term equations.
Output: A set of term equations in solved form or report not unifiable.
Perform the following transformations on the set of equations as long as any one
of them is applicable:

Transform $t = x$, where $t$ is not a variable, to $x = t$.
Erase the equation $x = x$.
Let $t = t'$ be an equation where $t$, $t'$  are not variables.

If the outermost function symbols of $t$ and $t'$ are not identical, terminate the algorithm and report not unifiable.
Otherwise, replace the equation $f (t_1, \dots , t_k) = f (t_1' , \dots , t_k')$ by the $k$ equations $t_1 = t_1' , \dots , t_k = t_k'$.

Let $x = t$ be an equation such that $x$ has another occurrence in the set.

If $x$ occurs in $t$ and $x$ differs from $t$, terminate the algorithm and report not unifiable.
Otherwise, transform the set by replacing all occurrences of $x$ in other equations by $t$.
Answer: You are almost done!
You have to iterate the steps of the unification algorithm until you get:

either an equation $x = t$ such that $x$ occurs in $t$ but $x \neq t$ (step 4), and this means that you cannot unify the formulas;
or an equation $f(t_1, \dots t_k) = g(s_1, \dots, s_n)$ with $f \neq g$ (step 3), and this means that you cannot unify the formulas (this is the meaning of step 3 that you don't understand);
or a set of term equations in solved form, and this means that you can unify the formulas by applying the substitutions defined in these equations.

You have obtained the equations $\ z = a$, $\ x = h(z,u)$, $\ u = g(y)$ and then you have to apply the second item of step 4 for $z = \dots$ and $u = \dots$.
The following is a step-to-step description of the execution of the unification algorithm, starting from the beginning:

First round:

step 3 (second item): $\ a = z$, $\ x = h(z,u)$, $\ f(g(y)) = f(u)$

Second round:

step 1: $\ z = a$, $\ x = h(z,u)$, $\ f(g(y)) = f(u)$
step 3 (second item): $\ z = a$, $\ x = h(z,u)$, $\ g(y) = u$
step 4 (second item): $\ z = a$, $\ x = h(a,u)$, $\ g(y) = u$

Third round:

step 1: $\ z = a$, $\ x = h(a,u)$, $\ u = g(y)$
step 4 (second item): $\ z = a$, $\ x = h(a,g(y))$, $\ u = g(y)$

After this last step, we have obtained a set of term equations in solved form, which unify the atomic formulas $p(a, x, f(g(y)))$ and $p(z, h(z,u), f(u))$. Indeed:
\begin{align}
&p(a, x, f(g(y))) [z = a,\  x = h(a,g(y)), \ u = g(y)] \\= \ &p(a, h(a,g(y)), f(g(y))) \\= \ &p(z, h(z,u), f(u))[z = a, \ x = h(a,g(y)), \ u = g(y)]
\end{align}
Comment: What means outermost ? in this context. I don't understand the second bullet of your answer
Comment: @Michelle - For instance, if you have a term equation of the form $h(z,x) = g(y)$, then the outermost function symbols of the two terms are $h$ and $g$, which are different, and so the two terms are not unifiable according to the first item of step 3.
Comment: hmm this sounds strange, what if you have two term equations, e.g. $h(z,x)=g(y)$ and $i(w)=j(y,u)$, outermost doesn't have relation with  taking the 'outermost'  of these equations?
Comment: @Michelle - "outermost" refers to the most external (i.e. leftmost in this context) symbol of a _single term_. The outermost symbol of $h(z,x)$ is $h$, the outermost symbol of $g(y)$ is $g$; since $h \neq g$, then you cannot unify the terms $h(z,x)$ and $g(y)$, according to step 3 (first item). Analogously for $i(w)$ and $j(y,u)$.
Comment: :) got it ${}{}$
Comment: To understand the first bullet, suppose that we have $x=f(a)$ and $y=f(x)$ thus x occurs in the term $f$, thus the unification can't exist, am I right?
Comment: @Michelle - No, in that case you can unify, actually you have $y = f(f(a))$. Indeed, $f$ is not a term but the outermost symbol of the term $f(y)$. The first item of step 4 means that for example the term equation $x = f(x)$ is not unifiable, because $x$ occurs in both the left-hand and right-hand sides of the equation.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/75692/discussion-between-taroccoesbrocco-and-michelle).

How to unify a pair of atomic formulas?


Invertendo Ordem coluna data.frame

Question: Tenho esse data frame:
> head(df1)
         data    spread
1 2006-01-01   -3.0404577
2 2006-02-01   -3.3902628
3 2006-03-01   -2.5283960
4 2006-04-01   -1.5279234
5 2006-05-01   -0.0897918
6 2006-06-01    1.0286549
> tail(df1)
         data    spread
112 2015-04-01   -0.2923391
113 2015-05-01   -0.8202538
114 2015-06-01   -1.0975489
115 2015-07-01   -1.1600462
116 2015-08-01   -0.4637534
117 2015-09-01    1.2141885

Quero inverter a ordem da coluna e dos dados:
Fiz esse comando:
df1<-df1[order(rev(df1$data),rev(df1$spread)),]

Ele embaralha e deixa desorganizado:
> head(df1)
      data          spread
114 jun2015 -1.09754890
110 fev2015  0.06755755
106 out2014  0.87560496
116 ago2015 -0.46375344
117 set2015  1.21418847
111 mar2015  0.32772727
> tail(MatrizVerticeSpreadMensala)
      data          spread
9 set2006  0.0742353
3 mar2006 -2.5283960
4 abr2006 -1.5279234
5 mai2006 -0.0897918
7 jul2006  0.5451561
1 jan2006 -3.0404577

Alguma sugestão?
Obrigado!
Answer: Recriando sua base de dados
df<- read.table(text="data    spread
1 2006-01-01   -3.0404577
2 2006-02-01   -3.3902628
3 2006-03-01   -2.5283960
4 2006-04-01   -1.5279234
5 2006-05-01   -0.0897918
6 2006-06-01    1.0286549
112 2015-04-01   -0.2923391
113 2015-05-01   -0.8202538
114 2015-06-01   -1.0975489
115 2015-07-01   -1.1600462
116 2015-08-01   -0.4637534
117 2015-09-01    1.2141885")

Utilizando o comando rev() para fazer o desejado (inverter a ordem das colunas e dos dados).
rev(df[nrow(df):1,])

        spread       data
117  1.2141885 2015-09-01
116 -0.4637534 2015-08-01
115 -1.1600462 2015-07-01
114 -1.0975489 2015-06-01
113 -0.8202538 2015-05-01
112 -0.2923391 2015-04-01
6    1.0286549 2006-06-01
5   -0.0897918 2006-05-01
4   -1.5279234 2006-04-01
3   -2.5283960 2006-03-01
2   -3.3902628 2006-02-01
1   -3.0404577 2006-01-01

Answer: De forma hipotética, recriei seus dados utilizando os pacotes lubridate e dylyr.
library (lubridate)
dados<-data.frame(data=seq(ymd('2006/01/01'),ymd('2015/09/01'),by='1 month'),spread=rnorm(117))

Para inverter, neste caso simplesmente reordenando as datas, apliquei a seguinte expressão:
library (dplyr)
dados_ordenados<-dados %>% arrange(desc(data))

Onde:

%>% é um operador pipe que simplifica a expressão f(x);
arrange é uma função de ordenamento e;
desc organiza na ordem decrescente.

E para reposicionar suas colunas:
posicao_dados<- dados_ordenados  %>%  select(spread, everything())

Onde:

everything() é tudo o resto.
Comment: A resposta não está necessariamente correta: 1. O AP pediu para inverter a coluna, não ordenar de forma diferente. Realmente parece ter o mesmo resultado, mas não foi o perguntado, para uma pessoa procurando apenas como inverter a ordem estaria errado. 2. Ele também pediu para inverter as colunas, neste caso apenas a ordem das linhas foi modificada.
Comment: Entendido, assim que puder vou corrigir a resposta. Obrigado!

Invertendo Ordem coluna data.frame


WPF Webbrowser: Launch method in view model once webbrowser loaded/rendered event completes

Question: I have a MVVM WPF application which in the main window I have placed a webbrowser component. I has binded a property in view model to the HtmlText property in Webbrowser.
Now I am trying to launch a method in view model when webbrowser has loaded (rendered) its content completely. I know there is a loaded event in webbrowser but I do not know how to from the view launch the method in view model on loaded (rendered) complete.
How can I do this?
I am using Visual Studio 2008 and NET Framework 3.5 SP1.
Answer: Handle the event in the view and call the method of the view model?
<code>private void WebBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
    var vm = DataContext as ViewModel;
    vm.Method();
}
</code>


Micro service architecture for Angular2

Question: If we take an enterprise  angular 2 web app it has several modules(screens) such as Customer management, Reservations, Booking management, Reporting and etc....
What we normally do is we create common components in a component library and use them on main angular application. The main angular app contains all the modules(screens) with REST API integrations(assuming backed is REST). When app is getting bigger & bigger compile time and rendering consuming more time & resources. Also if one particular area is having a issue we cannot have a release since all are bundle to one app.
As you all know Micro service architecture is a method of developing software systems that has grown in popularity. So, my question is can we apply same architecture for these type of enterprise angular 2 apps?.
It is like this. We have a customer management as a separate angular app. Again Booking management is another angular app. Reporting is another app. These apps are going to be separate war files when deploying to the web server.
Once we have developed such loosely coupled apps this will reduce the over head of project size, compile time & resources. Also this will make unit testing more easier. Particular set of developers are only considering the only one unit of the module.
Kindly share your expert thoughts about this
Thanks.
Comment: Seems a good way forward and you have a good plan. Is there anything specific you want to know about this architecture?
Comment: I think that you could apply the same principles from the microservices architecture as a web page could contain more angular applications.
Comment: Thanks Preet. Our back end services are already decided to align with the micro service architecture. My thought was whether same architecture can be used to  angular 2 web apps. Since we can get the benefits of the micro services to front end apps.
Comment: Thanks  Constantin Galbeenu. I will update this thread with the findings.
Answer: Yes, you could develop each module into its own application and release independently, you just need to make sure that you have a way (from menu for example) to go from one application to another application, if you host your all your applications on the same port, you will have a single token that can be shared by all applications, and you can seem less move user from one application to another as in portal experience.
You need to manage your state properly, if you are state baked into Session Storage (Master Data), you can get the experience you are looking for.
If you host your applications, with different URLs, you will not be able to share the token, instead you would have to use an approach how Google authentications works at Gmail, youtube etc

Micro service architecture for Angular2


Making a lead sheet to practise transcription - have a few queries

Question: I'm fairly new to music and have been transcribing melodies in the name of ear training and becoming more fluent with standard notation. I'm presently creating a lead sheet for this song:

I've transcribed the melody for the first verse and intend to add chord symbols down the line:

I have a few queries about this. In decreasing order of specificity:

About measure 11. Is the D note in measure 11 (highlighted with the red arrow) correctly tied?
Corollary question. If I were to instead have a half note spanning beats 3 and 4 and tied to the dotted eighth on beat 5, would it violate convention by stretching across the middle of the measure of 6/4? (For much the same reasoning that you can't have a quarter note across the middle of a measure of 6/8.) If so, does the lack of a clear triple pulse exempt it from having to follow a 3+3 subdivision? I ask because it's an isolated measure of 6/4 in a piece that's otherwise in 7/4.
Second verse. When I transcribe the second verse, should I a) use a repeat and add the second verse's lyrics to the existing notes, or b) create new measures specifically for it? I've seen some lead sheets for other songs that do the former, but I find that it doesn't accommodate subtle melodic and rhythmic alterations between verses. As such, an awkward "middle ground" is notated instead. What's the best practice here, or is it a case-by-case choice?
Any other matters. Are there any glaring errors/other things or best practices I should take note of? Anything and everything would be appreciated.

Many thanks for your help!
Comment: 0. The incomplete measure at the start (the anacrusis) shouldn't be given a bar number (or perhaps be given the number zero).  So all the bar numbering is off by one.
Answer: First let me say I don't know how new you are to music but this is a very good transcription! Here are my responses to your questions:
1&2: This bar is beamed correctly. 6/4 is generally treated as 3+3. Some will say that you can use a half note and group a 6/4 bar in different ways and I don't disagree. If I personally were to do that I would show the subdivision at the top of the bar, for example 2+2+2. In this song the 7/4 groove feels like a 3+4 and that bar feels like a 2+4 so I think the half note would be ok.
3: If there are differences in the notes and rhythms there's no reason to try and squeeze the second verse lyric line onto the first. You can Copy/paste the first verse to the end and then make the subtle changes necessary on the second verse if they are very similar. It will look cleaner and be easier to read. In general don't create a road map (repeats, multiple endings, D.S. etc.) when there is no need to. If you need or want to use road maps always be logical about it. In my personal experience the more complicated the road map the more mistakes and problems pop up in rehearsals and performances.
4: As I said at first, excellent transcription. One very subtle thing, the last 16th note of bar 6 sounds like a F, not a Bb but great work, keep it up!
Comment: Thank you very much, this was extremely clarifying!
Comment: The 2+2+2 bar could be written as 3/2
Comment: @ElementsinSpace Absolutely but within the context of a single bar within a 7/4 piece I would prefer 6/4.


What's the point in using identity matrix as weighting matrix in GMM?

Question: What is the point of using the identity matrix as weighting matrix in GMM?
GMM is the minimizer of the distance $g_n(\delta)'\hat{W}g_n({\delta})$, where $g_n = \frac{1}{n}\sum_ix_i\epsilon_i$. If we set $\hat{W}=I$, we would get a distance equal to $g_n(\delta)'g_n({\delta})$, i.e. the sum of squared coordinates of $g_n$.
The result of the minimization is still a GMM estimator but it is clearly not efficient (we should have set $\hat{W}=S^{-1}$, where $S = \frac{1}{n}\sum_ix_i'\epsilon_i'\epsilon_ix_i$).
So why should we proceed in this direction? Is it something common in practice as a first step towards the best GMM or are there other reasons?
Answer: Yes, getting a first step estimator is the canonical use. Of course, the error terms in $$S = \frac{1}{n}\sum_i\epsilon_i^2x_ix_i'$$ are not observable, so that you need to replace them with something feasible. As the efficient GMM estimator depends on $\hat S$, you first need some feasible preliminary estimator such as the one using $I$ as the weighting matrix.
There may be some further interesting considerations in a multiple equation setup, in which misspecification in one equation can "pollute" the entire system. You can avoid that risk through a less efficient, but more robust block-diagonal weighting matrix, of which $I$ would be an example.
Comment: Here, can I ask a question in this question? When We set $W=I$, why GMM is inefficient? How can I prove this? Can you please mention about this proof? Thank you.
Comment: I posted a second answer addressing this point (for any $W$, not just $I$).
Answer: This second answer, based on exposition from Hayashi, Econometrics, addresses the question posed in the comment to the first answer as to why the specific choice of $W$ results in an efficient GMM estimator.
The efficient weighting matrix results from the general one by setting $W=S^{-1}$ to get an asymptotic variance
\begin{eqnarray}
\mathrm{Avar}(\widehat{\delta}(\widehat{S}))&=&(\Sigma_{xz}'S^{-1}\Sigma_{xz})^{-1}\Sigma_{xz}'S^{-1}SS^{-1}\Sigma_{xz}(\Sigma_{xz}'S^{-1}\Sigma_{xz})^{-1}\notag\\
&=&(\Sigma_{xz}'S^{-1}\Sigma_{xz})^{-1}\Sigma_{xz}'S^{-1}\Sigma_{xz}(\Sigma_{xz}'S^{-1}\Sigma_{xz})^{-1}\notag\\
&=&(\Sigma_{xz}'S^{-1}\Sigma_{xz})^{-1}\label{avareffgmm}%\\[-4ex]
\end{eqnarray}
We therefore need to show that the difference between the general asymptotic variance and the one with the specific (to be shown) efficient weighting matrix is p.d.:
$$
(\Sigma_{xz}'W\Sigma_{xz})^{-1}\Sigma_{xz}'WSW\Sigma_{xz}(\Sigma_{xz}'W\Sigma_{xz})^{-1}-(\Sigma_{xz}'S^{-1}\Sigma_{xz})^{-1}\geqslant0$$ Linear algebra (see Thm. 1.24, Magnus/Neudecker 1988, i.e. $A-B\geqslant0\Leftrightarrow B^{-1}-A^{-1}\geqslant0$, much like $3>2$, but $1/2>1/3$) tells us that this condition is equivalent to
$$
Q:=\Sigma_{xz}'S^{-1}\Sigma_{xz}-\Sigma_{xz}'W\Sigma_{xz}(\Sigma_{xz}'WSW\Sigma_{xz})^{-1}\Sigma_{xz}'W\Sigma_{xz}\geqslant
0$$
As $S$ is p.d., $S^{-1}$ can be decomposed as $S^{-1}=C'C$. Further define $H=C\Sigma_{xz}$ and $G=C'^{-1}W\Sigma_{xz}$.
Then,
\begin{eqnarray*}
Q&=&\Sigma_{xz}'C'C\Sigma_{xz}-\Sigma_{xz}'W\Sigma_{xz}(\Sigma_{xz}'WC^{-1}C'^{-1}W\Sigma_{xz})^{-1}\Sigma_{xz}'W\Sigma_{xz}\\
&=&H'H-\Sigma_{xz}'W\Sigma_{xz}(G'G)^{-1}\Sigma_{xz}'W\Sigma_{xz}\\
&=&H'H-\Sigma_{xz}'C'C'^{-1}W\Sigma_{xz}(G'G)^{-1}\Sigma_{xz}'WC^{-1}C\Sigma_{xz}\\
&=&H'H-H'G(G'G)^{-1}G'H\\
&=&H'(I-G(G'G)^{-1}G')H\\[-4ex]
\end{eqnarray*}
The matrix in brackets is, as usual, symmetric and idempotent and therefore p.s.d. Thus, for an arbitrary $a$,
\begin{eqnarray*}
a'Qa&=&a'H'(I-G(G'G)^{-1}G')Ha\\
&=:&c'(I-G(G'G)^{-1}G')c\geqslant0
\end{eqnarray*}
Comment: Wow thank you so much:)


Android - Firebase Database

Question: My application was token generation mobile application. Iam using Firebase to store my data. The token were generated with the help of childrens count in firebase database. The problem I faced was if two users book their appointment at same time then both the users get same token number. For example, the number of childrens in firebase was 5. If the users A and B book their appointment then both the users get the token number 6. But the other user C book the appointment(after A and B) get the correct token number 8.
My code:
int ct=1;

public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
        ++ct;
        Log.d("log", "onDataChange: " + dataSnapshot1.child("Appointment").child("artistName").getValue());
    }
}

The variable ct represents the token number.
What was the solution to solve the above problem?
Answer: The token should not be generated based on children count under a node. It will not serve the purpose of identifying a token uniquely in your database.
As far as I could understand your problem, you want to provide a token to the users of your application for an automated appointments to some artists. In this case, I would like to suggest you to take another table in your firebase database which will store all the tokens. Tag the token number along with the artist.
So the final table structure will be something like this.
Appointment
    -- Artists
           -- TokenNumber

Token
    --TokenNumber

If you are familiar with the relational database, you might consider thinking of your token number as a foreign key of another table which is incremented automatically each time a token is assigned to some appointment.
Hope that helps!
Update
Based on the comment, I have found a nice answer in stackoverflow regarding this. Please have a look at the answer on how to increment a value in Firebase. The key idea is to setting the value from client side with a transactional mode. I am sharing the sample code from the answer referred.
public void incrementCounter() {
    firebase.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(final MutableData currentData) {
            if (currentData.getValue() == null) {
                currentData.setValue(1);
            } else {
                currentData.setValue((Long) currentData.getValue() + 1);
            }

            return Transaction.success(currentData);
        }

        @Override
        public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
            if (firebaseError != null) {
                Log.d("Firebase counter increment failed.");
            } else {
                Log.d("Firebase counter increment succeeded.");
            }
        }
    });
}

Comment: How to increment the token automatically?  @ReazMurshed
Comment: Actually I have tried the updated code. But it seems to be error.  Once again I will try the updated code.
Comment: I think the above code to increment the single firebase counter value. But i want the counter  variable for every registered patients.
Comment: Think the token number as a foreign key in a different table. That's the idea actually.
Comment: I dont want the single value. The value of token number varies for different user.
Comment: Of course it will vary from user to user. However, there should be a single token generation source, so that you can generate each token uniquely. .

Android - Firebase Database


Elemento não responde ao clique do Selenium (Python)

Question: Estou há pouco tempo trabalhando com o Selenium em Python e enfrentando um problema em minha automação:
O Selenium identifica o elemento (tanto por xpath como por qualquer outra maneira), mas no momento de clicar, o elemento não se comporta da maneira esperada. Seguem 2 imagens sobre:
O que deveria acontecer:

O que está acontecendo:

Se alguém não entendeu a pergunta, por favor me avise para que eu possa elaborá-la melhor. Estou realmente precisando dessa resposta.
Agradeço desde já!
Comment: Pelo que vi da imagem, existe o atributo `disabled="true"` no botão que deseja clicar, poderia remover a `metatag disabled` e depois de remover efetuar o clique.
Answer: Pelo que reparei, na primeira imagem o button tem um "is-loading" no final da classe, coisa que não tem na classe da segunda imagem.
Se esse for o único form com a classe "sort-request" você pode tentar algo assim:
elem = driver.find_element(By.Xpath, "//*[@class='sort-requests']/descedant-or-self::button");
elem.Click();

Eu costumo usar o Selenium em C#, o código acima escrevi baseado na documentação oficial em Python.
Comment: Então esse pode ser um erro ou até mesmo uma espécie de proteção do site. Com o Geckodriver eu tenho esse problema, com o navegador direto, não.
Answer: Você pode usar o expected_conditions do selenium com phyton para validar se esse elemento é clicavel. No expected_conditions você pode usar esse cara element_to_be_clickable. Já se o problema for de fato a localização do elemento tu pode localizar ele por CSS Selector, ai tu localiza o elemento de text dentro do botão. Seria mais ou menos assim:
driver.find_element_by_css_selector('button.send-update > text')
Comment: O botão é clicável. Ele identifica o elemento e aparentemente TENTA clicar. Quando isso acontece, ele apenas faz um "hover" e não ocorre o evento de clique em si.


Use standard deviation of sample or population in z test

Question: I am reading the book Statistics by Witte & Witte. Some questions puzzle me.
Question 10.9:

The normal range for a widely accepted measure of body size, the body
  mass index (BMI), ranges from 18.5 to 25. Using the midrange BMI score
  of 21.75 as the null hypothesized value for the population mean, test
  this hypothesis at the .01 level of significance given a random sample
  of 30 weight-watcher participants who show a mean BMI = 22.2 and a
  standard deviation of 3.1.

The chapter explains the z test. It uses the following formula.
<code>z = (mean_sam - mean_pop) / (stdev_pop / sqrt(n))
</code>
In the question only a standard deviation of the sample is given. I don't no whether and how this affects this formula.
Answer: There are different tests (z/Gauss-test and t-test) depending on whether the population stdev is known or the sample stdev is plugged in.
Comment: Actually for large samples the two are pretty much the same (equivalent for $n \to\infty$), and even for $n=30$ they shouldn't give you something too different.
Comment: thank you Then I conclude the question is misguiding.


Azure Webapp and SQL Secure networking

Question: I believe i'm trying to do simple pretty basic with Azure, yet so far I didn't found anything "safe".
Basically, I just want to have a Azure WebApp and a Azure SQL Server (no VMs) communicating to each other, the WebApp been public on internet, and the SQL Server been accessible ONLY by THAT specific webapp.
I found 3 ways to "secure" the communication to an Azure SQL Server:

Allow Azure Services
Whitelisting IP Addresses
Accepting VNet connections

The issues i have with 1, is that anyone that have a azure subscription can reach my DB via multiple components...
With 2, is that the "most secure" is allowing the outbound IPs for the WebApp in the Datacenter, as far as i understand it, anyone could create a WebApp in the same datacenter I choose for my webapp and they will have a chance to be in the same "IP Groups", which means they could reach my DB...
And with 3, maybe it's just me, but went i did that, I could managed to found a way to communicate to my WebApp from Internet...
I believe it's a pretty basic requirement I have...
How do I do it?
Thanks in advances!
Comment: FYI, your outbound IP's are not the same for the whole datacentre, they are the same for apps deployed to the same cluster as you. Granted this is >1 but not on the scale of the whole data centre.
Comment: Yeah that makes senses , thanks for the precision, but it still a problem
Answer: You can have more granular network access control if you use Service Endpoints.  See our documentation here:  https://docs.microsoft.com/en-us/azure/sql-database/sql-database-vnet-service-endpoint-rule-overview
Comment: you can use an App Gateway to expose your web app to the public.  https://docs.microsoft.com/en-us/azure/app-service/environment/integrate-with-application-gateway
Comment: Ain't that the option 3? If yes, how can you make the webapp public? When I try that I can't access my web app, since it's behind the vnet
Comment: So I have no choice but use the ASE to make sure that only my apps can access my database? Is that right?
Comment: Yes, looking at your requirement that says only your web app can talk to your DB then the only PaaS option is an ASE which isolates your app to a dedicated environment.
Comment: hmmm, ok, that been said, is it me or this is a weird concept/specification? I believe what I intend to do is pretty basic and a lot of people have this "architecture" and requirement no? WebApp talking securely to its database? Why do we need a "special service" for that? Shouldn't that be a basic functionnality of Azure WebApp?

Azure Webapp and SQL Secure networking