问:
Is there an alternative for the Excel function CONCATENATE that doesn't require text?
In excel, I am trying to obtain the average of a range of numbers in a single column with a fixed start row (B4) and a variable end row (which is the value of Cell C2 minus 1 with the match function) I am using the following formula in Excel that works perfectly:

```<code>=AVERAGE(B4:INDIRECT(CONCATENATE("B",MATCH((C2-1),A:A,0))))
</code>```

HOWEVER, I will need to copy and paste this formula into other columns, so the "B" will need to change to a "G" and so on. The new column letter will always be +5 from the previous column, and -3 from the column the cell formula is stored in. I want Excel to auto-populate the change in column letter, but CONCATENATE only works with text. I tried to use the offset function in place of the CONCATENATE "B" argument (see below), but I think INDIRECT might require text as well and/or I'm using the offset function incorrectly.

```<code>AVERAGE(B4:INDIRECT((OFFSET(5,-3,0)) & MATCH((C2-1),A:A,0))))
</code>```

Does anyone have any ideas for a fix?

答:
Use INDEX:</p>

```<code>=AVERAGE(B4:INDEX(B:B,MATCH((C2-1),A:A,0)))
</code>```

Body:
In excel, I am trying to obtain the average of a range of numbers in a single column with a fixed start row (B4) and a variable end row (which is the value of Cell C2 minus 1 with the match function) I am using the following formula in Excel that works perfectly:

=AVERAGE(B4:INDIRECT(CONCATENATE("B",MATCH((C2-1),A:A,0))))

HOWEVER, I will need to copy and paste this formula into other columns, so the "B" will need to change to a "G" and so on. The new column letter will always be +5 from the previous column, and -3 from the column the cell formula is stored in. I want Excel to auto-populate the change in column letter, but CONCATENATE only works with text. I tried to use the offset function in place of the CONCATENATE "B" argument (see below), but I think INDIRECT might require text as well and/or I'm using the offset function incorrectly.

AVERAGE(B4:INDIRECT((OFFSET(5,-3,0)) & MATCH((C2-1),A:A,0))))

Does anyone have any ideas for a fix?

Body:
Use INDEX:

=AVERAGE(B4:INDEX(B:B,MATCH((C2-1),A:A,0)))


来源: stackexchange

问:
My wordpress child-theme doesn't apply css changes
i've created a child theme from the nightingale theme but when I try to change a propetry in nigthingale-child/style.css it doesn't apply. For instance I've tried to change background-color of the body or display none for h1 markup just to see whether my child theme style.css works but nothing happens.

I've followed all steps for creating a child theme:
-new folder nightingale-child
-inside this foder I've added two files : function.php & style.css
here is my style.css :

```<code>/*
 Theme Name: nightingale-child
 Theme URI:    http://example.com/twenty-fifteen-child/
 Description:  nightingale Child Theme
 Author:       John Doe
 Author URI:   http://example.com
 Template:     nightingale
 Version:      1.0.0
 License:      GNU General Public License v2 or later
 License URI:  http://www.gnu.org/licenses/gpl-2.0.html
 Tags:         light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
 Text Domain:  nightingalechild
*/

a {
color: red;
}
</code>```

and here is my function.php:

```<code><?php
add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' );

function enqueue_parent_styles() {
   wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' );
}
</code>```

Does anybody know what's wrong with my nightingale-child theme ?

答:
Your function is loading the PARENT theme CSS. You need to change a couple things to load the CHILD CSS:

```<code><?php
// Let's change this to `enqueue_child_styles` so it's clearer.
add_action( 'wp_enqueue_scripts', 'enqueue_child_styles' );

// Now the function
function enqueue_child_styles() {
    // Rename the hook to child-style
   wp_enqueue_style( 'child-style', get_stylesheet_directory_uri().'/style.css' );
}
</code>```

In this instance, you want to use get_stylesheet_directory_uri() since get_template_directory_uri() always points to the PARENT theme, where as get_stylesheet_directory_uri() points to the CHILD theme.

ContentLicense: CC BY-SA 4.0

Body:
i've created a child theme from the nightingale theme but when I try to change a propetry in nigthingale-child/style.css it doesn't apply. For instance I've tried to change background-color of the body or display none for h1 markup just to see whether my child theme style.css works but nothing happens.

I've followed all steps for creating a child theme:
-new folder nightingale-child
-inside this foder I've added two files : function.php & style.css
here is my style.css :

/*
 Theme Name: nightingale-child
 Theme URI:    http://example.com/twenty-fifteen-child/
 Description:  nightingale Child Theme
 Author:       John Doe
 Author URI:   http://example.com
 Template:     nightingale
 Version:      1.0.0
 License:      GNU General Public License v2 or later
 License URI:  http://www.gnu.org/licenses/gpl-2.0.html
 Tags:         light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
 Text Domain:  nightingalechild
*/

a {
color: red;
}

and here is my function.php:

<?php
add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' );

function enqueue_parent_styles() {
   wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' );
}

Does anybody know what's wrong with my nightingale-child theme ?

Body:
Your function is loading the PARENT theme CSS. You need to change a couple things to load the CHILD CSS:

<?php
// Let's change this to `enqueue_child_styles` so it's clearer.
add_action( 'wp_enqueue_scripts', 'enqueue_child_styles' );

// Now the function
function enqueue_child_styles() {
    // Rename the hook to child-style
   wp_enqueue_style( 'child-style', get_stylesheet_directory_uri().'/style.css' );
}

In this instance, you want to use get_stylesheet_directory_uri() since get_template_directory_uri() always points to the PARENT theme, where as get_stylesheet_directory_uri() points to the CHILD theme.


问:
Networkx hamiltonian cycle
I would like to add Hamilton cycle functionality to my design, but I'm not sure how to do it. I know there are algorithms like nx.is_tournament.hamiltonian_path etc. But I don't know how to implement them exactly. Below is an example of an euler cycle that works fine for me and I would like to create a Hamilton cycle in a similar way.

def isEulerian():
    isEulerian = nx.is_eulerian(myGlobalGraph)
    if isEulerian == True:
        trueInfo = 'this is Eulerian graph'
        trueInfo2 = '\n'
        Log.insert(INSERT, trueInfo)
        Log.insert(INSERT, trueInfo2)
        eulerianCircuit = list(nx.eulerian_circuit(myGlobalGraph))
        eulerianCircuitInfo = 'Order of action:'
        eulerianCircuitInfo2 = '\n'
        Log.insert(INSERT, eulerianCircuitInfo)
        Log.insert(INSERT, eulerianCircuitInfo2)
        for i in range(len(eulerianCircuit)):
            x = eulerianCircuit[i][::2]
            eulerianCircuitInfo3 = x
            eulerianCircuitInfo4 = ' > '
            Log.insert(INSERT, eulerianCircuitInfo3)
            Log.insert(INSERT, eulerianCircuitInfo4)
        eulerianCircuitInfo5 = '\n'
        Log.insert(INSERT, eulerianCircuitInfo5)
        eulerianCircuitInfo6 = '\n'
        Log.insert(INSERT, eulerianCircuitInfo6)
    elif isEulerian == False:
        falseInfo = 'this is not Eulerian graph'
        falseInfo2 = '\n'
        falseInfo3 = '\n'
        Log.insert(INSERT, falseInfo)
        Log.insert(INSERT, falseInfo2)
        Log.insert(INSERT, falseInfo3)
```

答:
The implementation you are referring to in networkx is working only on tournament graphs, which are graphs where there is exactly one directed edge between each node. I assume you need a general graph implementation and therefore it is not suitable for you.

The reason (I believe) these is no implementation for hamiltonian path in networkx, is that the problem of finding one is NP-Complete. So if you would just create a brute force algorithm it will be the best you can do.

Here is one brute force implementation I found on github.

Title: Networkx hamiltonian cycle


问:
Java for embedded systems?
I have recently learned some basic Java and was thinking of seeing if I can use these new skills for an embedded computing project.
I have been looking around but I can't seem to be able to find any microcontrollers that are capable of running Java.
Does such a thing even exist?</p>

答:
Yes, microcontrollers that are capable of running Java on the bare metal exist

But JVM on this microcontrollers optimized for speed, and low memory usage. It's mean optimized JVM have some limitation instead of regular JVM, it's like Python and MicroPython

But pure code on Java allow you to transfer code with ease from the desktop to a microcontroller or embedded system

For self education with embedded computing project you can try to use Javaino
allow execute Java programs on this development board, read data from sensors via i2c, UART, etc like Arduino

ContentLicense: CC BY-SA 3.0

Title: Java for embedded systems?


问:
How to load a DFS table of DolphinDB into Python client with Orca?
I am trying to replace pandas with Orca in my project for a better performance. But I don't know How to load data from a DolphinDB DFS table, which I have already created and imported data into on DolphinDB Server.

I load the table in this way in DolphinDB:

```<code>tb=loadTable("dfs://tickData", "tick1")
</code>```

How to load a DolphinDB DFS table into Python client using Orca?

答:
```<code>import dolphindb.orca as orca
orca.read_table("dfs://tickData", "tick1")
</code>```

Body:
I am trying to replace pandas with Orca in my project for a better performance. But I don't know How to load data from a DolphinDB DFS table, which I have already created and imported data into on DolphinDB Server.

I load the table in this way in DolphinDB:

tb=loadTable("dfs://tickData", "tick1")

How to load a DolphinDB DFS table into Python client using Orca?


答:
with awk you can do something like this :

```<code>awk -F " " '{print $8,$11}' file.txt | awk 'NF>0{print $1","$2}' > newfile.txt
</code>```

NF > 0 : to remove blank lines

> newfile.txt : redirect the output to file

```<code>0.3430,0.8753
0.0849,0.9739
0.0742,0.9791
0.0565,0.9841
0.0409,0.9881
</code>```

Title: How to parse a text file using regex

Body:
I'm trying to parse some log files to get some numbers out and into a CSV file. The log files have a lot of log messages but below is an excerpt of the lines that need to parse.

I'm trying to get the loss and accuracy numbers out of this text file below into a CSV. Any recommendations for bash or python tricks?

1500/1500 [==============================] - 1802s 1s/step - loss: 0.3430 - accuracy: 0.8753 - val_loss: 0.1110 - val_accuracy: 0.9670
Epoch 00002: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_02_0.069291627_0.98.h5
1500/1500 [==============================] - 1679s 1s/step - loss: 0.0849 - accuracy: 0.9739 - val_loss: 0.0693 - val_accuracy: 0.9807
Epoch 00003: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_03_0.055876694_0.98.h5
1500/1500 [==============================] - 1674s 1s/step - loss: 0.0742 - accuracy: 0.9791 - val_loss: 0.0559 - val_accuracy: 0.9845
Epoch 00004: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_04_0.053867317_0.99.h5
1500/1500 [==============================] - 1671s 1s/step - loss: 0.0565 - accuracy: 0.9841 - val_loss: 0.0539 - val_accuracy: 0.9850
Epoch 00005: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_05_0.053266536_0.99.h5
1500/1500 [==============================] - 1675s 1s/step - loss: 0.0409 - accuracy: 0.9881 - val_loss: 0.0533 - val_accuracy: 0.9855

Here is what I tried in python:

import re
text = r"""00 [==============================] - 1802s 1s/step - loss: 0.3430 - accuracy: 0.8753 - val_loss: 0.1110 - val_accuracy: 0.9670
Epoch 00002: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_02_0.069291627_0.98.h5
1500/1500 [==============================] - 1679s 1s/step - loss: 0.0849 - accuracy: 0.9739 - val_loss: 0.0693 - val_accuracy: 0.9807
Epoch 00003: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_03_0.055876694_0.98.h5
1500/1500 [==============================] - 1674s 1s/step - loss: 0.0742 - accuracy: 0.9791 - val_loss: 0.0559 - val_accuracy: 0.9845
Epoch 00004: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_04_0.053867317_0.99.h5
1500/1500 [==============================] - 1671s 1s/step - loss: 0.0565 - accuracy: 0.9841 - val_loss: 0.0539 - val_accuracy: 0.9850
Epoch 00005: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_05_0.053266536_0.99.h5"""
regular_exp = re.compile(r'^.*val_accuracy.*$', re.M)
for match in regular_exp.finditer(text)
   print(match)

Body:
with awk you can do something like this :

awk -F " " '{print $8,$11}' file.txt | awk 'NF>0{print $1","$2}' > newfile.txt

NF > 0 : to remove blank lines

> newfile.txt : redirect the output to file

0.3430,0.8753
0.0849,0.9739
0.0742,0.9791
0.0565,0.9841
0.0409,0.9881


问:
When and how does bool get called in this code?
I've been working my way through CS50 just to learn the basics of coding. I successfully made plurality of Problem Set 3, but I don't really understand how the boolean works. So the specific questions are:

1) How does the structure of the boolean work?
2) When and how does it get called?

I'm trying to understand the fundamental aspect of using this. Thanks for any help.

Here's the code:

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

// Max number of candidates
#define MAX 9

// Candidates have name and vote count
typedef struct
{
    string name;
    int votes;
}
candidate;

// Array of candidates
candidate candidates[MAX];

// Number of candidates
int candidate_count;

// Function prototypes
bool vote(string name);
void print_winner(void);

int main(int argc, string argv[])
{
    // Check for invalid usage
    if (argc < 2)
    {
        printf("Usage: plurality [candidate ...]\n");
        return 1;
    }

    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i].name = argv[i + 1];
        candidates[i].votes = 0;
    }

    int voter_count = get_int("Number of voters: ");

    // Loop over all voters
    for (int i = 0; i < voter_count; i++)
    {
        string name = get_string("Vote: ");

        // Check for invalid vote
        if (!vote(name))
        {
            printf("Invalid vote.\n");
        }
    }

    // Display winner of election
    print_winner();
}

// Update vote totals given a new vote
bool vote(string name)
{
   // TODO
   for (int i = 0; i < candidate_count; i++)
   {
       if (strcmp (name, candidates[i].name) == 0)
       {
           candidates[i].votes++;
           return true;
       }
   }
    return false;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    // TODO
    for (int i = 1; i < candidate_count; i++)
    {
        if (candidates[0].votes < candidates[i].votes)
        candidates[0].votes = candidates[i].votes;
    }
    printf ("%s\n", candidates[0].name);
    for (int i = 1; i < candidate_count; i++)
    {
        if (candidates[0].votes == candidates[i].votes)
        printf ("%s\n", candidates[i].name);
    }
    return;
}
</code>```

答:
how does bool get called in this code?

You have some significant misunderstanding of terminology here. Asking "how does bool get called" doesn't make any sense. Let me clarify some of this for you:

bool is what we call a "data type". Other data types are int and char. These define the meaning of a value in memory. For example, int is positive and negative whole numbers, char is letters and symbols, and bool is true or false.

Functions are things that we "call". More specifically, a function is a section of code to perform a specific task. We "call" the function to make it perform that task. This is why it doesn't make sense to ask "when does bool get called". We never "call bool" because bool is a data type not a function.

When we declare a function, we have to provide 3 pieces of information: the functions name, the list of inputs (or more accurately the types of each of the inputs), and the type of the result of the function (called the "return type"). When you write bool vote(string name);, this declares a function named vote that takes a string as an input and returns a bool.

The confusion might be because we use bool as part of the definition of a function. In the example above, we are just saying that the result of calling the vote() function is either true or false.

With all this in mind, we can talk about when the vote() function is called. To figure that out, you just look through the code for all the occurrences of the word vote. If you do so, you will find a line if (!vote(name)). This is where vote() is called. In otherwords, we tell the computer to execute the code in the vote() function and it returns a true or false value that is used to evaluate the condition of the if statement.

As you continue to learn programming, be sure to pay close attention to terminology. Like many other disciplines, we have our own vocabulary. In order to communicate with other programmers, you will need to use the right words. More importantly, understanding the words we use will help you understand the concepts more clearly so you can apply them yourself.

Body:
I've been working my way through CS50 just to learn the basics of coding. I successfully made plurality of Problem Set 3, but I don't really understand how the boolean works. So the specific questions are:

1) How does the structure of the boolean work?
2) When and how does it get called?

I'm trying to understand the fundamental aspect of using this. Thanks for any help.

Here's the code:

#include <cs50.h>
#include <stdio.h>
#include <string.h>

// Max number of candidates
#define MAX 9

// Candidates have name and vote count
typedef struct
{
    string name;
    int votes;
}
candidate;

// Array of candidates
candidate candidates[MAX];

// Number of candidates
int candidate_count;

// Function prototypes
bool vote(string name);
void print_winner(void);

int main(int argc, string argv[])
{
    // Check for invalid usage
    if (argc < 2)
    {
        printf("Usage: plurality [candidate ...]\n");
        return 1;
    }

    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i].name = argv[i + 1];
        candidates[i].votes = 0;
    }

    int voter_count = get_int("Number of voters: ");

    // Loop over all voters
    for (int i = 0; i < voter_count; i++)
    {
        string name = get_string("Vote: ");

        // Check for invalid vote
        if (!vote(name))
        {
            printf("Invalid vote.\n");
        }
    }

    // Display winner of election
    print_winner();
}

// Update vote totals given a new vote
bool vote(string name)
{
   // TODO
   for (int i = 0; i < candidate_count; i++)
   {
       if (strcmp (name, candidates[i].name) == 0)
       {
           candidates[i].votes++;
           return true;
       }
   }
    return false;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    // TODO
    for (int i = 1; i < candidate_count; i++)
    {
        if (candidates[0].votes < candidates[i].votes)
        candidates[0].votes = candidates[i].votes;
    }
    printf ("%s\n", candidates[0].name);
    for (int i = 1; i < candidate_count; i++)
    {
        if (candidates[0].votes == candidates[i].votes)
        printf ("%s\n", candidates[i].name);
    }
    return;
}


问:
How do you get a list of invalid values from a decimal field in Db2?
I have an issue with a column having null values in a not-null decimal field. The issue arises when that column is used (like in a case statement), but not when I simply do a select * from.

The error it comes up with is SQL0802 type 6 - Numeric data that is not valid. I was able to find a few of them and fix it, but I would like to get a list of all of them from this very large table.

But again, any time I use it, it gives me the error. This is what I have been trying mostly:

```<code>SELECT *
FROM (
    SELECT keycol_1, keycol_2,
        IFNULL(badcol, -1) AS badcol_tmp
    FROM mytable
) WHERE badcol_tmp = -1
</code>```

(Note that the column should not have negative numbers, that's why I'm using -1 there). This gives the error listed above.

I have also tried

```<code>SELECT *
FROM mytable
WHERE badcol IS NULL
</code>```

which doesn't give me any results... No error, but no rows. But I have seen it be null from scrolling through all of the data.

How can I get the list of null values in badcol?

答:
The problem isn't that the value is null, if that were the case, then

```<code>SELECT *
FROM mytable
WHERE badcol IS NULL
</code>```

would work.  The problem is that the data in the field isn't numeric.

If you're keeping your system up to date, then congrats!  IBM has added some validation utilities in the most recent TR's for 7.3 and 7.4.

Otherwise try the following (for a 2 digit zoned number):

```<code>select *
from mytable
where substr(hex(badcol),1,1) not in ('F','D')
      or substr(hex(badcol),2,1) not between '0' and '9'
      or substr(hex(badcol),3,1) not in ('F','D')
      or substr(hex(badcol),4,1) not between '0' and '9'
</code>```

Body:
I have an issue with a column having null values in a not-null decimal field. The issue arises when that column is used (like in a case statement), but not when I simply do a select * from.

The error it comes up with is SQL0802 type 6 - Numeric data that is not valid. I was able to find a few of them and fix it, but I would like to get a list of all of them from this very large table.

But again, any time I use it, it gives me the error. This is what I have been trying mostly:

SELECT *
FROM (
    SELECT keycol_1, keycol_2,
        IFNULL(badcol, -1) AS badcol_tmp
    FROM mytable
) WHERE badcol_tmp = -1

(Note that the column should not have negative numbers, that's why I'm using -1 there). This gives the error listed above.

I have also tried

SELECT *
FROM mytable
WHERE badcol IS NULL

which doesn't give me any results... No error, but no rows. But I have seen it be null from scrolling through all of the data.

How can I get the list of null values in badcol?

Body:
The problem isn't that the value is null, if that were the case, then

SELECT *
FROM mytable
WHERE badcol IS NULL

would work.  The problem is that the data in the field isn't numeric.

If you're keeping your system up to date, then congrats!  IBM has added some validation utilities in the most recent TR's for 7.3 and 7.4.

Otherwise try the following (for a 2 digit zoned number):

select *
from mytable
where substr(hex(badcol),1,1) not in ('F','D')
      or substr(hex(badcol),2,1) not between '0' and '9'
      or substr(hex(badcol),3,1) not in ('F','D')
      or substr(hex(badcol),4,1) not between '0' and '9'


问:
insert into tables from another tables
Well, I trying insert into tables to another but I get this error;

WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''lcl_user_agent' (user_agent, hitcount, click_timestap) SELECT visite_useragent,' at line 1]

This is my code;

```<code>$addagent = "INSERT INTO $wpdb->prefix.'lcl_user_agent' (user_agent, hitcount, click_timestap) SELECT visite_useragent, visite_hitcount, click_timestap FROM $wpdb->prefix.'lcl_visite_agent' .agent_id IN (' . $agent_id . ')";

$wpdb->query($addagent);
</code>```

I want insert into lcl_user_agent the visites from visite_useragent then I get the visite for block with $agent_id from the form

答:
It looks like you're messing up at the very end.
It should be this form:

```<code>INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
</code>```

So maybe this is what you're going for?

```<code>$addagent = '
 INSERT INTO
        '.$wpdb->prefix.'lcl_user_agent
        (user_agent, hitcount, click_timestap)
    SELECT
        visite_useragent, visite_hitcount, click_timestap
    FROM
        '.$wpdb->prefix.'lcl_visite_agent
    WHERE
        agent_id IN (' . $agent_id . ')
 ';
</code>```

Title: insert into tables from another tables

Body:
Well, I trying insert into tables to another but I get this error;

WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''lcl_user_agent' (user_agent, hitcount, click_timestap) SELECT visite_useragent,' at line 1]

This is my code;

$addagent = "INSERT INTO $wpdb->prefix.'lcl_user_agent' (user_agent, hitcount, click_timestap) SELECT visite_useragent, visite_hitcount, click_timestap FROM $wpdb->prefix.'lcl_visite_agent' .agent_id IN (' . $agent_id . ')";

$wpdb->query($addagent);

I want insert into lcl_user_agent the visites from visite_useragent then I get the visite for block with $agent_id from the form

Body:
It looks like you're messing up at the very end.
It should be this form:

INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;

So maybe this is what you're going for?

$addagent = '
 INSERT INTO
        '.$wpdb->prefix.'lcl_user_agent
        (user_agent, hitcount, click_timestap)
    SELECT
        visite_useragent, visite_hitcount, click_timestap
    FROM
        '.$wpdb->prefix.'lcl_visite_agent
    WHERE
        agent_id IN (' . $agent_id . ')
 ';


问:
Doxygen strange problem while documenting PHP if
I face a strange problem while I'm trying to document a project of mine. I have the following code:

```<code>//! Set default ::$action for called controller. If no action is called, default (index) will be set.
$action = isset($_GET[ 'action']) ? $_GET[ 'action'] : 'index';

if ($action) {
    echo 'something 1';
}else{
    echo 'something 2';
}

//! Set default ::$action2 for called controller. If no action is called, default (index) will be set.
$action2 = isset($_GET[ 'action']) ? $_GET[ 'action'] : 'index';

//! Set default ::$action3 for called controller. If no action is called, default (index) will be set.
$action3 = isset($_GET[ 'action']) ? $_GET[ 'action'] : 'index';
</code>```

Doxygen generates the following:

As you may see, $action2 is missing. I check one of my other files and saw same problem. Next thing after if statement is never documented, but the one after that is documented. If I remove the if statement from above example, I get documentation for all 4 variables - $page, $action, action2 and action3.

I spend enormous time of trying to understand what exactly is wrong, but no luck, so every suggestion is welcomed.

System is:
Windows XP x64 with Doxygen 1.7.4. (I'm using the Doxygen GUI)

UPDATE
Also, when I have something like that in my code (notice the missing else for the if statement). When I add the }else{} however it works. Next $variables is not documented again, but that update was about the if/else.

Doxygen converts it to this

答:
Check out this http://www.doxygen.nl/manual/autolink.html which explains the weirdness you're seeing with the first code snippet.

Unfortunately Doxygen doesn't do so well documenting procedural PHP code AND after checking all of my own doxygen generated documentation, I can't find any documented variables for any function or method unless they are defined class properties.

Otherwise, I think the largest PHP Doxygen friendly project out there is Drupal, their guidelines were written to use Doxygen's comment processing system to it's fullest. http://drupal.org/node/1354

Note, if this is not the answer you're looking for and or I'm completely off target, please let me know immediately so I can delete this answer.

Body:
I face a strange problem while I'm trying to document a project of mine. I have the following code:

//! Set default ::$action for called controller. If no action is called, default (index) will be set.
$action = isset($_GET[ 'action']) ? $_GET[ 'action'] : 'index';

if ($action) {
    echo 'something 1';
}else{
    echo 'something 2';
}

//! Set default ::$action2 for called controller. If no action is called, default (index) will be set.
$action2 = isset($_GET[ 'action']) ? $_GET[ 'action'] : 'index';

//! Set default ::$action3 for called controller. If no action is called, default (index) will be set.
$action3 = isset($_GET[ 'action']) ? $_GET[ 'action'] : 'index';

Doxygen generates the following:

As you may see, $action2 is missing. I check one of my other files and saw same problem. Next thing after if statement is never documented, but the one after that is documented. If I remove the if statement from above example, I get documentation for all 4 variables - $page, $action, action2 and action3.

I spend enormous time of trying to understand what exactly is wrong, but no luck, so every suggestion is welcomed.

System is:
Windows XP x64 with Doxygen 1.7.4. (I'm using the Doxygen GUI)

UPDATE
Also, when I have something like that in my code (notice the missing else for the if statement). When I add the }else{} however it works. Next $variables is not documented again, but that update was about the if/else.

Doxygen converts it to this


问:
Android camera2 to framebuffer jagged image?
Why does rendering a camera frame with OpenGL (and then save it) create jagged images as compared to saving a camera frame with ImageReader (OpenGL - B/W, ImageReader - Color)? Both are using the same dimensions.

Background/details to this question:

I'm building a non-blocking version of ImageReader using Camera2 and GLES (up to GLES31) for the purpose of extracting high resolution still camera frames while not interrupting the preview.

The setup is making use of a TextureView for preview and GLSurfaceView for capturing the frames off-screen. The GLSurfaceView has a simple renderer and shader that draws the GL_TEXTURE_EXTERNAL_OES onto a framebuffer from which the raw image data can be extracted.

On my test device the dimensions are set up like this:
Camera sensor size is 3264x2448 (obtained via CameraCharacteristics)

GLSurfaceView has defaultBufferSize 3264x2448 and layout 3264x2448. Format is also set to JPEG with getHolder().setFormat(ImageFormat.JPEG) and JPEG quality is 100

Framebuffer is set to 3264x2448

This should in my mind result in a 1-to-1 transfer of the camera frame, but clearly that is not the case.

I have tried several other dimensions such as matching the screen size, picking appropriate dimensions from StreamConfigurationMap, custom dimensions, all result in jagged output. It's as if there is always some up or downsampling happening in the background (GL_TEXTURE_EXTERNAL_OES actually coming in at different dimensions?).

Any input on this topic is appreciated as I've been stuck on this for weeks at this point.

答:
Are you using the transform matrix available from the SurfaceTexture to transform the texture input in GL?  Due to some complexities in some rendering paths, the default transform shrinks borders of the image by 1 pixel:

https://cs.android.com/android/platform/superproject/+/master:frameworks/base/libs/hwui/surfacetexture/SurfaceTexture.cpp;l=312

So if you're using that, you may consider trying to write your own transform to avoid that shrink, since it shouldn't be necessary for you.

Beyond that, setting the format on the GLSurfaceView has no impact here; the GL rendering overrides all that anyway.

(Just to note, on some devices the max sensor resolution may exceed the max texture size GLES supports, so be careful there).


问:
mat-table sort not working with object path key
My data that I want to use with mat-table isn't flat - there are layers of different objects.  I can display the data fine but the sorting isn't working.  Here is an example using the element data with the fields sitting down one layer inside a 'foo' object.  How can I get the sorting working?

https://stackblitz.com/edit/angular-b8u3zr?file=src%2Fapp%2Ftable-sorting-example.ts

```<code>const ELEMENT_DATA: PeriodicElement[] = [
  {foo: {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'}},
  {foo: {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}},
  {foo: {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'}},
  ...
</code>```

```<code><table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">

  <ng-container matColumnDef="foo.position">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.foo.position}} </td>
  </ng-container>

  ...

</table>
</code>```

答:
According to docs (check api tab, and search for sort customization)

Allows for sort customization by overriding sortingDataAccessor, which
  defines how data properties are accessed. Also allows for filter
  customization by overriding filterTermAccessor, which defines how row
  data is converted to a string for filter matching.

So that's what you need, you need to add sortData function of type

sortData: ((data: T[], sort: MatSort) => T[])

here is an example

```<code>  @ViewChild(MatSort, {static: true}) sort: MatSort;

  ngOnInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.sortData = this.sortData;
  }
  sortData(data: PeriodicElement[],sort: MatSort): PeriodicElement[] {
    if (!sort.active || sort.direction === '') {
      return data;
    }
    return data.sort((a, b) => {
  const isAsc = sort.direction === 'asc';
  switch (sort.active) {
    // Add other cases (columns)
    // if you are wondering where is this 'position' coming from, check the html tag for the th below
    case 'position': return isAsc ?
    (a.foo.position - b.foo.position > 1 ? 1 : -1)  :
    (a.foo.position - b.foo.position > 1 ? -1 : 1);
     default: return 0;
  }
});
}}
</code>```

HTML

```<code><th mat-header-cell *matHeaderCellDef mat-sort-header='position'> No. </th>
</code>```

Body:
My data that I want to use with mat-table isn't flat - there are layers of different objects.  I can display the data fine but the sorting isn't working.  Here is an example using the element data with the fields sitting down one layer inside a 'foo' object.  How can I get the sorting working?

https://stackblitz.com/edit/angular-b8u3zr?file=src%2Fapp%2Ftable-sorting-example.ts

const ELEMENT_DATA: PeriodicElement[] = [
  {foo: {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'}},
  {foo: {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}},
  {foo: {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'}},
  ...

  <ng-container matColumnDef="foo.position">
     No.
     {{element.foo.position}}
  </ng-container>

  ...

Body:
According to docs (check api tab, and search for sort customization)

Allows for sort customization by overriding sortingDataAccessor, which
  defines how data properties are accessed. Also allows for filter
  customization by overriding filterTermAccessor, which defines how row
  data is converted to a string for filter matching.

So that's what you need, you need to add sortData function of type

sortData: ((data: T[], sort: MatSort) => T[])

here is an example

  @ViewChild(MatSort, {static: true}) sort: MatSort;

  ngOnInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.sortData = this.sortData;
  }
  sortData(data: PeriodicElement[],sort: MatSort): PeriodicElement[] {
    if (!sort.active || sort.direction === '') {
      return data;
    }
    return data.sort((a, b) => {
  const isAsc = sort.direction === 'asc';
  switch (sort.active) {
    // Add other cases (columns)
    // if you are wondering where is this 'position' coming from, check the html tag for the th below
    case 'position': return isAsc ?
    (a.foo.position - b.foo.position > 1 ? 1 : -1)  :
    (a.foo.position - b.foo.position > 1 ? -1 : 1);
     default: return 0;
  }
});
}}

HTML

<th mat-header-cell *matHeaderCellDef mat-sort-header='position'> No. </th>


问:
Flutter - Save BlendMode to Image
I'm trying to implement an UI where the user can edit and apply effects to an uploaded image, and want to save the BlendMode merged to the image. It's possible to save the result of the blended image or apply it using the Canvas?

There are some packages that apply some specific filters, but I want something more customizable for the end user.

I already saw some examples of how to implement Canvas to draw images, but can't figure it out how to use to load an image an apply the blend related in the docs. Anyone could give an example?

UPDATED:

For who has the same question, bellow follows the code with how to save a image from canvas to a file with blendMode applied.
But I still haven't the result expected. The quality of the image generated isn't the same as the original image, neither the blend seems to be the blend that i've applied. And i can't save as jpg, just as png file.

So, how can i load an image, apply a blend with canvas and save as a jpg file, without losing quality?

CODE:

```<code>const kCanvasSize = 200.0;

class CanvasImageToFile {
  CanvasImageToFile._();
  static final instance = CanvasImageToFile._();

  ByteData _readFromFile(File file) {
    // File file = getSomeCorrectFile();
    Uint8List bytes = file.readAsBytesSync();
    return ByteData.view(bytes.buffer);
  }

  Future<File> _writeToFile(ByteData data) async {
    String dir = (await getTemporaryDirectory()).path;
    String filePath = '$dir/tempImage.jpg';
    final buffer = data.buffer;
    return new File(filePath).writeAsBytes(
        buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));
  }

  Future<ui.Image> _loadImageSource(File imageSource) async {
    // ByteData data = await rootBundle.load(asset);
    ByteData data = _readFromFile(imageSource);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }

  Future<File> generateImage(File imageSource) async {
    File imageResult;
    ui.Image image;
    await _loadImageSource(imageSource).then((value) {
      image = value;
    });
    if (image != null) {
      final recorder = ui.PictureRecorder();
      var rect =
          Rect.fromPoints(Offset(0.0, 0.0), Offset(kCanvasSize, kCanvasSize));
      final canvas = Canvas(recorder, rect);

      Size outputSize = rect.size;
      Paint paint = new Paint();

      //OVERLAY - BlendMode uses the previously drawn content as a mask
      paint.blendMode = BlendMode.colorBurn;
      paint.color = Colors.red;
      // paint.colorFilter = ColorFilter.mode(Colors.blue, BlendMode.colorDodge);
      // paint = Paint()..color = Colors.red;
      // paint = Paint()..blendMode = BlendMode.multiply;

      //Image
      Size inputSize = Size(image.width.toDouble(), image.height.toDouble());
      final FittedSizes fittedSizes =
          applyBoxFit(BoxFit.cover, inputSize, outputSize);
      final Size sourceSize = fittedSizes.source;
      final Rect sourceRect =
          Alignment.center.inscribe(sourceSize, Offset.zero & inputSize);

      canvas.saveLayer(rect, paint);
      canvas.drawImageRect(
          image, sourceRect, rect, paint);
      canvas.restore();

      final picture = recorder.endRecording();
      final img = await picture.toImage(200, 200);
      final byteData = await img.toByteData(format: ImageByteFormat.png);

      await _writeToFile(byteData).then((value) {
        imageResult = value;
      });
      return imageResult;
    }
</code>```

答:
After some research e some adjust at decoding image from png to rawUnmodified in my previous code using (Bitmap package), i could save the image with the original format (jpg) and achieved what i wanted. If there's anyone who have the same question, bellow follows the code to load an image with canvas, apply a blend and write to a file with the same quality:</p>

```<code>Future<File> generateImage(
      File imageSource, Color color, BlendMode blendMode) async {
    File imageResult;
    ui.Image image;
    await _loadImageSource(imageSource).then((value) {
      image = value;
    });
    if (image != null) {
      final recorder = ui.PictureRecorder();
      var rect = Rect.fromPoints(Offset(0.0, 0.0),
          Offset(image.width.toDouble(), image.height.toDouble()));
      final canvas = Canvas(recorder, rect);

      Size outputSize = rect.size;
      Paint paint = new Paint();

      //OVERLAY - BlendMode uses the previously drawn content as a mask
      // paint.blendMode = blendMode;
      // paint.color = color;
      paint.colorFilter = ColorFilter.mode(color, blendMode);

      //Image
      Size inputSize = Size(image.width.toDouble(), image.height.toDouble());
      final FittedSizes fittedSizes =
          applyBoxFit(BoxFit.contain, inputSize, outputSize);
      final Size sourceSize = fittedSizes.source;
      final Rect sourceRect =
          Alignment.center.inscribe(sourceSize, Offset.zero & inputSize);

      canvas.drawImageRect(image, sourceRect, rect, paint);

      final picture = recorder.endRecording();
      final img = await picture.toImage(image.width, image.height);

      ByteData byteData =
          await img.toByteData(format: ui.ImageByteFormat.rawUnmodified);
      Bitmap bitmap = Bitmap.fromHeadless(
          image.width, image.height, byteData.buffer.asUint8List());
      Uint8List headedIntList = bitmap.buildHeaded();

      await _writeToFile(headedIntList.buffer.asByteData()).then((value) {
        imageResult = value;
      });
      return imageResult;
    }
  }
</code>```

Title: Flutter - Save BlendMode to Image

Body:
I'm trying to implement an UI where the user can edit and apply effects to an uploaded image, and want to save the BlendMode merged to the image. It's possible to save the result of the blended image or apply it using the Canvas?

There are some packages that apply some specific filters, but I want something more customizable for the end user.

I already saw some examples of how to implement Canvas to draw images, but can't figure it out how to use to load an image an apply the blend related in the docs. Anyone could give an example?

UPDATED:

For who has the same question, bellow follows the code with how to save a image from canvas to a file with blendMode applied.
But I still haven't the result expected. The quality of the image generated isn't the same as the original image, neither the blend seems to be the blend that i've applied. And i can't save as jpg, just as png file.

So, how can i load an image, apply a blend with canvas and save as a jpg file, without losing quality?

CODE:

const kCanvasSize = 200.0;

class CanvasImageToFile {
  CanvasImageToFile._();
  static final instance = CanvasImageToFile._();

  ByteData _readFromFile(File file) {
    // File file = getSomeCorrectFile();
    Uint8List bytes = file.readAsBytesSync();
    return ByteData.view(bytes.buffer);
  }

  Future<File> _writeToFile(ByteData data) async {
    String dir = (await getTemporaryDirectory()).path;
    String filePath = '$dir/tempImage.jpg';
    final buffer = data.buffer;
    return new File(filePath).writeAsBytes(
        buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));
  }

  Future<ui.Image> _loadImageSource(File imageSource) async {
    // ByteData data = await rootBundle.load(asset);
    ByteData data = _readFromFile(imageSource);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }

  Future<File> generateImage(File imageSource) async {
    File imageResult;
    ui.Image image;
    await _loadImageSource(imageSource).then((value) {
      image = value;
    });
    if (image != null) {
      final recorder = ui.PictureRecorder();
      var rect =
          Rect.fromPoints(Offset(0.0, 0.0), Offset(kCanvasSize, kCanvasSize));
      final canvas = Canvas(recorder, rect);

      Size outputSize = rect.size;
      Paint paint = new Paint();

      //OVERLAY - BlendMode uses the previously drawn content as a mask
      paint.blendMode = BlendMode.colorBurn;
      paint.color = Colors.red;
      // paint.colorFilter = ColorFilter.mode(Colors.blue, BlendMode.colorDodge);
      // paint = Paint()..color = Colors.red;
      // paint = Paint()..blendMode = BlendMode.multiply;

      //Image
      Size inputSize = Size(image.width.toDouble(), image.height.toDouble());
      final FittedSizes fittedSizes =
          applyBoxFit(BoxFit.cover, inputSize, outputSize);
      final Size sourceSize = fittedSizes.source;
      final Rect sourceRect =
          Alignment.center.inscribe(sourceSize, Offset.zero & inputSize);

      canvas.saveLayer(rect, paint);
      canvas.drawImageRect(
          image, sourceRect, rect, paint);
      canvas.restore();

      final picture = recorder.endRecording();
      final img = await picture.toImage(200, 200);
      final byteData = await img.toByteData(format: ImageByteFormat.png);

      await _writeToFile(byteData).then((value) {
        imageResult = value;
      });
      return imageResult;
    }

Body:
After some research e some adjust at decoding image from png to rawUnmodified in my previous code using (Bitmap package), i could save the image with the original format (jpg) and achieved what i wanted. If there's anyone who have the same question, bellow follows the code to load an image with canvas, apply a blend and write to a file with the same quality:

Future<File> generateImage(
      File imageSource, Color color, BlendMode blendMode) async {
    File imageResult;
    ui.Image image;
    await _loadImageSource(imageSource).then((value) {
      image = value;
    });
    if (image != null) {
      final recorder = ui.PictureRecorder();
      var rect = Rect.fromPoints(Offset(0.0, 0.0),
          Offset(image.width.toDouble(), image.height.toDouble()));
      final canvas = Canvas(recorder, rect);

      Size outputSize = rect.size;
      Paint paint = new Paint();

      //OVERLAY - BlendMode uses the previously drawn content as a mask
      // paint.blendMode = blendMode;
      // paint.color = color;
      paint.colorFilter = ColorFilter.mode(color, blendMode);

      //Image
      Size inputSize = Size(image.width.toDouble(), image.height.toDouble());
      final FittedSizes fittedSizes =
          applyBoxFit(BoxFit.contain, inputSize, outputSize);
      final Size sourceSize = fittedSizes.source;
      final Rect sourceRect =
          Alignment.center.inscribe(sourceSize, Offset.zero & inputSize);

      canvas.drawImageRect(image, sourceRect, rect, paint);

      final picture = recorder.endRecording();
      final img = await picture.toImage(image.width, image.height);

      ByteData byteData =
          await img.toByteData(format: ui.ImageByteFormat.rawUnmodified);
      Bitmap bitmap = Bitmap.fromHeadless(
          image.width, image.height, byteData.buffer.asUint8List());
      Uint8List headedIntList = bitmap.buildHeaded();

      await _writeToFile(headedIntList.buffer.asByteData()).then((value) {
        imageResult = value;
      });
      return imageResult;
    }
  }


问:
Removing coordinates from a dataarray that has been converted to a list
I have a dataarray that contains a list of values over lat,lon points across the globe. I want to supply a list of lat,lon values for specific cities and apply the values at those lat,lon points to create a dataframe. To accomplish this, I do the code below.

```<code>df1=pd.read_csv('E:/Riskpulse_HD/TroPYcal/GenscapePortList.csv')

lats=df1['Latitude']
lons=df1['Longitude']

count_city=[]
for idx,(lon,lat) in enumerate(zip(lons,lats)):
    val = grid.sel(lat=lat, lon=lon, method='nearest')
    count_city.append(val)

print(np.shape(count_city))
</code>```

The print that comes out looks like this:

```<code>[<xarray.DataArray ()>
 array(0.)
 Coordinates:
     lat      float64 40.0
     lon      float64 28.0,
 <xarray.DataArray ()>
 array(0.)
 Coordinates:
     lat      float64 40.0
     lon      float64 28.0,
 <xarray.DataArray ()>
 array(0.)
 Coordinates:
     lat      float64 42.0
     lon      float64 28.0,
</code>```

So this still looks like a dataarray, but when doing a type() command it is a list. How can I go about simply stripping the coordinates part of this list?

When creating the dataframe, it looks like this:

```<code>df1['Counts']= count_city
df1.head()

Latitude    Longitude   Port Name   Counts
0   39.871112   20.003421   Sarande <xarray.DataArray ()>\narray(0.)\nCoordinates:...
1   40.450605   19.483051   Vlora   <xarray.DataArray ()>\narray(0.)\nCoordinates:...
2   41.810046   19.584720   Shengjin    <xarray.DataArray ()>\narray(0.)\nCoordinates:...
3   41.308849   19.454677   Durres  <xarray.DataArray ()>\narray(0.)\nCoordinates:...
4   35.819101   -0.247319   Bettioua    <xarray.DataArray ()>\narray(0.)\nCoordinates:...
</code>```

I just want all of the values associated with the coordinates. I am familiar with how to do this when the type is a dataarray, but unsure with a list.

答:
The result of the code is indeed a list, but a list of DataArray objects. From the xarray docs:

xarray tries hard to be self-consistent: operations on a DataArray (resp. Dataset) return another DataArray (resp. Dataset) object. In particular, operations returning scalar values (e.g. indexing or aggregations like mean or sum applied to all axes) will also return xarray objects.

To get a numpy array instead, you have to add .values (could also be .data if working with Dask arrays and wanted to keep the underlying data structure).

```<code>val = grid.sel(lat=lat, lon=lon, method='nearest')
</code>```

Body:
I have a dataarray that contains a list of values over lat,lon points across the globe. I want to supply a list of lat,lon values for specific cities and apply the values at those lat,lon points to create a dataframe. To accomplish this, I do the code below.

df1=pd.read_csv('E:/Riskpulse_HD/TroPYcal/GenscapePortList.csv')

lats=df1['Latitude']
lons=df1['Longitude']

count_city=[]
for idx,(lon,lat) in enumerate(zip(lons,lats)):
    val = grid.sel(lat=lat, lon=lon, method='nearest')
    count_city.append(val)

print(np.shape(count_city))

The print that comes out looks like this:

[<xarray.DataArray ()>
 array(0.)
 Coordinates:
     lat      float64 40.0
     lon      float64 28.0,
 <xarray.DataArray ()>
 array(0.)
 Coordinates:
     lat      float64 40.0
     lon      float64 28.0,
 <xarray.DataArray ()>
 array(0.)
 Coordinates:
     lat      float64 42.0
     lon      float64 28.0,

So this still looks like a dataarray, but when doing a type() command it is a list. How can I go about simply stripping the coordinates part of this list?

When creating the dataframe, it looks like this:

df1['Counts']= count_city
df1.head()

Latitude    Longitude   Port Name   Counts
0   39.871112   20.003421   Sarande <xarray.DataArray ()>\narray(0.)\nCoordinates:...
1   40.450605   19.483051   Vlora   <xarray.DataArray ()>\narray(0.)\nCoordinates:...
2   41.810046   19.584720   Shengjin    <xarray.DataArray ()>\narray(0.)\nCoordinates:...
3   41.308849   19.454677   Durres  <xarray.DataArray ()>\narray(0.)\nCoordinates:...
4   35.819101   -0.247319   Bettioua    <xarray.DataArray ()>\narray(0.)\nCoordinates:...

I just want all of the values associated with the coordinates. I am familiar with how to do this when the type is a dataarray, but unsure with a list.

Body:
The result of the code is indeed a list, but a list of DataArray objects. From the xarray docs:

xarray tries hard to be self-consistent: operations on a DataArray (resp. Dataset) return another DataArray (resp. Dataset) object. In particular, operations returning scalar values (e.g. indexing or aggregations like mean or sum applied to all axes) will also return xarray objects.

To get a numpy array instead, you have to add .values (could also be .data if working with Dask arrays and wanted to keep the underlying data structure).

val = grid.sel(lat=lat, lon=lon, method='nearest')


问:
Processing is hanging at notary
Currently, I am using Corda V3.1 and there is one issue which I could not figure out the root cause of. The behavior of the error occurs when the application processes a transaction. It is hanged at the last step in the below logs:

```<code>>> Verifying contractCode constraints.
>> Signing transaction with our private key.
>> Collecting signatures from counterparties.
>> Done
>> Obtaining notary signature and recording transaction.
>> Requesting signature by notary service
>> Requesting signature by Notary service(hanged here)
</code>```

I didn't make any changes, but it stopped working. From the log, I could see:

```<code>[INFO ] 2018-06-10T07:06:35,287Z [main] BasicInfo.printBasicNodeInfo - Node for "Notary" started up and registered in 42.91 sec {}
[INFO ] 2018-06-10T07:06:40,305Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Adding node with info: NodeInfo(addresses=[[2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005], legalIdentitiesAndCerts=[O=CompanyA, L=London, C=GB], platformVersion=3, serial=1528610763747) {}
[INFO ] 2018-06-10T07:06:40,336Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Previous node was identical to incoming one - doing nothing {}
[INFO ] 2018-06-10T07:06:40,336Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Done adding node with info: NodeInfo(addresses=[[2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005], legalIdentitiesAndCerts=[O=CompanyA, L=London, C=GB], platformVersion=3, serial=1528610763747) {}
[INFO ] 2018-06-10T07:06:40,336Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Adding node with info: NodeInfo(addresses=[[2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10008], legalIdentitiesAndCerts=[O=CompanyB, L=New York, C=US], platformVersion=3, serial=1528610765829) {}
[INFO ] 2018-06-10T07:06:40,352Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Previous node was identical to incoming one - doing nothing {}
[INFO ] 2018-06-10T07:06:40,352Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Done adding node with info: NodeInfo(addresses=[[2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10008], legalIdentitiesAndCerts=[O=CompanyB, L=New York, C=US], platformVersion=3, serial=1528610765829) {}
[INFO ] 2018-06-10T07:06:40,352Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Adding node with info: NodeInfo(addresses=[[2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10002], legalIdentitiesAndCerts=[O=Notary, L=London, C=GB], platformVersion=3, serial=1528610765215) {}
[INFO ] 2018-06-10T07:06:40,352Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Discarding older nodeInfo for O=Notary, L=London, C=GB {}
[INFO ] 2018-06-10T07:06:53,654Z [nioEventLoopGroup-2-1] netty.AMQPClient.operationComplete - Failed to connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:06:54,663Z [nioEventLoopGroup-2-2] netty.AMQPClient.run - Retry connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:07:15,687Z [nioEventLoopGroup-2-3] netty.AMQPClient.operationComplete - Failed to connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:07:16,696Z [nioEventLoopGroup-2-4] netty.AMQPClient.run - Retry connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:07:37,720Z [nioEventLoopGroup-2-5] netty.AMQPClient.operationComplete - Failed to connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:07:38,728Z [nioEventLoopGroup-2-6] netty.AMQPClient.run - Retry connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:07:59,747Z [nioEventLoopGroup-2-7] netty.AMQPClient.operationComplete - Failed to connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:08:00,747Z [nioEventLoopGroup-2-8] netty.AMQPClient.run - Retry connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:08:21,768Z [nioEventLoopGroup-2-9] netty.AMQPClient.operationComplete - Failed to connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:08:22,779Z [nioEventLoopGroup-2-10] netty.AMQPClient.run - Retry connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
</code>```

The last two steps are repeating again and again. The only approach to resolve it is to clean and re-deploy nodes but, for sure, that is not correct. Anyone able to help with this? Thanks a lot.

答:
So it's not clear based on your description exactly how you were running your corda nodes.

The issue is that the corda nodes are having trouble communicating with each other but it's not clear why. if it was running on localhost than this is really strange.

If you're running these in the cloud than I'd try to regenerate your node configuration or maybe take another look at the network map corda node as it's definitely gotten wonky.

It also could be that the cordapp it's trying to run is making mistakes when trying to execute on the nodes or the notary.

You may have an easier time getting this to work with some of the newer developer samples in order to determine whether corda updates solved this problem.

The most basic sample that basically always works is the yo cordapp (https://github.com/corda/samples-java/tree/master/Basic/yo-cordapp). Try running it to see if you can isolate the problem to the flows or to corda.

Title: Processing is hanging at notary

Body:
Currently, I am using Corda V3.1 and there is one issue which I could not figure out the root cause of. The behavior of the error occurs when the application processes a transaction. It is hanged at the last step in the below logs:

>> Verifying contractCode constraints.
>> Signing transaction with our private key.
>> Collecting signatures from counterparties.
>> Done
>> Obtaining notary signature and recording transaction.
>> Requesting signature by notary service
>> Requesting signature by Notary service(hanged here)

I didn't make any changes, but it stopped working. From the log, I could see:

[INFO ] 2018-06-10T07:06:35,287Z [main] BasicInfo.printBasicNodeInfo - Node for "Notary" started up and registered in 42.91 sec {}
[INFO ] 2018-06-10T07:06:40,305Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Adding node with info: NodeInfo(addresses=[[2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005], legalIdentitiesAndCerts=[O=CompanyA, L=London, C=GB], platformVersion=3, serial=1528610763747) {}
[INFO ] 2018-06-10T07:06:40,336Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Previous node was identical to incoming one - doing nothing {}
[INFO ] 2018-06-10T07:06:40,336Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Done adding node with info: NodeInfo(addresses=[[2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005], legalIdentitiesAndCerts=[O=CompanyA, L=London, C=GB], platformVersion=3, serial=1528610763747) {}
[INFO ] 2018-06-10T07:06:40,336Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Adding node with info: NodeInfo(addresses=[[2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10008], legalIdentitiesAndCerts=[O=CompanyB, L=New York, C=US], platformVersion=3, serial=1528610765829) {}
[INFO ] 2018-06-10T07:06:40,352Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Previous node was identical to incoming one - doing nothing {}
[INFO ] 2018-06-10T07:06:40,352Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Done adding node with info: NodeInfo(addresses=[[2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10008], legalIdentitiesAndCerts=[O=CompanyB, L=New York, C=US], platformVersion=3, serial=1528610765829) {}
[INFO ] 2018-06-10T07:06:40,352Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Adding node with info: NodeInfo(addresses=[[2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10002], legalIdentitiesAndCerts=[O=Notary, L=London, C=GB], platformVersion=3, serial=1528610765215) {}
[INFO ] 2018-06-10T07:06:40,352Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Discarding older nodeInfo for O=Notary, L=London, C=GB {}
[INFO ] 2018-06-10T07:06:53,654Z [nioEventLoopGroup-2-1] netty.AMQPClient.operationComplete - Failed to connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:06:54,663Z [nioEventLoopGroup-2-2] netty.AMQPClient.run - Retry connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:07:15,687Z [nioEventLoopGroup-2-3] netty.AMQPClient.operationComplete - Failed to connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:07:16,696Z [nioEventLoopGroup-2-4] netty.AMQPClient.run - Retry connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:07:37,720Z [nioEventLoopGroup-2-5] netty.AMQPClient.operationComplete - Failed to connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:07:38,728Z [nioEventLoopGroup-2-6] netty.AMQPClient.run - Retry connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:07:59,747Z [nioEventLoopGroup-2-7] netty.AMQPClient.operationComplete - Failed to connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:08:00,747Z [nioEventLoopGroup-2-8] netty.AMQPClient.run - Retry connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:08:21,768Z [nioEventLoopGroup-2-9] netty.AMQPClient.operationComplete - Failed to connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}
[INFO ] 2018-06-10T07:08:22,779Z [nioEventLoopGroup-2-10] netty.AMQPClient.run - Retry connect to [2002:aafc:ce75:1007:34eb:f37b:e811:c350]:10005 {}

The last two steps are repeating again and again. The only approach to resolve it is to clean and re-deploy nodes but, for sure, that is not correct. Anyone able to help with this? Thanks a lot.


问:
Convert date string (from gmail) to timestamp | Python
I want to save the received date of emails from a Gmail account into a time-series database.

The problem is that I cannot convert the string that I got from the email to timestamp.

I tried this:

```<code>from datetime import datetime

date1 = 'Thu, 28 May 2020 08:15:58 -0700 (PDT)'

date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')

print(date1_obj)
</code>```

But got this error:

```<code>Traceback (most recent call last):
  File "/format_date.py", line 11, in <module>
    date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 359, in _strptime
    (data_string, format))
ValueError: time data 'Thu, 28 May 2020 08:15:58 -0700 (PDT)' does not match format '%a, %d %b %Y %H:%M:%S %z %Z'
</code>```

Tried with or without parenthesis wrapping Timezone.
Read a lot, but nothing about how to deal with date strings containing "(PDT)" or any other timezones. It's very important to get the right date... If I run the same code without "(PDT)", got an incorrect time (because of my local time).

I know I can use string methods to manipulate it and convert to a right datetime, but I feel like this would be flexible.

Sorry for my terrible English.

Thank you!

答:
Well, after all your answers, which were very helpful, I finally solved.

This is how:

```<code>>>> from email.utils import parsedate_tz, mktime_tz
>>> date = 'Thu, 28 May 2020 08:15:58 -0700 (PST)'
>>> timestamp = mktime_tz(parsedate_tz(date))
>>> timestamp
1590678958
>>>
</code>```

I checked that timestamp, and stands to 12:15:58 local time, what it's exactly what I was looking for.

Thank you very much to everybody who took a minute to answer.

Body:
I want to save the received date of emails from a Gmail account into a time-series database.

The problem is that I cannot convert the string that I got from the email to timestamp.

I tried this:

from datetime import datetime

date1 = 'Thu, 28 May 2020 08:15:58 -0700 (PDT)'

date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')

print(date1_obj)

But got this error:

Traceback (most recent call last):
  File "/format_date.py", line 11, in <module>
    date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 359, in _strptime
    (data_string, format))
ValueError: time data 'Thu, 28 May 2020 08:15:58 -0700 (PDT)' does not match format '%a, %d %b %Y %H:%M:%S %z %Z'

Tried with or without parenthesis wrapping Timezone.
Read a lot, but nothing about how to deal with date strings containing "(PDT)" or any other timezones. It's very important to get the right date... If I run the same code without "(PDT)", got an incorrect time (because of my local time).

I know I can use string methods to manipulate it and convert to a right datetime, but I feel like this would be flexible.

Sorry for my terrible English.

Thank you!

Body:
Well, after all your answers, which were very helpful, I finally solved.

This is how:

>>> from email.utils import parsedate_tz, mktime_tz
>>> date = 'Thu, 28 May 2020 08:15:58 -0700 (PST)'
>>> timestamp = mktime_tz(parsedate_tz(date))
>>> timestamp
1590678958
>>>

I checked that timestamp, and stands to 12:15:58 local time, what it's exactly what I was looking for.

Thank you very much to everybody who took a minute to answer.


答:
You could use case expressions:

```<code>select
    t.*,
    case when code1 = 101 then value1 else 0 end
        + case when code2 = 101 then value2 else 0 end
        + case when code3 = 101 then value3 else 0 end
        + case when code4 = 101 then value4 else 0 end
        as sum_code_101,
    case when code1 = 201 then value1 else 0 end
        + case when code2 = 201 then value2 else 0 end
        + case when code3 = 201 then value3 else 0 end
        + case when code4 = 201 then value4 else 0 end
        as sum_code_201,
    case when code1 = 301 then value1 else 0 end
        + case when code2 = 301 then value2 else 0 end
        + case when code3 = 301 then value3 else 0 end
        + case when code4 = 301 then value4 else 0 end
        as sum_code_301
from mytable t
</code>```

You can shorten the syntax a little by unpivoting the rows wirth cross apply, and then using conditional aggregation:

```<code>select
    t.*,
    s.*
from mytable t
outer apply (
    select
        sum(case when code = 101 then val else 0 end) sum_code_101,
        sum(case when code = 201 then val else 0 end) sum_code_201,
        sum(case when code = 301 then val else 0 end) sum_code_301,
        sum(case when code = 401 then val else 0 end) sum_code_401
    from (values
        (t.code1, t.value1),
        (t.code2, t.value2),
        (t.code3, t.value3),
        (t.code4, t.value4)
    ) as x(code, val)
)  s
</code>```

Title: Create columns where sum other columns based on conditional of other column values?

Body:
I need to create columns where sum other columns based on conditional of other column values. The requirement is as below.

I have the following table:

key code1  code2 code3 code4 value1 value2 value3 value4
0    101   101   101   101   1000    1000  1000   1000
1    101   101   101   201   1000    1000  1000   1000
2    101   101   201   201   1000    1000  1000   1000
3    101   201   201   201   1000    1000  1000   1000
4    101   201   201   301   1000    1000  1000   1000
5    101   201   301   301   1000    1000  1000   1000
6    101   301   301   301   1000    1000  1000   1000
7    101   101   101   301   1000    1000  1000   1000
8    101   201   301   0     1000    1000  1000   0
9    101   301   0     0     1000    1000  0      0
....

I need to create one column to sum the column value(value1, value2, value3, value4) considering the columns code (code1, code2, code3, code4). The result should be like this:

key  code1 code2 code3 code4 value1 value2 value3 value4 sum_code_101 sum_code_201 sum_code_301
0    101   101   101   101   1000    1000  1000   1000     4000           0           0
1    101   101   101   201   1000    1000  1000   1000     3000           1000        0
2    101   101   201   201   1000    1000  1000   1000     2000           2000        0
3    101   201   201   201   1000    1000  1000   1000     1000           3000        0
4    101   201   201   301   1000    1000  1000   1000     1000           2000        1000
5    101   201   301   301   1000    1000  1000   1000     1000           1000        2000
6    101   301   301   301   1000    1000  1000   1000     1000           0           3000
7    101   101   101   301   1000    1000  1000   1000     3000           0           1000
8    101   201   301   0     1000    1000  1000   0        1000           1000        1000
9    101   301   0     0     1000    1000  0      0        1000           0           1000

As the real table has 25 different codes (101, 201, 301...) I need to create 25 columns to sum their values.

Any help will be very appreciated.

Body:
You could use case expressions:

select
    t.*,
    case when code1 = 101 then value1 else 0 end
        + case when code2 = 101 then value2 else 0 end
        + case when code3 = 101 then value3 else 0 end
        + case when code4 = 101 then value4 else 0 end
        as sum_code_101,
    case when code1 = 201 then value1 else 0 end
        + case when code2 = 201 then value2 else 0 end
        + case when code3 = 201 then value3 else 0 end
        + case when code4 = 201 then value4 else 0 end
        as sum_code_201,
    case when code1 = 301 then value1 else 0 end
        + case when code2 = 301 then value2 else 0 end
        + case when code3 = 301 then value3 else 0 end
        + case when code4 = 301 then value4 else 0 end
        as sum_code_301
from mytable t

You can shorten the syntax a little by unpivoting the rows wirth cross apply, and then using conditional aggregation:

select
    t.*,
    s.*
from mytable t
outer apply (
    select
        sum(case when code = 101 then val else 0 end) sum_code_101,
        sum(case when code = 201 then val else 0 end) sum_code_201,
        sum(case when code = 301 then val else 0 end) sum_code_301,
        sum(case when code = 401 then val else 0 end) sum_code_401
    from (values
        (t.code1, t.value1),
        (t.code2, t.value2),
        (t.code3, t.value3),
        (t.code4, t.value4)
    ) as x(code, val)
)  s


问:
Upload multiple images with node in s3 map problem
I'm struggling finding a solution to upload two files to s3. I can upload one file with multer and I have learnt how to do it, but when I try to do a map inside all files in the formdata and upload each file, I push into an array each location URL which is the one I save in my database. Then I try to print each url but for my surprise they are print inside the if statement but not when I save it in the database outside the if. Could it be for an asychronous problem?.
Thanks.</p>

```<code>tournamentsCtrl.createTournament = async (req, res) => {
    var files_upload = []
    if (req.files) {
        aws.config.setPromisesDependency();
        aws.config.update({
            accessKeyId: process.env.AWS_ACCESS_KEY_ID,
            secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
            //region: process.env.REGION
        });
        const s3 = new aws.S3();
        req.files.map((item) => {
            var params = {
                ACL: 'public-read',
                Bucket: process.env.AWS_BUCKET_NAME,
                Body: fs.createReadStream(item.path),
                Key: `tournament_img/${uuidv4()/* +req.file.originalname */}`
            };

            await s3.upload(params, (err, data) => {
                if (err) {
                    console.log('Error occured while trying to upload to S3 bucket', err);
                }
                if (data) {
                    fs.unlinkSync(item.path); // Empty temp folder
                    const locationUrl = data.Location;
                    files_upload.push(locationUrl);
                    console.log(files_upload)
                }
            });
        });
    }
    console.log(files_upload)
    const new_data = { ...JSON.parse(req.body.values), img_source: files_upload[0], info_url: files_upload[1] }
    console.log(new_data)
    const newUser = new Tournaments(new_data);
    newUser
        .save()
        .then(user => {
            res.json({ message: 'User created successfully', user });
        })
        .catch(err => {
            console.log('Error occured while trying to save to DB');
        });
};
</code>```

答:
This is a bad place to ask for code advice but something like the following</p>

```<code>function uploadFile(s3, element) {
    return new Promise((resolve, reject) => {
        let folder;
        if (element.fieldname.includes('img')) {
            folder = 'club_images'
        } else if (element.fieldname.inlcudes('poster')) {
            folder = 'poster_tournament'
        } else {
            folder = 'info_tournament'
        }
        const params = {
            ACL: 'public-read',
            Bucket: process.env.AWS_BUCKET_NAME,
            Body: fs.createReadStream(element.path),
            Key: `${folder + '/' + uuidv4() + element.fieldname}`
        };
        s3.upload(params, (err, data) => {
            if (err) {
                return reject(err);
            }

            if (data) {
                return fs.unlink(element.path, err=> {
                    if(err) {
                        console.error("Failed to unlink file", element.path);
                    }
                    return resolve({[element.fieldname]: data.Location});
                }); // Empty temp folder
            }
            return resolve();

        });
    })
}

tournamentsCtrl.createTournament = async (req, res) => {
    aws.config.setPromisesDependency();
    aws.config.update({
        accessKeyId: process.env.AWS_ACCESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
        //region: process.env.REGION
    });
    const s3 = new aws.S3();

    try {
        const uploadData = await Promise.all(req.files.map(element => uploadFile(s3, element)));
        const returnData = Object.assign({}, ...uploadData);
        console.log(Object.assign(JSON.parse(req.body.values), returnData));
    } catch(e) {
        console.error('Failed to upload file', e);
        return res.sendStatus(500);
    }

    const newUser = new Tournaments(Object.assign(JSON.parse(req.body.values), files_upload));
    console.log(newUser)
    try {
        const user = await newUser.save()
        res.json({message: 'User created successfully', user});
    } catch(e) {
        console.error('Error occured while trying to save to DB');
        return res.sendStatus(500);
    }
};
</code>```

Body:
I'm struggling finding a solution to upload two files to s3. I can upload one file with multer and I have learnt how to do it, but when I try to do a map inside all files in the formdata and upload each file, I push into an array each location URL which is the one I save in my database. Then I try to print each url but for my surprise they are print inside the if statement but not when I save it in the database outside the if. Could it be for an asychronous problem?.
Thanks.

tournamentsCtrl.createTournament = async (req, res) => {
    var files_upload = []
    if (req.files) {
        aws.config.setPromisesDependency();
        aws.config.update({
            accessKeyId: process.env.AWS_ACCESS_KEY_ID,
            secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
            //region: process.env.REGION
        });
        const s3 = new aws.S3();
        req.files.map((item) => {
            var params = {
                ACL: 'public-read',
                Bucket: process.env.AWS_BUCKET_NAME,
                Body: fs.createReadStream(item.path),
                Key: `tournament_img/${uuidv4()/* +req.file.originalname */}`
            };

            await s3.upload(params, (err, data) => {
                if (err) {
                    console.log('Error occured while trying to upload to S3 bucket', err);
                }
                if (data) {
                    fs.unlinkSync(item.path); // Empty temp folder
                    const locationUrl = data.Location;
                    files_upload.push(locationUrl);
                    console.log(files_upload)
                }
            });
        });
    }
    console.log(files_upload)
    const new_data = { ...JSON.parse(req.body.values), img_source: files_upload[0], info_url: files_upload[1] }
    console.log(new_data)
    const newUser = new Tournaments(new_data);
    newUser
        .save()
        .then(user => {
            res.json({ message: 'User created successfully', user });
        })
        .catch(err => {
            console.log('Error occured while trying to save to DB');
        });
};

Body:
This is a bad place to ask for code advice but something like the following

function uploadFile(s3, element) {
    return new Promise((resolve, reject) => {
        let folder;
        if (element.fieldname.includes('img')) {
            folder = 'club_images'
        } else if (element.fieldname.inlcudes('poster')) {
            folder = 'poster_tournament'
        } else {
            folder = 'info_tournament'
        }
        const params = {
            ACL: 'public-read',
            Bucket: process.env.AWS_BUCKET_NAME,
            Body: fs.createReadStream(element.path),
            Key: `${folder + '/' + uuidv4() + element.fieldname}`
        };
        s3.upload(params, (err, data) => {
            if (err) {
                return reject(err);
            }

            if (data) {
                return fs.unlink(element.path, err=> {
                    if(err) {
                        console.error("Failed to unlink file", element.path);
                    }
                    return resolve({[element.fieldname]: data.Location});
                }); // Empty temp folder
            }
            return resolve();

        });
    })
}

tournamentsCtrl.createTournament = async (req, res) => {
    aws.config.setPromisesDependency();
    aws.config.update({
        accessKeyId: process.env.AWS_ACCESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
        //region: process.env.REGION
    });
    const s3 = new aws.S3();

    try {
        const uploadData = await Promise.all(req.files.map(element => uploadFile(s3, element)));
        const returnData = Object.assign({}, ...uploadData);
        console.log(Object.assign(JSON.parse(req.body.values), returnData));
    } catch(e) {
        console.error('Failed to upload file', e);
        return res.sendStatus(500);
    }

    const newUser = new Tournaments(Object.assign(JSON.parse(req.body.values), files_upload));
    console.log(newUser)
    try {
        const user = await newUser.save()
        res.json({message: 'User created successfully', user});
    } catch(e) {
        console.error('Error occured while trying to save to DB');
        return res.sendStatus(500);
    }
};


问:
Extract Numeric and Special Characters Separately
I have column in a table with values stored as

```<code>Cost

499.00
£ 7.75
£ 7.75
250.00
£ 5.99
$ 6.05
</code>```

Now, I need to store these values to another table like

```<code>Currency     Cost
RS           499.00
£            7.75
£            7.75
RS           250.00
£            5.99
$            6.05
</code>```

Plz let me the Query how to do this....

答:
You could create a regex CLR assembly like this one and specify in your query what to match on.

Probably a bit more work than the other suggestions but you could re-use the assembly elsewhere should you need it.

Body:
I have column in a table with values stored as

Cost

499.00
£ 7.75
£ 7.75
250.00
£ 5.99
$ 6.05

Now, I need to store these values to another table like

Currency     Cost
RS           499.00
£            7.75
£            7.75
RS           250.00
£            5.99
$            6.05

Plz let me the Query how to do this....


问:
NodeJS installation to jenkins : npm not found
Maybe someone can tell me what I missed installing nodeJS to jenkins, because when I want to execute shell script npm update I get error npm: not found.

I installed jenkins nodejs plugin then added installer:

After I created job with prams:

What I need to do more, to have accessible npm in any jenkins job?

答:
Windows users, did you restart?

Do keep in mind that you need to restart active processes after installing npm.
During installation the folder of your npm.cmd is added to the PATH variable. However, active applications don't refresh their PATH variable automatically. That also holds for your active Jenkins service (and its child processes). They are still running with an old version of your PATH variable.

In other words, you need to restart the Jenkins service (or restart your entire system). Once restarted, Jenkins will have an updated PATH variable, and it will be able to find the npm.cmd processes and others.

What's wrong with using absolute paths?

Using the full path is not a solid solution. A package.json file can contain references to other cli processes (e.g. node, ng, react-scripts, npm-run-all,  ...). You will probably have similar issues there. There is no way to keep up and reference all of them with full paths.


问:
Django inline formsets - only save the first formset
I am trying to dynamically add formsets, but after submitting it save only the first record and ignore the rest.

I am new to django and don not know exactly if the issue in my django code or js code.

models.py

```<code>class PvSystem(models.Model):
    gm_name = models.CharField(max_length=60, blank=True, null=True)
    gm_email = models.CharField(max_length=60, blank=True, null=True)

class Institution(models.Model):
    name = models.CharField(max_length=60, blank=True, null=True)
    tax_card = models.CharField(max_length=15, blank=True, null=True)
    pvsystem = models.ForeignKey(PvSystem, on_delete=models.CASCADE,
    blank=True, null=True)

class OriginalInstitutions(models.Model):
    name = models.CharField(max_length=60, blank=True, null=True)
    tax_card = models.CharField(max_length=15, blank=True, null=True)
    pvsystem = models.ForeignKey(PvSystem, on_delete=models.CASCADE,
    blank=True, null=True)
</code>```

forms.py

```<code>class InstitutionForm(forms.ModelForm):
    name = forms.ChoiceField(choices=[])
    class Meta:
        model = Institution
        exclude = ()

    def __init__(self, *args, **kwargs):
        super(InstitutionForm, self).__init__(*args, **kwargs)
        cleans = OriginalInstitutions.objects.values_list('name', flat=True)
        self.fields['name'] = forms.ChoiceField(choices = [(name, name) for name in cleans])

class PvSystemForm(forms.ModelForm):
    class Meta:
        model = PvSystem
        exclude = ()

InstitutionFormSet = inlineformset_factory(PvSystem, Institution,
                                            form=InstitutionForm, extra=1)

</code>```

views.py

```<code>class PVSystemList(ListView):
    template_name = 'pvsystem/pvsystem_list.html'
    model = PvSystem

class PVSystemDelete(DeleteView):
    template_name = 'pvsystem/pvsystem_confirm_delete.html'
    model = PvSystem
    success_url = reverse_lazy('pvsystem-list')
class PVSystemCreate(CreateView):
    template_name = 'pvsystem/pvsystem_form.html'
    form_class = PvSystemForm
    success_url = '/'
class PVSystemInstitutionCreate(CreateView):
    template_name = 'pvsystem/pvsystem_form.html'
    fields = ['gm_name','gm_email']
    model = PvSystem
    success_url = reverse_lazy('pvsystem-list')

    def get_context_data(self, **kwargs):
        data = super(PVSystemInstitutionCreate, self).get_context_data(**kwargs)
        if self.request.POST:
            data['institute'] = InstitutionFormSet(self.request.POST)
        else:
            data['institute'] = InstitutionFormSet()
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        institute = context['institute']
        with transaction.atomic():
            self.object = form.save()

            if institute.is_valid():
                institute.instance = self.object
                institute.save()
        return super(PVSystemInstitutionCreate, self).form_valid(form)

class PVSystemUpdate(UpdateView):
    template_name = 'pvsystem/pvsystem_form.html'
    form_class = PvSystemForm
    success_url = '/'

class PVSystemInstitutionUpdate(UpdateView):
    template_name = 'pvsystem/pvsystem_form.html'
    model = PvSystem
    fields = ['gm_name','gm_email']
    success_url = reverse_lazy('pvsystem-list')

    def get_context_data(self, **kwargs):
        data = super(PVSystemInstitutionUpdate, self).get_context_data(**kwargs)
        if self.request.POST:
            data['institute'] = InstitutionFormSet(self.request.POST, instance=self.object)
        else:
            data['institute'] = InstitutionFormSet(instance=self.object)
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        institute = context['institute']
        with transaction.atomic():
            self.object = form.save()

            if institute.is_valid():
                institute.instance = self.object
                institute.save()
        return super(PVSystemInstitutionUpdate, self).form_valid(form)
</code>```

template

```<code>{% extends "base.html" %}
{% load static %}

{% block title %}{% endblock %}
{% block content %}

    <h3>FormSet example</h3>
<form id="myForm" action="" method="post">{% csrf_token %}
{{ institute.management_form }}
<div id="form_set">
    {{ form.as_p }}
    {% for form in institute.forms %}
        {{form.non_field_errors}}
            {{form.errors}}
        <table class='no_error'>
            {{ form }}
        </table>

    {% endfor %}

</div>
<input type="button" value="Add More" id="add_more">
<div id="empty_form" style="display:none">
    <table class='no_error'>
        {{ institute.empty_form }}
    </table>

</div>
<input type="submit" value="Save" id="save"/> <a href="{% url 'pvsystem-list' %}">back to the list</a>
</form>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="{% static 'formset/jquery.formset.js' %}"></script>
    <script type="text/javascript">
        $('#add_more').click(function() {
      var form_idx = $('#id_form-TOTAL_FORMS').val();
      $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
      $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1);
    });
    </script>

    <!-- <script type="text/javascript">
      $(function() {
        $('#myForm tbody tr').formset({
          addText: 'add family member',
          deleteText: 'remove',
          prefix: '{{ formset.prefix }}'
        });
      })
    </script> -->
{% endblock %}

</code>```

I expected the form will save all the record, but it did not.
what can i do to make it save all record after submitting?

答:
For me it worked with extra above 1

Like this:

```<code>ClassFormSet = inlineformset_factory(ClassA, ClassB,
                                             form=ClassForm, extra=2)
</code>```

Body:
I am trying to dynamically add formsets, but after submitting it save only the first record and ignore the rest.

I am new to django and don not know exactly if the issue in my django code or js code.

models.py

class PvSystem(models.Model):
    gm_name = models.CharField(max_length=60, blank=True, null=True)
    gm_email = models.CharField(max_length=60, blank=True, null=True)

class Institution(models.Model):
    name = models.CharField(max_length=60, blank=True, null=True)
    tax_card = models.CharField(max_length=15, blank=True, null=True)
    pvsystem = models.ForeignKey(PvSystem, on_delete=models.CASCADE,
    blank=True, null=True)

class OriginalInstitutions(models.Model):
    name = models.CharField(max_length=60, blank=True, null=True)
    tax_card = models.CharField(max_length=15, blank=True, null=True)
    pvsystem = models.ForeignKey(PvSystem, on_delete=models.CASCADE,
    blank=True, null=True)

forms.py

class InstitutionForm(forms.ModelForm):
    name = forms.ChoiceField(choices=[])
    class Meta:
        model = Institution
        exclude = ()

    def __init__(self, *args, **kwargs):
        super(InstitutionForm, self).__init__(*args, **kwargs)
        cleans = OriginalInstitutions.objects.values_list('name', flat=True)
        self.fields['name'] = forms.ChoiceField(choices = [(name, name) for name in cleans])

class PvSystemForm(forms.ModelForm):
    class Meta:
        model = PvSystem
        exclude = ()

InstitutionFormSet = inlineformset_factory(PvSystem, Institution,
                                            form=InstitutionForm, extra=1)

views.py

class PVSystemList(ListView):
    template_name = 'pvsystem/pvsystem_list.html'
    model = PvSystem

class PVSystemDelete(DeleteView):
    template_name = 'pvsystem/pvsystem_confirm_delete.html'
    model = PvSystem
    success_url = reverse_lazy('pvsystem-list')
class PVSystemCreate(CreateView):
    template_name = 'pvsystem/pvsystem_form.html'
    form_class = PvSystemForm
    success_url = '/'
class PVSystemInstitutionCreate(CreateView):
    template_name = 'pvsystem/pvsystem_form.html'
    fields = ['gm_name','gm_email']
    model = PvSystem
    success_url = reverse_lazy('pvsystem-list')

    def get_context_data(self, **kwargs):
        data = super(PVSystemInstitutionCreate, self).get_context_data(**kwargs)
        if self.request.POST:
            data['institute'] = InstitutionFormSet(self.request.POST)
        else:
            data['institute'] = InstitutionFormSet()
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        institute = context['institute']
        with transaction.atomic():
            self.object = form.save()

            if institute.is_valid():
                institute.instance = self.object
                institute.save()
        return super(PVSystemInstitutionCreate, self).form_valid(form)

class PVSystemUpdate(UpdateView):
    template_name = 'pvsystem/pvsystem_form.html'
    form_class = PvSystemForm
    success_url = '/'

class PVSystemInstitutionUpdate(UpdateView):
    template_name = 'pvsystem/pvsystem_form.html'
    model = PvSystem
    fields = ['gm_name','gm_email']
    success_url = reverse_lazy('pvsystem-list')

    def get_context_data(self, **kwargs):
        data = super(PVSystemInstitutionUpdate, self).get_context_data(**kwargs)
        if self.request.POST:
            data['institute'] = InstitutionFormSet(self.request.POST, instance=self.object)
        else:
            data['institute'] = InstitutionFormSet(instance=self.object)
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        institute = context['institute']
        with transaction.atomic():
            self.object = form.save()

            if institute.is_valid():
                institute.instance = self.object
                institute.save()
        return super(PVSystemInstitutionUpdate, self).form_valid(form)

template

{% extends "base.html" %}
{% load static %}

{% block title %}{% endblock %}
{% block content %}

FormSet example

<form id="myForm" action="" method="post">{% csrf_token %}
{{ institute.management_form }}

    {{ form.as_p }}
    {% for form in institute.forms %}
        {{form.non_field_errors}}
            {{form.errors}}

            {{ form }}

    {% endfor %}

<input type="button" value="Add More" id="add_more">

        {{ institute.empty_form }}

<input type="submit" value="Save" id="save"/> back to the list
</form>

{% endblock %}

I expected the form will save all the record, but it did not.
what can i do to make it save all record after submitting?

Body:
For me it worked with extra above 1

Like this:

ClassFormSet = inlineformset_factory(ClassA, ClassB,
                                             form=ClassForm, extra=2)


问:
(Python) Beautifull soup and encoding (utf-8, cp1252,ascii...)
Please help, I am so loosing nerves now.I am having this problems since I started learning Python. Always come to a same issue and no one online can give any valid answer

My code:

```<code>from bs4 import BeautifulSoup
import requests

page = requests.get(
    'https://forecast.weather.gov/MapClick.php?lat=34.05349000000007&lon=-118.24531999999999#.XswiwMCxWUk')
soup = BeautifulSoup(page.content, 'html.parser')
week = soup.find(id='seven-day-forecast-body')
items = week.find_all(class_='forecast-tombstone')

print(items[0].find(class_='period-name').get_text())
print(items[0].find(class_='short-desc').get_text())
print(items[0].find(class_='temp temp-high').get_text())

period_names = [item.find(class_='period-name').get_text() for item in items]
short_descp = [item.find(class_='short-desc').get_text() for item in items]
temp = [item.find(class_='temp temp-high').get_text() for item in items]
print(period_names)
print(short_descp)
print(temp)
</code>```

output :

```<code>[Running] python -u "c:\Users\dukasu\Documents\Python\test.py"
ThisAfternoon
Partly Sunny
High: 76 �F
Traceback (most recent call last):
  File "c:\Users\dukasu\Documents\Python\test.py", line 20, in <module>
    temp = [item.find(class_='temp temp-high').get_text() for item in items]
  File "c:\Users\dukasu\Documents\Python\test.py", line 20, in <listcomp>
    temp = [item.find(class_='temp temp-high').get_text() for item in items]
AttributeError: 'NoneType' object has no attribute 'get_text'

[Done] exited with code=1 in 0.69 seconds
</code>```

Issue is due to a utf-8 encoding (my PC is at cp1252), but how to solve it terminally (I think problem is cos it cant operate with degree symbol). There is a simple code in Python 2, but how to solve it in Python 3.xx. How to set encoding at start of the code and forget about this issue.
anp please pardon my english, it is not my native language.

答:
This turned out to be a simple issue.

OK changed but here is a printout:

```<code>[Running] python -u "c:\Users\dukasu\Documents\Python\test.py"
ThisAfternoon
Partly Sunny
High: 76 �F
['ThisAfternoon', 'Tonight', 'Saturday', 'SaturdayNight', 'Sunday', 'SundayNight', 'Monday', 'MondayNight', 'Tuesday']
['Partly Sunny', 'Patchy Fog', 'Patchy Fogthen MostlySunny', 'Patchy Fog', 'Patchy Fogthen PartlySunny', 'Patchy Fog', 'Patchy Fogthen MostlyCloudy', 'Mostly Cloudy', 'Partly Sunny']
['High: 76 �F', 'Low: 58 �F', 'High: 75 �F', 'Low: 59 �F', 'High: 80 �F', 'Low: 61 �F', 'High: 78 �F', 'Low: 61 �F', 'High: 77 �F']

[Done] exited with code=0 in 0.619 seconds
</code>```

How to print out degree symbol  ° ?

later I added

```<code>import sys
sys.stdout.reconfigure(encoding='utf-8')
</code>```

and print out :

```<code>High: 76 °F
</code>```

Body:
Please help, I am so loosing nerves now.I am having this problems since I started learning Python. Always come to a same issue and no one online can give any valid answer

My code:

from bs4 import BeautifulSoup
import requests

page = requests.get(
    'https://forecast.weather.gov/MapClick.php?lat=34.05349000000007&lon=-118.24531999999999#.XswiwMCxWUk')
soup = BeautifulSoup(page.content, 'html.parser')
week = soup.find(id='seven-day-forecast-body')
items = week.find_all(class_='forecast-tombstone')

print(items[0].find(class_='period-name').get_text())
print(items[0].find(class_='short-desc').get_text())
print(items[0].find(class_='temp temp-high').get_text())

period_names = [item.find(class_='period-name').get_text() for item in items]
short_descp = [item.find(class_='short-desc').get_text() for item in items]
temp = [item.find(class_='temp temp-high').get_text() for item in items]
print(period_names)
print(short_descp)
print(temp)

output :

[Running] python -u "c:\Users\dukasu\Documents\Python\test.py"
ThisAfternoon
Partly Sunny
High: 76 �F
Traceback (most recent call last):
  File "c:\Users\dukasu\Documents\Python\test.py", line 20, in <module>
    temp = [item.find(class_='temp temp-high').get_text() for item in items]
  File "c:\Users\dukasu\Documents\Python\test.py", line 20, in <listcomp>
    temp = [item.find(class_='temp temp-high').get_text() for item in items]
AttributeError: 'NoneType' object has no attribute 'get_text'

[Done] exited with code=1 in 0.69 seconds

Issue is due to a utf-8 encoding (my PC is at cp1252), but how to solve it terminally (I think problem is cos it cant operate with degree symbol). There is a simple code in Python 2, but how to solve it in Python 3.xx. How to set encoding at start of the code and forget about this issue.
anp please pardon my english, it is not my native language.

Body:
This turned out to be a simple issue.

OK changed but here is a printout:

[Running] python -u "c:\Users\dukasu\Documents\Python\test.py"
ThisAfternoon
Partly Sunny
High: 76 �F
['ThisAfternoon', 'Tonight', 'Saturday', 'SaturdayNight', 'Sunday', 'SundayNight', 'Monday', 'MondayNight', 'Tuesday']
['Partly Sunny', 'Patchy Fog', 'Patchy Fogthen MostlySunny', 'Patchy Fog', 'Patchy Fogthen PartlySunny', 'Patchy Fog', 'Patchy Fogthen MostlyCloudy', 'Mostly Cloudy', 'Partly Sunny']
['High: 76 �F', 'Low: 58 �F', 'High: 75 �F', 'Low: 59 �F', 'High: 80 �F', 'Low: 61 �F', 'High: 78 �F', 'Low: 61 �F', 'High: 77 �F']

[Done] exited with code=0 in 0.619 seconds

How to print out degree symbol  ° ?

later I added

import sys
sys.stdout.reconfigure(encoding='utf-8')

and print out :

High: 76 °F