问:
looping through arrays of arrays
I have an arrays of arrays (some thing like graph), How to iterate all arrays?

```<code>var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];
</code>```

Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM

答:
what you need to do is something like this

```<code>var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];

for(int i = 0; i < parentArray.length;i++){
   var value = parent[i];

   for(int j = 0; j < parent[i].length; j++){
      var innerValue = parent[i][j];
   }
}
</code>```

So this will be like a nested loop, then there where innerValue and value is you can do some operations, hope it helps

Title: looping through arrays of arrays

Body:
I have an arrays of arrays (some thing like graph), How to iterate all arrays?

var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];

Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM

Body:
what you need to do is something like this

var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];

for(int i = 0; i < parentArray.length;i++){
   var value = parent[i];

   for(int j = 0; j < parent[i].length; j++){
      var innerValue = parent[i][j];
   }
}

So this will be like a nested loop, then there where innerValue and value is you can do some operations, hope it helps


来源: stackexchange

问:
Splunk query to create a table view?
This event is printed eveytime UserPin AreaCode AreaNum Sector Short Sem are unique for each userid and come only inside User Login successfully message with timestamp

```<code>"message":" *** User Login successfully credentials userid 2NANO-323254-7654-4  UserPin - 287654 AreaCode - 98765 AreaNum - 98765 Sector - 87612345 Short Sem - ZEB"
</code>```

Below these two event are only printed when certain conditions are meet. I am very new in Splunk like a naive, how can we write a Splunk query such that take out the userid with UserPin AreaCode AreaNum Sector Short Sem which have the below printed event then only create a table with userid. If below two message are not printed with userid from above message then we should not consider the userid

```<code>"message": "User Failed to login userid - 2NANO-323254-7654-4"
</code>```
```<code>"message": "User is from stackoverflow group, on XZ ABCE for userid - 2NAN0-323254-7654-4"
</code>```

this is table structure where i want to fill values

```<code>UserId | UserPin | AreaCode | AreaNum | Sector | Short_Sem
</code>```

I am very new in splunk can someone guide how to start to build where to look for the thing. Any hint or demo will work. Thank you

Example

```<code>"message":" *** User Login successfully credentials userid 2NANO-323254-7654-4  UserPin - 287654 AreaCode - 98765 AreaNum - 98765 Sector - 87612345 Short Sem - ZEB"
</code>```
```<code>"message": "User Failed to login userid - 2NANO-323254-7654-4"
</code>```
```<code>"message": "User is from stackoverflow group, on XZ ABCE for userid - 2NAN0-323254-7654-4"
</code>```
```<code>"message":" *** User Login successfully credentials userid 2ABDO-54312-7654-4  UserPin - 287654 AreaCode - 98765 AreaNum - 98765 Sector - 87612345 Short Sem - ZEB"
</code>```
```<code>"message":" *** User Login successfully credentials userid 2COMA-765234-8653-4  UserPin - 287654 AreaCode - 98765 AreaNum - 98765 Sector - 87612345 Short Sem - ZEB"
</code>```

So we consider first only because that userid have has two more event with same userid and associated all the event have timestamp

```<code>UserId              | UserPin| AreaCode | AreaNum | Sector   | Short_Sem
2NANO-323254-7654-4 | 287654 | 98765    | 98765   | 87612345 | ZEB
</code>```

答:
This question is an expansion of your question at how to write splunk query to create a table view so the answer is an expansion of that answer.

First, use rex to extract the desired fields.  Then the stats command will group the results by userid.  Finally, use the table command to display the fields.

```<code>| makeresults
| eval data="\"message\":\" *** User Login successfully credentials userid 2NANO-323254-7654-4  UserPin - 287654 AreaCode - 98765 AreaNum - 98765 Sector - 87612345 Short Sem - ZEB\"
    \"message\": \"User Failed to login userid - 2NANO-323254-7654-4\"
    \"message\": \"User is from stackoverflow group, on XZ ABCE for userid - 2NAN0-323254-7654-4\"
    \"message\":\" *** User Login successfully credentials userid 2ABDO-54312-7654-4  UserPin - 287654 AreaCode - 98765 AreaNum - 98765 Sector - 87612345 Short Sem - ZEB\"
    \"message\":\" *** User Login successfully credentials userid 2COMA-765234-8653-4  UserPin - 287654 AreaCode - 98765 AreaNum - 98765 Sector - 87612345 Short Sem - ZEB\""
| eval data=split(data,"
")
| mvexpand data
| eval _raw=data
```Everything above is for demo purposes only```
```Extract fields```
| rex "message\":\s*\"\s*(?:\*+\s)?(?<msg>.*?)(?:userid|,)"
| rex "userid\s(?:-\s)?(?<userid>\S+)"
| rex "UserPin - (?<UserPin>\S+) AreaCode - (?<AreaCode>\S+) AreaNum - (?<AreaNum>\S+) Sector - (?<Sector>\S+) Short Sem - (?<Short_Sem>\S+)"
```Clean up the fields```
| eval userid=trim(userid,"\""), Short_Sem=trim(Short_Sem, "\"")
```Group results```
| stats values(*) as * by userid
```Filter events```
| search (msg="*User Failed to login*") OR (msg="*User is from stackoverflow group*")
| rename userid as UserId
| table UserId UserPin AreaCode AreaNum Sector Short_Sem
</code>```

ContentLicense: CC BY-SA 4.0

Title: Splunk query to create a table view?

Body:
This event is printed eveytime UserPin AreaCode AreaNum Sector Short Sem are unique for each userid and come only inside User Login successfully message with timestamp

"message":" *** User Login successfully credentials userid 2NANO-323254-7654-4  UserPin - 287654 AreaCode - 98765 AreaNum - 98765 Sector - 87612345 Short Sem - ZEB"

Below these two event are only printed when certain conditions are meet. I am very new in Splunk like a naive, how can we write a Splunk query such that take out the userid with UserPin AreaCode AreaNum Sector Short Sem which have the below printed event then only create a table with userid. If below two message are not printed with userid from above message then we should not consider the userid

"message": "User Failed to login userid - 2NANO-323254-7654-4"

"message": "User is from stackoverflow group, on XZ ABCE for userid - 2NAN0-323254-7654-4"

this is table structure where i want to fill values

UserId | UserPin | AreaCode | AreaNum | Sector | Short_Sem

I am very new in splunk can someone guide how to start to build where to look for the thing. Any hint or demo will work. Thank you

Example

"message":" *** User Login successfully credentials userid 2NANO-323254-7654-4  UserPin - 287654 AreaCode - 98765 AreaNum - 98765 Sector - 87612345 Short Sem - ZEB"

"message": "User Failed to login userid - 2NANO-323254-7654-4"

"message": "User is from stackoverflow group, on XZ ABCE for userid - 2NAN0-323254-7654-4"

"message":" *** User Login successfully credentials userid 2ABDO-54312-7654-4  UserPin - 287654 AreaCode - 98765 AreaNum - 98765 Sector - 87612345 Short Sem - ZEB"

"message":" *** User Login successfully credentials userid 2COMA-765234-8653-4  UserPin - 287654 AreaCode - 98765 AreaNum - 98765 Sector - 87612345 Short Sem - ZEB"

So we consider first only because that userid have has two more event with same userid and associated all the event have timestamp

UserId              | UserPin| AreaCode | AreaNum | Sector   | Short_Sem
2NANO-323254-7654-4 | 287654 | 98765    | 98765   | 87612345 | ZEB

Body:
This question is an expansion of your question at how to write splunk query to create a table view so the answer is an expansion of that answer.

First, use rex to extract the desired fields.  Then the stats command will group the results by userid.  Finally, use the table command to display the fields.

| makeresults
| eval data="\"message\":\" *** User Login successfully credentials userid 2NANO-323254-7654-4  UserPin - 287654 AreaCode - 98765 AreaNum - 98765 Sector - 87612345 Short Sem - ZEB\"
    \"message\": \"User Failed to login userid - 2NANO-323254-7654-4\"
    \"message\": \"User is from stackoverflow group, on XZ ABCE for userid - 2NAN0-323254-7654-4\"
    \"message\":\" *** User Login successfully credentials userid 2ABDO-54312-7654-4  UserPin - 287654 AreaCode - 98765 AreaNum - 98765 Sector - 87612345 Short Sem - ZEB\"
    \"message\":\" *** User Login successfully credentials userid 2COMA-765234-8653-4  UserPin - 287654 AreaCode - 98765 AreaNum - 98765 Sector - 87612345 Short Sem - ZEB\""
| eval data=split(data,"
")
| mvexpand data
| eval _raw=data
```Everything above is for demo purposes only```
```Extract fields```
| rex "message\":\s*\"\s*(?:\*+\s)?(?<msg>.*?)(?:userid|,)"
| rex "userid\s(?:-\s)?(?<userid>\S+)"
| rex "UserPin - (?<UserPin>\S+) AreaCode - (?<AreaCode>\S+) AreaNum - (?<AreaNum>\S+) Sector - (?<Sector>\S+) Short Sem - (?<Short_Sem>\S+)"
```Clean up the fields```
| eval userid=trim(userid,"\""), Short_Sem=trim(Short_Sem, "\"")
```Group results```
| stats values(*) as * by userid
```Filter events```
| search (msg="*User Failed to login*") OR (msg="*User is from stackoverflow group*")
| rename userid as UserId
| table UserId UserPin AreaCode AreaNum Sector Short_Sem


问:
How to add more context into panick_info when catching?
In my project I have a panic hook which sends an HTTP request reporting an issue when some unplanned unwrap occurs. I am executing some function 100 times and I would like to somehow know when the panic occurs which of the executions it was in case the panic happened inside the function. Is it possible to somehow add a string to an intercepted unrolling of panic_info or how do people handle this?

I was thinking something along the lines of using catch_unwind, modifying the caught err and resuming the unwind, but the err is of opaque type so I don't see a way to add something to it. I see that panic_info has payload, is it somehow possible to add to it?

I would like to avoid having some global mutex which I can then modify when catching the unwind

答:
One simple option is to just use expect() instead of unwrap() and use an informative error message.

Another way is to use a custom panic type and try to downcast it, e.g.:

use std::any::Any;
use std::panic::{self, panic_any, UnwindSafe};

// The custom panic payload.
// Must be `'static + Any + Send` for `panic_any()`.
pub struct MyPanicInfo {
    pub description: String,
}

trait OptionExt {
    type Inner;
    fn unwrap_with<F: FnOnce() -> MyPanicInfo>(self, f: F) -> Self::Inner;
}
impl<T> OptionExt for Option<T> {
    type Inner = T;
    fn unwrap_with<F: FnOnce() -> MyPanicInfo>(self, f: F) -> Self::Inner {
        match self {
            Some(v) => v,
            None => panic_any(f()),
        }
    }
}

trait ResultExt {
    type Ok;
    type Err;
    fn unwrap_with<F: FnOnce(Self::Err) -> MyPanicInfo>(self, f: F) -> Self::Ok;
}
impl<T, E> ResultExt for Result<T, E> {
    type Ok = T;
    type Err = E;
    fn unwrap_with<F: FnOnce(<Self as ResultExt>::Err) -> MyPanicInfo>(
        self,
        f: F,
    ) -> <Self as ResultExt>::Ok {
        match self {
            Ok(v) => v,
            Err(e) => panic_any(f(e)),
        }
    }
}

pub enum PanicPayload {
    MyPanicInfo(Box<MyPanicInfo>),
    Unknown(Box<dyn Any + Send>),
}
pub fn my_catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R, PanicPayload> {
    panic::catch_unwind(f).map_err(|payload| match payload.downcast() {
        Ok(my_panic_info) => PanicPayload::MyPanicInfo(my_panic_info),
        Err(unknown_payload) => PanicPayload::Unknown(unknown_payload),
    })
}
```

Then use something like option.unwrap_with(|| MyPanicInfo { description: "abc".to_owned() }).

Body:
One simple option is to just use expect() instead of unwrap() and use an informative error message.

Another way is to use a custom panic type and try to downcast it, e.g.:

use std::any::Any;
use std::panic::{self, panic_any, UnwindSafe};

// The custom panic payload.
// Must be `'static + Any + Send` for `panic_any()`.
pub struct MyPanicInfo {
    pub description: String,
}

trait OptionExt {
    type Inner;
    fn unwrap_with<F: FnOnce() -> MyPanicInfo>(self, f: F) -> Self::Inner;
}
impl<T> OptionExt for Option<T> {
    type Inner = T;
    fn unwrap_with<F: FnOnce() -> MyPanicInfo>(self, f: F) -> Self::Inner {
        match self {
            Some(v) => v,
            None => panic_any(f()),
        }
    }
}

trait ResultExt {
    type Ok;
    type Err;
    fn unwrap_with<F: FnOnce(Self::Err) -> MyPanicInfo>(self, f: F) -> Self::Ok;
}
impl<T, E> ResultExt for Result<T, E> {
    type Ok = T;
    type Err = E;
    fn unwrap_with<F: FnOnce(<Self as ResultExt>::Err) -> MyPanicInfo>(
        self,
        f: F,
    ) -> <Self as ResultExt>::Ok {
        match self {
            Ok(v) => v,
            Err(e) => panic_any(f(e)),
        }
    }
}

pub enum PanicPayload {
    MyPanicInfo(Box<MyPanicInfo>),
    Unknown(Box<dyn Any + Send>),
}
pub fn my_catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R, PanicPayload> {
    panic::catch_unwind(f).map_err(|payload| match payload.downcast() {
        Ok(my_panic_info) => PanicPayload::MyPanicInfo(my_panic_info),
        Err(unknown_payload) => PanicPayload::Unknown(unknown_payload),
    })
}

Then use something like option.unwrap_with(|| MyPanicInfo { description: "abc".to_owned() }).


问:
how to calculate binary search complexity
I heard somebody say that since binary search halves the input required to search hence it is log(n) algorithm. Since I am not from a mathematics background I am not able to relate to it. Can somebody explain it in a little more detail? Does it have to do something with the logarithmic series?</p>

答:
we can establish a recurrence relation
T(n)=T(n/2)+1

T(n/2)= T(n/4)+1
therefore T(n)= T(n/4)+2

T(n/4)= T(n/8)+1
therefore T(n)= T(n/8)+3

we can establish a relation

T(n) = T(n/(2^k))+k ----------lets call this as equation 1

and we keep on expanding, we will reach a point where

2^k = n, applying log on both sides

log(2^k) = log(n)

therefore k = log(n)

putting this value of k in equation 1

T(n) = T(n/(2^(log(n)))) + log(n)

therefore
T(n) = T(n/n) + log(n)
therefore T(n) = T(1) + log(n)

hence T(n) = log(n)


问:
Flutter/Dart : Parsing 'yyyy-MM-dd HH:MM:SS' producing wrong output?
I am parsing a date in format yyyy-MM-dd HH:MM:SS using DateFormat

But I am getting some other date in parsed output

```<code>final dt = '2022-02-07 05:00:11';
final datm =  DateFormat('yyyy-MM-dd HH:MM:SS').parse(dt);

print ("DATE_CALC ${datm.day} - ${datm.month} - ${datm.year} ${datm.hour} : ${datm.minute} : ${datm.second}   ");
</code>```

Actual Output:

```<code>DATE_CALC 7 - 2 - 2021 5 : 0 : 0
</code>```

Expected :

```<code>DATE_CALC 07 - 12 - 2022 05 : 00 : 11
</code>```

Why I am getting some wrong date ? Am I doing anything wrong ?

答:
MM  is not month and minutes....  mm or MM  :-)</p>
```<code>wrong 'yyyy-MM-dd HH:MM:SS'
correct 'yyyy-MM-dd HH:mm:ss'
</code>```

Body:
I am parsing a date in format yyyy-MM-dd HH:MM:SS using DateFormat

But I am getting some other date in parsed output

final dt = '2022-02-07 05:00:11';
final datm =  DateFormat('yyyy-MM-dd HH:MM:SS').parse(dt);

print ("DATE_CALC ${datm.day} - ${datm.month} - ${datm.year} ${datm.hour} : ${datm.minute} : ${datm.second}   ");

Actual Output:

DATE_CALC 7 - 2 - 2021 5 : 0 : 0

Expected :

DATE_CALC 07 - 12 - 2022 05 : 00 : 11

Why I am getting some wrong date ? Am I doing anything wrong ?

Body:
MM  is not month and minutes....  mm or MM  :-)

wrong 'yyyy-MM-dd HH:MM:SS'
correct 'yyyy-MM-dd HH:mm:ss'


问:
UTF-8 to Unicode Code Points
Is there a function that will change UTF-8 to Unicode leaving non special characters as normal letters and numbers?

ie the German word "tchüß" would be rendered as something like "tch\20AC\21AC" (please note that I am making the Unicode codes up).

EDIT: I am experimenting with the following function, but although this one works well with ASCII 32-127, it seems to fail for double byte chars:

```<code>function strToHex ($string)
{
    $hex = '';
    for ($i = 0; $i < mb_strlen ($string, "utf-8"); $i++)
    {
        $id = ord (mb_substr ($string, $i, 1, "utf-8"));
        $hex .= ($id <= 128) ? mb_substr ($string, $i, 1, "utf-8") : "&#" . $id . ";";
}

    return ($hex);
}
</code>```

Any ideas?

EDIT 2: Found solution: The PHP ord() function does not work for double byte chars. Use instead: http://nl.php.net/manual/en/function.ord.php#78032

答:
Converting one character set to another can be done with iconv:

http://php.net/manual/en/function.iconv.php

Note that UTF is already an Unicode encoding.

Another way is simply using htmlentities with the right character set:

http://php.net/manual/en/function.htmlentities.php

ContentLicense: CC BY-SA 3.0

Title: UTF-8 to Unicode Code Points

Body:
Is there a function that will change UTF-8 to Unicode leaving non special characters as normal letters and numbers?

ie the German word "tchüß" would be rendered as something like "tch\20AC\21AC" (please note that I am making the Unicode codes up).

EDIT: I am experimenting with the following function, but although this one works well with ASCII 32-127, it seems to fail for double byte chars:

function strToHex ($string)
{
    $hex = '';
    for ($i = 0; $i < mb_strlen ($string, "utf-8"); $i++)
    {
        $id = ord (mb_substr ($string, $i, 1, "utf-8"));
        $hex .= ($id <= 128) ? mb_substr ($string, $i, 1, "utf-8") : "&#" . $id . ";";
}

    return ($hex);
}

Any ideas?

EDIT 2: Found solution: The PHP ord() function does not work for double byte chars. Use instead: http://nl.php.net/manual/en/function.ord.php#78032


问:
How to make odoo progress bar use decimal?
So I am learning odoo right now, and I want to make the progress bar that use decimal to determine it's percentage. so for example if I input a 0.5, the progress bar will show 50%, so I don't have to input 50 to get 50%.
I tried using options like below

PY

```<code>progress = fields.Float(string='Progress')
maximum_rate = fields.Float(string='Maximum Rate', default=1)
</code>```

XML

```<code><field name="maximum_rate" invisible="1"/>
<field name="progress" widget="progressbar" options="{'max_value': 'maximum_rate', 'editable': True}"/>
</code>```

but the output is either 0/1 or 1/1, it's always on integer value, and it's also not a percentage. so how do I make my progress bar show percentage using decimal value like 0.5 to show 50%?

答:
If the max_value  is different from 100, Odoo will compute the value using the following:

```<code>if (max_value !== 100) {
    this.$('.o_progressbar_value').text(utils.human_number(value) + " / " + utils.human_number(max_value));
}
</code>```

Unfortunately, you can't change this behavior using widget options

Body:
So I am learning odoo right now, and I want to make the progress bar that use decimal to determine it's percentage. so for example if I input a 0.5, the progress bar will show 50%, so I don't have to input 50 to get 50%.
I tried using options like below

PY

progress = fields.Float(string='Progress')
maximum_rate = fields.Float(string='Maximum Rate', default=1)

XML

<field name="maximum_rate" invisible="1"/>
<field name="progress" widget="progressbar" options="{'max_value': 'maximum_rate', 'editable': True}"/>

but the output is either 0/1 or 1/1, it's always on integer value, and it's also not a percentage. so how do I make my progress bar show percentage using decimal value like 0.5 to show 50%?

Body:
If the max_value  is different from 100, Odoo will compute the value using the following:

if (max_value !== 100) {
    this.$('.o_progressbar_value').text(utils.human_number(value) + " / " + utils.human_number(max_value));
}

Unfortunately, you can't change this behavior using widget options


问:
Why is this code giving me an output of 5?
The goal of this code is to double each number in the array. I was trying to mimic the map() method. But that is not important. What I am wondering is why this code gives me an output of 5 while I did not console.log it. Then when I run it again it keeps adding 5 to a variable I am not aware of?

const numbers = [1, 2, 3, 4, 5];
const doubleNumbers = [];
for (let i = 0; i < numbers.length; i += 1) {
  doubleNumbers.push(numbers[i] * 2)
}```

答:
From the documentation: the push() method adds one or more elements to the end of an array and returns the new length of the array.

If you run this in the developer console, it will log the last returned result.


问:
A few questions about SQL Table partitioning and performance
Let's assume I have a TABLE like this one with milions of rows:

```<code>CREATE TABLE TEST
(
    id INT NOT NULL,
    fname VARCHAR(25) NOT NULL,
    lname VARCHAR(25) NOT NULL,
    partitiontag INT NOT NULL,
    PRIMARY KEY (id)
)
PARTITION BY RANGE (partitiontag)
(
        PARTITION p0 VALUES LESS THAN (1),
        PARTITION p1 VALUES LESS THAN (2),
        PARTITION p2 VALUES LESS THAN (3),
        PARTITION p3 VALUES LESS THAN (MAXVALUE)
);
</code>```

1. Is there any performance difference between the following two queries?

a) SELECT * FROM test PARTITION(P1)

b) SELECT * FROM test WHERE partitiontag = 1

2. Is there any performance difference between the following three queries (WHERE id=5 as example, it can be fname = 'xxx' or sth)?

a) SELECT * FROM test WHERE id = 5

b) SELECT * FROM test PARTITION(P1) WHERE id = 5

c) SELECT * FROM test WHERE id=5 and partitiontag = 1

3. Is there any performance difference between the following three queries when we want to update/delete rows? - for example:

a) UPDATE TEST SET fname = 'Changed' WHERE id = 10;

b) UPDATE TEST SET fname = 'Changed' WHERE id = 10 and partitionTag = 1;

c) UPDATE TEST PARTITION(P1) SET fname = 'Changed' WHERE id = 10;

答:
Optimizer is smart enough to find out that partitiontag = 1 narrows the search to just one partition, therefore (a) and (b) are equivalent.

Since id is a primary key, all of these queries will use primary index. Just with (b) and (c) row would be filtered out if it is found outside of the partition. If instead of id you would filter on fname, then (a) would scan entire table (since there is no hint about partition), while (b) and (c) are equivalent and would both scan only a single partition.

Same as (2), update behaves in same way as select here.

It's definitely helpful to learn how to look at explain plan.

Body:
Let's assume I have a TABLE like this one with milions of rows:

CREATE TABLE TEST
(
    id INT NOT NULL,
    fname VARCHAR(25) NOT NULL,
    lname VARCHAR(25) NOT NULL,
    partitiontag INT NOT NULL,
    PRIMARY KEY (id)
)
PARTITION BY RANGE (partitiontag)
(
        PARTITION p0 VALUES LESS THAN (1),
        PARTITION p1 VALUES LESS THAN (2),
        PARTITION p2 VALUES LESS THAN (3),
        PARTITION p3 VALUES LESS THAN (MAXVALUE)
);

1. Is there any performance difference between the following two queries?

a) SELECT * FROM test PARTITION(P1)

b) SELECT * FROM test WHERE partitiontag = 1

2. Is there any performance difference between the following three queries (WHERE id=5 as example, it can be fname = 'xxx' or sth)?

a) SELECT * FROM test WHERE id = 5

b) SELECT * FROM test PARTITION(P1) WHERE id = 5

c) SELECT * FROM test WHERE id=5 and partitiontag = 1

3. Is there any performance difference between the following three queries when we want to update/delete rows? - for example:

a) UPDATE TEST SET fname = 'Changed' WHERE id = 10;

b) UPDATE TEST SET fname = 'Changed' WHERE id = 10 and partitionTag = 1;

c) UPDATE TEST PARTITION(P1) SET fname = 'Changed' WHERE id = 10;


问:
Extract mail address from HTML-like string in Python
Using the GMail API it is possible to recover the sender of an email with:

```<code>email = service.users().messages().get(userId='me', id=msg['id']).execute()
payload = email['payload']
headers = payload['headers']
for hdr in headers:
if hdr['name'] == 'From':
   sender = hdr['value']
</code>```

This returns the variable sender as a string with the format:

```<code>"Name Surname" <name.surname@gmail.com>
</code>```

I would like to recover separately the name and email address from this string.
So that I end up with 2 (str) variables:

```<code>sender_name = "Name Surname"
sender_email_address = "name.surname@gmail.com"
</code>```

Is there a library that can assist with this?

答:
You can use string manipulation or regular expression;</p>
```<code>import re
s='"Name Surname" <name.surname@gmail.com>'
re.search('^.*<', s).group()[:-1].strip()[1:-1]
'Name Surname'
re.search('<.*>',s).group()
'<name.surname@gmail.com>'
</code>```

Body:
Using the GMail API it is possible to recover the sender of an email with:

email = service.users().messages().get(userId='me', id=msg['id']).execute()
payload = email['payload']
headers = payload['headers']
for hdr in headers:
if hdr['name'] == 'From':
   sender = hdr['value']

This returns the variable sender as a string with the format:

"Name Surname" <name.surname@gmail.com>

I would like to recover separately the name and email address from this string.
So that I end up with 2 (str) variables:

sender_name = "Name Surname"
sender_email_address = "name.surname@gmail.com"

Is there a library that can assist with this?

Body:
You can use string manipulation or regular expression;

import re
s='"Name Surname" <name.surname@gmail.com>'
re.search('^.*<', s).group()[:-1].strip()[1:-1]
'Name Surname'
re.search('<.*>',s).group()
'<name.surname@gmail.com>'


问:
Can Terraform add individual Digital Ocean firewall rules?
I'm building a mix of EC2 instance and DO droplets which must be able to communicate in a fully meshed manner, which requires firewall configurations for AWS and DO to have knowledge of the WAN and LAN addresses for all created resources. The number of resources per platform is variable.

When using Terraform with the AWS provider, I can create a security group and later add individual rules to it:

```<code>resource "aws_security_group" "sg-1" {

  ingress {
     ...
  }
  egress {
    ...
  }
}

resource "aws_security_group_rule" "sg1-rule-1" {
  security_group_id = aws_security_group.sg-1.id
  ...
}
</code>```

The DigitalOcean provider provides the digitalocean_firewall resource, but nothing similar to the aws_security_group_rule resource, which means the entire firewall ruleset must be known in advance and applied within the digitalocean_firewall resource block.

My only solution so far is to dynamically create the digitalocean_firewall.tf file from a template once the resources have been created, but this then requires a second terraform apply to apply the dynamic rules.

In the absence of a digitalocean_firewall_rule resource, is there a better approach?

答:
Answering my own question!

The solution is to use Terraform's dynamic block resource:

```<code>resource "digitalocean_firewall" "firewall" {
  name = "${var.project_name}-${var.environment}-firewall"

  inbound_rule {
    protocol         = "tcp"
    port_range       = "22"
    source_addresses = ["x.x.x.x/32"]
  }

  dynamic "inbound_rule" {
    for_each = module.ec2_node
    content {
      protocol         = "tcp"
      port_range       = "1-65535"
      source_addresses = [inbound_rule.value.public_ip]
    }
  }

  dynamic "inbound_rule" {
    for_each = module.ec2_node
    content {
      protocol         = "udp"
      port_range       = "1-65535"
      source_addresses = [inbound_rule.value.public_ip]
    }
  }
}
</code>```

Body:
I'm building a mix of EC2 instance and DO droplets which must be able to communicate in a fully meshed manner, which requires firewall configurations for AWS and DO to have knowledge of the WAN and LAN addresses for all created resources. The number of resources per platform is variable.

When using Terraform with the AWS provider, I can create a security group and later add individual rules to it:

resource "aws_security_group" "sg-1" {

  ingress {
     ...
  }
  egress {
    ...
  }
}

resource "aws_security_group_rule" "sg1-rule-1" {
  security_group_id = aws_security_group.sg-1.id
  ...
}

The DigitalOcean provider provides the digitalocean_firewall resource, but nothing similar to the aws_security_group_rule resource, which means the entire firewall ruleset must be known in advance and applied within the digitalocean_firewall resource block.

My only solution so far is to dynamically create the digitalocean_firewall.tf file from a template once the resources have been created, but this then requires a second terraform apply to apply the dynamic rules.

In the absence of a digitalocean_firewall_rule resource, is there a better approach?

Body:
Answering my own question!

The solution is to use Terraform's dynamic block resource:

resource "digitalocean_firewall" "firewall" {
  name = "${var.project_name}-${var.environment}-firewall"

  inbound_rule {
    protocol         = "tcp"
    port_range       = "22"
    source_addresses = ["x.x.x.x/32"]
  }

  dynamic "inbound_rule" {
    for_each = module.ec2_node
    content {
      protocol         = "tcp"
      port_range       = "1-65535"
      source_addresses = [inbound_rule.value.public_ip]
    }
  }

  dynamic "inbound_rule" {
    for_each = module.ec2_node
    content {
      protocol         = "udp"
      port_range       = "1-65535"
      source_addresses = [inbound_rule.value.public_ip]
    }
  }
}


答:
It is because Array.push returns the new length of the array:

let arr = [];

console.log(arr.push('something')) // Should output 1
console.log(arr.push('something else')) // Should output 2```

You didn't log anything, but if you run code in the console it will print the outcome of the last statement.

Title: Why is this code giving me an output of 5?

Body:
The goal of this code is to double each number in the array. I was trying to mimic the map() method. But that is not important. What I am wondering is why this code gives me an output of 5 while I did not console.log it. Then when I run it again it keeps adding 5 to a variable I am not aware of?

const numbers = [1, 2, 3, 4, 5];
const doubleNumbers = [];
for (let i = 0; i < numbers.length; i += 1) {
  doubleNumbers.push(numbers[i] * 2)
}

Body:
It is because Array.push returns the new length of the array:

let arr = [];

console.log(arr.push('something')) // Should output 1
console.log(arr.push('something else')) // Should output 2

You didn't log anything, but if you run code in the console it will print the outcome of the last statement.


问:
Is there a way to detect if a scale_linetype_manual has been added to a ggplot?
I need to be able to detect whether a ggplot passed into a function already has a scale_linetype_manual added to it so that I know whether to use ggnewscale and add another new_scale("linetype") to it.

答:
This function should do the trick:

has_linetype_manual <- function(p) {
  x <- sapply(p$scales$scales, function(x) x$aesthetics == "linetype")
  y <- sapply(p$scales$scales, function(x) as.list(x$call)$scale_name == "manual")
  if(length(x) == 0) FALSE else any(x & y)
}
```
<p>So, setting up an example:</p>
<pre class="lang-r prettyprint-override"><code>library(ggplot2)

p1 <- ggplot(iris, aes(x = Sepal.Width, linetype = Species)) + geom_density()

p2 <- p1 + scale_linetype_manual(values = c(4, 5, 6))

p3 <- p1 + scale_linetype_discrete()
</code>```

Of the above plots, only p2 should give us TRUE when passed to has_linetype_manual

has_linetype_manual(p1)
#> [1] FALSE
has_linetype_manual(p2)
#> [1] TRUE
has_linetype_manual(p3)
#> [1] FALSE
```

Created on 2022-02-10 by the reprex package (v2.0.1)

Body:
This function should do the trick:

has_linetype_manual <- function(p) {
  x <- sapply(p$scales$scales, function(x) x$aesthetics == "linetype")
  y <- sapply(p$scales$scales, function(x) as.list(x$call)$scale_name == "manual")
  if(length(x) == 0) FALSE else any(x & y)
}

So, setting up an example:

library(ggplot2)

p1 <- ggplot(iris, aes(x = Sepal.Width, linetype = Species)) + geom_density()

p2 <- p1 + scale_linetype_manual(values = c(4, 5, 6))

p3 <- p1 + scale_linetype_discrete()

Of the above plots, only p2 should give us TRUE when passed to has_linetype_manual

has_linetype_manual(p1)
#> [1] FALSE
has_linetype_manual(p2)
#> [1] TRUE
has_linetype_manual(p3)
#> [1] FALSE

Created on 2022-02-10 by the reprex package (v2.0.1)


答:
The email.utils module in the standard library has a parseaddr function that does exactly that:

Parse address – which should be the value of some address-containing field such as To or Cc – into its constituent realname and email address parts. Returns a tuple of that information, unless the parse fails, in which case a 2-tuple of ('', '') is returned.

An example:

from email.utils import parseaddr

sender = '"Name Surname" <name.surname@gmail.com>'
sender_name, sender_email_address = parseaddr(sender)

sender_name
#=> 'Name Surname'

sender_email_address
#=> 'name.surname@gmail.com'
```

Title: Extract mail address from HTML-like string in Python


答:
Your Code output is okay

```<code>     const numbers = [1,2,3,4,5];
     const doubleNumbers = [];
     for (let i = 0; i < numbers.length; i+=1) {
         doubleNumbers.push(numbers[i] * 2)
      }

      console.log(doubleNumbers)
</code>```

Maybe You console the length of array

Body:
Your Code output is okay

     const numbers = [1,2,3,4,5];
     const doubleNumbers = [];
     for (let i = 0; i < numbers.length; i+=1) {
         doubleNumbers.push(numbers[i] * 2)
      }

      console.log(doubleNumbers)

Maybe You console the length of array


问:
Efficient way to concatenate dataframe with its columns reversed
One fairly recurring pattern I have is creating a dataframe that combines another dataframe with its columns reversed. Here's a small example:

import pandas as pd

df = pd.DataFrame({"a": range(5), "b": range(6, 1, -1)})
combined = pd.concat([df, df.rename(columns={"a": "b", "b": "a"})], ignore_index=True)
```

Is there a more efficient approach to achieving this operation (esp. with many, many rows)?

答:
Convert values to numpy array and use np.concatenate with reverse order of array by indexing a[:, ::-1], last pass to DataFrame constructor:

```<code>a = df.to_numpy()
combined = pd.DataFrame(np.concatenate([a, a[:, ::-1]]), columns=df.columns)
print(combined)
   a  b
0  0  6
1  1  5
2  2  4
3  3  3
4  4  2
5  6  0
6  5  1
7  4  2
8  3  3
9  2  4
</code>```

Body:
One fairly recurring pattern I have is creating a dataframe that combines another dataframe with its columns reversed. Here's a small example:

import pandas as pd

df = pd.DataFrame({"a": range(5), "b": range(6, 1, -1)})
combined = pd.concat([df, df.rename(columns={"a": "b", "b": "a"})], ignore_index=True)

Is there a more efficient approach to achieving this operation (esp. with many, many rows)?

Body:
Convert values to numpy array and use np.concatenate with reverse order of array by indexing a[:, ::-1], last pass to DataFrame constructor:

a = df.to_numpy()
combined = pd.DataFrame(np.concatenate([a, a[:, ::-1]]), columns=df.columns)
print(combined)
   a  b
0  0  6
1  1  5
2  2  4
3  3  3
4  4  2
5  6  0
6  5  1
7  4  2
8  3  3
9  2  4


问:
Why freeze application when use Coroutine in Android
In my application I want call API every 60 sec and for this I want use Coroutines.

I write below codes, but after some time my application has freeze and user can not use this application!

My codes :

```<code>private val coroutineScope = CoroutineScope(Dispatchers.Main)

...

private fun callLoopApi(): Job {
    return coroutineScope.launch {
        while (isActive) {
            delay(10000)
            presenter.callApi(5)
            Log.e("CoroutineLog", "CallApi")
        }
    }
}
</code>```

ApiCall codes:

```<code>override fun callApi(id: Int) {
        if (view.checkNetworkConnection()) {
            view.showLoader()
            disposable = ApiClientLive.getInstance().apisUseCase()
                .getTeamInfo(id)
                .applyIoScheduler()
                .subscribe({ response ->
                    view.hideLoader()
                    when (response.code()) {
                        in 200..202 -> {
                            response.body()?.let { itBody ->
                                itBody.data.let { itData ->
                                    itData?.results?.let { itResult ->
                                        view.loadTeamInfo(itResult)
                                    }
                                }
                            }
                        }
</code>```

I want call API every 60 sec and update my UI.

How can I fix this problem?!

答:
You launch it in the main tread
sample
Change it

```<code>private val coroutineScope = CoroutineScope(Dispatchers.IO)
private fun callLoopApi(): Job {
    return coroutineScope.launch {
        while (isActive) {
            if (isRunLoopedApi) {
                presenter.callApi(5)
                delay(60000)
            }
        }
    }
}
</code>```

or

```<code>private val coroutineScope = CoroutineScope(Dispatchers.Main)
    private fun callLoopApi(): Job {
    return coroutineScope.launch(Dispatchers.Default + "BackgroundCoroutine") {
        while (isActive) {
            if (isRunLoopedApi) {
                presenter.callApi(5)
                delay(60000)
            }
        }
    }
}
</code>```

Body:
In my application I want call API every 60 sec and for this I want use Coroutines.

I write below codes, but after some time my application has freeze and user can not use this application!

My codes :

private val coroutineScope = CoroutineScope(Dispatchers.Main)

...

private fun callLoopApi(): Job {
    return coroutineScope.launch {
        while (isActive) {
            delay(10000)
            presenter.callApi(5)
            Log.e("CoroutineLog", "CallApi")
        }
    }
}

ApiCall codes:

override fun callApi(id: Int) {
        if (view.checkNetworkConnection()) {
            view.showLoader()
            disposable = ApiClientLive.getInstance().apisUseCase()
                .getTeamInfo(id)
                .applyIoScheduler()
                .subscribe({ response ->
                    view.hideLoader()
                    when (response.code()) {
                        in 200..202 -> {
                            response.body()?.let { itBody ->
                                itBody.data.let { itData ->
                                    itData?.results?.let { itResult ->
                                        view.loadTeamInfo(itResult)
                                    }
                                }
                            }
                        }

I want call API every 60 sec and update my UI.

How can I fix this problem?!

Body:
You launch it in the main tread
sample
Change it

private val coroutineScope = CoroutineScope(Dispatchers.IO)
private fun callLoopApi(): Job {
    return coroutineScope.launch {
        while (isActive) {
            if (isRunLoopedApi) {
                presenter.callApi(5)
                delay(60000)
            }
        }
    }
}

or

private val coroutineScope = CoroutineScope(Dispatchers.Main)
    private fun callLoopApi(): Job {
    return coroutineScope.launch(Dispatchers.Default + "BackgroundCoroutine") {
        while (isActive) {
            if (isRunLoopedApi) {
                presenter.callApi(5)
                delay(60000)
            }
        }
    }
}


问:
How can I enable Huawei Push Kit? Authentication parameters needed
I do all the steps according to the Huawei documentation
First, I enabled the Push Kit api through the Project Settings -> Manage Apis

Then I go to the Grow -> Push Kit and turn on Push Kit there, after which I turn on precise messaging:

After that, I try to enable precise messaging for my app, but instead I see this window

I did not find any information about what to write in the Authentication parameters window

答:
If you are facing this problem, then most likely you do not have enough rights for these actions.

You need to contact the account owner and ask to expand your rights and permissions


问:
How do I make row_number () work after a case clause?
I'm having issues with applying this row_number() function on SQL Server. Ideally, I want to use the function, dense_rank() but only works when writing on Oracle.

When I run the query I get the SQL Error[207][S0001]: Invalid column name 'tag_year'.

```<code>    select
'last 7 days' as time_period,
CAST(dd.CalendarDate as DATE) as 'Date',
dd.CalendarID,
cast(CAST(dd.CalendarDate as DATE) as varchar) as time,
right(CAST(dd.CalendarDate as DATE), 5) as axis_date,
(case
    when dd.CalendarDate between dateadd(month, -11,getdate()) and getdate() then 'cy'
    else 'ly' end) as tag_year,
'DAY' + CAST(
ROW_NUMBER () over (partition by tag_year order by time desc ) as varchar) as time_index, --calendar week day
ROW_NUMBER() over (partition by tag_year order by time desc ) as last_n,
CAST(last_n AS varchar)+time_period as time_key
from dim.Calendar dd
where
(dd.CalendarDate between getdate() - 7 and getdate() - 1) -- last 31 days
or (dd.CalendarDate between getdate() - 7 - 52 * 7 and getdate() - 1 - 52 * 7);
</code>```

Not sure what the issue is and when I add group by, it crashes stil.

Any help or guidance would be appreciated

答:
tag_year is the result of an expression created inline in the query. To use its value on another expression, you'll need to create this value as a column in a subquery first.

For example:

```<code>select *,
  'DAY' + CAST(
  ROW_NUMBER () over (partition by tag_year order by time desc ) as varchar)
    as time_index, --calendar week day
  ROW_NUMBER() over (partition by tag_year order by time desc ) as last_n,
from (
  select
    'last 7 days' as time_period,
    CAST(dd.CalendarDate as DATE) as 'Date',
    dd.CalendarID,
    cast(CAST(dd.CalendarDate as DATE) as varchar) as time,
    right(CAST(dd.CalendarDate as DATE), 5) as axis_date,
    case
      when dd.CalendarDate between dateadd(month, -11,getdate()) and getdate()
      then 'cy'
      else 'ly'
    end as tag_year,
    CAST(last_n AS varchar)+time_period as time_key
  from dim.Calendar dd
  where
  (dd.CalendarDate between getdate() - 7 and getdate() - 1) -- last 31 days
  or (dd.CalendarDate between getdate() - 7 - 52 * 7 and getdate() - 1 - 52 * 7)
) x
</code>```

Body:
I'm having issues with applying this row_number() function on SQL Server. Ideally, I want to use the function, dense_rank() but only works when writing on Oracle.

When I run the query I get the SQL Error[207][S0001]: Invalid column name 'tag_year'.

    select
'last 7 days' as time_period,
CAST(dd.CalendarDate as DATE) as 'Date',
dd.CalendarID,
cast(CAST(dd.CalendarDate as DATE) as varchar) as time,
right(CAST(dd.CalendarDate as DATE), 5) as axis_date,
(case
    when dd.CalendarDate between dateadd(month, -11,getdate()) and getdate() then 'cy'
    else 'ly' end) as tag_year,
'DAY' + CAST(
ROW_NUMBER () over (partition by tag_year order by time desc ) as varchar) as time_index, --calendar week day
ROW_NUMBER() over (partition by tag_year order by time desc ) as last_n,
CAST(last_n AS varchar)+time_period as time_key
from dim.Calendar dd
where
(dd.CalendarDate between getdate() - 7 and getdate() - 1) -- last 31 days
or (dd.CalendarDate between getdate() - 7 - 52 * 7 and getdate() - 1 - 52 * 7);

Not sure what the issue is and when I add group by, it crashes stil.

Any help or guidance would be appreciated

Body:
tag_year is the result of an expression created inline in the query. To use its value on another expression, you'll need to create this value as a column in a subquery first.

For example:

select *,
  'DAY' + CAST(
  ROW_NUMBER () over (partition by tag_year order by time desc ) as varchar)
    as time_index, --calendar week day
  ROW_NUMBER() over (partition by tag_year order by time desc ) as last_n,
from (
  select
    'last 7 days' as time_period,
    CAST(dd.CalendarDate as DATE) as 'Date',
    dd.CalendarID,
    cast(CAST(dd.CalendarDate as DATE) as varchar) as time,
    right(CAST(dd.CalendarDate as DATE), 5) as axis_date,
    case
      when dd.CalendarDate between dateadd(month, -11,getdate()) and getdate()
      then 'cy'
      else 'ly'
    end as tag_year,
    CAST(last_n AS varchar)+time_period as time_key
  from dim.Calendar dd
  where
  (dd.CalendarDate between getdate() - 7 and getdate() - 1) -- last 31 days
  or (dd.CalendarDate between getdate() - 7 - 52 * 7 and getdate() - 1 - 52 * 7)
) x


问:
How do I add a sliding header to my Page View in Swift UI
I'm trying to add a header to my app depending on current Tab, so First, Second, Third Fourth. Similar to the reddit app News/Popular/Home. Is there something in Swift UI that can do this?

```<code>    var body: some View {
            TabView {
                Text("First")
                Text("Second")
                Text("Third")
                Text("Fourth")
            }
            .tabViewStyle(.page(indexDisplayMode: .never))
        }
}

</code>```

答:
You can put your own buttons above the TabView, that change the selected page:

```<code>struct ContentView: View {

    @State private var selectedTab = 1

    var body: some View {
        VStack(spacing: 0) {

            HStack {
                tabButton(title: "One", tag: 1)
                tabButton(title: "Two", tag: 2)
                tabButton(title: "Three", tag: 3)
            }
            .padding(.top)
            .font(.headline)

            TabView(selection: $selectedTab) {
                Text("First Tab").tag(1)
                Text("Second Tab").tag(2)
                Text("Third Tab").tag(3)
            }
            .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
            .background(.gray.opacity(0.5))
        }
    }

    func tabButton(title: String, tag: Int) -> some View {
        VStack {
            Button(title) { withAnimation { selectedTab = tag } }
            .frame(maxWidth: .infinity)
            .foregroundColor(selectedTab == tag ? .primary : .secondary)

            Color(selectedTab == tag ? .blue : .clear)
                .frame(height: 4)
                .padding(.horizontal)
        }
    }
}
</code>```

Body:
I'm trying to add a header to my app depending on current Tab, so First, Second, Third Fourth. Similar to the reddit app News/Popular/Home. Is there something in Swift UI that can do this?

    var body: some View {
            TabView {
                Text("First")
                Text("Second")
                Text("Third")
                Text("Fourth")
            }
            .tabViewStyle(.page(indexDisplayMode: .never))
        }
}

Body:
You can put your own buttons above the TabView, that change the selected page:

struct ContentView: View {

    @State private var selectedTab = 1

    var body: some View {
        VStack(spacing: 0) {

            HStack {
                tabButton(title: "One", tag: 1)
                tabButton(title: "Two", tag: 2)
                tabButton(title: "Three", tag: 3)
            }
            .padding(.top)
            .font(.headline)

            TabView(selection: $selectedTab) {
                Text("First Tab").tag(1)
                Text("Second Tab").tag(2)
                Text("Third Tab").tag(3)
            }
            .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
            .background(.gray.opacity(0.5))
        }
    }

    func tabButton(title: String, tag: Int) -> some View {
        VStack {
            Button(title) { withAnimation { selectedTab = tag } }
            .frame(maxWidth: .infinity)
            .foregroundColor(selectedTab == tag ? .primary : .secondary)

            Color(selectedTab == tag ? .blue : .clear)
                .frame(height: 4)
                .padding(.horizontal)
        }
    }
}


问:
getting seg fault on malloc'ing for a string array. please help
```<code>#include<stdio.h>
------------------
#include<stdlib.h>
--------------------
#include<string.h
--------------------

enum { buf = BUFSIZ };

char line[buf], **tab = NULL;

 int cur_buf, count_lineMax = -1, count_line = -1,
    i, j, k, l;

int main (int argc, char **argv) {

        FILE *file1;
        file1 = fopen(argv[1], "r");

        cur_buf = buf;

        /*printf("%d\n", cur_buf);*/

                while(fgets(line, cur_buf, file1) != NULL) {

                        i = strlen(line);

                        for(j=0;j<i;j++) {
                                if(line[j] == '\n') {
                                        count_lineMax++;
                                }
                                /*printf("%c", line[j]);*/
                        }

                }
                /*printf("%d\n", count_lineMax);*/

                rewind(file1);

                tab = malloc(count_lineMax);
                memset(tab, 0, count_lineMax);

                for(k=0;k<count_lineMax;k++) {
                        tab[k] = malloc(cur_buf+1);
                        memset(tab[k], 0, cur_buf+1);
                }

                        while(fgets(line, cur_buf, file1) != NULL) {
                                i = strlen(line);

                                for(j=0;j<i;j++) {
                                        if(line[j] == '\n') {
                                                count_line++;
                                        }
                                }
                        tab[count_line] = line;
                        printf("%s", tab[count_line]);
                        }
        return 0;
        for(l=0;l<count_lineMax;l++) {
                free(tab[l]);
        }

        free(tab);
        fclose(file1);
}
## Heading ##
</code>```

答: Also, you never check that count_line is in range so tab[count_line] could be invalid when you assign to it.</p>


答:
Maybe you aren't giving the entire context here?
What is numbers2 anyway? You declare a new array, doubleNumbers, but don't use it?

```<code>doubleNumbers.push(numbers[i] * 2)
</code>```

should work just fine I believe.

Body:
Maybe you aren't giving the entire context here?
What is numbers2 anyway? You declare a new array, doubleNumbers, but don't use it?

doubleNumbers.push(numbers[i] * 2)

should work just fine I believe.


问:
MongoDB query and update single object inside nested array by ID?
From this example document:

```<code>...
{
    "_id": ObjectId("5a934e000102030405000000"),
    "guild_id": 1234,
    "members": [
        ...
        {
            "member_id": 002,
            "name": "John Doe"
        },
        ...
    ]
}
...
</code>```

I want to fetch an individual member object from the nested array so that I will be returned:

```<code>{"member_id": 002, "name": "John Doe"}
</code>```

with which I can read in the member info.

How might one query by "member_id" like with 002 and get the desired result above? And with this, how would you also update the member "name" as well? Preferably in Python syntax, please, but any is fine as well.

答:
aggregate

```<code>db.collection.aggregate([
  {
    "$match": {
      "members.member_id": "001"
    }
  },
  {
    "$unwind": "$members"
  },
  {
    "$match": {
      "members.member_id": "001"
    }
  },
  {
    "$replaceWith": "$members"
  }
])
</code>```

mongoplayground

update

```<code>db.collection.update({
  "members.member_id": "001"
},
{
  "$set": {
    "members.$.name": "John"
  }
},
{
  "multi": false,
  "upsert": false
})
</code>```

mongoplayground

python(fastapi) Edit this by yourself

```<code>from fastapi import FastAPI, Request, status, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pymongo import MongoClient
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel

CONNECTION_STRING = "mongodb://localhost"
try:
    client = MongoClient(CONNECTION_STRING, serverSelectionTimeoutMS=3000)
    print('Connected ! Mongo version is', client.server_info()['version'])
except:
    print('Disconnected !')

app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}),
    )

templates = Jinja2Templates(directory="static")

@app.get("/")
async def root():
    db = get_database()
    c = db['key'].find({"_id":2})
    if (c):
        return {"message": c[0]}
    return {"message": c}

@app.get("/get/{id}")
async def root(id: int):
    db = get_database()
    c = list(db['key'].find({"_id":id}))
    return {"message": c}

def get_database():
    return client['test']

# This is added so that many files can reuse the function get_database()
if __name__ == "__main__":
    print('__main__ !')
    # Get the database
    dbname = get_database()
</code>```

Body:
From this example document:

...
{
    "_id": ObjectId("5a934e000102030405000000"),
    "guild_id": 1234,
    "members": [
        ...
        {
            "member_id": 002,
            "name": "John Doe"
        },
        ...
    ]
}
...

I want to fetch an individual member object from the nested array so that I will be returned:

{"member_id": 002, "name": "John Doe"}

with which I can read in the member info.

How might one query by "member_id" like with 002 and get the desired result above? And with this, how would you also update the member "name" as well? Preferably in Python syntax, please, but any is fine as well.

Body:
aggregate

db.collection.aggregate([
  {
    "$match": {
      "members.member_id": "001"
    }
  },
  {
    "$unwind": "$members"
  },
  {
    "$match": {
      "members.member_id": "001"
    }
  },
  {
    "$replaceWith": "$members"
  }
])

mongoplayground

update

db.collection.update({
  "members.member_id": "001"
},
{
  "$set": {
    "members.$.name": "John"
  }
},
{
  "multi": false,
  "upsert": false
})

mongoplayground

python(fastapi) Edit this by yourself

from fastapi import FastAPI, Request, status, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pymongo import MongoClient
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel

CONNECTION_STRING = "mongodb://localhost"
try:
    client = MongoClient(CONNECTION_STRING, serverSelectionTimeoutMS=3000)
    print('Connected ! Mongo version is', client.server_info()['version'])
except:
    print('Disconnected !')

app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}),
    )

templates = Jinja2Templates(directory="static")

@app.get("/")
async def root():
    db = get_database()
    c = db['key'].find({"_id":2})
    if (c):
        return {"message": c[0]}
    return {"message": c}

@app.get("/get/{id}")
async def root(id: int):
    db = get_database()
    c = list(db['key'].find({"_id":id}))
    return {"message": c}

def get_database():
    return client['test']

# This is added so that many files can reuse the function get_database()
if __name__ == "__main__":
    print('__main__ !')
    # Get the database
    dbname = get_database()


答:
You can use the underlying numpy array and vstack on the array and its reversed version, then generate a new DataFrame:

```<code>import numpy as np

a = df.to_numpy()
pd.DataFrame(np.vstack([a, a[:, ::-1]]), columns=df.columns)
</code>```

Title: Efficient way to concatenate dataframe with its columns reversed

Body:
You can use the underlying numpy array and vstack on the array and its reversed version, then generate a new DataFrame:

import numpy as np

a = df.to_numpy()
pd.DataFrame(np.vstack([a, a[:, ::-1]]), columns=df.columns)


问:
Image fullscreen on click (Wordpress Image carussell)
I have a similar problem like this (link). I want to edit my image carussel on my wordpress page, so that when I click on an image, it will be shown in full screen. If possible with close button.
The HTMl is:

  <title>Fullscreen Image</title>

```

Can someone give me an example for CSS or JS how I can do it (I do not know a lot of JS or jQuery)?

Thanks in advance

答:
You need to perform a few tricky operations. First, you need to be able to show things on full-screen. I did this by setting the backgroundImage of body and hiding everything else once body gets the fullscreen class. But we need to avoid propagating the event, so, if the image is clicked in fullscreen mode, then we can restore the normal view.

    function makeFullScreen(event, image) {
        event.stopPropagation();
        event.source;
        document.body.style.backgroundImage = `url("${image.src}")`;
        document.body.classList.add("fullscreen");
    }

    function hideFullScreen() {
        document.body.style.backgroundImage = '';
        document.body.classList.remove("fullscreen");
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body.fullscreen {
    background-size: cover;
    background-repeat: no-repeat;
}

body.fullscreen * {
    display: none;
}</code>```

  <title>Fullscreen Image</title>

```

Body:
I have a similar problem like this (link). I want to edit my image carussel on my wordpress page, so that when I click on an image, it will be shown in full screen. If possible with close button.
The HTMl is:

  <title>Fullscreen Image</title>

Can someone give me an example for CSS or JS how I can do it (I do not know a lot of JS or jQuery)?

Thanks in advance

Body:
You need to perform a few tricky operations. First, you need to be able to show things on full-screen. I did this by setting the backgroundImage of body and hiding everything else once body gets the fullscreen class. But we need to avoid propagating the event, so, if the image is clicked in fullscreen mode, then we can restore the normal view.

    function makeFullScreen(event, image) {
        event.stopPropagation();
        event.source;
        document.body.style.backgroundImage = `url("${image.src}")`;
        document.body.classList.add("fullscreen");
    }

    function hideFullScreen() {
        document.body.style.backgroundImage = '';
        document.body.classList.remove("fullscreen");
    }

body.fullscreen {
    background-size: cover;
    background-repeat: no-repeat;
}

body.fullscreen * {
    display: none;
}

<html onclick="hideFullScreen()">

<head>
  <title>Fullscreen Image</title>
</head>

<body>

        <div class="swiper-slide">
            <img class="swiper-slide-image" src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png" onclick="makeFullScreen(event, this);">
        </div>
        <div class="swiper-slide">
            <img class="swiper-slide-image" src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c2/1_aerial_yangshuo_panorama_2017.jpg/500px-1_aerial_yangshuo_panorama_2017.jpg" onclick="makeFullScreen(event, this);">
        </div>
</body>

</html>


问:
Cycle Cloud Run Instance Manually
Occasionally my instances get into a corrupted state (especially since min-instance=1). I would like to restart one manually. Is this possible?

I know I can go through the console to create a new version, but this messes up my Terraform state. I would like to keep with the current version and just cycle the instance, a classic IT procedure called "Turning it on and off again" to fix my short term issue while I figure out the larger issue.

答:
No, you can't do it. If you have a routine that can detect a corruption, you can exit the container (the instance stopped and a new one is created). For that, 2 options:

Either you have an internal check that detects automatically the state of the container and exits in case of corruption (works for max-instance >=1 )

Or you can have 2 different endpoints (works only for max-instance=1):

One tell you the state of the container (OK or KO)

In case of KO, you can call an endpoint in your app that stop the instance ( And if your container is public, it's dangerous because anyone can restart your container!)

Title: Cycle Cloud Run Instance Manually


问:
Max sum from a contiguous array(having atleast one element)
Given a list. I have to create sublists having at least one element, and then return the sublist having maximum sum.

here is what I tried :

```<code>class Solution:
def maxSubArray(self, nums: List[int]) -> int:
    lists=[[]]

    for i in range(1,len(nums)+1):
        for j in range(1,i):
            lists.append(nums[j:i])
    new_list=lists
    sum_list=[]
    for k in range(1,len(new_list)):
        sum1=sum(new_list[k])
        sum_list.append(sum1)
    return max(sum_list)
</code>```

this is giving this error :

```<code>ValueError: max() arg is an empty sequence
</code>```

How do I tweek my code to remove the empty sublist.

答:
You can check if the list is empty before applying the max() method like this:</p>
```<code>class Solution:
def maxSubArray(self, nums: List[int]) -> int:
    lists=[[]]

    for i in range(1,len(nums)+1):
        for j in range(1,i):
            lists.append(nums[j:i])
    new_list=lists
    sum_list=[]
    for k in range(1,len(new_list)):
        sum1=sum(new_list[k])
        sum_list.append(sum1)
    if sum_list:
        return max(sum_list)
    else:
        return 0  # or some default value you want
</code>```

Body:
Given a list. I have to create sublists having at least one element, and then return the sublist having maximum sum.

here is what I tried :

class Solution:
def maxSubArray(self, nums: List[int]) -> int:
    lists=[[]]

    for i in range(1,len(nums)+1):
        for j in range(1,i):
            lists.append(nums[j:i])
    new_list=lists
    sum_list=[]
    for k in range(1,len(new_list)):
        sum1=sum(new_list[k])
        sum_list.append(sum1)
    return max(sum_list)

this is giving this error :

ValueError: max() arg is an empty sequence

How do I tweek my code to remove the empty sublist.

Body:
You can check if the list is empty before applying the max() method like this:

class Solution:
def maxSubArray(self, nums: List[int]) -> int:
    lists=[[]]

    for i in range(1,len(nums)+1):
        for j in range(1,i):
            lists.append(nums[j:i])
    new_list=lists
    sum_list=[]
    for k in range(1,len(new_list)):
        sum1=sum(new_list[k])
        sum_list.append(sum1)
    if sum_list:
        return max(sum_list)
    else:
        return 0  # or some default value you want


问:
Pull only one folder from get repository Git from Azure Pipelines
I'm working on Git. My Environment is Azure DevOps. I have a vsts build agent.
I'm trying to pull only one folder from my repo on to the build agent. I'm using powershell.
What I have tried is :

```<code>git init
git remote add origin https://MYUSERNAME:MYPERSONALACCESSTOKEN@mytfs-git-project-url
git config core.sparseCheckout true
Set-Content .git\info\space-checkout "myfolder/*" -Encoding Ascii
git pull origin master
</code>```

I'm getting Authentication failed for username error. I can clone it locally using
"git clone https://MYPERSONALACCESSTOKEN@tfs-git-url", But if I try the same on Azure DevOps Powershell it gives the error as cannot read username error. I did try out the stackoverflow suggestions but it did not work. Any new suggestions are appreciated.

答:
I made a few changes to your script, it's working on my environment when downloading the sources from the same Azure DevOps organization. The changes are as follows:

Instead of relying on manually setting the sparse config, I use the sparse-checkout set command, it will automatically set other required flags and configs.

Instead of relying on (insecurely) setting the security token in the clone URL, instead I pass the variable in as an extraheader.

Instead of relying on a PAT (which is fine locally), I instead pick up the access token from the build/release job.

This results in the following task:

steps:
- task: PowerShell@2
  displayName: 'Sparse Checkout'
  inputs:
    script: |
     git init
     git remote add origin https://org@dev.azure.com/org/project/_git/repo
     git config core.sparseCheckout true
     git sparse-checkout set "Folder/*"
     git -c http.extraheader="AUTHORIZATION: Bearer $env:System.AccessToken" pull origin master
    workingDirectory: '$(System.ArtifactsDirectory)'
  env:
    System.AccessToken: $(System.AccessToken)
```

Setting these inputs in the UI works as well:

Body:
I'm working on Git. My Environment is Azure DevOps. I have a vsts build agent.
I'm trying to pull only one folder from my repo on to the build agent. I'm using powershell.
What I have tried is :

git init
git remote add origin https://MYUSERNAME:MYPERSONALACCESSTOKEN@mytfs-git-project-url
git config core.sparseCheckout true
Set-Content .git\info\space-checkout "myfolder/*" -Encoding Ascii
git pull origin master

I'm getting Authentication failed for username error. I can clone it locally using
"git clone https://MYPERSONALACCESSTOKEN@tfs-git-url", But if I try the same on Azure DevOps Powershell it gives the error as cannot read username error. I did try out the stackoverflow suggestions but it did not work. Any new suggestions are appreciated.

Body:
I made a few changes to your script, it's working on my environment when downloading the sources from the same Azure DevOps organization. The changes are as follows:

Instead of relying on manually setting the sparse config, I use the sparse-checkout set command, it will automatically set other required flags and configs.

Instead of relying on (insecurely) setting the security token in the clone URL, instead I pass the variable in as an extraheader.

Instead of relying on a PAT (which is fine locally), I instead pick up the access token from the build/release job.

This results in the following task:

steps:
- task: PowerShell@2
  displayName: 'Sparse Checkout'
  inputs:
    script: |
     git init
     git remote add origin https://org@dev.azure.com/org/project/_git/repo
     git config core.sparseCheckout true
     git sparse-checkout set "Folder/*"
     git -c http.extraheader="AUTHORIZATION: Bearer $env:System.AccessToken" pull origin master
    workingDirectory: '$(System.ArtifactsDirectory)'
  env:
    System.AccessToken: $(System.AccessToken)

Setting these inputs in the UI works as well:


问:
How can I set state on individual elements in a mapped function using React?
I have an array of questions that I'm mapping through and displaying them in the UI, there is about 70+ questions.

Each question has a '+' button that reveals an answer when clicked, I want to reveal the answer using state but only for the specific question that is clicked, not the entire list. Currently I have it so when a button is clicked, it reveals all 70+ answers, what's the best way to do this so it only reveals one?

This is my code:

```<code>  const [open, setOpen] = useState(false);

 <div className='md:mt-8 pb-20'>
            {results[0].data.glossary_boxes.map((item, i) => (
              <>
                <div
                  key={i}
                  className='w-full border-3 border-yellow-500 flex-grow p-2 md:p-2 my-8'>
                  <div className='flex h-full items-center'>
                    <div className='bg-yellow-500 px-3 py-1 flex items-center justify-start ml-2'>
                      <a
                        onClick={() => setOpen(!open)}
                        className='text-white text-3xl cursor-pointer'>
                        {open ? '-' : '+'}
                      </a>
                    </div>
                    <div className='flex flex-col items-start'>
                      <p className='text-gray-500 font-sansbold text-md md:text-xl px-12'>
                        {item.question}
                      </p>

                      <p
                        className={`text-xl gray-500 font-quote text-md md:text-lg px-12 ${
                          open ? 'block' : 'hidden'
                        }`}>
                        {item.answer}
                      </p>
                    </div>
                  </div>
                </div>
              </>
            ))}
          </div>
</code>```

When the state is true, it also displays a '-' in place of where the '+' was until clicked again to set to false (hide the answer).

Thanks in advance!

答:
In that situation, you need to handle the open/close trigger for every question.
So you need an additional variable in the object that corresponds for a single question if it's open or not (by default it will be false), that way you can handle every single question itself instead of one single open state that can tell if to open or close all.
Moreover, I would suggest creating a component for a single question, and the component will receive props (isOpen, answer, question, etc..) inside the map function you will render for every item of the component.

for example :
 <SingleQuestion question={item.question} answer={item.answer} isOpen={item.isOpen}>

You can let the component itself (SingleComponent) handle the inner state that decides isOpen true or false, that way every question will hold a state that lets show/hide the answer for the relevant question.

 Hope you got the point, if not I'll try to explain more if needed.

Body:
I have an array of questions that I'm mapping through and displaying them in the UI, there is about 70+ questions.

Each question has a '+' button that reveals an answer when clicked, I want to reveal the answer using state but only for the specific question that is clicked, not the entire list. Currently I have it so when a button is clicked, it reveals all 70+ answers, what's the best way to do this so it only reveals one?

This is my code:

  const [open, setOpen] = useState(false);

            {results[0].data.glossary_boxes.map((item, i) => (
              <>

                       setOpen(!open)}
                        className='text-white text-3xl cursor-pointer'>
                        {open ? '-' : '+'}

                        {item.question}

                        {item.answer}

              </>
            ))}

When the state is true, it also displays a '-' in place of where the '+' was until clicked again to set to false (hide the answer).

Thanks in advance!


问:
Optimize javascript function code if ... else
I implemented a logic that forces me to create many conditions based on different properties value. At first i thought i could refactor it with switch ... case statements but as it does not depend on a single value, i can't go for this solution.

If it were you, how would be optimize, maintain this code ?
context: We are in a React Component, so maybe i could also use useCallback or UseMemo ?

```<code>function navigateToNextStep() {
    if (
      user.lifecycle.stepCompany === 'todo' ||
      user.lifecycle.stepCompany === 'progress'
    ) {
      navigation.navigate(App.SETUP.COMPANY);
    }
    if (
      user.lifecycle.stepIdentity === 'todo' ||
      user.lifecycle.stepIdentity === 'progress'
    ) {
      navigation.navigate(App.SETUP.IDENTITY);
    }
    if (user.lifecycle.stepFinalize === 'todo') {
      navigation.navigate(App.SETUP.FINALIZE);
    }
    if (user.lifecycle.stepIdentity === 'awaiting_review') {
      navigation.navigate(App.SETUP.MODAL.AWAITING_REVIEW);
    }
    if (user.lifecycle.stepIdentity === 'need_approval') {
      navigation.navigate(App.SETUP.MODAL.APPROVAL_REQUIRED);
    }
  }
</code>```

答:
If you have quite complicated if-else statements take a look at RulesEngine,

This is a set of production rules, each of which has a condition and an action - simplistically you can think of it as a bunch of if-then statements.

maybe in your case, it's the best way to simplify(but in most cases, if-else or switch-case enough).

Here you can find different implementations for js.
Take a look at json-rules-engine as an example:

This example demonstates an engine for identifying employees who work for Microsoft and are taking Christmas day off.

const { Engine } = require('json-rules-engine')

/**
 * Setup a new engine
 */
let engine = new Engine()

// define a rule for detecting the player has exceeded foul limits.  Foul out any player who:
// (has committed 5 fouls AND game is 40 minutes) OR (has committed 6 fouls AND game is 48 minutes)
engine.addRule({
  conditions: {
    any: [{
      all: [{
        fact: 'gameDuration',
        operator: 'equal',
        value: 40
      }, {
        fact: 'personalFoulCount',
        operator: 'greaterThanInclusive',
        value: 5
      }]
    }, {
      all: [{
        fact: 'gameDuration',
        operator: 'equal',
        value: 48
      }, {
        fact: 'personalFoulCount',
        operator: 'greaterThanInclusive',
        value: 6
      }]
    }]
  },
  event: {  // define the event to fire when the conditions evaluate truthy
    type: 'fouledOut',
    params: {
      message: 'Player has fouled out!'
    }
  }
})

/**
 * Define facts the engine will use to evaluate the conditions above.
 * Facts may also be loaded asynchronously at runtime; see the advanced example below
 */
let facts = {
  personalFoulCount: 6,
  gameDuration: 40
}

// Run the engine to evaluate
engine
  .run(facts)
  .then(({ events }) => {
    events.map(event => console.log(event.params.message))
  })

/*
 * Output:
 *
 * Player has fouled out!
 */
```
<hr />
<p>Or you can write a simple implementation of Rule Engine based on Object on your own.</p>
<p>As an example for your case:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const rules = [{
    rule: (user) => ['todo', 'progress'].includes(user.lifecycle.stepCompany),
    action: () => console.log("App.SETUP.COMPANY")
  },
  {
    rule: (user) => ['todo', 'progress'].includes(user.lifecycle.stepIdentity),
    action: () => console.log("App.SETUP.IDENTITY")
  }
]

const user = {
  lifecycle: {
    stepCompany: 'todo',
    stepIdentity: 'progress'
  }
}

rules.forEach(r => {
  if (r.rule(user)) {
    r.action()
  }
})</code>```

Body:
I implemented a logic that forces me to create many conditions based on different properties value. At first i thought i could refactor it with switch ... case statements but as it does not depend on a single value, i can't go for this solution.

If it were you, how would be optimize, maintain this code ?
context: We are in a React Component, so maybe i could also use useCallback or UseMemo ?

function navigateToNextStep() {
    if (
      user.lifecycle.stepCompany === 'todo' ||
      user.lifecycle.stepCompany === 'progress'
    ) {
      navigation.navigate(App.SETUP.COMPANY);
    }
    if (
      user.lifecycle.stepIdentity === 'todo' ||
      user.lifecycle.stepIdentity === 'progress'
    ) {
      navigation.navigate(App.SETUP.IDENTITY);
    }
    if (user.lifecycle.stepFinalize === 'todo') {
      navigation.navigate(App.SETUP.FINALIZE);
    }
    if (user.lifecycle.stepIdentity === 'awaiting_review') {
      navigation.navigate(App.SETUP.MODAL.AWAITING_REVIEW);
    }
    if (user.lifecycle.stepIdentity === 'need_approval') {
      navigation.navigate(App.SETUP.MODAL.APPROVAL_REQUIRED);
    }
  }

Body:
If you have quite complicated if-else statements take a look at RulesEngine,

This is a set of production rules, each of which has a condition and an action - simplistically you can think of it as a bunch of if-then statements.

maybe in your case, it's the best way to simplify(but in most cases, if-else or switch-case enough).

Here you can find different implementations for js.
Take a look at json-rules-engine as an example:

This example demonstates an engine for identifying employees who work for Microsoft and are taking Christmas day off.

const { Engine } = require('json-rules-engine')

/**
 * Setup a new engine
 */
let engine = new Engine()

// define a rule for detecting the player has exceeded foul limits.  Foul out any player who:
// (has committed 5 fouls AND game is 40 minutes) OR (has committed 6 fouls AND game is 48 minutes)
engine.addRule({
  conditions: {
    any: [{
      all: [{
        fact: 'gameDuration',
        operator: 'equal',
        value: 40
      }, {
        fact: 'personalFoulCount',
        operator: 'greaterThanInclusive',
        value: 5
      }]
    }, {
      all: [{
        fact: 'gameDuration',
        operator: 'equal',
        value: 48
      }, {
        fact: 'personalFoulCount',
        operator: 'greaterThanInclusive',
        value: 6
      }]
    }]
  },
  event: {  // define the event to fire when the conditions evaluate truthy
    type: 'fouledOut',
    params: {
      message: 'Player has fouled out!'
    }
  }
})

/**
 * Define facts the engine will use to evaluate the conditions above.
 * Facts may also be loaded asynchronously at runtime; see the advanced example below
 */
let facts = {
  personalFoulCount: 6,
  gameDuration: 40
}

// Run the engine to evaluate
engine
  .run(facts)
  .then(({ events }) => {
    events.map(event => console.log(event.params.message))
  })

/*
 * Output:
 *
 * Player has fouled out!
 */

Or you can write a simple implementation of Rule Engine based on Object on your own.

As an example for your case:

const rules = [{
    rule: (user) => ['todo', 'progress'].includes(user.lifecycle.stepCompany),
    action: () => console.log("App.SETUP.COMPANY")
  },
  {
    rule: (user) => ['todo', 'progress'].includes(user.lifecycle.stepIdentity),
    action: () => console.log("App.SETUP.IDENTITY")
  }
]

const user = {
  lifecycle: {
    stepCompany: 'todo',
    stepIdentity: 'progress'
  }
}

rules.forEach(r => {
  if (r.rule(user)) {
    r.action()
  }
})


问:
Searching through thousands of records (properties) and returning the data
So I have implemented a google maps, using javascript to plot a polygon. I use getBounds to get the latLongs. Then I call a database (postcodes), which contains each lat long for each postcode in the UK.

This query looks like:

```<code>SELECT * FROM `postcode`.`postcodeGoogle` WHERE (`lat` BETWEEN '$lat1' AND '$lat2')
    AND (`long` BETWEEN '$long1' AND '$long2')
</code>```

Which is fine, returns the right data.

I then have a second database, address_list, which contains every address in the UK (at the moment it only contains Kettering area, so 12,000 rows). I do a while loop on the first query and then on each loop run this query:

```<code>SELECT * FROM `digital_hub`.`address_list` WHERE `postcode`='".$row['postcode']."'
</code>```

Then I add the latlong of the postcode to a variable:

$resultE = $resultE."(".$row['lat'].", ".$row['long'].") || ";

This then gets echoed out at the end of the loops.

This page is called via jQuery:

```<code>$.get("php/properties.php?bounds="+bounds, function(data){
        var theLatLongs = data.split(" || ");
        totalcount = 0;

        for(x in theLatLongs){
            var theLatLong = "";
            var latLong = theLatLongs[x].substr(1);
            var latLong = latLong.slice(0, -1);
            var theLatLong = latLong.split(", ");
            var thelat = theLatLong[0];
            var thelong = theLatLong[1];

                totalcount = totalcount+1;

        }
    $('#totalcount').html('<h6><span>'+totalcount+'</span> Households found</h6>Filtered by location');
});
</code>```

It all works fine (I think). It's just incredibly slow. I know facebook have much better resources, but there create advert filterer is amazingly quick. I will also be implementing further filters. I tried a join but the time difference didn't seem to massive. Sometimes it doesn't even return results at all and crashes my mysql service...

答:
there are 3 sources that can slow the code: mysql, php, js.

the first thing I would do is run the sql (the join version), in a tool like toad or do a php file that outputs the raw result. You can add console.time/console.timeEnd to js, and mictrotime in php.

another "fast and dirty" check is to past "your_server"/php/properties.php?bounds=YourBounds,
and check the result. it will give you some indication.

If you are certain it's sql, try to index digital_hub.address_list.postcodes, postcode.postcodeGoogle.lat, and postcode.postcodeGoogle.long.

Then, in your php "raw" script (or your sql tool), try to call the query with less column,
or even with "select count(*)". If the "select count(*)" is way faster, that means that the returning value is slowing the system. This is typical of empty (non null) date fields by example.

But they key is simple, time the different parts of the process to isolate the bottleneck.

```<code>console.time('load');
$.get("php/properties.php?bounds="+bounds, function(data){
        console.timeEnd('load');
        console.time('parse');
        var theLatLongs = data.split(" || ");
        totalcount = 0;

        for(x in theLatLong ){
            var theLatLong = "";
            var latLong = theLatLongs[x].substr(1);
            var latLong = latLong.slice(0, -1);
            var theLatLong = latLong.split(", ");
            var thelat = theLatLong[0];
            var thelong = theLatLong[1];

        totalcount = totalcount+1;
        }
console.timeEnd('parse');
    console.time('display');
    $('#totalcount').html('<h6><span>'+totalcount+'</span> Households found</h6>Filtered by location');
    console.timeEnd('display');
});
</code>```

on a side note, you might consider json data. (and review your use of thelatlong js var, but I guess you are debugging)
in php:

```<code>while ($row = msqlqresult) {
    $resultArray[] = $row;
}

$resultJson = json_encode($resultArray);
</code>```

in js:

```<code>console.time('load');
$.getJSON("php/properties.php", {bounds: bounds}, function(data){
        console.timeEnd('load');
        console.time('parse');
        totalcount = 0;

        for(var x in data){
            var thelat = theLatLong[x].lat;
            var thelong = theLatLong[x].long;

            totalcount = totalcount+1;
        }
    console.timeEnd('parse');
    console.time('display');
    $('#totalcount').html('<h6><span>'+totalcount+'</span> Households found</h6>Filtered by location');
    console.timeEnd('display');
</code>```

});

Body:
So I have implemented a google maps, using javascript to plot a polygon. I use getBounds to get the latLongs. Then I call a database (postcodes), which contains each lat long for each postcode in the UK.

This query looks like:

SELECT * FROM `postcode`.`postcodeGoogle` WHERE (`lat` BETWEEN '$lat1' AND '$lat2')
    AND (`long` BETWEEN '$long1' AND '$long2')

Which is fine, returns the right data.

I then have a second database, address_list, which contains every address in the UK (at the moment it only contains Kettering area, so 12,000 rows). I do a while loop on the first query and then on each loop run this query:

SELECT * FROM `digital_hub`.`address_list` WHERE `postcode`='".$row['postcode']."'

Then I add the latlong of the postcode to a variable:

$resultE = $resultE."(".$row['lat'].", ".$row['long'].") || ";

This then gets echoed out at the end of the loops.

This page is called via jQuery:

$.get("php/properties.php?bounds="+bounds, function(data){
        var theLatLongs = data.split(" || ");
        totalcount = 0;

        for(x in theLatLongs){
            var theLatLong = "";
            var latLong = theLatLongs[x].substr(1);
            var latLong = latLong.slice(0, -1);
            var theLatLong = latLong.split(", ");
            var thelat = theLatLong[0];
            var thelong = theLatLong[1];

                totalcount = totalcount+1;

        }
    $('#totalcount').html('
'+totalcount+' Households found
Filtered by location');
});

It all works fine (I think). It's just incredibly slow. I know facebook have much better resources, but there create advert filterer is amazingly quick. I will also be implementing further filters. I tried a join but the time difference didn't seem to massive. Sometimes it doesn't even return results at all and crashes my mysql service...

Body:
there are 3 sources that can slow the code: mysql, php, js.

the first thing I would do is run the sql (the join version), in a tool like toad or do a php file that outputs the raw result. You can add console.time/console.timeEnd to js, and mictrotime in php.

another "fast and dirty" check is to past "your_server"/php/properties.php?bounds=YourBounds,
and check the result. it will give you some indication.

If you are certain it's sql, try to index digital_hub.address_list.postcodes, postcode.postcodeGoogle.lat, and postcode.postcodeGoogle.long.

Then, in your php "raw" script (or your sql tool), try to call the query with less column,
or even with "select count(*)". If the "select count(*)" is way faster, that means that the returning value is slowing the system. This is typical of empty (non null) date fields by example.

But they key is simple, time the different parts of the process to isolate the bottleneck.

console.time('load');
$.get("php/properties.php?bounds="+bounds, function(data){
        console.timeEnd('load');
        console.time('parse');
        var theLatLongs = data.split(" || ");
        totalcount = 0;

        for(x in theLatLong ){
            var theLatLong = "";
            var latLong = theLatLongs[x].substr(1);
            var latLong = latLong.slice(0, -1);
            var theLatLong = latLong.split(", ");
            var thelat = theLatLong[0];
            var thelong = theLatLong[1];

        totalcount = totalcount+1;
        }
console.timeEnd('parse');
    console.time('display');
    $('#totalcount').html('<h6><span>'+totalcount+'</span> Households found</h6>Filtered by location');
    console.timeEnd('display');
});

on a side note, you might consider json data. (and review your use of thelatlong js var, but I guess you are debugging)
in php:

while ($row = msqlqresult) {
    $resultArray[] = $row;
}

$resultJson = json_encode($resultArray);

in js:

console.time('load');
$.getJSON("php/properties.php", {bounds: bounds}, function(data){
        console.timeEnd('load');
        console.time('parse');
        totalcount = 0;

        for(var x in data){
            var thelat = theLatLong[x].lat;
            var thelong = theLatLong[x].long;

            totalcount = totalcount+1;
        }
    console.timeEnd('parse');
    console.time('display');
    $('#totalcount').html('<h6><span>'+totalcount+'</span> Households found</h6>Filtered by location');
    console.timeEnd('display');

});


问:
Is there any event generated when tag is added to an existing S3 object?
I'd like to have an AWS lambda triggered when a tag is added to an existing object in S3 bucket (in the same way as we can do it for object create and remove). Any way to do that?</p>

答: According to AWS documentation there is s3:ObjectTagging:* event type, which can be used as Lambda trigger.


问:
Get average color on bufferedimage and bufferedimage portion as fast as possible
I am trying to find image in an image. I do this for desktop automation. At this moment, I'm trying to be fast, not precise. As such, I have decided to match similar image solely based on the same average color.

If I pick several icons on my desktop, for example:

And I will search for the last one (I'm still wondering what this file is):

You can clearly see what is most likely to be the match:

In different situations, this may not work. However when image size is given, it should be pretty reliable and lightning fast.

I can get a screenshot as BufferedImage object:

```<code>MSWindow window = MSWindow.windowFromName("Firefox", false);
BufferedImage img = window.screenshot();
//Or, if I can estimate smaller region for searching:
BufferedImage img2 = window.screenshotCrop(20,20,50,50);
</code>```

Of course, the image to search image will be loaded from template saved in a file:

```<code>BufferedImage img = ImageIO.read(...whatever goes in there, I'm still confused...);
</code>```

I explained what all I know so that we can focus on the only problem:

Q: How can I get average color on buffered image? How can I get such average color on sub-rectangle of that image?

Speed wins here. In this exceptional case, I consider it more valuable than code readability.

答:
Here's a version based on k_g's answer for a full BufferedImage with adjustable sample precision (step).</p>
```<code>public static Color getAverageColor(BufferedImage bi) {
    int step = 5;

    int sampled = 0;
    long sumr = 0, sumg = 0, sumb = 0;
    for (int x = 0; x < bi.getWidth(); x++) {
        for (int y = 0; y < bi.getHeight(); y++) {
            if (x % step == 0 && y % step == 0) {
                Color pixel = new Color(bi.getRGB(x, y));
                sumr += pixel.getRed();
                sumg += pixel.getGreen();
                sumb += pixel.getBlue();
                sampled++;
            }
        }
    }
    int dim = bi.getWidth()*bi.getHeight();
    // Log.info("step=" + step + " sampled " + sampled + " out of " + dim + " pixels (" + String.format("%.1f", (float)(100*sampled/dim)) + " %)");
    return new Color(Math.round(sumr / sampled), Math.round(sumg / sampled), Math.round(sumb / sampled));
}
</code>```

Body:
I am trying to find image in an image. I do this for desktop automation. At this moment, I'm trying to be fast, not precise. As such, I have decided to match similar image solely based on the same average color.

If I pick several icons on my desktop, for example:

And I will search for the last one (I'm still wondering what this file is):

You can clearly see what is most likely to be the match:

In different situations, this may not work. However when image size is given, it should be pretty reliable and lightning fast.

I can get a screenshot as BufferedImage object:

MSWindow window = MSWindow.windowFromName("Firefox", false);
BufferedImage img = window.screenshot();
//Or, if I can estimate smaller region for searching:
BufferedImage img2 = window.screenshotCrop(20,20,50,50);

Of course, the image to search image will be loaded from template saved in a file:

BufferedImage img = ImageIO.read(...whatever goes in there, I'm still confused...);

I explained what all I know so that we can focus on the only problem:

Q: How can I get average color on buffered image? How can I get such average color on sub-rectangle of that image?

Speed wins here. In this exceptional case, I consider it more valuable than code readability.

Body:
Here's a version based on k_g's answer for a full BufferedImage with adjustable sample precision (step).

public static Color getAverageColor(BufferedImage bi) {
    int step = 5;

    int sampled = 0;
    long sumr = 0, sumg = 0, sumb = 0;
    for (int x = 0; x < bi.getWidth(); x++) {
        for (int y = 0; y < bi.getHeight(); y++) {
            if (x % step == 0 && y % step == 0) {
                Color pixel = new Color(bi.getRGB(x, y));
                sumr += pixel.getRed();
                sumg += pixel.getGreen();
                sumb += pixel.getBlue();
                sampled++;
            }
        }
    }
    int dim = bi.getWidth()*bi.getHeight();
    // Log.info("step=" + step + " sampled " + sampled + " out of " + dim + " pixels (" + String.format("%.1f", (float)(100*sampled/dim)) + " %)");
    return new Color(Math.round(sumr / sampled), Math.round(sumg / sampled), Math.round(sumb / sampled));
}


问:
Use TextField Controller but only need a text field?
I read the doc that states I need a TextFieldController to save state of child widgets that scroll off screen.

My problem is I using a Text widget ( totalbagels ) and it will not support controller. I do not need user to input text since I am providing + -  icon to increase and decrease quantity value and display that in Text widget totalbagels count..

I tried to replace Text widget with TextField which but I do not need text  input.

Any suggestions? Thanks.

Code:

```<code>class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: CounterWidget(),
    );
  }
}

class CounterWidget extends StatefulWidget {
  @override
  _CounterWidgetState createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  int _ecounter = 0;

  int _bakerdoz = 0;

  int _totalbagels = 0;

  void _incrementCounter() {
    setState(() {
      //track increment   ~/ finds just total bager doz of 13
      // %  check total for multiple of 13 and return single
      // non bakers doz totals back
      // TB = 16     BDz = 1   and Bagels = 3 for example...

      _totalbagels++;
      _bakerdoz = (_totalbagels ~/ 13);
      _ecounter = (_totalbagels % 13);
    });
  }

  void _decrementCounter() {
    setState(() {

      if (_totalbagels == 0) {

          // check if zero do not go into -1

      } else {
        _totalbagels--;
        _bakerdoz = (_totalbagels ~/ 13);
        _ecounter = (_totalbagels % 13);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Material(

      child: Row(
        children: [
          IconButton(
            icon: Icon(Icons.add_circle),
            color: Colors.black,
            iconSize: 25,
            onPressed: _incrementCounter,
          ),
          Text(
            '$_totalbagels',
            style: Theme.of(context).textTheme.headline4,
          ),
          IconButton(
            icon: Icon(Icons.remove_circle),
            color: Colors.black,
            iconSize: 25,
            onPressed: _decrementCounter,
          ),
          /* Row(
            children: [
              Text(
                'BDz:$_bakerdoz',
                style: Theme.of(context).textTheme.headline4,
              ),
              Text(
                ' TB=:$_totalbagels',
                style: Theme.of(context).textTheme.headline4,
              ),
            ],
          ), */
        ],
      ),
    );
  }
}
</code>```

答:
You dont need to use material widget inside Material App, because the pared widget extends this attributes to children.

Use expanded in one of the widgets inside row, to avoid rendering overflow problems.

There is an issue that have been lately when you set a function directly inside a button.

When using:

```<code>onPressed() => _yourFunction;
</code>```

Use instead:

```<code>onPressed(){
  yourFunction();
}
</code>```

This will prevent running the function when building the widgets, i dont know why this is happening in the new updates, and i noticed that happens just with buttons.

Set the data to a Text.

Or if you want to use TextFormField, there is no need to set controller, just use initialData attribute.

Body:
I read the doc that states I need a TextFieldController to save state of child widgets that scroll off screen.

My problem is I using a Text widget ( totalbagels ) and it will not support controller. I do not need user to input text since I am providing + -  icon to increase and decrease quantity value and display that in Text widget totalbagels count..

I tried to replace Text widget with TextField which but I do not need text  input.

Any suggestions? Thanks.

Code:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: CounterWidget(),
    );
  }
}

class CounterWidget extends StatefulWidget {
  @override
  _CounterWidgetState createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  int _ecounter = 0;

  int _bakerdoz = 0;

  int _totalbagels = 0;

  void _incrementCounter() {
    setState(() {
      //track increment   ~/ finds just total bager doz of 13
      // %  check total for multiple of 13 and return single
      // non bakers doz totals back
      // TB = 16     BDz = 1   and Bagels = 3 for example...

      _totalbagels++;
      _bakerdoz = (_totalbagels ~/ 13);
      _ecounter = (_totalbagels % 13);
    });
  }

  void _decrementCounter() {
    setState(() {

      if (_totalbagels == 0) {

          // check if zero do not go into -1

      } else {
        _totalbagels--;
        _bakerdoz = (_totalbagels ~/ 13);
        _ecounter = (_totalbagels % 13);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Material(

      child: Row(
        children: [
          IconButton(
            icon: Icon(Icons.add_circle),
            color: Colors.black,
            iconSize: 25,
            onPressed: _incrementCounter,
          ),
          Text(
            '$_totalbagels',
            style: Theme.of(context).textTheme.headline4,
          ),
          IconButton(
            icon: Icon(Icons.remove_circle),
            color: Colors.black,
            iconSize: 25,
            onPressed: _decrementCounter,
          ),
          /* Row(
            children: [
              Text(
                'BDz:$_bakerdoz',
                style: Theme.of(context).textTheme.headline4,
              ),
              Text(
                ' TB=:$_totalbagels',
                style: Theme.of(context).textTheme.headline4,
              ),
            ],
          ), */
        ],
      ),
    );
  }
}

Body:
You dont need to use material widget inside Material App, because the pared widget extends this attributes to children.

Use expanded in one of the widgets inside row, to avoid rendering overflow problems.

There is an issue that have been lately when you set a function directly inside a button.

When using:

onPressed() => _yourFunction;

Use instead:

onPressed(){
  yourFunction();
}

This will prevent running the function when building the widgets, i dont know why this is happening in the new updates, and i noticed that happens just with buttons.

Set the data to a Text.

Or if you want to use TextFormField, there is no need to set controller, just use initialData attribute.