Como terminar este programa com EOF?

Question: Estava resolvendo um problema do site UriOnlineJudge e foi pedido para que a entrada terminasse com EOF. Fiz o código perfeitamente, com exceção de que não sei implementar o tal do EOF. Como posso fazê-lo?
<code>#include <stdio.h>

int main(void){
    int N, Q, i, e[101], o[101], d, j, m = -1, n;
    scanf("%d %d", &N, &Q);

    for(i=0;i<101;i++){
        e[i] = 0;
        o[i] = 0;
    }

    for(i = 1;i<=N;i++){
        scanf("%d", &e[i]);
    }
    for(i = 1;i<=N;i++){
        for(j=1;j<=N;j++){
            if (e[j]>m){
                m=e[j];
                n = j;
            }
        }
        o[i]=m;
        e[n]=-2;
        m = -1;
    }
    for(i = 1;i<=Q;i++){
        scanf("%d", &d);
        printf("%d\n", o[d]);
    }
    return 0;
}
</code>
Answer: Apos ler a primeira linha (dois números inteiros) você utiliza o EOF dentro de um while para ler as n entradas:
<code>int entrada;
while(scanf("%d", &entrada) != EOF) {
    // ...
}
</code>

Como terminar este programa com EOF?


Operational State Down on QLogic Switch

Question: I have a QLogic SANbox 5800  Fibre Channel Switch with 20 SFP ports. Out of these 20, I can use only 16. The last 4 ports are showing Operational State Down.
SANbox (admin) #> show port

    Admin       Operational  Login       Config Running     Link     Link
  Port  State       State        Status      Type   Type        State    Speed
  ----  -----       -----------  ------      ------ -------     -----    -----
  0     Online      Online       LoggedIn    GL     F           Active   8Gb/s
...
  15    Online      Online       LoggedIn    GL     F           Active   8Gb/s
  16    Online      Downed       NotLoggedIn GL     Unknown(isolated) Inactive Auto
  17    Online      Downed       NotLoggedIn GL     Unknown(isolated) Inactive Auto
  18    Online      Downed       NotLoggedIn GL     Unknown(isolated) Inactive Auto
  19    Online      Downed       NotLoggedIn GL     Unknown(isolated) Inactive Auto

How can I activate these ports? None of the connections to these ports work. I attempted to change the Operational State and the Login Status of these 4 ports, but I was unsuccessful.
I also checked the licenses and it says 20 ports are licensed but it doesn't specify which ones.
SANbox #> show version

...
       LicensedPorts       20

EDIT 1
I didn't mention that I already went through all the physical troubleshooting steps. Replaced SFPs, cables, used different ports on the connected devices, and so forth... None of those are the issue.
EDIT 2
#> show port 15

  Port Number: 15
  ------------
  AdminState       Online              PortWWN          20:0f:00:c0:dd:0d:8e:35
  AsicNumber       0                   POSTFaultCode    00000000
  AsicPort         11                  POSTStatus       Passed
  ConfigType       GL                  RunningType      Unknown
  DownstreamISL    False               MediaPartNumber  FTLF8528P3BCV
  EpConnState      None                MediaRevision    A
  EpIsoReason      NotApplicable       MediaType        800-MX-SN-S
  IOStreamGuard    Disabled            MediaVendor      DHS
  Licensed         True                MediaVendorID    00009065
  LinkSpeed        Auto                SupportedSpeeds  1, 2, 4, 8Gb/s
  LinkState        Inactive            SymbolicName     Port15
  LoginStatus      NotLoggedIn         SyncStatus       SyncLost
  MaxCredit        16                  TestFaultCode    00000000
  MediaSpeeds      2, 4, 8Gb/s         TestStatus       NeverRun
  OperationalState Offline             UpstreamISL      False
  PerfTuningMode   Normal              XmitterEnabled   True
  PortID           010f00

  ALInit             6                   LIP_F8_F7          0
  ALInitError        0                   LinkFailures       0
  BadFrames          0                   Login              5
  BBCR_FrameFailures 0                   Logout             5
  BBCR_RRDYFailures  0                   LongFramesIn       0
  Class2FramesIn     0                   LoopTimeouts       0
  Class2FramesOut    0                   LossOfSync         4
  Class2WordsIn      0                   LostFrames         0
  Class2WordsOut     0                   LostRRDYs          0
  Class3FramesIn     545327186           PrimSeqErrors      0
  Class3FramesOut    529806484           RxLinkResets       5
  Class3Toss         0                   RxOfflineSeq       0
  Class3WordsIn      259248383265        ShortFramesIn      0
  Class3WordsOut     259221106454        TotalErrors        16
  DecodeErrors       16                  TotalLinkResets    5
  EpConnects         0                   TotalLIPsRecvd     0
  FBusy              0                   TotalLIPsXmitd     8
  FlowErrors         0                   TotalOfflineSeq    15
  FReject            0                   TotalRxFrames      545327186
  InvalidCRC         0                   TotalRxWords       259248383265
  InvalidDestAddr    0                   TotalTxFrames      529806484
  LIP_AL_PD_AL_PS    0                   TotalTxWords       259221106454
  LIP_F7_AL_PS       0                   TxLinkResets       0
  LIP_F7_F7          0                   TxOfflineSeq       15
  LIP_F8_AL_PS       0

#> show port 16

  Port Number: 16
  ------------
  AdminState       Online              PortWWN          20:10:00:c0:dd:0d:8e:35
  AsicNumber       0                   POSTFaultCode    00000000
  AsicPort         13                  POSTStatus       Passed
  ConfigType       GL                  RunningType      Unknown
  DownstreamISL    False               MediaPartNumber  FTLF8528P2BNV
  EpConnState      None                MediaRevision    A
  EpIsoReason      NotLicensed         MediaType        800-MX-SN-S
  IOStreamGuard    Disabled            MediaVendor      FINISAR CORP.
  Licensed         False               MediaVendorID    00009065
  LinkSpeed        Auto                SupportedSpeeds  1, 2, 4, 8Gb/s
  LinkState        Inactive            SymbolicName     Port16
  LoginStatus      NotLoggedIn         SyncStatus       SyncLost
  MaxCredit        16                  TestFaultCode    00000000
  MediaSpeeds      2, 4, 8Gb/s         TestStatus       NeverRun
  OperationalState Downed              UpstreamISL      False
  PerfTuningMode   Normal              XmitterEnabled   False
  PortID           011000

  ALInit             0                   LIP_F8_F7          0
  ALInitError        0                   LinkFailures       0
  BadFrames          0                   Login              0
  BBCR_FrameFailures 0                   Logout             0
  BBCR_RRDYFailures  0                   LongFramesIn       0
  Class2FramesIn     0                   LoopTimeouts       0
  Class2FramesOut    0                   LossOfSync         0
  Class2WordsIn      0                   LostFrames         0
  Class2WordsOut     0                   LostRRDYs          0
  Class3FramesIn     0                   PrimSeqErrors      0
  Class3FramesOut    0                   RxLinkResets       0
  Class3Toss         0                   RxOfflineSeq       0
  Class3WordsIn      0                   ShortFramesIn      0
  Class3WordsOut     0                   TotalErrors        0
  DecodeErrors       0                   TotalLinkResets    0
  EpConnects         0                   TotalLIPsRecvd     0
  FBusy              0                   TotalLIPsXmitd     0
  FlowErrors         0                   TotalOfflineSeq    0
  FReject            0                   TotalRxFrames      0
  InvalidCRC         0                   TotalRxWords       0
  InvalidDestAddr    0                   TotalTxFrames      0
  LIP_AL_PD_AL_PS    0                   TotalTxWords       0
  LIP_F7_AL_PS       0                   TxLinkResets       0
  LIP_F7_F7          0                   TxOfflineSeq       0
  LIP_F8_AL_PS       0

SANbox #> show config port 15

  Configuration Name: default
  -------------------

  Port Number: 15
  ------------
  AdminState           Online
  LinkSpeed            Auto
  PortType             GL
  SymbolicName         Port15
  ALFairness           False
  DeviceScanEnabled    True
  ForceOfflineRSCN     False
  ARB_FF               False
  InteropCredit        0
  ExtCredit            0
  FANEnabled           True
  AutoPerfTuning       True
  MSEnabled            True
  NoClose              False
  IOStreamGuard        Auto
  PDISCPingEnabled     True

SANbox #> show config port 16

  Configuration Name: default
  -------------------

  Port Number: 16
  ------------
  AdminState           Online
  LinkSpeed            Auto
  PortType             GL
  SymbolicName         Port16
  ALFairness           False
  DeviceScanEnabled    True
  ForceOfflineRSCN     False
  ARB_FF               False
  InteropCredit        0
  ExtCredit            0
  FANEnabled           True
  AutoPerfTuning       True
  MSEnabled            True
  NoClose              False
  IOStreamGuard        Auto
  PDISCPingEnabled     True

Comment: Can you please show the output of a `show port 15` and `show port 16`, as well as a `show config port 15` and `show config port 16`? The `show port` command is not as verbose, and I'd like to make sure that those ports are allowed to be F ports.
Comment: @Basil I edited the question with the extra information.
Comment: Yep, I edited my answer based on it :)
Comment: just for completion: I already was facing he same Situation in the past. Please keep in mind that the four 20GB uplink ports are also consuming licenses. So if you have 20 licenses your port 16 is unlicensed... Greetz, Sledge Callahan
Answer: edit: removed incorrect information
So I'm seeing the EpIsoReason for port 16 is "NotLicensed". It also shows Licensed: False. I'm not sure why your show version command reported 20 licensed ports. The feature log command should display the true number of licensed ports- if that also agrees that it's 20 and these ports are still offline, then I'd open a ticket.
Comment: That's the `Admin State` which is already online. The `Operational State` is the one that I have issues with. I have already tried that with no success.
Comment: Do you see light coming from whatever they're plugged into? Take a cable out, shine it on your hand. If this were a Brocade, I'd be able to use a command to tell whether it has any light to work with, but I don't know QLogic :(
Comment: I already went through all the physical troubleshooting steps. Replaced SFPs, cables, used different ports on the connected devices,... None of those are the issue.
Comment: So you do see light coming through? Like when you point the cable at your hand, you see a light?
Comment: I've already specified that I went through all these troubleshooting steps insuring the ports are completely down. If you're referring to light coming out of the switch port, no it's not. Is you're referring to light going into the switch port, yes it is.
Comment: I was indeed referring to light going to the switch port, and going through those troubleshooting steps is what you do when you don't have light coming into the switch, which is why I asked.

Operational State Down on QLogic Switch


Como criar uma list com alguns atributos em java?

Question: Estou com problemas para criar uma list onde eu possa inserir diferentes valores.
Utilizo os seguintes códigos:
public class avaliacaoMensal {
    private String questao;
    private char potencial;
    private int resultado;
}

public avaliacaoMensal todosMensal(){
    List<avaliacaoMensal> dados = new ArrayList<avaliacaoMensal>();
    dados.add("Aaa", 'a', 1);
}

Como fazer isso funcionar?
public AvaliacaoMensal todosMensal(){
        List<AvaliacaoMensal> dados = new ArrayList<AvaliacaoMensal>();
        dados.add(new AvaliacaoMensal("Aaa", 'a', 1));
        dados.add(new AvaliacaoMensal("Bbb", 'b', 2));
        dados.add(new AvaliacaoMensal("Ccc", 'c', 3));
        // Continuação do código

        return (AvaliacaoMensal) dados;
    }

Ai quando eu adicionar, gera o erro
AvaliacaoMensal() in AvaliacaoMensal cannot be applied to: Expected Parameters: Actual Arguments
Comment: A dúvida é: como iniciar o objeto diretamente no método `add` da lista?
Comment: Isso mesmo @Renan
Comment: @LucasCharles Eu coloquei no final da minha resposta como você pode fazer isso.
Comment: @jbueno Muito obrigado, está me salvando. Mas está dando o seguinte erro: AvaliacaoMensal() in AvaliacaoMensal cannot be applied to:
Expected Parameters:
Actual Arguments:
Comment: Preciso ver o código pra saber do que você tá falando
Comment: @jbueno Editei la
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/60019/discussion-between-lucas-charles-and-jbueno).
Answer: Isso não faz muito sentido. Um ArrayList de avaliacaoMensal só pode conter objetos do tipo avaliacaoMensal. Você precisa criar uma instância desta classe e adicionar o elemento na lista.
public avaliacaoMensal todosMensal(){
    List<avaliacaoMensal> dados = new ArrayList<avaliacaoMensal>();
    avaliacaoMensal aMensal = new avaliacaoMensal();
    // Fazer algo para setar o valor dos atributos questao, potencial e resultado
    dados.add(aMensal);
}

Perceba que o código atual da classe avaliacaoMensal não contém os métodos de acessos às propriedades da mesma (os famosos getters e setters), você precisa criá-los.
Também é bom seguir o padrão de nomenclatura do Java para nomes de classes (camel case com a primeira letra maiúscula), a classe deveria se chamar AvaliacaoMensal.
Uma prática bastante comum também é  a criação de construtores que recebam como parâmetro alguns valores de atributos, para já criar uma instância da classe com alguns valores determinados.
Sua classe, seguindo estas dicas, ficaria assim:
public class AvaliacaoMensal {
    private String questao;
    private char potencial;
    private int resultado;

    public AvaliacaoMensal(String questao, char potencial, int resultado) {
        this.questao = questao;
        this.potencial = potencial;
        this.resultado = resultado;
    }

    public String getQuestao() {
        return questao;
    }

    public void setQuestao(String questao) {
        this.questao = questao;
    }

    public char getPotencial() {
        return potencial;
    }

    public void setPotencial(char potencial) {
        this.potencial = potencial;
    }

    public int getResultado() {
        return resultado;
    }

    public void setResultado(int resultado) {
        this.resultado = resultado;
    }
}

Dessa maneira, você poderia usar parecido com o que tentou no início:
public AvaliacaoMensal todosMensal(){
    List<AvaliacaoMensal> dados = new ArrayList<AvaliacaoMensal>();
    dados.add(new AvaliacaoMensal("Aaa", 'a', 1));
    // Continuação do código
}

Você pode ver funcionando no repl.it.
Answer: Você precisa fazer da seguinte forma.
AvaliacaoMensal.java vai ter esse código:
public class AvaliacaoMensal {
private String questao;
private char potencial;
private int resultado;

public String getQuestao() {
    return questao;
}

public void setQuestao(String questao) {
    this.questao = questao;
}

public char getPotencial() {
    return potencial;
}

public void setPotencial(char potencial) {
    this.potencial = potencial;
}

public int getResultado() {
    return resultado;
}

public void setResultado(int resultado) {
    this.resultado = resultado;
}

}

Agora você pode pegar uma classe de teste e fazer isso para ver se funciona :
    ArrayList<AvaliacaoMensal> lista = new ArrayList<AvaliacaoMensal>();

    AvaliacaoMensal avaliacao = null;
    for (int i = 0; i < 3; i++) {
        avaliacao = new AvaliacaoMensal();
        avaliacao.setPotencial('T');
        avaliacao.setQuestao("Teste");
        avaliacao.setResultado(2);
        lista.add(avaliacao);
    }


How to rewrite all routes not going to a specific subdirectory to a different subdirectory in nginx?

Question: My site content (which is currently kept in /public_html loosely) is under a Mercurial repository, so I would like it to have its own directory. Since my wiki is under /public_html/wiki, I am trying to come up with routing logic that will route all requests not going to mysite.com/wiki to /public_html/content.
Currently I have:
server {
    listen 80;
    server_name www.mysite.com mysite.com;
    access_log /www/mysite.com/logs/access.log;
    error_log /www/mysite.com/logs/error.log;
    root /www/mysite.com/public_html;

    location / {
        index index.html index.htm index.php;
    }

    location ~/\.hg
    {
        deny all;
    }

    location ~ \.php$ {
        try_files  $uri  /404.html;
        include /etc/nginx/fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /www/mysite.com/public_html$fastcgi_script_name;
    }
}

I tried try_files $uri /content$uri but that just made it loop back in on itself with rewriting. I also couldn't catch /wiki prefix with a location block because I would have had to stop the pattern matching at that point, preventing the .php from being matched.
Answer: Just determine $document_root for every location and use this variable in location for php/fastcgi:
server {
    listen 80;
    server_name www.mysite.com mysite.com;
    access_log /www/mysite.com/logs/access.log;
    error_log /www/mysite.com/logs/error.log;

    location / {
        root /www/mysite.com/public_html;
        index index.html index.htm index.php;
    }

    location /wiki {
        root /www/mysite.com/wiki;
        index index.php;
    }

    location ~/\.hg {
            deny all;
    }

    location ~ \.php$ {
        try_files  $uri  /404.html;
        include /etc/nginx/fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

Comment: This kept blowing up on the `try_files  $uri  /404.html;` line; `$uri` failed and it went to 404. I eventually found something that worked that I will post.
Answer: This is what ended up working for me:
server {
    listen 80;
    server_name www.mysite.com mysite.com;
    access_log /www/mysite.com/logs/access.log;
    error_log /www/mysite.com/logs/error.log;
    root /www/mysite.com;

    location / {
        try_files /public_html$uri =404;
        index index.html index.htm index.php;
    }

    location /wiki {
        index index.php;
    }

    location ~/\.hg
    {
        deny all;
    }

    location ~ \.php$ {
        try_files $uri =404;
        include /etc/nginx/fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}


Get Cell Value After Text Search

Question: I'm currently working on Excel.
I have two columns (Column A and COlumn B). Column A contains a list of jobs(one job per cell), while column B contains the cost of each job per hour.
I'm trying to find a formula that tests if a given text or word (for example "Accountant") is contained in one of the cells in Column A, and then returns the corresponding value from Column B (next to it).
Thanks in advance for your help!
Answer: The answer is =VLOOKUP("ACCOUNTANT";[RANGE COLUMN A AND B];2;FALSO)
Comment: THANKS BRO! IT WORKS!
Comment: Having a party with yourself?

Get Cell Value After Text Search


sendgrid cpanel exim failure

Question: I was following instructions at the below websites
http://sendgrid.com/docs/Integrate/Mail_Servers/exim.html
http://knowledgelayer.softlayer.com/procedure/e-mail-delivery-service-server-side-configuration-centos-cpanel-exim
It seems to be configured correctly, but when I try to send an email via a php script I get the following error:
2013-03-23 17:09:48 cwd=/home/chrism/public_html 3 args: /usr/sbin/sendmail -t -i
2013-03-23 17:09:48 1UJVhE-0008SI-VG <= firstname.lastname@example.com U=chrism P=local S=389 T="Test" for email@example.com
2013-03-23 17:09:48 cwd=/var/spool/exim 3 args: /usr/sbin/exim -Mc 1UJVhE-0008SI-VG
2013-03-23 17:09:49 1UJVhE-0008SI-VG remote host address is the local host: yahoo.com
2013-03-23 17:09:49 1UJVhE-0008SI-VG == firstname.lastname@example.com R=send_via_sendgrid defer (-1): remote host address is the local host
2013-03-23 17:09:49 1UJVhE-0008SI-VG Frozen

I am trying to send to a @yahoo.com address but it fails for some reason.
dig yahoo.com
root@host [~]# dig -t mx yahoo.com
; <<>> DiG 9.3.6-P1-RedHat-9.3.6-20.P1.el5_8.6 <<>> -t mx yahoo.com
;; global options:  printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 50122
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 7, ADDITIONAL: 7

;; QUESTION SECTION:
;yahoo.com.         IN  MX

;; ANSWER SECTION:
yahoo.com.      576 IN  MX  1 mta5.am0.yahoodns.net.
yahoo.com.      576 IN  MX  1 mta6.am0.yahoodns.net.
yahoo.com.      576 IN  MX  1 mta7.am0.yahoodns.net.

;; AUTHORITY SECTION:
yahoo.com.      147199  IN  NS  ns4.yahoo.com.
yahoo.com.      147199  IN  NS  ns5.yahoo.com.
yahoo.com.      147199  IN  NS  ns6.yahoo.com.
yahoo.com.      147199  IN  NS  ns8.yahoo.com.
yahoo.com.      147199  IN  NS  ns1.yahoo.com.
yahoo.com.      147199  IN  NS  ns2.yahoo.com.
yahoo.com.      147199  IN  NS  ns3.yahoo.com.

;; ADDITIONAL SECTION:
ns1.yahoo.com.      8562    IN  A   220.127.116.11
ns2.yahoo.com.      8562    IN  A   22.214.171.124
ns3.yahoo.com.      147199  IN  A   126.96.36.199
ns4.yahoo.com.      8562    IN  A   220.127.116.11
ns5.yahoo.com.      8562    IN  A   188.8.131.52
ns6.yahoo.com.      8562    IN  A   22.214.171.124
ns8.yahoo.com.      8562    IN  A   18.104.22.168

;; Query time: 31 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Sun Mar 24 13:48:02 2013
;; MSG SIZE  rcvd: 344

exim command:
root@host [~]# exim -d -bt firstname.lastname@example.com
Exim version 4.80 uid=0 gid=0 pid=13408 D=fbb95cfd
Berkeley DB: Sleepycat Software: Berkeley DB 4.3.29: (July 12, 2010)
Support for: crypteq iconv() IPv6 PAM Perl OpenSSL Content_Scanning DKIM Old_Demime Experimental_SPF Experimental_SRS
Lookups (built-in): lsearch wildlsearch nwildlsearch iplsearch dbm dbmjz dbmnz passwd
Authenticators: cram_md5 dovecot plaintext spa
Routers: accept dnslookup ipliteral manualroute queryprogram redirect
Transports: appendfile/maildir autoreply pipe smtp
Size of off_t: 8
Compiler: GCC [4.1.2 20080704 (Red Hat 4.1.2-52)]
Library version: OpenSSL: Compile: OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008
                          Runtime: OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008
Library version: PCRE: Compile: 8.12
                       Runtime: 8.12 2011-01-15
Total 9 lookups
WHITELIST_D_MACROS unset
TRUSTED_CONFIG_LIST: "/etc/exim_trusted_configs"
changed uid/gid: forcing real = effective
  uid=0 gid=0 pid=13408
  auxiliary group list: <none>
seeking password data for user "cpaneleximfilter": cache not available
getpwnam() succeeded uid=508 gid=505
seeking password data for user "root": cache not available
getpwnam() succeeded uid=0 gid=0
changed uid/gid: calling tls_validate_require_cipher
  uid=47 gid=12 pid=13409
  auxiliary group list: <none>
tls_require_ciphers expands to "ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:-LOW:-SSLv2:-EXP"
tls_validate_require_cipher child 13409 ended: status=0x0
configuration file is /etc/exim.conf
log selectors = 00001dfc 00293043
trusted user
admin user
seeking password data for user "mailnull": cache not available
getpwnam() succeeded uid=47 gid=47
originator: uid=0 gid=0 login=root name=root
sender address = firstname.lastname@example.com
Address testing: uid=0 gid=12 euid=0 egid=12
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Testing firstname.lastname@example.com
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Considering email@example.com
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
routing email@example.com
--------> send_via_sendgrid router <--------
local_part=blasto333 domain=yahoo.com
checking domains
search_open: lsearch "/etc/localdomains"
search_find: file="/etc/localdomains"
  key="yahoo.com" partial=-1 affix=NULL starflags=0
LRU list:
  4/etc/localdomains
  End
internal_search_find: file="/etc/localdomains"
  type=lsearch key="yahoo.com"
file lookup required for yahoo.com
  in /etc/localdomains
lookup failed
yahoo.com in "lsearch;/etc/localdomains"? no (end of list)
yahoo.com in "! +local_domains"? yes (end of list)
calling send_via_sendgrid router
send_via_sendgrid router called for firstname.lastname@example.com
  domain = yahoo.com
route_item = * smtp.sendgrid.net::587 byname
yahoo.com in "*"? yes (matched "*")
original list of hosts = "smtp.sendgrid.net::587" options = byname
expanded list of hosts = "smtp.sendgrid.net::587" options = byname
set transport sendgrid_smtp
finding IP address for smtp.sendgrid.net:587
host=smtp.sendgrid.net port=587
calling host_find_byname
gethostbyname2(af=inet6) returned 4 (NO_DATA)
local host found for non-MX address
fully qualified name = host.blastohosting.com
gethostbyname2 looked up these IP addresses:
  name=host.blastohosting.com address=188.8.131.52
LOG: MAIN
  remote host address is the local host: yahoo.com (while routing <email@example.com>)
send_via_sendgrid router: defer for email@example.com
  message: remote host address is the local host
email@example.com cannot be resolved at this time: remote host address is the local host
search_tidyup called
>>>>>>>>>>>>>>>> Exim pid=13408 terminating with rc=1 >>>>>>>>>>>>>>>>

exim command with default settings:
root@host [~]# exim -d -bt firstname.lastname@example.com
Exim version 4.80 uid=0 gid=0 pid=13681 D=fbb95cfd
Berkeley DB: Sleepycat Software: Berkeley DB 4.3.29: (July 12, 2010)
Support for: crypteq iconv() IPv6 PAM Perl OpenSSL Content_Scanning DKIM Old_Demime Experimental_SPF Experimental_SRS
Lookups (built-in): lsearch wildlsearch nwildlsearch iplsearch dbm dbmjz dbmnz passwd
Authenticators: cram_md5 dovecot plaintext spa
Routers: accept dnslookup ipliteral manualroute queryprogram redirect
Transports: appendfile/maildir autoreply pipe smtp
Size of off_t: 8
Compiler: GCC [4.1.2 20080704 (Red Hat 4.1.2-52)]
Library version: OpenSSL: Compile: OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008
                          Runtime: OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008
Library version: PCRE: Compile: 8.12
                       Runtime: 8.12 2011-01-15
Total 9 lookups
WHITELIST_D_MACROS unset
TRUSTED_CONFIG_LIST: "/etc/exim_trusted_configs"
changed uid/gid: forcing real = effective
  uid=0 gid=0 pid=13681
  auxiliary group list: <none>
seeking password data for user "cpaneleximfilter": cache not available
getpwnam() succeeded uid=508 gid=505
seeking password data for user "root": cache not available
getpwnam() succeeded uid=0 gid=0
changed uid/gid: calling tls_validate_require_cipher
  uid=47 gid=12 pid=13682
  auxiliary group list: <none>
tls_require_ciphers expands to "ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:-LOW:-SSLv2:-EXP"
tls_validate_require_cipher child 13682 ended: status=0x0
configuration file is /etc/exim.conf
log selectors = 00001dfc 00293043
trusted user
admin user
seeking password data for user "mailnull": cache not available
getpwnam() succeeded uid=47 gid=47
originator: uid=0 gid=0 login=root name=root
sender address = email@example.com
Address testing: uid=0 gid=12 euid=0 egid=12
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Testing email@example.com
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Considering firstname.lastname@example.com
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
routing firstname.lastname@example.com
--------> democheck router <--------
local_part=blasto333 domain=yahoo.com
checking require_files
file check: +/etc/demouids
expanded file: /etc/demouids
stat() yielded 0
checking "condition"
search_open: lsearch "/etc/demouids"
search_find: file="/etc/demouids"
  key="0" partial=-1 affix=NULL starflags=0
LRU list:
  4/etc/demouids
  End
internal_search_find: file="/etc/demouids"
  type=lsearch key="0"
file lookup required for 0
  in /etc/demouids
lookup failed
democheck router skipped: condition failure
--------> check_mail_permissions router <--------
local_part=blasto333 domain=yahoo.com
checking domains
search_open: lsearch "/etc/localdomains"
search_find: file="/etc/localdomains"
  key="yahoo.com" partial=-1 affix=NULL starflags=0
LRU list:
  4/etc/localdomains
  4/etc/demouids
  End
internal_search_find: file="/etc/localdomains"
  type=lsearch key="yahoo.com"
file lookup required for yahoo.com
  in /etc/localdomains
lookup failed
yahoo.com in "lsearch;/etc/localdomains"? no (end of list)
yahoo.com in "! +local_domains"? yes (end of list)
checking "condition"
Starting Perl interpreter
search_open: passwd "NULL"
search_find: file="NULL"
  key="nobody" partial=-1 affix=NULL starflags=0
LRU list:
  4/etc/localdomains
  4/etc/demouids
  End
internal_search_find: file="NULL"
  type=passwd key="nobody"
database lookup required for nobody
seeking password data for user "nobody": cache not available
getpwnam() succeeded uid=99 gid=99
lookup yielded: *:99:99:Nobody:/:/sbin/nologin
search_open: lsearch "/etc/domainusers"
search_find: file="/etc/domainusers"
  key="root" partial=-1 affix=NULL starflags=0
LRU list:
  4/etc/domainusers
  4/etc/localdomains
  4/etc/demouids
  End
internal_search_find: file="/etc/domainusers"
  type=lsearch key="root"
file lookup required for root
  in /etc/domainusers
lookup failed
search_open: lsearch "/etc/userdomains"
search_find: file="/etc/userdomains"
  key="" partial=-1 affix=NULL starflags=0
LRU list:
  4/etc/userdomains
  4/etc/domainusers
  4/etc/localdomains
  4/etc/demouids
  End
internal_search_find: file="/etc/userdomains"
  type=lsearch key=""
search_open: lsearch "/etc/userdomains"
  cached open
search_find: file="/etc/userdomains"
  key="host.blastohosting.com" partial=-1 affix=NULL starflags=0
LRU list:
  4/etc/userdomains
  4/etc/domainusers
  4/etc/localdomains
  4/etc/demouids
  End
internal_search_find: file="/etc/userdomains"
  type=lsearch key="host.blastohosting.com"
file lookup required for host.blastohosting.com
  in /etc/userdomains
lookup failed
check_mail_permissions router skipped: condition failure
--------> enforce_mail_permissions router <--------
local_part=blasto333 domain=yahoo.com
checking domains
cached no match for +local_domains
cached lookup data = NULL
yahoo.com in "! +local_domains"? yes (end of list)
checking "condition"
enforce_mail_permissions router skipped: condition failure
--------> increment_max_emails_per_hour_if_needed router <--------
local_part=blasto333 domain=yahoo.com
checking domains
cached no match for +local_domains
cached lookup data = NULL
yahoo.com in "! +local_domains"? yes (end of list)
checking "condition"
increment_max_emails_per_hour_if_needed router skipped: condition failure
--------> dkim_lookuphost router <--------
local_part=blasto333 domain=yahoo.com
checking domains
cached no match for +local_domains
cached lookup data = NULL
yahoo.com in "! +local_domains"? yes (end of list)
checking require_files
file check: +/var/cpanel/domain_keys/private/${sender_address_domain}
expanded file: /var/cpanel/domain_keys/private/host.blastohosting.com
stat() yielded -1
errno = 2
dkim_lookuphost router skipped: file check
--------> lookuphost router <--------
local_part=blasto333 domain=yahoo.com
checking domains
cached no match for +local_domains
cached lookup data = NULL
yahoo.com in "! +local_domains"? yes (end of list)
calling lookuphost router
lookuphost router called for email@example.com
  domain = yahoo.com
DNS lookup of yahoo.com (MX) succeeded
DNS lookup of mta5.am0.yahoodns.net (AAAA) gave NO_DATA
returning DNS_NODATA
DNS lookup of mta5.am0.yahoodns.net (A) succeeded
220.127.116.11 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
22.214.171.124 in "+loopback : 220.127.116.11/24"? no (end of list)
126.96.36.199 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
188.8.131.52 in "+loopback : 220.127.116.11/24"? no (end of list)
220.127.116.11 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
126.96.36.199 in "+loopback : 18.104.22.168/24"? no (end of list)
126.96.36.199 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
22.214.171.124 in "+loopback : 184.108.40.206/24"? no (end of list)
184.108.40.206 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
188.8.131.52 in "+loopback : 188.8.131.52/24"? no (end of list)
184.108.40.206 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
220.127.116.11 in "+loopback : 220.127.116.11/24"? no (end of list)
220.127.116.11 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
184.108.40.206 in "+loopback : 18.104.22.168/24"? no (end of list)
220.127.116.11 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
184.108.40.206 in "+loopback : 18.104.22.168/24"? no (end of list)
DNS lookup of mta6.am0.yahoodns.net (AAAA) gave NO_DATA
returning DNS_NODATA
DNS lookup of mta6.am0.yahoodns.net (A) succeeded
184.108.40.206 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
22.214.171.124 in "+loopback : 126.96.36.199/24"? no (end of list)
220.127.116.11 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
18.104.22.168 in "+loopback : 184.108.40.206/24"? no (end of list)
188.8.131.52 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
126.96.36.199 in "+loopback : 126.96.36.199/24"? no (end of list)
126.96.36.199 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
18.104.22.168 in "+loopback : 188.8.131.52/24"? no (end of list)
126.96.36.199 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
220.127.116.11 in "+loopback : 22.214.171.124/24"? no (end of list)
220.127.116.11 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
220.127.116.11 in "+loopback : 188.8.131.52/24"? no (end of list)
126.96.36.199 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
220.127.116.11 in "+loopback : 188.8.131.52/24"? no (end of list)
184.108.40.206 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
18.104.22.168 in "+loopback : 188.8.131.52/24"? no (end of list)
DNS lookup of mta7.am0.yahoodns.net (AAAA) gave NO_DATA
returning DNS_NODATA
DNS lookup of mta7.am0.yahoodns.net (A) succeeded
126.96.36.199 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
22.214.171.124 in "+loopback : 184.108.40.206/24"? no (end of list)
220.127.116.11 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
126.96.36.199 in "+loopback : 126.96.36.199/24"? no (end of list)
126.96.36.199 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
126.96.36.199 in "+loopback : 184.108.40.206/24"? no (end of list)
188.8.131.52 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
188.8.131.52 in "+loopback : 22.214.171.124/24"? no (end of list)
126.96.36.199 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
126.96.36.199 in "+loopback : 18.104.22.168/24"? no (end of list)
18.104.22.168 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
22.214.171.124 in "+loopback : 188.8.131.52/24"? no (end of list)
220.127.116.11 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
220.127.116.11 in "+loopback : 188.8.131.52/24"? no (end of list)
126.96.36.199 in "<; 127.0.0.0/8 ; 0.0.0.0 ; ::1 ; 0000:0000:0000:0000:0000:ffff:7f00:0000/8"? no (end of list)
22.214.171.124 in "+loopback : 220.127.116.11/24"? no (end of list)
duplicate IP address 220.127.116.11 (MX=1) removed
duplicate IP address 184.108.40.206 (MX=1) removed
duplicate IP address 188.8.131.52 (MX=1) removed
duplicate IP address 188.8.131.52 (MX=1) removed
duplicate IP address 184.108.40.206 (MX=1) removed
duplicate IP address 18.104.22.168 (MX=1) removed
duplicate IP address 220.127.116.11 (MX=1) removed
duplicate IP address 220.127.116.11 (MX=1) removed
duplicate IP address 184.108.40.206 (MX=1) removed
duplicate IP address 188.8.131.52 (MX=1) removed
duplicate IP address 184.108.40.206 (MX=1) removed
fully qualified name = yahoo.com
host_find_bydns yield = HOST_FOUND (2); returned hosts:
  mta5.am0.yahoodns.net 126.96.36.199 MX=1
  mta5.am0.yahoodns.net 184.108.40.206 MX=1
  mta5.am0.yahoodns.net 126.96.36.199 MX=1
  mta5.am0.yahoodns.net 220.127.116.11 MX=1
  mta5.am0.yahoodns.net 188.8.131.52 MX=1
  mta5.am0.yahoodns.net 184.108.40.206 MX=1
  mta5.am0.yahoodns.net 126.96.36.199 MX=1
  mta5.am0.yahoodns.net 220.127.116.11 MX=1
  mta6.am0.yahoodns.net 18.104.22.168 MX=1
  mta6.am0.yahoodns.net 220.127.116.11 MX=1
  mta6.am0.yahoodns.net 188.8.131.52 MX=1
  mta7.am0.yahoodns.net 184.108.40.206 MX=1
  mta7.am0.yahoodns.net 188.8.131.52 MX=1
set transport remote_smtp
queued for remote_smtp transport: local_part = blasto333
domain = yahoo.com
  errors_to=NULL
  domain_data=NULL localpart_data=NULL
routed by lookuphost router
  envelope to: firstname.lastname@example.com
  transport: remote_smtp
  host mta5.am0.yahoodns.net [188.8.131.52] MX=1
  host mta5.am0.yahoodns.net [220.127.116.11] MX=1
  host mta5.am0.yahoodns.net [220.127.116.11] MX=1
  host mta5.am0.yahoodns.net [22.214.171.124] MX=1
  host mta5.am0.yahoodns.net [126.96.36.199] MX=1
  host mta5.am0.yahoodns.net [126.96.36.199] MX=1
  host mta5.am0.yahoodns.net [220.127.116.11] MX=1
  host mta5.am0.yahoodns.net [184.108.40.206] MX=1
  host mta6.am0.yahoodns.net [184.108.40.206] MX=1
  host mta6.am0.yahoodns.net [220.127.116.11] MX=1
  host mta6.am0.yahoodns.net [18.104.22.168] MX=1
  host mta7.am0.yahoodns.net [188.8.131.52] MX=1
  host mta7.am0.yahoodns.net [188.8.131.52] MX=1
firstname.lastname@example.com
  router = lookuphost, transport = remote_smtp
  host mta5.am0.yahoodns.net [126.96.36.199]  MX=1
  host mta5.am0.yahoodns.net [126.96.36.199]  MX=1
  host mta5.am0.yahoodns.net [184.108.40.206]   MX=1
  host mta5.am0.yahoodns.net [126.96.36.199]  MX=1
  host mta5.am0.yahoodns.net [184.108.40.206]  MX=1
  host mta5.am0.yahoodns.net [220.127.116.11]  MX=1
  host mta5.am0.yahoodns.net [126.96.36.199] MX=1
  host mta5.am0.yahoodns.net [18.104.22.168] MX=1
  host mta6.am0.yahoodns.net [220.127.116.11]  MX=1
  host mta6.am0.yahoodns.net [188.8.131.52]   MX=1
  host mta6.am0.yahoodns.net [188.8.131.52]  MX=1
  host mta7.am0.yahoodns.net [126.96.36.199]  MX=1
  host mta7.am0.yahoodns.net [188.8.131.52]  MX=1
search_tidyup called
>>>>>>>>>>>>>>>> Exim pid=13681 terminating with rc=0 >>>>>>>>>>>>>>>>

Comment: It looks very much like "yahoo.com" resolves to the IP of the mail server you are working on.  Check what "dig -t mx yahoo.com" returns, and make sure that yahoo.com isn't somehow errantly defined in your /etc/hosts file.  Beyond that, show the results of "exim -d -bt firstname.lastname@example.com" and we'll see if there is some weird dns resolution issue going on.
Comment: I have added results of command. I also added how it looks when cpanel/whm is using exim default settings.
Answer: Check your cPanel email settings - I think it is in Mail >> MX entry section - is "Local mail exchanger" enabled? In that case, I believe, sendmail tries to deliver the email locally but since your server is not yahoo.com, it obviously fails. Unless you have some special requirements, you should probably set it to "Remote mail exchanger".
By the way, if you're using Sendgrid for email and you're sending large volumes of email, I'd suggest using their HTTP API - SMTP is a very verbose protocol and I've had considerable speed improvements when I switched from SMTP to HTTP.
Comment: since EXIM is a system wide configuration and NOT per domain. I think I would have to do this for all accounts. Is there a better solution?
Comment: The issue is that cPanel has added your domain - host.blastohosting.com - to /etc/localdomains, i.e. this domain is in the list of domains that should have their emails routed locally. If you change the mail exchanger setting to remote, *or* remove the domain from /etc/localdomains and add to /etc/remotedomains manually, you should be fine.

sendgrid cpanel exim failure


Any idea why draggable div not released on mouse up in IE?

Question: I use Jquery-UI draggable feature in my project.
It works perfect in Chrome.  It is also working in IE but it's buggy.
On IE When I click on 'draggable' div and start drug the div everything is OK. But when I release key (on mouse up) the 'draggble' div is not released and it continues to repeat mouse movements until the page reloads.
HTML:

Drag me around

And here is js bind method:
 $(function() {
    $( "#draggable" ).draggable();
  } );

Any idea why draggable div not released in IE?
UPDATE:
 I don't get any errors in the IE console.
Comment: I test your code in IE 11 but it work properly. Please this [fiddle](https://fiddle.jshell.net/ali_soltani/wrLypu4c/) in IE 11.
Comment: Have you checked to see if there is any error being reported in the IE console? That might get you started.
Comment: What version of IE are you using? jQuery UI officially supports IE11. Also check your document mode by opening developer tools.
Comment: @ice13 I use  IE11
Comment: The instance when the release is not working for me on IE/edge is when I click the draggable element and move my cursor out of the draggable area and release the mouse key and then move the cursor back the to draggable area.
Comment: https://stackoverflow.com/questions/11943344/jqueryui-draggable-not-working-in-ie
Comment: You might solve the problem with disabling compatibility mode in IE. ``
Comment: It's working in IE10, it would be good if you provide how to reproduce or gif or fiddle.
Comment: can you create fiddle for this?
Answer: Maybe it happens because you try to open the page locally and IE blocks some features? Try to upload your files to a server and run them from there to see if the problem still persists.


How do I display an image in a table column from a local URL?

Question: I need help in displaying an image to a table column. I have a programme which will ask input from the users (organisations) and one of them is to upload an image. Once they upload their image, the URL will be saved to a file according to the other details which they have filled in. This is part of the code for the model org (organisation) data:
final static ObservableList<OrgData> data = FXCollections.observableArrayList();

public OrgData(String email, String pw, String name, String contact, String address, String type,
        String desc,String status,String url) {
    super();
    this.email = email;
    this.pw = pw;
    this.name = name;
    this.contact = contact;
    this.address = address;
    this.type = type;
    this.desc = desc;
    this.status=status;
    this.url=url;
}

public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPw() {
    return pw;
}

public void setPw(String pw) {
    this.pw = pw;
}

public String getPw2() {
    return pw2;
}

public void setPw2(String pw2) {
    this.pw2 = pw2;
}

public String getName() {
    return name;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public void setName(String name) {
    this.name = name;
}

public String getContact() {
    return contact;
}

public void setContact(String contact) {
    this.contact = contact;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public void setType(String type) {
    this.type = type;
}

public String getType() {
    return type;
}

public String getDesc() {
    return desc;
}

public void setDesc(String desc) {
    this.desc = desc;
}

public String toString(){
    return email+","+pw+","+name+","+contact+","+address+","+type+","+desc+","+status+","+url;
}

This is part of the code for saving the data in a file:
String Type = ""+type;
        System.out.println(Type);
        String Desc = desc.getText();

        String url = imageURL;
        url = url.substring(6,url.length());
        System.out.println(url);
        InputStream d = new FileInputStream(new File(url));
        url=output(d);
        System.out.println(url);

        OrgData table = new OrgData(Email,Password,Name, Contact,Address,Type,Desc,null,url);

        OrgDataDAO dao = new OrgDataDAO();
        dao.createOrg(table);
    }

I'm able to view the other data by doing these lines of code as they will display strings in a table, but I do not want to display the URL but the image:
//data in table
        OrgDataDAO dao=new OrgDataDAO();
        data = dao.getAllOrg();

            //List Of table column

            email.setCellValueFactory(new PropertyValueFactory<OrgData, String>("email"));
            Orgname.setCellValueFactory(new PropertyValueFactory<OrgData, String>("name"));
            contact.setCellValueFactory(new PropertyValueFactory<OrgData, String>("contact"));
            address.setCellValueFactory(new PropertyValueFactory<OrgData, String>("address"));
            category.setCellValueFactory(new PropertyValueFactory<OrgData, String>("type"));
            description.setCellValueFactory(new PropertyValueFactory<OrgData, String>("desc"));
            //displaying pic from url code here
            pic.setCellValueFactory(new PropertyValueFactory<OrgData, ImageView>("url"));
            status.setCellValueFactory( new PropertyValueFactory<>( "DUMMY" ));

Note the line where it says pic.setCellValue.... line of code will just display the URL of the image from the data in the file, not the image itself, so what do I need to change to display the image in the table? The DUMMY can be ignored due to the fact that there will be radio buttons in that column. But the problem I have is regarding the image.
Answer: I think you should use a jeditorPane and display the image in it using html


react firebase config .env file doesn't work

Question: i have a question about configuration of firebase with a react app. I put all firebase config info in .env file at the top directory as environmental variables. When I tried to use them as process.env.REACT_APP_smth, they all didn't work. Once I replaced the variables to real, raw config info, my app worked. But For sure, it's too dangerous so I don't wanna do it.
Also, the .env file was darker in vs code like mentioning it's not valid or smth.

Anyone knows how to tackle with this issue??
Thanks for your time and effort here in advance.
.env
I replaced REACT_APP_FIREBASE_API_KEY with 123456789.
REACT_APP_FIREBASE_API_KEY = "123456789"
REACT_APP_FIREBASE_AUTH_DOMAIN = "kinnikuhub.firebaseapp.com"
REACT_APP_FIREBASE_DATABASE_URL = "https://kinnikuHub.firebaseio.com"
REACT_APP_FIREBASE_PROJECT_ID = "kinnikuhub"
REACT_APP_FIREBASE_STORAGE_BUCKET = "kinnikuhub.appspot.com"
REACT_APP_FIREBASE_MESSAGING_SENDER_ID = "131675559"
REACT_APP_FIREBASE_APP_ID = "1:131675559:web:3ca3bbad263b6be90ff282"

firebase.js
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// import { getAnalytics } from "firebase/analytics";
import { addDoc, getDocs, getFirestore } from "firebase/firestore"
import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
import { collection } from "firebase/firestore";
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID,
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
// const analytics = getAnalytics(app);
export const db = getFirestore();

export const auth = getAuth(app);
const provider = new GoogleAuthProvider();
export const signInWithGoogle = () => {
  signInWithPopup(auth, provider)
    .then((res) => {
      console.log(res);

      // todo: Why create users table?? To let users have personal info, number of answers and quizzes cretaed, biography, sns links, etc
      // todo: 1st, check if res.user exists
      const userCollectionRef = collection(db, 'users');
      let userExistance = false;
      console.log(`currentUser.uid => ${res.user.uid}`)
      console.log(userExistance)
      const checkUserExists = async () => {
        const querySnapshot = await getDocs(userCollectionRef);
        querySnapshot.forEach( (doc) => {
          // doc.data() is never undefined for query doc snapshots
          // console.log(doc.id, " => ", doc.data());
          // console.log(`currentUser.uid => ${res.user.uid}`)
          if (doc.data().uid === res.user.uid) {
            userExistance = true;
            // console.log(userExistance)
            return 0;
          }
        });
        console.log(userExistance)
        // todo: 2nd, add this user to users collection if it doesn't exists
        if (userExistance === false) {
          console.log(`userExistance is false, meaning this user hasn't been registerd so I am going add the user into users collection!!! ${res.user.displayName}, ${JSON.stringify(res.user)}`)
          const addUser = async () => {
            const payload = {
              username: res.user.displayName,
              uid: res.user.uid,
              email: res.user.email,
              photoURL: res.user.photoURL,
              createdAt: new Date(),
              bio: "biography",
            };
            await addDoc(userCollectionRef, payload);
          }
          addUser();
        } else {
          console.log('This user has been already registered!! So glad he/she keeps using this app!!')
        }
      }
      checkUserExists();

    }).catch((err) => {
      console.log(err);
    })
}

// export const AuthState = () => {
//   const [userInfo, setUserInfo] = useState({})
//   onAuthStateChanged(auth, (user) => {
//     if (user) {
//       const username = user.displayName;
//       const uid = user.uid;
//       const email = user.email;
//       const photoURL = user.photoURL
//       // const emailVerified = user.emailVerified

//       setUserInfo({username, uid, email, photoURL});

//       console.log(`username => ${username}`)
//       console.log(`uid => ${uid}`)
//       console.log(`email => ${email}`)
//       console.log(`photoURL => ${photoURL}`)
//       // console.log(`emailVerified => ${emailVerified}`)
//       return userInfo;
//     } else {
//       console.log("no user signed in")
//     }
//   })
// }

// sendEmailVerification(auth.currentUser)
//   .then(() => {
//     console.log('email verification sent!')
//   })

##.gitignore
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
.env
npm-debug.log*
yarn-debug.log*
yarn-error.log*

Background:
Yesterday, I initialized my pc to install Monterey in my macbook air and files in the pc were all gone. Then, I git-cloned the repo of this app.
Answer: You have everything correct from what I see except the file naming itself. I too struggled to try to get this to work until I made this simple change:
Try renaming your 'firebase.js' file to 'firebase.config.js', this will read your process.env variables as actual variables.
Answer: The variable values in .env should not be enclosed in the quotation marks. Remove the quotation marks.
Answer: You may have forgotten to restart the whole app. run npm start again
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: I have faced the same problem, let me share, how I am able to solve the problem.
firstly, change the file name which should be firebase.config.js and .env.local
secondly, set those files in the proper position. Here,  files should be settled in the same as where package.json file is allocated.
Now, in the .env.local file, the variable name must be started like this,
EX:
VITE_apiKey = abc
VITE_authDomain = abc
VITE_projectId = abc
VITE_storageBucket = abc
VITE_messagingSenderId = abc
VITE_appId = abc
[replace abc with firebase API keys]

Lastly, in firebase.config.js file, variable should be imported like this,
const firebaseConfig = {
  apiKey: import.meta.env.VITE_apiKey,
  authDomain: import.meta.env.VITE_authDomain,
  projectId: import.meta.env.VITE_projectId,
  storageBucket: import.meta.env.VITE_storageBucket,
  messagingSenderId: import.meta.env.VITE_messagingSenderId,
  appId: import.meta.env.VITE_appId
};

This way I am able to solve my problem. Thank you.
Answer: Faced similar issue and what solved it for me was putting the process.env.something in template literals (aka template strings) like below.
const firebaseConfig = {
  apiKey: `${process.env.REACT_APP_FIREBASE_API_KEY}`,
  authDomain: `${process.env.REACT_APP_FIREBASE_AUTH_DOMAIN}`,
  projectId: `${process.env.REACT_APP_FIREBASE_PROJECT_ID}`,
  storageBucket: `${process.env.REACT_APP_FIREBASE_STORAGE_BUCKET}`,
  messagingSenderId: `${process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID}`,
  appId: `${process.env.REACT_APP_FIREBASE_APP_ID}`,
};

Answer: I also had the same issue. I solved the issue by only replacing the projectID with the actual variable.
ex:-

const firebaseConfig = {
    apiKey: process.env.REACT_APP_APIKEY,
    authDomain: process.env.REACT_APP_AUTHDOMAIN,
    projectId: "personal-portfolio-f1e9f",
    storageBucket: process.env.REACT_APP_STORAGEBUCKET,
    messagingSenderId: process.env.REACT_APP_MESSAGINGSENDERID,
    appId: process.env.APPID,
    measurementId: process.env.MEASUREMENTID
  };


Project Centennial Apps in Hololens Emulator

Question: I have successfully converted my WPF based .net applications to UWP using Project Centennial. When i upload that project to Hololens Emulator using Emulator portal i get the following error.
My UWP app is compiled for x86 and the emulator version is 10.0.14393.0
<code>Failure reason: Failed to start deployment.
Failure text: A Prerequisite for an install could not be satisfied.(0x80073cfd)
</code>
Answer: HoloLens doesn't support Win32. Your app is Win32 just packed in .appx. It works on PC only and not on other device families. You may add an UWP app to the same package that will serve non-PC devices.
Comment: I have the same problem. Tried with x64 and I get "Failure reason: Failed to start deployment. Failure text: The deployment operation failed because the package targets the wrong processor architecture.
 (0x80073d10)"


Prolog, not sure as to why it is returning no

Question: In this example Sophia is the mother of George.
When I type in  the code: motherOf(sophia,george). prolog returns yes.
However if I type: motherOf(X,george). it returns X=sophia ?  I type y but it returns no.
What is the reason for it returning no when it should be yes.
Comment: Another example is if I do `motherOf(sophia,Y).` it returns `Y = george` yes.
Comment: What prolog implementation are you using?
Comment: @aBathologist gprolog
Answer: "No." because there aren't any other solutions. If sophia has more than one child, you'll be given both solutions when querying for "motherOf(sophia, Y)." before computer says "No."
Try it with an additional "motherOf(sophia, homer)." clause in the DB.
Comment: @BobDunakey that's because when you press return you are telling Prolog not to search for any more solutions. So there isn't a failure to find another (which is why entering `;` yields a "no" since it searches for another and fails). When you entered `motherOf(sophia,george).` it only has one choice since there are no uninstantiated variables, so it returns "yes" if what you typed is true or it would return "no" if it didn't find it (it was false).
Comment: Thanks, just making sure I didn't make a mistake. I even noticed if I just press return instead it will return a yes.


constant methods and constant objects in c++

Question: After getting a lot of help from the internet i finally was able to write the program below, but i have some confusions now.
CONFUSION 1:
Can anyone explain to me the function of access method.
int access()const
        {
            return n;
        }

CONFUSION 2 :
I don't understand the working of the lines below in he program i have written.
int* ptr=(int*)&f1;

Here is the program:
#include<iostream>
using namespace std;
class Factorial
{
    int n;
public:
    Factorial():n(0){}
    int access()const
    {
        return n;
    }
    int Calculate()const;
    void display()const;
};
int Factorial::Calculate()const
{
    int f=1;
    int i=0,j;
    j=access();
    for(i=1;i<=j;i++)
    {
        f=f*i;
    }
    return f;
}
void Factorial::display()const
{
    cout<<"\nFactorial is : "<<Calculate();
}
int main()
{
    const Factorial f1;
    int* ptr=(int*)&f1;
    int n1;
    cout<<"Enter the number whose factorial is to be calculated ";
    cin>>n1;
    *ptr=n1;
    f1.display();
}

Comment: Regarding "confusion 2", everything regarding `ptr` is wrong and break the rules of C++ (it breaks *strict aliasing* as well as attempting to modify a constant object). Who told you to use something like that?
Comment: So you wrote code that you don't understand, and now you're wondering why you wrote it that way?
Comment: Regarding "confusion 1", what about the function confuses you?
Comment: Generally, if you ever feel the need to use a C-style casting (as is done with `(int*)&f1`) you should take that as a sign that you're doing something wrong.
Comment: Question title does not match question content. No static methods or static objects on sight.
Comment: There are no static objects or methods here, and modifying a const object has undefined behaviour.
Comment: `reinterpret_cast` usage is often wrong. Here too (through a C-cast).
Comment: @Someprogrammerdude Can you not legally cast a pointer to a compund to a pointer to its first element? With structs (or classes with all public) it's certainly possible; does the private part in `Factorial` prevent that?
Comment: @Peter-ReinstateMonica Unfortunately the class is not a POD (because it's not [trivial](https://en.cppreference.com/w/cpp/named_req/TrivialType)) so there's no guarantee that the member will actually be first in the object. Also using the pointer breaks strict aliasing. And as mentioned, the object is defined as *constant* which means any attempt to modify it leads to UB.
Comment: @Someprogrammerdude Thanks, "trivial" is what I was looking for.
Comment: @Someprogrammerdude And at the danger of nitpicking: The cast does not violate strict aliasing: The object pointed to is indeed an int. (It is wrong for the other reasons you mentioned though.)
Answer: A good book on C++ will explain all this to you
(Your question title is not very clear, you ask nothing about "static")

a is a private class member variable ("private:" is implicit if the accessor type is not specified before). I.e. you cannot see it's value outside of the class (unless you are befriended). To see the value of a you call the member function access that returns the value it copies from a. (Note it is marked const which means it doesn't modify the class object).

int* ptr=(int*)&f1; consists of several parts. first the address of object f1 is taken using the &-operator. Then using a C-style cast the result is converted to an int pointer. That value is assigned to ptr, which is declared as an int pointer. C-style casting is not the way you should do it in C++. It is particularly bad in this code as it's just wrong to convert from Factorial* to int*: it's not an int. Furthermore, as ptr is not used, the whole line is redundant.
Comment: If `Factorial` were a `struct`, the cast would be legal though, would't it? The object there *is* an int. (I suppose that `n` is private makes this illegal, allowing compilers to re-order the members by accessability; but in all reality I think none of them does that, and since `n` is the only member to begin with it can reorder all it wants, it'll always be first.)
Comment: Oh yes, non-virtual and perhaps other restrictions (probably no multiple inheritance). Basically PODs (unsure myself what exactly is required). But basically `struct { int i; char c; } s; int *p = (int *)&s` is allowed, iirc.
Comment: @Peter-ReinstateMonica is that really legal (I'm no language lawyer)? I mean, that would be making assumptions that could easily break with any future changes (i.e. adding dynamic polymorphism, more objects etc.) Wouldn't this be UB?
Comment: The cast sounds like bad practice in any case. Especially given that the question is asked by a beginner, I'd strongly say that we should recommend usage of `std::dynamic_cast` (and no cast in this case), even if it would be proper defined behaviour.
Comment: @Aziuth Of course it is terrible (and, as SomeProgrammerDude correctly remarked, illegal because `Factorial` is not a trivial type (due to its user defined constructor), and because `f1` is const).


DefaultExceptionListener : failed to lazily initialize a collection of role could not initialize proxy - no Session

Question: I am getting the error failed to lazily initialize a collection of role could not initialize proxy - no Session when i am trying to retrieve a list from my database object.
<code>@Transactional
private DataListener<String> onGetPieceInfoEvent() {
return (senderClient, data, ack) -> {

        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(data);
        String roomId = jsonNode.get("roomId").textValue();
        String color = jsonNode.get("color").textValue();

        Game game = this.gameService.findByRoomId(roomId);

        List<Piece> pieces = color.equals("white") ? game.getWhitePieces()
        : game.getBlackPieces();

        Collection<SocketIOClient> clientsCollection =   this.server.getRoomOperations(roomId).getClients();

        ArrayList<SocketIOClient> clients = new ArrayList<>(clientsCollection);

        // SocketIOClient client1 = senderClient; // the client from where the data came

        // the client to whom we need to send the converted data.
        SocketIOClient client = clients.get(0).getSessionId().equals(senderClient.getSessionId()) ? clients.get(1)
                : clients.get(0);

        socketService.sendMessage(roomId, "colorOnMount",mapper.writeValueAsString(pieces),
                client);
    }
</code>
I get the error when I use mapper.writeValueAsString(pieces). Otherwise Its fine, But I need to use this to send it to the frontend.
Following is the game Class.
<code>@Entity
@Table(name="game_data")
public class Game {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="game_id")
private Integer gameId;

    @Column(name="room",nullable = false)
    private String roomId;

    GameState state;

    @ElementCollection
    @ColumnDefault("[]")
    @CollectionTable(name = "white_pieces", joinColumns = @JoinColumn(name = "game_id"))
    @Basic(fetch = FetchType.EAGER)
    private List<Piece> whitePieces = new ArrayList<>();

    @ElementCollection
    @ColumnDefault("[]")
    @CollectionTable(name = "black_pieces", joinColumns = @JoinColumn(name = "game_id"))
    @Basic(fetch = FetchType.EAGER)
    private List<Piece> blackPieces = new ArrayList<>();
}
</code>
Following is the Piece Class
<code>@Embeddable
@JsonIgnoreProperties(ignoreUnknown = true)
public class Piece {
@JsonProperty("image")
@Column
private String image;

@JsonProperty("x")
@Column
private Integer x;

@JsonProperty("y")
@Column
private Integer y;

@JsonProperty("type")
@Column
private String type;

@JsonProperty("team")
@Column
private String team;

@JsonProperty("enPassant")
@Column
private Boolean enPassant;
</code>
Answer: For lazy loading to work you need a session which is bound to the transaction where the entity was loaded or persisted.
You are running the code outside that transaction and therefore get the exception.
Note that you construct the lambda inside a transaction but execution happens elsewhere outside that transaction.
Comment: Thanks a lot for pointing out the mistake. I will try to solve it using your inputs.


Flutter Text overflows parent container with border radius

Question: I created a parent container with border radius circular but the text does not follow the same and overflows the container on the bottom left.How to make the text adjust to parent container?
Answer: Just add some padding using the padding parameter in your container and you are good to go!
Container(padding: EdgeInsets.all(10),)

You'll find everything about it here.
Answer: use the property clipBehavior and set it to  Clip.antiAlias like the example below
Container(
      margin: EdgeInsets.only(left: 10, right: 10),
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(
        color: Colors.red,
        borderRadius: const BorderRadius.all(Radius.circular(10)),
        boxShadow: [
          BoxShadow(
            color: Colors.black26,
            blurRadius: 6,
            offset: const Offset(0, 3),
          ),
        ],
        child: Container(
        colors: Colors.amber,
        child:Text('hello world'),
       ),
      ),

Answer: Just your text to new container and give the height and width to it, and do not to forget to change overflow property in Text widget. You can also wrap these widgets in to FittedBox, to size text to the container.


Python - Find duplicates in a list of dictionaries and group them

Question: i'm not a programmer and also new to python, i have a list of dicts coming from a json file:
# JSON file (film.json)
[{"year": ["1999"], "director": ["Wachowski"], "film": ["The Matrix"], "price": ["19,00"]},
{"year": ["1994"], "director": ["Tarantino"], "film": ["Pulp Fiction"], "price": ["20,00"]},
{"year": ["2003"], "director": ["Tarantino"], "film": ["Kill Bill vol.1"], "price": ["10,00"]},
{"year": ["2003"], "director": ["Wachowski"], "film": ["The Matrix Reloaded"], "price": ["9,99"]},
{"year": ["1994"], "director": ["Tarantino"], "film": ["Pulp Fyction"], "price": ["15,00"]},
{"year": ["1994"], "director": ["E. de Souza"], "film": ["Street Fighter"], "price": ["2,00"]},
{"year": ["1999"], "director": ["Wachowski"], "film": ["The Matrix"], "price": ["20,00"]},
{"year": ["1982"], "director": ["Ridley Scott"], "film": ["Blade Runner"], "price": ["19,99"]}]

i can import json file with:
import json
json_file = open('film.json')
f = json.load(json_file)

but after that i'm not able to find occurrences in f and separate them in groups by film title.
This is what i'm looking for to achieve:
## result grouped by 'film'
#group 1
{"year": ["1999"], "director": ["Wachowski"], "film": ["The Matrix"], "price": ["19,00"]}
{"year": ["1999"], "director": ["Wachowski"], "film": ["The Matrix"], "price": ["20,00"]}
#group 2
{"year": ["1994"], "director": ["Tarantino"], "film": ["Pulp Fiction"], "price": ["20,00"]}
{"year": ["1994"], "director": ["Tarantino"], "film": ["Pulp Fyction"], "price": ["15,00"]}
#group X
 ...

Or better:
new_dict = { 'group1':[[],[],...] , 'group2':[[],[],...] , 'groupX':[...] }

At the moment i'm testing with nested for but without luck..
Thank you.
note: "pulp fyction" is a wanted mistake for future implementation with fuzzy string matching, for now i need only a 'duplicates grouper'
note2: with python 2.x
Comment: What are you grouping on?  Title alone?  Title + director + year?
Comment: http://docs.python.org/2/library/itertools.html#itertools.groupby
Comment: Why not name your groups by film?
Comment: @wim grouping the whole dict line (title,director,year,price) based on values in 'film' key. So yes, title alone.
Answer: Because your data is not sorted, use a collections.defaultdict() object to materialize a list for new keys, then key by film title:
from collections import defaultdict

grouped = defaultdict(list)

for film in f:
    grouped[film['film'][0]].append(film)

The film['film'][0] value is used to group the films. You would have to create a canonical version of that key if you wanted to use more sophisticated title grouping.
Demo:
>>> from collections import defaultdict
>>> import json
>>> with open('film.json') as film_file:
...     f = json.load(film_file)
...
>>> grouped = defaultdict(list)
>>> for film in f:
...     grouped[film['film'][0]].append(film)
...
>>> grouped
defaultdict(<type 'list'>, {u'Street Fighter': [{u'director': [u'E. de Souza'], u'price': [u'2,00'], u'film': [u'Street Fighter'], u'year': [u'1994']}], u'Pulp Fiction': [{u'director': [u'Tarantino'], u'price': [u'20,00'], u'film': [u'Pulp Fiction'], u'year': [u'1994']}], u'Pulp Fyction': [{u'director': [u'Tarantino'], u'price': [u'15,00'], u'film': [u'Pulp Fyction'], u'year': [u'1994']}], u'The Matrix': [{u'director': [u'Wachowski'], u'price': [u'19,00'], u'film': [u'The Matrix'], u'year': [u'1999']}, {u'director': [u'Wachowski'], u'price': [u'20,00'], u'film': [u'The Matrix'], u'year': [u'1999']}], u'Blade Runner': [{u'director': [u'Ridley Scott'], u'price': [u'19,99'], u'film': [u'Blade Runner'], u'year': [u'1982']}], u'Kill Bill vol.1': [{u'director': [u'Tarantino'], u'price': [u'10,00'], u'film': [u'Kill Bill vol.1'], u'year': [u'2003']}], u'The Matrix Reloaded': [{u'director': [u'Wachowski'], u'price': [u'9,99'], u'film': [u'The Matrix Reloaded'], u'year': [u'2003']}]})
>>> from pprint import pprint
>>> pprint(dict(grouped))
{u'Blade Runner': [{u'director': [u'Ridley Scott'],
                    u'film': [u'Blade Runner'],
                    u'price': [u'19,99'],
                    u'year': [u'1982']}],
 u'Kill Bill vol.1': [{u'director': [u'Tarantino'],
                       u'film': [u'Kill Bill vol.1'],
                       u'price': [u'10,00'],
                       u'year': [u'2003']}],
 u'Pulp Fiction': [{u'director': [u'Tarantino'],
                    u'film': [u'Pulp Fiction'],
                    u'price': [u'20,00'],
                    u'year': [u'1994']}],
 u'Pulp Fyction': [{u'director': [u'Tarantino'],
                    u'film': [u'Pulp Fyction'],
                    u'price': [u'15,00'],
                    u'year': [u'1994']}],
 u'Street Fighter': [{u'director': [u'E. de Souza'],
                      u'film': [u'Street Fighter'],
                      u'price': [u'2,00'],
                      u'year': [u'1994']}],
 u'The Matrix': [{u'director': [u'Wachowski'],
                  u'film': [u'The Matrix'],
                  u'price': [u'19,00'],
                  u'year': [u'1999']},
                 {u'director': [u'Wachowski'],
                  u'film': [u'The Matrix'],
                  u'price': [u'20,00'],
                  u'year': [u'1999']}],
 u'The Matrix Reloaded': [{u'director': [u'Wachowski'],
                           u'film': [u'The Matrix Reloaded'],
                           u'price': [u'9,99'],
                           u'year': [u'2003']}]}

Using SoundEx to group films would be as simple as:
from itertools import groupby, islice, ifilter

_codes = ('bfpv', 'cgjkqsxz', 'dt', 'l', 'mn', 'r')
_sounds = {c: str(i) for i, code in enumerate(_codes, 1) for c in code}
_sounds.update(dict.fromkeys('aeiouy'))
def soundex(word, _sounds=_sounds):
    grouped = groupby(_sounds[c] for c in word.lower() if c in _sounds)
    if _sounds.get(word[0].lower()):
        next(grouped)  # remove first group.
    sdx = ''.join([k for k, g in islice((g for g in grouped if g[0]), 3)])
    return word[0].upper() + format(sdx, '<03')

grouped_by_soundex = defaultdict(list)
for film in f:
    grouped_by_soundex[soundex(film['film'][0])].append(film)

resulting in:
>>> pprint(dict(grouped_by_soundex))
{u'B436': [{u'director': [u'Ridley Scott'],
            u'film': [u'Blade Runner'],
            u'price': [u'19,99'],
            u'year': [u'1982']}],
 u'K414': [{u'director': [u'Tarantino'],
            u'film': [u'Kill Bill vol.1'],
            u'price': [u'10,00'],
            u'year': [u'2003']}],
 u'P412': [{u'director': [u'Tarantino'],
            u'film': [u'Pulp Fiction'],
            u'price': [u'20,00'],
            u'year': [u'1994']},
           {u'director': [u'Tarantino'],
            u'film': [u'Pulp Fyction'],
            u'price': [u'15,00'],
            u'year': [u'1994']}],
 u'S363': [{u'director': [u'E. de Souza'],
            u'film': [u'Street Fighter'],
            u'price': [u'2,00'],
            u'year': [u'1994']}],
 u'T536': [{u'director': [u'Wachowski'],
            u'film': [u'The Matrix'],
            u'price': [u'19,00'],
            u'year': [u'1999']},
           {u'director': [u'Wachowski'],
            u'film': [u'The Matrix Reloaded'],
            u'price': [u'9,99'],
            u'year': [u'2003']},
           {u'director': [u'Wachowski'],
            u'film': [u'The Matrix'],
            u'price': [u'20,00'],
            u'year': [u'1999']}]}

Answer: If it was a one off and I was in a hurry I would do it like this. Assuming for this example that your list of dictionaries is lod, and that the film title will only ever be a list with one item
new_dict = {k:[d for d in lod if d.get('film')[0] == k] for k in set(d.get('film')[0] for d in l)}

To make it more readable, and explain what it is doing, the same thing broken out, again the list of dictionaries is lod:
#get all the unique film names
# note: the [0] is because its a list for the title, and set doesn't work with lists,
#so we're just taking the first one for this example.
films = set(d.get('film')[0] for d in lod)

#create a dictionary
new_dict = {}

#iterate over the unique film names
for k in films:
    #make a list of all the films that match the name we're on
    filmswiththisname = [d for d in lod if d.get('film')[0] == k]
    #add the list of films to the new dictionary with the film name as the key.
    new_dict[k] = filmswiththisname


IPMI : FATAL: Error inserting ipmi_si

Question: i have a problem with ipmi:
i've already install ipmitool, ipmi_devintf, ipmi_msghandler, but when i try to install ipmi_si i receive this message:
$ modprobe ipmi_si module
FATAL: Error inserting ipmi_si (/lib/modules/2.6.32-642.11.1.el6.x86_64/kernel/drivers/char/ipmi/ipmi_si.ko): Unknown symbol in module, or unknown parameter (see dmesg)
this id a VM based on kvm with rhel 6.8.
Any tips ?
Thanks
Answer: ipmi_si only works with real hardware. you can use something like virt-manager to see the VM console.
Comment: again ipmi only works with real hardware.
Comment: and how i resolve this ?   # ipmitool
Could not open device at /dev/ipmi0 or /dev/ipmi/0 or /dev/ipmidev/0: No such file or directory

IPMI : FATAL: Error inserting ipmi_si


Ultra-Hamiltonian cycle

Question: Ultra-Hamiltonian cycling is defined to be a closed walk that visits every vertex exactly once, except for at most one vertex that visits more than once.
Question:- Prove that it is NP-hard to determine whether a given graph contains an ultra-Hamiltonian cycle.
We can reduce it from the Hamiltonian cycle problem which is a NP-hard problem but I'm not getting from where to start for reducing it to the ultra-hamiltonian cycle problem.
Can you tell me the approach to do it?
Comment: Given any graph G, take two copies of it, take one vertex from each copy and merge them togather. G has a Hamiltonian cycle if and only if the new graph has an ultra-Hamiltonian cycle (with that merged vertex being the one that is visited more than once).
Answer: As We know Hamiltonian-Path problem is known to be in NP-complete, Now to prove that ultra-Hamiltonian Cycle is NP-hard we will reduce Hamiltonian-Path problem to ultra Hamiltonian Cycle problem. To prove: Hamiltonian Path ≤P ultra-Hamiltonian Cycle Proof:For every instance of the Hamiltonian Path problem consisting of a graph G =(V, E) as the input can be converted to ultra-Hamiltonian Cycle problem consisting of graph G' = (V', E'). We will construct the graph G' in the following way: V' = Add vertices V of the original graph G and add 5-additional vertex V0 V1 V2 V3 V4 in butterfly formation(Explained below), such that each and every vertex of the original graph G are connected to vertices V3 and V4. Here in Graph G' The number of vertices increases by 5, V' =V+5. E' = Add edges E of the original graph G and add new edges between the newly added vertices V3 and V4 to the all original vertices of the graph G. In G' The number of edges increases by the number of vertices 2V. These 5 added vertices (V0 V1 V2 V3 V4) are in a butterfly graph with V0 as articulation point The new graph G' can be obtained in polynomial time. The validation of reduction can be proved by the following two claims: i)(Forward Direction) Let us assume that the graph G contains a hamiltonian path covering the V vertices of the graph starting at a random vertex say Vstart and ending at Vend, now since we connected all the vertices to two new vertices V3 and V4 in G'. We extend the original Hamiltonian Path to a ultra-Hamiltonian Cycle by using the edges Vend to V3 and V4 to Vstart respectively. The graph G' now contains the cycle traversing all vertices exactly once except V0 (articulation point in butterfly graph) which is visited more than once, this traversal start from V0 to V1 to V2 to V0 to V4 to Vstart to "hamiltonian path in G" to Vend to V3 to V0. (Here V0 V1 V2 V3 V4 are of butterfly graph). So this is ultra-hamiltonian path in G'. . ii)(backward Direction) We assume that the graph G' has a ultra-Hamiltonian Cycle passing through all the vertices, inclusive of V0 V1 V2 V3 V4, as V0 is an articulation point so it must be visited more than once and no other vertex is visited more than once, also the path from Graph G can enter the Butterfly graph either at V3 or V4 and leave the butterfly graph at V3 or V4(whichever is not used for entering in butterfly graph). Once the path leave the butterfly-graph it will visit each vertices of Graph G in path and comeback to butterfly graph(never to go back to vertex of graph G). This path must use one of V3 and V4 for exit and other for entry from Butterfly graph to vertices of Graph G (Ad V0 is articulation point and is already being visted more than once, so no other vertex can be visited more than once). Now to convert it to a Hamiltonian Path, we remove all the edges corresponding to the vertex V0 V1 V2 V3 V4 in the cycle. The resultant path will cover the vertices V of the graph and will cover them exactly once. So here we get hamiltonian path in G, from ultra-Hamiltonian cycle in G' Thus we can say that the graph G' contains a ultra-Hamiltonian Cycle if and only if graph G contains a Hamiltonian Path. Therefore, any instance of the ultra-Hamiltonian Cycle problem can be reduced to an instance of the Hamiltonian Path problem. Thus, the ultra-Hamiltonian Cycle is NP-Hard.
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).

Ultra-Hamiltonian cycle


Save a chart into a different Excel sheet

Question: This is what I need to do:

1) Open an existing Excel file using Matlab
2) Write data to the excel file using Matlab (currently using xlswrite1)
3) Insert a chart into an already existing sheet in the excel file that I specify

I got #1 and #2 working, but I'm stuck on #3.
The things I have tried for #3 either put it in a separate new sheet (even when I specify the active sheet) or puts it in the correct sheet, but I somehow lose the handles to the chart and can't assign ChartType without getting an error.
Comment: are you working on Linux or Windows?
Answer: Below is the code provided by Mathworks Support Team (link provided below) for inserting MATLAB Figure in an Excel sheet. You might have to update the sheet to your intended one.
% Create sample image from figure

img = 'figure1.png';

plot(1:10);

print('-dpng', img);

% Get handle to Excel COM Server

Excel = actxserver('Excel.Application');

% Set it to visible

set(Excel,'Visible',1);

% Add a Workbook

Workbooks = Excel.Workbooks;

Workbook = invoke(Workbooks, 'Add');

% Get a handle to Sheets and select Sheet 1

Sheets = Excel.ActiveWorkBook.Sheets;

Sheet1 = get(Sheets, 'Item', 1);

Sheet1.Activate;

% Alternative 1 BEGIN.

% Get a handle to Shapes for Sheet 1

Shapes = Sheet1.Shapes;

% Add image

Shapes.AddPicture([pwd '\' img] ,0,1,400,18,300,235);

% Alternative 1 END.

% Alternative 2 BEGIN.

% Add image

Sheet1.invoke('Pictures').Insert([pwd '\' img]);

% Alternative 2 END.

% Save the workbook and Close Excel

invoke(Workbook, 'SaveAs', [pwd '\myfile.xls']);

invoke(Excel, 'Quit');

% In the above code (Alternative 1), Excel's Shapes.AddPicture Method is used to insert a figure in the Excel Sheet - Mathworks.

Link to the response above:
A function img2xlsx by H K.Berg - which transfers one or multiple image(s) to a new or existing xlsx-file) can be downloaded from MATLAB Central
Comment: Thanks, I figured it out. And solution 2 is not actually what I was trying to do. I wanted to create an Excel figure in Excel from MATLAB not just insert a MATLAB figure into Excel.

This is what I ended up using:
Excel = actxserver('Excel.Application');
Workbook = invoke(Excel.Workbooks,'Open',fullfilename);
resultsheet = name;
sheet = get(Excel.Worksheets,'Item', resultsheet);
invoke(sheet, 'Activate');
Chart = Excel.ActiveSheet.Shapes.AddChart2;

The activate sheet command does not seem to work with the invoke chart command.


How can I retrieve the current currency symbol?

Question: I know there must be an API that returns the current currency symbol, but when I searched for it, I didn't find anything.
How can I retrieve the current currency symbol?
Answer: With Drupal 7, if you want to get the default (current) currency you can use  the following code.
<code>$cur = commerce_currency_load();
$sym = $cur['symbol'];
</code>
Answer: With the Commerce Multicurrency module and Drupal 7, you can use the following code.
<code>$enabled_curr = commerce_currencies(TRUE);
$current_curr = $enabled_curr[commerce_multicurrency_get_user_currency_code()];
$curr_symbol = $current_curr['symbol'];
</code>
Answer: From Drupal 8, you can use the following code.
<code>// Add the following line on the top of the file using the rest of the code.
use Drupal\commerce_price\Entity\Currency;

// Get the currency code from the active store.
$currency_code = $store->get('default_currency')->getValue()[0]['target_id'];
$currency = Currency::load($currency_code);
$symbol = $currency->get('symbol');
</code>
Comment: Any specific reason not to use direct calls like `$store->getDefaultCurrencyCode()` or `$currency->getSymbol()`? Maybe these weren't available back then? They sure are now...
Answer: With Drupal 8/9, if you are using the commerce_currency_resolver module (which is pretty cool):
<code>$currency_code = \Drupal::service('commerce_currency_resolver.current_currency')
                 ->getCurrency();
</code>


Finding minimum and maximum points with Lagrange Multipliers

Question: I need to use Lagrange Multipliers to find the maximum and minimum values of the function:
$f(x,y)=2e^{xy}$
subject to the given constraints:
$2x^2+y^2=32$
So I went through some examples, and I got:
$x=\pm2\sqrt{2}$ and $y=\pm4$ (Wolfram confirms).
Now I'm having trouble finding the maximum and the minimum.
I understood that If I want to find out if  $(2\sqrt2,4)$ is maxima or minima, then I'll take for example $x=3$, and by the constraint, this point will be $(3,\sqrt{14})$, and check if this value is greater or smaller than (for example) $(2\sqrt2,4)$, and if it is bigger - then my $(2\sqrt2,4)$ is a minimum.
But in my example, $3>2\sqrt2$ and $4>\sqrt{14}$, isn't it problematic?
This seems a bit messy. First, am I right? Second, any other way to do so, that is not much complicated?
Answer: I didn't check the calculation, but in general, once we have obtained the possible max/min points by Lagrange Multipliers, we simply need to plug the values into $f(x,y)$ and determine the max/min values, that is:

$f(2\sqrt 2,4)=2e^{8\sqrt 2}=\dots$
$\dots$

In this case it is not difficult to see that

$f_{max}=f(2\sqrt 2,4)=f(-2\sqrt 2,-4)=2e^{8\sqrt 2}$
$f_{min}=f(-2\sqrt 2,4)=f(2\sqrt 2,-4)=2e^{-8\sqrt 2}$
Answer: The points found are guaranteed to be maxima or minima, so it's enough to plug each pair back into $f(x)$ to determine which are which
Doing the way you suggested is not problematic, it's only required that the points are on the contraint, an ellipse in this case. If you plug, say, $(2\sqrt{2},4)$ and $(3,\sqrt{14})$
$$2e^{8\sqrt{2}}\approx  163874.4$$
$$2e^{3\sqrt{14}}\approx 149959.3$$
So it doesn't matter that $3>2\sqrt{2}$ because $\sqrt{14} < 4$. The process of Lagrange multipliers sorted it out for you already by finding the values that beat all the others
Answer: You don't really need to "plug" any numbers into the function in order to answer your question.  The function  $ \ f(x,y) \ = \ 2e^{xy} \ $ has  symmetry about the origin [ $ \ f(x,y) \ = \ f(-x,-y) \ $ ] .  The constraint curve $ \ 2x^2 \ + \ y^2 \ = \ 32 \ $ is an ellipse centered on the origin, so we expect a critical point in any quadrant to be "mirrored" by a critical point of the same kind in the diagonally-opposite quadrant.
You found two critical values for $ \ x \ $ and $ \ y \ $ each, producing four critical points in all, one in each quadrant as anticipated.  The product $ \ xy \ $ is positive in the first and third quadrants and negative in the second and fourth.  Thus, the exponent in $  \ 2e^{xy} \ $ is positive at $ \ (2\sqrt2 \ , \ 4) \ $  and $ \ (-2\sqrt2 \ , \ -4) \ $  , producing the absolute maxima for our function, with the exponent being negative at $ \ (2\sqrt2 \ , \ -4) \ $ and $ \ (-2\sqrt2 \ , \ 4) \ $  , where the absolute minima are located.  (The values are as shown by user.)


content administration page not found, and user manager page not found

Question: I don't know what did this...but now when I try and go to my content manager or my user manager I get a 'page not found' in the admin overlay.
.htaccess is ok and nothing has changed in the php.ini
Where do I look next?
also to note:  admin/people/people is giving me Permission denied?!   I am UID 1 obviously...
updated:  the add content button is still there..  so im guessing this is some broken core module?  I have tried replacing the core and it still is giving me the same thing.
attached is a screeen
Answer: Admin_views was turned on and not functioning causing the overridden admin url aliases it uses to throw this error.
After disabling, the admin screens returned to normal function.
Answer: I'm 99% confident the issue is not with the Drupal core code. Looking at the .htaccess file seems like the right path. The path to the 404 pages is not being resolved correctly and something at perhaps the Apache layer is standing in the way. Any chance you can try an install on a different server so you can have a point of reference.
Comment: I found out this was admin_views that were turned on and were overriding the path alias.... after turning them off this resolved the issue.  Looks like admin_views default settings are buggy in D7 right now.

Thanks for your help.
Comment: Nice detective work, thank you for posting that it's in fact a D7 bug. Do you have a link to where some of the details of the bug can found?


Prove that for all positive integers $x, \ x$ is not divisible by $3 \iff {x^2 - 1} $ is divisible by $3$.

Question: I am trying to self-study mathematics and I got stuck in this question. I did not find similar questions to this elsewhere so I am asking this one.
Also if you may please answer this follow up question:
Prove using mathematical induction that $x^2 - 1$ is divisible by $3$ for all positive integers $x$ that are not divisible by $3$.
Prove that for all positive integers $x, \ x$ is not divisible by $3 \iff {x^2 - 1} $ is divisible by $3$.
Answer: Hint : One of the numbers $x-1,x,x+1$ must be divisible by $3$
Answer: Try re-writing $ x^2-1 $ using the difference of two squares:
$$ x^2 - 1 = (x+1)(x-1)$$
If we know that this is a multiple of 3, then what can you say about $x+1$ and $x-1$?
Answer: Hint:
The sequence of $(n^2-1)\bmod 3$ is $2,0,0,2,0,0,2,0,0,\cdots$
Answer: $\Leftarrow:$
Assume $3|(x^2-1)$;
Then $3|(x-1)(x+1)$;
Euclid's lemma:
$3|(x-1)$ or $3|(x+1)$, hence $3 \not | x$;
$\Rightarrow:$
Assume $3\not | x$;
We have $3| (x-1)(x)(x+1)$, three consecutive integers.
Euclid's lemma:
$3|(x-1)$ or $3|(x+1)$, hence
$3|(x-1)(x+1)$, and we are done.
Answer: Use congruences:
A number $x$ is divisible by $3$ iff $x\equiv 0\bmod 3$. A number $x$ is not divisible by $3$  iff $x\equiv 1$ or $-1\bmod 3$, and in this single case, $x^2\equiv 1\bmod 3$.


Palindrome (python) input giving than stops

Question: I have a program, but I want it develop it more to:
That it reads a letter from input en print the string to this letter.
So if the input is b it will print aba. I have now a code that prints a til z and reverse of it... But i Don't know where to start now
a_y = ""

for val in range(97, 122):

    a_y += chr(val)

print( a_y + 'z' + a_y[::-1] )

Answer: You just need to compare val with your "start character":
a_y = ""
start = 'd'
#start = input("Where to start from: ")

for val in range(97, 122):
    if chr(val) >= start:
        a_y += chr(val)

print(a_y + 'z' + a_y[::-1])

Out:
defghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfed

Answer: you need to have a loop that will go to the inputed letter
you can do something like this:
a_y = input()
res = ""
i = 97
while i < ord(a_y):
    res += chr(i)
    i = i + 1
print( res + a_y + res[::-1] )

if input is for example d, output will be abcdcba
or
a_y = ""
end = input()

for val in range(97, 122):
    if val <= ord(end) - 1:
        a_y += chr(val)

print(a_y + end + a_y[::-1])

in: d
out: abcdcba
Python ord() function returns the Unicode code from a given character.
For example, ord('a') returns the integer 97
Answer: Here is a potential approach:
from string import ascii_lowercase as letters

def palindrome(c):
    n = ord(c)-96
    if 1>n or n>len(letters)+1:
        print(f'invalid input "{c}"')
    s = letters[:n]
    return s+s[-2::-1]

Example:
>>> palindrome('g')
'a'

>>> palindrome('g')
'abcdefgfedcba'

>>> palindrome('?')
invalid input "?"


tail a file on network Windows IoT Core machine

Question: Is it possible to tail a file on a Windows network machine?
For a linux machine I can
ssh  -t remotebox "tail -f /path/to/file.log"
Note. The ssh is open on the destination machine.
Answer: Powershell:
get-content C:\Users\Example\Example.txt -tail 10


Is webAudio no longer supported on iOS 15/16, is it a Bluetooth glitch, or is there some workaround required to get basic webAudio to play?

Question: As far as I can tell, the most basic webAudio functionality no longer works on iOS mobile Safari, or else some weird new requirement is now in place.  Code that runs fine in other browsers (including desktop Safari) produces no errors, but no sound in mobile Safari.
I have tried many ultra-simple examples of a user gesture to play a basic sound.
I just discovered that these examples WILL produce audio on iOS Safari, but only if bluetooth is not being used and has not been used.  Once bluetooth audio is used, as far as I can tell the only way to get webAudio to work again is to restart the Safari browser (with bluetooth off).
Here's one live example on the web:
https://codepen.io/LegDip/pen/KKQOMRr
Here's the code:

 let context;
    let mediaStream;
<code>function createAudioContext() {
    if (context == undefined) {
        context = new AudioContext();
    }
    return context;
}

function playTone() {
    const audioContext = createAudioContext();
    // play a tone
    const oscillator = audioContext.createOscillator();
    oscillator.frequency.value = 440;
    // don't play at max volume
    const gain = audioContext.createGain();
    gain.gain.value = 0.04;
    oscillator.connect(gain);
    gain.connect(audioContext.destination);
    oscillator.start();
    // stop after 10 seconds
    oscillator.stop(audioContext.currentTime + 10);
}
</code>
Here's another completely independent example, which once again works fine in other browser contexts.  The function playTone is called directly by a user button tap in a vue app:
const audioContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 44100 });
playTone() {
audioContext.resume()
const oscillator = audioContext.createOscillator();
oscillator.frequency.value = 440; // A4 note (440 Hz)
oscillator.connect(audioContext.destination);
oscillator.start();
oscillator.stop(audioContext.currentTime + 1); // Stop after 1 second
}
I've tried a number of other ultra-simple examples and everything under the sun that either me or chatGPT can think of to fix it.
Is there a fix?
Is it possible to wrap a webapp in chromium to solve this, or on iOS will that have the same problem?
Does the world just need to all simultaneously toss their iPhones in the sea?
Thank you
Comment: Are you sure it's not a specific problem with your device? I can run all that  on my iPhone, on myiPad
Comment: Thanks.  Were you able to run it with Bluetooth?  I can't figure out what's going on.  I have repeated the problem on multiple devices and simulator.
Comment: I'm able to run it with or without Bluetooth, on internal speaker and trough my AirPods. iOS 16.5.1
Comment: Can you run [this](https://pro-audio-live-assistant.vercel.app/signal_generator.html)? I'm an audio engineer, it's a very little utility I use in my live shows
Answer: I'm reasonably sure that there is a bug in WebKit where it doesn't handle audio hardware sample rate changes correctly (which is very likely to be the case if you use Bluetooth).
For example, if you open a web page that uses WebAudio on an iOS device with Bluetooth not connected, the AudioContext will have a sampleRate of 48000. With the page open, if you connect to an external Bluetooth speaker (which has a sampleRate of 41000) and return to the page, the audio is distorted because the AudioContext is using the wrong sampleRate (i.e. 48000 instead of 41000).
I've filed a bug report regarding this (which includes a demo page to test against): https://bugs.webkit.org/show_bug.cgi?id=258864
Note that WebKit is used for all browsers on iOS and iPadOS, so if your problem is related to mine (and I suspect it is), using another browser won't help.
Comment: @pierpy - it seems that you do not have the Bluetooth issue that I've experienced. May I ask what setup you have (i.e. iPhone model, iOS version, make and model of external Bluetooth speaker) ?
My guess is that the problem may depend on the Bluetooth hardware and / or codec that's being used.
Comment: Thanks very much for your help with this.  I can select any sampling rate that I want.  Is there a sample-rate that can be used that will solve this problem so audio 'works' on iOS?  Also -- and maybe this is related -- I'm finding all kinds of audio glitching when doing time-stretching of audio, but only on iOS.  I've tried many approaches to work around this.  HTML 'playbackRate', and webAudio using time shifting, many algorithms.  All work great on all other platforms.  Have not found a way to make even reasonable-sounding time-shifted audio for a webapp on iOS. Thanks again for your help.
Comment: I followed the instructions on your demo page, and: 1) on my iPad the audio plays just fine, without pitch change or other unintended modifications. 2) scrolling the page, audio becomes "crackly".  This maybe a buffer issue
Comment: 3) No artifacts while playing through audio element
Comment: 4) Sometimes when I tap stop, the music stops with audible "cracks". Not 100% reproducible for me
Comment: @user2330237 - glad to help ! Unfortunately, although the specification suggests that you can set the sample rate of a new AudioContext, it doesn't seem to make any difference on iOS.
Personally, I've come to the conclusion that the Bluetooth issue that I've reported cannot be detected nor avoided using JavaScript in the web page.
So, for the player that I'm working on, we're telling users to make sure they don't change the output device while the page is loaded.
That is: set the output device first, then open the player web page.
Comment: Regarding the audio glitches, I suspect it could be because WebAudio is on a lower priority thread than the one that handles user interactions.
In my player, we use the WebAssembly version of a library called Superpowered https://superpowered.com which does all the "heavy lifting".
Unfortunately, even it can't work around bugs in WebKit / WebAudio !
Comment: Finally, in WebKit, the HTML  element is considered a "first class citizen" and is treated the same way as audio produced in a native app.
Unfortunately, WebAudio is not treated in the same way and suffers as a result
So, for example on iOS, audio played using the  element continues to play if you switch to another app.
That's not true for audio played using WebAudio.
Comment: @peegee123 yes: iPhone13, model number MLPF3QL/A ,  iOS 16.5.1 AirPods 2nd gen; my bluetooth speaker is a low-end  chinese model, no brand. iPad 6° gen, MRJN2TY/A, iPadOS 16.5.1
Comment: @pierpy - thanks for the info. Based on what you have, it should show the problem. Would you mind trying my demo page on your iPhone again but before openng the page make sure that Bluetooth is enabled, your Bluetooth speaker is ON but ALL devices are showing as "Not Connected" in the settings including your AirPods.
Then, when following the instructions, make sure you do not refresh the page at all and only play audio through either the internal speaker or the Bluetooth speaker.