问:
MySQL date comparison query
I have this table in my database:

```<code>table t

id   |  a   | b  | date_x

1    |  81  | 12 | 2018-03-16
2    |  9   | 54 | 2025-04-21
3    |  81  | 67 | 2018-03-16
4    |  763 | 81 | 2018-03-16
5    |  90  | 22 | 2025-12-08
</code>```

date_x is type DATE

I would like to select the rows where a = 81 or b = 81 and date_x is before 2019-05-28 .

So I perform the following query in MySQL Workbench:

```<code>SELECT * FROM t
WHERE a = '81' OR b = '81'
AND date_x > '2019-05-28';
</code>```

This is what I get:

```<code>1    |  81  | 12 | 2018-03-16
3    |  81  | 67 | 2018-03-16
</code>```

I would expect that 2018-03-16 is not later than 2019-05-28 . Moreover, why only 2 rows returned? There is another with same date in date_x column.

This query return the same:

```<code>SELECT * FROM t
WHERE a = '81' OR b = '81'
AND date_x > str_to_date('2019-05-28', '%Y-$m-%d');
</code>```

I have performed the following query for debug:

```<code>SELECT * FROM t
WHERE a = '81' OR b = '81'
AND date_x < '2019-05-28';
</code>```

and

```<code>SELECT * FROM t
WHERE a = '81' OR b = '81'
AND date_x < str_to_date('2019-05-28', '%Y-$m-%d');
</code>```

then both return, as expected:

```<code>1    |  81  | 12 | 2018-03-16
3    |  81  | 67 | 2018-03-16
4    |  763 | 81 | 2018-03-16
</code>```

I read the following Q/A but I'm still missing something:

MySQL date comparison function

MySQL date comparison issue

MySQL date/author comparison

MySQL Date comparison advice

MySQL date comparison

Any hint? Thank you

答:
A rewite into

```<code>SELECT * FROM t
WHERE a = '81' AND date_x > '2019-05-28'
UNION ALL
SELECT * FROM t
WHERE b = '81' AND date_x > '2019-05-28'
</code>```

might make more sense especially when you consider performance, consider this table structure and indexing..

```<code>CREATE TABLE t (
  `id` INTEGER,
  `a` INTEGER,
  `b` INTEGER,
  `date_x` VARCHAR(10)
  , INDEX(a, date_x)
  , INDEX(b, date_x)
);
</code>```

As

```<code>SELECT * FROM t
WHERE (a = '81' OR b = '81')
AND date_x > '2019-05-28';
</code>```

can't use indexes see demo and most likely ends up scanning the complete table/index files.

As the MySQL optimizer is costs based i also included this to make sure the FULL scan for the first query was not simply triggerd by a to low number off records..

But it's but clear the second query has the more stabile plan..

Oracle database i believe does to OR to UNION ALL rewite direcly in this optimizer if indexed. As MySQL is owned by Oracle i hope they also add it that optimizion in MySQL.

Title: MySQL date comparison query

Body:
I have this table in my database:

table t

id   |  a   | b  | date_x

1    |  81  | 12 | 2018-03-16
2    |  9   | 54 | 2025-04-21
3    |  81  | 67 | 2018-03-16
4    |  763 | 81 | 2018-03-16
5    |  90  | 22 | 2025-12-08

date_x is type DATE

I would like to select the rows where a = 81 or b = 81 and date_x is before 2019-05-28 .

So I perform the following query in MySQL Workbench:

SELECT * FROM t
WHERE a = '81' OR b = '81'
AND date_x > '2019-05-28';

This is what I get:

1    |  81  | 12 | 2018-03-16
3    |  81  | 67 | 2018-03-16

I would expect that 2018-03-16 is not later than 2019-05-28 . Moreover, why only 2 rows returned? There is another with same date in date_x column.

This query return the same:

SELECT * FROM t
WHERE a = '81' OR b = '81'
AND date_x > str_to_date('2019-05-28', '%Y-$m-%d');

I have performed the following query for debug:

SELECT * FROM t
WHERE a = '81' OR b = '81'
AND date_x < '2019-05-28';

and

SELECT * FROM t
WHERE a = '81' OR b = '81'
AND date_x < str_to_date('2019-05-28', '%Y-$m-%d');

then both return, as expected:

1    |  81  | 12 | 2018-03-16
3    |  81  | 67 | 2018-03-16
4    |  763 | 81 | 2018-03-16

I read the following Q/A but I'm still missing something:

MySQL date comparison function

MySQL date comparison issue

MySQL date/author comparison

MySQL Date comparison advice

MySQL date comparison

Any hint? Thank you

Body:
A rewite into

SELECT * FROM t
WHERE a = '81' AND date_x > '2019-05-28'
UNION ALL
SELECT * FROM t
WHERE b = '81' AND date_x > '2019-05-28'

might make more sense especially when you consider performance, consider this table structure and indexing..

CREATE TABLE t (
  `id` INTEGER,
  `a` INTEGER,
  `b` INTEGER,
  `date_x` VARCHAR(10)
  , INDEX(a, date_x)
  , INDEX(b, date_x)
);

As

SELECT * FROM t
WHERE (a = '81' OR b = '81')
AND date_x > '2019-05-28';

can't use indexes see demo and most likely ends up scanning the complete table/index files.

As the MySQL optimizer is costs based i also included this to make sure the FULL scan for the first query was not simply triggerd by a to low number off records..

But it's but clear the second query has the more stabile plan..

Oracle database i believe does to OR to UNION ALL rewite direcly in this optimizer if indexed. As MySQL is owned by Oracle i hope they also add it that optimizion in MySQL.


来源: stackexchange

问:
How to open project properties in VS 2017?
I am trying to open Project Properties window in VS 2017 in order to add header files in a way described in this topic However it turned out to be very frustrating as when I reproduce steps described in the documentation (Project -> [project name] Properties), I end up with a different window, missing some content that is crucial in my case (Common Properties -> C/C++).

What I expect:

What I get:

How do I open the window that contains Common Properties?

答: Turns out that window can only be opened in C/C++ project, not in C#</p>

ContentLicense: CC BY-SA 4.0


问:
Is there a "Try" equivelent of DATETIME2FROMPARTS?
Given the following fields:

```<code>Y INT, --Year.
M INT, --Month.
D INT, --Day.
T FLOAT --Hours (H), minutes (m), seconds (s) and milliseconds (x) (in the form HHmmss.xxx).
</code>```

Is there a way to attempt to convert these values into a DATETIME2 without having to first convert them to a string-based data type?  If the attempt fails (e.g. due to an overflowing day value (e.g. 35th of January 2019)), I would like NULL to be returned.

If I use DATETIME2FROMPARTS it will simply fail if passed any invalid component.

I am trying to avoid converting these into a string as the only reason I am trying this compromised solution is because the performance of my other solution which actually handles overflow and underflow, is incredibly slow against a large database (doesn't complete in 5 hours!) so I'm trying to try something simpler to see if it improves the performance of adding this as a computed persisted column.

答:
Here is the bespoke solution I ended up writing for this.  There is unfortunately repeated logic since I'm using this in a persisted computed column and thus cannot use variables or scalar functions (for parameters to be used as variables).

```<code>DECLARE @Y INT = 2000, @M INT = 2, @D INT = 29, @T FLOAT = 135559.999

SELECT IIF
    (
        --If the Year is out-of-bounds.
        @Y <= 0 OR @Y > 9999
        --Or the Month is out-of-bounds.
        OR @M <= 0 OR @M > 12
        --Or the Day is out-of-bounds (Accounts for leap years).
        OR @D <= 0 OR @D > DAY(EOMONTH(DATETIME2FROMPARTS(@Y, @M, 1, 0, 0, 0, 0, 3)))
        --Or the Time is less than 0
        OR @T < 0
        --Or the Hour is out-of-bounds.
        OR ROUND(@T / 10000, 0, 1) >= 24
        --Or the Minute is out-of-bounds.
        OR ROUND(@T / 100, 0, 1) - ROUND(@T / 10000, 0, 1) * 100 >= 60
        --Or the Second is out-of-bounds.
        OR ROUND(@T, 0, 1) - ROUND(@T / 100, 0, 1) * 100 >= 60,
        --NULL is returned
        NULL,
        --Otherwise, the Date Time components are parsable into a DATETIME2.
        DATETIME2FROMPARTS
        (
            --Year
            @Y,
            --Month
            @M,
            --Day
            @D,
            --Hour
            ROUND(@T / 10000, 0, 1),
            --Minute
            ROUND(@T / 100, 0, 1) - ROUND(@T / 10000, 0, 1) * 100,
            --Second
            ROUND(@T, 0, 1) - ROUND(@T / 100, 0, 1) * 100,
            --Millisecond (multiplied by 1000 to use the first 3 decimal places).
            (@T - ROUND(@T, 0, 1)) * 1000,
            --Precision (3 is specified since only 3 decimal places become part of the integer for the fraction parameter above).
            3
        )
    )
</code>```

If you need millisecond precision different to 3 decimal places, where your millisecond precision is x, change 3 to x and * 1000 on the line above to * POWER(10, x).

Body:
Given the following fields:

Y INT, --Year.
M INT, --Month.
D INT, --Day.
T FLOAT --Hours (H), minutes (m), seconds (s) and milliseconds (x) (in the form HHmmss.xxx).

Is there a way to attempt to convert these values into a DATETIME2 without having to first convert them to a string-based data type?  If the attempt fails (e.g. due to an overflowing day value (e.g. 35th of January 2019)), I would like NULL to be returned.

If I use DATETIME2FROMPARTS it will simply fail if passed any invalid component.

I am trying to avoid converting these into a string as the only reason I am trying this compromised solution is because the performance of my other solution which actually handles overflow and underflow, is incredibly slow against a large database (doesn't complete in 5 hours!) so I'm trying to try something simpler to see if it improves the performance of adding this as a computed persisted column.

Body:
Here is the bespoke solution I ended up writing for this.  There is unfortunately repeated logic since I'm using this in a persisted computed column and thus cannot use variables or scalar functions (for parameters to be used as variables).

DECLARE @Y INT = 2000, @M INT = 2, @D INT = 29, @T FLOAT = 135559.999

SELECT IIF
    (
        --If the Year is out-of-bounds.
        @Y <= 0 OR @Y > 9999
        --Or the Month is out-of-bounds.
        OR @M <= 0 OR @M > 12
        --Or the Day is out-of-bounds (Accounts for leap years).
        OR @D <= 0 OR @D > DAY(EOMONTH(DATETIME2FROMPARTS(@Y, @M, 1, 0, 0, 0, 0, 3)))
        --Or the Time is less than 0
        OR @T < 0
        --Or the Hour is out-of-bounds.
        OR ROUND(@T / 10000, 0, 1) >= 24
        --Or the Minute is out-of-bounds.
        OR ROUND(@T / 100, 0, 1) - ROUND(@T / 10000, 0, 1) * 100 >= 60
        --Or the Second is out-of-bounds.
        OR ROUND(@T, 0, 1) - ROUND(@T / 100, 0, 1) * 100 >= 60,
        --NULL is returned
        NULL,
        --Otherwise, the Date Time components are parsable into a DATETIME2.
        DATETIME2FROMPARTS
        (
            --Year
            @Y,
            --Month
            @M,
            --Day
            @D,
            --Hour
            ROUND(@T / 10000, 0, 1),
            --Minute
            ROUND(@T / 100, 0, 1) - ROUND(@T / 10000, 0, 1) * 100,
            --Second
            ROUND(@T, 0, 1) - ROUND(@T / 100, 0, 1) * 100,
            --Millisecond (multiplied by 1000 to use the first 3 decimal places).
            (@T - ROUND(@T, 0, 1)) * 1000,
            --Precision (3 is specified since only 3 decimal places become part of the integer for the fraction parameter above).
            3
        )
    )

If you need millisecond precision different to 3 decimal places, where your millisecond precision is x, change 3 to x and * 1000 on the line above to * POWER(10, x).


问:
Cannot do CSS animation in Angular
I'm trying to use a vanilla css animation like so :

```<code>div {
  height: 0.5rem;
  width: 1rem;
  background-color: blue;
  transform-origin: left;
  transition: transform 5s;
  transition-delay: 2s;
  transform: scaleX(15);
}

</code>```

That it just not working at all. The div is displaying at scaleX(15)but with no duration.

It does work properly with CodePen but not with Stackblitz. What am I missing here? Can't CSS animation works with Angular?

答:
In Angular all CSS styles are encapsulated to the component by default, CSS animations do work in Angular, the framework does not (and cannot) do anything to stop the browser's DOM rendering. As long as your CSS rule selects an element correctly and the applied animations are correct then it will work.

It seems like you need to do 2 things

Make sure your styles are defined within the same component as the div elements that you want to animate (or read the Angular docs about non-encapsulated styles)

Your CSS animation does not work, you need to give it an initial state and then change the style based on an action. A simple example:

```<code>.my-div {
  height: 0.5rem;
  width: 20px;
  background-color: blue;
  transition: width 0.3s linear;
}

.my-div.animate {
  width: 200px;
}
</code>```

In your component you can set the animate class based on some logic for when you want the animation to trigger

In your template:

```<code><div [class.animate]="componentLoaded"></div>
</code>```

In your component:

```<code>export class MyComponent {
  componentLoaded = false;

  ngOnInit() {
    this.componentLoaded = true; // Will trigger animation
  }
}
</code>```

Title: Cannot do CSS animation in Angular

Body:
I'm trying to use a vanilla css animation like so :

div {
  height: 0.5rem;
  width: 1rem;
  background-color: blue;
  transform-origin: left;
  transition: transform 5s;
  transition-delay: 2s;
  transform: scaleX(15);
}

That it just not working at all. The div is displaying at scaleX(15)but with no duration.

It does work properly with CodePen but not with Stackblitz. What am I missing here? Can't CSS animation works with Angular?

Body:
In Angular all CSS styles are encapsulated to the component by default, CSS animations do work in Angular, the framework does not (and cannot) do anything to stop the browser's DOM rendering. As long as your CSS rule selects an element correctly and the applied animations are correct then it will work.

It seems like you need to do 2 things

Make sure your styles are defined within the same component as the div elements that you want to animate (or read the Angular docs about non-encapsulated styles)

Your CSS animation does not work, you need to give it an initial state and then change the style based on an action. A simple example:

.my-div {
  height: 0.5rem;
  width: 20px;
  background-color: blue;
  transition: width 0.3s linear;
}

.my-div.animate {
  width: 200px;
}

In your component you can set the animate class based on some logic for when you want the animation to trigger

In your template:

<div [class.animate]="componentLoaded"></div>

In your component:

export class MyComponent {
  componentLoaded = false;

  ngOnInit() {
    this.componentLoaded = true; // Will trigger animation
  }
}


问:
Creating Ruby on Rails cloud hosting
There is a lot of demand in my country for rails and hosting, yet there is not one provider that does this. Are there packaged solutions, or at least guides, out there that can help me get started with providing hosting to people?

You can think of it as a local Heroku.com

答:
Partnering with Jelastic PaaS is a perfect match here. This cloud platform provides out-of-box support for Ruby hosting with automated deployment to containers, automatic scaling and intuitive UI for management https://jelastic.com/blog/ruby-paas-hosting/

And it can be installed on top of any infrastructure (bare metal, IaaS, clouds like Azure or GCP). Currently, it is already available in many countries from local service providers https://jelastic.cloud/

If interested, just drop a message here https://jelastic.com/cloud-platform-for-hosting-providers/

ContentLicense: CC BY-SA 2.5

Title: Creating Ruby on Rails cloud hosting


问:
I want to readers/writers problem with binary semaphore
I have 5 writers, 20 readers.
I want to solve readers/writers problem with binary semaphore.

But my code has some problem. There is segmentation fault(core dumped).
I think that there is a problem when creating threads.
How can I solve the problem? and Is this right code to solve r/w problem?
I used my text book's pseudo code.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

sem_t mutex, rw_mutex;

int data = 0;
int readcount = 0;

void *reader(void* i)
{
    int num = *((int*)i);
    sem_wait(&mutex);
    readcount += 1;
    if(readcount == 1)
            sem_wait(&rw_mutex);
    sem_post(&mutex);

    printf("I'm reader%d, data is %d \n", num, data);
    sem_wait(&mutex);

    readcount -= 1;
    if( readcount == 0)
            sem_post(&rw_mutex);
    sem_post(&mutex);
}

void *writer(void *i)
{
      int num = *((int*)i);
      sem_wait(&rw_mutex);
      data++;
      printf("I'm writer%d, data is %d\n", num, data);
      sem_post(&rw_mutex);
}

void main()
{
      int i;
      pthread_t writer[5], reader[20];
      sem_init(&rw_mutex, 0, 1);
      sem_init(&mutex, 0, 1);

      for(i=0; i<5; i++)
              pthread_create(&writer[i], NULL, writer, &i);
      for(i=0; i<20; i++)
              pthread_create(&reader[i], NULL, reader, &i);
      for(i=0; i<5; i++)
            pthread_join(writer[i], NULL);
      for(i=0; i<20; i++)
              pthread_join(reader[i], NULL);
      printf("End \n");
}
</code>```

答:
Have you checked the warnings from your compiler? I get several warnings. One example is:

warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [enabled by default]
                 pthread_create(&reader[i], NULL, reader, &i);

The problem is that in main you have an array with the name reader but in the program you also have a function named reader. So the compiler (i.e. at least my compiler) use the array when you actually want the function. And the program crash.

Fix the warnings! Either by renaming the functions reader and writer or by renaming the arrays.

After that I don't see a program crash anymore.

Body:
I have 5 writers, 20 readers.
I want to solve readers/writers problem with binary semaphore.

But my code has some problem. There is segmentation fault(core dumped).
I think that there is a problem when creating threads.
How can I solve the problem? and Is this right code to solve r/w problem?
I used my text book's pseudo code.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

sem_t mutex, rw_mutex;

int data = 0;
int readcount = 0;

void *reader(void* i)
{
    int num = *((int*)i);
    sem_wait(&mutex);
    readcount += 1;
    if(readcount == 1)
            sem_wait(&rw_mutex);
    sem_post(&mutex);

    printf("I'm reader%d, data is %d \n", num, data);
    sem_wait(&mutex);

    readcount -= 1;
    if( readcount == 0)
            sem_post(&rw_mutex);
    sem_post(&mutex);
}

void *writer(void *i)
{
      int num = *((int*)i);
      sem_wait(&rw_mutex);
      data++;
      printf("I'm writer%d, data is %d\n", num, data);
      sem_post(&rw_mutex);
}

void main()
{
      int i;
      pthread_t writer[5], reader[20];
      sem_init(&rw_mutex, 0, 1);
      sem_init(&mutex, 0, 1);

      for(i=0; i<5; i++)
              pthread_create(&writer[i], NULL, writer, &i);
      for(i=0; i<20; i++)
              pthread_create(&reader[i], NULL, reader, &i);
      for(i=0; i<5; i++)
            pthread_join(writer[i], NULL);
      for(i=0; i<20; i++)
              pthread_join(reader[i], NULL);
      printf("End \n");
}


问:
Matrix multiplication (element-wise) from numpy to Pytorch
I got two numpy arrays (image and and environment map),

```<code>MatA
MatB
</code>```

Both with shapes (256, 512, 3)

When I did the multiplication (element-wise) with numpy:

```<code>prod = np.multiply(MatA,MatB)
</code>```

I got the wanted result (visualize via Pillow when turning back to Image)

But when I did it using pytorch, I got a really strange result(not even close to the aforementioned).

I did it with the following code:

```<code>MatATensor = transforms.ToTensor()(MatA)
MatBTensor = transforms.ToTensor()(MatB)

prodTensor = MatATensor * MatBTensor
</code>```

For some reasons, the shape for both MatATensor and MatBtensor is

```<code>torch.Size([3, 256, 512])
</code>```

Same for the prodTensor too.
When I tried to reshape to (256,512,3), I got an error.

Is there a way to get the same result?

I am new to pytorch, so any help would be appreciated.

答:
If you read the documentation of transforms.ToTensor() you'll see this transformation does not only convert a numpy array to torch.FloatTensor, but also transpose its dimensions from HxWx3 to 3xHxW.

To "undo" this you'll need to

```<code> prodasNp = (prodTensor.permute(2, 0, 1) * 255).to(torch.uint8).numpy()
</code>```

See permute for more information.

Body:
I got two numpy arrays (image and and environment map),

MatA
MatB

Both with shapes (256, 512, 3)

When I did the multiplication (element-wise) with numpy:

prod = np.multiply(MatA,MatB)

I got the wanted result (visualize via Pillow when turning back to Image)

But when I did it using pytorch, I got a really strange result(not even close to the aforementioned).

I did it with the following code:

MatATensor = transforms.ToTensor()(MatA)
MatBTensor = transforms.ToTensor()(MatB)

prodTensor = MatATensor * MatBTensor

For some reasons, the shape for both MatATensor and MatBtensor is

torch.Size([3, 256, 512])

Same for the prodTensor too.
When I tried to reshape to (256,512,3), I got an error.

Is there a way to get the same result?

I am new to pytorch, so any help would be appreciated.

Body:
If you read the documentation of transforms.ToTensor() you'll see this transformation does not only convert a numpy array to torch.FloatTensor, but also transpose its dimensions from HxWx3 to 3xHxW.

To "undo" this you'll need to

 prodasNp = (prodTensor.permute(2, 0, 1) * 255).to(torch.uint8).numpy()

See permute for more information.


问:
Cordova Android not allowing to open whitelisted intent to fb-messenger
I have an Ionic Cordova app for android which has a button to facebook messenger:

```<code><a href="https://m.me/my-fb-page" target="_blank"><img src="assets/images/messenger.svg" /></a>
</code>```

When tapped, nothing appears on the screen. I keep receiving this error through logcat:

```<code>CordovaWebViewImpl: Blocked (possibly sub-frame) navigation to non-allowed URL: intent://user/xxxxxxxxxxxxx/?intent_trigger=mme&nav=discover#Intent;scheme=fb-messenger;package=com.facebook.orca;end
</code>```

I have cordova-plugin-whitelist installed.

Content of config.xml:

```<code>    ...
    <content src="index.html" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-navigation href="*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <allow-intent href="fb-messenger:*" />
    <platform name="android">
        <allow-intent href="market:*" />
        <allow-intent href="fb-messenger:*" />
        ...
</code>```

I have tried a number of options for allow-intent, access and allow navigation.

The issue is not specifically related to facebook messenger, I have problems with opening other external (payment) apps as well

答: With <allow-navigation href="*" /> you are telling your app to navigate to every url, that prevents any allow-intent from working as it will try to navigate to it instead of launching the intent.

Body:
I have an Ionic Cordova app for android which has a button to facebook messenger:

When tapped, nothing appears on the screen. I keep receiving this error through logcat:

CordovaWebViewImpl: Blocked (possibly sub-frame) navigation to non-allowed URL: intent://user/xxxxxxxxxxxxx/?intent_trigger=mme&nav=discover#Intent;scheme=fb-messenger;package=com.facebook.orca;end

I have cordova-plugin-whitelist installed.

Content of config.xml:

    ...
    <content src="index.html" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-navigation href="*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <allow-intent href="fb-messenger:*" />
    <platform name="android">
        <allow-intent href="market:*" />
        <allow-intent href="fb-messenger:*" />
        ...

I have tried a number of options for allow-intent, access and allow navigation.

The issue is not specifically related to facebook messenger, I have problems with opening other external (payment) apps as well


问:
test case format for login page contains 2 fields only
What is the format of writing the test case documentation for login page which contains only userid and password field and for birth form?</p>

答:
Give the Username as string in the User name field, which is of maximum .

Provide the relevant Password, after giving the password if click on submit button and if the password and username matches for a particular user then the application allows the user to login or else gives an error message.

ContentLicense: CC BY-SA 3.0


问:
How can I return a reference to a sub-element of a nested entry in a structure?
I have structure with a vector of other structures:

```<code>pub struct StructB {
    value1: u64,
    value2: String,
}

pub struct StructA {
    array: Vec<StructB>,
}
</code>```

StructB is constant; during the creation of StructA, an array is filled with the objects that are read from a file and is unlikely to be modified.

I would like to have a function to get element StructB corresponding to an input parameter: get_structB(input: u64) -> &StructB. For the sake of simplicity, let's say that we will just return element with the given index, assuming that someone else is checking boundaries.

I struggle with how to implement that in Rust. I would like to return a kind of "read only" reference or a reference to an object that is immutable but not doing a copy. I cannot figure out the proper way to do that.

```<code>impl StructA {
    fn get_structB(&self, idx: u64) -> Box<StructB> {   // Or should I use here Rc?
        // Here I don't want to consume self just return reference wrapped to the idx element
        // Should I implement something like as_ref() for the StructA?
        self.array[idx]     // That of course won't compile
    }
}
</code>```

答:
impl StructA {
    fn get_structB(&self, i: usize) -> &StructB {
        return &self.array[i];
    }
}
```

<p>This does the trick. However, you may encounter some problem if you write the following:</p>

<pre class="lang-rust prettyprint-override"><code>// `a` is a StructA instance
let bb = a.get_struct_b(0);
println!("{:?}", bb);
drop(a);              // move out of `a` occurs here
println!("{:?}", bb); // borrow of `a` is used here
</code>```

You will have to modify your struct definition and use Rc to write the function. Rc introduces a little performance impact and makes the code more complex, so you may want to use it only when you know that the data will be used after moving StructA.

pub struct StructA {
    array: Vec<Rc<StructB>>,
}

impl StructA {
    fn get_structB(&self, i: usize) -> Rc<StructB> {
        return Rc::clone(self.array[i]);
    }
}
```

Body:
I have structure with a vector of other structures:

pub struct StructB {
    value1: u64,
    value2: String,
}

pub struct StructA {
    array: Vec<StructB>,
}

StructB is constant; during the creation of StructA, an array is filled with the objects that are read from a file and is unlikely to be modified.

I would like to have a function to get element StructB corresponding to an input parameter: get_structB(input: u64) -> &StructB. For the sake of simplicity, let's say that we will just return element with the given index, assuming that someone else is checking boundaries.

I struggle with how to implement that in Rust. I would like to return a kind of "read only" reference or a reference to an object that is immutable but not doing a copy. I cannot figure out the proper way to do that.

impl StructA {
    fn get_structB(&self, idx: u64) -> Box<StructB> {   // Or should I use here Rc?
        // Here I don't want to consume self just return reference wrapped to the idx element
        // Should I implement something like as_ref() for the StructA?
        self.array[idx]     // That of course won't compile
    }
}

Body:
impl StructA {
    fn get_structB(&self, i: usize) -> &StructB {
        return &self.array[i];
    }
}

This does the trick. However, you may encounter some problem if you write the following:

// `a` is a StructA instance
let bb = a.get_struct_b(0);
println!("{:?}", bb);
drop(a);              // move out of `a` occurs here
println!("{:?}", bb); // borrow of `a` is used here

You will have to modify your struct definition and use Rc to write the function. Rc introduces a little performance impact and makes the code more complex, so you may want to use it only when you know that the data will be used after moving StructA.

pub struct StructA {
    array: Vec<Rc<StructB>>,
}

impl StructA {
    fn get_structB(&self, i: usize) -> Rc<StructB> {
        return Rc::clone(self.array[i]);
    }
}


问:
How to I explore data by a certain column in R
I'm having difficulty exploring, summarising and vizualizing a data frame by a specific column. My data "services" is in the following format (I will insert only the first 5 rows, as my data is very large:

```<code>services = data.frame(ID = 1:5,
           Sex = c('F','F','M','M','M'),
           Internet_Service = c(rep('Fiber optic', 2), rep('DSL',3)),
           Phone_service = c('Yes', 'Yes','Yes','No', 'No'),
           Payment_method = c('transfer','transfer','bill','bill','bill'),
           Monthly_charges = c(23,45,54,65,65),
           Total_Charges = c(78,67,98,67,90),
           Churn = c('Yes', 'No', 'Yes', 'No', 'Yes'))
</code>```

I have explored the data by 'Churn' (please see the code below).   I would now like to explore by 'Total_Charges', but this is numeric data rather than a factor and I'm not sure how to proceed.  I would like to generate summaries and graphs.

```<code>services %>%
  group_by(Churn) %>%
  summarise(Count = n())%>%
  mutate(percent = prop.table(Count)*100)%>%
  ggplot(aes(reorder(Churn, -percent), percent), fill = Churn)+
  geom_col(fill = c("#505050", "#D3D3D3"))+
  theme_bw()+
  scale_y_continuous(expand = c(0, 0), limits = c(0,100))   +
  xlab("Churn") +
  ylab("Percent")+
  ggtitle("Churn Percent")
</code>```

Could you please help me to figure out?
Thank you.

答:
How's this?</p>

```<code>    services %>%
    group_by(Sex) %>% #you can use any of the factors to group by
    summarise(mean=mean(Total_Charges))
    services %>%
    ggplot(aes(Sex,Total_Charges))+
    geom_boxplot()+
    theme_bw()
</code>```

Body:
I'm having difficulty exploring, summarising and vizualizing a data frame by a specific column. My data "services" is in the following format (I will insert only the first 5 rows, as my data is very large:

services = data.frame(ID = 1:5,
           Sex = c('F','F','M','M','M'),
           Internet_Service = c(rep('Fiber optic', 2), rep('DSL',3)),
           Phone_service = c('Yes', 'Yes','Yes','No', 'No'),
           Payment_method = c('transfer','transfer','bill','bill','bill'),
           Monthly_charges = c(23,45,54,65,65),
           Total_Charges = c(78,67,98,67,90),
           Churn = c('Yes', 'No', 'Yes', 'No', 'Yes'))

I have explored the data by 'Churn' (please see the code below).   I would now like to explore by 'Total_Charges', but this is numeric data rather than a factor and I'm not sure how to proceed.  I would like to generate summaries and graphs.

services %>%
  group_by(Churn) %>%
  summarise(Count = n())%>%
  mutate(percent = prop.table(Count)*100)%>%
  ggplot(aes(reorder(Churn, -percent), percent), fill = Churn)+
  geom_col(fill = c("#505050", "#D3D3D3"))+
  theme_bw()+
  scale_y_continuous(expand = c(0, 0), limits = c(0,100))   +
  xlab("Churn") +
  ylab("Percent")+
  ggtitle("Churn Percent")

Could you please help me to figure out?
Thank you.

Body:
How's this?

    services %>%
    group_by(Sex) %>% #you can use any of the factors to group by
    summarise(mean=mean(Total_Charges))
    services %>%
    ggplot(aes(Sex,Total_Charges))+
    geom_boxplot()+
    theme_bw()


问:
Item overlap in recyclerview
I want to overlap first item on second item in recycler view .

this is what I want to achieve:

this is how my recycler view is looking now:

[]

content inside green border is actually a recyclerView  and the first item in parent recycler view and the rating bar layout is the second item in parent recyclerview .
please suggest me how can i overlap first item on to second item
i have tried this

item_rating_layout:

```<code> <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        style="@style/LayoutHeightWrapWidthMatchStyling"
        android:layout_width="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        android:padding="@dimen/padding_large">

        <TextView
            android:id="@+id/tvRatingMessage"
            style="@style/TextStyleNormal.XXLarge"
            android:text="@string/rating_exp" />

        <RatingBar
            android:id="@+id/ratingBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/margin_medium"
            android:numStars="5"
            android:progressBackgroundTint="@color/gray"
            android:stepSize="1.0"
            android:progressTint="@color/primaryColor"
            android:rating="2.5" />

        <TextView
            android:id="@+id/tvWriteFeedBack"
            style="@style/TextStyleNormal.XXXLarge.primary"
            android:padding="@dimen/padding_medium"
            android:text="Write Feedback"
            android:visibility="gone" />

    </LinearLayout>
</code>```

item_recycler_view:

```<code> <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tool="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_24dp"
        android:layout_marginEnd="@dimen/margin_24dp"
        android:background="@color/warranty_card_background">

        <androidx.core.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/btn_shap_without_solid_green"
                android:gravity="center_horizontal"
                android:orientation="vertical">

                <ImageView
                    android:id="@+id/ivProductImage"
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_marginTop="@dimen/margin_medium"
                    android:scaleType="fitXY"
                    app:srcCompat="@drawable/ic_original_placeholder" />

                <TextView
                    android:id="@+id/tvName"
                    style="@style/TextStyleNormal.XXLarge.black"
                    android:textStyle="bold"
                    tool:text="Steelbird Air" />

                    <TextView
                        android:id="@+id/tvModel"
                        style="@style/TextStyleNormal.XXLarge"
                        tool:text="SBA-2 Horn Matt Black With Red " />

                <TextView
                    android:id="@+id/tvId"
                    style="@style/TextStyleNormal.XXLarge.gray"
                    android:text="@string/product_id" />

                <TextView
                    android:id="@+id/tvViewProductDetails"
                    style="@style/TextStyleNormal.XLarge.primary"
                    android:text="View product Details" />

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/rvWarrantyCard"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="@dimen/margin_medium"
                    android:layout_marginBottom="@dimen/margin_medium">

                </androidx.recyclerview.widget.RecyclerView>
            </LinearLayout>
        </androidx.core.widget.NestedScrollView>
    </LinearLayout>
</code>```

答: Use main layout Relative otherwise Frame layout</p>

Title: Item overlap in recyclerview

Body:
I want to overlap first item on second item in recycler view .

this is what I want to achieve:

this is how my recycler view is looking now:

[]

content inside green border is actually a recyclerView  and the first item in parent recycler view and the rating bar layout is the second item in parent recyclerview .
please suggest me how can i overlap first item on to second item
i have tried this

item_rating_layout:

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        style="@style/LayoutHeightWrapWidthMatchStyling"
        android:layout_width="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        android:padding="@dimen/padding_large">

        <TextView
            android:id="@+id/tvRatingMessage"
            style="@style/TextStyleNormal.XXLarge"
            android:text="@string/rating_exp" />

        <RatingBar
            android:id="@+id/ratingBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/margin_medium"
            android:numStars="5"
            android:progressBackgroundTint="@color/gray"
            android:stepSize="1.0"
            android:progressTint="@color/primaryColor"
            android:rating="2.5" />

        <TextView
            android:id="@+id/tvWriteFeedBack"
            style="@style/TextStyleNormal.XXXLarge.primary"
            android:padding="@dimen/padding_medium"
            android:text="Write Feedback"
            android:visibility="gone" />

    </LinearLayout>

item_recycler_view:

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tool="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/margin_24dp"
        android:layout_marginEnd="@dimen/margin_24dp"
        android:background="@color/warranty_card_background">

        <androidx.core.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/btn_shap_without_solid_green"
                android:gravity="center_horizontal"
                android:orientation="vertical">

                <ImageView
                    android:id="@+id/ivProductImage"
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:layout_marginTop="@dimen/margin_medium"
                    android:scaleType="fitXY"
                    app:srcCompat="@drawable/ic_original_placeholder" />

                <TextView
                    android:id="@+id/tvName"
                    style="@style/TextStyleNormal.XXLarge.black"
                    android:textStyle="bold"
                    tool:text="Steelbird Air" />

                    <TextView
                        android:id="@+id/tvModel"
                        style="@style/TextStyleNormal.XXLarge"
                        tool:text="SBA-2 Horn Matt Black With Red " />

                <TextView
                    android:id="@+id/tvId"
                    style="@style/TextStyleNormal.XXLarge.gray"
                    android:text="@string/product_id" />

                <TextView
                    android:id="@+id/tvViewProductDetails"
                    style="@style/TextStyleNormal.XLarge.primary"
                    android:text="View product Details" />

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/rvWarrantyCard"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="@dimen/margin_medium"
                    android:layout_marginBottom="@dimen/margin_medium">

                </androidx.recyclerview.widget.RecyclerView>
            </LinearLayout>
        </androidx.core.widget.NestedScrollView>
    </LinearLayout>


问:
Which part of the source code should I lock?
The following are the basic skeleton of my .net server:

C# server skeleton

```<code>class ServerProgram
{
    static string origClientID = string.Empty;
    static string reqClientID = string.Empty;
    static string stKey = string.Empty;
    static string stValue = string.Empty;
    static Dictionary<string, KeyValue> KeyValueDictionary;
    static Dictionary<string, ClientClass> ClientDictionary;

    static void Main(string[] args)
    {
        Console.Title = "Server";
        Console.WriteLine("Server program started on address [" + Constants.SERVER_IP +":"+Constants.PORT_NO+"]");

        KeyValueDictionary = new Dictionary<string, KeyValue>();
        ClientDictionary = new Dictionary<string, ClientClass>();

        string ipAddress = Constants.SERVER_IP;
        int portNo = Constants.PORT_NO;

        IPAddress ip = IPAddress.Parse(ipAddress);
        TcpListener listener = new TcpListener(ip, portNo);

        // poll for clients in a 2nd thread
        Thread thread = new Thread(delegate()
        {
            ServerProgram.PollIncomingClientConns(listener);
        });

        thread.Start();
    }

    #region catching client connections
    static void PollIncomingClientConns(TcpListener listener)
    {
        listener.Start();

        try
        {
            bool keepRunning = true;

            while (keepRunning)
            {
                ClientClass client = new ClientClass(listener);

                ClientDictionary.Add(client.ID, client);

                Thread thread = new Thread(delegate()
                {
                    ServerProgram.ReadFromClient(client);
                });
                thread.Start();
            }
        }
        catch (Exception ex)
        {
            var inner = ex.InnerException as SocketException;
            if (inner != null && inner.SocketErrorCode == SocketError.ConnectionReset)
                Console.WriteLine("Disconnected");
            else
                Console.WriteLine(ex.Message);

            listener.Stop();
        }
    }
    #endregion

    static void ReadFromClient(ClientClass client)
    {
       try
        {
            while (client.Tcp.Connected)
            {
                string str = client.Read();
                Console.WriteLine("[" + client.ID + "] says: " + str);

                switch(str)
                {
                    case Commands.AddKeyValue:
                        //...
                        break;

                    case Commands.ListKeys:
                        //...
                        break;

                    case Commands.UpdateValue:
                        //...
                        break;

                    case Commands.Yes:
                        //...
                        break;
                }
            }
        }
        catch
        {
            client.Disconnect();
        }
    }
}
</code>```

The objective of the program is:

the server keeps a common dictionary of key-values.

clients are able to add, update, and see the key-values in the server.

There are six static global variables used in the class.

Which of them should I lock before accessing (I think, dictionaries do not need locking)?

Which part of code should I lock?  Should I lock switch-cases individually, or, should I lock the entire while loop in static void ReadFromClient(ClientClass client)?

答:
We can definitely say that you should be synchronizing access of the two dictionaries - since no operations on dictionaries are documented as being thread-safe, and you're mutating them from multiple threads. Some similar structures do have thread-safety notes, but not Dictionary<TKey,TValue>.

Whether you need to synchronize the strings is ... tricky, not least because you don't show the usage. Reads and writes against reference-types (string) are atomic, and strings themselves are immutable (at least when used normally). However, if you are doing multiple operations that would assume an unchanged value between them, you may need to synchronize for the duration of composite operations. Additionally, keep in mind that you can't just lock (stValue), because when stValue changes, two different paths will be locking against different objects. Instead, you'd need a separate field that exists just for locking, and is independent of the value.

Finally, note that static fields - when mutable like this - are often a bad idea.

Body:
The following are the basic skeleton of my .net server:

C# server skeleton

class ServerProgram
{
    static string origClientID = string.Empty;
    static string reqClientID = string.Empty;
    static string stKey = string.Empty;
    static string stValue = string.Empty;
    static Dictionary<string, KeyValue> KeyValueDictionary;
    static Dictionary<string, ClientClass> ClientDictionary;

    static void Main(string[] args)
    {
        Console.Title = "Server";
        Console.WriteLine("Server program started on address [" + Constants.SERVER_IP +":"+Constants.PORT_NO+"]");

        KeyValueDictionary = new Dictionary<string, KeyValue>();
        ClientDictionary = new Dictionary<string, ClientClass>();

        string ipAddress = Constants.SERVER_IP;
        int portNo = Constants.PORT_NO;

        IPAddress ip = IPAddress.Parse(ipAddress);
        TcpListener listener = new TcpListener(ip, portNo);

        // poll for clients in a 2nd thread
        Thread thread = new Thread(delegate()
        {
            ServerProgram.PollIncomingClientConns(listener);
        });

        thread.Start();
    }

    #region catching client connections
    static void PollIncomingClientConns(TcpListener listener)
    {
        listener.Start();

        try
        {
            bool keepRunning = true;

            while (keepRunning)
            {
                ClientClass client = new ClientClass(listener);

                ClientDictionary.Add(client.ID, client);

                Thread thread = new Thread(delegate()
                {
                    ServerProgram.ReadFromClient(client);
                });
                thread.Start();
            }
        }
        catch (Exception ex)
        {
            var inner = ex.InnerException as SocketException;
            if (inner != null && inner.SocketErrorCode == SocketError.ConnectionReset)
                Console.WriteLine("Disconnected");
            else
                Console.WriteLine(ex.Message);

            listener.Stop();
        }
    }
    #endregion

    static void ReadFromClient(ClientClass client)
    {
       try
        {
            while (client.Tcp.Connected)
            {
                string str = client.Read();
                Console.WriteLine("[" + client.ID + "] says: " + str);

                switch(str)
                {
                    case Commands.AddKeyValue:
                        //...
                        break;

                    case Commands.ListKeys:
                        //...
                        break;

                    case Commands.UpdateValue:
                        //...
                        break;

                    case Commands.Yes:
                        //...
                        break;
                }
            }
        }
        catch
        {
            client.Disconnect();
        }
    }
}

The objective of the program is:

the server keeps a common dictionary of key-values.

clients are able to add, update, and see the key-values in the server.

There are six static global variables used in the class.

Which of them should I lock before accessing (I think, dictionaries do not need locking)?

Which part of code should I lock?  Should I lock switch-cases individually, or, should I lock the entire while loop in static void ReadFromClient(ClientClass client)?


问:
Triple ampersand in Sass
What does three ampersands do in Sass?

Here in a styled-components context:

```<code>const Grid = styled.div`
  display: grid;
  &&& {
    ${someFunction}
  }
`
</code>```

Seen in code here:
https://github.com/reakit/reakit/blob/website%400.16.0/packages/reakit/src/Grid/Grid.ts#L23

答:
The docs say it is to override any already given styles with a higher specificity, as an alternative to using !important.

It affects the generated css classes.

Title: Triple ampersand in Sass

Body:
What does three ampersands do in Sass?

Here in a styled-components context:

const Grid = styled.div`
  display: grid;
  &&& {
    ${someFunction}
  }
`

Seen in code here:
https://github.com/reakit/reakit/blob/website%400.16.0/packages/reakit/src/Grid/Grid.ts#L23


问:
xml.parsers.expat.ExpatError: not well-formed (invalid token)
When I use xmltodict to load the xml file below I get an error:
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 1

Here is my file:

```<code><?xml version="1.0" encoding="utf-8"?>
<mydocument has="an attribute">
  <and>
    <many>elements</many>
    <many>more elements</many>
  </and>
  <plus a="complex">
    element as well
  </plus>
</mydocument>
</code>```

Source:

```<code>import xmltodict
with open('fileTEST.xml') as fd:
   xmltodict.parse(fd.read())
</code>```

I am on Windows 10, using Python 3.6 and xmltodict 0.11.0

If I use ElementTree it works

```<code>tree = ET.ElementTree(file='fileTEST.xml')
    for elem in tree.iter():
            print(elem.tag, elem.attrib)

mydocument {'has': 'an attribute'}
and {}
many {}
many {}
plus {'a': 'complex'}
</code>```

Note: I might have encountered a new line problem.

Note2: I used Beyond Compare on two different files.

It crashes on the file that is UTF-8 BOM encoded, and works om the UTF-8 file.

  UTF-8 BOM is a sequence of bytes (EF BB BF) that allows the reader to identify a file as being encoded in UTF-8.

答:
In my case, the issue was with the first 3 characters. So removing them worked:</p>

```<code>import xmltodict
from xml.parsers.expat import ExpatError

with open('your_data.xml') as f:
    data = f.read()
    try:
        doc = xmltodict.parse(data)
    except ExpatError:
        doc = xmltodict.parse(data[3:])
</code>```

Body:
When I use xmltodict to load the xml file below I get an error:
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 1

Here is my file:

<?xml version="1.0" encoding="utf-8"?>
<mydocument has="an attribute">
  <and>
    <many>elements</many>
    <many>more elements</many>
  </and>
  <plus a="complex">
    element as well
  </plus>
</mydocument>

Source:

import xmltodict
with open('fileTEST.xml') as fd:
   xmltodict.parse(fd.read())

I am on Windows 10, using Python 3.6 and xmltodict 0.11.0

If I use ElementTree it works

tree = ET.ElementTree(file='fileTEST.xml')
    for elem in tree.iter():
            print(elem.tag, elem.attrib)

mydocument {'has': 'an attribute'}
and {}
many {}
many {}
plus {'a': 'complex'}

Note: I might have encountered a new line problem.

Note2: I used Beyond Compare on two different files.

It crashes on the file that is UTF-8 BOM encoded, and works om the UTF-8 file.

  UTF-8 BOM is a sequence of bytes (EF BB BF) that allows the reader to identify a file as being encoded in UTF-8.

Body:
In my case, the issue was with the first 3 characters. So removing them worked:

import xmltodict
from xml.parsers.expat import ExpatError

with open('your_data.xml') as f:
    data = f.read()
    try:
        doc = xmltodict.parse(data)
    except ExpatError:
        doc = xmltodict.parse(data[3:])


问:
Disable WordPress from adding
 tags
All I've got is the following little snippet of code:

```<code><select size="1" name="EventHour<?php echo $i; ?>">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
    <option>8</option>
    <option>9</option>
    <option>10</option>
    <option>11</option>
    <option>12</option>
  </select>
  : <!-- note this character -->
  <select size="1" name="EventMinute<?php echo $i; ?>">
    <option>00</option>
    <option>05</option>
    <option>10</option>
    <option>15</option>
    <option>20</option>
    <option>25</option>
    <option>30</option>
    <option>35</option>
    <option>40</option>
    <option>45</option>
    <option>50</option>
    <option>55</option>
  </select>
</code>```

The should output fine. However, WordPress adds a p-tag around both of my select-elements as well as around the ":"-character. This makes them all end up on different rows.

I've installed and activated the WordPress plugin "Disable Visual Editor WYSIWYG" on this page without any success. Any other ideas what I can do to stop this from happening?

答: If the post is custom post type, you can add meta box with add_meta_box and there you can initialize your own editor with wp_editor which can be customized. For example you can pass settings to the tinymce like 'force_p_newslines' and 'forced_root_block'</p>

Title: Disable WordPress from adding <p> tags

Body:
All I've got is the following little snippet of code:

<select size="1" name="EventHour<?php echo $i; ?>">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
    <option>8</option>
    <option>9</option>
    <option>10</option>
    <option>11</option>
    <option>12</option>
  </select>
  :
  <select size="1" name="EventMinute<?php echo $i; ?>">
    <option>00</option>
    <option>05</option>
    <option>10</option>
    <option>15</option>
    <option>20</option>
    <option>25</option>
    <option>30</option>
    <option>35</option>
    <option>40</option>
    <option>45</option>
    <option>50</option>
    <option>55</option>
  </select>

The should output fine. However, WordPress adds a p-tag around both of my select-elements as well as around the ":"-character. This makes them all end up on different rows.

I've installed and activated the WordPress plugin "Disable Visual Editor WYSIWYG" on this page without any success. Any other ideas what I can do to stop this from happening?


问:
Send a webhook request when a defined comment is received
My question is simple: is there a way to activate a webhook only if the commit message received from the push is equal to a phrase we already defined.

Example: Let's say my message signal would be "Launch me"

if I do the following:

```<code>git commit -m "Imported Something"
git push origin master
</code>```

then nothing will happen. But with:

```<code>git commit -m "Launch me"
git push origin master
</code>```

then the webhook will get launched and send the signal to the address configured.

Thank you.

答:
You could actually use something called git hooks for rejecting the commit/push based on the commit-message phrase and based on that webhook will be triggered automatically if it is configured to be invoked for push events.
please refer to this link
https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks</p>

Body:
My question is simple: is there a way to activate a webhook only if the commit message received from the push is equal to a phrase we already defined.

Example: Let's say my message signal would be "Launch me"

if I do the following:

git commit -m "Imported Something"
git push origin master

then nothing will happen. But with:

git commit -m "Launch me"
git push origin master

then the webhook will get launched and send the signal to the address configured.

Thank you.


问:
How to mount a component on click?
I'm using this react-csv, and it triggers the download only when it gets mounted. The problem is that I have a normal material button, and I need to trigger that when that button is clicked:

```<code><MButton id="csv-download" onClick={<CSVDownload data={this.state.rowData} filename={"relatorio.csv"} target="csv-download"/>} style={{
    ...buttons.action,
    ...buttons.topRight
}}>Exportar</MButton>
</code>```

The component inside the onClick sounds absurd, but I've put it there to illustrate my point. How can I do it?

答:
I've not tested this, but I've done something like this in the past:

```<code>downloadCSV() {
  this.setState({
    downloadCSV: true
  })
}

renderCSVDownload() {
  if(this.state.downloadCSV) {
    return (
      <CSVDownload
        data={this.state.rowData}
        filename={"relatorio.csv"}
        target="csv-download"/>
    )
  }
}

render() {
  return (
    <div>
      <MButton id="csv-download" onClick={this.downloadCSV} style={{
          ...buttons.action,
          ...buttons.topRight
      }}>Exportar</MButton>
      {this.renderCSVDownload()}
    </div>
  )
}

</code>```

While CSVLink already does what you are attempting, it is not a Material button (MButton):

```<code><CSVLink
  data={this.state.rowData}
  filename={"relatorio.csv"}
  target="csv-download"
>Exportar</CSVLink>
</code>```

Title: How to mount a component on click?

Body:
I'm using this react-csv, and it triggers the download only when it gets mounted. The problem is that I have a normal material button, and I need to trigger that when that button is clicked:

<MButton id="csv-download" onClick={<CSVDownload data={this.state.rowData} filename={"relatorio.csv"} target="csv-download"/>} style={{
    ...buttons.action,
    ...buttons.topRight
}}>Exportar</MButton>

The component inside the onClick sounds absurd, but I've put it there to illustrate my point. How can I do it?

Body:
I've not tested this, but I've done something like this in the past:

downloadCSV() {
  this.setState({
    downloadCSV: true
  })
}

renderCSVDownload() {
  if(this.state.downloadCSV) {
    return (
      <CSVDownload
        data={this.state.rowData}
        filename={"relatorio.csv"}
        target="csv-download"/>
    )
  }
}

render() {
  return (
    <div>
      <MButton id="csv-download" onClick={this.downloadCSV} style={{
          ...buttons.action,
          ...buttons.topRight
      }}>Exportar</MButton>
      {this.renderCSVDownload()}
    </div>
  )
}

While CSVLink already does what you are attempting, it is not a Material button (MButton):

<CSVLink
  data={this.state.rowData}
  filename={"relatorio.csv"}
  target="csv-download"
>Exportar</CSVLink>


问:
How to read and convert Bluetooth characteristic from byte data to proper values(Bluetooth for flutter)
I have to read and write some values to a Bike Smart trainer with BLE (Bluetooth Low Energy) used with Flutter. When I try to read the values from the GATT characteristic org.bluetooth.characteristic.supported_power_range (found on bluetooth.org site https://www.bluetooth.com/specifications/gatt/characteristics/ ) I get the return value of an Int List [0,0,200,0,1,0].

The GATT characteristic sais that there are 3 sint16 fields for Min., Max. and step size Watts (Power).

The Byte transmission order also sais that the least significant octet is transmitted first.

My guessings are, that the 3 parameters are returned in an Int array with 8bit value each. But I can't interpret the 200 for maybe the maximum Power setting. Because the smart trainer should provide max. 2300W Watts resistance (ELITE Drivo https://www.elite-it.com/de/produkte/home-trainer/rollentrainer-interaktive/drivo)

The Output results from this code snippet:

device.readCharacteristic(savedCharacteristics[Characteristics.SUPPORTED_POWER_RANGE]).then((List<int> result) {
  result.forEach((i) {
    print(i.toString());
  });
});
// result: [0,0,200,0,1,0]
```

Maybe some one of u knows how to interpret the binary/hex/dec values of the flutter_blue characteristic output.
Or some hints would be great

Edit

For future readers, I got the solution. I'm a bit asheamed because I read the wrong characteristic.

The return value [0,0,200,0,1,0] was for supported resistance level. (which is 20% and the 200 shows the 20% with a resolution of 0.1 like described in the GATT spec)

I also got a return value for the supported power level which was [0,0,160,15,1,0]. Now the solution how to read the 2 Bytes of max powre level: you get the 160,15 the spec sais LSO (least significant octet first, don't confuse it with LSB least significant bit first). In fact of that you have to read it like 15,160. now do the math with the first Byte 15*256 + 160 = 4000 and thats the correct maximum supported power of the trainer like in the datasheet.

I hope I help someone with that. Thanks for the two replys they are also correct and helped me to find my mistake.

答:
You can use my package byte_data_wrapper to transform this data to a decimal value which you can understand:

Get the buffer:

```<code>import 'dart:typed_data';

final buffer = Uint16List.fromList(result).buffer;
</code>```

Create the byteDataCreator:

```<code>// Don't forget to add it to your pubspec.yaml
//dependencies:
//  byte_data_wrapper:
//    git: git://github.com/Taym95/byte_data_wrapper.git

import 'byte_data_wrapper/byte_data_wrapper.dart';

final byteDataCreator = ByteDataCreator.view(buffer);
</code>```

Get your data :

```<code>// You can use getUint8() if valeu is Uint8
final min = byteDataCreator.getUint16();
final max = byteDataCreator.getUint16();
final stepSize = byteDataCreator.getUint16();
</code>```

Body:
I have to read and write some values to a Bike Smart trainer with BLE (Bluetooth Low Energy) used with Flutter. When I try to read the values from the GATT characteristic org.bluetooth.characteristic.supported_power_range (found on bluetooth.org site https://www.bluetooth.com/specifications/gatt/characteristics/ ) I get the return value of an Int List [0,0,200,0,1,0].

The GATT characteristic sais that there are 3 sint16 fields for Min., Max. and step size Watts (Power).

The Byte transmission order also sais that the least significant octet is transmitted first.

My guessings are, that the 3 parameters are returned in an Int array with 8bit value each. But I can't interpret the 200 for maybe the maximum Power setting. Because the smart trainer should provide max. 2300W Watts resistance (ELITE Drivo https://www.elite-it.com/de/produkte/home-trainer/rollentrainer-interaktive/drivo)

The Output results from this code snippet:

device.readCharacteristic(savedCharacteristics[Characteristics.SUPPORTED_POWER_RANGE]).then((List<int> result) {
  result.forEach((i) {
    print(i.toString());
  });
});
// result: [0,0,200,0,1,0]

Maybe some one of u knows how to interpret the binary/hex/dec values of the flutter_blue characteristic output.
Or some hints would be great

Edit

For future readers, I got the solution. I'm a bit asheamed because I read the wrong characteristic.

The return value [0,0,200,0,1,0] was for supported resistance level. (which is 20% and the 200 shows the 20% with a resolution of 0.1 like described in the GATT spec)

I also got a return value for the supported power level which was [0,0,160,15,1,0]. Now the solution how to read the 2 Bytes of max powre level: you get the 160,15 the spec sais LSO (least significant octet first, don't confuse it with LSB least significant bit first). In fact of that you have to read it like 15,160. now do the math with the first Byte 15*256 + 160 = 4000 and thats the correct maximum supported power of the trainer like in the datasheet.

I hope I help someone with that. Thanks for the two replys they are also correct and helped me to find my mistake.

Body:
You can use my package byte_data_wrapper to transform this data to a decimal value which you can understand:

Get the buffer:

import 'dart:typed_data';

final buffer = Uint16List.fromList(result).buffer;

Create the byteDataCreator:

// Don't forget to add it to your pubspec.yaml
//dependencies:
//  byte_data_wrapper:
//    git: git://github.com/Taym95/byte_data_wrapper.git

import 'byte_data_wrapper/byte_data_wrapper.dart';

final byteDataCreator = ByteDataCreator.view(buffer);

Get your data :

// You can use getUint8() if valeu is Uint8
final min = byteDataCreator.getUint16();
final max = byteDataCreator.getUint16();
final stepSize = byteDataCreator.getUint16();


问:
Client on Node.js: Uncaught ReferenceError: require is not defined
I am writing an application with the Node.js, Express.js, and Jade combination.

I have file client.js, which is loaded on the client. In that file I have code that calls functions from other JavaScript files. My attempt was to use

```<code>var m = require('./messages');
</code>```

in order to load the contents of messages.js (just like I do on the server side) and later on call functions from that file. However, require is not defined on the client side, and it throws an error of the form Uncaught ReferenceError: require is not defined.

These other JavaScript files are also loaded at runtime at the client, because I place the links at the header of the webpage. So the client knows all the functions that are exported from these other files.

How do I call these functions from these other JavaScript files (such as messages.js) in the main client.js file that opens the socket to the server?

答:
I am coming from an Electron environment, where I need IPC communication between a renderer process and the main process. The renderer process sits in an HTML file between script tags and generates the same error.

The line

```<code>const {ipcRenderer} = require('electron')
</code>```

throws the Uncaught ReferenceError: require is not defined

I was able to work around that by specifying Node.js integration as true when the browser window (where this HTML file is embedded) was originally created in the main process.

```<code>function createAddItemWindow() {

    // Create a new window
    addItemWindown = new BrowserWindow({
        width: 300,
        height: 200,
        title: 'Add Item',

        // The lines below solved the issue
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false
        }
})}
</code>```

That solved the issue for me. The solution was proposed here.

Body:
I am writing an application with the Node.js, Express.js, and Jade combination.

I have file client.js, which is loaded on the client. In that file I have code that calls functions from other JavaScript files. My attempt was to use

var m = require('./messages');

in order to load the contents of messages.js (just like I do on the server side) and later on call functions from that file. However, require is not defined on the client side, and it throws an error of the form Uncaught ReferenceError: require is not defined.

These other JavaScript files are also loaded at runtime at the client, because I place the links at the header of the webpage. So the client knows all the functions that are exported from these other files.

How do I call these functions from these other JavaScript files (such as messages.js) in the main client.js file that opens the socket to the server?

Body:
I am coming from an Electron environment, where I need IPC communication between a renderer process and the main process. The renderer process sits in an HTML file between script tags and generates the same error.

The line

const {ipcRenderer} = require('electron')

throws the Uncaught ReferenceError: require is not defined

I was able to work around that by specifying Node.js integration as true when the browser window (where this HTML file is embedded) was originally created in the main process.

function createAddItemWindow() {

    // Create a new window
    addItemWindown = new BrowserWindow({
        width: 300,
        height: 200,
        title: 'Add Item',

        // The lines below solved the issue
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false
        }
})}

That solved the issue for me. The solution was proposed here.


问:
Security in Android Application
I am working on the android application and I want to make the app more secure, so I would like to know the different types of security measures can be added to the application to make the app secure?</p>

答:
Google have created set of tips to optimism your app for security on bellow link.

https://developer.android.com/topic/security/best-practices

Title: Security in Android Application


问:
iOS8 extension needs own provisioning profile?
I am starting an iOS 8 extension but I can't run it on my device. The error when trying to run it is:

No matching provisioning profiles found

The provisioning profile specified in your build settings
  (“ExtensionName”) has an AppID of net.company.AppName which does not
  match your bundle identifier net.company.AppName.ExtensionName.
  Xcode can resolve this issue by downloading a new provisioning profile
  from the Member Center.

Do I need a separate provisioning profile for both the main app and the extension ?

Should they share a bundle identifier (by default it adds the extension name to the bundle identifier, so perhaps not) ?

If it has a separate bundle identifier how is that reflected in the provisioning profile (if there is a separate one) ?

答:
I simply use "Automatically manage sign in" until I need to push to App store. This works out of the box with simulators, haven't tried with devices yet.

Few pointers for Appstore Build:

I created one wildcard id for every notification extension, but the prefix of this wildcard bundle id should match your app's bundle id as prefixed. If it's not like this, this error will come up: "Embedded binary's bundle identifier is not prefixed with the parent app's bundle identifier". So, if your app's bundle-id is: "com.companyName.appName", the wildcard bundle-id for your extension should be "com.companyName.appName.*". You can then replace * with a specific notification extension in the XCode. Note apple only allows one period(".") after the app's bundle id for naming your extension's bundle id.

The version and build number of your extension should match that of your app.

Once App Id is created, create a distribution provisioning profile with this and use it in XCode.


问:
Storing user's IP address in django's database on POST requests
Trying to store user's IP address when he's sending POST requests via submitting my form, tried more than a few suggestions on getting the IP address, but didn't manage to make it work properly as I always get null values stored for the IP in the database table.

I tried using model forms and setting the ip address as a variable inside the form so I can store it more easily into the database using request.META.get, and x_forwarded_for to get the actual address from the request in views.py.
My app built as below:

models.py:

```<code>class RequestPull(models.Model):
    a =  models.CharField(max_length=10)
    b =  models.CharField(max_length=10)
    ip_address = models.GenericIPAddressField(null=True)
</code>```

forms.py:

```<code>class GetReq(forms.ModelForm):
    class Meta:
        model = RequestPull
            fields = ['a','b','ip_address']
</code>```

views.py (one of the attempts that give the same result- null values in the database):

```<code>def get_client_ip(request):
    remote_address = request.META.get('HTTP_X_FORWARDED_FOR') or request.META.get('REMOTE_ADDR')
    ip = remote_address
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        proxies = x_forwarded_for.split(',')
        while (len(proxies) > 0 and proxies[0].startswith(PRIVATE_IPS_PREFIX)):
            proxies.pop(0)
            if len(proxies) > 0:
                ip = proxies[0]
                print"IP Address",ip
        return ip

def reqPull(request):
    if request.method == 'GET':
        form = GetReq()
    else:
        form = GetReq(request.POST)
        if form.is_valid():
            form.ip_address = get_client_ip(request)
            form.save()
</code>```

Expected result is an IP address of the user, as one of the values of the form, to be stored in the database.
Actual result, as said earlier, is valid values for every field in the form but the ip address, which always stored as null.

Edit.
Managed to make it work properly by changing views.py from.

```<code>if form.is_valid():
    form.ip_address = get_client_ip(request)
    form.save()
</code>```

to.

```<code>if form.is_valid():
    obj = form.save(commit=False)
    obj.ip_address = get_client_ip(request)
    obj.save()
</code>```

and by editing the input field in my template.

答:
Managed to make it work properly by changing views.py from.

```<code>if form.is_valid():
    form.ip_address = get_client_ip(request)
    form.save()
</code>```

to.

```<code>if form.is_valid():
    obj = form.save(commit=False)
    obj.ip_address = get_client_ip(request)
    obj.save()
</code>```

and by editing the input field in my template.

For others who may read this, you should also take note of Kevin's comment, and exclude the ip_address field out of the form entirely instead of using hidden input in the template.

Body:
Trying to store user's IP address when he's sending POST requests via submitting my form, tried more than a few suggestions on getting the IP address, but didn't manage to make it work properly as I always get null values stored for the IP in the database table.

I tried using model forms and setting the ip address as a variable inside the form so I can store it more easily into the database using request.META.get, and x_forwarded_for to get the actual address from the request in views.py.
My app built as below:

models.py:

class RequestPull(models.Model):
    a =  models.CharField(max_length=10)
    b =  models.CharField(max_length=10)
    ip_address = models.GenericIPAddressField(null=True)

forms.py:

class GetReq(forms.ModelForm):
    class Meta:
        model = RequestPull
            fields = ['a','b','ip_address']

views.py (one of the attempts that give the same result- null values in the database):

def get_client_ip(request):
    remote_address = request.META.get('HTTP_X_FORWARDED_FOR') or request.META.get('REMOTE_ADDR')
    ip = remote_address
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        proxies = x_forwarded_for.split(',')
        while (len(proxies) > 0 and proxies[0].startswith(PRIVATE_IPS_PREFIX)):
            proxies.pop(0)
            if len(proxies) > 0:
                ip = proxies[0]
                print"IP Address",ip
        return ip

def reqPull(request):
    if request.method == 'GET':
        form = GetReq()
    else:
        form = GetReq(request.POST)
        if form.is_valid():
            form.ip_address = get_client_ip(request)
            form.save()

Expected result is an IP address of the user, as one of the values of the form, to be stored in the database.
Actual result, as said earlier, is valid values for every field in the form but the ip address, which always stored as null.

Edit.
Managed to make it work properly by changing views.py from.

if form.is_valid():
    form.ip_address = get_client_ip(request)
    form.save()

to.

if form.is_valid():
    obj = form.save(commit=False)
    obj.ip_address = get_client_ip(request)
    obj.save()

and by editing the input field in my template.

Body:
Managed to make it work properly by changing views.py from.

if form.is_valid():
    form.ip_address = get_client_ip(request)
    form.save()

to.

if form.is_valid():
    obj = form.save(commit=False)
    obj.ip_address = get_client_ip(request)
    obj.save()

and by editing the input field in my template.

For others who may read this, you should also take note of Kevin's comment, and exclude the ip_address field out of the form entirely instead of using hidden input in the template.


问:
How to declare an object and assign its properties later
I have the example below that creates a google maps Rectangle Object. I want to only declare the Object, something like 'rectangle = new google.maps.Rectangle()' and then access its properties like 'rectangle.bounds' but seem that this doesn't work</p>

```<code>rectangle = new google.maps.Rectangle({
    bounds: bounds,
    editable: true,
    draggable: true
});
</code>```

答:
bounds is not a property, but a parameter of constructor. CMIIW.

According to the documentation, you can get the bounds property with method getBounds()

This should work. I haven't tried.
var bounds = rectangle.getBounds()

Body:
I have the example below that creates a google maps Rectangle Object. I want to only declare the Object, something like 'rectangle = new google.maps.Rectangle()' and then access its properties like 'rectangle.bounds' but seem that this doesn't work

rectangle = new google.maps.Rectangle({
    bounds: bounds,
    editable: true,
    draggable: true
});


问:
Execute Task in new background thread
I know there are a million questions on this and I am trying their solutions but it does not seem to behave as I would expect.

With the following code:

```<code>await Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("I'm running after Thread.Sleep"); });
Console.WriteLine("I'm running after Task.Run");
</code>```

I get the output:

```<code>[ 5 seconds elapses ]
I'm running after Thread.Sleep
I'm running after Task.Run
</code>```

Which is the same output I would get without using Task.Run

What I want is the output:

```<code>I'm running after Task.Run
[ 5 seconds elapses ]
I'm running after Thread.Sleep
</code>```

Where execution of the 'parent' thread continues and the long-running task is executed 'in the background' in a way which does not affect the 'parent' thread.

答:
If you want to run asynchronously you should remove the command away

```<code>        static void Main(string[] args)
        {
            Task.Run(() => { Thread.Sleep(5000); Console.WriteLine(DateTime.Now + " => I'm running after Thread.Sleep"); });
            Console.WriteLine(DateTime.Now + " => I'm running after Task.Run");
            while (true)
            {
                Thread.Sleep(500);
            }
        }
</code>```

Output

28/05/2019 09:49:58 => I'm running after Task.Run
28/05/2019 09:50:03 => I'm running after Thread.Sleep

Title: Execute Task in new background thread

Body:
I know there are a million questions on this and I am trying their solutions but it does not seem to behave as I would expect.

With the following code:

await Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("I'm running after Thread.Sleep"); });
Console.WriteLine("I'm running after Task.Run");

I get the output:

[ 5 seconds elapses ]
I'm running after Thread.Sleep
I'm running after Task.Run

Which is the same output I would get without using Task.Run

What I want is the output:

I'm running after Task.Run
[ 5 seconds elapses ]
I'm running after Thread.Sleep

Where execution of the 'parent' thread continues and the long-running task is executed 'in the background' in a way which does not affect the 'parent' thread.

Body:
If you want to run asynchronously you should remove the command away

        static void Main(string[] args)
        {
            Task.Run(() => { Thread.Sleep(5000); Console.WriteLine(DateTime.Now + " => I'm running after Thread.Sleep"); });
            Console.WriteLine(DateTime.Now + " => I'm running after Task.Run");
            while (true)
            {
                Thread.Sleep(500);
            }
        }

Output

28/05/2019 09:49:58 => I'm running after Task.Run
28/05/2019 09:50:03 => I'm running after Thread.Sleep


问:
Whats the correct way to measure a git blob object size
I am measuring git blobs sizes with

fileSizeThreshold=2^19
git rev-list --objects --all \
| git cat-file --batch-check='"%(objecttype)","%(objectname)",%(objectsize),%(objectsize:disk),"%(rest)"' \
| sed -n 's/^"blob",//p' \
| awk -F',' '$2'">= ${fileSizeThreshold}" \
| sort -t "," --numeric-sort --key=2 > ${outDir}/largeBlobs
```

Which gives me all blobs greater than 512kb.
I am wondering which size is the correct one to consider when thinking about putting this file (its path pattern...) in the Git Large Files Storage (LFS).

Is it %(objectsize) or %(objectsize:disk)?

Because %(objectsize:disk) reports some strange sizes (the bold one):

"0901797d58f6916cad4ef4fd581d8254596bdd19", 722013b, 105b

In the caveat section of git cat-file, there is some note about that, which I dont understand.

Considering LFS, one should look at the objectsize:disk supposedly because that is the space used for this blob...?

答:
You should look at %(objectsize).

When git stores blobs, it may store them either as flat objects, or as packed objects.

when storing flat objects, git still compresses the content, so the %(objectsize:disk) will reflect the compressed size of the blob ;

when packing blobs together, git may chosse to store blob2 next to blob1 using only its diff ;

in that case : the disksize for blob1 would be the compressed size of the blob, and the disksize for blob2 would be the compressed size of its diff with blob1

The CAVEAT section mentions that some blobs may have very low reported disksize because only their diff is reported.

Body:
I am measuring git blobs sizes with

fileSizeThreshold=2^19
git rev-list --objects --all \
| git cat-file --batch-check='"%(objecttype)","%(objectname)",%(objectsize),%(objectsize:disk),"%(rest)"' \
| sed -n 's/^"blob",//p' \
| awk -F',' '$2'">= ${fileSizeThreshold}" \
| sort -t "," --numeric-sort --key=2 > ${outDir}/largeBlobs

Which gives me all blobs greater than 512kb.
I am wondering which size is the correct one to consider when thinking about putting this file (its path pattern...) in the Git Large Files Storage (LFS).

Is it %(objectsize) or %(objectsize:disk)?

Because %(objectsize:disk) reports some strange sizes (the bold one):

"0901797d58f6916cad4ef4fd581d8254596bdd19", 722013b, 105b

In the caveat section of git cat-file, there is some note about that, which I dont understand.

Considering LFS, one should look at the objectsize:disk supposedly because that is the space used for this blob...?


答:
```<code>var rectangle = {}
rectangle = new google.maps.Rectangle({
            bounds: bounds,
            editable: true,
            draggable: true
          });
</code>```

try like above, pls

Title: How to declare an object and assign its properties later

Body:
var rectangle = {}
rectangle = new google.maps.Rectangle({
            bounds: bounds,
            editable: true,
            draggable: true
          });

try like above, pls


问:
Tensorflow Serving: InvalidArgumentError: Expected image (JPEG, PNG, or GIF), got unknown format starting with 'AAAAAAAAAAAAAAAA'
I'm trying to prepare my custom Keras model for deploy to be used with Tensorflow Serving, but I'm running into issues with preprocessing my images.

When i train my model i use the following functions to preprocess my images:

def process_image_from_tf_example(self, image_str_tensor, n_channels=3):
    image = tf.image.decode_image(image_str_tensor)
    image.set_shape([256, 256, n_channels])
    image = tf.cast(image, tf.float32) / 255.0
    return image

def read_and_decode(self, serialized):
    parsed_example = tf.parse_single_example(serialized=serialized, features=self.features)
    input_image = self.process_image_from_tf_example(parsed_example["image_raw"], 3)
    ground_truth_image = self.process_image_from_tf_example(parsed_example["gt_image_raw"], 1)
    return input_image, ground_truth_image
```

<p>My images are PNGs saved locally, and when i write them on the <code>.tfrecord</code> files i use
<code>tf.gfile.GFile(str(image_path), 'rb').read()</code></p>

<p>This works, I'm able to train my model and use it for local predictions.</p>

<p>Now I want to deploy my model to be used with Tensorflow Serving. My <code>serving_input_receiver_fn</code> function looks like this:</p>

<pre class="lang-py prettyprint-override"><code>def serving_input_receiver_fn(self):
    input_ph = tf.placeholder(dtype=tf.string, shape=[None], name='image_bytes')
    images_tensor = tf.map_fn(self.process_image_from_tf_example, input_ph, back_prop=False, dtype=tf.float32)
    return tf.estimator.export.ServingInputReceiver({'input_1': images_tensor}, {'image_bytes': input_ph})
</code>```

where process_image_from_tf_example is the same function as above, but i get the following error:

InvalidArgumentError (see above for traceback): assertion failed: [Unable to decode bytes as JPEG, PNG, GIF, or BMP]

Reading here it looks like this error is due to the fact that i'm not using
tf.gfile.GFile(str(image_path), 'rb').read()

as with my training/test files, but i can't use it because i need to send encoded bytes formatted as

{"image_bytes": {'b64': base64.b64encode(image).decode()}}

as requested by TF Serving.

Examples online send JPEG encoded bytes and preprocess the image starting with

tf.image.decode_jpeg(image_buffer, channels=3)

but if i use a different preprocessing function in my serving_input_receiver_fn (different than the one used for training) that starts with

tf.image.decode_png(image_buffer, channels=3)

i get the following error:

InvalidArgumentError (see above for traceback): Expected image (JPEG, PNG, or GIF), got unknown format starting with 'AAAAAAAAAAAAAAAA'

(the same happens with decode_jpeg, by the way)

What am i doing wrong? Do you need more code from me to answer? Thanks a lot!

Edit!!
Changed the title because it was not clear enough

答:
OK I solved it.

image was a numpy array but i had to do the following:

buffer = cv2.imencode('.jpg', image)[1].tostring()
bytes_image = base64.b64encode(buffer).decode('ascii')
{"image_bytes": {"b64": bytes_image}}
```

<p>Also, my preprocessing and <code>serving_input_receiver_fn</code> functions changed:</p>

<pre class="lang-py prettyprint-override"><code>def process_image_from_buffer(self, image_buffer):
    image = tf.image.decode_jpeg(image_buffer, channels=3)
    image = tf.image.convert_image_dtype(image, dtype=tf.float32)
    image = tf.expand_dims(image, 0)
    image = tf.image.resize_bilinear(image, [256, 256], align_corners=False)
    image = tf.squeeze(image, [0])
    image = tf.cast(image, tf.float32) / 255.0
    return image

def serving_input_receiver_fn(self):
    input_ph = tf.placeholder(dtype=tf.string, shape=[None])
    images_tensor = tf.map_fn(self.process_image_from_buffer, input_ph, back_prop=False, dtype=tf.float32)
    return tf.estimator.export.ServingInputReceiver({'input_1': images_tensor}, {'image_bytes': input_ph})

</code>```

process_image_from_buffer is different than process_image_from_tf_example used above for training.
I also removed name='image_bytes' from input_ph above.

Hope it's clear enough to help someone else.

Excellent guide partially used for solving it

Body:
I'm trying to prepare my custom Keras model for deploy to be used with Tensorflow Serving, but I'm running into issues with preprocessing my images.

When i train my model i use the following functions to preprocess my images:

def process_image_from_tf_example(self, image_str_tensor, n_channels=3):
    image = tf.image.decode_image(image_str_tensor)
    image.set_shape([256, 256, n_channels])
    image = tf.cast(image, tf.float32) / 255.0
    return image

def read_and_decode(self, serialized):
    parsed_example = tf.parse_single_example(serialized=serialized, features=self.features)
    input_image = self.process_image_from_tf_example(parsed_example["image_raw"], 3)
    ground_truth_image = self.process_image_from_tf_example(parsed_example["gt_image_raw"], 1)
    return input_image, ground_truth_image

My images are PNGs saved locally, and when i write them on the .tfrecord files i use
tf.gfile.GFile(str(image_path), 'rb').read()

This works, I'm able to train my model and use it for local predictions.

Now I want to deploy my model to be used with Tensorflow Serving. My serving_input_receiver_fn function looks like this:

def serving_input_receiver_fn(self):
    input_ph = tf.placeholder(dtype=tf.string, shape=[None], name='image_bytes')
    images_tensor = tf.map_fn(self.process_image_from_tf_example, input_ph, back_prop=False, dtype=tf.float32)
    return tf.estimator.export.ServingInputReceiver({'input_1': images_tensor}, {'image_bytes': input_ph})

where process_image_from_tf_example is the same function as above, but i get the following error:

InvalidArgumentError (see above for traceback): assertion failed: [Unable to decode bytes as JPEG, PNG, GIF, or BMP]

Reading here it looks like this error is due to the fact that i'm not using
tf.gfile.GFile(str(image_path), 'rb').read()

as with my training/test files, but i can't use it because i need to send encoded bytes formatted as

{"image_bytes": {'b64': base64.b64encode(image).decode()}}

as requested by TF Serving.

Examples online send JPEG encoded bytes and preprocess the image starting with

tf.image.decode_jpeg(image_buffer, channels=3)

but if i use a different preprocessing function in my serving_input_receiver_fn (different than the one used for training) that starts with

tf.image.decode_png(image_buffer, channels=3)

i get the following error:

InvalidArgumentError (see above for traceback): Expected image (JPEG, PNG, or GIF), got unknown format starting with 'AAAAAAAAAAAAAAAA'

(the same happens with decode_jpeg, by the way)

What am i doing wrong? Do you need more code from me to answer? Thanks a lot!

Edit!!
Changed the title because it was not clear enough

Body:
OK I solved it.

image was a numpy array but i had to do the following:

buffer = cv2.imencode('.jpg', image)[1].tostring()
bytes_image = base64.b64encode(buffer).decode('ascii')
{"image_bytes": {"b64": bytes_image}}

Also, my preprocessing and serving_input_receiver_fn functions changed:

def process_image_from_buffer(self, image_buffer):
    image = tf.image.decode_jpeg(image_buffer, channels=3)
    image = tf.image.convert_image_dtype(image, dtype=tf.float32)
    image = tf.expand_dims(image, 0)
    image = tf.image.resize_bilinear(image, [256, 256], align_corners=False)
    image = tf.squeeze(image, [0])
    image = tf.cast(image, tf.float32) / 255.0
    return image

def serving_input_receiver_fn(self):
    input_ph = tf.placeholder(dtype=tf.string, shape=[None])
    images_tensor = tf.map_fn(self.process_image_from_buffer, input_ph, back_prop=False, dtype=tf.float32)
    return tf.estimator.export.ServingInputReceiver({'input_1': images_tensor}, {'image_bytes': input_ph})

process_image_from_buffer is different than process_image_from_tf_example used above for training.
I also removed name='image_bytes' from input_ph above.

Hope it's clear enough to help someone else.

Excellent guide partially used for solving it


问:
How to display letters with french accents: é and others like it?
My code does:

Search in a Form for checked name (button radio)

Search for that name in a CSV file and extract some values (Name, Title, function and link to pictures)

Insert those values into Word document (for reference value or signature value)

It does work for standard names like John Smith but when I have special letters in the name like François Bénét, it doesn't. Instead of é, Ã© appears in the documents.

If the name has some other special characters it also does not find anything in the CSV. But for that I could find a workaround.

Have tried with other CSV format like UTF 8. But in that case I get an error 3265.

```<code>'Répertoire
directory = "W:\Tous\DigitRHTemp\"
FileName = "BaseSignatureTest.csv"
'Ouverture de la connexion CSV
Set rs = CreateObject("ADODB.Recordset")
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & directory & ";" _
& "Extended Properties=""text;HDR=Yes;FMT=Delimited;CharacterSet=850"";"
strSQL = "SELECT * FROM " & FileName
rs.Open strSQL, strcon, 3, 3
rs.MoveFirst

'Passer au travers des colonnes
Do
   'Mise en variable des valeurs
   col1 = rs("Nom")
   col2 = rs("Fonction")
   col3 = rs("DPT")
   col4 = rs("Titre")
   col5 = rs("Signature")
   rs.MoveNext

   'Si une valeur a été trouvée et qu'elle corresponds, définition des valeurs
   If col1 = RHREF Then

    '***
    '--- Populer les signets Signatures 1
    '***
        'Test si signet exist dans le document
        If ActiveDocument.Bookmarks.Exists("RHRefInt") = True Then
            'Si oui - Position sur le signet
            Selection.GoTo What:=wdGoToBookmark, Name:="RHRefInt"
            'Insére le text
            Selection.TypeText Text:=col4
        End If
        If ActiveDocument.Bookmarks.Exists("RHRefNom") = True Then
            Selection.GoTo What:=wdGoToBookmark, Name:="RHRefNom"
            Selection.TypeText Text:=col1
        End If

   End If

Loop Until rs.EOF
</code>```

Is there some parameter to add to have the proper format for French characters (é, à, è ,ç, etc.)?

答:
I've managed to do a big part (thank you Mathieu Guindon).

So the part that shows the department, title and name with special characters work fine (it is even quicker than the previous version of my code).

I've used the ADODB.Stream as suggested ans open the csv by forcing it in UTF-8

```<code>'Définition de l'objet
Dim objStream, strData
'Création d'un objet ADODB Stream
Set objStream = CreateObject("ADODB.Stream")
'Définition format en Utf-8
objStream.Charset = "utf-8"
'Ouverture de l'objet
objStream.Open
'Load du fichier
objStream.LoadFromFile ("W:\Tous\DigitRHTemp\BaseSignatureTest.csv")
'Définition du ligne par ligne
objStream.LineSeparator = 10
'Ouvrir chaque ligne jusqu'à la dernière ligne du fichier
Do Until objStream.EOS
'Défintion du texte à lire (ligne complète)
strData = objStream.ReadText(-2)

'Définition pour la partie valeur par valeur - sépare la ligne en valeur
Dim LArray() As String
'Sépare la valeur en se basant sur la virgule ","
LArray = Split(strData, ",")

   'Si une valeur a été trouvée et qu'elle corresponds, définition des valeurs
   If LArray(0) = RHSignature1 Then

    '***
    '--- Populer les signets Signatures 1
    '***
        'Test si signet exist dans le document
        If ActiveDocument.Bookmarks.Exists("RHSign1Nom") = True Then
            'Si oui - Position sur le signet
            Selection.GoTo What:=wdGoToBookmark, Name:="RHSign1Nom"
            'Insére le text
            Selection.TypeText Text:=LArray(0)
        End If
        If ActiveDocument.Bookmarks.Exists("RHSign1DPT") = True Then
            Selection.GoTo What:=wdGoToBookmark, Name:="RHSign1DPT"
            Selection.TypeText Text:=LArray(1)
        End If
        If ActiveDocument.Bookmarks.Exists("RHSign1Fonction") = True Then
            Selection.GoTo What:=wdGoToBookmark, Name:="RHSign1Fonction"
            Selection.TypeText Text:=LArray(2)
        End If
   End If
'Fermeture de la boucle
Loop
'fermeture du objstream
objStream.Close
</code>```

Body:
My code does:

Search in a Form for checked name (button radio)

Search for that name in a CSV file and extract some values (Name, Title, function and link to pictures)

Insert those values into Word document (for reference value or signature value)

It does work for standard names like John Smith but when I have special letters in the name like François Bénét, it doesn't. Instead of é, Ã© appears in the documents.

If the name has some other special characters it also does not find anything in the CSV. But for that I could find a workaround.

Have tried with other CSV format like UTF 8. But in that case I get an error 3265.

'Répertoire
directory = "W:\Tous\DigitRHTemp\"
FileName = "BaseSignatureTest.csv"
'Ouverture de la connexion CSV
Set rs = CreateObject("ADODB.Recordset")
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & directory & ";" _
& "Extended Properties=""text;HDR=Yes;FMT=Delimited;CharacterSet=850"";"
strSQL = "SELECT * FROM " & FileName
rs.Open strSQL, strcon, 3, 3
rs.MoveFirst

'Passer au travers des colonnes
Do
   'Mise en variable des valeurs
   col1 = rs("Nom")
   col2 = rs("Fonction")
   col3 = rs("DPT")
   col4 = rs("Titre")
   col5 = rs("Signature")
   rs.MoveNext

   'Si une valeur a été trouvée et qu'elle corresponds, définition des valeurs
   If col1 = RHREF Then

    '***
    '--- Populer les signets Signatures 1
    '***
        'Test si signet exist dans le document
        If ActiveDocument.Bookmarks.Exists("RHRefInt") = True Then
            'Si oui - Position sur le signet
            Selection.GoTo What:=wdGoToBookmark, Name:="RHRefInt"
            'Insére le text
            Selection.TypeText Text:=col4
        End If
        If ActiveDocument.Bookmarks.Exists("RHRefNom") = True Then
            Selection.GoTo What:=wdGoToBookmark, Name:="RHRefNom"
            Selection.TypeText Text:=col1
        End If

   End If

Loop Until rs.EOF

Is there some parameter to add to have the proper format for French characters (é, à, è ,ç, etc.)?

Body:
I've managed to do a big part (thank you Mathieu Guindon).

So the part that shows the department, title and name with special characters work fine (it is even quicker than the previous version of my code).

I've used the ADODB.Stream as suggested ans open the csv by forcing it in UTF-8

'Définition de l'objet
Dim objStream, strData
'Création d'un objet ADODB Stream
Set objStream = CreateObject("ADODB.Stream")
'Définition format en Utf-8
objStream.Charset = "utf-8"
'Ouverture de l'objet
objStream.Open
'Load du fichier
objStream.LoadFromFile ("W:\Tous\DigitRHTemp\BaseSignatureTest.csv")
'Définition du ligne par ligne
objStream.LineSeparator = 10
'Ouvrir chaque ligne jusqu'à la dernière ligne du fichier
Do Until objStream.EOS
'Défintion du texte à lire (ligne complète)
strData = objStream.ReadText(-2)

'Définition pour la partie valeur par valeur - sépare la ligne en valeur
Dim LArray() As String
'Sépare la valeur en se basant sur la virgule ","
LArray = Split(strData, ",")

   'Si une valeur a été trouvée et qu'elle corresponds, définition des valeurs
   If LArray(0) = RHSignature1 Then

    '***
    '--- Populer les signets Signatures 1
    '***
        'Test si signet exist dans le document
        If ActiveDocument.Bookmarks.Exists("RHSign1Nom") = True Then
            'Si oui - Position sur le signet
            Selection.GoTo What:=wdGoToBookmark, Name:="RHSign1Nom"
            'Insére le text
            Selection.TypeText Text:=LArray(0)
        End If
        If ActiveDocument.Bookmarks.Exists("RHSign1DPT") = True Then
            Selection.GoTo What:=wdGoToBookmark, Name:="RHSign1DPT"
            Selection.TypeText Text:=LArray(1)
        End If
        If ActiveDocument.Bookmarks.Exists("RHSign1Fonction") = True Then
            Selection.GoTo What:=wdGoToBookmark, Name:="RHSign1Fonction"
            Selection.TypeText Text:=LArray(2)
        End If
   End If
'Fermeture de la boucle
Loop
'fermeture du objstream
objStream.Close