passar dois parametros via GET

Question: Olá,
Estou com dúvida de como posso passar 2 parâmetro via GET, só que o segundo seria após a resposta do primeiro.
o que quero fazer é selecionar um item em um input select e atualizar a pagina com aquele parâmetro no GET e depois com base neste parâmetro vai habilitar um campo input text pra mim digitar algo que vai consultar no banco os 2 parâmetros juntos na clausula WHERE.
meu código atual:
if ( isset($_GET["revenda"])  ) {
$var1 = $_GET["revenda"];

$query = ("SELECT bem, des_bem, revenda FROM AFX_BEM WHERE revenda LIKE :imobilizado ");
$stmt = $pdo->prepare($query);
$stmt->bindValue(':imobilizado', '%' . $var1 . '%', PDO::PARAM_STR);
$stmt->execute();

}

if ( isset($_GET["bemdesc"])  ) {
$var1 = $_GET["revenda"];
$var2 = $_GET["bemdesc"];

$query = ("SELECT bem, des_bem, revenda FROM AFX_BEM WHERE revenda LIKE :rev AND des_bem LIKE :bd ");
$stmt2 = $pdo->prepare($query);
$stmt2->bindValue(':rev', '%' . $var1 . '%', PDO::PARAM_STR);
$stmt2->bindValue(':bd', '%' . $var2 . '%', PDO::PARAM_STR);
$stmt2->execute();

}

<form class="form-inline" role="form" action="lista.php" method="get">

             Pesquisar

             <select class="form-control" name="revenda" style="width: 140px" onchange="this.form.submit();" >
                       <option value="" disabled selected><?php if(isset($_GET["revenda"]) ) {
                       if ( ($_GET["revenda"]) == 1 ) { echo "Piracicaba"; }
                       if ( ($_GET["revenda"]) == 2 ) { echo "Botucatu"; }
                       if ( ($_GET["revenda"]) == 3 ) { echo "São Manuel"; }
                       if ( ($_GET["revenda"]) == 4 ) { echo "Lençóis Paulista"; }
                       if ( ($_GET["revenda"]) == 5 ) { echo "Jaú"; }
                       if ( ($_GET["revenda"]) == 6 ) { echo "Ibitinga"; }

                       } else {  ?>Revenda <?php } ?></option>
                        <?php
                            $linha2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
                            foreach($linha2 as $listar2){

                        ?>
                        <option value="<?php echo $listar2["REVENDA"]; ?>">
                            <?php echo utf8_encode($listar2["RAZAO_SOCIAL"]);    ?>
                        </option>

                        <?php
                            }

                        ?>

                        </select>

            <?php if(isset($_GET["revenda"]) ) {
                $bemdesc = "teste";
            ?>

            <form action="lista.php?revenda='<?php echo $revenda ?>' " method="get">
             <input class="form-control" type="text" name="bemdesc" id="bemdesc" placeholder="BEM ou Descrição">
             <button class="btn btn-default" type="submit"></button>

            <?php
            }
            ?>
             </form>

     </form>insira o código aqui

Comment: Você esta tentando enviar dois `` com o mesmo `submit`? É isso que esta tentando fazer?
Comment: mesmo fechando um  em cima do outro qdo eu digito algo no segundo e submit o primeiro parâmetro some da url e só fica o novo
Comment: Tenta colocar tudo dentro do mesmo `form`
Comment: mesmo efeito.. a url apaga  o revenda=5 (/imobilizados/lista.php?revenda=5) e fica somente assim: /imobilizados/lista.php?bemdesc=mesa .. preciso juntar revenda=5&bemdesc=mesa
Answer: Coloque dentro de apenas 1 <form> assim:
<form class="form-inline" role="form" action="lista.php" method="get">
<input type="text" name="texto1" value="textoDigitado1">
<input type="text" name="texto2" value="textoDigitado2">
<button type="submit"></button></form>

Dessa forma o resultado da url seria assim:
lista.php?texto1=textoDigitado1&texto2=textoDigitado2

Comment: eu preciso submeter o valor do select primeiro.. dai minha url vai ficar com 1 get.. após isso vai abrir um campo input pra mim submeter um segundo get do tipo text

passar dois parametros via GET


Do I need to setup an SMTP MTA for a contact us form on a VPS?

Question: I'm about to setup a Linode running a Centos server with a rails apps. The rails app has a contact us form. That justs send enquirys to the site owner. No other email functionality is needed
The site owner just uses his gmail email account, so no email is currently configured for the domain hosting rails app.
My question is, do I have to setup postfix on server hosting the rails app so it can send emails to the site owner or is there some other way ?
If I have to do it, am I correct in assuming I'll have to setup MX records, Sender frameworks SSL certs,etc ? :(
I'm looking for an easy way out :)
The server will have a static IP and a valid DNS entry.
Answer: there is NO need for anything installed as mailx - send and receive Internet mail IS already installed on your system, this is part of any Linux distro out there, but just in case if it doesn't you can always install it separately UNLESS you're planning to receive emails as well and in that case you DO need to install SMTP MTA (such as: sendmail/postfix/etc).
Comment: Is that right ?  Whats the difference between me sending emails from Linux server and a spammer doing it ?  I thought for me to send emails the receiver mail server has to do MX lookups/ reverse lookups plus other verification before it will accept the email I've sent. This server is a VPS on the internet not a VM at home using my isp domain.
Comment: MX is only needed for incoming emails and not for outgoing.
Comment: mailx is fine, but there is *great* value in installing a local MTA that can queue mails locally before relaying them out to a smarthost. This protects you from transient issues that would otherwise cause mailx (and it's "fire and forget" stance) to lose mail.
Comment: Thanks @EEAA. I understand, but this server would be the smarthost :)
Comment: @AndyM - well then you *definitely* don't want to use mailx. A smarthost *needs* to run a real MTA.
Answer: I would suggest that you check out Postmark if you're not comfortable with setting up your own SMTP server.
You can SPF and DKIM verify your emails as well to reduce your risk of having your email blocked.
Cheers
Answer: All you'll have to do is enter the connection information for an existing MTA. You can send email to a gmail account from a gmail account.  Google's SMTP settings can be found here.
To see the SMTP settings in the link above, click on "I want to enable POP" and then select "Other" for your mail client.
Comment: If you send out email from an IP address that is from a shared hosting provider or from a dynamic IP, you'll get blocked by spam filters, sometimes they don't even make it to the Spam folder.  For a reliable solution, a trusted MTA is needed.  It doesn't have to be Gmail, but creating your own is much harder than it sounds.
Comment: he's looking for SMTP and your link is for POP/IMAP
Comment: You have to select POP and then select other.
Comment: How is this getting a minus?  You need to send email through an MTA, or you'll get blocked by spam filters.  Google is a valid MTA. What am I missing?
Comment: At the end of the day it's up to @AndyM, but for me personally that wouldn't be a solution as I'd prefer have my own SMTP server instead of using 3rd party and as I mentioned in mine answer most likely there is something already installed that sends out email, so this is just not needed at the first place.
Comment: you don't know if OP has a dynamic IP or not, right? Also in production environment you wouldn't want to use 3rd party services such as this, you'd want to have your own SMTP server, and SMTP server is _NOT_ that hard to set it up.
Comment: The server will have a fixed IP, it will have a valid DNS name. I've used SMTP servers before but they have all forward onto another server for relaying out to the internet. The case in my question - the server is sending direct not forwarding/relaying to some other mail server.


getting specific object of xml which can be parsed using XStream

Question: I'm new to XML parsing and want to convert XML file resulting from a web service to list of POJOs. as i have done some work with JSon and found it very easy to work with. while in the case of XML there is quiet same process but i cant find way of traversing through the Hierarchy and reaching a specific node to be parsed to POJO. As i explain my question with example . here is response in XML format
<hash>

<resp_status>1</resp_status>

<message>success</message>

<errors></errors>

<calendars>
    <calendar>
        <id>44</id>

        <name>Air Force</name>

        <expiry_date>2012-03-01</expiry_date>

        <thumbnail_url>http://www.countdownyourgame.com/uploads/44_thumbnail.png</thumbnail_url>
    </calendar>
    <calendar>
        <id>103</id>

        <name>Akron</name>

        <expiry_date>2012-02-01</expiry_date>

        <thumbnail_url>http://www.countdownyourgame.com/uploads/103_thumbnail.png</thumbnail_url>
    </calendar>
    <calendar>
        <id>16</id>

        <name>Alabama</name>

        <expiry_date>2012-03-01</expiry_date>

        <thumbnail_url>http://www.countdownyourgame.com/uploads/16_thumbnail.png</thumbnail_url>
    </calendar>
</calendars>

and same response in JSon format
{
 "hash":
    {
     "resp_status":"1",
     "message":"success",
     "errors":"",
     "calendars":
        {
         "calendar":[
                     {
                      "id":"44",
                      "name":"Air Force",
                      "expiry_date":"2012-03-01",
                      "thumbnail_url":"http://www.countdownyourgame.com/uploads/44_thumbnail.png"
                      },

                      {
                       "id":"103",
                       "name":"Akron",
                       "expiry_date":"2012-02-01",
                       "thumbnail_url":"http://www.countdownyourgame.com/uploads/103_thumbnail.png"
                       },

                       {
                        "id":"16",
                        "name":"Alabama",
                        "expiry_date":"2012-03-01",
                        "thumbnail_url":"http://www.countdownyourgame.com/uploads/16_thumbnail.png"
                        }
                       ]
         }
    }
}

here is POJO for calendar objects contained inside calendars (file name Calendar.java)
public class Calendar {

private String id, name, expiry_date, thumbnail_url;

Calendar() {
    id = new String("");
    name = new String("");
    expiry_date = new String("");
    thumbnail_url = new String("");
}

public String getId() {
    return id;

}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;

}

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

public String getExpiryDate() {
    return expiry_date;

}

public void setExpiryDate(String expiry_date) {
    this.expiry_date = expiry_date;
}

public String getThumbnailUrl() {
    return thumbnail_url;

}

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

}

to convert the above JSon response i just need following code
 JSONObject json=new JSONObject(JsonResponceString);
        for(int i=0;i<json.getJSONObject("hash").getJSONObject("calendars").getJSONArray("calendar").length();i++)
        {
            //by using refrenced jar of Gson
            Calendars obj=new Gson().fromJson(json.getJSONObject("hash").getJSONObject("calendars").getJSONArray("calendar").getJSONObject(i).toString(), Calendar.class);
            //ArrayList for calendar type objects
            calendarList.add(obj);

        }

for above process with XML there are many parsers but i found XStream the simple one.
here as shown in the following link http://x-stream.github.io/tutorial.html in the example there is one object not array of objects which is converted to POJO as defined in bottom portion of code
here is my question that how can i traverse throw whole XML response and get the specific or all calendar objects(XML objects) which can be converted to string like in JSon and then passed as an argument to fromXML() method so that parsed to POJO.
any idea of writing a class by my self to split calendar objects using string methods or regular expression will take the same amount of time as required to choose simple parsing so please help me by giving a clean answer that the process I'm trying is possible or not , possible but not this way...then in what way?
i also studied about others specially JAXB but it needs schema and although it can even design POJOs for you but what if i don't need the whole XML to be parsed the problem with most of parsers i have is they are likely to parse the whole response and hence demanding a messy structure of POJO for this. if I'm wrong then please suggest me but with some solid example...thankx
Comment: JAXB does NOT require an XML schema.  Since you have tried XStream the following article may be useful.  It maps the same object model to the same XML document using both JAXB and XStream:  http://blog.bdoughan.com/2010/10/how-does-jaxb-compare-to-xstream.html
Answer: Alternatively you can use SAX parser for parsing xml.
Refer this example code
Comment: this is not the answer i want they way of traversing through xml file and getting a specific portion
Answer: At last found the way resembling to JSon . i hope this can help someone else. @parag this is what i was asking.........i appreciate your help but that was not what i was looking for..
package com.samjanz.xmlparsing;

import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.samjanz.xmlparsing.helpers.MyConverter;
import com.samjanz.xmlparsing.helpers.MyHTTPConnector;
import com.samjanz.xmlparsing.pojos.Calendar;
import com.thoughtworks.xstream.XStream;

public class XmlParsingActivity extends Activity {

LinearLayout parent;
String serverResponce;
Document xmlDoc;
ArrayList<Calendar> calendarList;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    parent = (LinearLayout) findViewById(R.id.parent);
    XStream xstream = new XStream();
    xstream.alias("calendar", Calendar.class);

    calendarList = new ArrayList<Calendar>();
    String url = getText(R.string.calendar_url).toString();
    // get DOC
    xmlDoc = MyConverter.streamToDocument(MyHTTPConnector.UrlToStream(url));
    NodeList nodeLst = xmlDoc.getElementsByTagName("calendar");

    for (int i = 0; i < nodeLst.getLength(); i++) {
        Node node = nodeLst.item(i);
        if (node != null) {
            Calendar obj = (Calendar) xstream.fromXML(MyConverter
                    .nodeToString(node));
            calendarList.add(obj);
            LayoutParams lparams = new LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            TextView tv = new TextView(this);
            tv.setLayoutParams(lparams);
            tv.setText("\n\nLoop No:" + (i + 1) + "\nId = "
                    + calendarList.get(i).getId() + "\nName = "
                    + calendarList.get(i).getName() + "\nExpiry Date = "
                    + calendarList.get(i).getExpiryDate()
                    + "\nThumbnail Url = "
                    + calendarList.get(i).getThumbnailUrl());
            parent.addView(tv);

        }

    }
}

}


Por que eu não consigo acessar o vetor de inteiros na função main()?

Question: Não consigo acessar as posições do vetor de inteiros que carreguei na função carrega. Naquela função eu consigo de forma correta acessar os dados com:
printf("%d\n", n[i]);

Mas na função main(), abaixo de onde chamo a função carrega, quando tento acessar qualquer posição desse vetor de inteiros o programa simplesmente fecha. Acredito que estou trabalhando errado com ponteiros
#include <stdio.h>

void carrega (int *n);

int main
(int argc,char *argv[])
{
    int *n=NULL;
    carrega (n);
    printf("%d\n", n[0]); //Erro aqui, não consegue acessar.
}

void carrega (int *n)
{
    int i = 0;
    FILE *f = NULL;
    f = fopen ("arquivo.txt", "r");

    n = (int *) malloc(3*sizeof(int));

    for(i=0;i<3;i++){
    fscanf (f, "%d", &n[i]);
    printf("%d\n", n[i]);  //Tudo ok
    }
}

Answer: O problema é meio subtil devido a estar a trabalhar com vetores e ponteiros, mas é algo simples.
Imagine este cenário:
void altera(int x){
    x = 10;
}

Chamando assim:
int var1 = 50;
altera(var1);
printf("%d", var1); //50

Veja no ideone
Acontece que no C os parametros são sempre passados por copia, logo alterar o valor de um parametro numa função não altera a variavel original. Olhando para este exemplo que dei, o parametro x é uma copia do valor que var1 tinha, logo alterar x na função não altera o valor de var1.
Você fez exatamente o mesmo mas através de um ponteiro, ora veja:
void carrega (int *n){
    ...
    n = (int *) malloc(3*sizeof(int));
    ...
}

int main(int argc,char *argv[]){
    int *n=NULL;
    carrega (n);
    printf("%d\n", n[0]);
}

Veja como é exatamente igual ao exemplo que dei mas agora com um int*, um ponteiro de inteiro. Você cria um ponteiro, passa-o à função na esperança que a função o altere, mas lembre-se que o que é passado é uma copia do ponteiro. Logo fazer n = (int *) malloc(3*sizeof(int)); não altera o n que tem no main mas sim a copia desse n que tem na função.
Aqui tem duas soluções para resolver
1) Retornar o valor com que queria alterar:
int* carrega (int *n);
//^-- agora retorno de int*

int main(int argc,char *argv[]) {
    int *n = NULL;
    n = carrega (n); //coloca o valor devolvido de novo em n
    printf("%d\n", n[0]);
}

int* carrega (int *n) {
//^--- agora retorno de int*
    int i = 0;
    FILE *f = fopen ("arquivo.txt", "r");
    n = (int *) malloc(3*sizeof(int));

    for(i=0; i<3; i++) {
        fscanf (f, "%d", &n[i]);
        printf("%d\n", n[i]);
    }
    return n; //retorna o novo array alocado
}

2) Passar o endereço da variável que quer alterar:
void carrega (int **endereco_n);
//                 ^-- agora recebe o endereço do array

int main(int argc,char *argv[]) {
    int *n = NULL;
    carrega (&n); //passa o endereço do array através do &
    printf("%d\n", n[0]);
}

void carrega (int **endereco_n) {
//                 ^-- agora recebe o endereço do array
    int i = 0;
    FILE *f = fopen ("arquivo.txt", "r");
    int *n = (int *) malloc(3*sizeof(int));

    for(i=0; i<3; i++) {
        fscanf (f, "%d", &n[i]);
        printf("%d\n", n[i]);
    }
    *endereco_n = n; //altera o array do main através do endereço recebido
}

Answer: O código tem alguns problemas e pode ser escrito de forma mais simples, mas o principal é quanto a alocação de memória. Prefira alocar a memória para receber os dados na função onde vai usar. E aí fica mais fácil lembrar de librar com free(). Se quiser um código mais robusto tem que fazer uma série de verificar ou ler de uma forma diferente. Este código é bom como exercício básico para ler algo que você tem certeza que tudo dará certo.
Provavelmente há problema em como o dado está no arquivo. Tem certeza que tem uma forma de separa os números? Eles estão válidos? Eu testei com um arquivo muito simples com os dados separados por espaço.
#include <stdio.h>
#include <stdlib.h>

void carrega(int *n) {
    FILE *f = fopen("arquivo.txt", "r");
    for (int i = 0; i < 3; i++) fscanf(f, "%d", &n[i]);
    fclose(f);
}

int main() {
    int *n = malloc(3 * sizeof(int));
    carrega(n);
    for (int i = 0; i < 3; i++) printf("%d\n", n[i]);
    free(n);
    system("pause");
}

Coloquei no GitHub para referência futura.
Comment: Opa Maniero. Desculpe pelo código meio esquisito. Cortei várias coisas para ficar mais simples de vocês entenderem qual era minha dúvida, não validei o malloc, não utilizei o free, etc ... Na verdade eu precisa realizar toda a alocação dentro da função "carrega" e depois brincar com ela na main. O Isac aqui embaixo me lembrou que eu estava passando a cópia do ponteiro e não o ponteiro em si.
Comment: @EduardoOliveira só que não é assim que as pessoas costumam fazer me C e é um código propenso a erros. De forma geral todas as bibliotecas trabalham com essa ideia de alocar e passar o ponteiro, a sua foge do padrão. É um direito seu fazer assim, mas está fazendo de forma considerada ruim.
Comment: Entendi,  vou seguir sua dica. Esse código que estou fazendo é um exercício bem específico para aprendizado, onde tenho um arquivo que o 1º elemento inteiro informa a quantidade de nºs inteiros que o arquivo possui. Por exemplo:
3 90 100 87  <<< Informa que tenho três inteiros(90,100,87)
Após descobrir a quantidade, precisava colocar esses três em um array, achar o menor valor e printar a ordem inversa desses elementos. Aí o professor pediu para deixar nada na main, inclusive a abertura do arquivo. Como tenho que pegar a quantidade de elementos tive que colocar a abertura na função carrega.


Building vs buying a server for an academic lab

Question: I'm looking for advice on the classic build vs buy question.
We need a new linux server to run Matlab computation on in our lab (academic). Matlab parallel computing toolbox licence allows up to 12 local workers so we are aiming at a 12 core server with 4GB memory per core (total of 48gb). The system will have an SSD for the OS and a raid-5 (4x2tb) for data.
I looked around and found a (relatively) cheap vendor, Silicon Mechanics, that offers a system to our liking (specs below) for $6732. However, buying the components from newegg cost only $4464!
The difference is $2268 which is 50% of the base cost. If buying from a company can be thought of as a sort of insurance, basically my premiums are of 50% of the base cost which to me sounds like a lot.
Of course any downtime is bad, but the work is not "mission critical", i.e. if it takes a few days to fix it when it breaks its no the end of the world. If it takes weeks to months then its a problem. If it breaks 2-3 times in 3 years, not too bad. If it breaks every month not good.
In term of build experience, I set up a linux cluster in grad school (from existing computers) and I build my home pcs but I never built a server before.
The server components I'm thinking about:
1 x SUPERMICRO SYS-7046T-6F 4U Tower Server Barebone Dual LGA 1366 Intel 5520 DDR3 1333/1066/800 ($1,050)
12 x Kingston 4GB 240-Pin DDR3 SDRAM DDR3 1333 (PC3 10600) ECC Unbuffered Server Memory  ($420)
2 x Intel Xeon E5645 Westmere-EP 2.4GHz LGA 1366 80W Six-Core ($1,116)
4 x Seagate Constellation ES  2TB 7200 RPM SATA 6.0Gb/s 3.5" ($1,040)
1 x SAMSUNG Internal DVD Writer Black SATA ($20)
1 x Intel 520 Series 2.5" 180GB SATA III MLC SSD $300
1 x LSI LSI00281 PCI-Express 2.0 x8 MD2 Low profile SATA / SAS MegaRAID SAS 9260CV-4i Controller Card, $695
Answer: You're looking at a one-off server, with defined performance parameters, and you know your uptime requirements. When considering the DIY or Buy option, you already know about the difference in recovery time between the two options. One thing to consider is the time it'll take to ship a new part once something breaks. For a warranty service next-day or next-business-day is entirely possible. For a DIY server it could take a week depending on the shipping options used.
In an academic environment, I know that departments are sensitive to sudden unexpected costs. Costs like something major breaking and having the replacement be purchased NOW and use not-cheapest shipping when doing it. This is one reason such departments like to front-load costs in the form of a server + warranty.
If you believe you can get the resources to handle breakage during the lifetime of the server, and 'week' is a good-enough recovery-time-objective for you, then the DIY route makes sense in your case.
Answer: "I'm looking for advice on the classic build vs buy question. " - I barely need to read the rest of your post.
Unless you've got some kind of specialist requirement that makes buying a server in a problem, then that is what you should do. It's usually more reliable, you can get support in case of weird compatibility issues (and they are less likely for parts that came in the server), you can get it backed with a warranty that meets your needs, including hot spares on site if that's what you want to do.
And if cost is an issue, unless you're working for free its probably cheaper to buy a server and use the time it would have taken up to do other work tasks that can't be solved with an off-the-shelf part, instead.


Como subtrair indices extremos do mesmo vetor?

Question:
Estou com dificuldade neste exercício, gostaria de saber como é possível realizar essa operação da fórmula
<code>int main()
{
    int A[20], i, soma, j;

    cout << "Digite o valor do vetor A";

        for (i = 0; i < 6; i++)
        {
            cin >> A[i];
        }

            for (i = 0; i < 6; i--)
            {
                soma=A[i]+A[pow(i+i--)]
            }

    return 0;
}
</code>
Answer: Faça um loop até a metade da quantidade de elementos.
Pegue os extremos (em ordem crescente e decrescente) e some o quadrado dd diferença.
Ao final exiba a soma calculada.
<code>#include <iostream>
#include <cmath>
#define N 6
using namespace std;
int main() {
    int AN0], i, soma=0, j;
    cout << "Digite o valor do vetor A";
    for (i = 0; i < N; i++) {
        cin >> A[i];
    }
    for (i = 0; i < N/2; i++) {
        soma += pow((A[i] - A[N-i-1])), 2);
    }
    cout << "Soma: " << soma << endl
    return 0;
}
</code>
Note que em seu loop você parte de i com o valor zero e decrementa a cada ciclo, portanto ficará em um loop infinito pois sempre será menor que 6 (pelo menos até ocorrer um underflow).


launch SAS code through VBA modules and licence needed

Question: I am trying to launch the following SAS code through VBA. But an

error 429 ActiveX can't create the object

is showing.
Does someone know which licenses/Modules/required_drivers are needed for SAS or Excel?
I am using SAS Enterprise Guide 6.1 and Microsoft Office 15.
The same code worked before on the other PC containing all SAS licenses for SAS 9.3 and Microsoft Office 16.
    Dim OleSAS As Object
    Set OleSAS = CreateObject("SAS.Application")
    OleSAS.Visible = True
    OleSAS.Wait = True
    OleSAS.Submit("SAScode")
    OleSAS.Quit
    Set OleSAS = Nothing

Comment: "ActiveX can't create object" usually means the ProgID you've given `CreateObject` either doesn't exist in the Windows Registry, or the type library otherwise isn't registered for late-binding, or the bitness isn't compatible (e.g. trying to use a 64-bit library from a 32-bit process). Given that same code worked on another machine, I'd first confirm the bitness of the host application (Excel) is the same on both machines, then verify the library registration.
Comment: You're trying to launch a local SAS.EXE?  Or when you say you use enterprise guide, you're actually submitting code to a server and don't have local SAS?
Comment: @Joe Yes I want to submit my SAS code to SAS.exe. SAS is locally installed.
Comment: @Mat'sMug Thank you very much, I will check it out
Answer: The easiest way to call SAS from VBA is via the StoredProcess server.  This approach also nicely separates the SAS code from VBA logic.  An explanation can be found here, which essentially involves:

Registering your SAS code as a Stored Process with streaming output
Setting up a web query in excel, with relevant parameters in the url
Calling the refresh event on the QueryTables object

Another nice thing about this approach is that you don't need the addin, or a local instance of SAS.  However you do need SSO.


How to display the value of a variable used in a PL/SQL block in the log file of a batch file? And Arrays?

Question: Basically I'm using a batch file to run a .sql file on Windows Task Scheduler. The batch file generates a log file that displays all the put_lines. I now want to also see the value assigned to the variable: v_chks_dm, but couldn't figure out a way to do it. Tried the get_line statement but failed... Does anyone know how to do it?
thanks!
This is what's in the batch file:
echo off
echo ****************************>>C:\output.log

sqlplus userid/password@csdpro @V:\CONDITION_TEST.sql>>C:\output.log

Here's the .sql file
declare
  v_chks_dm  number;
  begin
  Select /*+parallel (a,4)*/ count(distinct a.src_table) into v_chks_dm
    from hcr_dm.hcr_dm_fact a;
    dbms_output.put_line('v_chkt_dm value assigned');
--  dbms_output.get_line(v_chks_dm);
  if.... then... else.... end if;
  end;

One more question... what if the variable is an array? I have something like this, but got an error says ORA-06533: Subscript beyond count. The number of values in the array usually varies from 0 to 10, but could be more. Thanks!
  declare
  type v_chks_array is varray(10) of varchar2(50);
  arrSRCs v_chks_array;
  begin
  arrSRCs :=v_chks_array();
  arrSRCs.EXTEND(10);
  Select /*+parallel (a,4)*/ distinct a.src_table BULK collect into arrSRCs
    from hcr_dm.hcr_dm_fact a;
  dbms_output.put_line(arrSRCs(10));
  end;

Answer: dbms_output.put_line('v_chkt_dm value = ' || v_chkt_dm);

or, better
dbms_output.put_line('v_chkt_dm value = ' || to_char(v_chkt_dm, '<number format>'));

You can choose appropriate number formats in documentation.
Comment: Well that was easy... Thanks!
Comment: Well, you also should know about functions lpad and rpad, I predict it is next you will want to use :)))
Comment: You can use lpad and rpad functions to format text output.


Convert line endings when copying from excel to word

Question: Is there an elegant / correct way to deal with CRLF line endings when copying from Excel to Word?
We have some text stored in a database that uses \r\n (i.e. CRLF) for new lines. We use a tool[1] to query the  database and pull the values into Excel. It looks fine in Excel but if we then copy a cell into Word there are two line breaks where there should only be one.
For example the string This is line #1\r\nThis is line #2. looks fine in excel but if we copy from Excel and paste into Word it's 3 lines long.
I've got a macro that removes the CR but it's a bit of a nasty hack and I'd rather not push it out to all users if there is a better solution.
Sub UpdateLineEndings()
'
' UpdateLineEndings Macro
'
ActiveCell.Value = Replace(Selection.Text, vbCr, "")

End Sub

[1] We're useing Sharperlight but I'm sure there are lot's of similar tools out there.
Comment: You have to do a replace *somewhere*, so either you do it in your SQL or you do it in VBA.  It might be safer to do `Replace(txt, vbCrLf, vbLf)`
Answer: Thanks for that @tim-williams I had been hoping there was a way to do it when copy / pasting (a bit like the "keep text only" option).
As you said, I have to do a replace somewhere, I ended up doing it in the SQL of the Sharperlight data model. The column was text, so I cast it as varchar and then did the replace.
REPLACE(CAST({_Table.Alias}.COMMENTS as varchar(MAX)), CHAR(13)+CHAR(10), CHAR(10))
If you want to make your comment as an answer I'm happy to mark it as correct.


How to properly test query performance

Question: I have a function that takes either an array of IDs or a singular ID as an argument.  If an array is passed, it is imploded on comma to make the IDs query friendly.
There is a query inside this function that updates the records for the IDs that were passed.
The query is as follows:
"UPDATE tbl_name SET enabled = 1 WHERE ID IN (" . $IDs . ")";

Now, I'm wondering if there's a performance issue with using tha above query for the array and something like:
"UPDATE tbl_name SET enabled = 1 WHERE ID = " . $IDs;

if only a single ID is passed.
I tested both queries in the MySQL query browser for the same ID and got a performance of .02 seconds for both queries - a trivial difference in performance.
Is simply testing the two in the query browser an ok way to check the optimal query performance?
It's just that I don't want to pollute my code with two queries in the one function if it is not necessary.
Answer: I would lose the second query and only leave the first one to make the code more readable and maintainable.
if (is_array($id)) $id = implode(',', $id);
$query = 'UPDATE table SET marked = 1 WHERE id IN ('.$id.')';

That way you'll get either one of these sample queries:
UPDATE table SET marked = 1 WHERE id IN (15);
UPDATE table SET marked = 1 WHERE id IN (21,12,15,16);

Here's what MySQL manual says about the usage of operator IN:

If all values are constants, they are evaluated according to the type of expr and sorted. The search for the item then is done using a binary search. This means IN is very quick if the IN value list consists entirely of constants.

I'd also suggest to "don't fix what isn't broken" and better take care to write a clean, readable and maintainable code, because your time is more valuable than your server's time especially if it's a millisecond or less. First look at the performance of an application and if it's okay then you're done - move on to other things you can do with your time. If it's slow - measure it (simple time measurements will do) to pinpoint what is slow and then only optimize that. Usually what is slow is some big messy select from lots of tables with lots of joins, but not a simple update like this. Also keep in mind that updates (usually) are rare and the user can wait for them, so focus on optimizing selects.
Answer: If you are looking to be thrifty on cpu cycles and want performance go with IN .
Think of it this way .. you have to take 10 items to ur neighbors house ... which will be faster? taking all 10 at the same time or doing it one by one.. even if its a millisecond , when multiplied with the number of instances  , it would become significant.
Just imagine what would happen in the background when u send one query to mysql , the mysql engine needs to compile every query and then process it and dont forget the part where PHP has to communicate over the network to send ur query to mysql.
So if u are sending 10 queries instead of one .. u multiply the processing time. This is exactly why "Views" are faster than standard select statements.
Answer: you can try running both queries in big loops with random IDs
Answer: this is what i would use.. and actualy this is what i usualy use when i need to update my mysql.
"UPDATE tbl_name SET enabled = 1 WHERE ID = " . $IDs;

but if you realy want to compare this 2.. i suggest you give them a lot of ids o proccess and then you will know which one is the best.. for a single id the preformance is the same.. but i dont think the performance for 100 id`s will be the same. let me know the result please.thanks
Comment: for 100 IDS I have no choice but to use the IN version, unless I want to run the above query 100 times for 100 ids.  Obviously, that would be unwise.

How to properly test query performance


How can I tell if I have Windows 2012 R2 (vs the 'R1' original release')?

Question: How can I tell if I have Windows 2012 R2 or just "2012"?  I can't seem to see any signs of "R2" anywhere yet I ordered a (remote) server with this installed and I want to verify I have the correct edition installed before I go any further with the server build.
Answer: Drop into a command prompt and issue either of the following commands;
systeminfo | findstr OS

Or
winver

You can then use this table to determine the version;

Operating System Version

Which shows:
Operating system            Version number
Windows 8.1                 6.3*
Windows Server 2012 R2      6.3*
Windows 8                   6.2
Windows Server 2012         6.2
Windows 7                   6.1
Windows Server 2008 R2      6.1
Windows Server 2008         6.0
Windows Vista               6.0
Windows Server 2003 R2      5.2
Windows Server 2003         5.2
Windows XP 64-Bit Edition   5.2
Windows XP                  5.1
Windows 2000                5.0

Based on your comment, it would appear you're running Windows Server 2012 as opposed to Windows Server 2012 R2
Comment: Added some more detail for you, I'd appreciate the tick and an upvote if this has worked for you :)
Comment: But what should it say for R2? Will it actually say "R2" somewhere or just give a later build number?  I'm just getting Version 6.2 (Build 9200).
Comment: No problem, glad I could help
Answer: If you have the GUI installed an instant visual clue will be the absence (Server 2012) or presence (Server 2012 R2) of an actual Start button on the taskbar.
Answer: In GUI it's easy to check the version: Control Panel > System and Security > System
Comment: The critical thing was, I wasn't sure if "R2" would say anything different on this screen and "R1" obviously doesn't say R1, so thanks for the screenshot.
Answer: You could also search for the Software Identification Tag File (ISO 19772). This is an XML file on your drive. Just search for: regid.1991-06.com.microsoft.*.swidtag
Usually for Windows OS the files are located in "c:\ProgramData\regid.1991-06.com.microsoft". In this file you will find the tag <product_title> e.g.
<product_title>Windows Server 2012 R2 Datacenter</product_title>


Interpreting a non-significant interaction when only one of the first order effect remains significant

Question: I'm trying to figure out how to interpret these results.
In my first regression, I include both of my two independent variables (IV1 and IV2) to predict a Dependent Variable (DV):

IV1 is significant
IV2 is significant

In my second regression, when I add the interaction term:

IV1 remains significant
IV2 is no longer significant
IV1*IV2 is not significant

This pattern occurs when the DV is coded as a dummy (in a logistic regression) and when it is a continuous variable (in a linear regression).
How do I interpret these results?
Answer: When adding a term to a model causes another term to become nonsignificant, that means that the new term has some collinearity with the old one.  The fact that the new term in this case is an interaction doesn't change the general nature of linear regression.  In order for a term to gain significance it has to make a distinct contribution to the explanation of the Dependent Variable.  If two terms carry the same information then neither will be significant even when that information is valuable.
My interpretation of your result is that IV2 does matter but the interaction IV1*IV2 looks a lot like IV2 and it doesn't add much information about the DV.  I would expect a model selection criterion like AIC to tell you that model your first model is better than your second, but that the second model is better than one with IV1 alone.
Comment: Thanks! You were correct. AIC indicated that my first model was better than the second.


about transform property in css

Question:

* {
  padding: 0;
  margin: 0;
}
div {
  /* background-image: url(img/pic-1.png); */
  background-color: green;
  background-repeat: no-repeat;
  width: 10vw;
  height: 30vh;
  border-radius: 10px;
  padding: 0.5em;
  background-size: cover;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transition: 0.5s;
}
div:hover {
  box-shadow: 5px 5px 2px greenyellow;
  transform: rotateZ(10deg);
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias, nihil!

as you can see i used transform:translate() property to center the div.and i want it rotate about 10deg when i hover on the div but it isn't happening i know its because i used translate property to center the div ,when i commented that part out it working fine. i just want to know what causing this behavior.
Answer: Change transform: rotateZ(10deg) to transform: translate(-50%, -50%) rotateZ(10deg); to keep the traslate value along with rotate. Otherwise you're overriding translate with rotate on hover and the element will move to it's actual position and rotate from there.

* {
  padding: 0;
  margin: 0;
}
div {
  /* background-image: url(img/pic-1.png); */
  background-color: green;
  background-repeat: no-repeat;
  width: 10vw;
  height: 30vh;
  border-radius: 10px;
  padding: 0.5em;
  background-size: cover;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transition: 0.5s;
}
div:hover {
  box-shadow: 5px 5px 2px greenyellow;
  transform: translate(-50%, -50%) rotateZ(10deg);
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias, nihil!

about transform property in css


how do i add a line break to a text from react state

Question: So here's a perfectly working react code
const about={
  text1: 'Lorem, ipsum dolor sit amet consectetur adipisicing elit. Facere, qui?',
  text2: 'eligendi voluptates nesciunt quam dolor reiciendis dolorum voluptas? Labore, a pariatur?'
}

function App() {

  const [text, setText] = useState(about)
  const [switchh, setSwitch] = useState(false)

  return (

      <button onClick={() => setSwitch(!switchh)}>switch</button>

{switchh ? text.text1 : text.text2}

  );
}

export default App;

this code is working as it should however I can't seem to find a way to add line break to it. I want it to look like this

Lorem, ipsum dolor sit amet
 consectetur adipisicing elit. Facere, qui?

how do i achieve that while using state cause I need the switch also
Comment: why can't you add the same html as text1's value ?
Comment: I have created a codebase - https://codesandbox.io/s/determined-feather-qd7me?file=/src/App.js
Comment: @Sarun UK - Your approach is great, using React elements / JSX instead of a string is very powerful. You should turn it into an answer :)
Answer: If you can change the content of about object, and if you don't mind to add some css for the element, you can try this:
const about={
  text1: 'Lorem, ipsum dolor sit amet \n consectetur adipisicing elit. Facere, qui?',
  text2: 'eligendi voluptates nesciunt \n quam dolor reiciendis dolorum voluptas? Labore, a pariatur?'
}

...

{switchh ? text.text1 : text.text2}

and the css:
.my-text {
  white-space: pre-wrap;
}

Answer: Try this approach,
Use html as value to the text1 itself like below,
const about = {
  text1: (

      Lorem, ipsum dolor sit amet

 consectetur adipisicing elit. Facere, qui?

  ),
  text2:
    "eligendi voluptates nesciunt quam dolor reiciendis dolorum voluptas? Labore, a pariatur?"
};

Complete Code:-
import React, { useState } from "react";
import "./styles.css";

const about = {
  text1: (

      Lorem, ipsum dolor sit amet

 consectetur adipisicing elit. Facere, qui?

  ),
  text2:
    "eligendi voluptates nesciunt quam dolor reiciendis dolorum voluptas? Labore, a pariatur?"
};

export default function App() {
  const [text, setText] = useState(about);
  const [switchh, setSwitch] = useState(false);

  return (

      <button onClick={() => setSwitch(!switchh)}>switch</button>

{switchh ? text.text1 : text.text2}

  );
}

Working code - https://codesandbox.io/s/determined-feather-qd7me?file=/src/App.js
Answer: Storing a react element in state is not a good practice and try not to use reserved words like switch. If a state holds a boolean value, a good practice is to name the variable starting with 'is' or 'has'.
My solution:
import React, { useState } from "react";
import "./styles.css";

const about = {
  text1: (

      Lorem, ipsum dolor sit amet

 consectetur adipisicing elit. Facere, qui?

  ),
  text2:
    "eligendi voluptates nesciunt quam dolor reiciendis dolorum voluptas? Labore, a pariatur?"
};

export default function App() {
  const [isSwitchedOn, setIsSwitchedOn] = useState(false);

  return (

      <button onClick={() => setIsSwitchedOn(!isSwitchedOn)}>switch</button>

{isSwitchedOn ? about.text1 : about.text2}

  );
}

Answer: you could use an array and map it to {text}
import React, { useState } from "react";
import "./styles.css";

const about = {
  text1: [
    'Lorem, ipsum dolor sit amet',
     'consectetur adipisicing elit. Facere, qui?'
  ],
  text2:
    "eligendi voluptates nesciunt quam dolor reiciendis dolorum voluptas? Labore, a pariatur?"
};

export default function App() {
  const [text, setText] = useState(about);
  const [switchh, setSwitch] = useState(false);
console.log(text.text1)
  return (

      <button onClick={() => setSwitch(!switchh)}>switch</button>

{switchh ? text.text1.map(line=>(<React.Fragment key={line}>{line}
</React.Fragment>)) : text.text2}

  );
}


Exchange 2010 - Hybrid Office 365, need to update admin identity password

Question: We have two on-premise Exchange 2010 servers, and one Exchange Online (O365 for Business).
I've changed the password for our O365 Global Admin account (which is also used to connect the hybrid set-up) and now when I jump on to our On premise server, I can't view mailbox, distribution group etc through the EMC.
Can anyone point me in the right direction on where I update the credentials for the Administrator Identity within our on-premise Exchange server for our Remote server?
Do I need to use Powershell for this?
Regards,
Vas
Answer: In the EAC, right-click the top node and just re-add the O365 connection as a new forest.  It will ask you for credentials to connect.


Fragment Android

Question: Estou tentando fazer um app com o layout Navigation Drawer, porem usa Fragments, não estou conseguindo chamar outra tela utilizando Fragments.
             Login fragment = new Login();
             android.support.v4.app.FragmentTransaction fragmentTransaction =                              getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

Codigo que eu utlizava , porem não da mais, da erro no fragment_container. Alguem poderia ajudar?
Answer: Veja assim:
        Login fragment = new Login();
        FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, fragment);
        transaction.addToBackStack(null);
        transaction.commit();

Aqui estou usando getActivity() porque estou chamando o fragmento login de dentro de outro fragmento. Talvez você tenha de adaptar à sua logica.

Fragment Android


Simple rule engine to replace if statements with AND condition

Question: I have some simple conditions:
if(source.equals("something") && target.equals("something")){
        // suggested tool (high priority)
        // suggested another tool (low priority)
    }

else if (...){
        // suggested some other tool
    }
.....

There are around 50 conditions. It can grow later.

There is only && condition
priority can be a number between 1 to 5.

I can provide a csv input file like:
source,target,tool,priority
abc,xyz,xxx,5
abc,xyz,yyy,3
...

Possible ways I can think of:

read this csv file
convert it into objects and persist it in the embedded database
query the database and fetch the highest priority tool

This is not the best way as the number of conditions is few (around 50).
Is there any simple rule engine that can do this work?
Comment: ehm ..; so, what is it you're actually asking?
Comment: solve 'what'? there is no problem described, so what is it you have, what is it you try to achieve and what have you tried so far?
Comment: you still haven't put anything yet that needs "solving"
Comment: @Stultuske As mentioned in the question - Is there any simple rule engine that can solve this?
Comment: @Stultuske check updated question
Comment: You don't really need a database though? I mean... why not just write the objects in a HashMap with source+target as the key and a list of tool+priority as the value? That way you can easily get to any tool suggestion list (which you can simply sort by priority)?
Comment: @Mark this can be an option and yes its better than persisting in db
Comment: You could compose a condition in Javascript and execute the script through the java api. If you use Java 7 or higher version, the javascript interpeter is integrated, for lower version have a look to Mozilla Rhino. If you have in mind something like a rule engine try [drools](http://www.drools.org/)
Answer: Every rule engine can do this:)
Try engines for Java like Jess, Drools, or more lighweight solutions like HeaRTDroid, or EasyRules.


Importar Tabelas do Excel no R

Question: Gostaria de saber qual a melhor library para importar tabelas do excel para serem manipuladas em R. Gostaria de uma que me desse suporte a todas as extensões, principalmente a .xlsm.
Comment: Já tinha lido esse tópico, mas não funcionou para mim.
Comment: Lá tem 3 soluções. Uma delas é a idêntica à resposta que você aceitou..
Comment: Testei as 3 e não funcionaram.
Comment: você testou essa? https://pt.stackoverflow.com/a/159395/6036
Comment: Instalei a library, segui o passo a passo do exemplo. Mas, logo quando eu mando montar a library com o comando library("readxl") ele já me dá uma mensagem de alerta avisando que o pacote foi feito em uma varsão anterior a do R que eu uso - a versão 3.3.3 x64. O que eu poderia fazer para solucionar isso?
Comment: esse warning não é um problema!! ele só está dizendo que a sua versão do R está desatualizada.
Answer: Encontrei uma forma de fazer a leitura com o pacote XLConnect.
require(XLConnect)

dados <- readWorksheetFromFile("Pasta1.xlsm", sheet=1)

Aqui funcionou para um conjunto bem simples de dados salvos em xlsm.
Este pacote serve para vários tipos de arquivo excel. Mas a forma mais comum (para .xls e .xlsx) é a que havia descrito antes:

Segundo a resposta neste tópico do StackOverflow em inglês, é
  possível fazer a leitura com o pacote XLSX do R, com o comando
  read.xlsx ou read.xlsx2. Acredito que funcione para xlsm, porém
  não posso dizer com certeza pois nunca utilizei para este formato.
Este pacote possibilita a leitura de vários formatos utilizados no
  Excel, tais como csv, xls e xlsx. Acredito que também funcione para
  xlsb e xlsm.

Espero que dessa vez ajude!
Comment: Testei essa função, mas não funcionou para a extensão .xlsm. Vou continuar pesquisando. Muito obrigado!
Comment: Acho que com essa edição que fiz resolve seu problema. Deu certo em um teste simples que fiz.
Comment: Consegui instalar o pacote, mas dá um erro dizendo que não foi encontrado o "perl" e também que ele foi construindo em uma versão anterior.
Comment: Isso para o XLConnect?
Porque agora que vi, tinha colocado o pacote errado no require. Era para ser o próprio XLConnect
Comment: Agora consegui acionar o pacote! Mas, ele não está localizando a planilha. Tentei incluir o caminho da planilha, mas daí dá erro de parametrização. Será como eu poderia resolver isso?
Comment: Pode postar a mensagem de erro? (e também como você passou o caminho?)
Comment: > data <- readWorksheetFromFile("BRFS3.xlsm", sheet=2)
Erro: FileNotFoundException (Java): File 'BRFS3.xlsm' could not be found - you may specify to automatically create the file if not existing.
> data <- readWorksheetFromFile("D:\Folha Invest\2017\selecao\BRFS3.xlsm", sheet=2)
Erro: '\F'  é uma seqüência de escape não reconhecida na cadeia de caracteres começando com ""D:\F"
Comment: Tente com:
readWorksheetFromFile("D:\\Folha Invest\\2017\\selecao\\BRFS3.xlsm", sheet=2)

O R interpreta a '\' como um caracter especial. Você precisa colocar \\ (dupla) para ele entender como parte do endereço, ou substituir pot '/'.

Avise se der certo :)
Comment: Agora deu certo! Muito obrigado!
Comment: Show :)

Abraços!

Importar Tabelas do Excel no R


Como desabilitar o evento do botão direito do mouse no Angular 7?

Question: Estou tentando desabilitar aquele menu que aparece na página quando o usuário clica com o botão direito do mouse.
No Angular, eu consigo pegar o evento de click usando (click)="onRightClick($event), mas eu pego apenas o "Left Click" no $event.
Lembrando que se eu fizer HostListener('click') myClick(){ } é a mesma coisa que (click)="myClick()
Pesquisei na documentação do Angular e do @HostListener e não encontrei uma solução.
Link da documentação do @HostListener: Angular - HostListener
Esse é o código onde pego o evento do click, mas ele pega apenas o Left Click, quando é o Right Click, o código não é acionado.
@HostListener('click', ['$event'])
  onClick(event) {
    console.log(event);
  }

Answer: O (click) assim como o parametro 'click' em @HostListener irão executar como addEventListner, o evento click funciona mesmo somente com o click esquerdo, se deseja fazer mais iterações com o mouse deve usar mousedown, exemplo:
@HostListener('mousedown', ['$event'])
teste(event: MouseEvent)
{
    switch (event.button) {
        case 1:
            console.log('Botão esquerdo do mouse! ');
            break;
        case 2:
            console.log('Botão direito do mouse! ');
            break;
        default:
            console.log('Outro botão de mouse (click no scroll, mouse gamer, etc)');
    }
}

Comment: @EdwardRamos não imaginei que o objetivo era bloquear o menu de contexto, no caso se for isso experimente assim `@HostListener('contextmenu', ['$event'])` e pode experimentar também: `(contextmenu)="teste($event)"` e na classe aplique o preventDefault: `teste(event) { event.preventDefault(); }`
Comment: Obrigado pela ajuda, o seu código funcionou, só preciso de uma forma de cancelar o evento. Seja executando a ação de novo, seja, ocultando o menu que abre ao clicar com o botão direito... enfim, se tiver algum comando para tratar esse evento, é bem vindo.
Comment: @EdwardRamos seria dentro do método o `teste(event: MouseEvent)
{ event.preventDefault();`?
Comment: Isso mesmo, só que quando uso `event.preventDefault();` , nada acontece. Parece que esse método não funciona.
Comment: @EdwardRamos quer cancelar qual evento?
Comment: Cancelar o evento do botão direito, pois o preventDefaulr() não está funcionando. Eu resolvi esconder o Body quando esse evento for acionado, foi a forma mais simples de resolver isso, mas os usuários vão acabar reclamando que a página "some", enfim, é o que dá pra fazer até aqui. Vou marcar como valida a sua resposta, pois foi a que mais me ajudou a chegar no objetivo.
Comment: Olha, funcionou! @GuilhermeNascimento muito obrigado pela ajuda!


sqlite3 and sqlalchemy stores a different datetime

Question: I'm trying to create a async database for my api, but when i insert a datetime, it stores a different value. The database schema that i created in my Python files.
prices = sqlalchemy.Table(
"prices",
metadata,
sqlalchemy.Column("id", sqlalchemy.String),
sqlalchemy.Column("value", sqlalchemy.String),
sqlalchemy.Column("date", sqlalchemy.DateTime, primary_key=True),)

I tried to insert a datetime manually with the ISO 8601(YYYY-MM-DD) format;
insert into prices (date) values (2001-08-27);
insert into prices (date) values (2000-04-21);

But when i check the database, i see this weird result;
sqlite> select * from prices;
||1966
||1975

Is there a spesific reason why or am i missing something?
Answer: You've got to quote the values.
Here's an example:
sqlite> insert into prices (date) values ('2001-08-27');
sqlite> select date from prices;
2001-08-27


Fazer Variável com múltiplos nomes e uma única String de Valor

Question: Seria possível criar uma única variável que tem a influência mútua por outros nomes nela.
Em outras palavras, nomes diferentes para mesma declaração var, e no fim terão o mesmo valor.
Exemplo
Estou fazendo assim:

var perfume = "Racco";

var colonia = "Racco";

var roll-on = "Racco";

Desejo algo assim:

var perfume, colonia, roll-on = "Racco"

Não importa! Qualquer um dos três nomes, corresponde a mesma new String();.
Basta apenas uma var, com diversos nomes, para chamar somente um único Valor.

Ha como fazer isso? Depois de declarada mais de uma variável na mesma linha trazer um único valor para todas elas.
Answer: Você pode atribuir o mesmo valor a várias variáveis de uma vez da seguinte maneira:
var perfume = colonia = rollon = "Racco"

Mas no caso acima, se as variáveis colonia e rollon ainda não tiverem declaradas, elas serão variáveis globais.
Se você deseja criar variáveis para o escopo local e atribuir o mesmo valor à elas você precisa fazer as duas coisas em etapas separadas:
var perfume, colonia, rollon;
perfume = colonia = rollon = "Racco";

Se na verdade o que você quer é alterar uma só variável e ter o valor "automaticamente" alterado nas outras: No javascript isso não é possível com tipos primitivos, somente com tipos complexos, pois eles são passados como referência:

var objeto = {};
objeto.x = 10;
var objeto_2 = objeto;
objeto_2.x = 20;
console.log(objeto.x); // objeto.x == 20


Creating a Navigation fades to different colors when scrolling to element

Question: I am creating a single page website with a fixed navigation. There are 4 different sections. When the user clicks the link in the navigation, I would like to fade the color of the navigation to match the theme of the section it takes them to. What would be the best way to go about doing this? I've tried many different things, but nothing seems to achieve the look I am going for. -Thanks in advance!
Comment: Please post what ever code you tried
Comment: Id rather not alter the crappy code Ive already tried. Im looking to start fresh, doing things correctly.
Answer: So you will need a couple of things to accomplish this.

Nav layer sitting above other layers
stacked background layers for each section with static background colors
knowledge of current color and new section color

And what you will do with that is to have each section keep track of its color. When the nav for that section is selected, the current layer behind the nav begins to fade out. At the same time, the layer of the new section begins to fade in. This will give the impression of one color fading into another.

edit
jsFiddle Demo
Here is a very rudimentary example of doing this. There should probably be more structure, better styling, and perhaps more management of state in code. However, clicking the links will demonstrate the color fading.

js

$("#redSection,#redPane").show();
$("#navLinks div").click(function(){
 $(".pane:visible,.section:visible").fadeOut("slow");
 var color = this.getAttribute("data-color");
 $("#"+color+"Section,#"+color+"Pane").stop().fadeIn("slow");
});

html

about

contact

overview

links

about

contact

overview

links

css

#layers{
 position:relative;
}
#navLinks div{
 font-weight:bold;
 font-size:110%;
 text-decoration:underline;
 cursor:pointer;
 position:relative;
 z-index:1;
}
.section{
 display:none;
 height:100px;
 width:100px;
 position:absolute;
}
#redSection{
 background-color:red;
}
#greenSection{
 background-color:green;
}
#blueSection{
 background-color:blue;
}
#orangeSection{
 background-color:orange;
}
.pane{
 position:absolute;
 right:0;
 left:0;
 top:0;
 bottom:0;
 display:none;
}
#redPane{
 background-color:red;
}
#greenPane{
 background-color:green;
}
#bluePane{
 background-color:blue;
}
#orangePane{
 background-color:orange;
}
#contentArea{
 position:relative;
}

Comment: I am very visual. Care to show me a brief example? I would greatly appreciate it.
Comment: It is very nice. Just the type of effect I am looking for. However, does the data-color absolutely necessary? I had done something similar to this but unfortunately it is not compatible with the CMS I am using... Can it be replaced with "id" and then replaced in the js as well?
Comment: @TheDesigner - This is just a demo of the concept, you can change anything you wish. The functionality derives from fading one color out while fading the next in, in the same place, to mimic fading from one color the another.


Different way of expressing variance

Question: I am having trouble with the following statement (from one of the answers from SOA exam, don't worry about the question as it has no bearing on the question I am asking).

The marginal distribution of X has probability $1/5 + a$ at $0$, $2a + b$ at $1$, and $1/5 + a$ at $2$. Due to symmetry, the mean is $1$ and so the variance is $(0-1)^2 (1/ 5+a ) +(1- 0)^2 (1/ 5 +a) = 2/5+2a$

I do not recognize this expression for variance from anywhere that I remember. The only one I am familiar with is $${E(X^2)-{[E(X)]}^2}$$
Can somebody please explain to me this other expression that is being used here, $(0-1)^2 (1/ 5+a ) +(1- 0)^2 (1/ 5 +a)$, or even just provide a link?
Comment: Have you understood why $a=b$?
Comment: It is not, I think it was a typo.
Comment: No it isn´t a typo
Comment: Well, here is a link to the question,how does $a=b$?. https://i.stack.imgur.com/TfhjE.png
Comment: After I have looked at the joint pdf I recognised that we cannot say for sure that $a=b$
Answer: \begin{align}
E[(X-E[X])^2] &= E[X^2-2XE[X]+(E[X])^2] \\
&=E[X^2]-2E[X]E[X]+(E[X])^2 \\
&=E[X^2]-2(E[X])^2+(E[X])^2 \\
&=E[X^2]-(E[X])^2 \\
\end{align}
They use an alternative expression for the variance which is just $E[((X-E[X])^2] $.
We have three values, $x_1, x_2, x_3$ where $x_2$ is the mean and $(x_3-x_2)^2=(x_1-x_2)^2$ in this question.
Comment: Shouldn't it be $(0-1)^2 (1/ 5+a )+(2-1)^2 (1/ 5 +a)$ as that would be consistent with the alternative expression you posted, $E[((X-E[X])^2]$?
Comment: yes, just that by symmetry, you could have just written it as $2(0-1)^2(1/5+a)$ as well.
Comment: Sorry, would you mind explaining a bit more, I think I understand $(0-1)^2 (1/ 5+a )$ but I am still confused about $(1- 0)^2 (1/ 5 +a)$, what does the $0$ represent?
Comment: I think they use symmetry about the mean. There are two values that is not equal to the mean, of which the distance to the mean is equal.
Comment: thanks callculus.
Comment: Ah, I think I understand what you are saying now. Thank you!

Different way of expressing variance


minimal sufficient statistic

Question: Let X ~ Ber(n1; p), Y ~ Ber(n2; p^2), where X and Y are independent. Find a minimal
sufficient statistic T and, using a nontrivial function, show that it is not complete.
I get confused by having two different distribution! is it true to simply multiply these two distribution and use factorization theory?
Comment: I think so, because the joint density f(x,y|p)=f(x|p)f(y|p) because they are independent. But what is Bern(n1, p)? Bernoulli has just one parameter. Do you mean Binomial?
Comment: I double @Stacker, what do you mean by $Ber(n_1; p)$?
Comment: it seems that, it ends with two different variable that can not merge with each other in a good way !!
Comment: I am sorry but that does not answer the question of what do you mean by $Ber$?
Comment: @mrsergazinov, I am actually not sure but you are right, it should be Bin(n1,p) and Bin(n2,p^2), or just Be(p) and Be(p^2),  but I think it does not make much difference in solution path.
Comment: I think the easiest way here would be to use the Lehmann-Scheffe theorem to obtain your MSS.
Comment: so it means that I should find T and then use Lehmann-theorem, my question is when I use factorization theory, its end up with "p^sumX+2sumY . (1-p)^n1-sumX . (1-p^2)^n2-sumY"  . I dont know how to use factorization theory for this equation. @mrsergazinov
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/119841/discussion-between-mrsergazinov-and-sara-st).
Answer: First write the likelihood function: $$f(x,y|p) = [p^x(1-p)^{1-x}][p^{2y}(1-p^2)^{1-y}]$$
From this use the Lehmann-Scheffe Theorem. Need to find $T$ such that $$T(x_1, y_1) = T(x_2, y_2) \Leftrightarrow \frac{f(x_1,y_1|p)}{f(x_2,y_2|p)} = c(x_1, y_1, x_2, y_2)$$
To this end, let's compute the likelihood ratio:
\begin{align}
\frac{f(x_1,y_1|p)}{f(x_2,y_2|p)} &=
\frac{p^{x_1}(1-p)^{1-x_1}p^{2y_1}(1-p^2)^{1-y_1}}{p^{x_2}(1-p)^{1-x_2}p^{2y_2}(1-p^2)^{1-y_2}} \\
&= p^{(x_1 - x_2)} (1-p)^{x_2 - x_1}p^{2(y_1 - y_2)} (1-p^2)^{y_2-y_1}
\end{align}
It can be seen then that the ratio does not depend on $p$ if and only if $x_1 = x_2, y_1 = y_2$. By the Lehmann-Scheffe, this implies that $T(X, Y) = (X, Y)$ is the minimal sufficient statistic.
Comment: I have not worked this out, but you can try and find some function $g$ of $T(X, Y) = (X, Y)$ that has $E_p[g(X, Y)] = 0$ for all $p$ with $g$ not being $=0$ almost everywhere.
Comment: do you know,how I can show that this is not complete??! because it seems that is complete but in the question ask to show that its not complete!

minimal sufficient statistic


QGraphicsScene, QTextEdit and lost focus

Question: QTextEdit and similar widgets embedded in QGraphicsScene lose focus after using standard context menu (copy/paste), i. e. you need to click on QTextEdit again to continue editing. Scene emits focusItemChanged with newFocusItem==0.
First question: Is it a bug or standard behavior?
My investigation shows that function QGraphicsItemPrivate::setVisibleHelper() clears focus here:
if (hasFocus && scene) {
    // Hiding the focus item or the closest non-panel ancestor of the focus item
    QGraphicsItem *focusItem = scene->focusItem();
    bool clear = true;
    if (isWidget && !focusItem->isPanel()) {
        do {
            if (focusItem == q_ptr) {
                clear = !static_cast<QGraphicsWidget *>(q_ptr)->focusNextPrevChild(true);
                break;
            }
        } while ((focusItem = focusItem->parentWidget()) && !focusItem->isPanel());
    }
    if (clear)
        clearFocusHelper(/* giveFocusToParent = */ false, hiddenByPanel);
}

QGraphisItem has undocumented (internal) flag QGraphicsItem::ItemIsFocusScope. If the flag is set for QTextEdit's proxy-item it gets focus back after menu, but in any case focus cleared at first and after that Item receives it again or not.
Second Question: What is flag QGraphicsItem::ItemIsFocusScope for?
Answer: Looks like QGraphicsItem::ItemIsFocusScope is for FocusScope QML item. QtQuick1 is QGraphicsScene based and used that flag.
I'm not sure about side effects but that helps:
auto edit = new QLineEdit();
auto item = scene->addWidget(edit);
item->setFlag(QGraphicsItem::GraphicsItemFlag::ItemIsPanel);

Tested on Qt 5.9, Linux

EDIT
For me looks as bug:

add QLineEdit to scene
click to focus QLineEdit
hit ContextMenu key to show context menu
hit Esc key to exit context menu
try to type

Expected: QLineEdit is focused and text appears
Actual: QLineEdit lost input focus
Please find it or report with Qt bug tracker
So it's OK to have workaround using QGraphicsItem::ItemIsFocusScope flag for example.
#if (QT_VERSION < QT_VERSION_CHECK(<fixed in Qt version>))
// it's workaround of bug QTBUG-...
#    if (QT_VERSION == QT_VERSION_CHECK(<version you are develop with>)
    item.setFlag(QGraphicsItem::ItemIsFocusScope);
#    else
#        error("The workaround is not tested on this version of Qt. Please run tests/bug_..._workaround_test")
#    endif

Comment: Антон Сергунов, ItemIsPanel flag totally disallows focus in Qt 5.6.2.
Comment: I've tested on Linux, Qt 5.9
Comment: @Guest2016 Edited the answer. Please check
Comment: I have checked 5.7.1 and 5.9.1 on Linux.

If the flag ItemIsPanel is set for a proxy item, focus does not work immediately after the qt app starts.
To make it work It is necessary to switch to another app and return back.

Moreover if we have two QTextEdits: the first in QMainWindow and the second in QGraphicsScene, after the second switch/return we can see two blinking cursors simultaneously (in the both QLineEdits).


How can I make a CSS background that is all white with a 100px blue bar at the top of the page, with a 50px orange bar?

Question: I asked a similar question a month ago where I just needed the blue bar, and I wound up using this code:
html {  }
body:before {
content: " ";
display:block;
position:absolute;
top:0;
left:0;
right:0;
height:60px;
background:#00205c;
}

it worked great, but now I am trying to add a 50px orange bar below it. i was trying to use gradients, but haven't had any luck. thank you in advance!
Answer: html supports the :before pseudo class as well so this works for me...

html:before {
  content: "";
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: blue;
}
body:before {
  content: "";
  display: block;
  position: absolute;
  top: 60px;
  left: 0;
  right: 0;
  height: 50px;
  background: orange;
}
Comment: Ahhh... I misunderstood what you wanted... Give me a minute
Comment: Note common properties can be moved to a `html:before, body:before` rule: http://jsfiddle.net/y12rmvfo/
Comment: this makes the orange bar go to the bottom of the page at whatever size the window currently is.... very odd
Comment: awesome. that makes so much sense not!
Answer: You can add a linear-gradient this way.

html {
}
body:before {
    content:" ";
    display:block;
    position:absolute;
    top:0;
    left:0;
    right:0;
    height:110px;
    background: linear-gradient(#00205c 0px, #00205c 60px, orange 110px);
}

Or if you want solid colors use repeating-linear-gradient:

html {
}
body:before {
    content:" ";
    display:block;
    position:absolute;
    top:0;
    left:0;
    right:0;
    height:110px;
    background: repeating-linear-gradient(#00205c, #00205c 60px, orange 60px, orange 110px);
}
Comment: this still looks like a gradient. when i tested it, and in the stackoverflow code snippet preview. (running chrome)
Answer: This also works well.
                 /* Css code */

   body
    {
        margin:0px;
    }
   #blue
    {
        width:1366px;
        height:100px;
        background-color:blue;
    }
   #orange
    {
        width:1366px;
        height:50px;
        background-color:orange;
        margin-top:-100px;
    }


Prove that limit of vector valued function is equal to vector of limits of its component

Question: Let $A \subseteq \mathbb R$ be a subset, $f : A \rightarrow \mathbb R^m$ a function and $a \in \mathbb R$ a limit point of $A$. Prove that
$$\lim_{x \rightarrow a} f(x) = b \iff \lim_{x \rightarrow a} f_i(x) = b_i \qquad i = 1,2,\ldots,m$$
I saw that this statement is used at many places but I could not find the proof for it. Can someone help me with the proof ?
Answer: Suppose $\lim_{x\to a}f(x)=b$.
Then, given $\epsilon\gt 0$, we know there exists $\delta\gt 0$ such that $|x-a|\lt\delta\implies|f(x)-b|\lt\epsilon$
But $|f(x)-b|=\sqrt{\sum_{i=i}^{n}(f_i(x)-b_i)^2}$
Therefore, for any $i\in\{1,2,...,n\}$
$|f_i(x)-b_i|=\sqrt{(f_i(x)-b_i)^2}\le\sqrt{\sum_{i=i}^{n}(f_i(x)-b_i)^2}\lt\epsilon$
$\therefore\lim_{x\to}f_i(x)=b_i$
Conversely, suppose $\lim_{x\to a}f_i(x)=b_i$ for $i\in\{1,2,...,n\}$
For $\epsilon\gt 0$ and each $i$ choose $\delta_i$ such that $|x-a|\lt\delta_i\implies |f_i(x)-b_i|\lt\frac{\epsilon}{n}$
Let $\delta$ be the minimum of the $\delta_i$s.
Then if $|x-a|\lt\delta$ $$|f(x)-b|=\sqrt{\sum_{i=1}^{n}(f_i(x)-b_i)^2}\le\sum_{i=1}^{n}\sqrt{(f_i(x)-b_i)^2}=\sum_{i=1}^{n}|f_i(x)-b_i|\lt\sum_{i=1}^{n}\frac{\epsilon}{n}=\epsilon$$
$\therefore\lim_{x\to a}f(x)=b$


Contar repetições de TAG em arquivo XML

Question: Exemplo do arquivo XML:
<rec>
<v001>001</v001>
<v002>2012609272311</v002>
<v003>616.890231</v003>
<v005>7</v005>
<v006>m</v006>
<v007>^a115001^b1^c1^d20100000^e2^fOvernight^m1</v007>
<v007>^a115002^b2^c1^d20100000^e1^m2</v007>
<v007>^a115003^b3^c1^d20100000^e1^m3</v007>
<v007>^a115004^b4^c1^d20100000^e1^m4</v007>
<v007>^a115005^b5^c1^d20100000^e1^m5</v007>
<v007>^a115006^b6^c1^d20100000^e1^m6</v007>
<v016>ROCHA, Ruth Mylius</v016>
<v018>Enfermagem em Saúde Mental</v018>
</rec>

As tags "rec" correspondem há um novo registro e eu preciso contabilizar quantas vezes a tag v007 se repete dentro de cada rec.Estou usando a seguinte função:
static private int getCount(Node parentNode, String childName) {
    int qtdEx = 0;
    NodeList nList = parentNode.getChildNodes();
    for (int i = 0; i < nList.getLength(); i++) {
        Node n = nList.item(i);
        String name = n.getNodeName();
        if (name != null && name.equals(childName)) {
            return qtdEx++;
        }
    }
    return 0;

}

Essa função só me retorna 0, testo da seguinte forma:
 NodeList nList = doc.getElementsByTagName("rec");

 for (int i = 0; i < nList.getLength(); i++) {
            Node node = nList.item(i);
            List<Object> columns = null;
            columns = Arrays.asList(getCount(node, "v007"));
            }

Se alguém puder ajudar, agradeço.
Answer: Encontrei a solução utilizando a seguinte função:
private static int getCount(Node parentNode) {
    int qtdEx = 0;
    NodeList nList = parentNode.getChildNodes();
    for (int i = 0; i < nList.getLength(); i++) {
        Node n = nList.item(i);
        String name = n.getNodeName();
        if ("v007".equals(name)) {
            qtdEx++;
        }
    }
    return qtdEx++;

}

Contar repetições de TAG em arquivo XML


Impedir entrada duplicada em uma lista usando AngularJS

Question: HTML:

Lista de compras

                          Comprado?
                          Produto
                          Quantidade

                          <input type="checkbox" ng-model="item.comprado">
                          {{ item.produto }}
                          {{ item.quantidade }}

                <form class="form-inline" name="formItem">
                  <input type="text" ng-model="item.produto" placeholder="Produto">
                  <input type="number" ng-model="item.quantidade" placeholder="Quantidade" class="input-small">
                  <button class="btn btn-primary" ng-click="adicionaItem()">adicionar ítem</button>
                </form>

Controller:
function ListaComprasController($scope) {
    $scope.itens = [
        {produto: 'Leite', quantidade: 2, comprado: false},
        {produto: 'Cerveja', quantidade: 12, comprado: false}
    ];

    $scope.adicionaItem = function () {
        $scope.itens.push({produto: $scope.item.produto,
                           quantidade: $scope.item.quantidade,
                           comprado: false});
        $scope.item.produto = $scope.item.quantidade = '';

    };
}

Gostaria de evitar entrada de itens duplicados na lista.
Tentei utilizar indexoff e foreach sem sucesso.
Answer: Olá, segue seu código adaptado!
veja o método
$scope.verificaProdutoExistente = function(value) {
    for(var i = 0; i < $scope.itens.length; i++) {
        if($scope.itens[i].hasOwnProperty("produto") && $scope.itens[i]["produto"] === value) {
            return i;
        }
    }
    return -1;
}

e a sua utilização logo abaixo, OBS no StackOverflow o alert não irá funcionar.

angular.module('app',[]).controller('ListaComprasController', function($scope) {

    $scope.itens = [
         {produto: 'Leite', quantidade: 2, comprado: false},
         {produto: 'Cerveja', quantidade: 12, comprado: false}
        ];

    $scope.adicionaItem = function () {
        //Verifica se o produto ja existe
        if ( $scope.verificaProdutoExistente($scope.item.produto) === -1 ){

            $scope.itens.push({produto: $scope.item.produto,
                            quantidade: $scope.item.quantidade,
                            comprado: false});
            $scope.item.produto = $scope.item.quantidade = '';

        } else {
            //Logica caso o produdo ja exista na lista
            alert("Produto ja existe.")
        }
    };

    $scope.verificaProdutoExistente = function(value) {
        for(var i = 0; i < $scope.itens.length; i++) {
            if($scope.itens[i].hasOwnProperty("produto") && $scope.itens[i]["produto"] === value) {
                return i;
            }
        }
        return -1;
    }

});

Lista de compras

                  Comprado?
                  Produto
                  Quantidade

                  <input type="checkbox" ng-model="item.comprado">
                  {{ item.produto }}
                  {{ item.quantidade }}

        <form class="form-inline" name="formItem">
          <input type="text" ng-model="item.produto" placeholder="Produto">
          <input type="number" ng-model="item.quantidade" placeholder="Quantidade" class="input-small">
          <button class="btn btn-primary" ng-click="adicionaItem()">adicionar ítem</button>
        </form>

Comment: Perfeito, muito obrigado!


Run old 32-bit program on Windows 2008 R2 64bit

Question: I am setting Windows Server 2008 R2 as an Application Server (RDP, SeamlessRDP).
I was going to first install that app on the server and then provisioning it to the clients.
The problem is that it's 32 bit app and when I'm trying to install it I'm getting:

The version of this file is not compatible with the version of Windows
  you're running. Check your computer's system information to see
  whether  you need an x86 (32-bit) or x64 (64-bit) version of the
  program, and then  contact the software publisher.

I tried to set compatibility mode with XP SP2 and SP3, tried Windows 2000.
Btw, It works perfect on XP SP2, SP3.
The installer is InstallShield. The Windows built in compatibility wizard is didn't work.
I played with other settings like "Run as Admin.." and work in 640x480 mode - no results.
Other apps (also 32bit) are working fine
Answer: The only time I've seen this is when there's a 16-bit application pretending to be a 32-bit (some really old helpdesk software or some PBX telephony tools). Windows 64-bit has no 16-bit support.
It could even be a 32-bit application that is just using a 16-bit installshield program. If that's the case, it should be simple enough to extract the application out of the installshield wrapper and set it up manually.
More details can be found here.
Comment: thanks, trying to install on another machine and copy it to R2 and run it from R2.
Comment: The latter case is especially common; quite a lot of old 32 bit software came with 16-bit installer routines.
Answer: This has nothing to do with 32 to 64 bit . it has to do with the softwar enot being compatible, and being blacklisted as such, mostly because it was written by people which "got it working" instead of reading the documentation on how it should work.
Get an update from the publisher.
Comment: Unfortunately this is not an option.


getting dimension of a 2d array in node js

Question: I'm working on a discord bot in node js and i need to get the length of the 2 dimentions of a 2d array.
My array is structurated like this, that algo get expanded at the bottom when needed:
var users = [["","","","",""]];

now i need to know how to get the dimentions.
i was originaly doing like this, but it didn't work .
// for the y length
users.length

// for the x length
users[i].length

hope you can help
thanks in advance
Enrico
Comment: What about your approach did not work? The code you're showing seems fine, it should work. Please create a [Minimal, Reproducible Example](https://stackoverflow.com/help/reprex).
Comment: https://stackoverflow.com/questions/10237615/get-size-of-dimensions-in-array
Answer: Actually you almost are correct:
var users = [[1,2],[3,4]]
users.length // y
users[0].length // x

Just keeps in mind that index for each X demantion statred since zero , and might be different  for each row.
Answer: Assuming that none of the elements in the array varies its length from the first one you could just get the length of the first element with
var dimensions = [users.length, users[0].length]
// returns [1, 5]

In a more practical world, probably is better for you to get the dimensions on each of the elements on the array users and decide on whether to use the biggest or the smallest, naturally I'll chose the biggest.
var users = [["", "", ""], ["", ""], ["", "", "", ""]];
var elementsLength = users.map((user) => (user.length));
var lengthY = Math.max(...elementsLength);
var lengthX = users.length;
var dimensions = [lengthX, lengthY];
// returns [3, 4]

It all depends on what you want.
Answer: Your array var users = [["","","","",""]]; is a 2d array where only the 0th index is occupied.  In your case, users[i].length would probably throw a length not defined error of some sort at index 1 and beyond.  You should used users[0].length to get the length of the 2d element


FIRST activity fullscreen android

Question: I want to make my first activity fullscreen, not all activities, how can I do?
Answer: call below method, before calling setcontentView(--) in oncreate method of ur Actiity which you want in full screen.
public void setFullScreen() {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
}

Answer: In Manifest file, Add android:theme="@android:style/Theme.NoTitleBar.Fullscreen" attribute only for the activity which you want to display as a full-screen.
For example :
<activity android:name=".FirstActivity"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
</activity>

Answer: Add:
requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                                    WindowManager.LayoutParams.FLAG_FULLSCREEN);

To the onCreate() of the Activity you want in full screen mode.
Comment: :(     this is for make all the activities fullscreen
Comment: Try using only the first one
Comment: hhhhhh, are you try this or only you copy and paste this codes ?
Comment: I've used it in 23 published apps on the play store. I assure you it works. If other activities are becoming full screen, make sure you haven't set their theme in the manifest to full screen.
Comment: please see this picture for understand my problem http://i47.tinypic.com/2607v4l.png
Comment: Only the first one is fullscreen. I don't see how that is not what you want
Comment: @JeffBic I don't even know what the problem is. In the image you posted, your first Activity is full screen, and the second one isn't. Just as you requested.
Answer: In onCreate method of activity that you want to be fullscreen you can use the following code.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

write this code after setContentView

FIRST activity fullscreen android


How to pass a reference to an object to another class

Question: I'm trying to pass a reference to an object from my main.cpp to menux.cpp however I'm getting this error:
error: conflicting declaration 'MenuX alpha4'
MenuX(alpha4);
main.cpp
#include "MenuX.h"
Adafruit_AlphaNum4 alpha4 = Adafruit_AlphaNum4();
MenuX(alpha4);

MenuX.h
#ifndef MENUX_H
#define MENUX_H

#include "Adafruit_LEDBackpack.h"
#include <Adafruit_GFX.h> // Core graphics library

class MenuX
{
public:
    MenuX(Adafruit_AlphaNum4 *alpha4);
    void addX();

private:
    Adafruit_AlphaNum4 *xLed;
};

#endif

MenuX.cpp
#include "MenuX.h"

MenuX::MenuX(Adafruit_AlphaNum4 *alpha4) {
    xLed = alpha4;
}
void MenuX::addX()
{
    xLed->writeDigitAscii(0, 'X');
    xLed->writeDigitAscii(1, 'X');
    xLed->writeDigitAscii(2, 'X');
    xLed->writeDigitAscii(3, 'X');
    xLed->writeDisplay();
}

Comment: Your constructor takes a pointer but in main.cpp alpha4 isn't a pointer
Comment: when i try this still still doesnt work:

Adafruit_AlphaNum4 *alpha4 = &Adafruit_AlphaNum4();
MenuX(*alpha4);
Comment: Just pass in the address
Adafruit_AlphaNum4 alpha4 = Adafruit_AlphaNum4();
MenuX(&alpha4);
Answer:
You don't have your main code inside of a main function
You can create the alpha4 in main without creating and assigning a temporary
The MenuX constructor takes a pointer so you need to pass &alpha4
Not an error but probably a mistake, you don't use the MenuX you've created

#include "MenuX.h"

int main() {
    Adafruit_AlphaNum4 alpha4;
    MenuX menu(&alpha4);  // added & and object name
}


mod_rewrite, mod_alias, subdomain changes how domain serves website?

Question: I've made a django site for a magazine, and it's found in mag.org/django-site. the old site is still at mag.org/httpdocs (hosted by mediatemple).
I would like it so that a hit to www.mag.org turns up the django site (as is currently the case, configured so in the conf file) while a hit to archive.mag.org serves the old site from httpdocs, that is, it's served by apache and not mod_python.
Is this possible to do through mod-rewrite, or mod-alias?

hosted by mediatemple dv. httpd.conf is rewritten by plesk; httpd.conf access is limited to a single vhost.conf for each domain/subdomain.
a simple [DocumentRoot /var/www/vhosts/mag.org/httpdocs] in the [/mag.org/subdomains/archive/conf/vhost.conf] was all I needed.
now mag.org points to the django site being served by mod-python, while archive.mag.org points to the httpdocs folder, served by apache.

(I initially posted this at stack-overflow, but I think it's more suited for serverfault.)
Answer: You can do the following in your vhost.conf file:
ServerAdmin email@example.com
ServerName  a server name
ServerAlias a server alias
DocumentRoot /path-to-django-web/root
<Directory  /path-to-django-web/root >
    Options FollowSymLinks Indexes
    DirectoryIndex index.php index.html
    AllowOverride All
    Order allow,deny
    Allow from all

       <IfModule mod_rewrite.c>
               RewriteEngine On
               RewriteBase /

               #Do your rewrite magic here
       </IfModule>
       <IfModule !mod_rewrite.c>
               ErrorDocument 404 /index.php
       </IfModule>
</Directory>

That is the way MT DV's vhost loads custom vhost configuration, it does not need the VirtualHost tags since they are already loaded by the default VH configuration.
Remember to restart your server and to reconfigure your domain, check what are the options available on your server manager, in the terminal type the following:
$ /usr/local/psa/admin/sbin/websrvmng --help

Usually you will have to reconfigure vhost
After that restart apache
$ /etc/init.d/httpd graceful

That should do it.
Answer: Best way to do this is with two virtual hosts, one for www.mag.org, and one for archive.mag.org
<VirtualHost *:80>
    ServerName www.mag.org
    DocumentRoot /path/to/django-site
</VirtualHost>

<VirtualHost *:80>
    ServerName archive.mag.org
    DocumentRoot /path/to/httpdocs
</VirtualHost>

This answer on virtualhosts and aliases may be helpful to you.

Edit: It is possible to do this with mod_rewrite, if you really need to. If you have mod_proxy you can also proxy the re-write so that the address doesn't change in the user address bar.
DocumentRoot  /path/to/django-site
Alias         /archive/                    "/path/to/httpdocs/"
RewriteRule   ^archive\.mag\.org(.*)$      http://www.mag.org/archive$1 [NC,P,L]

Comment: thanks for the quick reply, but I don't think this will work at mediatemple.  I'm using their dv container, and all domains contain their own vhost directory and vhost.conf file.  I'll try it, though.


Describe how to find a basis $\beta$ for $R^n$ and a basis $C$ for $R^m$

Question: Let $T : R^n → R^m$ be a linear transformation. Describe how to find a basis
$\beta$
for $R^n$ and a basis $C$ for $R^m$ such that matrix for $T$ relative to $\beta$ and $C$ is an
diagonal matrix $P$ of size $m × n$.
Comment: In standard terminology a diagonal matrix has to be square; I have no idea what a "diagonal" $m\times n$ matrix might be.
Answer: This is the well known canonical form of a matrix.
Take $\{\beta_{k+1}, \dots, \beta_n\}$ (where $0\le k \le n$) as a basis of the kernel of $T$. Then according to the rank-nullity theorem, the dimension of the image of $T$ is $k$. Take $\{\beta_1, \dots, \beta_{k}\}$ such that $$\{C_1=T(\beta_1), \dots, C_{k} = T(\beta_{k})\}$$ is a basis of the image of $T$. Complete $\{C_1, \dots , C_{k}\}$ into a basis $\{C_1, \dots C_m\}$ of $\mathbb R^m$.
The two basis are the one you're looking for.


Way to reference objects in Raphael JS?

Question: I am trying to draw shapes based off of where on the screen existing shapes are, so that I only have to change the coordinates of one shape for all the others to shift appropriately. Is there some way to reference a rectangle's x coordinate when constructing another?
For example, the following code does not work as I thought it would:
var paper = Raphael(0, 0, 1000,600);

    var rectangleOne = paper.rect(100, 100, 100, 50);

    var rectangleTwo = paper.rect(rectangleOne.x, rectangleOne.y + 40, rectangleOne.width + 50, rectangleOne.height);

I get some error that "rectangleOne.x" is undefined and defaults to zero...Any ideas how to fix this? Thanks all!
Comment: can you try to grab the `x` attribute using the raphaeljs `attr` function? i.e. `rectangleOne.attr('x')` and `rectangleOne.attr('y')`. See http://raphaeljs.com/reference.html#Element.attr
Comment: Ah you beat me to it!
Answer: var rectangleTwo = paper.rect(rectangleOne.attr('x'), rectangleOne.attr('y') + 40, rectangleOne.attr('width') + 50, rectangleOne.attr('height'));

Way to reference objects in Raphael JS?


Why does my QStyleItemDelegate pop up in a new window instead of in my TableView?

Question: I'm trying to create a pretty simple app with Pyside2 that displays some data in a table that the user can edit. I want the cells of the table to autocomplete based on other values in the table, so I implemented a custom delegate following this tutorial. It was pretty straightforward and the delegate works as expected except for some reason the delegate pops up in a new window instead of being attached to the cell in the table, illustrated by this example (the custom delegate is defined at the end):
import pandas as pd
from PySide2 import QtWidgets, QtCore
from PySide2.QtCore import Qt

class TableView(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.setObjectName(u"TableView")
        self.centralwidget = QtWidgets.QWidget(self)
        self.centralwidget.setObjectName(u"centralwidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName(u"verticalLayout")
        self.frame = QtWidgets.QFrame(self.centralwidget)
        self.frame.setObjectName(u"frame")
        self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.frame)
        self.verticalLayout_2.setObjectName(u"verticalLayout_2")

        self.tableView = QtWidgets.QTableView(self.frame)
        self.tableView.setObjectName(u"tableView")
        delegate = QAutoCompleteDelegate(self.tableView)
        self.tableView.setItemDelegate(delegate)
        self.tableModel = TableModel(self.tableView)
        self.tableView.setModel(self.tableModel)

        self.verticalLayout_2.addWidget(self.tableView)
        self.verticalLayout.addWidget(self.frame)

        self.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(self)
        self.statusbar.setObjectName(u"statusbar")
        self.setStatusBar(self.statusbar)

        QtCore.QMetaObject.connectSlotsByName(self)

class TableModel(QtCore.QAbstractTableModel):

    def __init__(self, parent=None):
        super(TableModel, self).__init__(parent=parent)
        self._data = pd.DataFrame([["A0", "B0", "C0"], ["A1", "B1", "C1"], ["A2", "B2", "C2"]], columns=["A", "B", "C"])

    def data(self, index, role):
        # Should only ever refer to the data by iloc in this method, unless you
        # go specifically fetch the correct loc based on the iloc
        row = index.row()
        col = index.column()
        if role == Qt.DisplayRole or role == Qt.EditRole:
            return self._data.iloc[row, col]

    def rowCount(self, index):
        return len(self._data)

    def columnCount(self, index):
        return len(self._data.columns)

    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self._data.columns[col]
        return None

    def unique_vals(self, index):
        """ Identify the values to include in an autocompletion delegate for the given index """
        column = index.column()
        col_name = self._data.columns[column]
        return list(self._data[col_name].unique())

    def setData(self, index, value, role):
        if role != Qt.EditRole:
            return False
        row = self._data.index[index.row()]
        column = self._data.columns[index.column()]
        self._data.loc[row, column] = value
        self.dataChanged.emit(index, index)
        return True

    def flags(self, index):
        flags = super(self.__class__, self).flags(index)
        flags |= Qt.ItemIsEditable
        flags |= Qt.ItemIsSelectable
        flags |= Qt.ItemIsEnabled
        flags |= Qt.ItemIsDragEnabled
        flags |= Qt.ItemIsDropEnabled
        return flags

class QAutoCompleteDelegate(QtWidgets.QStyledItemDelegate):

    def createEditor(self, parent: QtWidgets.QWidget, option: QtWidgets.QStyleOptionViewItem, index: QtCore.QModelIndex) -> QtWidgets.QWidget:
        le = QtWidgets.QLineEdit()
        test = ["option1", "option2", "option3"]
        complete = QtWidgets.QCompleter(test)
        le.setCompleter(complete)
        return le

    def setEditorData(self, editor:QtWidgets.QLineEdit, index:QtCore.QModelIndex):
        val = index.model().data(index, Qt.EditRole)
        options = index.model().unique_vals(index)
        editor.setText(val)
        completer = QtWidgets.QCompleter(options)
        editor.setCompleter(completer)

    def updateEditorGeometry(self, editor: QtWidgets.QWidget, option: QtWidgets.QStyleOptionViewItem, index: QtCore.QModelIndex):
        editor.setGeometry(option.rect)

app = QtWidgets.QApplication()
tv = TableView()
tv.show()
app.exec_()

Image showing table behavior when a cell is active

From everything I've read, the updateEditorGeometry method on the custom delegate should anchor it to the active cell, but something clearly isn't working as expected in my case. And I am still learning Qt so I can't claim to understand what it is doing. Is there anyone out there who might be able to explain what is going on here? Much appreciated.

OS: Ubuntu 20.04
Python 3.8.5
PySide2 5.15.0
Qt 5.12.9
Answer: Any widget that does not have a parent will be a window and since the QLineEdit has no parent then you observe the behavior that the OP indicates, for that reason the createEditor method has "parent" as an argument.
On the other hand, it is better to create a custom QLineEdit that easily implements the handling of adding suggestions to the QCompleter through a model.
class AutoCompleteLineEdit(QtWidgets.QLineEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._completer_model = QtGui.QStandardItemModel()
        completer = QtWidgets.QCompleter()
        completer.setModel(self._completer_model)
        self.setCompleter(completer)

    @property
    def suggestions(self):
        return [
            self._completer_model.item(i).text()
            for i in range(self._completer_model.rowCount())
        ]

    @suggestions.setter
    def suggestions(self, suggestions):
        self._completer_model.clear()
        for suggestion in suggestions:
            item = QtGui.QStandardItem(suggestion)
            self._completer_model.appendRow(item)

class QAutoCompleteDelegate(QtWidgets.QStyledItemDelegate):
    def createEditor(
        self,
        parent: QtWidgets.QWidget,
        option: QtWidgets.QStyleOptionViewItem,
        index: QtCore.QModelIndex,
    ) -> QtWidgets.QWidget:
        le = AutoCompleteLineEdit(parent)
        return le

    def setEditorData(self, editor: QtWidgets.QWidget, index: QtCore.QModelIndex):
        val = index.model().data(index, Qt.EditRole)
        options = index.model().unique_vals(index)
        editor.setText(val)
        editor.suggestions = options


Why do we assume all controls are exogenous in an instrumental variable analysis?

Question: I have seen two instructions for estimating the first-stage OLS for IV:

Regress the endogenous variable (predictor of interest) on the instrument and controls that will be used in the second-stage
Regress the endogenous variable on the instrument and all exogenous variables that will be used in the second stage

These two rules imply that all controls in the second-stage are assumed to be exogenous. Why? If I have a contorl that is endogenous, do I still include it in the first-stage?
Answer: In 2SLS you divide predictors into exogenous (instruments) $Z$ and endogenous variables $X$: $Y=X\beta_X+Z\beta_Z$. In 1st stage you regress $X= Z\beta_{IV}+u$, then obtain estimators $\hat X=Z\beta_{IV}$. In the second stage you plug these into main equation: $Y=\hat X\beta_X+Z\beta_Z+\varepsilon=Z(\beta_{IV}\beta_X+\beta_Z)+\varepsilon$
Once you solve the equation, your coefficients $\hat\beta_X$ are for the endogenous variable.


For each row return the column names of the smallest value - pandas

Question: Assuming that I have a dataframe with the following values:
id    product1sold   product2sold   product3sold
1     2              3              3
2     0              0              5
3     3              2              1

How do I add a 'most_sold' and 'least_sold' column containing all most and least sold products in a list per id?
It should look like this.
id    product1   product2   product3    most_sold                least_sold
1        2          3          3        [product2, product3]      [product1]
2        0          0          5        [product3]                [product1, product2]
3        3          2          1        [product1]                [product3]

Answer: Use list comprehension with test minimal and maximal values for list of products:
#select all columns without first
df1 = df.iloc[:, 1:]
cols = df1.columns.to_numpy()

df['most_sold'] = [cols[x].tolist() for x in df1.eq(df1.max(axis=1), axis=0).to_numpy()]
df['least_sold'] = [cols[x].tolist() for x in df1.eq(df1.min(axis=1), axis=0).to_numpy()]
print (df)
   id  product1sold  product2sold  product3sold                     most_sold  \
0   1             2             3             3  [product2sold, product3sold]
1   2             0             0             5                [product3sold]
2   3             3             2             1                [product1sold]

                     least_sold
0                [product1sold]
1  [product1sold, product2sold]
2                [product3sold]

If performance is not important is possible use DataFrame.apply:
df1 = df.iloc[:, 1:]

f = lambda x: x.index[x].tolist()
df['most_sold'] = df1.eq(df1.max(axis=1), axis=0).apply(f, axis=1)
df['least_sold'] = df1.eq(df1.min(axis=1), axis=0).apply(f, axis=1)

Answer: You can do something like this.
minValueCol = yourDataFrame.idxmin(axis=1)
maxValueCol =  yourDataFrame.idxmax(axis=1)


Como paginar usando o Flask e retornar em Json?

Question: Preciso fazer uma consulta ao banco (neo4j) e retornar um json, porém como a resposta é muito grande preciso paginar. Já olhei muito aqui no stack, porém a maioria das respostas usam o método de paginação do sqlalchemy ou retornam um render template com o objeto Pagination, e não é isso que eu preciso. Tem alguma forma de retornar isso em json ou de ao menos converter esse Pagination para json?
Answer: Qualquer objeto pode ser convertido para JSON. Existe o método jsonify.
<code>from flask import jsonify

return jsonify(Pagination)
</code>