问:
URL decode in iOS
I am using Swift 1.2 to develop my iPhone application and I am communicating with a http web service.

The response I am getting is in query string format (key-value pairs) and URL encoded in .Net.

I can get the response, but looking the proper way to decode using Swift.

Sample response is as follows

```<code>status=1&message=The+transaction+for+GBP+12.50+was+successful
</code>```

Tried following way to decode and get the server response

```<code>// This provides encoded response String
var responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
var decodedResponse = responseString.stringByReplacingEscapesUsingEncoding(NSUTF8StringEncoding)!
</code>```

How can I replace all URL escaped characters in the string?

答:
You only need: </p>

```<code>print("Decode: ", yourUrlAsString.removingPercentEncoding)
</code>```

Title: URL decode in iOS

Body:
I am using Swift 1.2 to develop my iPhone application and I am communicating with a http web service.

The response I am getting is in query string format (key-value pairs) and URL encoded in .Net.

I can get the response, but looking the proper way to decode using Swift.

Sample response is as follows

status=1&message=The+transaction+for+GBP+12.50+was+successful

Tried following way to decode and get the server response

// This provides encoded response String
var responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
var decodedResponse = responseString.stringByReplacingEscapesUsingEncoding(NSUTF8StringEncoding)!

How can I replace all URL escaped characters in the string?

Body:
You only need:

print("Decode: ", yourUrlAsString.removingPercentEncoding)


来源: stackexchange

问:
Export data from DynamoDB
Is it possible to export data from DynamoDB table in some format?

The concrete use case is that I want to export data from my production dynamodb database and import that data into my local dynamodb instance so my application can work with local copy of data instead of production data.

I use the standard DynamoDB-local as a local instance of DynamoDB.

答:
I extend Valy dia solution to allow all the process of exporting with only aws-cli | jq

aws dynamodb scan --max-items 25 --table-name <TABLE_NAME> \
| jq '{"<TABLE_NAME>": [.Items[] | {PutRequest: {Item: .}}]}' > data.json

aws dynamodb describe-table --table-name <TABLE_NAME> > describe.json | jq ' .Table | {"TableName": .TableName, "KeySchema": .KeySchema, "AttributeDefinitions": .AttributeDefinitions,  "ProvisionedThroughput": {
      "ReadCapacityUnits": 5,
      "WriteCapacityUnits": 5
}}' > table-definition.json

aws dynamodb create-table --cli-input-json file://table-definition.json  --endpoint-url http://localhost:8000 --region us-east-1

aws dynamodb batch-write-item --request-items file://data.json --endpoint-url http://localhost:8000

aws dynamodb scan --table-name <TABLE_NAME> --endpoint-url http://localhost:8000
```

ContentLicense: CC BY-SA 4.0

Title: Export data from DynamoDB


问:
How to implement CRC-10 algorithm
I'm trying to implement a 10-bit CRC with a polynomial of 0x633. I've scoured through countless pages but not much is written on CRC-10.

I've written some sample code that seems to calculate it just fine. I can run some test data through to get a CRC then run the data + CRC back through to get 0, which is expect. The problem is that we're testing it against this calculator and getting incongruent results: http://www.ghsi.de/pages/subpages/Online%20CRC%20Calculation/indexDetails.php?Polynom=11000110011&Message=1f+ff+30+04+05+34+a7. This includes the poly and test data. The result from this calculator is "0x10e" while mine is "0x3b1".

Here is the code, modified from https://cs.fit.edu/code/svn/cse2410f13team7/wireshark/wsutil/crc10.c:

```<code>#include <stdio.h>
#include <stdint.h>

uint16_t GetCRC10(uint16_t crc10, const uint8_t *data_blk_ptr, int data_blk_size);

static const uint16_t byte_crc10_table[256] = {
    0x0000, 0x0233, 0x0255, 0x0066, 0x0299, 0x00aa, 0x00cc, 0x02ff,
    0x0301, 0x0132, 0x0154, 0x0367, 0x0198, 0x03ab, 0x03cd, 0x01fe,
    0x0031, 0x0202, 0x0264, 0x0057, 0x02a8, 0x009b, 0x00fd, 0x02ce,
    0x0330, 0x0103, 0x0165, 0x0356, 0x01a9, 0x039a, 0x03fc, 0x01cf,
    0x0062, 0x0251, 0x0237, 0x0004, 0x02fb, 0x00c8, 0x00ae, 0x029d,
    0x0363, 0x0150, 0x0136, 0x0305, 0x01fa, 0x03c9, 0x03af, 0x019c,
    0x0053, 0x0260, 0x0206, 0x0035, 0x02ca, 0x00f9, 0x009f, 0x02ac,
    0x0352, 0x0161, 0x0107, 0x0334, 0x01cb, 0x03f8, 0x039e, 0x01ad,
    0x00c4, 0x02f7, 0x0291, 0x00a2, 0x025d, 0x006e, 0x0008, 0x023b,
    0x03c5, 0x01f6, 0x0190, 0x03a3, 0x015c, 0x036f, 0x0309, 0x013a,
    0x00f5, 0x02c6, 0x02a0, 0x0093, 0x026c, 0x005f, 0x0039, 0x020a,
    0x03f4, 0x01c7, 0x01a1, 0x0392, 0x016d, 0x035e, 0x0338, 0x010b,
    0x00a6, 0x0295, 0x02f3, 0x00c0, 0x023f, 0x000c, 0x006a, 0x0259,
    0x03a7, 0x0194, 0x01f2, 0x03c1, 0x013e, 0x030d, 0x036b, 0x0158,
    0x0097, 0x02a4, 0x02c2, 0x00f1, 0x020e, 0x003d, 0x005b, 0x0268,
    0x0396, 0x01a5, 0x01c3, 0x03f0, 0x010f, 0x033c, 0x035a, 0x0169,
    0x0188, 0x03bb, 0x03dd, 0x01ee, 0x0311, 0x0122, 0x0144, 0x0377,
    0x0289, 0x00ba, 0x00dc, 0x02ef, 0x0010, 0x0223, 0x0245, 0x0076,
    0x01b9, 0x038a, 0x03ec, 0x01df, 0x0320, 0x0113, 0x0175, 0x0346,
    0x02b8, 0x008b, 0x00ed, 0x02de, 0x0021, 0x0212, 0x0274, 0x0047,
    0x01ea, 0x03d9, 0x03bf, 0x018c, 0x0373, 0x0140, 0x0126, 0x0315,
    0x02eb, 0x00d8, 0x00be, 0x028d, 0x0072, 0x0241, 0x0227, 0x0014,
    0x01db, 0x03e8, 0x038e, 0x01bd, 0x0342, 0x0171, 0x0117, 0x0324,
    0x02da, 0x00e9, 0x008f, 0x02bc, 0x0043, 0x0270, 0x0216, 0x0025,
    0x014c, 0x037f, 0x0319, 0x012a, 0x03d5, 0x01e6, 0x0180, 0x03b3,
    0x024d, 0x007e, 0x0018, 0x022b, 0x00d4, 0x02e7, 0x0281, 0x00b2,
    0x017d, 0x034e, 0x0328, 0x011b, 0x03e4, 0x01d7, 0x01b1, 0x0382,
    0x027c, 0x004f, 0x0029, 0x021a, 0x00e5, 0x02d6, 0x02b0, 0x0083,
    0x012e, 0x031d, 0x037b, 0x0148, 0x03b7, 0x0184, 0x01e2, 0x03d1,
    0x022f, 0x001c, 0x007a, 0x0249, 0x00b6, 0x0285, 0x02e3, 0x00d0,
    0x011f, 0x032c, 0x034a, 0x0179, 0x0386, 0x01b5, 0x01d3, 0x03e0,
    0x021e, 0x002d, 0x004b, 0x0278, 0x0087, 0x02b4, 0x02d2, 0x00e1
};

/* update the data block's CRC-10 remainder one byte at a time */
uint16_t GetCRC10(uint16_t crc10, const uint8_t *data_blk_ptr, int data_blk_size)
{
    register int i;
    uint16_t crc10_accum = 0;

    for (i = 0;  i < data_blk_size; i++) {
        crc10_accum = ((crc10_accum << 8) & 0x3ff)
        ^ byte_crc10_table[( crc10_accum >> 2) & 0xff]
        ^ *data_blk_ptr++;
    }
    crc10_accum = ((crc10_accum << 8) & 0x3ff)
        ^ byte_crc10_table[( crc10_accum >> 2) & 0xff]
        ^ (crc10>>2);
    crc10_accum = ((crc10_accum << 8) & 0x3ff)
        ^ byte_crc10_table[( crc10_accum >> 2) & 0xff]
        ^ ((crc10<<6) & 0xFF);

    return crc10_accum;
}

#define TEST_DATA_SIZE    9

void main()
{
  uint8_t test_input_data[TEST_DATA_SIZE] = {0x1f, 0xff, 0x30, 0x4, 0x5, 0x34, 0xa7, 0x0, 0x0};
  uint16_t crc;
  uint16_t crc_final;

  GenerateCRC10Table();
  crc = GetCRC10(0, test_input_data, TEST_DATA_SIZE-2);
  test_input_data[TEST_DATA_SIZE-2] ^= crc >> 8;
  test_input_data[TEST_DATA_SIZE-1] ^= crc & 0xFF;

  printf("%x\n", crc); // Error here. This crc doesn't match with the calculator.

  crc_final = GetCRC10(0, test_input_data, TEST_DATA_SIZE);

  if (crc_final == 0)
  {
    printf("Success");
  }
}
</code>```

This is the function used to produce the lookup table:

```<code>#define POLYNOMIAL 0x633

static uint16_t byte_crc10_table[256];

void gen_byte_crc10_table(void)
/* generate the table of CRC-10 remainders for all possible bytes */
{
    register int i, j;
    register unsigned short crc10_accum;

    for ( i = 0;  i < 256;  i++ )
    {
        crc10_accum = ((unsigned short) i << 2);
        for ( j = 0;  j < 8;  j++ )
        {
            if ((crc10_accum <<= 1) & 0x400) crc10_accum ^= POLYNOMIAL;
        }
        byte_crc10_table[i] = crc10_accum;
    }
    return;
}
</code>```

I've tried this with the 0x233 normal polynomial form as well.

Is this even possible? In essence, I'm tying to bitwise operations on a complete array of bytes. I suspect the problem is that the calculator does it bit-by-bit and mine is byte-by-byte. Since the poly is 10 bits wide, it doesn't work cleanly with uint8s. I'd really appreciate some feedback. Thanks.

Does it make sense that the calculator CRC and my CRC are different because of the 10 bit polynomial and 8 bit data difference?

答:
The code in the question is implementing CRC-10/ATM, which includes 6 padded 0 bits after the bytes of data and before the 10 bit CRC. For the example data in the question:

```<code>1f ff 30 04 05 34 a7
</code>```

It should be getting 0x3b1, which is what the code you posted generates.

Alternate implementation, also results in 0x3b1 for the example case you posted, and both the questions code and this alternate implementation match the examples from CRC-10/ATM :

```<code>typedef unsigned char   uint8_t;
typedef unsigned short uint16_t;

#define CRC10 (0x233<<6)

static uint16_t crctbl[256];

void gentbl(void)
{
uint16_t crc;
uint16_t c;
uint16_t i;
    for(c = 0; c < 0x100; c++){
        crc = c << 8;
        for(i = 0; i < 8; i++)
            /* assumes twos complement */
            crc = (crc<<1)^((0-(crc>>15))&CRC10);
        crctbl[c] = crc;
    }
}

uint16_t crc10(uint8_t * bfr, int len)
{
uint16_t crc = 0x0000;
    while(len--){
        /* shifting 6 bits instead of 8 will leave crc cycled -2 bits when done */
        crc ^= ((uint16_t)(*bfr++))<<6;     /* xor byte<<6 into crc */
        crc  = (crc<<8)^crctbl[(crc>>8)];   /* cycle crc */
    }
    /* At this point, crc is cycled -2 bits, meaning that */
    /* 2 bit of data have not been cycled yet,  so cycle */
    /* 8 bits to cycle the 2 bits of data and 6 padding bits of 0 */
    crc = (crc<<8)^crctbl[(crc>>8)];        /* cycle crc +8 bits */
    return(crc>>6);                         /* return 10 bit crc */
}
</code>```

Test code:

```<code>#include <stdio.h>

/* test messages including 10 bit CRC */
static uint8_t tst1[] =
   {0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0xf6};

static uint8_t tst2[] =
   {0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x6B};

static uint8_t tst3[] =
   {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
    0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
    0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x03,0x0F};

static uint8_t tst4[] =
   {0x12,0x34,0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,
    0x34,0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,0x34,
    0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,0x02,0xED};

static uint8_t tst5[] =
   {0x10,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,
    0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,
    0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x03,0xB9};

static uint8_t tst6[] =
   {0x18,0x01,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
    0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0x00,0x00,0x00,0x00,0x00,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x00,0x4A};

static uint8_t* ptst[6] = {tst1, tst2, tst3, tst4, tst5, tst6};

/* length of msgs including crc */
#define LEN (48)

int main(void)
{
uint16_t crc;
int i;
    gentbl();
    for(i = 0; i < (sizeof(ptst)/sizeof(ptst[0])); i++){
        crc = crc10(ptst[i], LEN-2);            /* generate a 10 bit CRC */
        if((crc>>8)   != ptst[i][LEN-2] ||      /* verify it matches test CRC */
           (crc&0xff) != ptst[i][LEN-1])
            break;
        crc = crc10(ptst[i], LEN);              /* verify CRC == 0 */
        if(0 != crc)
            break;
    }
    if(i == 6)
        printf("passed\n");
    else
        printf("error\n");
    return 0;
}
</code>```

Title: How to implement CRC-10 algorithm

Body:
I'm trying to implement a 10-bit CRC with a polynomial of 0x633. I've scoured through countless pages but not much is written on CRC-10.

I've written some sample code that seems to calculate it just fine. I can run some test data through to get a CRC then run the data + CRC back through to get 0, which is expect. The problem is that we're testing it against this calculator and getting incongruent results: http://www.ghsi.de/pages/subpages/Online%20CRC%20Calculation/indexDetails.php?Polynom=11000110011&Message=1f+ff+30+04+05+34+a7. This includes the poly and test data. The result from this calculator is "0x10e" while mine is "0x3b1".

Here is the code, modified from https://cs.fit.edu/code/svn/cse2410f13team7/wireshark/wsutil/crc10.c:

#include <stdio.h>
#include <stdint.h>

uint16_t GetCRC10(uint16_t crc10, const uint8_t *data_blk_ptr, int data_blk_size);

static const uint16_t byte_crc10_table[256] = {
    0x0000, 0x0233, 0x0255, 0x0066, 0x0299, 0x00aa, 0x00cc, 0x02ff,
    0x0301, 0x0132, 0x0154, 0x0367, 0x0198, 0x03ab, 0x03cd, 0x01fe,
    0x0031, 0x0202, 0x0264, 0x0057, 0x02a8, 0x009b, 0x00fd, 0x02ce,
    0x0330, 0x0103, 0x0165, 0x0356, 0x01a9, 0x039a, 0x03fc, 0x01cf,
    0x0062, 0x0251, 0x0237, 0x0004, 0x02fb, 0x00c8, 0x00ae, 0x029d,
    0x0363, 0x0150, 0x0136, 0x0305, 0x01fa, 0x03c9, 0x03af, 0x019c,
    0x0053, 0x0260, 0x0206, 0x0035, 0x02ca, 0x00f9, 0x009f, 0x02ac,
    0x0352, 0x0161, 0x0107, 0x0334, 0x01cb, 0x03f8, 0x039e, 0x01ad,
    0x00c4, 0x02f7, 0x0291, 0x00a2, 0x025d, 0x006e, 0x0008, 0x023b,
    0x03c5, 0x01f6, 0x0190, 0x03a3, 0x015c, 0x036f, 0x0309, 0x013a,
    0x00f5, 0x02c6, 0x02a0, 0x0093, 0x026c, 0x005f, 0x0039, 0x020a,
    0x03f4, 0x01c7, 0x01a1, 0x0392, 0x016d, 0x035e, 0x0338, 0x010b,
    0x00a6, 0x0295, 0x02f3, 0x00c0, 0x023f, 0x000c, 0x006a, 0x0259,
    0x03a7, 0x0194, 0x01f2, 0x03c1, 0x013e, 0x030d, 0x036b, 0x0158,
    0x0097, 0x02a4, 0x02c2, 0x00f1, 0x020e, 0x003d, 0x005b, 0x0268,
    0x0396, 0x01a5, 0x01c3, 0x03f0, 0x010f, 0x033c, 0x035a, 0x0169,
    0x0188, 0x03bb, 0x03dd, 0x01ee, 0x0311, 0x0122, 0x0144, 0x0377,
    0x0289, 0x00ba, 0x00dc, 0x02ef, 0x0010, 0x0223, 0x0245, 0x0076,
    0x01b9, 0x038a, 0x03ec, 0x01df, 0x0320, 0x0113, 0x0175, 0x0346,
    0x02b8, 0x008b, 0x00ed, 0x02de, 0x0021, 0x0212, 0x0274, 0x0047,
    0x01ea, 0x03d9, 0x03bf, 0x018c, 0x0373, 0x0140, 0x0126, 0x0315,
    0x02eb, 0x00d8, 0x00be, 0x028d, 0x0072, 0x0241, 0x0227, 0x0014,
    0x01db, 0x03e8, 0x038e, 0x01bd, 0x0342, 0x0171, 0x0117, 0x0324,
    0x02da, 0x00e9, 0x008f, 0x02bc, 0x0043, 0x0270, 0x0216, 0x0025,
    0x014c, 0x037f, 0x0319, 0x012a, 0x03d5, 0x01e6, 0x0180, 0x03b3,
    0x024d, 0x007e, 0x0018, 0x022b, 0x00d4, 0x02e7, 0x0281, 0x00b2,
    0x017d, 0x034e, 0x0328, 0x011b, 0x03e4, 0x01d7, 0x01b1, 0x0382,
    0x027c, 0x004f, 0x0029, 0x021a, 0x00e5, 0x02d6, 0x02b0, 0x0083,
    0x012e, 0x031d, 0x037b, 0x0148, 0x03b7, 0x0184, 0x01e2, 0x03d1,
    0x022f, 0x001c, 0x007a, 0x0249, 0x00b6, 0x0285, 0x02e3, 0x00d0,
    0x011f, 0x032c, 0x034a, 0x0179, 0x0386, 0x01b5, 0x01d3, 0x03e0,
    0x021e, 0x002d, 0x004b, 0x0278, 0x0087, 0x02b4, 0x02d2, 0x00e1
};

/* update the data block's CRC-10 remainder one byte at a time */
uint16_t GetCRC10(uint16_t crc10, const uint8_t *data_blk_ptr, int data_blk_size)
{
    register int i;
    uint16_t crc10_accum = 0;

    for (i = 0;  i < data_blk_size; i++) {
        crc10_accum = ((crc10_accum << 8) & 0x3ff)
        ^ byte_crc10_table[( crc10_accum >> 2) & 0xff]
        ^ *data_blk_ptr++;
    }
    crc10_accum = ((crc10_accum << 8) & 0x3ff)
        ^ byte_crc10_table[( crc10_accum >> 2) & 0xff]
        ^ (crc10>>2);
    crc10_accum = ((crc10_accum << 8) & 0x3ff)
        ^ byte_crc10_table[( crc10_accum >> 2) & 0xff]
        ^ ((crc10<<6) & 0xFF);

    return crc10_accum;
}

#define TEST_DATA_SIZE    9

void main()
{
  uint8_t test_input_data[TEST_DATA_SIZE] = {0x1f, 0xff, 0x30, 0x4, 0x5, 0x34, 0xa7, 0x0, 0x0};
  uint16_t crc;
  uint16_t crc_final;

  GenerateCRC10Table();
  crc = GetCRC10(0, test_input_data, TEST_DATA_SIZE-2);
  test_input_data[TEST_DATA_SIZE-2] ^= crc >> 8;
  test_input_data[TEST_DATA_SIZE-1] ^= crc & 0xFF;

  printf("%x\n", crc); // Error here. This crc doesn't match with the calculator.

  crc_final = GetCRC10(0, test_input_data, TEST_DATA_SIZE);

  if (crc_final == 0)
  {
    printf("Success");
  }
}

This is the function used to produce the lookup table:

#define POLYNOMIAL 0x633

static uint16_t byte_crc10_table[256];

void gen_byte_crc10_table(void)
/* generate the table of CRC-10 remainders for all possible bytes */
{
    register int i, j;
    register unsigned short crc10_accum;

    for ( i = 0;  i < 256;  i++ )
    {
        crc10_accum = ((unsigned short) i << 2);
        for ( j = 0;  j < 8;  j++ )
        {
            if ((crc10_accum <<= 1) & 0x400) crc10_accum ^= POLYNOMIAL;
        }
        byte_crc10_table[i] = crc10_accum;
    }
    return;
}

I've tried this with the 0x233 normal polynomial form as well.

Is this even possible? In essence, I'm tying to bitwise operations on a complete array of bytes. I suspect the problem is that the calculator does it bit-by-bit and mine is byte-by-byte. Since the poly is 10 bits wide, it doesn't work cleanly with uint8s. I'd really appreciate some feedback. Thanks.

Does it make sense that the calculator CRC and my CRC are different because of the 10 bit polynomial and 8 bit data difference?

Body:
The code in the question is implementing CRC-10/ATM, which includes 6 padded 0 bits after the bytes of data and before the 10 bit CRC. For the example data in the question:

1f ff 30 04 05 34 a7

It should be getting 0x3b1, which is what the code you posted generates.

Alternate implementation, also results in 0x3b1 for the example case you posted, and both the questions code and this alternate implementation match the examples from CRC-10/ATM :

typedef unsigned char   uint8_t;
typedef unsigned short uint16_t;

#define CRC10 (0x233<<6)

static uint16_t crctbl[256];

void gentbl(void)
{
uint16_t crc;
uint16_t c;
uint16_t i;
    for(c = 0; c < 0x100; c++){
        crc = c << 8;
        for(i = 0; i < 8; i++)
            /* assumes twos complement */
            crc = (crc<<1)^((0-(crc>>15))&CRC10);
        crctbl[c] = crc;
    }
}

uint16_t crc10(uint8_t * bfr, int len)
{
uint16_t crc = 0x0000;
    while(len--){
        /* shifting 6 bits instead of 8 will leave crc cycled -2 bits when done */
        crc ^= ((uint16_t)(*bfr++))<<6;     /* xor byte<<6 into crc */
        crc  = (crc<<8)^crctbl[(crc>>8)];   /* cycle crc */
    }
    /* At this point, crc is cycled -2 bits, meaning that */
    /* 2 bit of data have not been cycled yet,  so cycle */
    /* 8 bits to cycle the 2 bits of data and 6 padding bits of 0 */
    crc = (crc<<8)^crctbl[(crc>>8)];        /* cycle crc +8 bits */
    return(crc>>6);                         /* return 10 bit crc */
}

Test code:

#include <stdio.h>

/* test messages including 10 bit CRC */
static uint8_t tst1[] =
   {0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0xf6};

static uint8_t tst2[] =
   {0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x6B};

static uint8_t tst3[] =
   {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
    0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
    0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x03,0x0F};

static uint8_t tst4[] =
   {0x12,0x34,0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,
    0x34,0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,0x34,
    0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,0x34,0x56,0x78,0x90,0x12,0x02,0xED};

static uint8_t tst5[] =
   {0x10,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,
    0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,
    0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x03,0xB9};

static uint8_t tst6[] =
   {0x18,0x01,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
    0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0x00,0x00,0x00,0x00,0x00,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x6A,0x00,0x4A};

static uint8_t* ptst[6] = {tst1, tst2, tst3, tst4, tst5, tst6};

/* length of msgs including crc */
#define LEN (48)

int main(void)
{
uint16_t crc;
int i;
    gentbl();
    for(i = 0; i < (sizeof(ptst)/sizeof(ptst[0])); i++){
        crc = crc10(ptst[i], LEN-2);            /* generate a 10 bit CRC */
        if((crc>>8)   != ptst[i][LEN-2] ||      /* verify it matches test CRC */
           (crc&0xff) != ptst[i][LEN-1])
            break;
        crc = crc10(ptst[i], LEN);              /* verify CRC == 0 */
        if(0 != crc)
            break;
    }
    if(i == 6)
        printf("passed\n");
    else
        printf("error\n");
    return 0;
}


问:
Custom HTML - SSRS
I am trying to write out custom HTML in an SSRS report.  If I try to put the html in a placeholder (selecting Markup type = "HTML - Interpret HTML tags as styles"), SSRS will strip out any unsupported tags.  Therefore, I am trying to write it out in custom code.  My expression is as follows:

```<code>=Code.WriteHTML("<b>ryantest</b>")
</code>```

My custom code is as follows:

```<code>Function WriteHTML(ByVal Msg As String) As String
If Not (IsNothing(System.Web.HttpContext.Current)) Then
                System.Web.HttpContext.Current.Response.Write(Msg)
End If
End Function
</code>```

When I try to view the report, I get the following error:

```<code>An error occurred during client rendering.
Exception of type 'System.OutOfMemoryException' was thrown.
</code>```

Any ideas?

答:
I take it you've added a reference to that assembly to the report, otherwise it would probably throw some other error.

What about permissions? You need to do something funky to call outside assemblies from SSRS custom code.

PS: I've never seen anyone call that assembly from custom code. Cool hack.

ContentLicense: CC BY-SA 3.0

Title: Custom HTML - SSRS

Body:
I am trying to write out custom HTML in an SSRS report.  If I try to put the html in a placeholder (selecting Markup type = "HTML - Interpret HTML tags as styles"), SSRS will strip out any unsupported tags.  Therefore, I am trying to write it out in custom code.  My expression is as follows:

=Code.WriteHTML("ryantest")

My custom code is as follows:

Function WriteHTML(ByVal Msg As String) As String
If Not (IsNothing(System.Web.HttpContext.Current)) Then
                System.Web.HttpContext.Current.Response.Write(Msg)
End If
End Function

When I try to view the report, I get the following error:

An error occurred during client rendering.
Exception of type 'System.OutOfMemoryException' was thrown.

Any ideas?


问:
run `nvm use` automatically every time there's a .nvmrc file on the directory
How to configure my shell so that nvm use run automatically every time there's a .nvmrc file on the directory and use the latest version or a global config when there's no .nvmrc file?

答:
Yet another solution using direnv. Direnv comes with OS X and many distros so no installation is needed.

Add these two lines to your .zshenv or .bash_profile depending on which shell you use:

export NVM_DIR="$HOME/.nvm" # You probably have this line already
export NODE_VERSIONS="${NVM_DIR}/versions/node"
export NODE_VERSION_PREFIX="v"
```

<p>Add an .envrc file to the project root with the contents</p>

```set -e
use node
```

Finally cd to your directory. (Don't forget to source .zshenv)

direnv will ask you to allow load config.
Type direnv allow and voila!

Note that direnv doesn't support fancy constructs like lts/* in .nvrmc. On the positive side, direnv supports a bunch of runtimes like node, php, go, pyhton, ruby etc. allowing us to use a single tool to solve path issues.

Body:
Yet another solution using direnv. Direnv comes with OS X and many distros so no installation is needed.

Add these two lines to your .zshenv or .bash_profile depending on which shell you use:

export NVM_DIR="$HOME/.nvm" # You probably have this line already
export NODE_VERSIONS="${NVM_DIR}/versions/node"
export NODE_VERSION_PREFIX="v"

Add an .envrc file to the project root with the contents

set -e
use node

Finally cd to your directory. (Don't forget to source .zshenv)

direnv will ask you to allow load config.
Type direnv allow and voila!

Note that direnv doesn't support fancy constructs like lts/* in .nvrmc. On the positive side, direnv supports a bunch of runtimes like node, php, go, pyhton, ruby etc. allowing us to use a single tool to solve path issues.


问:
How to Pass data between Screen when Icon is pressed
I am working on a project where When I Press Bookmark Icon The Image should pass to the Saved.dart Page. Below code Contain a Bookmark icon. when Ever I press that icon it should pass the image to saved.dart page but it should not push(Should no open Saved.dart page when pressed) to Saved.dart Page.

```<code>import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:image_downloader/image_downloader.dart';
import 'downloadingPage.dart';

class FullScreen extends StatefulWidget {
  String imgUrl;
  FullScreen({this.imgUrl});

  @override
  FullScreenState createState() => FullScreenState(imgUrl);
}

class FullScreenState extends State<FullScreen> {
  Color colour = Colors.black;
  Color colour2 = Colors.red;
  Color colour3 = Colors.black;
  bool isSaved = false;

  String imgUrl;
  FullScreenState(this.imgUrl);

  String message = "";
  String path = "";
  int _progress = 0;

  @override
  void initState() {
    super.initState();
    events = new StreamController<int>.broadcast();

    events.add(0);

    ImageDownloader.callback(onProgressUpdate: (String imageId, int progress) {
      setState(() {
        print("progress $progress");
        _progress = progress;
        events.add(progress);
        if (progress == 100) {
          Navigator.pop(context);
        }
      });
    });
  }

  @override
  void dispose() {
    events.close();
    super.dispose();
  }

  Future<void> _downloadImage(String url,
      {AndroidDestinationType destination, bool whenError = false}) async {
    String fileName;
    String path;
    try {
      String imageId;

      if (whenError) {
        imageId = await ImageDownloader.downloadImage(url).catchError((error) {
          if (error is PlatformException) {
            var path = "";
            if (error.code == "404") {
              print("Not Found Error.");
            } else if (error.code == "unsupported_file") {
              print("UnSupported FIle Error.");
              path = error.details["unsupported_file_path"];
            }
            setState(() {
              message = error.toString();
              path = path;
            });
          }

          print(error);
        }).timeout(Duration(seconds: 10), onTimeout: () {
          print("timeout");
        });
      } else {
        if (destination == null) {
          imageId = await ImageDownloader.downloadImage(url);
        } else {
          imageId = await ImageDownloader.downloadImage(
            url,
            destination: destination,
          );
        }
      }

      if (imageId == null) {
        print("imageId is null");
        return;
      }
      fileName = await ImageDownloader.findName(imageId);
      path = await ImageDownloader.findPath(imageId);
    } on PlatformException catch (error) {
      setState(() {
        message = error.message;
      });
      return;
    }

    if (!mounted) return;
    setState(() {
      message = 'Image Downloaded';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            RaisedButton(
              onPressed: () {
                events.add(0);
                _downloadImage(imgUrl);
                showDialog(
                  context: context,
                  builder: (_) => FunkyOverlay(
                    progress: _progress,
                    message: message,
                  ),
                );
              },
              child: Text("download"),
            ),
            IconButton(
                icon: Icon(
                  Icons.bookmark,
                  color: colour,
                ),
                onPressed: () {
                <-----when user press this icon the current image shold be passed to saved page----->
                })
          ],
        ),
      ),
    );
  }
}
</code>```

The following code is Saved.dart

```<code>import 'package:flutter/material.dart';

class Saved extends StatefulWidget {
  @override
  _SavedState createState() => _SavedState();
}

class _SavedState extends State<Saved> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Container(
        // here the images should be displayed
      )
    );
  }
}
</code>```

答:
You can pass arguments when opening a page via named routes:

Named Routes in your app:

```<code>MaterialApp(
  routes: {
    ExtractArgumentsScreen.routeName: (context) => ExtractArgumentsScreen(),
  },
);
</code>```

Pass the argument object, e.g. your image:

```<code>  onPressed: () {
    // When the user taps the button, navigate to a named route
    // and provide the arguments as an optional parameter.
    Navigator.pushNamed(
      context,
      ExtractArgumentsScreen.routeName,
      arguments: ScreenArguments(
        'Extract Arguments Screen',
        'This message is extracted in the build method.',
      ),
    );
  },
</code>```

Receive the argument in your saved.dart page:

```<code>class ExtractArgumentsScreen extends StatelessWidget {
  static const routeName = '/extractArguments';

  @override
  Widget build(BuildContext context) {
    // Extract the arguments from the current ModalRoute settings and cast
    // them as ScreenArguments.
    final ScreenArguments args = ModalRoute.of(context).settings.arguments;

    return Scaffold(
      appBar: AppBar(
        title: Text(args.title),
      ),
      body: Center(
        child: Text(args.message),
      ),
    );
  }
}
</code>```

source: https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments

Body:
I am working on a project where When I Press Bookmark Icon The Image should pass to the Saved.dart Page. Below code Contain a Bookmark icon. when Ever I press that icon it should pass the image to saved.dart page but it should not push(Should no open Saved.dart page when pressed) to Saved.dart Page.

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:image_downloader/image_downloader.dart';
import 'downloadingPage.dart';

class FullScreen extends StatefulWidget {
  String imgUrl;
  FullScreen({this.imgUrl});

  @override
  FullScreenState createState() => FullScreenState(imgUrl);
}

class FullScreenState extends State<FullScreen> {
  Color colour = Colors.black;
  Color colour2 = Colors.red;
  Color colour3 = Colors.black;
  bool isSaved = false;

  String imgUrl;
  FullScreenState(this.imgUrl);

  String message = "";
  String path = "";
  int _progress = 0;

  @override
  void initState() {
    super.initState();
    events = new StreamController<int>.broadcast();

    events.add(0);

    ImageDownloader.callback(onProgressUpdate: (String imageId, int progress) {
      setState(() {
        print("progress $progress");
        _progress = progress;
        events.add(progress);
        if (progress == 100) {
          Navigator.pop(context);
        }
      });
    });
  }

  @override
  void dispose() {
    events.close();
    super.dispose();
  }

  Future<void> _downloadImage(String url,
      {AndroidDestinationType destination, bool whenError = false}) async {
    String fileName;
    String path;
    try {
      String imageId;

      if (whenError) {
        imageId = await ImageDownloader.downloadImage(url).catchError((error) {
          if (error is PlatformException) {
            var path = "";
            if (error.code == "404") {
              print("Not Found Error.");
            } else if (error.code == "unsupported_file") {
              print("UnSupported FIle Error.");
              path = error.details["unsupported_file_path"];
            }
            setState(() {
              message = error.toString();
              path = path;
            });
          }

          print(error);
        }).timeout(Duration(seconds: 10), onTimeout: () {
          print("timeout");
        });
      } else {
        if (destination == null) {
          imageId = await ImageDownloader.downloadImage(url);
        } else {
          imageId = await ImageDownloader.downloadImage(
            url,
            destination: destination,
          );
        }
      }

      if (imageId == null) {
        print("imageId is null");
        return;
      }
      fileName = await ImageDownloader.findName(imageId);
      path = await ImageDownloader.findPath(imageId);
    } on PlatformException catch (error) {
      setState(() {
        message = error.message;
      });
      return;
    }

    if (!mounted) return;
    setState(() {
      message = 'Image Downloaded';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            RaisedButton(
              onPressed: () {
                events.add(0);
                _downloadImage(imgUrl);
                showDialog(
                  context: context,
                  builder: (_) => FunkyOverlay(
                    progress: _progress,
                    message: message,
                  ),
                );
              },
              child: Text("download"),
            ),
            IconButton(
                icon: Icon(
                  Icons.bookmark,
                  color: colour,
                ),
                onPressed: () {
                <-----when user press this icon the current image shold be passed to saved page----->
                })
          ],
        ),
      ),
    );
  }
}

The following code is Saved.dart

import 'package:flutter/material.dart';

class Saved extends StatefulWidget {
  @override
  _SavedState createState() => _SavedState();
}

class _SavedState extends State<Saved> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Container(
        // here the images should be displayed
      )
    );
  }
}

Body:
You can pass arguments when opening a page via named routes:

Named Routes in your app:

MaterialApp(
  routes: {
    ExtractArgumentsScreen.routeName: (context) => ExtractArgumentsScreen(),
  },
);

Pass the argument object, e.g. your image:

  onPressed: () {
    // When the user taps the button, navigate to a named route
    // and provide the arguments as an optional parameter.
    Navigator.pushNamed(
      context,
      ExtractArgumentsScreen.routeName,
      arguments: ScreenArguments(
        'Extract Arguments Screen',
        'This message is extracted in the build method.',
      ),
    );
  },

Receive the argument in your saved.dart page:

class ExtractArgumentsScreen extends StatelessWidget {
  static const routeName = '/extractArguments';

  @override
  Widget build(BuildContext context) {
    // Extract the arguments from the current ModalRoute settings and cast
    // them as ScreenArguments.
    final ScreenArguments args = ModalRoute.of(context).settings.arguments;

    return Scaffold(
      appBar: AppBar(
        title: Text(args.title),
      ),
      body: Center(
        child: Text(args.message),
      ),
    );
  }
}

source: https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments


问:
Apache Flink Table query result as string values
I am writing a query from a flink table api to retrieve a record. Then check if a record was found and if so, get the string value of each of the record's column values.

i.e.

```<code>users:
|id | name | phone |
|---|------|-------|
| 01| sam  | 23354 |
| 02| jake | 23352 |
| 03| kim  | 23351 |
</code>```

Issue is that flink only returns Table from a query so i am not able to 1: check if a record was found and 2: get the individual values of the found record's values

sudo code:

```<code>foundRecord = find record by phone
  if foundRecord {
    create new instance of Visitor
    Visitor.name = foundRecord.name
    Visitor.id = foundRecord.id
  } else {
    throw exception
  }
</code>```

The code below as recommended by flink docs gives me a table but not sure how to implement the above sudo code since it is returning as another table and i need the actual record values.

```<code>Table users = registeredUsers.select("id, name, phone").where("phone === '23354'"));
</code>```

Flink Docs for ref: https://ci.apache.org/projects/flink/flink-docs-stable/dev/table/tableApi.html#expression-syntax

答:
In order to know that a matching record cannot be found, the input must be bounded -- so we'll use a BatchTableEnvironment, and not a StreamTableEnvironment. (With streaming input, a matching record might eventually arrive and satisfy the query. Only with batch input can we prove the absence of a match.)

import org.apache.flink.api.common.functions.FlatMapFunction
import org.apache.flink.api.scala.ExecutionEnvironment
import org.apache.flink.table.api.scala.BatchTableEnvironment
import org.apache.flink.types.Row
import org.apache.flink.api.scala._
import org.apache.flink.table.api.scala._
import org.apache.flink.util.Collector

class MissingResultException() extends Exception {}

object Phone {
  case class Visitor(name: String, id: String)

  @throws[Exception]
  def main(args: Array[String]): Unit = {
    val env = ExecutionEnvironment.getExecutionEnvironment
    val tableEnv = BatchTableEnvironment.create(env)

    val rawInput = env.fromElements(
      ("01", "sam", "23354"),
      ("02", "jake", "23352"),
      ("03", "kim", "23351"))

    val events = tableEnv.fromDataSet(rawInput, 'id, 'name, 'phone)
    tableEnv.registerTable("events", events)
    val resultTable = tableEnv
      .from("events")
      .select('id, 'name, 'phone)
      .where("phone === 'missing'")

    val results = resultTable.toDataSet[Row]

    results
      .map(row => new Visitor(row.getField(1).toString, row.getField(0).toString))
      .print

    val count: DataSet[Long] = env.fromElements(results.count())

    count
      .flatMap(new FlatMapFunction[Long, Collector[Long]]{

        override def flatMap(x: Long, collector: Collector[Collector[Long]]): Unit = {
          if (x == 0L) {
            throw new MissingResultException
          }
        }})

      .print()
  }
}
```

The approach I used to detect that the result set is empty feels like something of a hack, but I couldn't think of anything better. Note that the print() at the very end is necessary, though there's nothing to print, because any computation that isn't ultimately fed to a sink will be optimized away, and not executed.

Body:
I am writing a query from a flink table api to retrieve a record. Then check if a record was found and if so, get the string value of each of the record's column values.

i.e.

users:
|id | name | phone |
|---|------|-------|
| 01| sam  | 23354 |
| 02| jake | 23352 |
| 03| kim  | 23351 |

Issue is that flink only returns Table from a query so i am not able to 1: check if a record was found and 2: get the individual values of the found record's values

sudo code:

foundRecord = find record by phone
  if foundRecord {
    create new instance of Visitor
    Visitor.name = foundRecord.name
    Visitor.id = foundRecord.id
  } else {
    throw exception
  }

The code below as recommended by flink docs gives me a table but not sure how to implement the above sudo code since it is returning as another table and i need the actual record values.

Table users = registeredUsers.select("id, name, phone").where("phone === '23354'"));

Flink Docs for ref: https://ci.apache.org/projects/flink/flink-docs-stable/dev/table/tableApi.html#expression-syntax

Body:
In order to know that a matching record cannot be found, the input must be bounded -- so we'll use a BatchTableEnvironment, and not a StreamTableEnvironment. (With streaming input, a matching record might eventually arrive and satisfy the query. Only with batch input can we prove the absence of a match.)

import org.apache.flink.api.common.functions.FlatMapFunction
import org.apache.flink.api.scala.ExecutionEnvironment
import org.apache.flink.table.api.scala.BatchTableEnvironment
import org.apache.flink.types.Row
import org.apache.flink.api.scala._
import org.apache.flink.table.api.scala._
import org.apache.flink.util.Collector

class MissingResultException() extends Exception {}

object Phone {
  case class Visitor(name: String, id: String)

  @throws[Exception]
  def main(args: Array[String]): Unit = {
    val env = ExecutionEnvironment.getExecutionEnvironment
    val tableEnv = BatchTableEnvironment.create(env)

    val rawInput = env.fromElements(
      ("01", "sam", "23354"),
      ("02", "jake", "23352"),
      ("03", "kim", "23351"))

    val events = tableEnv.fromDataSet(rawInput, 'id, 'name, 'phone)
    tableEnv.registerTable("events", events)
    val resultTable = tableEnv
      .from("events")
      .select('id, 'name, 'phone)
      .where("phone === 'missing'")

    val results = resultTable.toDataSet[Row]

    results
      .map(row => new Visitor(row.getField(1).toString, row.getField(0).toString))
      .print

    val count: DataSet[Long] = env.fromElements(results.count())

    count
      .flatMap(new FlatMapFunction[Long, Collector[Long]]{

        override def flatMap(x: Long, collector: Collector[Collector[Long]]): Unit = {
          if (x == 0L) {
            throw new MissingResultException
          }
        }})

      .print()
  }
}

The approach I used to detect that the result set is empty feels like something of a hack, but I couldn't think of anything better. Note that the print() at the very end is necessary, though there's nothing to print, because any computation that isn't ultimately fed to a sink will be optimized away, and not executed.


问:
Find the two numbers that appear only once - divide and conquer
Given an array in which each element appears twice, I have to find which two numbers of the array appear only once. Maximum additional memory is O(1).

I have found this amazing solution: https://medium.com/@gurupad93/two-numbers-that-appear-once-b89e92a9334b

The problem is that my solution should be divide and conquer, and my understanding is that the solution I found is not.

I know how to solve this problem with divide and conquer when the element appearing once is just one. Here, I wouldn't know how to divide the array recursively to be honest.

Any suggestions?

Thank you so much!

答:
I was able to find an algorithm to my question:

I find the median of the array and use partition to have all the smaller elements on the left of the median and all the greater elements on the right.

I have an algorithm that is able to return when the element appearing once is only one (using XOR on all elements). If there is no element appearing only once, the XOR result is 0.

I run this algorithm on both of the two subarray, two options:

If the algorithm outputs 0 on one array, then for sure the element is not in this subarray, and we call the function recursively on the other half.

If (and only if) the algorithm outputs two numbers different than 0, it means the results got separated in the arrays. In this case, these two numbers will also be the results of the problem.

Note that there are no other options than these two.

Space Complexity is O(1)

Time Complexity: We have some operations that cost O(n), we divide at each iteration half of the array, we get:

T(n) = T(n/2) + O(n) -> (Master Theorem) -> O(n)


问:
Python Pocketsphinx: Keyword not being recognised from a .wav file
I'm trying to detect the keyword temperature from a recording of me only saying the phase temperature (there are no other words present). Originally I used the keyword hello and it worked fine but whenever I try with any other word it does not. My current code is as follows:

```<code>import pocketsphinx as ps
import requests
import json
import sys, os

model_path = ps.get_model_path()
data_path = ps.get_data_path()

# Call to API
def get_temperature():
    headers = {
        'accept': 'application/json',
        'x-api-key': 'REMOVED'
    }

    response = requests.get(url=TEMPERATURE_URL, headers=headers)
    print("Response Code: ", response)

    temperature_data = response.json()
    print(temperature_data)
    temp = temperature_data[0]["value"]
    return temp

print("start")
while True:
    speech = ps.AudioFile(lm=False, kws='keyphrase.list', kws_threshold=1e-1)
    for phrase in speech:
        print("--------------------------------------------------------------")
        print(phrase.segments(detailed=True))
        print(phrase)
        if phrase.__eq__('temperature '):
            print("if equal")
            temperature = get_temperature()
            print("Temperature: ", temperature)
</code>```

The contents of my keyphrase.list file is:

```<code>temperature /1e-1/
</code>```

It currently starts and runs but doesn't detect anything.

Edit: Here is the audio file I am using

答:
Your file has wrong format:

```<code>file client_audio.wav
client_audio.wav: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, 4 channels 20000 Hz
</code>```

You have to convert it to proper format 16 bit mono 16khz before decoding, it wouldn't work otherwise.

In case threshold is small, you can try different threshold values like 1e-10, 1e-20, 1e-30, 1e-40 to balance between detections and false alarms.

Body:
I'm trying to detect the keyword temperature from a recording of me only saying the phase temperature (there are no other words present). Originally I used the keyword hello and it worked fine but whenever I try with any other word it does not. My current code is as follows:

import pocketsphinx as ps
import requests
import json
import sys, os

model_path = ps.get_model_path()
data_path = ps.get_data_path()

# Call to API
def get_temperature():
    headers = {
        'accept': 'application/json',
        'x-api-key': 'REMOVED'
    }

    response = requests.get(url=TEMPERATURE_URL, headers=headers)
    print("Response Code: ", response)

    temperature_data = response.json()
    print(temperature_data)
    temp = temperature_data[0]["value"]
    return temp

print("start")
while True:
    speech = ps.AudioFile(lm=False, kws='keyphrase.list', kws_threshold=1e-1)
    for phrase in speech:
        print("--------------------------------------------------------------")
        print(phrase.segments(detailed=True))
        print(phrase)
        if phrase.__eq__('temperature '):
            print("if equal")
            temperature = get_temperature()
            print("Temperature: ", temperature)

The contents of my keyphrase.list file is:

temperature /1e-1/

It currently starts and runs but doesn't detect anything.

Edit: Here is the audio file I am using

Body:
Your file has wrong format:

file client_audio.wav
client_audio.wav: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, 4 channels 20000 Hz

You have to convert it to proper format 16 bit mono 16khz before decoding, it wouldn't work otherwise.

In case threshold is small, you can try different threshold values like 1e-10, 1e-20, 1e-30, 1e-40 to balance between detections and false alarms.


问:
VS 2010 - copy XSDs when building solution
I have a website (MVC) and some other projects in the same solution.
In one of those separate projects I have some XSDs that I want copied to the bin folder of the website on build.

I have specified the XSDs as content and copy always but they only get copied to that project's bin/debug folder not the bin of the website.

Is there any way of having them copied to the website's bin?

Is it possible to write a post-build script to deploy these files to the project flagged as StartUp in a solution?

The bigger picture - I just want to validate some generated xmls against these XSDs, but dont want to have these XSDs as content in every solution that uses this project.

Cannot use the XSDs as embedded resources because of import statements in the XSDs referencing each other.

答:
I have flagged these XSDs as content and copy always to output folder.
For some reason this doesn't copy them when building/publish the solution on my local machine through VS, but it works when running a TFS build.
Good enough I guess...</p>


问:
Remove first 'n' elements from list without iterating
I need an efficient way of removing items from list. If some condition happens, I need to remove first 'n' elements from a list. Can some one suggest the best way to do this? Please keep in mind: performance is a factor for me, so I need a faster way than itterating. Thanks.

I'm thinking of a way through which the 'n'th item can be made as the starting of the list so that the 0-n items will get garbage collected. Is it possible?

答:
A single line solution is:

```<code> list.subList(n, m).clear();
</code>```

Removes m - n elements from the list starting at index n stopping at index m - 1.

Body:
A single line solution is:

 list.subList(n, m).clear();

Removes m - n elements from the list starting at index n stopping at index m - 1.


问:
localStorage breaks when timer reaches double digits
I have a timer (in seconds) function, and it stores the recent time, and the best time, however if the recent time goes to double digits, the best time will simply be the last single digit timer score, any reason as to why it won't store double digit values?

```<code>    timer = () => {
        let time = document.getElementById("seconds");
        let bestTime = document.getElementById("bestTime");
        time.innerText++;

        localStorage.setItem("latestTime", time.innerText);
        localStorage.setItem("bestTime", bestTime.innerText);

        if (localStorage.getItem("bestTime") < time.innerText) {
            localStorage.setItem("bestTime", localStorage.getItem("latestTime"));
            bestTime.innerText = time.innerText;
        }
    };
</code>```

Key Value pairs in browser for example

The timer is 12s so the Highscore should be 12, but stops at 9

答:
You are doing string comparisons rather than number comparisons.

Local storage and element.innerText both return strings rather than numbers, and string comparisons are done lexically. In string comparisons, '1'<'9', but '12'<'9' because '12' starts with a 1.

console.log('"12"<"9"','12'<'9')
console.log('12<9',12<9)```
</div>
</div>
</p>

<p>You need to convert your strings to numbers and then things should work fine:</p>

<p>an easy way to convert a string to a number is by putting a <code>+</code> in front of it: <code>+time.innerText</code></p>

```    timer = () => {
        let time = document.getElementById("seconds");
        let bestTime = document.getElementById("bestTime");
        time.innerText++;

        localStorage.setItem("latestTime", time.innerText);
        localStorage.setItem("bestTime", bestTime.innerText);

        if (+localStorage.getItem("bestTime") < +time.innerText) {
            localStorage.setItem("bestTime", localStorage.getItem("latestTime"));
            bestTime.innerText = time.innerText;
        }
    };
```

Body:
I have a timer (in seconds) function, and it stores the recent time, and the best time, however if the recent time goes to double digits, the best time will simply be the last single digit timer score, any reason as to why it won't store double digit values?

    timer = () => {
        let time = document.getElementById("seconds");
        let bestTime = document.getElementById("bestTime");
        time.innerText++;

        localStorage.setItem("latestTime", time.innerText);
        localStorage.setItem("bestTime", bestTime.innerText);

        if (localStorage.getItem("bestTime") < time.innerText) {
            localStorage.setItem("bestTime", localStorage.getItem("latestTime"));
            bestTime.innerText = time.innerText;
        }
    };

Key Value pairs in browser for example

The timer is 12s so the Highscore should be 12, but stops at 9

Body:
You are doing string comparisons rather than number comparisons.

Local storage and element.innerText both return strings rather than numbers, and string comparisons are done lexically. In string comparisons, '1'<'9', but '12'<'9' because '12' starts with a 1.

console.log('"12"<"9"','12'<'9')
console.log('12<9',12<9)

You need to convert your strings to numbers and then things should work fine:

an easy way to convert a string to a number is by putting a + in front of it: +time.innerText

    timer = () => {
        let time = document.getElementById("seconds");
        let bestTime = document.getElementById("bestTime");
        time.innerText++;

        localStorage.setItem("latestTime", time.innerText);
        localStorage.setItem("bestTime", bestTime.innerText);

        if (+localStorage.getItem("bestTime") < +time.innerText) {
            localStorage.setItem("bestTime", localStorage.getItem("latestTime"));
            bestTime.innerText = time.innerText;
        }
    };


问:
Divide image to single objects (coins) for machine learning
I want to automatically divide an image of multiple coins to the single coins, so that afterwards the single coins can be put into a model that classifies the coins (with Tensorflow/Keras).

The input images look something like this

And they should look like this (Sorry that I cannot integrate the images directly as I'm new to StackOverflow).

I want to divide the input images, put the single coins into a classification model, so that I know the single value of the single coins and thereby can identify the value of the first input image.

I already tried an object detection model, but it didn't detect coins (https://towardsdatascience.com/object-detection-with-10-lines-of-code-d6cb4d86f606). As I already know that all objects on the image are coins, I thought that there is maybe an easier way to divide the image?

Thank you in advance.

答:
```<code>import cv2
import imutils
import numpy as np
import matplotlib.pyplot as plt

def display(img,count,cmap="gray"):
    f_image = cv2.imread("coins.jpg")
    f, axs = plt.subplots(1,2,figsize=(12,5))
    axs[0].imshow(f_image,cmap="gray")
    axs[1].imshow(img,cmap="gray")
    axs[1].set_title("Total Money Count = {}".format(count))

image = cv2.imread("coins.jpg")
image_blur = cv2.medianBlur(image,25)
image_blur_gray = cv2.cvtColor(image_blur, cv2.COLOR_BGR2GRAY)
image_res ,image_thresh = cv2.threshold(image_blur_gray,240,255,cv2.THRESH_BINARY_INV)
kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(image_thresh,cv2.MORPH_OPEN,kernel)
dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5)
ret, last_image =  cv2.threshold(dist_transform, 0.3*dist_transform.max(),255,0)
last_image = np.uint8(last_image)

cnts = cv2.findContours(last_image.copy(), cv2.RETR_EXTERNAL,
    cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

for (i, c) in enumerate(cnts):
    ((x, y), _) = cv2.minEnclosingCircle(c)
    cv2.putText(image, "#{}".format(i + 1), (int(x) - 45, int(y)+20),
        cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0), 5)
    cv2.drawContours(image, [c], -1, (0, 255, 0), 2)

display(image,len(cnts))
</code>```


问:
Calling parent move assignment operator when source object still needs to be used after
TLDR - Feel free to mark this as a duplicate if it is so; I will delete the question. However, I couldn't find anything after looking around for a bit.

Consider the following classes:

class Base
{
public:
    Base(std::string var1);

    Base& operator=(Base&& other) noexcept
    {
        if (this != &other)
            var1_ = std::move(other.var1_);
        return *this;
    }

protected:
    std::string var1_;
};

class Child final : public Base
{
public:
    Child(std::string var1, std::string var2);

    Child& operator=(Child&& other) noexcept
    {
        if (this != &other)
        {
            // Take note of HERE for explanation below
            Base::operator=(std::move(other));
            var2_ = std::move(other.var2_);
        }
    }

private:
    std::string var2_;
};
```

Here there are two classes, Child deriving from Base. Child has more members than Base. In the move assignment operator of Child, we have a situation where we have extra members that also need to be assigned to the values of other's members. However, we're first moving the memory of other to the parent move assignment operator, so wouldn't that data then be unusable?

I suppose I'm simply confused on (1) if there's actually anything wrong with what I have above, (2) if so, why does it work since other is supposed to be moved before it is used, and (3) if not, what is the best way to accomplish the task I have?

Is the better way to do this simply to initialize the members of Child first and then hand it over to the Base move assignment operator? Does it make a difference?

答:
Yes, this is safe.

First, note that the rule about not using a moved-from object is a default guideline for designing and using objects. It is not a rule of the language itself. It's the common practice for what class objects generally guarantee after they've been moved-from, including Standard Library class types that don't specify otherwise (like std::unique_ptr<T> guarantees a moved-from pointer holds a null pointer).

So since you know exactly what Base::operator= does to other, and that only moves from other.var1_, it's still safe to use other.var2_.

There's another reason this pattern is safe, even if you don't actually know precisely what Base::operator= does, or you want to write the Child code to keep working even if the details of Base change. A Child object contains two subobjects: the Base base class subobject and the var2_ member subobject. These objects don't inherently know anything about the other. (They could have manually set-up interactions with each other via pointers, virtual functions, etc., to complicate things, but that sort of thing should be documented for Base or known in Child) The Base::operator=(std::move(other)); statement moves from just the base class subobject, not from the member subobject, so the member subobject is not affected, and the definition of Child::operator=(Child&&) is safe against changes to Base.

Body:
TLDR - Feel free to mark this as a duplicate if it is so; I will delete the question. However, I couldn't find anything after looking around for a bit.

Consider the following classes:

class Base
{
public:
    Base(std::string var1);

    Base& operator=(Base&& other) noexcept
    {
        if (this != &other)
            var1_ = std::move(other.var1_);
        return *this;
    }

protected:
    std::string var1_;
};

class Child final : public Base
{
public:
    Child(std::string var1, std::string var2);

    Child& operator=(Child&& other) noexcept
    {
        if (this != &other)
        {
            // Take note of HERE for explanation below
            Base::operator=(std::move(other));
            var2_ = std::move(other.var2_);
        }
    }

private:
    std::string var2_;
};

Here there are two classes, Child deriving from Base. Child has more members than Base. In the move assignment operator of Child, we have a situation where we have extra members that also need to be assigned to the values of other's members. However, we're first moving the memory of other to the parent move assignment operator, so wouldn't that data then be unusable?

I suppose I'm simply confused on (1) if there's actually anything wrong with what I have above, (2) if so, why does it work since other is supposed to be moved before it is used, and (3) if not, what is the best way to accomplish the task I have?

Is the better way to do this simply to initialize the members of Child first and then hand it over to the Base move assignment operator? Does it make a difference?


问:
How can I produce a situation when $EUID is different than $UID?
It might be a silly question but I am not understanding EUID and UID correctly.

The description of real ID and effective ID is clear and I get it. Based on what I have found on Google and ebooks, when using su, sudo or SUID, effective ID should change. Also, to my understanding UID in Bash should contain real ID and EUID should contain effective ID.

My assumption is EUID and UID should be different when I am using su, sudo or SUID but whenever I try echo $EUID and echo $UID the result of both are the same.

Also, I tried id -u and id -r -u and again they are always the same.

Could someone explain to me at when and what situation exactly $EUID and $UID are different?

答:
By default bash drops the privileges. There is a special privileged mode set -p.

```<code># copy bash executable
$ sudo cp /usr/bin/bash ./bash
# set the suid mode
$ chmod +s ./bash
$ ls -l bash
-rwsr-sr-x 1 root root 903504 05-29 23:48 ./bash*
# run it
$ ./bash -p -c 'echo $UID $EUID'
1000 0
</code>```

Body:
By default bash drops the privileges. There is a special privileged mode set -p.

# copy bash executable
$ sudo cp /usr/bin/bash ./bash
# set the suid mode
$ chmod +s ./bash
$ ls -l bash
-rwsr-sr-x 1 root root 903504 05-29 23:48 ./bash*
# run it
$ ./bash -p -c 'echo $UID $EUID'
1000 0


答:
That's because the Local Storage can only store strings, not numbers or anything else.

When you store a number into the Local Storage,  it will be automatically converted to a string, which isn't a problem.

However, your code doesn't convert it back after you retrieve it!

This:

```<code>localStorage.getItem("bestTime") < time.innerText
</code>```

will receive two strings, and therefore use string comparison, in which 10 comes before 2 (as the first character is the most significant).

You'll have to convert them numbers, like:

```<code>+localStorage.getItem("bestTime") < +time.innerText
</code>```

Title: localStorage breaks when timer reaches double digits

Body:
That's because the Local Storage can only store strings, not numbers or anything else.

When you store a number into the Local Storage,  it will be automatically converted to a string, which isn't a problem.

However, your code doesn't convert it back after you retrieve it!

This:

localStorage.getItem("bestTime") < time.innerText

will receive two strings, and therefore use string comparison, in which 10 comes before 2 (as the first character is the most significant).

You'll have to convert them numbers, like:

+localStorage.getItem("bestTime") < +time.innerText


问:
Ionic 4 Angular AlertController message not showing in release build
I've built a small alert service (wrapper for Angular AlertController) in my Ionic 4 project, it works perfectly when I view the project in "ionic serve" (browser), "ionic cordova emulate" (on my connected phone), "ionic cordova build android" (installing the app-debug APK manually on my phone) however when I build the release version of the app using "ionic cordova build android --prod --release" the "message" part of the Alert does not show. The header (title) and the buttons show and work fine still, but the message does not appear.

Here is my method which creates and presents the alert:

```<code>   /**
 * "Confirm" with callback or "Cancel" alert
 */
async confirmOrCancelAlert(title, message, callback) {
    const alert = await this.alertController.create({
        header: title,
        message: message,
        buttons: [
            {
                text: 'Cancel',
                role: 'cancel',
                cssClass: 'secondary',
            }, {
                text: 'Confirm',
                handler: () => {
                    callback();
                }
            }
        ]
    });

    await alert.present();
}
</code>```

This is the code which called the method shown above, which is called from a button click:

```<code>    /**
 * Answer questions button event click
 */
answerQuestions() {
    if (this.shift.getEarly() && (this.shift.getTimeToStart().asHours() > environment.alertTimes.answerQuestions)) {
        var timeTo = this.durationFormatPipe.transform(this.shift.getStart());
        var message = 'Your shift starts ' + timeTo + ', are you sure you want to answer questions now?';

        this.alertService.confirmOrCancelAlert('You are early!', message, () => {
            this.doAnswerQuestions();
        });
    } else {
        this.doAnswerQuestions();
    }
}
</code>```

Here are two images showing the message messing from the release build but showing in the serve / emulate / debug builds:

Many thanks in advance for any and all advice.

答:
I think it's a timing problem. when you call confirmOrCancelAlert() the timeTo is not prepared yet. so the type of message will be undefined.

try this:

```<code>    answerQuestions() {
        if (this.shift.getEarly() && (this.shift.getTimeToStart().asHours() > environment.alertTimes.answerQuestions)) {
            var timeTo = this.durationFormatPipe.transform(this.shift.getStart());
            var message = 'Your shift starts ' + timeTo + ', are you sure you want to answer questions now?';

            setTimeout(() => {
                this.alertService.confirmOrCancelAlert('You are early!', message, () => {
                    this.doAnswerQuestions();
                });
            }, 50);

        } else {
            this.doAnswerQuestions();
        }
    }
</code>```

Body:
I've built a small alert service (wrapper for Angular AlertController) in my Ionic 4 project, it works perfectly when I view the project in "ionic serve" (browser), "ionic cordova emulate" (on my connected phone), "ionic cordova build android" (installing the app-debug APK manually on my phone) however when I build the release version of the app using "ionic cordova build android --prod --release" the "message" part of the Alert does not show. The header (title) and the buttons show and work fine still, but the message does not appear.

Here is my method which creates and presents the alert:

   /**
 * "Confirm" with callback or "Cancel" alert
 */
async confirmOrCancelAlert(title, message, callback) {
    const alert = await this.alertController.create({
        header: title,
        message: message,
        buttons: [
            {
                text: 'Cancel',
                role: 'cancel',
                cssClass: 'secondary',
            }, {
                text: 'Confirm',
                handler: () => {
                    callback();
                }
            }
        ]
    });

    await alert.present();
}

This is the code which called the method shown above, which is called from a button click:

    /**
 * Answer questions button event click
 */
answerQuestions() {
    if (this.shift.getEarly() && (this.shift.getTimeToStart().asHours() > environment.alertTimes.answerQuestions)) {
        var timeTo = this.durationFormatPipe.transform(this.shift.getStart());
        var message = 'Your shift starts ' + timeTo + ', are you sure you want to answer questions now?';

        this.alertService.confirmOrCancelAlert('You are early!', message, () => {
            this.doAnswerQuestions();
        });
    } else {
        this.doAnswerQuestions();
    }
}

Here are two images showing the message messing from the release build but showing in the serve / emulate / debug builds:

Many thanks in advance for any and all advice.

Body:
I think it's a timing problem. when you call confirmOrCancelAlert() the timeTo is not prepared yet. so the type of message will be undefined.

try this:

    answerQuestions() {
        if (this.shift.getEarly() && (this.shift.getTimeToStart().asHours() > environment.alertTimes.answerQuestions)) {
            var timeTo = this.durationFormatPipe.transform(this.shift.getStart());
            var message = 'Your shift starts ' + timeTo + ', are you sure you want to answer questions now?';

            setTimeout(() => {
                this.alertService.confirmOrCancelAlert('You are early!', message, () => {
                    this.doAnswerQuestions();
                });
            }, 50);

        } else {
            this.doAnswerQuestions();
        }
    }


问:
Function pointer and calling convention
```<code>float __stdcall (*pFunc)(float a, float b) = (float (__stdcall *)(float,float))0x411280;
</code>```

How to declare a function pointer with calling convention? The above gives me an error.

答:
For a regular function, you can usually do:

```<code>__cdecl const int func();
__cdecl const int (func)();
const __cdecl int func();
const int __cdecl func();
const int (__cdecl func)();
__cdecl const __cdecl int (__cdecl func)();
</code>```

It is implementation defined whether or not a compiler will accept all of these forms. Clang does. To me, the 5th version makes the most semantic sense, because it is a property of the function and not the return type alone.

You can do all of this with __attribute__((cdecl)) instead of __cdecl, which can also be used after the function, unlike __cdecl

```<code>const int (__cdecl func)() __attribute__((cdecl));
</code>```

Now, to declare a constant pointer pfunc to a function with a specific calling convention:

```<code>__cdecl const int (*const pfunc)();
const __cdecl int (*const pfunc)();
const int __cdecl (*const pfunc)();
const int (__cdecl *const pfunc)();
const int (*const __cdecl pfunc)();
const int (*__cdecl const pfunc)();
__cdecl const __cdecl int (__cdecl *const pfunc)();
const int (*const pfunc)() __attribute__((cdecl));
</code>```

Note that const has to be after the asterisk as usual. With double function pointers, the pointers can go anywhere with respect to the calling convention, but you have to put it in the correct place with respect to const.

Again, it is implementation defined as to what form a compiler accepts. Clang accepts all forms and correctly interprets them as the type const int (*const)() __attribute__((cdecl))

ContentLicense: CC BY-SA 2.5

Title: Function pointer and calling convention

Body:
float __stdcall (*pFunc)(float a, float b) = (float (__stdcall *)(float,float))0x411280;

How to declare a function pointer with calling convention? The above gives me an error.

Body:
For a regular function, you can usually do:

__cdecl const int func();
__cdecl const int (func)();
const __cdecl int func();
const int __cdecl func();
const int (__cdecl func)();
__cdecl const __cdecl int (__cdecl func)();

It is implementation defined whether or not a compiler will accept all of these forms. Clang does. To me, the 5th version makes the most semantic sense, because it is a property of the function and not the return type alone.

You can do all of this with __attribute__((cdecl)) instead of __cdecl, which can also be used after the function, unlike __cdecl

const int (__cdecl func)() __attribute__((cdecl));

Now, to declare a constant pointer pfunc to a function with a specific calling convention:

__cdecl const int (*const pfunc)();
const __cdecl int (*const pfunc)();
const int __cdecl (*const pfunc)();
const int (__cdecl *const pfunc)();
const int (*const __cdecl pfunc)();
const int (*__cdecl const pfunc)();
__cdecl const __cdecl int (__cdecl *const pfunc)();
const int (*const pfunc)() __attribute__((cdecl));

Note that const has to be after the asterisk as usual. With double function pointers, the pointers can go anywhere with respect to the calling convention, but you have to put it in the correct place with respect to const.

Again, it is implementation defined as to what form a compiler accepts. Clang accepts all forms and correctly interprets them as the type const int (*const)() __attribute__((cdecl))


问:
Visual Basic Login Form Query
```<code>Private Sub cmdOK_Click()
 Adodc1.Recordset.MoveFirst
 Do While Not Adodc1.Recordset.EOF
        If Adodc1.Recordset.Fields(0) <> txtuser.Text Or Adodc1.Recordset.Fields(1) <>   txtPassword.Text Then

            MsgBox "Please verify login details", vbInformation + vbOKOnly, "Login Denied"
            txtuser.SetFocus
            txtuser.Text = ""
            txtPassword.Text = ""
        Else
            Unload Me
            Load Main
            Main.Show
        End If
        Adodc1.Recordset.MoveNext
        Loop
End Sub
</code>```

I would appreciate it if someone looked at the code snippet above and told me if any changes need be made! This is the code I use for a login form that connects to a SQL SERVER 2005 DB! Now why isn't this working? It seems to ONLY fetch the data from the first row of the two columns, not the rows that follow?

答: I would take a step back and rewrite all of this.  You should be sending the database the username and password, not sending every username and password to your application and looping through it. Let the DBMS do the work for you.  I would also suggest that you refrain from storing passwords as plain text (as it appears you are doing).  This information is general and can be found by searching, but if you're having a particular problem, post back.</p>

OwnerDisplayName: Sigz

LastEditorDisplayName: EndangeredMassa

Title: Visual Basic Login Form Query

Body:
Private Sub cmdOK_Click()
 Adodc1.Recordset.MoveFirst
 Do While Not Adodc1.Recordset.EOF
        If Adodc1.Recordset.Fields(0) <> txtuser.Text Or Adodc1.Recordset.Fields(1) <>   txtPassword.Text Then

            MsgBox "Please verify login details", vbInformation + vbOKOnly, "Login Denied"
            txtuser.SetFocus
            txtuser.Text = ""
            txtPassword.Text = ""
        Else
            Unload Me
            Load Main
            Main.Show
        End If
        Adodc1.Recordset.MoveNext
        Loop
End Sub

I would appreciate it if someone looked at the code snippet above and told me if any changes need be made! This is the code I use for a login form that connects to a SQL SERVER 2005 DB! Now why isn't this working? It seems to ONLY fetch the data from the first row of the two columns, not the rows that follow?

OwnerDisplayName: colithium


问:
How to access values from NSSet?
I am using CoreData and it's returning a NSMangedObject. I have taken it into NSSet and now i want to take the value out and display it. Here's the code snippets:

```<code>NSManagedObject *financialsData = [serverResult valueForKey:@"financials"];
    NSSet *financiers = [financialsData valueForKey:@"planFinanciers"];
    for (NSManagedObject *financier in financiers)
    {

    }
</code>```

Please help.

答:
You haven't told us anything about the attributes and relationships that a particular financier has, but in general you can use accessors or KVC to get the data from each object:

```<code>NSManagedObject *financialsData = [serverResult valueForKey:@"financials"];
NSSet *financiers = [financialsData valueForKey:@"planFinanciers"];
for (NSManagedObject *financier in financiers)
{
    // Assuming there are 'name' and 'netWorth' attributes...
    NSLog(@"Name: %@\tNet Worth:%.2f", financier.name, financier.netWorth);

    // ...or...
    NSLog(@"Name: %@\tNet Worth:%.2f", [financier valueForKey:@"name"], [[financier valueForKey@"netWorth"] floatValue]);
}
</code>```

Don't take my word for it, though... read Managed Object Accessor Methods.

Title: How to access values from NSSet?

Body:
I am using CoreData and it's returning a NSMangedObject. I have taken it into NSSet and now i want to take the value out and display it. Here's the code snippets:

NSManagedObject *financialsData = [serverResult valueForKey:@"financials"];
    NSSet *financiers = [financialsData valueForKey:@"planFinanciers"];
    for (NSManagedObject *financier in financiers)
    {

    }

Please help.

Body:
You haven't told us anything about the attributes and relationships that a particular financier has, but in general you can use accessors or KVC to get the data from each object:

NSManagedObject *financialsData = [serverResult valueForKey:@"financials"];
NSSet *financiers = [financialsData valueForKey:@"planFinanciers"];
for (NSManagedObject *financier in financiers)
{
    // Assuming there are 'name' and 'netWorth' attributes...
    NSLog(@"Name: %@\tNet Worth:%.2f", financier.name, financier.netWorth);

    // ...or...
    NSLog(@"Name: %@\tNet Worth:%.2f", [financier valueForKey:@"name"], [[financier valueForKey@"netWorth"] floatValue]);
}

Don't take my word for it, though... read Managed Object Accessor Methods.


问:
Memory management of function pointers and lambdas
I'm relatively new in C++, and I've some questions about memory management.

I'm a C# developer and memory management is easier than C++ because of the garbage collector and I don't know when I've to free memory manually.

For example:

```<code>void (*ptr)() = [] { /* 1rst lambda expression code*/ };
ptr = [] { /*2nd lambda expression code*/ };
</code>```

What happen with the first lambda expression?, Is still in memory?, I've to do something before reassigning 'ptr'?.

If someone can explain to me this particular case and how C++ and memory works I would appreciate it!.

答:
The C++ language handles lambda functions without capture lists as though they were real functions with some compiler-generated name that's different from the names of all other functions. As a result, when you write

```<code>void (*ptr)() = [] { /* 1rst lambda expression code*/ };
</code>```

it's kinda sorta like writing the following:

```<code>static void _CompilerGeneratedFn137() {
    /* lambda code */
}

void (*ptr)() = &_CompilerGeneratedFn137;
</code>```

No memory is actually allocated here (except for the space for the ptr variable itself), and the pointer just points somewhere into the code segment of the program. When you then reassign ptr to point to a different lambda, you're not leaking any memory; you're just changing which anonymous function the ptr variable points at.

Hope this helps!

Body:
I'm relatively new in C++, and I've some questions about memory management.

I'm a C# developer and memory management is easier than C++ because of the garbage collector and I don't know when I've to free memory manually.

For example:

void (*ptr)() = [] { /* 1rst lambda expression code*/ };
ptr = [] { /*2nd lambda expression code*/ };

What happen with the first lambda expression?, Is still in memory?, I've to do something before reassigning 'ptr'?.

If someone can explain to me this particular case and how C++ and memory works I would appreciate it!.

Body:
The C++ language handles lambda functions without capture lists as though they were real functions with some compiler-generated name that's different from the names of all other functions. As a result, when you write

void (*ptr)() = [] { /* 1rst lambda expression code*/ };

it's kinda sorta like writing the following:

static void _CompilerGeneratedFn137() {
    /* lambda code */
}

void (*ptr)() = &_CompilerGeneratedFn137;

No memory is actually allocated here (except for the space for the ptr variable itself), and the pointer just points somewhere into the code segment of the program. When you then reassign ptr to point to a different lambda, you're not leaking any memory; you're just changing which anonymous function the ptr variable points at.

Hope this helps!


问:
how can I extract a position of values that match a logical selection in a matrix in r?
How can I extract the position of every 0 per column in a following matrix:

```<code>bm <- matrix(c(0,1,0,1,1,1,0,1,1,1,1,0,0,0,0),5,3)
</code>```

that gives a matrix like:

```<code>+---+---+---+
| x | y | z |
+---+---+---+
| 0 | 1 | 1 |
+---+---+---+
| 1 | 0 | 0 |
+---+---+---+
| 0 | 1 | 0 |
+---+---+---+
| 1 | 1 | 0 |
+---+---+---+
| 1 | 1 | 0 |
+---+---+---+
</code>```

So I want to have a data frame or matrix in whichever form it's easier with the positions of each 0 according to the rows or column position. Something like:

```<code>+---+---+---+
| x | y | z |
+---+---+---+
| 1 | 2 | 2 |
+---+---+---+
| 3 |   | 3 |
+---+---+---+
|   |   | 4 |
+---+---+---+
|   |   | 5 |
+---+---+---+
|   |   |   |
+---+---+---+
</code>```

It's a very basic question that I did not find an answer right away yet.

答:
If we don't want to reorder the index by column

```<code>row(bm) * !bm
</code>```

If we want to reorder, an option is row multiplied with the logical matrix and then reorder the positions

```<code>apply(row(bm)* !bm, 2, function(x) c(x[x!=0], x[x==0]))
#      [,1] [,2] [,3]
#[1,]    1    2    2
#[2,]    3    0    3
#[3,]    0    0    4
#[4,]    0    0    5
#[5,]    0    0    0
</code>```

Or using order

```<code>apply(row(bm) * !bm, 2, function(x) x[order(!x)])
</code>```

Or another option

```<code>sapply(asplit(replace(row(bm), !!bm, NA), 2),
       function(x)  x[order(is.na(x))])
</code>```

Body:
How can I extract the position of every 0 per column in a following matrix:

bm <- matrix(c(0,1,0,1,1,1,0,1,1,1,1,0,0,0,0),5,3)

that gives a matrix like:

+---+---+---+
| x | y | z |
+---+---+---+
| 0 | 1 | 1 |
+---+---+---+
| 1 | 0 | 0 |
+---+---+---+
| 0 | 1 | 0 |
+---+---+---+
| 1 | 1 | 0 |
+---+---+---+
| 1 | 1 | 0 |
+---+---+---+

So I want to have a data frame or matrix in whichever form it's easier with the positions of each 0 according to the rows or column position. Something like:

+---+---+---+
| x | y | z |
+---+---+---+
| 1 | 2 | 2 |
+---+---+---+
| 3 |   | 3 |
+---+---+---+
|   |   | 4 |
+---+---+---+
|   |   | 5 |
+---+---+---+
|   |   |   |
+---+---+---+

It's a very basic question that I did not find an answer right away yet.

Body:
If we don't want to reorder the index by column

row(bm) * !bm

If we want to reorder, an option is row multiplied with the logical matrix and then reorder the positions

apply(row(bm)* !bm, 2, function(x) c(x[x!=0], x[x==0]))
#      [,1] [,2] [,3]
#[1,]    1    2    2
#[2,]    3    0    3
#[3,]    0    0    4
#[4,]    0    0    5
#[5,]    0    0    0

Or using order

apply(row(bm) * !bm, 2, function(x) x[order(!x)])

Or another option

sapply(asplit(replace(row(bm), !!bm, NA), 2),
       function(x)  x[order(is.na(x))])


问:
Erase arrays with a variable
I'm creating a macro with a data sheet that has 185 columns.  I need to capture the data in each column for the total number of rows in the data sheet (maybe 800).

I want to capture all of the data so I created variables like this so the number corresponds to the the column number:

```<code>Public vVar1() as string
Public vVar2() as string
Public vVar3() as string
Public vVar4() as string.....etc.
</code>```

I want to erase the array and I'm trying to do something like this:

```<code>vCnt = 1
 vTmp = ""

 Do Until vCnt = 186
      DoEvents
      vTmp = "vVar"
      vTmp = vTmp & vCnt

      Erase vTmp

      vCnt = vCnt + 1

Loop
</code>```

However, I'm getting an "Expected Array" error message on the "Erase vTmp" line.  I was trying to do it this way instead of having ERASE vTMP1, ERASE vTmp2.....183 more times.

Is there a way to do this?  Thanks......Any suggestions would be greatly appreciated.  Thanks again.

答:
```<code>Erase vTmp
</code>```

vTmp is a Variant/String here, not an array. Just because the string happens to match the name of a programmatic identifier doesn't make it a magical string that arbitrarily becomes an actual identifier depending on context like it would in PHP - and that's a very, very good thing.

The real problem is having 185 arrays to clear in the first place. Whenever you feel the need to number something - anything - there's a 99% chance you're in the wrong spot and need to think of a data structure instead. Like Tim said, an array with 185 items that are themselves arrays makes much more sense than having 185 variables that go by the names of vVar1 through vVar185.

And then you can Erase them, because now you're dealing with arrays, not strings:

```<code>For i = 0 To 184
    Erase allArrays(i)
Next
</code>```

Title: Erase arrays with a variable

Body:
I'm creating a macro with a data sheet that has 185 columns.  I need to capture the data in each column for the total number of rows in the data sheet (maybe 800).

I want to capture all of the data so I created variables like this so the number corresponds to the the column number:

Public vVar1() as string
Public vVar2() as string
Public vVar3() as string
Public vVar4() as string.....etc.

I want to erase the array and I'm trying to do something like this:

vCnt = 1
 vTmp = ""

 Do Until vCnt = 186
      DoEvents
      vTmp = "vVar"
      vTmp = vTmp & vCnt

      Erase vTmp

      vCnt = vCnt + 1

Loop

However, I'm getting an "Expected Array" error message on the "Erase vTmp" line.  I was trying to do it this way instead of having ERASE vTMP1, ERASE vTmp2.....183 more times.

Is there a way to do this?  Thanks......Any suggestions would be greatly appreciated.  Thanks again.

Body:
Erase vTmp

vTmp is a Variant/String here, not an array. Just because the string happens to match the name of a programmatic identifier doesn't make it a magical string that arbitrarily becomes an actual identifier depending on context like it would in PHP - and that's a very, very good thing.

The real problem is having 185 arrays to clear in the first place. Whenever you feel the need to number something - anything - there's a 99% chance you're in the wrong spot and need to think of a data structure instead. Like Tim said, an array with 185 items that are themselves arrays makes much more sense than having 185 variables that go by the names of vVar1 through vVar185.

And then you can Erase them, because now you're dealing with arrays, not strings:

For i = 0 To 184
    Erase allArrays(i)
Next


问:
Swap misuse absurdity?
the following is a reverse array implementation in java. I walked through it logically and I feel like it should work.

```<code>public static int[] reverseArray(int[] arr){
int temp = 0;
int[] newArr;
newArr = Arrays.copyOf(arr, arr.length);
for (int i = 0; i < arr.length - 1; i++){
temp = newArr[i];
newArr[i] = newArr[arr.length - 1 - i];
newArr[arr.length - 1 - i] = temp;
}
return newArr;
}
</code>```

I pass in an array [1, 2, 3, 4, 5]
It returns to me only the first the the last number swapped.
Returns [5, 2, 3, 4, 1]

答:
You are swapping elements twice.

In your example, when i is 1, you swap elements 1 and 3. Then when i is 3, you swap elements 3 and 1, effectively putting them back where they were originally.

Title: Swap misuse absurdity?

Body:
the following is a reverse array implementation in java. I walked through it logically and I feel like it should work.

public static int[] reverseArray(int[] arr){
int temp = 0;
int[] newArr;
newArr = Arrays.copyOf(arr, arr.length);
for (int i = 0; i < arr.length - 1; i++){
temp = newArr[i];
newArr[i] = newArr[arr.length - 1 - i];
newArr[arr.length - 1 - i] = temp;
}
return newArr;
}

I pass in an array [1, 2, 3, 4, 5]
It returns to me only the first the the last number swapped.
Returns [5, 2, 3, 4, 1]


问:
Create multiple label over the multiple ellipse
I have 6 ellipse and 6 label. I want to add labels over the ellipse. 2 of labels is OK but the others not.

In debug mode there is no error.

Here is the code:

```<code>private void Form1_Paint(object sender, PaintEventArgs e)
        {
            int locY = 200, locX = 10, i = 0;
            for (int k = 0; k < 3; k++)
            {
                locX += 40;
                for (int j = 0; j < 2; j++)
                {
                    locY += 30;
                    Pen pen = new Pen(Color.Red, 10);
                    e.Graphics.DrawEllipse(pen, new Rectangle(locX, locY, 10, 10));
                    Label label = new Label();
                    label.Text = i.ToString();
                    label.Location = new Point(locX,locY);
                    label.BackColor = Color.Transparent;
                    Controls.Add(label);
                    i++;
                }
                locY = 200;
            }
        }
</code>```

Here is the output:

答:
You should also create that Pen outside of the loop and make sure to dispose of it.

Here's an example using DrawString() as described in the comments:

```<code>private void Form1_Paint(object sender, PaintEventArgs e)
{
    StringFormat sf = new StringFormat();
    sf.Alignment = StringAlignment.Center;
    sf.LineAlignment = StringAlignment.Center;

    int locY = 200, locX = 10, i = 0;
    using (Pen pen = new Pen(Color.Red, 10))
    {
        for (int k = 0; k < 3; k++)
        {
            locX += 40;
            for (int j = 0; j < 2; j++)
            {
                locY += 30;
                Rectangle rc = new Rectangle(locX, locY, 10, 10);
                e.Graphics.DrawEllipse(pen, rc);

                SizeF szF = e.Graphics.MeasureString(i.ToString(), this.Font);
                Rectangle rc2 = new Rectangle(new Point(rc.Left + rc.Width / 2, rc.Top + rc.Height / 2), new Size(1, 1));
                rc2.Inflate((int)szF.Width, (int)szF.Height);
                e.Graphics.DrawString(i.ToString(), this.Font, Brushes.Black, rc2, sf);

                i++;
            }
            locY = 200;
        }
    }
}
</code>```

Body:
I have 6 ellipse and 6 label. I want to add labels over the ellipse. 2 of labels is OK but the others not.

In debug mode there is no error.

Here is the code:

private void Form1_Paint(object sender, PaintEventArgs e)
        {
            int locY = 200, locX = 10, i = 0;
            for (int k = 0; k < 3; k++)
            {
                locX += 40;
                for (int j = 0; j < 2; j++)
                {
                    locY += 30;
                    Pen pen = new Pen(Color.Red, 10);
                    e.Graphics.DrawEllipse(pen, new Rectangle(locX, locY, 10, 10));
                    Label label = new Label();
                    label.Text = i.ToString();
                    label.Location = new Point(locX,locY);
                    label.BackColor = Color.Transparent;
                    Controls.Add(label);
                    i++;
                }
                locY = 200;
            }
        }

Here is the output:

Body:
You should also create that Pen outside of the loop and make sure to dispose of it.

Here's an example using DrawString() as described in the comments:

private void Form1_Paint(object sender, PaintEventArgs e)
{
    StringFormat sf = new StringFormat();
    sf.Alignment = StringAlignment.Center;
    sf.LineAlignment = StringAlignment.Center;

    int locY = 200, locX = 10, i = 0;
    using (Pen pen = new Pen(Color.Red, 10))
    {
        for (int k = 0; k < 3; k++)
        {
            locX += 40;
            for (int j = 0; j < 2; j++)
            {
                locY += 30;
                Rectangle rc = new Rectangle(locX, locY, 10, 10);
                e.Graphics.DrawEllipse(pen, rc);

                SizeF szF = e.Graphics.MeasureString(i.ToString(), this.Font);
                Rectangle rc2 = new Rectangle(new Point(rc.Left + rc.Width / 2, rc.Top + rc.Height / 2), new Size(1, 1));
                rc2.Inflate((int)szF.Width, (int)szF.Height);
                e.Graphics.DrawString(i.ToString(), this.Font, Brushes.Black, rc2, sf);

                i++;
            }
            locY = 200;
        }
    }
}


问:
How to use Go package that is in another module
I have two repos github.com/x/a and github.com/x/b and they both have Go modules at the root of each. How can i access a package that that is in the other repo? Normally I would be able to access it by doing a go get github.com/x/b if I want to use b in a. But neither are in production and we are still working in a development branch so I need to find a way to do this locally. Any ideas?

答:
The quick and dirty way is to clone the repository into GOPATH/src. Then you can import the packages simply with

import "a" or import "b"


问:
Python PostgreSQL "error insert has more target columns than expressions" but its not
Im new to SQL and PostgreSQL and I cant understand whats going on with this code.

Im trying to insert csv to postgres with this code:

```<code>import csv
import psycopg2 as pg
filename = 'myfile.csv'
try:
    conn = pg.connect(user="myuser",
        password="mypass",
        host="myhost",
        port="5432",
        database="mydb")
    cursor = conn.cursor()
    with open(filename, 'r') as f:
        reader = csv.reader(f)
        next(reader) # This skips the 1st row which is the header.
        for record in reader:
            print(record)
            cursor.execute("""INSERT INTO auth VALUES (%s, %s, %s, %s)""", record)
            conn.commit()
except (Exception, pg.Error) as e:
    print(e)
finally:
    if (conn):
        cursor.close()
        conn.close()
        print("Connection closed.")
</code>```

but it raise error insert has more target columns than expressions
LINE 1: ...00000000-0000-0000-0000-000000000000', '1580463062', 'auto')

but here is what i want to insert
['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '1580463062', 'auto']
and its look like its definitely has exactly 4 colums

I also tried to change the encoding of csv from ASCII to UTF-8 and UTF-8_SIG but i still get this error

答:
I solve my problem with this code</p>

```<code>import psycopg2
conn = psycopg2.connect("host=host dbname=dbname user=user
password=password")
cur = conn.cursor()
with open(filename, 'r') as f:
    next(f)
    cur.copy_from(f, 'auth', sep=',')

conn.commit()
cur.close()
conn.close()
</code>```

Body:
Im new to SQL and PostgreSQL and I cant understand whats going on with this code.

Im trying to insert csv to postgres with this code:

import csv
import psycopg2 as pg
filename = 'myfile.csv'
try:
    conn = pg.connect(user="myuser",
        password="mypass",
        host="myhost",
        port="5432",
        database="mydb")
    cursor = conn.cursor()
    with open(filename, 'r') as f:
        reader = csv.reader(f)
        next(reader) # This skips the 1st row which is the header.
        for record in reader:
            print(record)
            cursor.execute("""INSERT INTO auth VALUES (%s, %s, %s, %s)""", record)
            conn.commit()
except (Exception, pg.Error) as e:
    print(e)
finally:
    if (conn):
        cursor.close()
        conn.close()
        print("Connection closed.")

but it raise error insert has more target columns than expressions
LINE 1: ...00000000-0000-0000-0000-000000000000', '1580463062', 'auto')

but here is what i want to insert
['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '1580463062', 'auto']
and its look like its definitely has exactly 4 colums

I also tried to change the encoding of csv from ASCII to UTF-8 and UTF-8_SIG but i still get this error

Body:
I solve my problem with this code

import psycopg2
conn = psycopg2.connect("host=host dbname=dbname user=user
password=password")
cur = conn.cursor()
with open(filename, 'r') as f:
    next(f)
    cur.copy_from(f, 'auth', sep=',')

conn.commit()
cur.close()
conn.close()