问:
How to query rows grouped by matching string column but only count the most recent row for a specific set of keywords?
Have a single table of email events where each row is keyed with a specific outgoing email record fk and a specific recipient user fk. At any given time and in no specific order and even simultaneously from different threads I can have new records dropping into this table. Here are the relevant columns...

```<code>id (pk), email_id (fk), user_id (fk), event (string/name), created_at
</code>```

I am calculating the overall event counts for a given email, like how many emails were delivered, how many bounced, etc. However I need to ignore specific combinations of email events for a specific user because they become outdated when a newer event comes in. For example if a row says the email was 'deferred' for a specific user but then later a new event row is inserted that says 'delivered' or 'bounced' then I only want the most recently added row of any of those related keywords to be counted once as the current state.

What's a good way to do this at read time? I am having trouble because of the multiple layers of grouping that I need to do and reaching the limits of my SQL chops, here is the query I am trying to enhance as described:

```<code>select `event`, COUNT(1) as count, COUNT(DISTINCT user_id) as unique_count
from `email_activity`
where `email_id` = 7518
group by `event`
</code>```

For most of the events I want them all counted without any replacement so grouping by only event is fine in those cases, eg if something was a 'click' or 'open' event just total them up.

However, if there are any number of 'deferred', 'bounced', or 'delivered' events for the same email_id/user_id I only want to count the one with the most recent created_at date and ignore all the older ones.

Example row set (email_id, event, user_id, created_at):

```<code>7518, "click", 25, 1-20-2021
7518, "click", 73, 1-5-2021
7518, "bounced", 45, 1-19-2021
7518, "deferred", 45, 1-17-2021
7518, "delivered", 19, 1-1-2021
7518, "delivered", 25, 1-1-2021
7518, "delivered", 73, 1-1-2021
</code>```

So the queried count for email 7518 would be:

2 "click", 3 "delivered", and 1 "bounced" as the "deferred" row would be ignored for user 45 since it is older (only "bounced", "deferred", and "delivered" events are part of this "only count the latest" rule, all other event names are always counted).

答:
Solution 1:

If the WITH clause and the window functions are available, I prefer to divide the table into two parts, give a proper priority to each row, combine them by using UNION ALL, and finally aggregate only rows with the top priority.

WITH specific_email_activity AS (
    SELECT * FROM email_activity WHERE email_id = 7518
),
specific_email_activity_with_priority AS (
    SELECT
        *,
        1 AS rank_priority
    FROM
        specific_email_activity
    WHERE
        event NOT IN ('deferred', 'bounced', 'delivered')
    UNION ALL
    SELECT
        *,
        ROW_NUMBER () over (PARTITION BY email_id, user_id ORDER BY created_at DESC) AS rank_priority
    FROM
        specific_email_activity
    WHERE
        event IN ('deferred', 'bounced', 'delivered')
)
SELECT
    email_id,
    event,
    COUNT(*) AS count_event,
    COUNT(DISTINCT user_id) AS unique_count_event
FROM
    specific_email_activity_with_priority
WHERE
    rank_priority = 1
GROUP BY
    email_id,
    event
ORDER BY
    email_id,
    event;
```
<h2>Solution 2:</h2>
<p>If you can not use the <code>WITH</code> clause nor the window functions, then try the following code:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
    email_id,
    event,
    COUNT(*) AS count_event,
    COUNT(DISTINCT user_id) AS unique_count_event
FROM
    (
        SELECT
            *
        FROM
            email_activity
        WHERE
            email_id = 7518
            AND event NOT IN ('deferred', 'bounced', 'delivered')
        UNION ALL
        SELECT
            *
        FROM
            email_activity
        WHERE
            email_id = 7518
            AND event IN ('deferred', 'bounced', 'delivered')
            AND email_activity.created_at = (
                SELECT
                    MAX(created_at)
                FROM
                    email_activity AS ea
                WHERE
                    email_id = 7518
                    AND event IN ('deferred', 'bounced', 'delivered')
                    AND email_id = email_activity.email_id
                    AND user_id = email_activity.user_id
            )
    ) AS t
GROUP BY
    email_id,
    event
ORDER BY
    email_id,
    event;
</code>```

Output of solution 1 and 2:

email_id
event
count_event
unique_count_event

7518
bounced
1
1

7518
click
2
2

7518
delivered
3
3

Note:

If there are more than one row of the same user_id and the same created_at where their events are composed of a combination of 'deferred', 'bounced', or 'delivered’, you would get unexpected results. In that case, priority about which one of them should be counted must be clarified. Then, the code must be modified in accordance with that rule.

If event is nullable, it must be clarified how NULL is handled in aggregation. Then, the code must be modified in accordance with that rule.

Sample table creation:

The sample table can be created by the following sql:

CREATE TABLE IF NOT EXISTS email_activity(id SERIAL PRIMARY KEY, email_id INT, user_id INT, event VARCHAR(16), created_at DATE);
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(7518, 'click', 25, '2021-1-20');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(7518, 'click', 73, '2021-1-5');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(7518, 'bounced', 45, '2021-1-19');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(7518, 'deferred', 45, '2021-1-17');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(7518, 'delivered', 19, '2021-1-1');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(7518, 'delivered', 25, '2021-1-1');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(7518, 'delivered', 73,'2021-1-1');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(9999, 'click', 25, '2021-1-20');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(9999, 'click', 73, '2021-1-5');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(9999, 'bounced', 45, '2021-1-19');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(9999, 'deferred', 45, '2021-1-17');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(9999, 'delivered', 19, '2021-1-1');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(9999, 'delivered', 25, '2021-1-1');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(9999, 'delivered', 73,'2021-1-1');
```

Body:
Have a single table of email events where each row is keyed with a specific outgoing email record fk and a specific recipient user fk. At any given time and in no specific order and even simultaneously from different threads I can have new records dropping into this table. Here are the relevant columns...

id (pk), email_id (fk), user_id (fk), event (string/name), created_at

I am calculating the overall event counts for a given email, like how many emails were delivered, how many bounced, etc. However I need to ignore specific combinations of email events for a specific user because they become outdated when a newer event comes in. For example if a row says the email was 'deferred' for a specific user but then later a new event row is inserted that says 'delivered' or 'bounced' then I only want the most recently added row of any of those related keywords to be counted once as the current state.

What's a good way to do this at read time? I am having trouble because of the multiple layers of grouping that I need to do and reaching the limits of my SQL chops, here is the query I am trying to enhance as described:

select `event`, COUNT(1) as count, COUNT(DISTINCT user_id) as unique_count
from `email_activity`
where `email_id` = 7518
group by `event`

For most of the events I want them all counted without any replacement so grouping by only event is fine in those cases, eg if something was a 'click' or 'open' event just total them up.

However, if there are any number of 'deferred', 'bounced', or 'delivered' events for the same email_id/user_id I only want to count the one with the most recent created_at date and ignore all the older ones.

Example row set (email_id, event, user_id, created_at):

7518, "click", 25, 1-20-2021
7518, "click", 73, 1-5-2021
7518, "bounced", 45, 1-19-2021
7518, "deferred", 45, 1-17-2021
7518, "delivered", 19, 1-1-2021
7518, "delivered", 25, 1-1-2021
7518, "delivered", 73, 1-1-2021

So the queried count for email 7518 would be:

2 "click", 3 "delivered", and 1 "bounced" as the "deferred" row would be ignored for user 45 since it is older (only "bounced", "deferred", and "delivered" events are part of this "only count the latest" rule, all other event names are always counted).

Body:
Solution 1:

If the WITH clause and the window functions are available, I prefer to divide the table into two parts, give a proper priority to each row, combine them by using UNION ALL, and finally aggregate only rows with the top priority.

WITH specific_email_activity AS (
    SELECT * FROM email_activity WHERE email_id = 7518
),
specific_email_activity_with_priority AS (
    SELECT
        *,
        1 AS rank_priority
    FROM
        specific_email_activity
    WHERE
        event NOT IN ('deferred', 'bounced', 'delivered')
    UNION ALL
    SELECT
        *,
        ROW_NUMBER () over (PARTITION BY email_id, user_id ORDER BY created_at DESC) AS rank_priority
    FROM
        specific_email_activity
    WHERE
        event IN ('deferred', 'bounced', 'delivered')
)
SELECT
    email_id,
    event,
    COUNT(*) AS count_event,
    COUNT(DISTINCT user_id) AS unique_count_event
FROM
    specific_email_activity_with_priority
WHERE
    rank_priority = 1
GROUP BY
    email_id,
    event
ORDER BY
    email_id,
    event;

Solution 2:

If you can not use the WITH clause nor the window functions, then try the following code:

SELECT
    email_id,
    event,
    COUNT(*) AS count_event,
    COUNT(DISTINCT user_id) AS unique_count_event
FROM
    (
        SELECT
            *
        FROM
            email_activity
        WHERE
            email_id = 7518
            AND event NOT IN ('deferred', 'bounced', 'delivered')
        UNION ALL
        SELECT
            *
        FROM
            email_activity
        WHERE
            email_id = 7518
            AND event IN ('deferred', 'bounced', 'delivered')
            AND email_activity.created_at = (
                SELECT
                    MAX(created_at)
                FROM
                    email_activity AS ea
                WHERE
                    email_id = 7518
                    AND event IN ('deferred', 'bounced', 'delivered')
                    AND email_id = email_activity.email_id
                    AND user_id = email_activity.user_id
            )
    ) AS t
GROUP BY
    email_id,
    event
ORDER BY
    email_id,
    event;

Output of solution 1 and 2:

email_id
event
count_event
unique_count_event

7518
bounced
1
1

7518
click
2
2

7518
delivered
3
3

Note:

If there are more than one row of the same user_id and the same created_at where their events are composed of a combination of 'deferred', 'bounced', or 'delivered’, you would get unexpected results. In that case, priority about which one of them should be counted must be clarified. Then, the code must be modified in accordance with that rule.

If event is nullable, it must be clarified how NULL is handled in aggregation. Then, the code must be modified in accordance with that rule.

Sample table creation:

The sample table can be created by the following sql:

CREATE TABLE IF NOT EXISTS email_activity(id SERIAL PRIMARY KEY, email_id INT, user_id INT, event VARCHAR(16), created_at DATE);
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(7518, 'click', 25, '2021-1-20');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(7518, 'click', 73, '2021-1-5');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(7518, 'bounced', 45, '2021-1-19');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(7518, 'deferred', 45, '2021-1-17');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(7518, 'delivered', 19, '2021-1-1');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(7518, 'delivered', 25, '2021-1-1');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(7518, 'delivered', 73,'2021-1-1');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(9999, 'click', 25, '2021-1-20');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(9999, 'click', 73, '2021-1-5');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(9999, 'bounced', 45, '2021-1-19');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(9999, 'deferred', 45, '2021-1-17');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(9999, 'delivered', 19, '2021-1-1');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(9999, 'delivered', 25, '2021-1-1');
INSERT INTO email_activity(email_id, event, user_id, created_at) VALUES(9999, 'delivered', 73,'2021-1-1');


来源: stackexchange

问:
Global GOPRIVATE setting in Goland
Is there any way to have the Goland inherit the global environment for the go get command? We have lots of private packages and projects on a self-hosted git and we need to have them work with the same GOPRIVATE settings. Unfortunately Goland works with it's completely separated env vars for each project and I can't find any workarounds.

答: You can specify GOPRIVATE variable for GoLand globally via File | New Projects Setup | Preferences/Settings for New Projects | Go | Go modules | Environment.

ContentLicense: CC BY-SA 4.0

Title: Global GOPRIVATE setting in Goland


问:
Accessing vector of objects C++
Say I store a vector of objects. The object has an attribute such as int age which is private and we need to access it via getAge().

Lets say we call the object "people"

I store the object "people" in a vector...
soo...

```<code> vector<people> vectorOfPeople
</code>```

My question is...
Is it possible to directly access the 'age' via the vector vectorOfPeople?
Maybe something like vectorOfPeople[0].getAge() or something... (I know that doesn't work).

Thanks!

答:
Doing what you said should work:

```<code>// Make a vector of people
vector<people> pVec;
// Stick a people (person?) in it
pVec.push_back(people(someAge, someName)); // Or whatever constructor you have
// Show the age
cout << pVec[0].getAge(); // This should print out the age assigned in the c'tor
</code>```

The name you chose is a bit unintuitive in this case, but otherwise you should have no problems.

ContentLicense: CC BY-SA 3.0

Title: Accessing vector of objects C++

Body:
Say I store a vector of objects. The object has an attribute such as int age which is private and we need to access it via getAge().

Lets say we call the object "people"

I store the object "people" in a vector...
soo...

 vector<people> vectorOfPeople

My question is...
Is it possible to directly access the 'age' via the vector vectorOfPeople?
Maybe something like vectorOfPeople[0].getAge() or something... (I know that doesn't work).

Thanks!

Body:
Doing what you said should work:

// Make a vector of people
vector<people> pVec;
// Stick a people (person?) in it
pVec.push_back(people(someAge, someName)); // Or whatever constructor you have
// Show the age
cout << pVec[0].getAge(); // This should print out the age assigned in the c'tor

The name you chose is a bit unintuitive in this case, but otherwise you should have no problems.


问:
Which WordPress hook fires after save all post data and post meta?
I have a custom post type crm, and i need to send a mail after each crm saved or updated. i user cmb2 for some custom meta like subject, to users etc. I know the save_post hook fires after post save (according to WordPress codex) in my case when i call save_post with two parameters (id and post) the post does not contains update values. here is my code :

```<code>function send_mail_to_user($id, $post){
    $crm = $post;
    $user_email = array();
    if($crm->vc_all_vc == 'on'){
        $args = array('orderby' => 'display_name');
        $wp_user_query = new WP_User_Query($args);
        $authors = $wp_user_query->get_results();
        if (!empty($authors)) {
            foreach ($authors as $author) {
                array_push($user_email , $author->user_email );
            }
        }
    }
    else{
        $to_users = $crm->vc_users;
        $to_program = $crm->vc_program;
        $to_group = $crm->vc_group;
        $to_excode = $crm->vc_ex_code;
        foreach ($to_users as $key => $value) {
            $user_data = get_userdata($value);
            array_push($user_email, $user_data->user_email);
        }
        foreach ($to_program as $key => $value) {
            $users = get_users( array('meta_key'     => 'programs'  ) );
            if($users){
                foreach ($users as $index => $data) {
                    if(in_array($value , explode('#', $data->programs))){
                        if(! in_array($data->user_email, $user_email)  )
                        {
                            array_push($user_email, $data->user_email);
                        }
                    }
                }
            }
        }
        foreach($to_group as $group) {
            $term = get_term_by('slug', esc_attr($group), 'user-group');
            $user_ids = get_objects_in_term($term->term_id, 'user-group');
            foreach($user_ids as $user_id){
                $fc_user = get_userdata($user_id);
                if(! in_array($fc_user->user_email, $user_email)  )
                {
                    array_push($user_email, $fc_user->user_email);
                }
            }
        }
        foreach($to_excode as $codes) {
            $value = explode('*',$codes)[1];
            $users = get_users( array('meta_key'     => 'programs'  ) );
            if($users){
                foreach ($users as $index => $data) {
                    if(in_array($value , explode('#', $data->programs))){
                        if(! in_array($data->user_email, $user_email)  )
                        {
                            array_push($user_email, $data->user_email);
                        }
                    }
                }
            }
        }
    }
    foreach($user_email as $index => $email){
        $to      = $email;
        $subject = $crm->vc_subject;
        $body    = $crm->post_content;
        $headers = array(
        'Content-Type: text/html; charset=UTF-8'
        );
        wp_mail($to, $subject, $body, $headers);
    }
}

add_action( 'save_post', 'send_mail_to_user', 10, 2 );
</code>```

And i also try publish_post hook , that works fine when new post created but when updated it works same. I have tried edit_post and post_updated hook also, but i never be able to retrieve my update data.

So how can i solve it? which action hook will give me all the new data?
thanks in advance.

答:
The correct and simpler answer is to use the wp_insert_post action.

https://developer.wordpress.org/reference/hooks/wp_insert_post/

An important distinction of wp_insert_post action is that it is fired
after update_post_meta has been called.

There are 3 parameters available - the $update flag tells you if this is a new or updated post.

```<code>do_action( 'wp_insert_post', int $post_ID, WP_Post $post, bool $update )
</code>```

So - to implement your code after all post meta has been updated, use something like this:

```<code>add_action('wp_insert_post', 'run_after_post_updated', 10, 3);
function run_after_post_updated($post_ID, $post, $update ) {
   //  ...
}
</code>```

Body:
I have a custom post type crm, and i need to send a mail after each crm saved or updated. i user cmb2 for some custom meta like subject, to users etc. I know the save_post hook fires after post save (according to WordPress codex) in my case when i call save_post with two parameters (id and post) the post does not contains update values. here is my code :

function send_mail_to_user($id, $post){
    $crm = $post;
    $user_email = array();
    if($crm->vc_all_vc == 'on'){
        $args = array('orderby' => 'display_name');
        $wp_user_query = new WP_User_Query($args);
        $authors = $wp_user_query->get_results();
        if (!empty($authors)) {
            foreach ($authors as $author) {
                array_push($user_email , $author->user_email );
            }
        }
    }
    else{
        $to_users = $crm->vc_users;
        $to_program = $crm->vc_program;
        $to_group = $crm->vc_group;
        $to_excode = $crm->vc_ex_code;
        foreach ($to_users as $key => $value) {
            $user_data = get_userdata($value);
            array_push($user_email, $user_data->user_email);
        }
        foreach ($to_program as $key => $value) {
            $users = get_users( array('meta_key'     => 'programs'  ) );
            if($users){
                foreach ($users as $index => $data) {
                    if(in_array($value , explode('#', $data->programs))){
                        if(! in_array($data->user_email, $user_email)  )
                        {
                            array_push($user_email, $data->user_email);
                        }
                    }
                }
            }
        }
        foreach($to_group as $group) {
            $term = get_term_by('slug', esc_attr($group), 'user-group');
            $user_ids = get_objects_in_term($term->term_id, 'user-group');
            foreach($user_ids as $user_id){
                $fc_user = get_userdata($user_id);
                if(! in_array($fc_user->user_email, $user_email)  )
                {
                    array_push($user_email, $fc_user->user_email);
                }
            }
        }
        foreach($to_excode as $codes) {
            $value = explode('*',$codes)[1];
            $users = get_users( array('meta_key'     => 'programs'  ) );
            if($users){
                foreach ($users as $index => $data) {
                    if(in_array($value , explode('#', $data->programs))){
                        if(! in_array($data->user_email, $user_email)  )
                        {
                            array_push($user_email, $data->user_email);
                        }
                    }
                }
            }
        }
    }
    foreach($user_email as $index => $email){
        $to      = $email;
        $subject = $crm->vc_subject;
        $body    = $crm->post_content;
        $headers = array(
        'Content-Type: text/html; charset=UTF-8'
        );
        wp_mail($to, $subject, $body, $headers);
    }
}

add_action( 'save_post', 'send_mail_to_user', 10, 2 );

And i also try publish_post hook , that works fine when new post created but when updated it works same. I have tried edit_post and post_updated hook also, but i never be able to retrieve my update data.

So how can i solve it? which action hook will give me all the new data?
thanks in advance.

Body:
The correct and simpler answer is to use the wp_insert_post action.

https://developer.wordpress.org/reference/hooks/wp_insert_post/

An important distinction of wp_insert_post action is that it is fired
after update_post_meta has been called.

There are 3 parameters available - the $update flag tells you if this is a new or updated post.

do_action( 'wp_insert_post', int $post_ID, WP_Post $post, bool $update )

So - to implement your code after all post meta has been updated, use something like this:

add_action('wp_insert_post', 'run_after_post_updated', 10, 3);
function run_after_post_updated($post_ID, $post, $update ) {
   //  ...
}


问:
Why does my SQL Statement not SUM() up correctly?
I have the following statement:

```<code>SELECT
   ROUND(SUM(invoicetitle.unitpricegross*invoicetitle.suppliedquantity),2) as Costs,
   SUM(invoicetitle.suppliedquantity) AS Unitamounts
FROM invoicetitle
WHERE
  ((SELECT invoice.state
    FROM invoice where invoicetitle.invoiceid = invoice.invoiceid
     and (invoice.invoicedate >= 1609459200000 and invoice.invoicedate <= 1640908800000)) = (1 or 4))
GROUP BY invoicetitle.invoicetitle_number
</code>```

note that = (1 or 4) refers to two statements in the database where 1 is sold and 4 is a refund.

With = (1)) I get the following results:

Costs    -    Unitamounts
3.281,10  -    582

With = (4)) I get the following results:

Costs    -    Unitamounts
-115,2   -    -32

With = (1 or 4)) I get the following results:

Costs    -    Unitamounts
3.281,10  -    582

But I expect as a correct SUM() of it:

Costs    -    Unitamounts
3.165,9  -    550

What am I doing wrong that the results are not subtracted correctly?

答:
You probably meant to do:</p>
```<code>SELECT
   ROUND(SUM(invoicetitle.unitpricegross*invoicetitle.suppliedquantity),2) as Costs,
   SUM(invoicetitle.suppliedquantity) AS Unitamounts
FROM invoicetitle
INNER JOIN invoice ON invoicetitle.invoiceid = invoice.invoiceid
          and (invoice.invoicedate BETWEEN 1609459200000
                                      and  1640908800000)
WHERE invoice.state IN (1,4)
GROUP BY invoicetitle.invoicetitle_number
</code>```

Body:
I have the following statement:

SELECT
   ROUND(SUM(invoicetitle.unitpricegross*invoicetitle.suppliedquantity),2) as Costs,
   SUM(invoicetitle.suppliedquantity) AS Unitamounts
FROM invoicetitle
WHERE
  ((SELECT invoice.state
    FROM invoice where invoicetitle.invoiceid = invoice.invoiceid
     and (invoice.invoicedate >= 1609459200000 and invoice.invoicedate <= 1640908800000)) = (1 or 4))
GROUP BY invoicetitle.invoicetitle_number

note that = (1 or 4) refers to two statements in the database where 1 is sold and 4 is a refund.

With = (1)) I get the following results:

Costs    -    Unitamounts
3.281,10  -    582

With = (4)) I get the following results:

Costs    -    Unitamounts
-115,2   -    -32

With = (1 or 4)) I get the following results:

Costs    -    Unitamounts
3.281,10  -    582

But I expect as a correct SUM() of it:

Costs    -    Unitamounts
3.165,9  -    550

What am I doing wrong that the results are not subtracted correctly?

Body:
You probably meant to do:

SELECT
   ROUND(SUM(invoicetitle.unitpricegross*invoicetitle.suppliedquantity),2) as Costs,
   SUM(invoicetitle.suppliedquantity) AS Unitamounts
FROM invoicetitle
INNER JOIN invoice ON invoicetitle.invoiceid = invoice.invoiceid
          and (invoice.invoicedate BETWEEN 1609459200000
                                      and  1640908800000)
WHERE invoice.state IN (1,4)
GROUP BY invoicetitle.invoicetitle_number


问:
How to use libsrtp or similar library to decrypt/encrypt the WebRTC data stream?
I have a server which receives OFFER, ANSWER, CANDIDATE-s from web browser for a WebRTC session and passes to its peer. Later the data is also passed from the same server.

Now to implement our own SFU-like mechanism, I was considering, if this data I can decrypt to the actual raw bytes and then pass it to the multiple peers with their own encryption. For that I thought of using open source libsrtp library. Here is its example code.

It has primarily 2 functions srtp_protect() to encrtypt and srtp_unprotect() to decrypt.

Question: How to use such library in the conjunction of above WebRTC SDP headers (viz offer, answer, candidate) to get the raw RTP bytes & encrypt them again?

[Note: The other open source solutions like "MediaSoup", "Janus" etc. are not in scope of this post.]

答:
If you have the Offer, Answer and Candidates you have enough information to establish a WebRTC Session. Before you worry about encrypting/decrypting you need to establish ICE Connectivity

For ICE you need each Agents user-fragment and password. You exchange these values via Offer/Answer. I would start with ice-lite. You need to accept STUN Request packets, assert that the user-fragment is correct and it is signed with the password. You then respond with STUN Response with your user fragment and signed with your password. The IP/Port that is sending you traffic is the remote peer.

For C/C++ I would suggest libjuice or libnice. This is also something you could write yourself! Happy to add more details to my answer on either implementation if that is helpful.

Next you need to establish a DTLS Session. You need to know each sides role. In the Offer/Answer each side will declare either setup:active for Client, setup:passive for Server or setup:actpass if it defers the choice to the other side. When you know the details it is time to start the handshake.

See dtls.c for examples of making a DTLS Handshake, Extracting the keying material and more. The important part is setting your role properly, and setting up Read/Write BIOs. Since OpenSSL can't send over ICE you need to pass data in/out of OpenSSL yourself. Also make sure you validate the certificate fingerprint in the Offer/Answer!

When you are done you can send SCTP(DataChannels) over this DTLS connection.

If you want to do SRTP you need to Export the Keying material and then determine what cipher suite was used.

With this keying material + cipher suite. You create the session and then you can decrypt the packets

I am happy to add more examples/talk more specifically about certain APIs if that is helpful.


问:
Whats wrong with my Javascript Date Comparison
Im tyring to compare two dates in javascript but im getting strange values when calculating the dates.

Can anyone see anything obvious in my code that is causing the issue?

The problem is the Todays date variable looks like a normal date, but my calculation for next week and last week are coming out as large numbers and the comparison wont work.

```<code>//Handles client side date selection changed
function dateSelectionChanged(sender, args) {

    //Declare array for Day names
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    //Get the date
    var date = sender.get_selectedDate();

    //Get todays Date
    var today = new Date();
    var nextWeek = new Date().setDate(today.getDate() + 7);
    var lastWeek = new Date().setDate(today.getDate() - 7);

    //Show the day name
    $('#<%= txtDay.ClientID %>').val(days[date.getDay()]);

    if ( date < lastWeek ) {
        alert('Date Under Week');
    }
    if ( date > nextWeek ) {
        alert('Date Over Week');
    }
}
</code>```

And here is the Code in Debug so you can see the values:

EDIT:
Solution

```<code>//Handles client side date selection changed
function dateSelectionChanged(sender, args) {

    //Declare array for Day names
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    //Get the date
    var date = sender.get_selectedDate();

    //Get todays Date
    var today = new Date();
    var nextWeek = new Date().setDate(today.getDate() + 7);
    var lastWeek = new Date().setDate(today.getDate() - 7);

    //Get the dates in easier to compare format
    nextWeek = new Date(nextWeek);
    lastWeek = new Date(lastWeek);

    //Show the day name
    $('#<%= txtDay.ClientID %>').val(days[date.getDay()]);

    if ( date < lastWeek) {
        alert('Date Under Week');
    }
    if ( date > nextWeek) {
        alert('Date Over Week');
    }
}
</code>```

答:
For setDate, JavaScript returns timestamps, which represent the amount of milliseconds since 1 January 1970 00:00:00 to a specific moment in time. It might look useless, but in fact is very useful as you can represent any time as a simple number.

In case you want to get back a Date, you can use:

```<code>new Date(timestamp);
</code>```

so e.g. add:

```<code>nextWeek = new Date(nextWeek);
lastWeek = new Date(lastWeek);
</code>```

Body:
Im tyring to compare two dates in javascript but im getting strange values when calculating the dates.

Can anyone see anything obvious in my code that is causing the issue?

The problem is the Todays date variable looks like a normal date, but my calculation for next week and last week are coming out as large numbers and the comparison wont work.

//Handles client side date selection changed
function dateSelectionChanged(sender, args) {

    //Declare array for Day names
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    //Get the date
    var date = sender.get_selectedDate();

    //Get todays Date
    var today = new Date();
    var nextWeek = new Date().setDate(today.getDate() + 7);
    var lastWeek = new Date().setDate(today.getDate() - 7);

    //Show the day name
    $('#<%= txtDay.ClientID %>').val(days[date.getDay()]);

    if ( date < lastWeek ) {
        alert('Date Under Week');
    }
    if ( date > nextWeek ) {
        alert('Date Over Week');
    }
}

And here is the Code in Debug so you can see the values:

EDIT:
Solution

//Handles client side date selection changed
function dateSelectionChanged(sender, args) {

    //Declare array for Day names
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    //Get the date
    var date = sender.get_selectedDate();

    //Get todays Date
    var today = new Date();
    var nextWeek = new Date().setDate(today.getDate() + 7);
    var lastWeek = new Date().setDate(today.getDate() - 7);

    //Get the dates in easier to compare format
    nextWeek = new Date(nextWeek);
    lastWeek = new Date(lastWeek);

    //Show the day name
    $('#<%= txtDay.ClientID %>').val(days[date.getDay()]);

    if ( date < lastWeek) {
        alert('Date Under Week');
    }
    if ( date > nextWeek) {
        alert('Date Over Week');
    }
}

Body:
For setDate, JavaScript returns timestamps, which represent the amount of milliseconds since 1 January 1970 00:00:00 to a specific moment in time. It might look useless, but in fact is very useful as you can represent any time as a simple number.

In case you want to get back a Date, you can use:

new Date(timestamp);

so e.g. add:

nextWeek = new Date(nextWeek);
lastWeek = new Date(lastWeek);


问:
How to change used Dart version in Android Studio?
So I am trying to run this command in terminal

```<code>flutter pub run intl_translation:extract_to_arb --output-dir=lib/i18n lib/i18n/app_localization.dart
</code>```

and I get this error

```<code>Dart 2.15.1 is incompatible with your dependencies' SDK constraints. Please run "flutter pub get" again.
pub finished with exit code 65
</code>```

And I noticed that the used Dart version is 2.15.1 and not version 2.10.5 which is specified in the Android Studio project settings

How would I change the actually used Dart version to be able to run the intl_translation command ?

答: You can download the version you want from this link. https://dart.dev/get-dart/archive</p>

Body:
So I am trying to run this command in terminal

flutter pub run intl_translation:extract_to_arb --output-dir=lib/i18n lib/i18n/app_localization.dart

and I get this error

Dart 2.15.1 is incompatible with your dependencies' SDK constraints. Please run "flutter pub get" again.
pub finished with exit code 65

And I noticed that the used Dart version is 2.15.1 and not version 2.10.5 which is specified in the Android Studio project settings

How would I change the actually used Dart version to be able to run the intl_translation command ?


问:
async await calling function node.js
I have this function, that queries my database, and then calls getNumOfSessionForTrainerClientList function:

```<code>var select = "select * from USERS WHERE ASSIGNED_TRAINER = ?"
mysqlconn.connect(function(err) {
    if (err) {
        console.error('Database connection failed: ' + err.stack);
        return;
    }

    mysqlconn.query(select, [req.session.username], async function(err, rows) {
        if (err) {
            console.log(err);
        } else {

            let numOfSessionsLeft = {
                numberOfSessionsLeftIs: 0
            }
            for (var i = 0; i < rows.length; i++) {
                getNumOfSessionForTrainerClientList(req, res, rows[i], numOfSessionsLeft)
                rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs)
                console.log(numOfSessionsLeft)
            }

        }
        mysqlconn.end();

    })
})
</code>```

and then inside the function getNumOfSessionForTrainerClientList, I have this:

```<code>async function getNumOfSessionForTrainerClientList(req, res, rows, numOfSessionsLeft) {

var getNumOfSessionForTrainerClientList = "select * from SCHEDULE WHERE CLIENT_USERNAME = ? AND ASSIGNED_TRAINER = ?"
mysqlconn.connect(async function(err) {
    if (err) {
        console.error('Database connection failed: ' + err.stack);
        return;
    }
        mysqlconn.query(getNumOfSessionForTrainerClientList, [rows["USERNAME"], req.session.username], async function(err, sessionData) {
            if (err) {
                console.log(err);
            } else {
                numOfSessionsLeft.numberOfSessionsLeftIs = 1;
                console.log(numOfSessionsLeft.numberOfSessionsLeftIs)

            }

        })

})

}
</code>```

however, what is happening is that this line : rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs) is actually assigning 0 to rows[i]["NUM_OF_SESSIONS_PER_MONTH"] because that variable assignment is happening before the function call for getNumOfSessionForTrainerClientList finishes. So it is happening out of sync. I am not sure how to fix this, i have run into issues with async await before, but nothing like this. would appreciate the help.

答:
For loop is synchronous in nature and hence doesn't wait for your method getNumOfSessionForTrainerClientList to return to continue the iteration.

The right way to do is:

Put your code inside an async block and use await() while calling getNumOfSessionForTrainerClientList call.

Second, your function getNumOfSessionForTrainerClientList should
return a promise.

Sample:

```<code>async function functionA() {
    var select = "select * from USERS WHERE ASSIGNED_TRAINER = ?"
    mysqlconn.connect(function(err) {
        if (err) {
            console.error('Database connection failed: ' + err.stack);
            return;
        }

        mysqlconn.query(select, [req.session.username], async function(err, rows) {
            if (err) {
                console.log(err);
            } else {

                let numOfSessionsLeft = {
                    numberOfSessionsLeftIs: 0
                }
                for (var i = 0; i < rows.length; i++) {
                    await getNumOfSessionForTrainerClientList(req, res, rows[i], numOfSessionsLeft)
                    rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs)
                    console.log(numOfSessionsLeft)
                }
            }
            mysqlconn.end();
        })
    })
}
</code>```

And your function getNumOfSessionForTrainerClientList should look like:

```<code>async function getNumOfSessionForTrainerClientList(req, res, rows, numOfSessionsLeft) {

    return new Promise((resolve, reject) => {

        var getNumOfSessionForTrainerClientList = "select * from SCHEDULE WHERE CLIENT_USERNAME = ? AND ASSIGNED_TRAINER = ?"
        mysqlconn.connect(async function(err) {
            if (err) {
                console.error('Database connection failed: ' + err.stack);
                return reject(err);
            }
                mysqlconn.query(getNumOfSessionForTrainerClientList, [rows["USERNAME"], req.session.username], async function(err, sessionData) {
                    if (err) {
                        console.log(err);
                        return reject(err);
                    } else {
                        numOfSessionsLeft.numberOfSessionsLeftIs = 1;
                        console.log(numOfSessionsLeft.numberOfSessionsLeftIs)
                        return resolve();

                    }
                })

        })
    })

}
</code>```

And then call functionA() with whatever params you need to.

Title: async await calling function node.js

Body:
I have this function, that queries my database, and then calls getNumOfSessionForTrainerClientList function:

var select = "select * from USERS WHERE ASSIGNED_TRAINER = ?"
mysqlconn.connect(function(err) {
    if (err) {
        console.error('Database connection failed: ' + err.stack);
        return;
    }

    mysqlconn.query(select, [req.session.username], async function(err, rows) {
        if (err) {
            console.log(err);
        } else {

            let numOfSessionsLeft = {
                numberOfSessionsLeftIs: 0
            }
            for (var i = 0; i < rows.length; i++) {
                getNumOfSessionForTrainerClientList(req, res, rows[i], numOfSessionsLeft)
                rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs)
                console.log(numOfSessionsLeft)
            }

        }
        mysqlconn.end();

    })
})

and then inside the function getNumOfSessionForTrainerClientList, I have this:

async function getNumOfSessionForTrainerClientList(req, res, rows, numOfSessionsLeft) {

var getNumOfSessionForTrainerClientList = "select * from SCHEDULE WHERE CLIENT_USERNAME = ? AND ASSIGNED_TRAINER = ?"
mysqlconn.connect(async function(err) {
    if (err) {
        console.error('Database connection failed: ' + err.stack);
        return;
    }
        mysqlconn.query(getNumOfSessionForTrainerClientList, [rows["USERNAME"], req.session.username], async function(err, sessionData) {
            if (err) {
                console.log(err);
            } else {
                numOfSessionsLeft.numberOfSessionsLeftIs = 1;
                console.log(numOfSessionsLeft.numberOfSessionsLeftIs)

            }

        })

})

}

however, what is happening is that this line : rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs) is actually assigning 0 to rows[i]["NUM_OF_SESSIONS_PER_MONTH"] because that variable assignment is happening before the function call for getNumOfSessionForTrainerClientList finishes. So it is happening out of sync. I am not sure how to fix this, i have run into issues with async await before, but nothing like this. would appreciate the help.

Body:
For loop is synchronous in nature and hence doesn't wait for your method getNumOfSessionForTrainerClientList to return to continue the iteration.

The right way to do is:

Put your code inside an async block and use await() while calling getNumOfSessionForTrainerClientList call.

Second, your function getNumOfSessionForTrainerClientList should
return a promise.

Sample:

async function functionA() {
    var select = "select * from USERS WHERE ASSIGNED_TRAINER = ?"
    mysqlconn.connect(function(err) {
        if (err) {
            console.error('Database connection failed: ' + err.stack);
            return;
        }

        mysqlconn.query(select, [req.session.username], async function(err, rows) {
            if (err) {
                console.log(err);
            } else {

                let numOfSessionsLeft = {
                    numberOfSessionsLeftIs: 0
                }
                for (var i = 0; i < rows.length; i++) {
                    await getNumOfSessionForTrainerClientList(req, res, rows[i], numOfSessionsLeft)
                    rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs)
                    console.log(numOfSessionsLeft)
                }
            }
            mysqlconn.end();
        })
    })
}

And your function getNumOfSessionForTrainerClientList should look like:

async function getNumOfSessionForTrainerClientList(req, res, rows, numOfSessionsLeft) {

    return new Promise((resolve, reject) => {

        var getNumOfSessionForTrainerClientList = "select * from SCHEDULE WHERE CLIENT_USERNAME = ? AND ASSIGNED_TRAINER = ?"
        mysqlconn.connect(async function(err) {
            if (err) {
                console.error('Database connection failed: ' + err.stack);
                return reject(err);
            }
                mysqlconn.query(getNumOfSessionForTrainerClientList, [rows["USERNAME"], req.session.username], async function(err, sessionData) {
                    if (err) {
                        console.log(err);
                        return reject(err);
                    } else {
                        numOfSessionsLeft.numberOfSessionsLeftIs = 1;
                        console.log(numOfSessionsLeft.numberOfSessionsLeftIs)
                        return resolve();

                    }
                })

        })
    })

}

And then call functionA() with whatever params you need to.


问:
Using spring converter in @RequestBody
Is it possible to enforce Converter ( org.springframework.core.convert.converter.Converter) to finish json object mapping?

Json code example:

```<code>{
 "name": "somename",
 "customObject": id
}
</code>```

where somename - string, id - integer value

mapping to :

```<code>@Getter
@Setter
@NoArgConstructor
public class ParentObject{
    private String name;
    private CustomObject customObject;
}
</code>```

Converter code example:

```<code>@Component
public class CustomObjectConverter implements Converter<String, CustomObject>{

    @Autowired
    private CustomObjectService customObjectService;

    @Override
    public CustomObject convert(String arg0) {
        Long id = Long.parseLong(arg0);
        return customObjectService.findById(id);
    }
}
</code>```

What I want to achieve is to map that json to the object which will have automatically fetched from db nested object.

答:
I think there is a better way to solve this problem.
All you need is to add one more implementation:

```<code>com.fasterxml.jackson.databind.util.Converter
</code>```

And put an annotation over your object:

```<code>import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
...
@JsonDeserialize(converter = CustomObjectConverter.class)
private CustomObject customObject;
</code>```

As a result, your code will look like this.
Model:

```<code>@Getter
@Setter
@NoArgConstructor
public class ParentObject{
   private String name;

   @JsonDeserialize(converter = CustomObjectConverter.class)
   private CustomObject customObject;
}
</code>```

Converter:

```<code>@Component
public class CustomObjectConverter implements
  org.springframework.core.convert.converter.Converter<String, CustomObject>,
  com.fasterxml.jackson.databind.util.Converter<String, CustomObject>{

   @Autowired
   private CustomObjectService customObjectService;

   @Override
   public CustomObject convert(String arg0) {
       Long id = Long.parseLong(arg0);
       return customObjectService.findById(id);
   }

   @Override
   public JavaType getInputType(TypeFactory typeFactory) {
       return typeFactory.constructType(String.class);
   }

   @Override
   public JavaType getOutputType(TypeFactory typeFactory) {
       return typeFactory.constructType(CustomObject.class);
   }
}
</code>```

Title: Using spring converter in @RequestBody

Body:
Is it possible to enforce Converter ( org.springframework.core.convert.converter.Converter) to finish json object mapping?

Json code example:

{
 "name": "somename",
 "customObject": id
}

where somename - string, id - integer value

mapping to :

@Getter
@Setter
@NoArgConstructor
public class ParentObject{
    private String name;
    private CustomObject customObject;
}

Converter code example:

@Component
public class CustomObjectConverter implements Converter<String, CustomObject>{

    @Autowired
    private CustomObjectService customObjectService;

    @Override
    public CustomObject convert(String arg0) {
        Long id = Long.parseLong(arg0);
        return customObjectService.findById(id);
    }
}

What I want to achieve is to map that json to the object which will have automatically fetched from db nested object.

Body:
I think there is a better way to solve this problem.
All you need is to add one more implementation:

com.fasterxml.jackson.databind.util.Converter

And put an annotation over your object:

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
...
@JsonDeserialize(converter = CustomObjectConverter.class)
private CustomObject customObject;

As a result, your code will look like this.
Model:

@Getter
@Setter
@NoArgConstructor
public class ParentObject{
   private String name;

   @JsonDeserialize(converter = CustomObjectConverter.class)
   private CustomObject customObject;
}

Converter:

@Component
public class CustomObjectConverter implements
  org.springframework.core.convert.converter.Converter<String, CustomObject>,
  com.fasterxml.jackson.databind.util.Converter<String, CustomObject>{

   @Autowired
   private CustomObjectService customObjectService;

   @Override
   public CustomObject convert(String arg0) {
       Long id = Long.parseLong(arg0);
       return customObjectService.findById(id);
   }

   @Override
   public JavaType getInputType(TypeFactory typeFactory) {
       return typeFactory.constructType(String.class);
   }

   @Override
   public JavaType getOutputType(TypeFactory typeFactory) {
       return typeFactory.constructType(CustomObject.class);
   }
}


问:
updating dns CNAME
I'm trying to update a bunch of dns cname entry, using azure-powershell.

I have no troubles getting the dns entry I need to update, but my problem starts when trying to update the cname (due to the fact there can be only one cname entry).

I went to azure documentation, and found about set-azdnsrecordset, but I failed to find the correct parameter/syntax to update the CNAME

Here is what I tried.

```<code>$rs = Get-AzDnsRecordSet -name "test1" -RecordType CNAME -ZoneName "zone.io" -ResourceGroupName "dns"
$rs.Records[0].Records = "new-test-v1.com"
Set-AzDnsRecordSet -RecordSet $rs
</code>```

With error on $rs.Records[0].Records = "new-test-v1.com":

```<code>The property 'Records' cannot be found on this object. Verify that the property exists and can be set.
</code>```

echo $rs

```<code>Id                : /subscriptions/[redacted]/resourceGroups/[redacted]/providers/Microsoft.Network/dnszones/[redacted].io/CNAME/test1
Name              : test1
ZoneName          : zone.io
ResourceGroupName : dns
Ttl               : 3600
Etag              : [redacted]
RecordType        : CNAME
TargetResourceId  :
Records           : {test-v1.com}
Metadata          :
ProvisioningState : Succeeded
</code>```

PS : I did found a working solution. Deleting/recreating the records works fine enough. I also realise that if something goes wrong in the creation segment, I lose my record (setting failsafe would be a lot of additional work), So I keep it as a last ressort.

答:
Climbing on AjayKumarGhose-MT shoulders (mention of -Cname $rs.Records.cname) , I did found the solution
I needed to use

```<code>$rs.Records[0].cname = "new-test-v1.com"
</code>```

instead of

```<code>$rs.Records[0].Records = "new-test-v1.com"
</code>```

Full solution is then :

```<code>$rs = Get-AzDnsRecordSet -name "test1" -RecordType CNAME -ZoneName "zone.io" -ResourceGroupName "dns"
$rs.Records[0].Records = "new-test-v1.com"
Set-AzDnsRecordSet -RecordSet $rs
</code>```

Title: updating dns CNAME

Body:
I'm trying to update a bunch of dns cname entry, using azure-powershell.

I have no troubles getting the dns entry I need to update, but my problem starts when trying to update the cname (due to the fact there can be only one cname entry).

I went to azure documentation, and found about set-azdnsrecordset, but I failed to find the correct parameter/syntax to update the CNAME

Here is what I tried.

$rs = Get-AzDnsRecordSet -name "test1" -RecordType CNAME -ZoneName "zone.io" -ResourceGroupName "dns"
$rs.Records[0].Records = "new-test-v1.com"
Set-AzDnsRecordSet -RecordSet $rs

With error on $rs.Records[0].Records = "new-test-v1.com":

The property 'Records' cannot be found on this object. Verify that the property exists and can be set.

echo $rs

Id                : /subscriptions/[redacted]/resourceGroups/[redacted]/providers/Microsoft.Network/dnszones/[redacted].io/CNAME/test1
Name              : test1
ZoneName          : zone.io
ResourceGroupName : dns
Ttl               : 3600
Etag              : [redacted]
RecordType        : CNAME
TargetResourceId  :
Records           : {test-v1.com}
Metadata          :
ProvisioningState : Succeeded

PS : I did found a working solution. Deleting/recreating the records works fine enough. I also realise that if something goes wrong in the creation segment, I lose my record (setting failsafe would be a lot of additional work), So I keep it as a last ressort.

Body:
Climbing on AjayKumarGhose-MT shoulders (mention of -Cname $rs.Records.cname) , I did found the solution
I needed to use

$rs.Records[0].cname = "new-test-v1.com"

instead of

$rs.Records[0].Records = "new-test-v1.com"

Full solution is then :

$rs = Get-AzDnsRecordSet -name "test1" -RecordType CNAME -ZoneName "zone.io" -ResourceGroupName "dns"
$rs.Records[0].Records = "new-test-v1.com"
Set-AzDnsRecordSet -RecordSet $rs


问:
How to implement lookup/reference data in apache tinkerpop gremlin or graph database?
How to implement lookup/reference data in a gremlin or graph database?

I need to collect all types of identification,

```<code>1. Diving license,
2. Social security number,
3....
</code>```

For UI, I need to send the "identification_type" list (above list).

&

What is the best way to implement this? Create an edge b/w type and actual value? or type as a property?

答: The model mostly depends on your required queries. Will you be looking at persons who share the same SSN or driving license (Lots of fraud detection work that way), then use an edge to a node with a value. If you don't care about users who have the same identification values, then simply use node properties.</p>

Body:
How to implement lookup/reference data in a gremlin or graph database?

I need to collect all types of identification,

1. Diving license,
2. Social security number,
3....

For UI, I need to send the "identification_type" list (above list).

&

What is the best way to implement this? Create an edge b/w type and actual value? or type as a property?


问:
Undefined behavior of printf in C?
What should be the output of a single percent sign?

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

void main()
{
    printf("%");
}
</code>```

"Unknown format code" is not like "Unknown escape sequence".

答:
% is used to signal that you want to print a variable e.g.

```<code>int i = 10;
printf("%d", i); //prints 10
</code>```

In order to just print the '%' sign you must escape it as

printf("%%");

Title: Undefined behavior of printf in C?

Body:
What should be the output of a single percent sign?

#include <stdio.h>

void main()
{
    printf("%");
}

"Unknown format code" is not like "Unknown escape sequence".

Body:
% is used to signal that you want to print a variable e.g.

int i = 10;
printf("%d", i); //prints 10

In order to just print the '%' sign you must escape it as

printf("%%");


问:
"lvalue required as left operand of assignment" for all of my if/else statements. What have I done wrong?
I'm making a basic calculator that uses if/else statements to select a sign to use in the equation. All of the else/if statements are reporting an error:

error: lvalue required as left operand of assignment

```<code>#include <iostream>
using namespace std;

int main()
{
    //declare variables

    int num1;
    int num2;
    int sol;
    bool sign;

    //prompt for num1
    cout << "Greetings! Please enter a number." << endl;
    cin >> num1;

    //prompt for num2
    cout << "Great! Now, please enter the second number." << endl;
    cin >> num2;

    //prompt for sign
    cout << "Almost there! Now, please enter the sign you wish to use in the equation." << endl;
    cin >> sign;

    //arguments
    if (sign == '+')
    {
        num1 + num2 = sol;
    }
    else if (sign == '-')
    {
        num1 - num2 = sol;
    }
    else if (sign == '*')
    {
        num1 * num2 = sol;
    }
    else if (sign == '/')
    {
        num1 / num2 = sol;
    }
    else
    {
        cout << "Sorry, that is not a valid symbol." << endl;
        return 0;
    }

    //print results
    cout << "The solution is: " << sol << endl;
    return 0;
}
</code>```

答:
You have your assignments reversed. = is not a commutative operator.

They should all be of the form

```<code>sol = num1 op num2
</code>```

What you are trying to do is assign the (uninitialised) value of sol to the unnamed temporary that results from the calculation. Happily this is a hard error with fundamental types.

Body:
I'm making a basic calculator that uses if/else statements to select a sign to use in the equation. All of the else/if statements are reporting an error:

error: lvalue required as left operand of assignment

#include <iostream>
using namespace std;

int main()
{
    //declare variables

    int num1;
    int num2;
    int sol;
    bool sign;

    //prompt for num1
    cout << "Greetings! Please enter a number." << endl;
    cin >> num1;

    //prompt for num2
    cout << "Great! Now, please enter the second number." << endl;
    cin >> num2;

    //prompt for sign
    cout << "Almost there! Now, please enter the sign you wish to use in the equation." << endl;
    cin >> sign;

    //arguments
    if (sign == '+')
    {
        num1 + num2 = sol;
    }
    else if (sign == '-')
    {
        num1 - num2 = sol;
    }
    else if (sign == '*')
    {
        num1 * num2 = sol;
    }
    else if (sign == '/')
    {
        num1 / num2 = sol;
    }
    else
    {
        cout << "Sorry, that is not a valid symbol." << endl;
        return 0;
    }

    //print results
    cout << "The solution is: " << sol << endl;
    return 0;
}

Body:
You have your assignments reversed. = is not a commutative operator.

They should all be of the form

sol = num1 op num2

What you are trying to do is assign the (uninitialised) value of sol to the unnamed temporary that results from the calculation. Happily this is a hard error with fundamental types.


问:
Is there any better solution then passing prop up to the parent component?
I am in situation that I need to use state from one component as a dependency value in another's componet useEffect hook. Easy illustration of this situation is in attached image.

I know that I can pass state from first component up to the parent component, in this case the App component, and then the state from parent component (App) pass down to the second component as a prop. But is there any better solution?

Thank you for your help.

答: you could either lift the state up to the parent component using a func for example and pass it down to component2, or use a state management library, depending on the scale of your app, smaller - medium scale I would use React context-API or redux since its widely used and easy to master</p>


问:
JavaScript: SyntaxError: missing ) after argument list
I am getting the error:

SyntaxError: missing ) after argument list

With this javascript:

```<code>var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
    nav[i].addEventListener('click',function(){
            console.log('haha');
        }
    }, false);
};
</code>```

What does this error mean?

答:
This error maybe is the version of your Android (especially if you are using Web Views), try to change your code like an old version of the JavaScript Engine, like:</p>
```<code>   .then(function(canvas){
            //canvas object can gained here
   });
</code>```

Body:
I am getting the error:

SyntaxError: missing ) after argument list

With this javascript:

var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
    nav[i].addEventListener('click',function(){
            console.log('haha');
        }
    }, false);
};

What does this error mean?

Body:
This error maybe is the version of your Android (especially if you are using Web Views), try to change your code like an old version of the JavaScript Engine, like:

   .then(function(canvas){
            //canvas object can gained here
   });


问:
How to do N-Point circular convolution for 1D signal with numpy?
I want a circular convolution function where I can set the number N as I like.

All examples I looked at like here and here assume that full padding is required but that not what I want.

I want to have the result for different values of N

so input would N and and two different arrays of values

the output should be the N point convolved signal

Here is the formula for circular convolution. Sub N can be seen as the modulo operation.

taken from this basic introduction

update for possible solution

This answer is a suitable solution when the array a is piled accordingly to the different cases of N.

When I find time I will post a complete answer, meanwhile feel free to do so.

Thanks to @André pointing this out in the comments!

examples for input/output from here

N = 4

N = 7 with zero padding

答:
I think that this should work:

```<code>def conv(x1, x2, N):
    n, m = np.ogrid[:N, :N]
    return (x1[:N] * x2[(n - m) % N]).sum(axis=1)
</code>```

This is a direct translation of the formula posted in the question:

To implement this formula, first we compute an array of indices used by x₂. This is done using the code

```<code>n, m = np.ogrid[:N, :N]
indices = (n - m) % N
</code>```

For example, for N=5, the array indices is:

```<code>[[0 4 3 2 1]
 [1 0 4 3 2]
 [2 1 0 4 3]
 [3 2 1 0 4]
 [4 3 2 1 0]]
</code>```

The entry in the i-th row and j-th column is (i-j) % N. Then,
x2[indices] creates an array consisting of elements of x2 corresponding to these indices. It remains to multiply each row of this array by the first N elements of x1 and take the sum of each row:

```<code>(x1[:N] * x2[indices]).sum(axis=1)
</code>```

Body:
I think that this should work:

def conv(x1, x2, N):
    n, m = np.ogrid[:N, :N]
    return (x1[:N] * x2[(n - m) % N]).sum(axis=1)

This is a direct translation of the formula posted in the question:

To implement this formula, first we compute an array of indices used by x₂. This is done using the code

n, m = np.ogrid[:N, :N]
indices = (n - m) % N

For example, for N=5, the array indices is:

[[0 4 3 2 1]
 [1 0 4 3 2]
 [2 1 0 4 3]
 [3 2 1 0 4]
 [4 3 2 1 0]]

The entry in the i-th row and j-th column is (i-j) % N. Then,
x2[indices] creates an array consisting of elements of x2 corresponding to these indices. It remains to multiply each row of this array by the first N elements of x1 and take the sum of each row:

(x1[:N] * x2[indices]).sum(axis=1)


问:
Firebase Pubsub Schedule Job can't run result is: "UNAUTHENTICATED"
I'm trying to realise a leaderboard for my App which should rewrite every 24h, but I can't get it to work... The job doesn't even start.

This is all I found about the function, but it doesn't help me.
https://firebase.google.com/docs/functions/schedule-functions

And this is my function:

```<code>exports.leaderboardjob = functions.region('europe-west1').pubsub.schedule( '0 0 * * *').onRun(async (context) => {
    await leaderboard();
    console.log("job done");
    return null;
});

async function leaderboard(){

    const rdb = admin.firestore();

    const ref = rdb.ref('users');

    try {
        await ref.orderByChild('xp').limitToLast(2).on('child_added', (snapshot) => { //test first with 2 results
            console.log(snapshot.key);
        });

    } catch (error) {
         console.log('error: ' + error.message);
    }

    return{
        result: ok
    }
}
</code>```

I already moved the function to my region europe-west1 like all my other functions.

error that I get back when I call this function (leaderboardjob) manually:

```<code>{"@type":"type.googleapis.com/google.cloud.scheduler.logging.AttemptFinished", "jobName":"projects/censored/locations/europe-west1/jobs/firebase-schedule-leaderboardjob-europe-west1", "pubsubTopic":"projects/censored/topics/firebase-schedule-leaderboardjob-europe-west1", "status":"UNAUTHENTICATED", "targetType":"PUB_SUB"}
</code>```

Maybe its just not possible, if not: can someone explain me how to realise something like this with functions?

EDIT: I forgot to tell, that I gave the function the role with a new account "pubsub.subscriber"

答:
I just deleted the whole function and tested it with a new name.

I don't know why, but this worked...

You don't even need to add a role. Everything works just fine.

Body:
I'm trying to realise a leaderboard for my App which should rewrite every 24h, but I can't get it to work... The job doesn't even start.

This is all I found about the function, but it doesn't help me.
https://firebase.google.com/docs/functions/schedule-functions

And this is my function:

exports.leaderboardjob = functions.region('europe-west1').pubsub.schedule( '0 0 * * *').onRun(async (context) => {
    await leaderboard();
    console.log("job done");
    return null;
});

async function leaderboard(){

    const rdb = admin.firestore();

    const ref = rdb.ref('users');

    try {
        await ref.orderByChild('xp').limitToLast(2).on('child_added', (snapshot) => { //test first with 2 results
            console.log(snapshot.key);
        });

    } catch (error) {
         console.log('error: ' + error.message);
    }

    return{
        result: ok
    }
}

I already moved the function to my region europe-west1 like all my other functions.

error that I get back when I call this function (leaderboardjob) manually:

{"@type":"type.googleapis.com/google.cloud.scheduler.logging.AttemptFinished", "jobName":"projects/censored/locations/europe-west1/jobs/firebase-schedule-leaderboardjob-europe-west1", "pubsubTopic":"projects/censored/topics/firebase-schedule-leaderboardjob-europe-west1", "status":"UNAUTHENTICATED", "targetType":"PUB_SUB"}

Maybe its just not possible, if not: can someone explain me how to realise something like this with functions?

EDIT: I forgot to tell, that I gave the function the role with a new account "pubsub.subscriber"


问:
Selenium-chromedriver: Cannot construct KeyEvent from non-typeable key
I updated my Chrome and Chromedriver to the latest version yesterday, and since then I get the following error messages when running my Cucumber features:

```<code>....
unknown error: Cannot construct KeyEvent from non-typeable key
        (Session info: chrome=98.0.4758.80) (Selenium::WebDriver::Error::UnknownError)
      #0 0x55e9ce6a4093 <unknown>
      #1 0x55e9ce16a648 <unknown>
      #2 0x55e9ce1a9866 <unknown>
      #3 0x55e9ce1cbd29 <unknown>
      .....
</code>```

I try to fill a text field with Capybara's fill_in method. While debugging I noticed that Capybara has problems especially with the symbols @ and \. Every other character can be written into the text field without any problems.

The code that triggers the error looks like this

```<code>def sign_in(user)
  visit new_sign_in_path
  fill_in 'Email', with: user.email
  fill_in 'Password', with: user.password
  click_button 'Sign in'
end
</code>```

user.email contains a string like "example1@mail.com".

I work with Rails 6.1.3.1, Cucumber 5.3.0, Chromedriver 98.0.4758.48, capybara 3.35.3

The error only occurs on features that are tagged with @javascript

Do you have any ideas what causes this error or how to fix it?

答: I was getting the same error for python. If Google chrome automatically updated to version 98 don't update your chromedriver to 98 also, use 97 instead. This solved my issue.</p>

Body:
I updated my Chrome and Chromedriver to the latest version yesterday, and since then I get the following error messages when running my Cucumber features:

....
unknown error: Cannot construct KeyEvent from non-typeable key
        (Session info: chrome=98.0.4758.80) (Selenium::WebDriver::Error::UnknownError)
      #0 0x55e9ce6a4093 <unknown>
      #1 0x55e9ce16a648 <unknown>
      #2 0x55e9ce1a9866 <unknown>
      #3 0x55e9ce1cbd29 <unknown>
      .....

I try to fill a text field with Capybara's fill_in method. While debugging I noticed that Capybara has problems especially with the symbols @ and \. Every other character can be written into the text field without any problems.

The code that triggers the error looks like this

def sign_in(user)
  visit new_sign_in_path
  fill_in 'Email', with: user.email
  fill_in 'Password', with: user.password
  click_button 'Sign in'
end

user.email contains a string like "example1@mail.com".

I work with Rails 6.1.3.1, Cucumber 5.3.0, Chromedriver 98.0.4758.48, capybara 3.35.3

The error only occurs on features that are tagged with @javascript

Do you have any ideas what causes this error or how to fix it?


问:
asyncTask and progressDialog : Freeze
please see my code .. and if you can, tell me why my progressDialog stopped when the function is halfway done in the background, the screen hangs (nothing is displayed, the logcat shows all logs i put in the background function).

Then, right before the end, the progressDialog starts animating again and closes after a couple seconds (the function is finished and the result is displayed normally)

```<code>public class changeWall extends AsyncTask<Integer, Integer, Integer> {
        protected Integer doInBackground(Integer... urls) {
            int totalSize=0;
            try {

                 if(s.loadBoolean() == false)
                {
                     log("IF = false");
                     log("tempLogin = "+tempLogin);
                     log("tempPassword = "+tempPassword);
                     getNewResponse(tempLogin,tempPassword);
                if(needSave)
                {
                 s.saveBoolean(true);
                }

                }
                 else
                 {
                if(s.loadLogin()==null)
                {
                   getNewResponse(tempLogin,tempPassword);
                }else
                {
                    getNewResponse(s.loadLogin(),s.loadPassowrd());
                }
                 }
                parser.setLol(0);

                parser.startParse(RESULT_STRING);

             log("end parse");
            } catch (ClientProtocolException e) {
                log("internet connection lost");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log(" connection lost");
            }
            log("count = "+parser.getFacebookId(1));
            publishProgress();
            totalSize=1;
            log("end of start");
            return totalSize;
        }

        protected void onProgressUpdate(Integer... progress) {
            log("wall click ON PROGRESS UPDATE");
            wall.setBackgroundResource(R.drawable.tabbuttonon);
            messages.setBackgroundResource(0);
            activity.setBackgroundResource(0);
            profile.setBackgroundResource(0);
            l1_1.setBackgroundResource(R.drawable.tabbuttononleft);
            l1_2.setBackgroundResource(R.drawable.tabbuttononright);
            l2_1.setBackgroundResource(0);
            l2_2.setBackgroundResource(0);
            l3_1.setBackgroundResource(0);
            l3_2.setBackgroundResource(0);
            l4_2.setBackgroundResource(0);
            l4_2.setBackgroundResource(0);
            wall.setTextColor(Color.BLACK);
            messages.setTextColor(Color.WHITE);
            profile.setTextColor(Color.WHITE);
            activity.setTextColor(Color.WHITE);

            try {
                loadWall();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
               wallProgres.dismiss();
        }

        protected void onPostExecute(Long result) {
           if(result==1)
           {
               log("end WallChange");

           }
        }
    }
</code>```

simple map as this showed :

```<code>----start progress(progress.show())
----start function
--- animation (progressDialog)
---animation(---)
---animation(---)
---FREEZ
---FREEZ(Function steel working normal, progressDialog in freeze mode)
---animation
---end function
---progress.dismis();//
</code>```

similar problem i found here..(this problem = my problem but without download) Freezing UI Thread with AsyncTask
Regards,Peter.

答:
place this line "wallProgres.dismiss()" in onPostExecute().

```<code>   protected void onPostExecute(Long result) {
               if(result==1)
               {
                   log("end WallChange");

               }
               if(wallProgress.isShowing())
                       wallProgres.dismiss();
      }
</code>```

Title: asyncTask and progressDialog : Freeze

Body:
please see my code .. and if you can, tell me why my progressDialog stopped when the function is halfway done in the background, the screen hangs (nothing is displayed, the logcat shows all logs i put in the background function).

Then, right before the end, the progressDialog starts animating again and closes after a couple seconds (the function is finished and the result is displayed normally)

public class changeWall extends AsyncTask<Integer, Integer, Integer> {
        protected Integer doInBackground(Integer... urls) {
            int totalSize=0;
            try {

                 if(s.loadBoolean() == false)
                {
                     log("IF = false");
                     log("tempLogin = "+tempLogin);
                     log("tempPassword = "+tempPassword);
                     getNewResponse(tempLogin,tempPassword);
                if(needSave)
                {
                 s.saveBoolean(true);
                }

                }
                 else
                 {
                if(s.loadLogin()==null)
                {
                   getNewResponse(tempLogin,tempPassword);
                }else
                {
                    getNewResponse(s.loadLogin(),s.loadPassowrd());
                }
                 }
                parser.setLol(0);

                parser.startParse(RESULT_STRING);

             log("end parse");
            } catch (ClientProtocolException e) {
                log("internet connection lost");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log(" connection lost");
            }
            log("count = "+parser.getFacebookId(1));
            publishProgress();
            totalSize=1;
            log("end of start");
            return totalSize;
        }

        protected void onProgressUpdate(Integer... progress) {
            log("wall click ON PROGRESS UPDATE");
            wall.setBackgroundResource(R.drawable.tabbuttonon);
            messages.setBackgroundResource(0);
            activity.setBackgroundResource(0);
            profile.setBackgroundResource(0);
            l1_1.setBackgroundResource(R.drawable.tabbuttononleft);
            l1_2.setBackgroundResource(R.drawable.tabbuttononright);
            l2_1.setBackgroundResource(0);
            l2_2.setBackgroundResource(0);
            l3_1.setBackgroundResource(0);
            l3_2.setBackgroundResource(0);
            l4_2.setBackgroundResource(0);
            l4_2.setBackgroundResource(0);
            wall.setTextColor(Color.BLACK);
            messages.setTextColor(Color.WHITE);
            profile.setTextColor(Color.WHITE);
            activity.setTextColor(Color.WHITE);

            try {
                loadWall();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
               wallProgres.dismiss();
        }

        protected void onPostExecute(Long result) {
           if(result==1)
           {
               log("end WallChange");

           }
        }
    }

simple map as this showed :

----start progress(progress.show())
----start function
--- animation (progressDialog)
---animation(---)
---animation(---)
---FREEZ
---FREEZ(Function steel working normal, progressDialog in freeze mode)
---animation
---end function
---progress.dismis();//

similar problem i found here..(this problem = my problem but without download) Freezing UI Thread with AsyncTask
Regards,Peter.

Body:
place this line "wallProgres.dismiss()" in onPostExecute().

   protected void onPostExecute(Long result) {
               if(result==1)
               {
                   log("end WallChange");

               }
               if(wallProgress.isShowing())
                       wallProgres.dismiss();
      }


问:
Encoding in ROracle
I'm having issues importing norwegian characters like æ, ø, and å from an Oracle database using ROracle. I've had similar problems with RODBC before. I don't have the problem when importing from files like csv and xlsx, I'm sure the problem is with setting the encoding when importing with ROracle, but the documentation does't really tell me how to do that.

Various answers write a function for converting to UTF-8 after importing, but that is not a solution that works for me. I wish to make queries to the oracle DB using the dplyr package and need to be able to query using letters like æøå.

Here is my connection string, and the sql-query I use as a test:

```<code>library(ROracle)

drv <- dbDriver("Oracle", unicode_as_utf8 = TRUE, ora.attributes = TRUE)
# Create the connection string
host <- "xx.xxx.xx.x"
port <- xxxx
sid <- "xxxxxx"
connect.string <- paste(
  "(DESCRIPTION=",
  "(ADDRESS=(PROTOCOL=tcp)(HOST=", host, ")(PORT=", port, "))",
  "(CONNECT_DATA=(SID=", sid, ")))", sep = "")
con <- dbConnect(drv, username = "",
                 password = "",dbname=connect.string)

test <- dbGetQuery(con, "SELECT DECODE FROM T_CODE where key_id=17")
</code>```

That gives me results like this: R?dgivningskontor

Here is my session info:

```<code>R version 3.5.0 (2018-04-23)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.4

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] ROracle_1.3-1 DBI_1.0.0

loaded via a namespace (and not attached):
[1] compiler_3.5.0 tools_3.5.0    yaml_2.1.19
</code>```

答:
Can't comment, so I write this as an answer.

The .Renviron solution worked for me with a spanish database, but when I used NLS_LANG="AMERICAN_AMERICA.AL32UTF8" I got an error with the password and username.

Then I find this article and finally understood, my solution was.

# First with 'usethis' library create the .Renviron
library(usethis)
usethis::edit_r_environ()

# Then add the NLS_LANG in Renviron
# NLS_LANG=".WE8ISO8859P1"

# If for some reason Renviron wont load you can use this in your script
readRenviron("path_to_the_file/.Renviron")
```

Of course restart RStudio and I finally can get the ñ character instead of a ? simbol.

Thanks to @Ion Garaicoechea

Title: Encoding in ROracle

Body:
I'm having issues importing norwegian characters like æ, ø, and å from an Oracle database using ROracle. I've had similar problems with RODBC before. I don't have the problem when importing from files like csv and xlsx, I'm sure the problem is with setting the encoding when importing with ROracle, but the documentation does't really tell me how to do that.

Various answers write a function for converting to UTF-8 after importing, but that is not a solution that works for me. I wish to make queries to the oracle DB using the dplyr package and need to be able to query using letters like æøå.

Here is my connection string, and the sql-query I use as a test:

library(ROracle)

drv <- dbDriver("Oracle", unicode_as_utf8 = TRUE, ora.attributes = TRUE)
# Create the connection string
host <- "xx.xxx.xx.x"
port <- xxxx
sid <- "xxxxxx"
connect.string <- paste(
  "(DESCRIPTION=",
  "(ADDRESS=(PROTOCOL=tcp)(HOST=", host, ")(PORT=", port, "))",
  "(CONNECT_DATA=(SID=", sid, ")))", sep = "")
con <- dbConnect(drv, username = "",
                 password = "",dbname=connect.string)

test <- dbGetQuery(con, "SELECT DECODE FROM T_CODE where key_id=17")

That gives me results like this: R?dgivningskontor

Here is my session info:

R version 3.5.0 (2018-04-23)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.4

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] ROracle_1.3-1 DBI_1.0.0

loaded via a namespace (and not attached):
[1] compiler_3.5.0 tools_3.5.0    yaml_2.1.19

Body:
Can't comment, so I write this as an answer.

The .Renviron solution worked for me with a spanish database, but when I used NLS_LANG="AMERICAN_AMERICA.AL32UTF8" I got an error with the password and username.

Then I find this article and finally understood, my solution was.

# First with 'usethis' library create the .Renviron
library(usethis)
usethis::edit_r_environ()

# Then add the NLS_LANG in Renviron
# NLS_LANG=".WE8ISO8859P1"

# If for some reason Renviron wont load you can use this in your script
readRenviron("path_to_the_file/.Renviron")

Of course restart RStudio and I finally can get the ñ character instead of a ? simbol.

Thanks to @Ion Garaicoechea


问:
XSLT target specific string before closing tags
I am currently trying to add a new attribute to an element but the value needs to come from the data itself and I have no clue how to target it as the text value can happen in 2 different places.

My input XML is as following:

Case 1

```<code><div>
   <title/>
   <p>This is an example where the string is being used in the text (0123-45-6789) and how a sentence can look like. (0123-45-6789)</p>
</div>
</code>```

Case 2

```<code><div>
   <title>This is an example title. (0123-45)</title>
   <p>This is an example sentence.</p>
</div>
</code>```

Target

```<code><div id="0123-45">
    <title>This is an example title. (0123-45)</title>
    <p>This is an example sentence.</p>
</div>
</code>```

The string I need is the one between the brackets and it can consist of 2 digits, 4 digits, 6 digits or 10 digits. As the string can also be used in text I can only target the ones that are before the closing tag
 and .

I already tried to use analyze-string with regex but ended up targeting all of the strings instead of the ones I need.

Is there any way this can be done in XSLT? Thanks in advance to point me in the right direction!

Kind regards

答:
How about:

XSLT 2.0

```<code><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="div">
    <div id="{replace(., '.*\((.*)\).*', '$1')}">
        <xsl:apply-templates/>
    </div>
</xsl:template>

</xsl:stylesheet>
</code>```

Body:
I am currently trying to add a new attribute to an element but the value needs to come from the data itself and I have no clue how to target it as the text value can happen in 2 different places.

My input XML is as following:

Case 1

   <title/>

This is an example where the string is being used in the text (0123-45-6789) and how a sentence can look like. (0123-45-6789)

Case 2

   <title>This is an example title. (0123-45)</title>

This is an example sentence.

Target

    <title>This is an example title. (0123-45)</title>

This is an example sentence.

The string I need is the one between the brackets and it can consist of 2 digits, 4 digits, 6 digits or 10 digits. As the string can also be used in text I can only target the ones that are before the closing tag
 and .

I already tried to use analyze-string with regex but ended up targeting all of the strings instead of the ones I need.

Is there any way this can be done in XSLT? Thanks in advance to point me in the right direction!

Kind regards

Body:
How about:

XSLT 2.0

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="div">
    <div id="{replace(., '.*\((.*)\).*', '$1')}">
        <xsl:apply-templates/>
    </div>
</xsl:template>

</xsl:stylesheet>


问:
How to click on copy button with cypress
So in my app i have a button and when i click on it, it will save some text into my clipboard, then i can past it by ctrl+v somewhere.

And i am trying to write cypress test for this. Problem is, when i click on that button i got cypress error:

I can´t figured out. Element is clearly viewed on page. I tryied to wait few second before clicking and it didn´t help.

Is there a way how to test it?

Thank you for your answers.

答:
You can catch exceptions globally by writing this under cypress/support/index.js

Cypress.on('uncaught:exception', (err, runnable) => {
  return false
})
```


问:
Media query syntax for Reactjs
How do I do the following CSS media query in Reactjs?

```<code>.heading {
  text-align: right;
  /* media queries */
  @media (max-width: 767px) {
    text-align: center;
  }
  @media (max-width: 400px) {
    text-align: left;
  }
}
</code>```

I tried the following but it throws a syntax error and fails to compile.

```<code>heading: {
  textAlign: 'right',
  @media (maxWidth: '767px') {
    textAlign: 'center';
  }
  @media (maxWidth: '400px') {
    textAlign: 'left';
  }
}
</code>```

答:
const styles = (window.innerWidth > window.innerHeight) ? {
    header: {
        display: 'flex',
        justifyContent: 'center',
    },
    body: {
        boxShadow: '0px 0px 5px black',
        display: 'flex',
        justifyContent: 'center',
        flexDirection: 'column'
    }
} : {
    // other styles
}
```

You can use this syntax for your styles.

Title: Media query syntax for Reactjs

Body:
How do I do the following CSS media query in Reactjs?

.heading {
  text-align: right;
  /* media queries */
  @media (max-width: 767px) {
    text-align: center;
  }
  @media (max-width: 400px) {
    text-align: left;
  }
}

I tried the following but it throws a syntax error and fails to compile.

heading: {
  textAlign: 'right',
  @media (maxWidth: '767px') {
    textAlign: 'center';
  }
  @media (maxWidth: '400px') {
    textAlign: 'left';
  }
}

Body:
const styles = (window.innerWidth > window.innerHeight) ? {
    header: {
        display: 'flex',
        justifyContent: 'center',
    },
    body: {
        boxShadow: '0px 0px 5px black',
        display: 'flex',
        justifyContent: 'center',
        flexDirection: 'column'
    }
} : {
    // other styles
}

You can use this syntax for your styles.


问:
How to retrieve a column that appear in multiple rows based on a condition with pandas?
I am using a large IMDB dataset to do some practicing.

df_movies[(df_movies['movie'] == 'Fight Club (1999)') | (df_movies['movie'] == 'Se7en (1995)')].value_counts('actor')
```
<p>The above query has given me this dataset.</p>
```
movie   actor   year    duration    adult_movie rating  votes
3506    Se7en (1995)    Brad Pitt (b.1963)  1995    127.0   0   8.6 1342867.0
3513    Fight Club (1999)   Brad Pitt (b.1963)  1999    139.0   0   8.8 1742920.0
5380    Se7en (1995)    Morgan Freeman (b.1937) 1995    127.0   0   8.6 1342867.0
8065    Se7en (1995)    Kevin Spacey (b.1959)   1995    127.0   0   8.6 1342867.0
40124   Fight Club (1999)   Meat Loaf (b.1947)  1999    139.0   0   8.8 1742920.0
40905   Fight Club (1999)   Edward Norton (b.1969)  1999    139.0   0   8.8 1742920.0
46730   Se7en (1995)    Andrew Kevin Walker (b.1964)    1995    127.0   0   8.6 1342867.0
390010  Fight Club (1999)   Zach Grenier (b.1954)   1999    139.0   0   8.8 1742920.0
```

Brad Pitt  is the only actor on this list to appear in both movies. How can I filter it such that Brad Pitt is returned?

答:
Replace value_counts by groupby_filter:

```<code>movies = ['Fight Club (1999)', 'Se7en (1995)']

both_movies = lambda x: len(x) == len(movies)
out = df_movies[df_movies['movie'].isin(movies)].groupby('actor').filter(both_movies)
</code>```

Output:

```<code>>>> out
                  movie               actor  year  duration  adult_movie  rating      votes
3506       Se7en (1995)  Brad Pitt (b.1963)  1995     127.0            0     8.6  1342867.0
3513  Fight Club (1999)  Brad Pitt (b.1963)  1999     139.0            0     8.8  1742920.0
</code>```

Body:
I am using a large IMDB dataset to do some practicing.

df_movies[(df_movies['movie'] == 'Fight Club (1999)') | (df_movies['movie'] == 'Se7en (1995)')].value_counts('actor')

The above query has given me this dataset.

movie   actor   year    duration    adult_movie rating  votes
3506    Se7en (1995)    Brad Pitt (b.1963)  1995    127.0   0   8.6 1342867.0
3513    Fight Club (1999)   Brad Pitt (b.1963)  1999    139.0   0   8.8 1742920.0
5380    Se7en (1995)    Morgan Freeman (b.1937) 1995    127.0   0   8.6 1342867.0
8065    Se7en (1995)    Kevin Spacey (b.1959)   1995    127.0   0   8.6 1342867.0
40124   Fight Club (1999)   Meat Loaf (b.1947)  1999    139.0   0   8.8 1742920.0
40905   Fight Club (1999)   Edward Norton (b.1969)  1999    139.0   0   8.8 1742920.0
46730   Se7en (1995)    Andrew Kevin Walker (b.1964)    1995    127.0   0   8.6 1342867.0
390010  Fight Club (1999)   Zach Grenier (b.1954)   1999    139.0   0   8.8 1742920.0

Brad Pitt  is the only actor on this list to appear in both movies. How can I filter it such that Brad Pitt is returned?

Body:
Replace value_counts by groupby_filter:

movies = ['Fight Club (1999)', 'Se7en (1995)']

both_movies = lambda x: len(x) == len(movies)
out = df_movies[df_movies['movie'].isin(movies)].groupby('actor').filter(both_movies)

Output:

>>> out
                  movie               actor  year  duration  adult_movie  rating      votes
3506       Se7en (1995)  Brad Pitt (b.1963)  1995     127.0            0     8.6  1342867.0
3513  Fight Club (1999)  Brad Pitt (b.1963)  1999     139.0            0     8.8  1742920.0


问:
Console.log in a custom .map function React
I've grabbed some data from redux and am mapping to a component.

If I console.log the text attribute, I do recieve all the data available. See below:
https://gyazo.com/ae7167952d14623be30f80b69cc20d5c

However I would like to link this to an onClick event. E.g if I click on 'Data Analyst', this will console.log -> Data Analyst. This however is not functioning and I am getting zero response from these events.

What is incorrect on my syntax?

```<code>    const searchResults = useSelector(state => state.jobsearch.roles.map(role => role.title))

    const SearchResultsText = ({ text }) => {
        console.log(text)

        return (
            <JobContainer onClick={() => console.log(text)}>
                <JobSearchTypography
                >
                    {text}
                </JobSearchTypography>
          </JobContainer>
        );
      };

</code>```

When it's in the app itself, it looks as such:

```<code>                <JobContainer >
                {searchResults && searchResults.length < 3 && searchResults.map((result) =>
                    (<IndividualContainer >
                        <SearchResultsText text={result}/>
                    </IndividualContainer>
                    )
                )}
                </JobContainer>
</code>```

答:
If your text is inside JobSearchTypography  then you can try it something like this-

<JobSearchTypography  onClick={(e)=>console.log(e.target.innerHTML)}>
      {text}
</JobSearchTypography>```

Body:
I've grabbed some data from redux and am mapping to a component.

If I console.log the text attribute, I do recieve all the data available. See below:
https://gyazo.com/ae7167952d14623be30f80b69cc20d5c

However I would like to link this to an onClick event. E.g if I click on 'Data Analyst', this will console.log -> Data Analyst. This however is not functioning and I am getting zero response from these events.

What is incorrect on my syntax?

    const searchResults = useSelector(state => state.jobsearch.roles.map(role => role.title))

    const SearchResultsText = ({ text }) => {
        console.log(text)

        return (
            <JobContainer onClick={() => console.log(text)}>
                <JobSearchTypography
                >
                    {text}
                </JobSearchTypography>
          </JobContainer>
        );
      };

When it's in the app itself, it looks as such:

                <JobContainer >
                {searchResults && searchResults.length < 3 && searchResults.map((result) =>
                    (<IndividualContainer >
                        <SearchResultsText text={result}/>
                    </IndividualContainer>
                    )
                )}
                </JobContainer>