问:
Decrypting an AES-encrypted message with an RSA-encrypted key with EVP tool
For industrial purposes, I want to decrypt an AES-encrypted message with an RSA-encrypted key in C. At first, I thought doing it step-by-step by first, using OpenSSL libcrypto library, by first RSA decoding the key then AES decoding the data.

I have found out that EVP tools were commonly seen as a better way to do this since it actually does what the low-levels functions do but correctly.
Here is what I see the flow of the program :

Initialize OpenSSL;

Read and store the RSA private key;

Initialize the decryption by specifying the decryption algorithm (AES) and the private key;

Update the decryption by giving the key, the data, the key and their length

Finally decrypt the data and return it.

I have been a lot confused by the fact that so far we do not intend to use any IV or ADD (although IV might come up later in the project). I have followed this guide it is not very clear and does not fit the way I use EVP.

So here is my actual code :

```<code>#include <openssl/evp.h>
#include <openssl/conf.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/aes.h>
#include <openssl/err.h>
#include "openssl\applink.c"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

const char PRIVATE_KEY_PATH[] = "C:/Users/Local_user/privateKey.pem";

EVP_PKEY* initializePrivateKey(void)
{
    FILE* privateKeyfile;
    if ((privateKeyfile = fopen(PRIVATE_KEY_PATH, "r")) == NULL) // Check PEM file opening
    {
        perror("Error while trying to access to private key.\n");
        return NULL;
    }

    RSA *rsaPrivateKey = RSA_new();
    EVP_PKEY *privateKey = EVP_PKEY_new();

    if ((rsaPrivateKey = PEM_read_RSAPrivateKey(privateKeyfile, &rsaPrivateKey, NULL, NULL)) == NULL) // Check PEM file reading
    {
        fprintf(stderr, "Error loading RSA Private Key File.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    if (!EVP_PKEY_assign_RSA(privateKey, rsaPrivateKey))
    {
        fprintf(stderr, "Error when initializing EVP private key.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    return privateKey;
}
const uint8_t* decodeWrappingKey(uint8_t const* data, const size_t data_len, uint8_t const* wrappingKey, const size_t wrappingKey_len)
{
    // Start Decryption
    EVP_CIPHER_CTX *ctx;
    if (!(ctx = EVP_CIPHER_CTX_new())) // Initialize context
    {
        fprintf(stderr, "Error when initializing context.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    EVP_PKEY *privateKey = initializePrivateKey();
    if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, privateKey, NULL)) // Initialize decryption
    {
        fprintf(stderr, "Error when initializing decryption.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    uint8_t* res;
    if ((res = calloc(data_len, sizeof(uint8_t))) == NULL) // Check memory allocating
    {
        perror("Memory allocating error ");
        return NULL;
    }
    puts("Initialization done. Decoding..\n");
    size_t res_len = 0;
    if (1 != EVP_DecryptUpdate(ctx, res, &res_len, data, data_len))
    {
        fprintf(stderr, "Error when preparing decryption.\n");
        ERR_print_errors_fp(stderr);
    }

    if (1 != EVP_DecryptFinal_ex(ctx, res, &res_len))
    {
        fprintf(stderr, "Error when decrypting.\n");
        ERR_print_errors_fp(stderr);
    }
    return res;
}

void hexToBytes(uint8_t *des, char const *source, const size_t size) {

    for (int i = 0; i < size - 1; i += 2)
        sscanf(source + i, "%02x", des + (i / 2));
}

int main(void) {
    char const *strWrap = "5f82c48f85054ef6a3b2621819dd0e969030c79cc00deb89........";
    char const *strData = "ca1518d44716e3a4588af741982f29ad0a3e7a8d67.....";

    uint8_t *wrap = calloc(strlen(strWrap), sizeof(uint8_t));
    hexToBytes(wrap, strWrap, strlen(strWrap)); // Converts string to raw data
    uint8_t *data = calloc(strlen(strData), sizeof(uint8_t));
    hexToBytes(data, strData, strlen(strData));

    /* Load the human readable error strings for libcrypto */
    ERR_load_crypto_strings();

    /* Load all digest and cipher algorithms */
    OpenSSL_add_all_algorithms();

    /* Load config file, and other important initialisation */
    OPENSSL_config(NULL);
    const uint8_t *res = decodeWrappingKey(data, strlen(strData) / 2, wrap, strlen(strWrap) / 2);
    if (res == NULL)
        return 1;
    return 0;
}
</code>```

My output is the following one :

```<code>Initialization done. Decoding..

Error when preparing decryption.
Error when decrypting.
</code>```

Obviously it fails when updating and finalising the decryption but I can't figure out why and the ERR_print_errors_fp(stderr); which had always worked for me so far seems to be mute.

答:
Here is a complete working example of how you can encrypt a key using RSA, and encrypt a message using that key using AES, followed by the subsequent decryption of those things. It assumes AES-256-CBC is being used. If you want to use AES-256-GCM instead then you will need to make some changes to get and set the tag (ask me if you need some pointers on how to do this). It also assumes that the RSA encryption is done with PKCS#1 padding (which is all that the EVP_Seal* APIs support). If you need some other kind of padding then you will need to use a different method. Finally it assumes you are using OpenSSL 1.1.0. If you are using 1.0.2 then some changes will probably be necessary (at least you will need to explicitly init and de-init the library - that isn't required in 1.1.0).

The code reads the RSA private and public keys from files called privkey.pem and pubkey.pem which are in the current working directory. I generated these files like this:

```<code>openssl genrsa -out privkey.pem 2048
openssl rsa -in privkey.pem -pubout -out pubkey.pem
</code>```

I've tested this on Linux only. The code is as follows:

```<code>#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int envelope_seal(EVP_PKEY *pub_key, unsigned char *plaintext,
                         int plaintext_len, unsigned char **encrypted_key,
                         int *encrypted_key_len, unsigned char **iv,
                         int *iv_len,  unsigned char **ciphertext,
                         int *ciphertext_len)
{
    EVP_CIPHER_CTX *ctx;
    int len, ret = 0;
    const EVP_CIPHER *type = EVP_aes_256_cbc();
    unsigned char *tmpiv = NULL, *tmpenc_key = NULL, *tmpctxt = NULL;

    if((ctx = EVP_CIPHER_CTX_new()) == NULL)
        return 0;

    *iv_len = EVP_CIPHER_iv_length(type);
    if ((tmpiv = malloc(*iv_len)) == NULL)
        goto err;

    if ((tmpenc_key = malloc(EVP_PKEY_size(pub_key))) == NULL)
        goto err;

    if ((tmpctxt = malloc(plaintext_len + EVP_CIPHER_block_size(type)))
            == NULL)
        goto err;

    if(EVP_SealInit(ctx, type, &tmpenc_key, encrypted_key_len, tmpiv, &pub_key,
                    1) != 1)
        goto err;

    if(EVP_SealUpdate(ctx, tmpctxt, &len, plaintext, plaintext_len) != 1)
        goto err;
    *ciphertext_len = len;

    if(EVP_SealFinal(ctx, tmpctxt + len, &len) != 1)
        goto err;
    *ciphertext_len += len;

    *iv = tmpiv;
    *encrypted_key = tmpenc_key;
    *ciphertext = tmpctxt;
    tmpiv = NULL;
    tmpenc_key = NULL;
    tmpctxt = NULL;
    ret = 1;
 err:
    EVP_CIPHER_CTX_free(ctx);
    free(tmpiv);
    free(tmpenc_key);
    free(tmpctxt);

    return ret;
}

int envelope_open(EVP_PKEY *priv_key, unsigned char *ciphertext,
                  int ciphertext_len, unsigned char *encrypted_key,
                  int encrypted_key_len, unsigned char *iv,
                  unsigned char **plaintext, int *plaintext_len)
{
    EVP_CIPHER_CTX *ctx;
    int len, ret = 0;
    unsigned char *tmpptxt = NULL;

    if((ctx = EVP_CIPHER_CTX_new()) == NULL)
        return 0;

    if ((tmpptxt = malloc(ciphertext_len)) == NULL)
        goto err;

    if(EVP_OpenInit(ctx, EVP_aes_256_cbc(), encrypted_key, encrypted_key_len,
                    iv, priv_key) != 1)
        return 0;

    if(EVP_OpenUpdate(ctx, tmpptxt, &len, ciphertext, ciphertext_len) != 1)
        return 0;
    *plaintext_len = len;

    if(EVP_OpenFinal(ctx, tmpptxt + len, &len) != 1)
        return 0;
    *plaintext_len += len;

    *plaintext = tmpptxt;
    tmpptxt = NULL;
    ret = 1;
 err:
    EVP_CIPHER_CTX_free(ctx);
    free(tmpptxt);

    return ret;
}

int main(void)
{
    EVP_PKEY *pubkey = NULL, *privkey = NULL;
    FILE *pubkeyfile, *privkeyfile;
    int ret = 1;
    unsigned char *iv = NULL, *message = "Hello World!\n";
    unsigned char *enc_key = NULL, *ciphertext = NULL, *plaintext = NULL;
    int iv_len = 0, enc_key_len = 0, ciphertext_len = 0, plaintext_len = 0, i;

    if ((pubkeyfile = fopen("pubkey.pem", "r")) == NULL) {
        printf("Failed to open public key for reading\n");
        goto err;
    }
    if ((pubkey = PEM_read_PUBKEY(pubkeyfile, &pubkey, NULL, NULL)) == NULL) {
        fclose(pubkeyfile);
        goto err;
    }
    fclose(pubkeyfile);

    if ((privkeyfile = fopen("privkey.pem", "r")) == NULL) {
        printf("Failed to open private key for reading\n");
        goto err;
    }
    if ((privkey = PEM_read_PrivateKey(privkeyfile, &privkey, NULL, NULL))
            == NULL) {
        fclose(privkeyfile);
        goto err;
    }
    fclose(privkeyfile);

    if (!envelope_seal(pubkey, message, strlen(message), &enc_key, &enc_key_len,
                       &iv, &iv_len, &ciphertext, &ciphertext_len))
        goto err;

    printf("Ciphertext:\n");
    for (i = 0; i < ciphertext_len; i++)
        printf("%02x", ciphertext[i]);
    printf("\n");

    printf("Encrypted Key:\n");
    for (i = 0; i < enc_key_len; i++)
        printf("%02x", enc_key[i]);
    printf("\n");

    printf("IV:\n");
    for (i = 0; i < iv_len; i++)
        printf("%02x", iv[i]);
    printf("\n");

    if (!envelope_open(privkey, ciphertext, ciphertext_len, enc_key,
                       enc_key_len, iv, &plaintext, &plaintext_len))
        goto err;

    plaintext[plaintext_len] = '\0';
    printf("Plaintext: %s\n", plaintext);

    ret = 0;
 err:
    if (ret != 0) {
        printf("Error\n");
        ERR_print_errors_fp(stdout);
    }
    EVP_PKEY_free(pubkey);
    EVP_PKEY_free(privkey);
    free(iv);
    free(enc_key);
    free(ciphertext);
    free(plaintext);

    return ret;
}
</code>```

Body:
For industrial purposes, I want to decrypt an AES-encrypted message with an RSA-encrypted key in C. At first, I thought doing it step-by-step by first, using OpenSSL libcrypto library, by first RSA decoding the key then AES decoding the data.

I have found out that EVP tools were commonly seen as a better way to do this since it actually does what the low-levels functions do but correctly.
Here is what I see the flow of the program :

Initialize OpenSSL;

Read and store the RSA private key;

Initialize the decryption by specifying the decryption algorithm (AES) and the private key;

Update the decryption by giving the key, the data, the key and their length

Finally decrypt the data and return it.

I have been a lot confused by the fact that so far we do not intend to use any IV or ADD (although IV might come up later in the project). I have followed this guide it is not very clear and does not fit the way I use EVP.

So here is my actual code :

#include <openssl/evp.h>
#include <openssl/conf.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/aes.h>
#include <openssl/err.h>
#include "openssl\applink.c"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

const char PRIVATE_KEY_PATH[] = "C:/Users/Local_user/privateKey.pem";

EVP_PKEY* initializePrivateKey(void)
{
    FILE* privateKeyfile;
    if ((privateKeyfile = fopen(PRIVATE_KEY_PATH, "r")) == NULL) // Check PEM file opening
    {
        perror("Error while trying to access to private key.\n");
        return NULL;
    }

    RSA *rsaPrivateKey = RSA_new();
    EVP_PKEY *privateKey = EVP_PKEY_new();

    if ((rsaPrivateKey = PEM_read_RSAPrivateKey(privateKeyfile, &rsaPrivateKey, NULL, NULL)) == NULL) // Check PEM file reading
    {
        fprintf(stderr, "Error loading RSA Private Key File.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    if (!EVP_PKEY_assign_RSA(privateKey, rsaPrivateKey))
    {
        fprintf(stderr, "Error when initializing EVP private key.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    return privateKey;
}
const uint8_t* decodeWrappingKey(uint8_t const* data, const size_t data_len, uint8_t const* wrappingKey, const size_t wrappingKey_len)
{
    // Start Decryption
    EVP_CIPHER_CTX *ctx;
    if (!(ctx = EVP_CIPHER_CTX_new())) // Initialize context
    {
        fprintf(stderr, "Error when initializing context.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    EVP_PKEY *privateKey = initializePrivateKey();
    if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, privateKey, NULL)) // Initialize decryption
    {
        fprintf(stderr, "Error when initializing decryption.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    uint8_t* res;
    if ((res = calloc(data_len, sizeof(uint8_t))) == NULL) // Check memory allocating
    {
        perror("Memory allocating error ");
        return NULL;
    }
    puts("Initialization done. Decoding..\n");
    size_t res_len = 0;
    if (1 != EVP_DecryptUpdate(ctx, res, &res_len, data, data_len))
    {
        fprintf(stderr, "Error when preparing decryption.\n");
        ERR_print_errors_fp(stderr);
    }

    if (1 != EVP_DecryptFinal_ex(ctx, res, &res_len))
    {
        fprintf(stderr, "Error when decrypting.\n");
        ERR_print_errors_fp(stderr);
    }
    return res;
}

void hexToBytes(uint8_t *des, char const *source, const size_t size) {

    for (int i = 0; i < size - 1; i += 2)
        sscanf(source + i, "%02x", des + (i / 2));
}

int main(void) {
    char const *strWrap = "5f82c48f85054ef6a3b2621819dd0e969030c79cc00deb89........";
    char const *strData = "ca1518d44716e3a4588af741982f29ad0a3e7a8d67.....";

    uint8_t *wrap = calloc(strlen(strWrap), sizeof(uint8_t));
    hexToBytes(wrap, strWrap, strlen(strWrap)); // Converts string to raw data
    uint8_t *data = calloc(strlen(strData), sizeof(uint8_t));
    hexToBytes(data, strData, strlen(strData));

    /* Load the human readable error strings for libcrypto */
    ERR_load_crypto_strings();

    /* Load all digest and cipher algorithms */
    OpenSSL_add_all_algorithms();

    /* Load config file, and other important initialisation */
    OPENSSL_config(NULL);
    const uint8_t *res = decodeWrappingKey(data, strlen(strData) / 2, wrap, strlen(strWrap) / 2);
    if (res == NULL)
        return 1;
    return 0;
}

My output is the following one :

Initialization done. Decoding..

Error when preparing decryption.
Error when decrypting.

Obviously it fails when updating and finalising the decryption but I can't figure out why and the ERR_print_errors_fp(stderr); which had always worked for me so far seems to be mute.

Body:
Here is a complete working example of how you can encrypt a key using RSA, and encrypt a message using that key using AES, followed by the subsequent decryption of those things. It assumes AES-256-CBC is being used. If you want to use AES-256-GCM instead then you will need to make some changes to get and set the tag (ask me if you need some pointers on how to do this). It also assumes that the RSA encryption is done with PKCS#1 padding (which is all that the EVP_Seal* APIs support). If you need some other kind of padding then you will need to use a different method. Finally it assumes you are using OpenSSL 1.1.0. If you are using 1.0.2 then some changes will probably be necessary (at least you will need to explicitly init and de-init the library - that isn't required in 1.1.0).

The code reads the RSA private and public keys from files called privkey.pem and pubkey.pem which are in the current working directory. I generated these files like this:

openssl genrsa -out privkey.pem 2048
openssl rsa -in privkey.pem -pubout -out pubkey.pem

I've tested this on Linux only. The code is as follows:

#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int envelope_seal(EVP_PKEY *pub_key, unsigned char *plaintext,
                         int plaintext_len, unsigned char **encrypted_key,
                         int *encrypted_key_len, unsigned char **iv,
                         int *iv_len,  unsigned char **ciphertext,
                         int *ciphertext_len)
{
    EVP_CIPHER_CTX *ctx;
    int len, ret = 0;
    const EVP_CIPHER *type = EVP_aes_256_cbc();
    unsigned char *tmpiv = NULL, *tmpenc_key = NULL, *tmpctxt = NULL;

    if((ctx = EVP_CIPHER_CTX_new()) == NULL)
        return 0;

    *iv_len = EVP_CIPHER_iv_length(type);
    if ((tmpiv = malloc(*iv_len)) == NULL)
        goto err;

    if ((tmpenc_key = malloc(EVP_PKEY_size(pub_key))) == NULL)
        goto err;

    if ((tmpctxt = malloc(plaintext_len + EVP_CIPHER_block_size(type)))
            == NULL)
        goto err;

    if(EVP_SealInit(ctx, type, &tmpenc_key, encrypted_key_len, tmpiv, &pub_key,
                    1) != 1)
        goto err;

    if(EVP_SealUpdate(ctx, tmpctxt, &len, plaintext, plaintext_len) != 1)
        goto err;
    *ciphertext_len = len;

    if(EVP_SealFinal(ctx, tmpctxt + len, &len) != 1)
        goto err;
    *ciphertext_len += len;

    *iv = tmpiv;
    *encrypted_key = tmpenc_key;
    *ciphertext = tmpctxt;
    tmpiv = NULL;
    tmpenc_key = NULL;
    tmpctxt = NULL;
    ret = 1;
 err:
    EVP_CIPHER_CTX_free(ctx);
    free(tmpiv);
    free(tmpenc_key);
    free(tmpctxt);

    return ret;
}

int envelope_open(EVP_PKEY *priv_key, unsigned char *ciphertext,
                  int ciphertext_len, unsigned char *encrypted_key,
                  int encrypted_key_len, unsigned char *iv,
                  unsigned char **plaintext, int *plaintext_len)
{
    EVP_CIPHER_CTX *ctx;
    int len, ret = 0;
    unsigned char *tmpptxt = NULL;

    if((ctx = EVP_CIPHER_CTX_new()) == NULL)
        return 0;

    if ((tmpptxt = malloc(ciphertext_len)) == NULL)
        goto err;

    if(EVP_OpenInit(ctx, EVP_aes_256_cbc(), encrypted_key, encrypted_key_len,
                    iv, priv_key) != 1)
        return 0;

    if(EVP_OpenUpdate(ctx, tmpptxt, &len, ciphertext, ciphertext_len) != 1)
        return 0;
    *plaintext_len = len;

    if(EVP_OpenFinal(ctx, tmpptxt + len, &len) != 1)
        return 0;
    *plaintext_len += len;

    *plaintext = tmpptxt;
    tmpptxt = NULL;
    ret = 1;
 err:
    EVP_CIPHER_CTX_free(ctx);
    free(tmpptxt);

    return ret;
}

int main(void)
{
    EVP_PKEY *pubkey = NULL, *privkey = NULL;
    FILE *pubkeyfile, *privkeyfile;
    int ret = 1;
    unsigned char *iv = NULL, *message = "Hello World!\n";
    unsigned char *enc_key = NULL, *ciphertext = NULL, *plaintext = NULL;
    int iv_len = 0, enc_key_len = 0, ciphertext_len = 0, plaintext_len = 0, i;

    if ((pubkeyfile = fopen("pubkey.pem", "r")) == NULL) {
        printf("Failed to open public key for reading\n");
        goto err;
    }
    if ((pubkey = PEM_read_PUBKEY(pubkeyfile, &pubkey, NULL, NULL)) == NULL) {
        fclose(pubkeyfile);
        goto err;
    }
    fclose(pubkeyfile);

    if ((privkeyfile = fopen("privkey.pem", "r")) == NULL) {
        printf("Failed to open private key for reading\n");
        goto err;
    }
    if ((privkey = PEM_read_PrivateKey(privkeyfile, &privkey, NULL, NULL))
            == NULL) {
        fclose(privkeyfile);
        goto err;
    }
    fclose(privkeyfile);

    if (!envelope_seal(pubkey, message, strlen(message), &enc_key, &enc_key_len,
                       &iv, &iv_len, &ciphertext, &ciphertext_len))
        goto err;

    printf("Ciphertext:\n");
    for (i = 0; i < ciphertext_len; i++)
        printf("%02x", ciphertext[i]);
    printf("\n");

    printf("Encrypted Key:\n");
    for (i = 0; i < enc_key_len; i++)
        printf("%02x", enc_key[i]);
    printf("\n");

    printf("IV:\n");
    for (i = 0; i < iv_len; i++)
        printf("%02x", iv[i]);
    printf("\n");

    if (!envelope_open(privkey, ciphertext, ciphertext_len, enc_key,
                       enc_key_len, iv, &plaintext, &plaintext_len))
        goto err;

    plaintext[plaintext_len] = '\0';
    printf("Plaintext: %s\n", plaintext);

    ret = 0;
 err:
    if (ret != 0) {
        printf("Error\n");
        ERR_print_errors_fp(stdout);
    }
    EVP_PKEY_free(pubkey);
    EVP_PKEY_free(privkey);
    free(iv);
    free(enc_key);
    free(ciphertext);
    free(plaintext);

    return ret;
}


来源: stackexchange

问:
codeigniter, set_flashdata('abc', 'hi);
I am using codeigniter on my project.

when page refresh,

in controller page,

```<code>$this->session->set_flashdata('abc', 'hi);
</code>```

in view page,
echo

```<code>$this->session->flashdata('abc');
</code>```

works fine.

but, when ajax call, not page refresh,
controller,

```<code> $this->session->set_flashdata('abc', 'hi);
</code>```

view,

```<code>echo $this->session->flashdata('abc');
</code>```

doesn't work.....

echoing nothing~ -_-;
ajax doesn't have mechanism to catch session flash data?

any idea?

答:
Your Ajax call will only ouput whatever the Controller/Method prints to the output buffer. So if you add

```<code>echo $this->session->flashdata('abc');
</code>```

to your controller that gets called by the Ajax method, it will return the echo to the Ajax method which u can then display on the page. The echo statement in the view will only get executed when your page is refreshed, since PHP has to compile that echo statement on the server at run time and then return the result to your browser.

ContentLicense: CC BY-SA 2.5

Title: codeigniter, set_flashdata('abc', 'hi);

Body:
I am using codeigniter on my project.

when page refresh,

in controller page,

$this->session->set_flashdata('abc', 'hi);

in view page,
echo

$this->session->flashdata('abc');

works fine.

but, when ajax call, not page refresh,
controller,

 $this->session->set_flashdata('abc', 'hi);

view,

echo $this->session->flashdata('abc');

doesn't work.....

echoing nothing~ -_-;
ajax doesn't have mechanism to catch session flash data?

any idea?

Body:
Your Ajax call will only ouput whatever the Controller/Method prints to the output buffer. So if you add

echo $this->session->flashdata('abc');

to your controller that gets called by the Ajax method, it will return the echo to the Ajax method which u can then display on the page. The echo statement in the view will only get executed when your page is refreshed, since PHP has to compile that echo statement on the server at run time and then return the result to your browser.


问:
preg_match with 2 rules doesn't work
I want that preg_match accepts https:// and http:// but also URLs without that like google.de, sh.st and stuff like that.

This if statement works, but it only accepts https:// and http:// URLs

```<code>if(!preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $flink)) {
    $html = "Error: invalid URL";
}
</code>```

I tried this, but this doesn't work too...

```<code>$bd = "/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i";
$dbb = "/^[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i";
if(!preg_match($bd, $flink)  || !preg_match($dbb, $flink))  {
    $html = "Error: invalid URL";
}
</code>```

What is wrong? The problem page is https://viid.su

答:
I think you want:

```<code>/^[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+$/
                ^-- removed a \ here.
</code>```

for the second regexp. Then it will match google.de and sh.st.

ContentLicense: CC BY-SA 3.0

Title: preg_match with 2 rules doesn't work

Body:
I want that preg_match accepts https:// and http:// but also URLs without that like google.de, sh.st and stuff like that.

This if statement works, but it only accepts https:// and http:// URLs

if(!preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $flink)) {
    $html = "Error: invalid URL";
}

I tried this, but this doesn't work too...

$bd = "/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i";
$dbb = "/^[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i";
if(!preg_match($bd, $flink)  || !preg_match($dbb, $flink))  {
    $html = "Error: invalid URL";
}

What is wrong? The problem page is https://viid.su

Body:
I think you want:

/^[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+$/
                ^-- removed a \ here.

for the second regexp. Then it will match google.de and sh.st.


问:
Get li value from ul filled by JavaScript
I have filled some "ul"s directly in HTML e.g.

```<code><button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Kennzahl
    <span class="caret"></span></button>
        <ul class="dropdown-menu" id="measure">
            <li><a href="#">volume</a></li>
            <li><a href="#">netSentiment</a></li>
            <li><a href="#">authors</a></li>
        </ul>
</code>```

and had no trouble reading the selected value by

```<code>$('#measure li').on('click', function(){
    $(this).text();
});
</code>```

Then I have tried to get the chosen Value from a "ul" that I filled by JavaScript:

Something like

```<code>$('#projectId').append('<li><a href="#">' + projects[i].name + '</a></li>');
</code>```

The Select is filled with the "li"s. But when I select one, the result isn't caught by the same JavaScript I could use with the "li" directly filled in HTML.

答:
When you dynamically add new elements after the page has loaded, you need to delegate the events to a parent element. You've almost done this, just change you code to

```<code>$('#measure').on('click','li', function(){
    $(this).text();
});
</code>```

Note your method here will not do anything - but ive kept the code as close to your example. Perhaps you meant console.log($(this).text());

Body:
I have filled some "ul"s directly in HTML e.g.

<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Kennzahl
    </button>

volume

netSentiment

authors

and had no trouble reading the selected value by

$('#measure li').on('click', function(){
    $(this).text();
});

Then I have tried to get the chosen Value from a "ul" that I filled by JavaScript:

Something like

$('#projectId').append('
' + projects[i].name + '
');

The Select is filled with the "li"s. But when I select one, the result isn't caught by the same JavaScript I could use with the "li" directly filled in HTML.

Body:
When you dynamically add new elements after the page has loaded, you need to delegate the events to a parent element. You've almost done this, just change you code to

$('#measure').on('click','li', function(){
    $(this).text();
});

Note your method here will not do anything - but ive kept the code as close to your example. Perhaps you meant console.log($(this).text());


问:
Click Link using Robot Framework doesn't work with Firefox
I'm new with Robot Framework. I made couple of scripts, that I have tested with Chrome and Firefox. With Chrome everything works fine, but with Firefox I have one tricky problem. I try to click link called Post like this:

```<code>Click Link link=Post
</code>```

With Firefox it won't work and I just get following error:

ElementNotInteractableException: Message:

In Chrome, this same test is working fine.

Firefox version is 53.0.3 (64-bit).

Selenium Driver version: 3.4.3

Geckodriver version:  0.16.1

Any suggestions? What can I try?

答:
You can use

```<code>Click Element  xpath=(//a[text()='Post'])[1]
</code>```

or there will be different class for mobile and web I guess.
You can add these to narrow down on single element out of two.
Something like:

```<code>Click Element  xpath=//a[text()='Post']/parent::div[contains(@class,'web')]
</code>```

Body:
I'm new with Robot Framework. I made couple of scripts, that I have tested with Chrome and Firefox. With Chrome everything works fine, but with Firefox I have one tricky problem. I try to click link called Post like this:

Click Link link=Post

With Firefox it won't work and I just get following error:

ElementNotInteractableException: Message:

In Chrome, this same test is working fine.

Firefox version is 53.0.3 (64-bit).

Selenium Driver version: 3.4.3

Geckodriver version:  0.16.1

Any suggestions? What can I try?

Body:
You can use

Click Element  xpath=(//a[text()='Post'])[1]

or there will be different class for mobile and web I guess.
You can add these to narrow down on single element out of two.
Something like:

Click Element  xpath=//a[text()='Post']/parent::div[contains(@class,'web')]


问:
Make 4 buttons take a quarter of the screen each
I want my buttons to look exactly like this but I cannot figure out how to do it. I have tried looking into different places on Google but none of the ways are like how I want it. I want to make my buttons have images and I was also wondering how I was going to resize these images on different screen sizes.

This is my layout_main.xml now.

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.mudd.devin.drivenow.MainActivity"
    android:weightSum="2">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button3"
        android:layout_marginTop="199dp">

    </Button>

    <Button

        android:layout_width="wrap_content"
        android:id="@+id/button1"
        android:layout_gravity="center"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/activity_vertical_margin" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button2"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>
</code>```

答: A bit late, but you could just use a RelativeLayout, put a dummy object centered, and set the rest of the elements around that central point.</p>

Body:
I want my buttons to look exactly like this but I cannot figure out how to do it. I have tried looking into different places on Google but none of the ways are like how I want it. I want to make my buttons have images and I was also wondering how I was going to resize these images on different screen sizes.

This is my layout_main.xml now.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.mudd.devin.drivenow.MainActivity"
    android:weightSum="2">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button3"
        android:layout_marginTop="199dp">

    </Button>

    <Button

        android:layout_width="wrap_content"
        android:id="@+id/button1"
        android:layout_gravity="center"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/activity_vertical_margin" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button2"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>


问:
Counting google analytics unique events in BigQuery
I have managed to calculate total events by ISOweek but not unique events for a given Google Analytics Event using BigQuery. When checking GA, total_events matches the GA interface on the dot but unique_events are off. Do you know how I can solve this?

The query:

```<code>SELECT INTEGER(STRFTIME_UTC_USEC(PARSE_UTC_USEC(date),"%V")) iso8601_week_number,
hits.eventInfo.eventCategory,
hits.eventInfo.eventAction,
COUNT(hits.eventInfo.eventCategory) AS total_events,
EXACT_COUNT_DISTINCT(fullVisitorId) AS unique_events
FROM
    TABLE_DATE_RANGE([XXXXXX.ga_sessions_], TIMESTAMP('2017-05-01'), TIMESTAMP('2017-05-07'))
WHERE
  hits.type = 'EVENT' AND hits.eventInfo.eventCategory = 'BIG_Transaction'
GROUP BY
iso8601_week_number, hits.eventInfo.eventCategory, hits.eventInfo.eventAction
</code>```

答:
The definition of unique events in Google Analytics is:

A count of the number of times an event with the category/action/label
  value was seen at least once within a session.

In other words, the number of sessions in which a specific event (defined by category, action AND label) was sent. In your query, you count the number of unique visitors that had the event, while you need to count the number of sessions and keep in mind that events with different labels should be counted as different unique events (although we are only interested in category and action).

A possible way to fix your code is:

```<code>SELECT
  INTEGER(STRFTIME_UTC_USEC(PARSE_UTC_USEC(date),"%V")) iso8601_week_number,
  hits.eventInfo.eventCategory,
  hits.eventInfo.eventAction,
  COUNT(hits.eventInfo.eventCategory) AS total_events,
  EXACT_COUNT_DISTINCT(CONCAT(fullVisitorId,'-',string(visitId),'-',date,'-',ifnull(hits.eventInfo.eventLabel,'null'))) AS unique_events
FROM
  TABLE_DATE_RANGE([XXXXXX.ga_sessions_], TIMESTAMP('2017-05-01'), TIMESTAMP('2017-05-07'))
WHERE
  hits.type = 'EVENT' AND hits.eventInfo.eventCategory = 'BIG_Transaction'
GROUP BY
    iso8601_week_number, hits.eventInfo.eventCategory, hits.eventInfo.eventAction
</code>```

The results of this query should match with the data in the GA interface.

Body:
I have managed to calculate total events by ISOweek but not unique events for a given Google Analytics Event using BigQuery. When checking GA, total_events matches the GA interface on the dot but unique_events are off. Do you know how I can solve this?

The query:

SELECT INTEGER(STRFTIME_UTC_USEC(PARSE_UTC_USEC(date),"%V")) iso8601_week_number,
hits.eventInfo.eventCategory,
hits.eventInfo.eventAction,
COUNT(hits.eventInfo.eventCategory) AS total_events,
EXACT_COUNT_DISTINCT(fullVisitorId) AS unique_events
FROM
    TABLE_DATE_RANGE([XXXXXX.ga_sessions_], TIMESTAMP('2017-05-01'), TIMESTAMP('2017-05-07'))
WHERE
  hits.type = 'EVENT' AND hits.eventInfo.eventCategory = 'BIG_Transaction'
GROUP BY
iso8601_week_number, hits.eventInfo.eventCategory, hits.eventInfo.eventAction

Body:
The definition of unique events in Google Analytics is:

A count of the number of times an event with the category/action/label
  value was seen at least once within a session.

In other words, the number of sessions in which a specific event (defined by category, action AND label) was sent. In your query, you count the number of unique visitors that had the event, while you need to count the number of sessions and keep in mind that events with different labels should be counted as different unique events (although we are only interested in category and action).

A possible way to fix your code is:

SELECT
  INTEGER(STRFTIME_UTC_USEC(PARSE_UTC_USEC(date),"%V")) iso8601_week_number,
  hits.eventInfo.eventCategory,
  hits.eventInfo.eventAction,
  COUNT(hits.eventInfo.eventCategory) AS total_events,
  EXACT_COUNT_DISTINCT(CONCAT(fullVisitorId,'-',string(visitId),'-',date,'-',ifnull(hits.eventInfo.eventLabel,'null'))) AS unique_events
FROM
  TABLE_DATE_RANGE([XXXXXX.ga_sessions_], TIMESTAMP('2017-05-01'), TIMESTAMP('2017-05-07'))
WHERE
  hits.type = 'EVENT' AND hits.eventInfo.eventCategory = 'BIG_Transaction'
GROUP BY
    iso8601_week_number, hits.eventInfo.eventCategory, hits.eventInfo.eventAction

The results of this query should match with the data in the GA interface.


问:
using -replace to remove a string with special characters from cells in a csv
I have a CSV file like:

```<code>"localpath"
"C:\Users\calabresel"
"C:\Users\goslinep"
"C:\Users\deangelisr"
"C:\Users\bannont"
"C:\Users\goodwind"
</code>```

I am looking for a way to isolate just the username from each field.  I will then query the AD to determine if each user is disabled or enabled.  I haven't been able to figure out how to get just the last piece though.  My idea was to use -replace to replace the identical string with null like this:

```<code>$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace "C:\Users\", ""}
</code>```

That came back with invalid regular expression pattern errors though which I assumed was a result of the target string containing special characters (the backslashes).  I then started looking for a way to get powershell to take the \ literally instead.  That lead me to try this:

```<code>$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace [Regex]::Escape("C:\\Users\\"), ""}
</code>```

and this

```<code>$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace "C:\\Users\\", ""}
</code>```

both of those methods stop the invalid regular expression errors and just return me a fresh line without complaining.  however when I print the $txt variable it is empty...

I'm certain I am approaching this problem from the wrong angle and/or with improper syntax but I could use some guidance as I just started working with powershell a week ago.

any help provided would be greatly appreciated.

答:
The following will import the CSV file and then get the leaf of the path. I.e the user name.

```<code>$txt = Import-Csv paths1.csv | ForEach-Object { Split-Path $_.localpath -leaf }
</code>```

If you still want to use your replace method, just take out the $_.localpath = part and it should work.

```<code>$txt = Import-Csv C:\@@Scatch\test.csv | % { $_.localpath -replace "C:\\Users\\", ""}
</code>```

Body:
I have a CSV file like:

"localpath"
"C:\Users\calabresel"
"C:\Users\goslinep"
"C:\Users\deangelisr"
"C:\Users\bannont"
"C:\Users\goodwind"

I am looking for a way to isolate just the username from each field.  I will then query the AD to determine if each user is disabled or enabled.  I haven't been able to figure out how to get just the last piece though.  My idea was to use -replace to replace the identical string with null like this:

$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace "C:\Users\", ""}

That came back with invalid regular expression pattern errors though which I assumed was a result of the target string containing special characters (the backslashes).  I then started looking for a way to get powershell to take the \ literally instead.  That lead me to try this:

$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace [Regex]::Escape("C:\\Users\\"), ""}

and this

$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace "C:\\Users\\", ""}

both of those methods stop the invalid regular expression errors and just return me a fresh line without complaining.  however when I print the $txt variable it is empty...

I'm certain I am approaching this problem from the wrong angle and/or with improper syntax but I could use some guidance as I just started working with powershell a week ago.

any help provided would be greatly appreciated.

Body:
The following will import the CSV file and then get the leaf of the path. I.e the user name.

$txt = Import-Csv paths1.csv | ForEach-Object { Split-Path $_.localpath -leaf }

If you still want to use your replace method, just take out the $_.localpath = part and it should work.

$txt = Import-Csv C:\@@Scatch\test.csv | % { $_.localpath -replace "C:\\Users\\", ""}


问:
a very simple query is not working PHP
i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S

here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!

```<code>  <?php

 $email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];

$connection = mysql_connect('localhost','root','') ;

$db_selected = mysql_select_db("lab5" , $connection) ;

$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
    while($row=mysql_fetch_array($result))
    {
        echo $row['name'];
    }
mysql_close($connection);
?>
</code>```

答:
try

```<code>$query = 'select * From user where email="' . $email . '" and password="'. $password . '" ' ;
</code>```

or

```<code>$query = "select * From user where email='$email' and password='$password'" ;
</code>```

Title: a very simple query is not working PHP

Body:
i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S

here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!

  <?php

 $email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];

$connection = mysql_connect('localhost','root','') ;

$db_selected = mysql_select_db("lab5" , $connection) ;

$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
    while($row=mysql_fetch_array($result))
    {
        echo $row['name'];
    }
mysql_close($connection);
?>

Body:
try

$query = 'select * From user where email="' . $email . '" and password="'. $password . '" ' ;

or

$query = "select * From user where email='$email' and password='$password'" ;


问:
SQL Server : insert data set into table with an identity column
I have a table with an auto-incrementing identity column. Typically I might insert data as follows

```<code>INSERT INTO [dbo].[table]
DEFAULT VALUES;

SET @value = SCOPE_IDENTITY();
</code>```

This way I know the identity value I've just inserted. However I need to insert a "set" of values into that table. Preferably also be able to identify the values I just inserted. I was hoping something similar to the following would be possible ...

```<code>INSERT INTO dbo.table DEFAULT VALUES
OUTPUT INSERTED.id INTO @output
SELECT SCOPE_IDENTITY()   -- obviously this isn't possible and doesn't actually make sense
FROM @records
WHERE somecolumn IS NULL
</code>```

I know I might need to set identity_insert on ... I would prefer not to if I don't have to. I am also aware that maybe I could also use some sort of recursive CTE, though I haven't used one of those in a while. Any help would be appreciated.

EDIT: to be clear the question I am asking is: how do I insert a "SET" of data into a table with an auto-incrementing identity column. And hopefully identify the values I just inserted in some way.

答:
```<code>INSERT INTO [dbo].[table]
DEFAULT VALUES;
SET @value = SCOPE_IDENTITY();
</code>```

One does not "typically" do any such thing. It would be highly unusual (to be gentle) to insert a single row that consisted of nothing but default values. And inserting hundreds or thousands of rows is even more suspicious. I think you have chosen a path that doesn't completely make sense.

But let's assume you have not lost your senses. Unfortunately, you cannot insert multiple rows using the "default values" syntax (directly or indirectly). But we can kludge together a script that "sort of" does this (with assumptions) using the output clause suggested by both Gordon and Sachin (using tally table logic here).

```<code>set nocount on;

declare @id int;
declare @outputtable table (id int);

create table #x (id int not null identity(1,1), descr varchar(20) null, dd int not null default(2));
insert #x (descr, dd) values ('test', 4), ('zork', 2), (null, 55); -- some extra fluff for demonstartion
insert #x default values;
set @id = SCOPE_IDENTITY();
select @id;
select * from #x order by id;

WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1),
    E02(N) AS (SELECT 1 FROM E00 a, E00 b),
    E04(N) AS (SELECT 1 FROM E02 a, E02 b),
    E08(N) AS (SELECT 1 FROM E04 a, E04 b),
    E16(N) AS (SELECT 1 FROM E08 a, E08 b),
    E32(N) AS (SELECT 1 FROM E16 a, E16 b),
cteTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY N) FROM E32)
insert #x (descr, dd)
output inserted.id into @outputtable(id)
select src.descr, src.dd
from #x as src cross join cteTally
where src.id = @id and cteTally.N < 5;

select x.*
from @outputtable as ids inner join #x as x on ids.id = x.id order by x.id;

if object_id('tempdb..#x') is not null drop table #x;
go
</code>```

This might not work depending on your table DDL. I'll let you find the assumptions built into this logic.

Body:
I have a table with an auto-incrementing identity column. Typically I might insert data as follows

INSERT INTO [dbo].[table]
DEFAULT VALUES;

SET @value = SCOPE_IDENTITY();

This way I know the identity value I've just inserted. However I need to insert a "set" of values into that table. Preferably also be able to identify the values I just inserted. I was hoping something similar to the following would be possible ...

INSERT INTO dbo.table DEFAULT VALUES
OUTPUT INSERTED.id INTO @output
SELECT SCOPE_IDENTITY()   -- obviously this isn't possible and doesn't actually make sense
FROM @records
WHERE somecolumn IS NULL

I know I might need to set identity_insert on ... I would prefer not to if I don't have to. I am also aware that maybe I could also use some sort of recursive CTE, though I haven't used one of those in a while. Any help would be appreciated.

EDIT: to be clear the question I am asking is: how do I insert a "SET" of data into a table with an auto-incrementing identity column. And hopefully identify the values I just inserted in some way.

Body:
INSERT INTO [dbo].[table]
DEFAULT VALUES;
SET @value = SCOPE_IDENTITY();

One does not "typically" do any such thing. It would be highly unusual (to be gentle) to insert a single row that consisted of nothing but default values. And inserting hundreds or thousands of rows is even more suspicious. I think you have chosen a path that doesn't completely make sense.

But let's assume you have not lost your senses. Unfortunately, you cannot insert multiple rows using the "default values" syntax (directly or indirectly). But we can kludge together a script that "sort of" does this (with assumptions) using the output clause suggested by both Gordon and Sachin (using tally table logic here).

set nocount on;

declare @id int;
declare @outputtable table (id int);

create table #x (id int not null identity(1,1), descr varchar(20) null, dd int not null default(2));
insert #x (descr, dd) values ('test', 4), ('zork', 2), (null, 55); -- some extra fluff for demonstartion
insert #x default values;
set @id = SCOPE_IDENTITY();
select @id;
select * from #x order by id;

WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1),
    E02(N) AS (SELECT 1 FROM E00 a, E00 b),
    E04(N) AS (SELECT 1 FROM E02 a, E02 b),
    E08(N) AS (SELECT 1 FROM E04 a, E04 b),
    E16(N) AS (SELECT 1 FROM E08 a, E08 b),
    E32(N) AS (SELECT 1 FROM E16 a, E16 b),
cteTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY N) FROM E32)
insert #x (descr, dd)
output inserted.id into @outputtable(id)
select src.descr, src.dd
from #x as src cross join cteTally
where src.id = @id and cteTally.N < 5;

select x.*
from @outputtable as ids inner join #x as x on ids.id = x.id order by x.id;

if object_id('tempdb..#x') is not null drop table #x;
go

This might not work depending on your table DDL. I'll let you find the assumptions built into this logic.


问:
Multiple PHP versions released on same day
I have just noticed the banner across the top of php.net, stating that PHP 7.0.20 has been released. I thought it a bit strange since I'm using PHP 7.1.5. Following the link has left me very confused.

PHP 7.0.20: Released 08 Jun 2017

PHP 7.1.5: Released 11 May 2017

PHP 7.0.19: Released 11 May 2017

Is there any significance to 7.1.5 version number and it being released on the same day as 7.0.19 and being released before the lesser version of 7.0.20?

I can understand them skipping the whole 6.x.x, but the current 7.x.x version seem to be just mishmashed.

答:
There are currently three versions of PHP under development and support: 5.6 (security fixes only), 7.0 and 7.1 (active development and support).

They go in parallel and many times patch versions (when the 3rd component of the version changes) are released for all three of them on the same day. Such releases fix bugs or security issues and it is normal to be fixed on all currently supported versions.


问:
Truecaller web login : Unable to process JSON - Error
```<code>Unirest.setTimeouts(7000, 7000);
         HttpResponse<JsonNode> accessToken = Unirest.post("https://api4.truecaller.com/v1/apps/requests")
                    .header("Content-Type", "application/json")
                    .header("Accept", "application/json")
                    .header("appKey", "app-key-here")
                    .header("Cache-Control", "no-cache")
                    .field("phoneNumber", "46760123456")
                    .asJson();
</code>```

I am using TrueCaller Web-login API (https://github.com/truecaller/web-login),

The above mentioned is my code (Java-Unirest), please help me to solve this problem (Unable to call API)

Response from truecaller server :
  Error: 400
  Message: Unable to process JSON.

答:
http://unirest.io/java.html

You have to use body method as per the documentation.

Example

```<code>Unirest.setTimeouts(7000, 7000);
HttpResponse<JsonNode> accessToken = Unirest.post("https://api4.truecaller.com/v1/apps/requests")
 .header("Content-Type", "application/json")
.header("Accept", "application/json")
.header("appKey", "app-key-here")
.header("Cache-Control", "no-cache")
.body("{\"phoneNumber\":7777777777}")
.asJson();
</code>```

OR

```<code>Unirest.setObjectMapper(new ObjectMapper() {
    private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
    public <T> T readValue(String value, Class<T> valueType) {
                try {
                    return jacksonObjectMapper.readValue(value, valueType);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            public String writeValue(Object value) {
                try {
                    return jacksonObjectMapper.writeValueAsString(value);
                } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
        });

class Test implements Serializable {
    final public Long phoneNumber;

    public Test(Long phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
}

Test t = new Test(7777777777L);

Unirest.setTimeouts(7000, 7000);

HttpResponse<JsonNode> accessToken = Unirest.post("https://api4.truecaller.com/v1/apps/requests")
    .header("Content-Type", "application/json")
    .header("Accept", "application/json")
    .header("appKey", "app-key-here")
    .header("Cache-Control", "no-cache")
    .body(t)
    .asJson();
</code>```

Body:
Unirest.setTimeouts(7000, 7000);
         HttpResponse<JsonNode> accessToken = Unirest.post("https://api4.truecaller.com/v1/apps/requests")
                    .header("Content-Type", "application/json")
                    .header("Accept", "application/json")
                    .header("appKey", "app-key-here")
                    .header("Cache-Control", "no-cache")
                    .field("phoneNumber", "46760123456")
                    .asJson();

I am using TrueCaller Web-login API (https://github.com/truecaller/web-login),

The above mentioned is my code (Java-Unirest), please help me to solve this problem (Unable to call API)

Response from truecaller server :
  Error: 400
  Message: Unable to process JSON.

Body:
http://unirest.io/java.html

You have to use body method as per the documentation.

Example

Unirest.setTimeouts(7000, 7000);
HttpResponse<JsonNode> accessToken = Unirest.post("https://api4.truecaller.com/v1/apps/requests")
 .header("Content-Type", "application/json")
.header("Accept", "application/json")
.header("appKey", "app-key-here")
.header("Cache-Control", "no-cache")
.body("{\"phoneNumber\":7777777777}")
.asJson();

OR

Unirest.setObjectMapper(new ObjectMapper() {
    private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
    public <T> T readValue(String value, Class<T> valueType) {
                try {
                    return jacksonObjectMapper.readValue(value, valueType);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            public String writeValue(Object value) {
                try {
                    return jacksonObjectMapper.writeValueAsString(value);
                } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
        });

class Test implements Serializable {
    final public Long phoneNumber;

    public Test(Long phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
}

Test t = new Test(7777777777L);

Unirest.setTimeouts(7000, 7000);

HttpResponse<JsonNode> accessToken = Unirest.post("https://api4.truecaller.com/v1/apps/requests")
    .header("Content-Type", "application/json")
    .header("Accept", "application/json")
    .header("appKey", "app-key-here")
    .header("Cache-Control", "no-cache")
    .body(t)
    .asJson();


问:
Uncaught SyntaxError JSON.parse
I am trying to parse a JSON string and it throws
Uncaught SyntaxError : Unexpected token error. Below is the content am having in a variable as a string.

Note : I checked the typeof() for the jsonString variable and it returned string. So the variable is of string type and no doubt in
  that

JSON String :

```<code>{"title":"This is my Title","body":"<div class="ExternalClassB5F21AC89A1F40D0BCA5A8DBB6F738ED"><span style="font-size:11.0pt;font-family:"Calibri",sans-serif;">Our commitment to the development of this feature is
delayed  due to the unexpected JSON parse error.  </span></div>","byline":"This issue is killing me now for more than 2 days.  ","tile":0,"showText":true,"showImage":true,"image":{"ImageUrl":"/Path/to/imgFolder/hero%20background.png","Hyperlink":"","OpenHyperlinkInNewWindow":false,"Alignment":"","AlternateText":"","BorderWidth":0,"Height":0,"HorizontalSpacing":0,"VerticalSpacing":0,"Width":0},"publishedDate":"/Date(1496864514000)/","labels":["Character and Values"],"peopleList":[]}
</code>```

I couldn't identify whats the problem is. Does any one have the clue?

Based on the line and column number in the error, it shows that the unexpected character is in ending of line 1 i.e at the end of this feature is in line 1. So all I can guess is that the line break might be the problem. Even if the line break causes, is there any way to handle this parsing issue.

Thanks in advance.

答:
You have a linebreak with your JSON.body after delayed.

```<code> ..... feature is <--- THERE IS A LINEBREAK HERE
delayed  .....
</code>```

This is not a valid JSON character and shall be defined as \n

Title: Uncaught SyntaxError JSON.parse

Body:
I am trying to parse a JSON string and it throws
Uncaught SyntaxError : Unexpected token error. Below is the content am having in a variable as a string.

Note : I checked the typeof() for the jsonString variable and it returned string. So the variable is of string type and no doubt in
  that

JSON String :

{"title":"This is my Title","body":"
Our commitment to the development of this feature is
delayed  due to the unexpected JSON parse error. &#160;
","byline":"This issue is killing me now for more than 2 days.  ","tile":0,"showText":true,"showImage":true,"image":{"ImageUrl":"/Path/to/imgFolder/hero%20background.png","Hyperlink":"","OpenHyperlinkInNewWindow":false,"Alignment":"","AlternateText":"","BorderWidth":0,"Height":0,"HorizontalSpacing":0,"VerticalSpacing":0,"Width":0},"publishedDate":"/Date(1496864514000)/","labels":["Character and Values"],"peopleList":[]}

I couldn't identify whats the problem is. Does any one have the clue?

Based on the line and column number in the error, it shows that the unexpected character is in ending of line 1 i.e at the end of this feature is in line 1. So all I can guess is that the line break might be the problem. Even if the line break causes, is there any way to handle this parsing issue.

Thanks in advance.

Body:
You have a linebreak with your JSON.body after delayed.

 ..... feature is <--- THERE IS A LINEBREAK HERE
delayed  .....

This is not a valid JSON character and shall be defined as \n


问:
How can I launch a Android Activity from Xamarin Forms Page?
I know that i can launch a Xamarin Forms page from an Native Android Activity, but how do i start a Native Android Activity from Xamarin Forms ContentPage. I tried with DependencyService but without success.</p>

答:
I figured it out.

First i needed to create a Interface like this in Xamarin Project

```<code>public interface IRecordVideoPage
{
    void StartNativeIntentOrActivity();
}
</code>```

then i launched the Native Android Activity from my Xamarin Forms Content Page using Dependency Service like this:

```<code>DependencyService.Register<IRecordVideoPage>();
DependencyService.Get<IRecordVideoPage>().StartNativeIntentOrActivity();
</code>```

next I created a RecordActivity class in my Android Project that loads the Test Activity

```<code>[assembly: Xamarin.Forms.Dependency(typeof(RecordActivity))]
namespace StreamTest.Droid
{
    [Activity(Label = "RecordActivity")]
    public class RecordActivity : IRecordVideoPage
    {
        public void StartNativeIntentOrActivity()
        {
            var intent = new Intent(Forms.Context, typeof(Test));
            Forms.Context.StartActivity(intent);
        }
    }
</code>```

finally I set the content view in the Test class:

```<code>public class Test : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        public Test() { }

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Record);
        }
    }
}
</code>```

Body:
I figured it out.

First i needed to create a Interface like this in Xamarin Project

public interface IRecordVideoPage
{
    void StartNativeIntentOrActivity();
}

then i launched the Native Android Activity from my Xamarin Forms Content Page using Dependency Service like this:

DependencyService.Register<IRecordVideoPage>();
DependencyService.Get<IRecordVideoPage>().StartNativeIntentOrActivity();

next I created a RecordActivity class in my Android Project that loads the Test Activity

[assembly: Xamarin.Forms.Dependency(typeof(RecordActivity))]
namespace StreamTest.Droid
{
    [Activity(Label = "RecordActivity")]
    public class RecordActivity : IRecordVideoPage
    {
        public void StartNativeIntentOrActivity()
        {
            var intent = new Intent(Forms.Context, typeof(Test));
            Forms.Context.StartActivity(intent);
        }
    }

finally I set the content view in the Test class:

public class Test : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        public Test() { }

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Record);
        }
    }
}


问:
How to extract image names from SQL column
We have Wordpress installation based on SQL Server and would like to extract the image names from the field post_content in wp_post. I have tried a lot with patindex, like clause and so on but I cant figure out how to do.

Here's an example of the content on row in the post_content column :

```<code><a href="http://www.example.com/wp-content/uploads/2017/06/1-1.jpg"><img class="aligncenter size-large wp-image-133975" src="http://www.example.com/wp-content/uploads/2017/06/1-1-1024x682.jpg" alt="" width="604" height="402" /></a>
</code>```

I have about 10 000 records in the table and the content in post_content can contain one or more images.
I would like to extract the image names like this :

/wp-content/uploads/2017/06/1-1.jpg

/wp-content/uploads/2017/06/1-1-1024x682.jpg

Thankful for help.

答:
Try This:</p>

```<code>DECLARE @table TABLE (ID INT IDENTITY(1,1),data NVARCHAR(500))
INSERT @table VALUES('<a href="http://www.example.com/wp-content/uploads/2017/06/1-1.jpg"><img "D:/abc.jpg" class="aligncenter size-large wp-image-133975" src="http://www.example.com/wp-content/uploads/2017/06/1-1-1024x682.jpg" alt="" width="604" height="402" /></a>')
DECLARE @images TABLE (ID INT,data NVARCHAR(500),passed INT)
DECLARE @collecter INT = 1

WHILE(@collecter=1)
BEGIN
INSERT INTO @images
SELECT ID, SUBSTRING(REVERSE(data),CHARINDEX('gpj.',REVERSE(data))+4,500),0 FROM @table
UPDATE @images SET data = REVERSE(SUBSTRING(data,1,CHARINDEX('/',data+'/')-1))+'.jpg' WHERE passed = 0
UPDATE A SET A.data = SUBSTRING(A.data,1,CHARINDEX(B.data,A.data)-1) FROM @table A JOIN @images B ON A.ID = B.ID WHERE passed = 0
UPDATE @images SET passed = 1
IF EXISTS (SELECT 1 FROM @table GROUP BY data HAVING CHARINDEX('.jpg',data)>0) SET @collecter = 1 ELSE SET @collecter = 0
END

SELECT data FROM @images
</code>```

Body:
We have Wordpress installation based on SQL Server and would like to extract the image names from the field post_content in wp_post. I have tried a lot with patindex, like clause and so on but I cant figure out how to do.

Here's an example of the content on row in the post_content column :

I have about 10 000 records in the table and the content in post_content can contain one or more images.
I would like to extract the image names like this :

/wp-content/uploads/2017/06/1-1.jpg

/wp-content/uploads/2017/06/1-1-1024x682.jpg

Thankful for help.

Body:
Try This:

DECLARE @table TABLE (ID INT IDENTITY(1,1),data NVARCHAR(500))
INSERT @table VALUES('<a href="http://www.example.com/wp-content/uploads/2017/06/1-1.jpg"><img "D:/abc.jpg" class="aligncenter size-large wp-image-133975" src="http://www.example.com/wp-content/uploads/2017/06/1-1-1024x682.jpg" alt="" width="604" height="402" /></a>')
DECLARE @images TABLE (ID INT,data NVARCHAR(500),passed INT)
DECLARE @collecter INT = 1

WHILE(@collecter=1)
BEGIN
INSERT INTO @images
SELECT ID, SUBSTRING(REVERSE(data),CHARINDEX('gpj.',REVERSE(data))+4,500),0 FROM @table
UPDATE @images SET data = REVERSE(SUBSTRING(data,1,CHARINDEX('/',data+'/')-1))+'.jpg' WHERE passed = 0
UPDATE A SET A.data = SUBSTRING(A.data,1,CHARINDEX(B.data,A.data)-1) FROM @table A JOIN @images B ON A.ID = B.ID WHERE passed = 0
UPDATE @images SET passed = 1
IF EXISTS (SELECT 1 FROM @table GROUP BY data HAVING CHARINDEX('.jpg',data)>0) SET @collecter = 1 ELSE SET @collecter = 0
END

SELECT data FROM @images


问:
Is there an easier way than nested iifs to count mismatched conditions in SQL server
The picture below shows a table of accounts and the outcomes that I want to count. Ie every time the account number is 106844 and the outcome is "MESSAGE" or "ESCALATION EMAIL" that should count as 1 where any other outcome counts as 0. What I would normally do is a horrible mess of iifs like

```<code>   sum( iif([account] = '106719' and [Outcome] in ('MESSAGE','ESCALATION_EMAIL'),1,iif([account] = '310827' and [outcome] <> 'ABORT' and 'CALL_OUTCOME_LB' in ("Call patched to Customer Care","Message Taken"),1,iif( ... , 0) as [Total Outcomes]
</code>```

and so on but man it feel like there's got to be an easier way or one less prone to making a random mistake in the 7th nested iif and messing the whole thing up. Any ideas?

答:
Yeah... there is<br>
The last parameter is for when the condition is false, everything else will fall in there. </p>

```<code>SUM( IIF([ACCOUNT] = '106719' AND [OUTCOME] IN ('MESSAGE','ESCALATION_EMAIL'),1,0))
</code>```

Body:
The picture below shows a table of accounts and the outcomes that I want to count. Ie every time the account number is 106844 and the outcome is "MESSAGE" or "ESCALATION EMAIL" that should count as 1 where any other outcome counts as 0. What I would normally do is a horrible mess of iifs like

   sum( iif([account] = '106719' and [Outcome] in ('MESSAGE','ESCALATION_EMAIL'),1,iif([account] = '310827' and [outcome] <> 'ABORT' and 'CALL_OUTCOME_LB' in ("Call patched to Customer Care","Message Taken"),1,iif( ... , 0) as [Total Outcomes]

and so on but man it feel like there's got to be an easier way or one less prone to making a random mistake in the 7th nested iif and messing the whole thing up. Any ideas?

Body:
Yeah... there is

The last parameter is for when the condition is false, everything else will fall in there.

SUM( IIF([ACCOUNT] = '106719' AND [OUTCOME] IN ('MESSAGE','ESCALATION_EMAIL'),1,0))


问:
Submit drop down values into google spreadsheet with google script
I have coded a script with help from several stackoverflow examples but I get stuck when trying to go a bit further.

It seems very straightforward but I cannot seem to work it out.

So here it is:
I have coded an HTML script that initiates a dialogbox with some drop down menus. The data in the drop down menus is dynamic and taken from a range in a spreadsheet. I want for users to open the spreadsheet, run the script and choose the options from the drop down values. These drop down values will be pasted on the same spreadsheet.

The bit I got working is that the code sees the values that need to go in the drop down box, illustrates that and that there is a submit box.

However, I cannot seem to submit the values onto the spreadsheet. Please could anyone help me out or point me in the right direction?

test.gs

```<code>   function openInputDialog1() {
  var html = HtmlService.createHtmlOutputFromFile('Test').setSandboxMode(HtmlService.SandboxMode.IFRAME);
  SpreadsheetApp.getUi()
    .showModalDialog(html, 'Add Item');
}

function getMenuListFromSheet() {
  return SpreadsheetApp.getActive().getSheetByName('Part Names')
     .getRange(1,5,6,1).getValues();
}

function getThicknessFromSheet(){
  return SpreadsheetApp.getActive().getSheetByName('Part Names')
     .getRange(1,5,6,1).getValues();
}

function itemadd(form) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Part Names');
  var LastRow=sheet.getLastRow();
  Logger.log(LastRow);
  Logger.log(form);
  sheet.getRange(LastRow+1,1,1,2).setValues(form);

  return true;

}
</code>```

Test.html

```<code><!DOCTYPE html>
<html>
<p>List of parts:</p>

<select id="menu">
  <option></option>
  <option>Google Chrome</option>
  <option>Firefox</option>
</select>

<select id="thickness">
  <option></option>
  <option>1</option>
  <option>2</option>
</select>

<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<input type="submit" value="Submit" onclick="select()">
<script>
// The code in this function runs when the page is loaded.
$(function() {
  google.script.run.withSuccessHandler(showMenu)
      .getMenuListFromSheet();
  google.script.run.withSuccessHandler(showThickness)
      .getThicknessFromSheet();

});

/**function showThings(things) {
 var list = $('#things');
 list.empty();
 for (var i = 0; i < things.length; i++) {
   list.append('<li>' + things[i] + '</li>');
}
}
**/
function showMenu(menuItems) {
  var list = $('#menu');
  list.find('option').remove();  // remove existing contents

  for (var i = 0; i < menuItems.length; i++) {
    list.append('<option>' + menuItems[i] + '</option>');
  }
}

function showThickness(menuThickness) {
  var list = $('#thickness');
  list.find('option').remove();  // remove existing contents

  for (var i = 0; i < menuThickness.length; i++) {
    list.append('<option>' + menuThickness[i] + '</option>');
  }
}

</script>
<script>
function select(){
var x = document.getElementById('menu').value;
var y = document.getElementById('thickness').value;

google.script.run
            .itemadd(x,y)

google.script.host.close();
</script>

</html>
</code>```

I know that I am somewhere not making the connection between the script and the HTML side but fail to understand where.

Thanks,
Tim

答:
Here's the lacking bits from your code:

```<code><input type="submit" value="Submit" onclick="sheetConnect()">
</code>```

In your .HTML file:

```<code>function sheetConnect(){

   var e = document.getElementById('menu'); //choices are Google Chrome and Firefox
   var name = e.options[e.selectedIndex].value; //get whatever the user selected
   google.script.run.writeData(name); //pass the value to Code.gs
}
</code>```

In your Code.gs

```<code>function writeData(name){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Sheet1'); //whatever your sheet's name
  var cell = sheet.getRange(1,8); //assign position to column H row 1
      cell.setValue(name);        // write selected data from Dropdown named 'menu'
}
</code>```

result:

Use the knowledge here to complete your project :)

Body:
I have coded a script with help from several stackoverflow examples but I get stuck when trying to go a bit further.

It seems very straightforward but I cannot seem to work it out.

So here it is:
I have coded an HTML script that initiates a dialogbox with some drop down menus. The data in the drop down menus is dynamic and taken from a range in a spreadsheet. I want for users to open the spreadsheet, run the script and choose the options from the drop down values. These drop down values will be pasted on the same spreadsheet.

The bit I got working is that the code sees the values that need to go in the drop down box, illustrates that and that there is a submit box.

However, I cannot seem to submit the values onto the spreadsheet. Please could anyone help me out or point me in the right direction?

test.gs

   function openInputDialog1() {
  var html = HtmlService.createHtmlOutputFromFile('Test').setSandboxMode(HtmlService.SandboxMode.IFRAME);
  SpreadsheetApp.getUi()
    .showModalDialog(html, 'Add Item');
}

function getMenuListFromSheet() {
  return SpreadsheetApp.getActive().getSheetByName('Part Names')
     .getRange(1,5,6,1).getValues();
}

function getThicknessFromSheet(){
  return SpreadsheetApp.getActive().getSheetByName('Part Names')
     .getRange(1,5,6,1).getValues();
}

function itemadd(form) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Part Names');
  var LastRow=sheet.getLastRow();
  Logger.log(LastRow);
  Logger.log(form);
  sheet.getRange(LastRow+1,1,1,2).setValues(form);

  return true;

}

Test.html

<!DOCTYPE html>

List of parts:

<select id="menu">
  <option></option>
  <option>Google Chrome</option>
  <option>Firefox</option>
</select>

<select id="thickness">
  <option></option>
  <option>1</option>
  <option>2</option>
</select>

<input type="submit" value="Submit" onclick="select()">

I know that I am somewhere not making the connection between the script and the HTML side but fail to understand where.

Thanks,
Tim

Body:
Here's the lacking bits from your code:

<input type="submit" value="Submit" onclick="sheetConnect()">

In your .HTML file:

function sheetConnect(){

   var e = document.getElementById('menu'); //choices are Google Chrome and Firefox
   var name = e.options[e.selectedIndex].value; //get whatever the user selected
   google.script.run.writeData(name); //pass the value to Code.gs
}

In your Code.gs

function writeData(name){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Sheet1'); //whatever your sheet's name
  var cell = sheet.getRange(1,8); //assign position to column H row 1
      cell.setValue(name);        // write selected data from Dropdown named 'menu'
}

result:

Use the knowledge here to complete your project :)


问:
TFS2017 Release Management TFVC Artifacts Source - only a changeset
On the Artifacts tab of the release definition editor I can choose as artifacts source type the "Team Foundation Version Control" in the Link an artifact source pop-up.

According with the documentation it's possible to specify a certain changeset to be used as a source:

When you link a TFVC branch, you can specify the changeset to be
  deployed when creating a release.

But in the editor is possible to select only the root (e.g. $/FooBarProject).

How can I specify to download only a specific changeset? I don't need to download the entire repository when I need just one script.

TFS Version 15.112.26301.0

答:
When you specify a changeset, you're specifying a specific changeset for the entire repository. There's no way to conditionally restrict it to just the contents of that changeset.

If you need a specific file or subset of files, you should publish it as a build artifact.


答: Why not use a lookup table that has the Account and Outcome and use that? Then, as requirements change, you could update the lookup table and not worry about your code.</p>

Title: Is there an easier way than nested iifs to count mismatched conditions in SQL server


问:
Listing Blocks of content in horizontal line html
I am trying to make blocks of information presented in horizontal list, and they are currently vertical. Any suggestions?[block example][code]</p>

答:
One way of doing what I think you are asking would be to use the CSS "display" property. You just need to set the container of all the blocks you want inline horizontally to "display: inline-block", and then float them.

For example:
HTML:

```<code><div id="container">
     <div class="block">
        <p>...</p>
        <p>...</p>
    </div>
    <div class="block">
        <p>...</p>
        <p>...</p>
    </div>
</div>
</code>```

CSS:

```<code>#container {
    display: inline-block;
}

.block {
    float: left;
}
</code>```

Body:
One way of doing what I think you are asking would be to use the CSS "display" property. You just need to set the container of all the blocks you want inline horizontally to "display: inline-block", and then float them.

For example:
HTML:

<div id="container">
     <div class="block">
        <p>...</p>
        <p>...</p>
    </div>
    <div class="block">
        <p>...</p>
        <p>...</p>
    </div>
</div>

CSS:

#container {
    display: inline-block;
}

.block {
    float: left;
}


问:
Why can't I push this additional data into my array?
I'm making an API call and here is the response

As you can see, key 0 & 1 have NULL for their 'outcome_status' whereas key 2 is populated. The number of returned results is dynamic

I wish to loop the results and push the 'category' & 'location' details into the array and if 'outcome_status' isn't NULL then I wish to add that data into the same array.

The problem is, within the IF statement that checks if outcome_status is null, I can't assign the forloop var i; variable as the key for
 mapData where I use.push() the second time.

line:68 Uncaught TypeError: Cannot read property 'push' of undefined

```<code>var mapData = [];
function getPolApi(year,month,lat,lng,mapData) {
    $.ajax({
    url : "https://data.police.uk/api/crimes-at-location?date="+year+"-"+month+"&lat="+lat+"&lng="+lng,
    type : "get",
    async: false,
    success : function(data) {
      console.log(data);
      mapData = [];// Empty the array of old results
      for(var i = 1; i < data.length; i++) {
</code>```

EDIT: I want to do this.

```<code>            mapData.push([
              data[i]['category'],
              data[i]['location']['street']['name'],
              data[i]['outcome_status']['category'],
              data[i]['outcome_status']['date']
            ]);
</code>```

But if there is no outcome_status then it will fail... So I added the second part into a conditional instead

```<code>         if(data[i].outcome_status != null) {

          //In order to access the original array by key,
         // I wish to the use the forloop iteration otherwise
         //mapData.push() will add the data as NEW arrays instead of adding on to the end of the existing arrays.

          //Why can't I use the current index for the key here?

              mapData[i].push([ //line 68

              data[i]['outcome_status']['category'],
              data[i]['outcome_status']['date'],
            ]);
         }
           heatmapData.push(new google.maps.LatLng(data[i].location.latitude,data[i].location.longitude));
      }

      console.log(mapData);
       //Add results into view

          for(var i = 0; i < mapData.length; i++) {
             var fill = '<div class="row resu"><div class="col-xs-2 number"><h5>'+[i+1]+'</h5></div><div class="col-xs-10"><p class="text-primary">Type of crime: <span class="text-strong">'+mapData[i][0]+'</span></p><p class="text-primary">Location specifics: <span class="text-strong">'+mapData[i][1]+'</span></p></div></div>';
            $('.output').append(fill);

          }//endforloop

          //Move the map into view of the heatmaps
          moveMap(lat,lng);
          //Add the heatmaps
          addHeatMap();

      // console.log(mapData);
    },
    error: function(dat) {
       console.log('error');
    }
 });
</code>```

答:
Some issues:

Your for loop starts with i equal to one, so even after the first push, mapData[i] does not yet exist, so applying push to that makes no sense.

If you want to push additional elements to an existing array, you should not add those additional elements as part of an array, but provide them as separate arguments to push.

Furthermore, the code becomes a bit more functional when use array methods like map.

Here is how the part to fill mapData and heatmapData could look like:

```<code>// Create a new array, with nested arrays: one per data item
mapData = data.map(function (item) {
    // Use a local variable to build the sub-array:
    var arr = [
      item.category,
      item.location.street.name,
    ];
    if (item.outcome_status) { // add 2 more elements if they exist
        arr.push( // note: no square brackets here
            item.outcome_status.category,
            item.outcome_status.date,
        );
    }
    // Add it to `dataMap` by returning it to the `map` callback:
    return arr;
});

// Extend the heatmap with additional locations
heatmapData = heatmapData.concat(data.map(function (item) {
    return new google.maps.LatLng(item.location.latitude,item.location.longitude);
}));
</code>```

Body:
I'm making an API call and here is the response

As you can see, key 0 & 1 have NULL for their 'outcome_status' whereas key 2 is populated. The number of returned results is dynamic

I wish to loop the results and push the 'category' & 'location' details into the array and if 'outcome_status' isn't NULL then I wish to add that data into the same array.

The problem is, within the IF statement that checks if outcome_status is null, I can't assign the forloop var i; variable as the key for
 mapData where I use.push() the second time.

line:68 Uncaught TypeError: Cannot read property 'push' of undefined

var mapData = [];
function getPolApi(year,month,lat,lng,mapData) {
    $.ajax({
    url : "https://data.police.uk/api/crimes-at-location?date="+year+"-"+month+"&lat="+lat+"&lng="+lng,
    type : "get",
    async: false,
    success : function(data) {
      console.log(data);
      mapData = [];// Empty the array of old results
      for(var i = 1; i < data.length; i++) {

EDIT: I want to do this.

            mapData.push([
              data[i]['category'],
              data[i]['location']['street']['name'],
              data[i]['outcome_status']['category'],
              data[i]['outcome_status']['date']
            ]);

But if there is no outcome_status then it will fail... So I added the second part into a conditional instead

         if(data[i].outcome_status != null) {

          //In order to access the original array by key,
         // I wish to the use the forloop iteration otherwise
         //mapData.push() will add the data as NEW arrays instead of adding on to the end of the existing arrays.

          //Why can't I use the current index for the key here?

              mapData[i].push([ //line 68

              data[i]['outcome_status']['category'],
              data[i]['outcome_status']['date'],
            ]);
         }
           heatmapData.push(new google.maps.LatLng(data[i].location.latitude,data[i].location.longitude));
      }

      console.log(mapData);
       //Add results into view

          for(var i = 0; i < mapData.length; i++) {
             var fill = '

'+[i+1]+'

Type of crime: '+mapData[i][0]+'

Location specifics: '+mapData[i][1]+'

';
            $('.output').append(fill);

          }//endforloop

          //Move the map into view of the heatmaps
          moveMap(lat,lng);
          //Add the heatmaps
          addHeatMap();

      // console.log(mapData);
    },
    error: function(dat) {
       console.log('error');
    }
 });

Body:
Some issues:

Your for loop starts with i equal to one, so even after the first push, mapData[i] does not yet exist, so applying push to that makes no sense.

If you want to push additional elements to an existing array, you should not add those additional elements as part of an array, but provide them as separate arguments to push.

Furthermore, the code becomes a bit more functional when use array methods like map.

Here is how the part to fill mapData and heatmapData could look like:

// Create a new array, with nested arrays: one per data item
mapData = data.map(function (item) {
    // Use a local variable to build the sub-array:
    var arr = [
      item.category,
      item.location.street.name,
    ];
    if (item.outcome_status) { // add 2 more elements if they exist
        arr.push( // note: no square brackets here
            item.outcome_status.category,
            item.outcome_status.date,
        );
    }
    // Add it to `dataMap` by returning it to the `map` callback:
    return arr;
});

// Extend the heatmap with additional locations
heatmapData = heatmapData.concat(data.map(function (item) {
    return new google.maps.LatLng(item.location.latitude,item.location.longitude);
}));


问:
how to display the maximum value in the array?
```<code>int main()
{
   int numbers[30];
   int i;

   // making array of 30 random numbers under 100
   for(i=0;i<30;i++)
   {
       numbers[i] = rand() % 100;
   }

   // finding the greatest number in the array
   int greatest = 0;
   srand(1);
   for(i=0;i<30;i++)
   {
        if ( numbers[i] > greatest)
            greatest = numbers[i];
   }
</code>```

How do I then tell the program to display the max value of the array??
Thank you

答:
Is this what you're referring to?

printf("%d", greatest);

Make sure to include "cstdio".

Body:
int main()
{
   int numbers[30];
   int i;

   // making array of 30 random numbers under 100
   for(i=0;i<30;i++)
   {
       numbers[i] = rand() % 100;
   }

   // finding the greatest number in the array
   int greatest = 0;
   srand(1);
   for(i=0;i<30;i++)
   {
        if ( numbers[i] > greatest)
            greatest = numbers[i];
   }

How do I then tell the program to display the max value of the array??
Thank you


问:
defining a "symbolic" math function in sage?
I don't know if this feature exists or if symbolic is the right name for it.

I want to be able to have a variable, say f, for a (math) function with certain properties. I want to be able to use this variable in expressions. But I don't actually want to define what the function f does.

For example, I might want to say "define f to be a function in one variable that is differentiable on the real numbers". Then I want to be able to use f(x) in expressions. I might want to define another function g(x) in terms of f(x) and be able to differentiate g(x) and get an expression from sage. So I want to issue the following commands

```<code>f is defined as before
define g(x)=(f(x))^2
differentiate g
output: g'(x)=2f(x)f'(x)
</code>```

Does this feature exist?

答:
How about this:</p>

```<code>sage: f = function('f')
sage: g(x) = f(x)**2
sage: g.derivative()
x |--> 2*f(x)*diff(f(x), x)
</code>```

Body:
I don't know if this feature exists or if symbolic is the right name for it.

I want to be able to have a variable, say f, for a (math) function with certain properties. I want to be able to use this variable in expressions. But I don't actually want to define what the function f does.

For example, I might want to say "define f to be a function in one variable that is differentiable on the real numbers". Then I want to be able to use f(x) in expressions. I might want to define another function g(x) in terms of f(x) and be able to differentiate g(x) and get an expression from sage. So I want to issue the following commands

f is defined as before
define g(x)=(f(x))^2
differentiate g
output: g'(x)=2f(x)f'(x)

Does this feature exist?

Body:
How about this:

sage: f = function('f')
sage: g(x) = f(x)**2
sage: g.derivative()
x |--> 2*f(x)*diff(f(x), x)


问:
Importing json that was serialized by JSON is failing
So I have an object with some fields...

```<code>protected String name;
protected String relativePathAndFileName;
protected DateTime next_Run;
protected ArrayList<String> hosts;
</code>```

Which gets serialized to JSON like this:

```<code>public void serialize(){
    Gson gson = Converters.registerDateTime(new GsonBuilder()).setPrettyPrinting().create();
    String json = gson.toJson(this);

    try {
        FileWriter writer = new FileWriter(this.relativePathAndFileName);
        writer.write (json);
        writer.close();
    } catch (IOException e) {
        logger.error("Error while trying to write myAlert to json: ", e);
    }
}
</code>```

Later when I need to read in this json file, I try to do so like this:

```<code>try {
        for (File f : alertConfigFiles) {
            Gson gson = new Gson();
            JsonReader reader = new JsonReader(new FileReader(f));
            Type type = new TypeToken<Map<String, String>>(){}.getType();
            Map<String, String> myMap = gson.fromJson(reader, type);
            Alert tempAlert = new Alert(myMap);
            myAlerts.add(tempAlert);
            logger.debug("Imported: " + f.toString());
        }
</code>```

The error that I'm getting is:

```<code>Unhandled exception when trying to import config files:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 28 column 13 path $.
</code>```

The JSON inside the file is something to the effect of:

```<code> {
 "name": "Logs Per Host - past 24 hours",
 "relativePathAndFileName": "./Elk-Reporting/Alerts/logs_per_host24h.json",
 "next_Run": "2017-06-07T22:24:56.682-04:00",
 "hosts": [
    "app-12c",
    "app1-18",
    "wp-01",
    "app-02",
    "wp-02",
    "cent-04",
    "app-06",
    "app-05"
  ]
  }
</code>```

It seems to be choking when it tries to import the ArrayList of hosts, but it was able to write them out without issues.

Can anyone offer some advice on how to get my import working without issues?

答:
Those two lines seem to be the problem:

```<code>Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(reader, type);
</code>```

You serialize your object of some specific class. You then deserialize it to type. But your JSON does not fit into a Map. Better do it like this, so you can use your own class.

```<code>YourClass myMap = gson.fromJson(reader, YourClass.class);
</code>```

If you want to use this approach, you might want to change your Java class to hold an array of strings instead of an ArrayList of strings.

Maybe this page helps you a bit. Especially the first case fits your situation.

Another option is a custom Deserialzer as described here.

Body:
So I have an object with some fields...

protected String name;
protected String relativePathAndFileName;
protected DateTime next_Run;
protected ArrayList<String> hosts;

Which gets serialized to JSON like this:

public void serialize(){
    Gson gson = Converters.registerDateTime(new GsonBuilder()).setPrettyPrinting().create();
    String json = gson.toJson(this);

    try {
        FileWriter writer = new FileWriter(this.relativePathAndFileName);
        writer.write (json);
        writer.close();
    } catch (IOException e) {
        logger.error("Error while trying to write myAlert to json: ", e);
    }
}

Later when I need to read in this json file, I try to do so like this:

try {
        for (File f : alertConfigFiles) {
            Gson gson = new Gson();
            JsonReader reader = new JsonReader(new FileReader(f));
            Type type = new TypeToken<Map<String, String>>(){}.getType();
            Map<String, String> myMap = gson.fromJson(reader, type);
            Alert tempAlert = new Alert(myMap);
            myAlerts.add(tempAlert);
            logger.debug("Imported: " + f.toString());
        }

The error that I'm getting is:

Unhandled exception when trying to import config files:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 28 column 13 path $.

The JSON inside the file is something to the effect of:

 {
 "name": "Logs Per Host - past 24 hours",
 "relativePathAndFileName": "./Elk-Reporting/Alerts/logs_per_host24h.json",
 "next_Run": "2017-06-07T22:24:56.682-04:00",
 "hosts": [
    "app-12c",
    "app1-18",
    "wp-01",
    "app-02",
    "wp-02",
    "cent-04",
    "app-06",
    "app-05"
  ]
  }

It seems to be choking when it tries to import the ArrayList of hosts, but it was able to write them out without issues.

Can anyone offer some advice on how to get my import working without issues?

Body:
Those two lines seem to be the problem:

Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(reader, type);

You serialize your object of some specific class. You then deserialize it to type. But your JSON does not fit into a Map. Better do it like this, so you can use your own class.

YourClass myMap = gson.fromJson(reader, YourClass.class);

If you want to use this approach, you might want to change your Java class to hold an array of strings instead of an ArrayList of strings.

Maybe this page helps you a bit. Especially the first case fits your situation.

Another option is a custom Deserialzer as described here.


问:
How to have different colors for different value range in simple Google Line Charts?
Here is my JS Fiddle. From the values I have specified in the Y-Axis, 0, 10, 23, 17, 18 etc, I want the line from 0-10 to have a different color, 10-23 to have a different color, 23-17 a different color.

https://jsfiddle.net/pyvqcbou/

Here is my JS. I tried adding colors to various places but I was unable to do so. How do I go about it?

```<code>function drawBasic() {
     var data = new google.visualization.DataTable();
     data.addColumn('number', '');
     data.addColumn('number', '');
     data.addRows([
        [0, 0],   [1, 10],  [2, 23],  [3, 17],  [4, 18],  [5, 9],
      ]);

     var options = {
          height: 152,
          legend: 'none',
          baselineColor: '#fff',
          gridlineColor: '#fff',
          textPosition: 'none',
          colors: ['#ff926c'],
          dataOpacity: 0.7,
          hAxis: {
            textPosition: 'none'
           },
           vAxis: {
              textPosition: 'none',
            },
      };

     var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
     chart.draw(data, options);
    }
</code>```

答:
use a style column, see following working snippet...

google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawBasic);

function drawBasic() {

     var data = new google.visualization.DataTable();
      data.addColumn('number', '');
      data.addColumn('number', '');
      data.addColumn({type: 'string', role: 'style'});

     data.addRows([
        [0, 0, 'red'],   [1, 10, 'blue'],  [2, 23, 'green'],  [3, 17, 'orange'],  [4, 18, 'purple'],  [5, 9, 'black'],
      ]);

     var options = {
          height: 152,
          legend: 'none',
          baselineColor: '#fff',
          gridlineColor: '#fff',
          textPosition: 'none',
          colors: ['#ff926c'],
          dataOpacity: 0.7,
          hAxis: {
            textPosition: 'none'
           },
           vAxis: {
              textPosition: 'none',
            },
      };

     var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

     chart.draw(data, options);
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <div id="chart_div"></div>
      </code>```

Body:
Here is my JS Fiddle. From the values I have specified in the Y-Axis, 0, 10, 23, 17, 18 etc, I want the line from 0-10 to have a different color, 10-23 to have a different color, 23-17 a different color.

https://jsfiddle.net/pyvqcbou/

Here is my JS. I tried adding colors to various places but I was unable to do so. How do I go about it?

function drawBasic() {
     var data = new google.visualization.DataTable();
     data.addColumn('number', '');
     data.addColumn('number', '');
     data.addRows([
        [0, 0],   [1, 10],  [2, 23],  [3, 17],  [4, 18],  [5, 9],
      ]);

     var options = {
          height: 152,
          legend: 'none',
          baselineColor: '#fff',
          gridlineColor: '#fff',
          textPosition: 'none',
          colors: ['#ff926c'],
          dataOpacity: 0.7,
          hAxis: {
            textPosition: 'none'
           },
           vAxis: {
              textPosition: 'none',
            },
      };

     var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
     chart.draw(data, options);
    }

Body:
use a style column, see following working snippet...

google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawBasic);

function drawBasic() {

     var data = new google.visualization.DataTable();
      data.addColumn('number', '');
      data.addColumn('number', '');
      data.addColumn({type: 'string', role: 'style'});

     data.addRows([
        [0, 0, 'red'],   [1, 10, 'blue'],  [2, 23, 'green'],  [3, 17, 'orange'],  [4, 18, 'purple'],  [5, 9, 'black'],
      ]);

     var options = {
          height: 152,
          legend: 'none',
          baselineColor: '#fff',
          gridlineColor: '#fff',
          textPosition: 'none',
          colors: ['#ff926c'],
          dataOpacity: 0.7,
          hAxis: {
            textPosition: 'none'
           },
           vAxis: {
              textPosition: 'none',
            },
      };

     var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

     chart.draw(data, options);
    }

  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <div id="chart_div"></div>