问:
Correct use of polymorphism and inheritance for some logic
I have basic class:

```<code>@Entity
@Table(name = "data_model_query")
@Inheritance
@DiscriminatorColumn(name="query_type",
public abstract class Query {

    private String dmlQuery;

    private String ddlQuery;

    //getters and setters
}
</code>```

And two child. SimpleQuery:

```<code>@Entity
@DiscriminatorValue("SIMPLE")
public class SimpleQuery extends Query {

    private ConnectionInfo connectionInfo; //initialize via constructor or setter

    public Integer getConnectionId() {
        return connectionInfo.getId();
    }

}
</code>```

SummaryQuery:

```<code>@Entity
@DiscriminatorValue("COMPLEX")
public class SummaryQuery extends Query {

    private List<SimpleQuery> children;

}
</code>```

In some service, I want add some logic for validate sql query. I created method:

```<code>@Service
class SomeService {
    //some business logic
    @Autowired
    private final DataExtractorService dataExtractorService;

    private void validateQueries(Query query) {
        if (query instanceof SimpleQuery) {
            String sqlQuery = ((SimpleQuery) query).getSqlQuery();
            Integer connectionId = ((SimpleQuery) query).getConnectionId();
            //validate by sqlQuery and connectionId
            dataExtractorService.tryToextractOneRecord(connectionId , sqlQuery);
        } else {
            SummaryQuery summaryQuery = (SummaryQuery) query;
            List<SimpleQuery> children = ((SummaryQuery) query).getChildren();
            children.forEach(query -> dataExtractorService.tryToextractOneRecord(query.getConnectionId(), query.getSqlQuery());
        }
    }
}
</code>```

In this solution, I strongly dislike the use of if check, as well as the use of instanceof. What if I had more than two inheritors, the code would be too huge and I need to remember to add another if. This is not a OOP approach. How could this problem be solved?

EDIT:

Query validation is essentially executing it on the DB. For this you need ddlQuery and connectionId. To do this, you need a service for working with the database. I can't inject it in POJO classes, because of this I can't implement the validate() method

答:
This is an extension of Herber Marshall response.

I want to start saying that if your problem is:

This is not a OOP approach. How could this problem be solved?

Herber Marshall is the correct answer, covering basic use cases, to cover more complex case, we should start from there, making the code more complex.

The pattern suggested is very simple and elegant, but seems it can't be applied because in the validate method you require to use a service that can't be injected in your DTO (good practice).

As first step check if it is a good fit passing that service into the validate method as an argument (so, all your cases can be implemented using the same service/dependency). If that is true go for that solution.

In your code seems that all the cases (if branches) use the same service object to implement their logic, this response is for cases in which this doesn't apply, or you need different number of services for each branch.

Let's add another query type to make an example:

@Entity
@DiscriminatorValue("DIFFERENT")
public class DifferentQuery extends Query {

    private Something something; //initialize via constructor or setter

    public Integer getConnectionId() {
        return something.getConnectionInfo().getId();
    }

}
```

<p>And changing your validation logic as:</p>

<pre class="lang-java prettyprint-override"><code>@Service
class SomeService {
    //some business logic
    @Autowired
    private final DataExtractorService dataExtractorService;

    @Autowired
    private final SomeOtherService someOtherService;

    private void validateQueries(Query query) {
        if (query instanceof SimpleQuery) {
            String sqlQuery = ((SimpleQuery) query).getSqlQuery();
            Integer connectionId = ((SimpleQuery) query).getConnectionId();
            //validate by sqlQuery and connectionId
            dataExtractorService.tryToextractOneRecord(connectionId , sqlQuery);
        } else if (query instanceof SummaryQuery){
            SummaryQuery summaryQuery = (SummaryQuery) query;
            List<SimpleQuery> children = ((SummaryQuery) query).getChildren();
            children.forEach(query -> dataExtractorService.tryToextractOneRecord(query.getConnectionId(), query.getSqlQuery());
        }
        else {
             DifferentQuery dQuery = (DifferentQuery) query;
             String sqlQuery = someOtherService.retrieveSql(dQuery);
             dataExtractorService.tryToextractOneRecord(query.getConnectionId(), sql);
        }
    }
}
</code>```

In this case to be "more OOP" what we should do is using a mix of double dispatch, and visitor pattern.

As first thing we should have an interface to manage validation for all the types of queries:

interface QueryValidation {
    void validate(SimpleQuery query);
    void validate(SummaryQuery query);
    void validate(DifferentQuery query);
}
```

<p>This interface will be passed to the <code>validate</code> method added to your <code>Query</code> type:</p>

<pre class="lang-java prettyprint-override"><code>@Entity
@Table(name = "data_model_query")
@Inheritance
@DiscriminatorColumn(name="query_type",
public abstract class Query {

    private String dmlQuery;

    private String ddlQuery;

    //getters and setters

    public abstract void validate(QueryValidation validation);
}
</code>```

Your types extending query will use that service to implement the validate method:

public class SimpleQuery extends Query {

    private ConnectionInfo connectionInfo;

    public Integer getConnectionId() {
        return connectionInfo.getId();
    }

    @Override
    public boolean validate(QueryValidation validation) {  //  <----
        validation.validate(this);
    }

}
```

<p>In this way all your query types will need to have a validation, all of them implement <code>validate</code> in this way, so that if you forget to add a validation for a type in the <code>QueryValidation</code> interface, your code will not compile.</p>

<p>Then you will have to implement the <code>QueryValidation</code> interface and use it in your main service:</p>

<pre class="lang-java prettyprint-override"><code>class QueryValidationImpl implements QueryValidation{
    @Autowired
    private final DataExtractorService dataExtractorService;

    @Autowired
    private final SomeOtherService someOtherService;

    public void validate(SimpleQuery query) {
        String sqlQuery = query.getSqlQuery();
        Integer connectionId = ((SimpleQuery) query).getConnectionId();
        //validate by sqlQuery and connectionId
        dataExtractorService.tryToextractOneRecord(connectionId , sqlQuery);
    }
    public void validate(SummaryQuery query) {
        List<SimpleQuery> children = query.getChildren();
        children.forEach(query ->
        dataExtractorService.tryToextractOneRecord(query.getConnectionId(), query.getSqlQuery());
    }
    public void validate(DifferentQuery query){
        String sqlQuery = someOtherService.retrieveSql(query);
        dataExtractorService.tryToextractOneRecord(query.getConnectionId(), sql);
    }
}

@Service
class SomeService {
    //some business logic
    @Autowired
    private final QueryValidation queryValidation;

    private void validateQueries(Query query) {
       query.validate(queryValidation);
    }
}
</code>```

With this solution you avoid using the instanceof and all the if letting the compiler doing them for you.

I find this as an heavy solution, and required only for few cases.

Most of the times having if else if using instanceof is not so bad, and if you look to "newer" languages (kotlin, scala) they have sealed types that is another way to do it. It is what in functional programming is called "pattern matching" and there it is a good practice (but in FP you have also some useful tools provided by the lang to be safe and avoid boilerplate)

Watch out that you can use this only if you have a closed set of types (you know/are in control of all the classes extending Query), if you need them to be an open set (who use this can implement its own Query type and can't change the QueryValidation interface), you will need to make it more complex introducing generics in the query.

This is true also for the if else if way, if you want end users to add their own types of query, letting them implement the validation logic, you will require some other strategy.
I sometimes use to have a Map<Class, Logic> retrieving from the map the right Logic to apply, but this as some cons too but I think this is another topic.

What I suggest is use a solution that covers all the cases that you know now, because an entire book can be wrote to solve this kind of issues in a "generic" way.

Body:
I have basic class:

@Entity
@Table(name = "data_model_query")
@Inheritance
@DiscriminatorColumn(name="query_type",
public abstract class Query {

    private String dmlQuery;

    private String ddlQuery;

    //getters and setters
}

And two child. SimpleQuery:

@Entity
@DiscriminatorValue("SIMPLE")
public class SimpleQuery extends Query {

    private ConnectionInfo connectionInfo; //initialize via constructor or setter

    public Integer getConnectionId() {
        return connectionInfo.getId();
    }

}

SummaryQuery:

@Entity
@DiscriminatorValue("COMPLEX")
public class SummaryQuery extends Query {

    private List<SimpleQuery> children;

}

In some service, I want add some logic for validate sql query. I created method:

@Service
class SomeService {
    //some business logic
    @Autowired
    private final DataExtractorService dataExtractorService;

    private void validateQueries(Query query) {
        if (query instanceof SimpleQuery) {
            String sqlQuery = ((SimpleQuery) query).getSqlQuery();
            Integer connectionId = ((SimpleQuery) query).getConnectionId();
            //validate by sqlQuery and connectionId
            dataExtractorService.tryToextractOneRecord(connectionId , sqlQuery);
        } else {
            SummaryQuery summaryQuery = (SummaryQuery) query;
            List<SimpleQuery> children = ((SummaryQuery) query).getChildren();
            children.forEach(query -> dataExtractorService.tryToextractOneRecord(query.getConnectionId(), query.getSqlQuery());
        }
    }
}

In this solution, I strongly dislike the use of if check, as well as the use of instanceof. What if I had more than two inheritors, the code would be too huge and I need to remember to add another if. This is not a OOP approach. How could this problem be solved?

EDIT:

Query validation is essentially executing it on the DB. For this you need ddlQuery and connectionId. To do this, you need a service for working with the database. I can't inject it in POJO classes, because of this I can't implement the validate() method

Body:
This is an extension of Herber Marshall response.

I want to start saying that if your problem is:

This is not a OOP approach. How could this problem be solved?

Herber Marshall is the correct answer, covering basic use cases, to cover more complex case, we should start from there, making the code more complex.

The pattern suggested is very simple and elegant, but seems it can't be applied because in the validate method you require to use a service that can't be injected in your DTO (good practice).

As first step check if it is a good fit passing that service into the validate method as an argument (so, all your cases can be implemented using the same service/dependency). If that is true go for that solution.

In your code seems that all the cases (if branches) use the same service object to implement their logic, this response is for cases in which this doesn't apply, or you need different number of services for each branch.

Let's add another query type to make an example:

@Entity
@DiscriminatorValue("DIFFERENT")
public class DifferentQuery extends Query {

    private Something something; //initialize via constructor or setter

    public Integer getConnectionId() {
        return something.getConnectionInfo().getId();
    }

}

And changing your validation logic as:

@Service
class SomeService {
    //some business logic
    @Autowired
    private final DataExtractorService dataExtractorService;

    @Autowired
    private final SomeOtherService someOtherService;

    private void validateQueries(Query query) {
        if (query instanceof SimpleQuery) {
            String sqlQuery = ((SimpleQuery) query).getSqlQuery();
            Integer connectionId = ((SimpleQuery) query).getConnectionId();
            //validate by sqlQuery and connectionId
            dataExtractorService.tryToextractOneRecord(connectionId , sqlQuery);
        } else if (query instanceof SummaryQuery){
            SummaryQuery summaryQuery = (SummaryQuery) query;
            List<SimpleQuery> children = ((SummaryQuery) query).getChildren();
            children.forEach(query -> dataExtractorService.tryToextractOneRecord(query.getConnectionId(), query.getSqlQuery());
        }
        else {
             DifferentQuery dQuery = (DifferentQuery) query;
             String sqlQuery = someOtherService.retrieveSql(dQuery);
             dataExtractorService.tryToextractOneRecord(query.getConnectionId(), sql);
        }
    }
}

In this case to be "more OOP" what we should do is using a mix of double dispatch, and visitor pattern.

As first thing we should have an interface to manage validation for all the types of queries:

interface QueryValidation {
    void validate(SimpleQuery query);
    void validate(SummaryQuery query);
    void validate(DifferentQuery query);
}

This interface will be passed to the validate method added to your Query type:

@Entity
@Table(name = "data_model_query")
@Inheritance
@DiscriminatorColumn(name="query_type",
public abstract class Query {

    private String dmlQuery;

    private String ddlQuery;

    //getters and setters

    public abstract void validate(QueryValidation validation);
}

Your types extending query will use that service to implement the validate method:

public class SimpleQuery extends Query {

    private ConnectionInfo connectionInfo;

    public Integer getConnectionId() {
        return connectionInfo.getId();
    }

    @Override
    public boolean validate(QueryValidation validation) {  //  <----
        validation.validate(this);
    }

}

In this way all your query types will need to have a validation, all of them implement validate in this way, so that if you forget to add a validation for a type in the QueryValidation interface, your code will not compile.

Then you will have to implement the QueryValidation interface and use it in your main service:

class QueryValidationImpl implements QueryValidation{
    @Autowired
    private final DataExtractorService dataExtractorService;

    @Autowired
    private final SomeOtherService someOtherService;

    public void validate(SimpleQuery query) {
        String sqlQuery = query.getSqlQuery();
        Integer connectionId = ((SimpleQuery) query).getConnectionId();
        //validate by sqlQuery and connectionId
        dataExtractorService.tryToextractOneRecord(connectionId , sqlQuery);
    }
    public void validate(SummaryQuery query) {
        List<SimpleQuery> children = query.getChildren();
        children.forEach(query ->
        dataExtractorService.tryToextractOneRecord(query.getConnectionId(), query.getSqlQuery());
    }
    public void validate(DifferentQuery query){
        String sqlQuery = someOtherService.retrieveSql(query);
        dataExtractorService.tryToextractOneRecord(query.getConnectionId(), sql);
    }
}

@Service
class SomeService {
    //some business logic
    @Autowired
    private final QueryValidation queryValidation;

    private void validateQueries(Query query) {
       query.validate(queryValidation);
    }
}

With this solution you avoid using the instanceof and all the if letting the compiler doing them for you.

I find this as an heavy solution, and required only for few cases.

Most of the times having if else if using instanceof is not so bad, and if you look to "newer" languages (kotlin, scala) they have sealed types that is another way to do it. It is what in functional programming is called "pattern matching" and there it is a good practice (but in FP you have also some useful tools provided by the lang to be safe and avoid boilerplate)

Watch out that you can use this only if you have a closed set of types (you know/are in control of all the classes extending Query), if you need them to be an open set (who use this can implement its own Query type and can't change the QueryValidation interface), you will need to make it more complex introducing generics in the query.

This is true also for the if else if way, if you want end users to add their own types of query, letting them implement the validation logic, you will require some other strategy.
I sometimes use to have a Map<Class, Logic> retrieving from the map the right Logic to apply, but this as some cons too but I think this is another topic.

What I suggest is use a solution that covers all the cases that you know now, because an entire book can be wrote to solve this kind of issues in a "generic" way.


来源: stackexchange

问:
Get html from  and attach it to img
I have HTML:

```<code><table id='ansichttable' class='table appels'>
    <thead>
        <tr>
            <th class='bold'>Afbeelding</th>
            <th class="bold">Locatie</th>
            <th class='bold'>Groep</th>
            <th class='bold'>Soort</th>
            <th class='bold'>Bijzonderheden</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><a class="img" href="images/imagesfruit/boomgaard4.jpg"><img src="images/imagesfruit/thumbs/t-boomgaard4.jpg"/></a></td>
            <td valign="top">Tuin</td>
            <td valign="top">Appels</td>
            <td valign="top" class="titel">Dubbele Bellefleur</td>
            <td valign="top">Zoete stevige appel</td>
        </tr>
        <tr>
            <td><a class="img" href="images/imagesfruit/boomgaard4.jpg"><img src="images/imagesfruit/thumbs/t-boomgaard4.jpg"/></a></td>
            <td valign="top">Tuin</td>
            <td valign="top">Appels</td>
            <td valign="top" class="titel">Dubbele Zoete Aagt</td>
            <td valign="top">Zoete stevige appel</td>
        </tr>
        <tr>
            <td><a href="images/imagesfruit/boomgaard4.jpg"><img src="images/imagesfruit/thumbs/t-boomgaard4.jpg"/></a></td>
            <td valign="top">Tuin</td>
            <td valign="top">Appels</td>
            <td valign="top" class="titel">Ellisons Orange</td>
            <td valign="top">Zoete stevige appel</td>
        </tr>
    </tbody>
</table>
</code>```

What I am trying to create is that jQuery gets the title from the: td class="titel"
and create at the a href="......" a title tag like this:

```<code><td><a href="images/imagesfruit/boomgaard4.jpg" titel="Ellisons Orange"><img src="images/imagesfruit/thumbs/t-boomgaard4.jpg"/></a></td>
<td valign="top">Tuin</td>
<td valign="top">Appels</td>
<td valign="top" class="titel">Ellisons Orange</td>
<td valign="top">Zoete stevige appel</td>
</code>```

I have tried the following :

```<code>$(document).ready(function(){
 var gettitle = $("td:eq(3)").html();
                 $("td a").attr("title", $('td.titel').text());
</code>```

And:

```<code>$("td a.img").attr("title", $('.titel').html());
</code>```

And:

```<code>$('table').each(function() {
  var title = $(this).find('td.titel').text();
  $(this).find('td a').attr('title', title);
 });
</code>```

All of them are working, but collecting all the titles from the table and attach them to all the images.

What I need is that jQuery collects the title and attach it to the image above the td where it gets the title. What am I doing wrong?

答:
This should work. You want to make sure you stay within context of "each" index:</p>

```<code>$('table tr').each(function(i,obj){
    $('td{0} a',this).attr('title',$('td.titel',this).text());
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get html from <td class"title"> and attach it to img

Body:
I have HTML:

            Afbeelding
            Locatie
            Groep
            Soort
            Bijzonderheden

            Tuin
            Appels
            Dubbele Bellefleur
            Zoete stevige appel

            Tuin
            Appels
            Dubbele Zoete Aagt
            Zoete stevige appel

            Tuin
            Appels
            Ellisons Orange
            Zoete stevige appel

What I am trying to create is that jQuery gets the title from the: td class="titel"
and create at the a href="......" a title tag like this:

Tuin
Appels
Ellisons Orange
Zoete stevige appel

I have tried the following :

$(document).ready(function(){
 var gettitle = $("td:eq(3)").html();
                 $("td a").attr("title", $('td.titel').text());

And:

$("td a.img").attr("title", $('.titel').html());

And:

$('table').each(function() {
  var title = $(this).find('td.titel').text();
  $(this).find('td a').attr('title', title);
 });

All of them are working, but collecting all the titles from the table and attach them to all the images.

What I need is that jQuery collects the title and attach it to the image above the td where it gets the title. What am I doing wrong?

Body:
This should work. You want to make sure you stay within context of "each" index:

$('table tr').each(function(i,obj){
    $('td{0} a',this).attr('title',$('td.titel',this).text());
});


问:
AttributeError: 'str' object has no attribute 'json'
I wrote little script on python 3.7 to receive actual browser version

Here is it:

```<code>import json

def json_open():
    file_json = open('/Users/user/PycharmProjects/Test/configuration.json')
    return json.load(file_json)

def get_last_version(browser_name):
    f = json_open()
    res = (f['global']['link_to_latest_browser_version'])
    last_version = repr(res.json()['latest']['client'][browser_name]['version'])
    #print(last_version[1:-1])
    return last_version[1:-1]
</code>```

Also, json file exists, but it does not matter now.

Received:

```<code>AttributeError: 'str' object has no attribute 'json'.
</code>```

In row

```<code>last_version = repr(res.json()['latest']['client'][browser_name]['version'])
</code>```

Please, tell me what is my mistake?

答:
Try this:

```<code>import json

FILEJSON = '/Users/user/PycharmProjects/Test/configuration.json'

def get_last_version(browser_name):
    with open(FILEJSON, 'r') as fson:
        res = json.load(fson)
    last_version = res['global']['link_to_latest_browser_version']\
                    ['latest']['client'][browser_name]['version'][1:-1]
    return last_version
</code>```

I think that the json_open function is unnecessary. Also take into account that the behavior of the json.load() method depends on the type of file you are reading.

ContentLicense: CC BY-SA 4.0

Body:
I wrote little script on python 3.7 to receive actual browser version

Here is it:

import json

def json_open():
    file_json = open('/Users/user/PycharmProjects/Test/configuration.json')
    return json.load(file_json)

def get_last_version(browser_name):
    f = json_open()
    res = (f['global']['link_to_latest_browser_version'])
    last_version = repr(res.json()['latest']['client'][browser_name]['version'])
    #print(last_version[1:-1])
    return last_version[1:-1]

Also, json file exists, but it does not matter now.

Received:

AttributeError: 'str' object has no attribute 'json'.

In row

last_version = repr(res.json()['latest']['client'][browser_name]['version'])

Please, tell me what is my mistake?

Body:
Try this:

import json

FILEJSON = '/Users/user/PycharmProjects/Test/configuration.json'

def get_last_version(browser_name):
    with open(FILEJSON, 'r') as fson:
        res = json.load(fson)
    last_version = res['global']['link_to_latest_browser_version']\
                    ['latest']['client'][browser_name]['version'][1:-1]
    return last_version

I think that the json_open function is unnecessary. Also take into account that the behavior of the json.load() method depends on the type of file you are reading.


问:
What is the most efficient (time, memory) way to add a 2D-horizontal- and a 2D-vertical-aligned boost::multi_array resulting in a 3D array?
I want to add two boost multi-arrays in C++.

The first challenge is the alignment of the two arrays. One of these arrays is vertically aligned and the other is horizontally aligned as shown in the figure below. They shall be added, resulting in a 3-dimensional array (see also below). The easiest/laziest way would be to duplicate the vertically aligned array along its y-axis until it has the same width as the horizontally aligned array. Additionally duplicating the horizontally aligned array along its x-axis until it has the same height as the vertically aligned array. Then I would need a possibility to add two 3-dimensionally boost multi-arrays.

The second challenge is, that adding boost multi-arrays is not natively supported by boost, or I am wrong on this point? I want to avoid for-loops and take advantage of the straight allocated memory which makes e.g. copy operations less time intensive.

Does anybody have a good recommendation to handle this quest?

答: After a lot of thoughts about it, I think the best solution will be to extend one of these 2d arrays to an 3d array. Then I can sum the 2d matrix slide-wise to the 3d matrix.</p>


问:
FHIR Coverage resource
I am working an a project to create FHIR Coverage resource for Patient ID search.

I am looking for examples of Coverage resource especially for medicare insurance. I tried a lot but could not find examples for Medicare.

Can someone please share some samples or provide any pointers.

答:
Thanks for the question. Are on the official FHIR chat on Zulip (chat.fhir.org)? We have a CARIN Consumer Directed Payer Data Exchange (aka CARIN Blue Button) IG stream there (https://chat.fhir.org/#narrow/stream/204607-CARIN-Blue.20Button.20IG) where this and similar questions are addressed.

As far as your question, for Coverage resource details regarding traditional Medicare insurance, currently you'd want to browse the STU3-based CMS Blue Button API 2.0 documentation at https://bluebutton.cms.gov/developers/#core-resources. I say "currently" because it is possible that at some point in time that API will move to the R4-based CARIN BB IG. Do note that the CMS Blue Button 2.0 API is the inspiration behind the CARIN BB IG.

Hope this helps.
-Amol Vyas (https://chat.fhir.org/#narrow/pm-with/192132-tech)

Title: FHIR Coverage resource


问:
How to shorten the Qt make process?
I have downloaded an open source Qt that target on Windows. Since I am using the VS2010 command prompt to do the installation, it automatically set the platform to msvc-2010. When I am trying to build using nmake, it took about 7-8 hours to complete the installation. During the process, I have notice that Qt is compiling the libraries which I don't need like javascript.

May I know how can I shorten the build process since I am focusing on desktop development?

答:
Take a look at jom.

jom is a clone of nmake to support the execution of multiple independent commands in parallel.
  It adds the -j command line switch similar to GNU make.

Title: How to shorten the Qt make process?


问:
Shift date for multiple commits

I am quite new with GIT and looking for advice. Accidentally I had set incorrect time and all my commits are with wrong time/date and I would like to shift commit times/dates (f.e +8 hours/ +10 days).
I have found solution for one commit but I was wondering whether it can be done for many commits in one branch. I have managed to figure out how to change date but I am lost with rebasing :

```<code>COMMITS=($(git rev-list $COM~..HEAD))
for COMMIT in "${COMMITS[@]}"
do
   COMMIT_DATE=$(git log $COMMIT -n1 --format=%aD)
   NEW_DATE=$(date -d "$COMMIT_DATE+30 days" -R)
   echo "I: $COMMIT FROM $COMMIT_DATE TO $NEW_DATE"
   GIT_COMMITTER_DATE="$NEW_DATE" GIT_AUTHOR_DATE="$NEW_DATE" git commit --amend --no-edit --date "NEW_DATE"
   ...... rebase command
done
</code>```

Can somebody advise me how to correctly rebase?

Thanks in advance

答:
The following will rebase the last 3 commits with the current time and date:</p>

```<code>NEW_DATE="$(date -R)"
NUM_COMMITS_TO_REBASE=3
GIT_SEQUENCE_EDITOR=: git rebase -i HEAD~${NUM_COMMITS_TO_REBASE} --exec "git commit --amend --date \"$NEW_DATE\""
</code>```

Title: Shift date for multiple commits

Body:
I am quite new with GIT and looking for advice. Accidentally I had set incorrect time and all my commits are with wrong time/date and I would like to shift commit times/dates (f.e +8 hours/ +10 days).
I have found solution for one commit but I was wondering whether it can be done for many commits in one branch. I have managed to figure out how to change date but I am lost with rebasing :

COMMITS=($(git rev-list $COM~..HEAD))
for COMMIT in "${COMMITS[@]}"
do
   COMMIT_DATE=$(git log $COMMIT -n1 --format=%aD)
   NEW_DATE=$(date -d "$COMMIT_DATE+30 days" -R)
   echo "I: $COMMIT FROM $COMMIT_DATE TO $NEW_DATE"
   GIT_COMMITTER_DATE="$NEW_DATE" GIT_AUTHOR_DATE="$NEW_DATE" git commit --amend --no-edit --date "NEW_DATE"
   ...... rebase command
done

Can somebody advise me how to correctly rebase?

Thanks in advance

Body:
The following will rebase the last 3 commits with the current time and date:

NEW_DATE="$(date -R)"
NUM_COMMITS_TO_REBASE=3
GIT_SEQUENCE_EDITOR=: git rebase -i HEAD~${NUM_COMMITS_TO_REBASE} --exec "git commit --amend --date \"$NEW_DATE\""


问:
How do I remove a part of an URL using regex in Python?
I have an a list of URL that looks like this:

'https://www.superpopgadget.com/collections/best-sellers/products/sushi-roll-bazooka?Ffbclid=IwAR3WfVizYJF0RCP2AsSoulLjJK2_OUwQZ0Y1eep_b3Einm1XNJbcF_K3wYI'

I wanna scrape it to just get:
'https://www.superpopgadget.com/collections/best-sellers/products/sushi-roll-bazooka'

答:
Not sure if there is any other more efficient method but this might work fine:

(.+)\?(.+)

It matches in the first group everything before the character ? and the second group is everything after it. What you need is the first group.

Example in Regex101


问:
AWS Dead Letter Queue Cloudwatch alarm every time a message is added
I want to trigger a AWS cloudwatch alarm every time a message is added to my DLQ. I am using cloud formation to deploy my sqs/dlq resource and I can't figure out how to configure this type of alarm.

答:
You need to use NumberOfMessagesSent when configuring the alarm. See the refernce in CloudFormation: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudwatch-alarm.html Here is my solution. This will raise an alarm for each message, but the alarm state will not clear if errors keep occurring in your period. If the alarm state doesn't clear, it will prevent the future notifications. So I wouldn't make the period too long.

Also note, that if you are not manually adding the message to the queue then you will need another solution.

AWS Documentation:
If you send a message to a dead-letter queue manually, it is captured by the NumberOfMessagesSent metric. However, if a message is sent to a dead-letter queue as a result of a failed processing attempt, it isn't captured by this metric. Thus, it is possible for the values of NumberOfMessagesSent and NumberOfMessagesReceived to be different.

A solution is outlined in this question which is more vague but similar  Configure SQS Dead letter Queue to raise a cloud watch alarm on receiving a message

```<code>DLQthresholdAlarm:
 Type: AWS::CloudWatch::Alarm
    Properties:
      AlarmDescription: "Alarm dlq messages when we have 1 or more failed messages in 10 minutes"
      Namespace: "AWS/SQS"
      MetricName: "NumberOfMessagesSent"
      Dimensions:
        - Name: "QueueName"
          Value:
            Fn::GetAtt:
              - "MyDeadLetterQueue"
              - "QueueName"
      Statistic: "Sum"
      Period: 300
      DatapointsToAlarm: 1
      EvaluationPeriods: 2
      Threshold: 1
      ComparisonOperator: "GreaterThanOrEqualToThreshold"
      AlarmActions:
        - !Ref MyAlarmTopic
</code>```

Body:
You need to use NumberOfMessagesSent when configuring the alarm. See the refernce in CloudFormation: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudwatch-alarm.html Here is my solution. This will raise an alarm for each message, but the alarm state will not clear if errors keep occurring in your period. If the alarm state doesn't clear, it will prevent the future notifications. So I wouldn't make the period too long.

Also note, that if you are not manually adding the message to the queue then you will need another solution.

AWS Documentation:
If you send a message to a dead-letter queue manually, it is captured by the NumberOfMessagesSent metric. However, if a message is sent to a dead-letter queue as a result of a failed processing attempt, it isn't captured by this metric. Thus, it is possible for the values of NumberOfMessagesSent and NumberOfMessagesReceived to be different.

A solution is outlined in this question which is more vague but similar  Configure SQS Dead letter Queue to raise a cloud watch alarm on receiving a message

DLQthresholdAlarm:
 Type: AWS::CloudWatch::Alarm
    Properties:
      AlarmDescription: "Alarm dlq messages when we have 1 or more failed messages in 10 minutes"
      Namespace: "AWS/SQS"
      MetricName: "NumberOfMessagesSent"
      Dimensions:
        - Name: "QueueName"
          Value:
            Fn::GetAtt:
              - "MyDeadLetterQueue"
              - "QueueName"
      Statistic: "Sum"
      Period: 300
      DatapointsToAlarm: 1
      EvaluationPeriods: 2
      Threshold: 1
      ComparisonOperator: "GreaterThanOrEqualToThreshold"
      AlarmActions:
        - !Ref MyAlarmTopic


问:
can't make a programm that counts nonterminal nodes in a tree
This is a syntactic tree and it looks like this in the form of code

My program is supposed to count the number of non-terminal nodes on that tree. The idea is that every tree is a 2 tuple. On the first position stands the mother node as a string and on the second position stands either a string if there is a terminal node or a list with daughter trees of the mother node. They are recursive. The program should count the number of nonterminal nodes.
so the result should just be a number of nonterminal nodes, e.g. 9.

So far as I have understood, I should do this using recursion. But there are some things that I fail to do correctly to make my programm work. My code is:

```<code>tuple_list = []
second_tuple_elements = [a_tuple[1] for a_tuple in tuple_list]
print(second_tuple_elements)
def nonterminal(count):

    if second_tuple_elements == type(""):

        return 1

    if second_tuple_elements == type([]):
        for element in list:
            if element == type (""):
                return 1
            nonterminal = second_tuple_elements + element
</code>```

答:
Here's a solution: </p>

```<code>def count_nodes(tree):
    count = 0

    if isinstance(tree, str):
        return 0
    node, rest = tree
    count +=1
    for subtree in rest:
        count += count_nodes(subtree)

    return count
</code>```

Body:
This is a syntactic tree and it looks like this in the form of code

My program is supposed to count the number of non-terminal nodes on that tree. The idea is that every tree is a 2 tuple. On the first position stands the mother node as a string and on the second position stands either a string if there is a terminal node or a list with daughter trees of the mother node. They are recursive. The program should count the number of nonterminal nodes.
so the result should just be a number of nonterminal nodes, e.g. 9.

So far as I have understood, I should do this using recursion. But there are some things that I fail to do correctly to make my programm work. My code is:

tuple_list = []
second_tuple_elements = [a_tuple[1] for a_tuple in tuple_list]
print(second_tuple_elements)
def nonterminal(count):

    if second_tuple_elements == type(""):

        return 1

    if second_tuple_elements == type([]):
        for element in list:
            if element == type (""):
                return 1
            nonterminal = second_tuple_elements + element

Body:
Here's a solution:

def count_nodes(tree):
    count = 0

    if isinstance(tree, str):
        return 0
    node, rest = tree
    count +=1
    for subtree in rest:
        count += count_nodes(subtree)

    return count


问:
AWS Gateway calling AWS Lambda Java Function receives null body
I am implementing an aws lambda function coded in java using the aws-lambda-java-events library. For troubleshooting purpose I am for now just trying to respond back with the same request body

```<code>public class LambdaFunctionHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
    @Override
    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
        return new APIGatewayProxyResponseEvent().withBody(input.getBody());
    }
}
</code>```

I have defined the above lambda function and an api gateway but I get the input.getBody as null. The output of the lambda function is an empty json object

```<code>{}
</code>```

I tested this through the AWS lambda test console. The execution succeeds and the output is as above.
The api gateway integration request is configured to call the above lambda function on a POST method.

Below are my queries

How do I get the aws test event json as part of the APIGatewayProxyRequestEvent getBody() string?

How do I get the request body passed to the API Gateway POST method in the APIGatewayProxyRequestEvent getBody() string variable? Do I need to define a mapping template? If so how should it look like (I made multiple attempts but with no success)

The request body I want to pass to the API gateway POST method through POSTMAN is

```<code>{
    "question":"Hello, how are you doing?"
}
</code>```

Thanks!

答:
I tried the same. The code I used was

```<code>public class LambdaFunctionHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {

    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent apiGatewayProxyRequestEvent,
            Context context) {
        return new APIGatewayProxyResponseEvent().withBody(apiGatewayProxyRequestEvent.getBody());
    }
}
</code>```

I guess you are testing from the AWS console directly. You cannot test an event-triggered lambda directly.

You have to create the test with "Amazon API Gateway Proxy" event as shown below.

And pass the request body as part of the parameters.

With these inputs, I got the expected output.

Body:
I am implementing an aws lambda function coded in java using the aws-lambda-java-events library. For troubleshooting purpose I am for now just trying to respond back with the same request body

public class LambdaFunctionHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
    @Override
    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
        return new APIGatewayProxyResponseEvent().withBody(input.getBody());
    }
}

I have defined the above lambda function and an api gateway but I get the input.getBody as null. The output of the lambda function is an empty json object

{}

I tested this through the AWS lambda test console. The execution succeeds and the output is as above.
The api gateway integration request is configured to call the above lambda function on a POST method.

Below are my queries

How do I get the aws test event json as part of the APIGatewayProxyRequestEvent getBody() string?

How do I get the request body passed to the API Gateway POST method in the APIGatewayProxyRequestEvent getBody() string variable? Do I need to define a mapping template? If so how should it look like (I made multiple attempts but with no success)

The request body I want to pass to the API gateway POST method through POSTMAN is

{
    "question":"Hello, how are you doing?"
}

Thanks!

Body:
I tried the same. The code I used was

public class LambdaFunctionHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {

    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent apiGatewayProxyRequestEvent,
            Context context) {
        return new APIGatewayProxyResponseEvent().withBody(apiGatewayProxyRequestEvent.getBody());
    }
}

I guess you are testing from the AWS console directly. You cannot test an event-triggered lambda directly.

You have to create the test with "Amazon API Gateway Proxy" event as shown below.

And pass the request body as part of the parameters.

With these inputs, I got the expected output.


问:
how to update state in mockstore in ngrx unit testing?
I have a object defined as:

obj:{
  name:"string",
  system:"string"
}
```

<p>however I am trying to update the value in mockstore as:</p>

<pre class="lang-js prettyprint-override"><code>store.setState({
  name:"Rose",
  system:"Updated Dummy"
});
store.refreshState();
fixture.detectChanges();
</code>```

but the value  is not updating. How can I update the value and then verify that it has been updated as a part of unit testing?

答:
store.setState updates the whole state. Therefore you need to use its feature name too to repeat the real store structure.

const featureSelector = createFeatureSelector('FEATURE_NAME_IS_HERE');

store.setState({
  FEATURE_NAME_IS_HERE: { // <- adding the feature state.
    name:"Rose",
    system:"Updated Dummy"
  },
});
store.refreshState();
fixture.detectChanges();
```

If you use nested reducers - then you need to nest the object to de desired child.

Body:
I have a object defined as:

obj:{
  name:"string",
  system:"string"
}

however I am trying to update the value in mockstore as:

store.setState({
  name:"Rose",
  system:"Updated Dummy"
});
store.refreshState();
fixture.detectChanges();

but the value  is not updating. How can I update the value and then verify that it has been updated as a part of unit testing?

Body:
store.setState updates the whole state. Therefore you need to use its feature name too to repeat the real store structure.

const featureSelector = createFeatureSelector('FEATURE_NAME_IS_HERE');

store.setState({
  FEATURE_NAME_IS_HERE: { // <- adding the feature state.
    name:"Rose",
    system:"Updated Dummy"
  },
});
store.refreshState();
fixture.detectChanges();

If you use nested reducers - then you need to nest the object to de desired child.


问:
I used Joins same table (self join) with having count. But the results are not as expected. I am using Oracle database
I tried to run the below query. I want all the data in column rp_num to be in the column rp_num_group. And also i want all the data of the column rp_num which is having count more than one (more than one count in std_id, rp_fam,  rn, rp_id) to be in the column std_id_group. But with my query i get the data which is having count more than 1 in both the columns rp_num_group and std_id_group. Kindly suggest the right way to use the joins to get the correct result.

for example, if my table is like below:

std_id      rn      rp_id       rp_fam      rp_num

1234        1234    1           abc         a12
1234        1235    1           abc         a34
1234        1236    1           xyz         a56
1244        1246    2           xyz         234
1244        1245    2           hgf         z65
1254        1456    2           hgf         z78
```

<p>I would expect my result to be:</p>

<pre class="lang-none prettyprint-override"><code>std_id      rp_num_group        std_id_group
1234        a12 a34 a56          a12:abc  a34:abc
1244        234 265 z78          z65:hgf  z78:hgf
</code>```

But my result is like below:

std_id      rp_num_group        std_id_group
1234        a12 a34            a12:abc  a34:abc
1244        z65 z78            z65:hgf  z78:hgf
```

```     SELECT DISTINCT rrpn.std_id,
                          Stringagg(rrpn.rp_num)
                          over (
                            PARTITION BY tmta.rp_id,tmta.rn,tmta.std_id
                            ORDER BY Nlssort(tmta.mta, 'NLS_SORT=BINARY_CI') ROWS
                          BETWEEN unbounded
                          preceding AND unbounded following ) AS rp_num_group,
                            Stringagg_distinct(rrpn3.rp_num||':'||rrpn3.rp_fam )
                          over (
                            PARTITION BY rrpn3.std_id, rrpn3.rn, rrpn3.rp_id
                            ORDER BY Nlssort(rrpn3.rp_num, 'NLS_SORT=BINARY_CI') ROWS
                          BETWEEN unbounded
                          preceding AND unbounded following ) AS std_id_group
        FROM   data_rrpn rrpn
                join data_rrpn rrpn3
                  ON rrpn3.std_id = rrpn.std_id
                AND rrpn3.rp_fam = rrpn.rp_fam
                AND rrpn3.rn = rrpn.rn
                AND rrpn3.rp_id = rrpn.rp_id
               join (SELECT std_id,
                            rp_fam,
                            rn,
                            rp_id,
                            Count(*)
                     FROM   data_rrpn
                     GROUP  BY std_id,
                               rp_fam,
                               rn,
                               rp_id
                     HAVING Count(*) > 1) rrpn2
                 ON rrpn3.std_id = rrpn2.std_id
                    AND rrpn3.rp_fam = rrpn2.rp_fam
                    AND rrpn3.rn = rrpn2.rn
                    AND rrpn3.rp_id = rrpn2.rp_id
        ORDER  BY rrpn.std_id;
```

答:
You very probably want to to group only on std_id, rp_fam, rp_id and not on RN (which is unique?).

Here you get a preview which rp_nums will be considered (GRP_CNT > 1):

```<code>select a.*,
count(*) over (partition by std_id, rp_fam, rp_id) grp_cnt
from tst a;

    STD_ID         RN      RP_ID RP_FA RP_NU    GRP_CNT
---------- ---------- ---------- ----- ----- ----------
      1234       1234          1 abc   a12            2
      1234       1235          1 abc   a34            2
      1234       1236          1 xyz   a56            1
      1244       1245          2 hgf   z65            1
      1244       1246          2 xyz   234            1
      1254       1456          2 hgf   z78            1
</code>```

The final query would be

```<code>with grp as
(
select a.*,
count(*) over (partition by std_id, rp_fam, rp_id) grp_cnt
from tst a
)
select STD_ID,
  listagg(RP_NUM, ' ') within group(order by RP_NUM) rp_num_group,
  listagg(case when grp_cnt > 1 then RP_NUM || ':' || RP_FAM end, ' ') within group(order by RP_NUM) std_id_group
from grp
group by STD_ID;
</code>```

giving the result:

```<code>STD_ID, RP_NUM_GROUP, STD_ID_GROUP
1234    a12 a34 a56   a12:abc a34:abc
1244    234 z65
1254    z78
</code>```

Not sur ehow you get the z65:hgf  z78:hgfin your sample result, but I think if there is some additional magic logic, you need only adjust the calculation of the GRP_CNT using the analytic function as proposed above.

Body:
I tried to run the below query. I want all the data in column rp_num to be in the column rp_num_group. And also i want all the data of the column rp_num which is having count more than one (more than one count in std_id, rp_fam,  rn, rp_id) to be in the column std_id_group. But with my query i get the data which is having count more than 1 in both the columns rp_num_group and std_id_group. Kindly suggest the right way to use the joins to get the correct result.

for example, if my table is like below:

std_id      rn      rp_id       rp_fam      rp_num

1234        1234    1           abc         a12
1234        1235    1           abc         a34
1234        1236    1           xyz         a56
1244        1246    2           xyz         234
1244        1245    2           hgf         z65
1254        1456    2           hgf         z78

I would expect my result to be:

std_id      rp_num_group        std_id_group
1234        a12 a34 a56          a12:abc  a34:abc
1244        234 265 z78          z65:hgf  z78:hgf

But my result is like below:

std_id      rp_num_group        std_id_group
1234        a12 a34            a12:abc  a34:abc
1244        z65 z78            z65:hgf  z78:hgf

     SELECT DISTINCT rrpn.std_id,
                          Stringagg(rrpn.rp_num)
                          over (
                            PARTITION BY tmta.rp_id,tmta.rn,tmta.std_id
                            ORDER BY Nlssort(tmta.mta, 'NLS_SORT=BINARY_CI') ROWS
                          BETWEEN unbounded
                          preceding AND unbounded following ) AS rp_num_group,
                            Stringagg_distinct(rrpn3.rp_num||':'||rrpn3.rp_fam )
                          over (
                            PARTITION BY rrpn3.std_id, rrpn3.rn, rrpn3.rp_id
                            ORDER BY Nlssort(rrpn3.rp_num, 'NLS_SORT=BINARY_CI') ROWS
                          BETWEEN unbounded
                          preceding AND unbounded following ) AS std_id_group
        FROM   data_rrpn rrpn
                join data_rrpn rrpn3
                  ON rrpn3.std_id = rrpn.std_id
                AND rrpn3.rp_fam = rrpn.rp_fam
                AND rrpn3.rn = rrpn.rn
                AND rrpn3.rp_id = rrpn.rp_id
               join (SELECT std_id,
                            rp_fam,
                            rn,
                            rp_id,
                            Count(*)
                     FROM   data_rrpn
                     GROUP  BY std_id,
                               rp_fam,
                               rn,
                               rp_id
                     HAVING Count(*) > 1) rrpn2
                 ON rrpn3.std_id = rrpn2.std_id
                    AND rrpn3.rp_fam = rrpn2.rp_fam
                    AND rrpn3.rn = rrpn2.rn
                    AND rrpn3.rp_id = rrpn2.rp_id
        ORDER  BY rrpn.std_id;

Body:
You very probably want to to group only on std_id, rp_fam, rp_id and not on RN (which is unique?).

Here you get a preview which rp_nums will be considered (GRP_CNT > 1):

select a.*,
count(*) over (partition by std_id, rp_fam, rp_id) grp_cnt
from tst a;

    STD_ID         RN      RP_ID RP_FA RP_NU    GRP_CNT
---------- ---------- ---------- ----- ----- ----------
      1234       1234          1 abc   a12            2
      1234       1235          1 abc   a34            2
      1234       1236          1 xyz   a56            1
      1244       1245          2 hgf   z65            1
      1244       1246          2 xyz   234            1
      1254       1456          2 hgf   z78            1

The final query would be

with grp as
(
select a.*,
count(*) over (partition by std_id, rp_fam, rp_id) grp_cnt
from tst a
)
select STD_ID,
  listagg(RP_NUM, ' ') within group(order by RP_NUM) rp_num_group,
  listagg(case when grp_cnt > 1 then RP_NUM || ':' || RP_FAM end, ' ') within group(order by RP_NUM) std_id_group
from grp
group by STD_ID;

giving the result:

STD_ID, RP_NUM_GROUP, STD_ID_GROUP
1234    a12 a34 a56   a12:abc a34:abc
1244    234 z65
1254    z78

Not sur ehow you get the z65:hgf  z78:hgfin your sample result, but I think if there is some additional magic logic, you need only adjust the calculation of the GRP_CNT using the analytic function as proposed above.


问:
How to pass Object in as string list in c# controller?
```<code>public class abcController : ApiController
{
    public IEnumerable<string> Get()
    {
        return new string[] { "A","B","C"};
    }

}
</code>```

I want to pass object containing name, id and image in string array..
How to accomplish this??
Please help me..
Also tell me how to access any specific element in this object..

答:
What you can do is use XML Serializing.

What XML Serializing does is it converts an object to XML format (which is a string) and then when you want to get the object back you can use XML Deserializer to Deserialize the XML string format to the original object.

for example, your object can be a class that contains a string name, int ID, string imagePath, let's call that class person.

The Class

```<code>[System.Serializable]
public class person
{
   public string name { get; set; }
   public int id { get; set; }
   public string imagePath { get; set; }
}
</code>```

Class Notes

Make sure that the class has the system.Serializable attribute.

Make sure that all the fields and properties you have are public (otherwise the program will crash !).

The XML Manager

Make sure that you have the namespace below otherwise you won't be able to use any of the methods listed

```<code>using System.Xml.Serialization;
</code>```

The XML_Manager class Which we'll put our methods in :-

```<code>public static class XML_Manager
    {
        // The Serializing Method
        public static string serializeObject<T>(T toSerialize)
        {
            // Create the result string variable
            string result = "";

            // Create a new StringWriter that will carry the serialization and dispose it as soon as it's done it's job
            using(StringWriter sw = new StringWriter())
            {
                // Create the serializer that will serialize the object of type (T)
                XmlSerializer xs = new XmlSerializer(typeof(T));

                // Serialize the object and put the result on the StringWriter (sw)
                xs.Serialize(sw, toSerialize);

                // Exctract the result from the StringWriter (sw) by converting it to string
                result = sw.ToString();
            }

            // Return the result
            return result;
        }

        // The Deserializing Method
        public static T deserializeObject<T>(string XmlString)
        {
            // Create the result variable of type (T)
            T Result;

            // Create a new StringReader that will carry the XmlString and dispose it as soon as it's done it's job
            using (StringReader sr = new StringReader(XmlString))
            {
                // Create the serializer that will deserialize the object of type (T)
                XmlSerializer xs = new XmlSerializer(typeof(T));

                // Deserialize the XmlString and extract the object
                Result = (T)xs.Deserialize(sr);
            }

            // Return the result
            return Result;
        }
    }
</code>```

Putting the scripts to work

```<code>            // Create a new person
            person p = new person();

            // Set the name
            p.name = "John";

            // Set the ID
            p.id = 2345;

            // Set the Image Path
            p.imagePath = "desktop";

            // the xml serialized string
            string xmlString = XML_Manager.serializeObject(p);

            // the deserialized person
            person deserializePerson = XML_Manager.deserializeObject<person>(xmlString);

            // Show the serialized string
            MessageBox.Show(xmlString);

            // Show the deserialized object
            MessageBox.Show($"Name: {deserializePerson.name}, Id: {deserializePerson.id}, Image Path: {deserializePerson.imagePath}");
</code>```

Body:
public class abcController : ApiController
{
    public IEnumerable<string> Get()
    {
        return new string[] { "A","B","C"};
    }

}

I want to pass object containing name, id and image in string array..
How to accomplish this??
Please help me..
Also tell me how to access any specific element in this object..

Body:
What you can do is use XML Serializing.

What XML Serializing does is it converts an object to XML format (which is a string) and then when you want to get the object back you can use XML Deserializer to Deserialize the XML string format to the original object.

for example, your object can be a class that contains a string name, int ID, string imagePath, let's call that class person.

The Class

[System.Serializable]
public class person
{
   public string name { get; set; }
   public int id { get; set; }
   public string imagePath { get; set; }
}

Class Notes

Make sure that the class has the system.Serializable attribute.

Make sure that all the fields and properties you have are public (otherwise the program will crash !).

The XML Manager

Make sure that you have the namespace below otherwise you won't be able to use any of the methods listed

using System.Xml.Serialization;

The XML_Manager class Which we'll put our methods in :-

public static class XML_Manager
    {
        // The Serializing Method
        public static string serializeObject<T>(T toSerialize)
        {
            // Create the result string variable
            string result = "";

            // Create a new StringWriter that will carry the serialization and dispose it as soon as it's done it's job
            using(StringWriter sw = new StringWriter())
            {
                // Create the serializer that will serialize the object of type (T)
                XmlSerializer xs = new XmlSerializer(typeof(T));

                // Serialize the object and put the result on the StringWriter (sw)
                xs.Serialize(sw, toSerialize);

                // Exctract the result from the StringWriter (sw) by converting it to string
                result = sw.ToString();
            }

            // Return the result
            return result;
        }

        // The Deserializing Method
        public static T deserializeObject<T>(string XmlString)
        {
            // Create the result variable of type (T)
            T Result;

            // Create a new StringReader that will carry the XmlString and dispose it as soon as it's done it's job
            using (StringReader sr = new StringReader(XmlString))
            {
                // Create the serializer that will deserialize the object of type (T)
                XmlSerializer xs = new XmlSerializer(typeof(T));

                // Deserialize the XmlString and extract the object
                Result = (T)xs.Deserialize(sr);
            }

            // Return the result
            return Result;
        }
    }

Putting the scripts to work

            // Create a new person
            person p = new person();

            // Set the name
            p.name = "John";

            // Set the ID
            p.id = 2345;

            // Set the Image Path
            p.imagePath = "desktop";

            // the xml serialized string
            string xmlString = XML_Manager.serializeObject(p);

            // the deserialized person
            person deserializePerson = XML_Manager.deserializeObject<person>(xmlString);

            // Show the serialized string
            MessageBox.Show(xmlString);

            // Show the deserialized object
            MessageBox.Show($"Name: {deserializePerson.name}, Id: {deserializePerson.id}, Image Path: {deserializePerson.imagePath}");


问:
Protractor can't perform click on
 tag
I'm tring to make an e2e test of my application but I can't perform click on search engine.
This is the example I want to try to "click" on the first element but protractor stuck on the image below :

The website that I'm taliking about is this : https://rent.decathlon.it/

The result is a timeout error, so the element is not clicked.

This is the protractor code :

```<code>import { AppPage } from './app.po';
import {browser, by, element, logging} from 'protractor';
import {SearchBoxWizard} from '../elements/searchbox_wizard';

describe('workspace-project App', () => {
  let page: AppPage;

  beforeEach(() => {
    page = new AppPage();
  });

  it('shoud open select item', async () => {
    await page.navigateTo();
    browser.sleep(500);
    const searchBoxWizardElements = new SearchBoxWizard();
    await searchBoxWizardElements.getLocationInput().click();
    await searchBoxWizardElements.getLocationInput().clear();
    await searchBoxWizardElements.getLocationInput().sendKeys('Milano');
    await browser.sleep(500);
    element(by.css(`.autocomplete-search > ul > li:nth-child(1) > span`)).click();
  });

  afterEach(async () => {
    // Assert that there are no errors emitted from the browser
    const logs = await browser.manage().logs().get(logging.Type.BROWSER);
    expect(logs).not.toContain(jasmine.objectContaining({
      level: logging.Level.SEVERE,
    } as logging.Entry));
  });
});
</code>```

Someone have an idea of why?

I'm using this stack :

Angular 8

protractor 5.6 or 7

Karma 4.1

Jasmin 3

Regards

EDIT :

I notice very strange behavior, If I check if body is displayed, protractor can't see it, this is the code...

```<code>  it('shoud open select item', async () => {
    await page.navigateTo();
    const searchBoxWizardElements = new SearchBoxWizard();
    const cookiePolicy = new CookiePolicy();
    await cookiePolicy.getAcceptCta().click();
    await searchBoxWizardElements.getLocationInput().click();
    await searchBoxWizardElements.getLocationInput().clear();
    await searchBoxWizardElements.getLocationInput().sendKeys('Milano').then(
      async _ => {
        await browser.sleep(2500);
        await element(by.css('body')).isDisplayed();
      });
  });
</code>```

I think it is something like "loosing" app focus... I don't know...

Have you got any idea?

Regards

答:
it is definitely a google api. I checked that. Requests are coming back from https://maps.googleapis.com/maps/api/place/js

You missed await in many places. You need to read about promises and way to handle is with await

browser.sleep needs await

.click() needs await

Title: Protractor can't perform click on <li> tag

Body:
I'm tring to make an e2e test of my application but I can't perform click on search engine.
This is the example I want to try to "click" on the first element but protractor stuck on the image below :

The website that I'm taliking about is this : https://rent.decathlon.it/

The result is a timeout error, so the element is not clicked.

This is the protractor code :

import { AppPage } from './app.po';
import {browser, by, element, logging} from 'protractor';
import {SearchBoxWizard} from '../elements/searchbox_wizard';

describe('workspace-project App', () => {
  let page: AppPage;

  beforeEach(() => {
    page = new AppPage();
  });

  it('shoud open select item', async () => {
    await page.navigateTo();
    browser.sleep(500);
    const searchBoxWizardElements = new SearchBoxWizard();
    await searchBoxWizardElements.getLocationInput().click();
    await searchBoxWizardElements.getLocationInput().clear();
    await searchBoxWizardElements.getLocationInput().sendKeys('Milano');
    await browser.sleep(500);
    element(by.css(`.autocomplete-search > ul > li:nth-child(1) > span`)).click();
  });

  afterEach(async () => {
    // Assert that there are no errors emitted from the browser
    const logs = await browser.manage().logs().get(logging.Type.BROWSER);
    expect(logs).not.toContain(jasmine.objectContaining({
      level: logging.Level.SEVERE,
    } as logging.Entry));
  });
});

Someone have an idea of why?

I'm using this stack :

Angular 8

protractor 5.6 or 7

Karma 4.1

Jasmin 3

Regards

EDIT :

I notice very strange behavior, If I check if body is displayed, protractor can't see it, this is the code...

  it('shoud open select item', async () => {
    await page.navigateTo();
    const searchBoxWizardElements = new SearchBoxWizard();
    const cookiePolicy = new CookiePolicy();
    await cookiePolicy.getAcceptCta().click();
    await searchBoxWizardElements.getLocationInput().click();
    await searchBoxWizardElements.getLocationInput().clear();
    await searchBoxWizardElements.getLocationInput().sendKeys('Milano').then(
      async _ => {
        await browser.sleep(2500);
        await element(by.css('body')).isDisplayed();
      });
  });

I think it is something like "loosing" app focus... I don't know...

Have you got any idea?

Regards


问:
How to merge two data streams in Alteryx
Alteryx

Table 1 is a google sheet file. It has x fields with primary key.
Every day to that table is added the weekday with the x data
For example:
Monday
Tuesday (is added on Tuesday) and so on.
My problem is that my workflow has a formula that does calculations with all the Weekdays.

Example:
Balance = All_Income - Monday - Tuesday - Wednesday - Thursday - Friday - Saturday - Sunday

But today for example, in the google sheet data I don't have the other weekdays except Monday and Tuesday, so I get the error "Unknown Variable" for Thursday.

I've inserted a Text Input and added all the weekdays.
I want to (Append maybe) these two data streams together so that I have all the weekdays there.
So if I run the calculations I have all the weekdays there.
Right now that formula works only on Sunday, when all weekdays are inserted as columns.
Any idea how to achieve this?
(p.s Creating the weekdays as columns in the google sheet with empty rows is not an option).

答:
I managed to do it by creating a Text Input with the same column names (headers) as the other Data Source and performing a union.

Apparently I needed to perform a IF statement to check all Weekdays if they exist and replace the null values with.

If anyone encounters the same error, feel free to contact for help :)


问:
How to wait for an action to complete?
I'm new to react and redux and have been exploring how it is different from angular.

I'm trying to do a simple login page and am not able to achieve what I want. Once I get the username and password from a login form, I submit it like below :

```<code>  submitHandler(e){
    e.preventDefault();
    var user = {
      name : this.state.username,
      password: this.state.password
    }
    this.props.authenticateUser(user);
    browserHistory.push('/home');
    this.setState({
      username:'',
      password:''
    })
  }
</code>```

Here, authenticateUser is a function inside my reducer (shown below) which checks from an already existing user's list and then the state with a property isAuthenticated :

```<code> case 'AUTHENTICATE_USER':
        var users = state.userslist;
        var payloadUser = action.payload;
        for (let i = 0; i < users.length; i++) {
            let user = users[i]
            if (user.name === payloadUser.name) {
                return {...state, isAuthenticated: true };
            }
        };
        return {...state, isAuthenticated: false };
</code>```

Now in Angular, I would just wait for this call to finish and check whether this value is true or false, and navigate to the home page using angular-router.

But how would I achieve the same in react. I am using react-router in my sample application.

I tried to check isAuthenticated in my submitHandler function right below where I call this.props.authenticateUser(user) , but the problem is , this.props.isAuthenticateUser is not updated and returns false, which I have set as the initialState in my reducer.

Please tell me how I can check isAuthenticated after the authenticateUser function has called so that I can proceed with my homepage routing. Do I have to use a promise and wait for the state to be updated by redux and then check it again ?? (I know react is a one way path and it doesn't work that way.)

Also if my authentication fails, how do I show an error panel below my login form. I think using a component for the error panel which takes in isAuthenticated as input and checking if false in order to show (ie. ngShow like in Angular.) But I'm afraid that will not work as well, since my state will not be updated just in time.

I know that the render function will be called with any change in state. But I just can't wrap my head around React clearly.

Edit: For brevity, I have not provided the action creators and the full reducer above rather shown only the switch case operation for authenticate user. My app follows the original redux architecture with actions, reducers, containers, components and such.

EDIT: Github link here

答:
I prefer code like this:

```<code>const mapStateToProps = (state) => {
  return {
      isAuthenticated: state.isAuthenticated
  }
}

class Dashboard extends PureComponent {
  render() {
    const { isAuthenticated } = this.props

    return (
      <div>
        { isAuthenticated ? (
          <div>
            <p>Hello</p>
          </div>
        ) : (
          Login()
        )}
      </div>
    )
  }
}
</code>```

Source: https://stackoverflow.com/a/56899814/3850405

Addition to the answer from @Nupur. componentWillReceiveProps() is considered unsafe and the method name now is: UNSAFE_componentWillReceiveProps()

https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops

Use componentDidUpdate() instead if you would like this approach, this method is not called for the initial render.

```<code>componentDidUpdate(prevProps) {
    if (this.props.isAuthenticated ) {
        //perform code here
    }
}
</code>```

https://reactjs.org/docs/react-component.html#componentdidupdate

Title: How to wait for an action to complete?

Body:
I'm new to react and redux and have been exploring how it is different from angular.

I'm trying to do a simple login page and am not able to achieve what I want. Once I get the username and password from a login form, I submit it like below :

  submitHandler(e){
    e.preventDefault();
    var user = {
      name : this.state.username,
      password: this.state.password
    }
    this.props.authenticateUser(user);
    browserHistory.push('/home');
    this.setState({
      username:'',
      password:''
    })
  }

Here, authenticateUser is a function inside my reducer (shown below) which checks from an already existing user's list and then the state with a property isAuthenticated :

 case 'AUTHENTICATE_USER':
        var users = state.userslist;
        var payloadUser = action.payload;
        for (let i = 0; i < users.length; i++) {
            let user = users[i]
            if (user.name === payloadUser.name) {
                return {...state, isAuthenticated: true };
            }
        };
        return {...state, isAuthenticated: false };

Now in Angular, I would just wait for this call to finish and check whether this value is true or false, and navigate to the home page using angular-router.

But how would I achieve the same in react. I am using react-router in my sample application.

I tried to check isAuthenticated in my submitHandler function right below where I call this.props.authenticateUser(user) , but the problem is , this.props.isAuthenticateUser is not updated and returns false, which I have set as the initialState in my reducer.

Please tell me how I can check isAuthenticated after the authenticateUser function has called so that I can proceed with my homepage routing. Do I have to use a promise and wait for the state to be updated by redux and then check it again ?? (I know react is a one way path and it doesn't work that way.)

Also if my authentication fails, how do I show an error panel below my login form. I think using a component for the error panel which takes in isAuthenticated as input and checking if false in order to show (ie. ngShow like in Angular.) But I'm afraid that will not work as well, since my state will not be updated just in time.

I know that the render function will be called with any change in state. But I just can't wrap my head around React clearly.

Edit: For brevity, I have not provided the action creators and the full reducer above rather shown only the switch case operation for authenticate user. My app follows the original redux architecture with actions, reducers, containers, components and such.

EDIT: Github link here

Body:
I prefer code like this:

const mapStateToProps = (state) => {
  return {
      isAuthenticated: state.isAuthenticated
  }
}

class Dashboard extends PureComponent {
  render() {
    const { isAuthenticated } = this.props

    return (
      <div>
        { isAuthenticated ? (
          <div>
            <p>Hello</p>
          </div>
        ) : (
          Login()
        )}
      </div>
    )
  }
}

Source: https://stackoverflow.com/a/56899814/3850405

Addition to the answer from @Nupur. componentWillReceiveProps() is considered unsafe and the method name now is: UNSAFE_componentWillReceiveProps()

https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops

Use componentDidUpdate() instead if you would like this approach, this method is not called for the initial render.

componentDidUpdate(prevProps) {
    if (this.props.isAuthenticated ) {
        //perform code here
    }
}

https://reactjs.org/docs/react-component.html#componentdidupdate


问:
Why does the LastPasswordSet property always change?
I try to get a LastPasswordSet datetime for a Windows local account "toto" with C#

This property value always change (millisecond or second).

Do you have any idea for fix it ? Do you have a same comportement ?

```<code>for (int i = 0; i < 100; i++)
{

    PrincipalContext context = new PrincipalContext(ContextType.Machine);
    UserPrincipal user = new UserPrincipal(context) { SamAccountName = "toto" };
    user = (UserPrincipal)new PrincipalSearcher(user).FindOne();
    Debug.WriteLine("User : " + user.LastPasswordSet.Value.ToString("dd/MM/yyyy HH:mm:ss.fff"));
}
</code>```

```<code>User : 01/06/2020 09:09:34.475
User : 01/06/2020 09:09:34.479
User : 01/06/2020 09:09:34.484
User : 01/06/2020 09:09:34.489
User : 01/06/2020 09:09:34.494
User : 01/06/2020 09:09:34.499
User : 01/06/2020 09:09:34.504
User : 01/06/2020 09:09:34.509
User : 01/06/2020 09:09:34.513
User : 01/06/2020 09:09:34.519
User : 01/06/2020 09:09:34.524
User : 01/06/2020 09:09:34.528
User : 01/06/2020 09:09:34.533
User : 01/06/2020 09:09:34.538
User : 01/06/2020 09:09:34.542
User : 01/06/2020 09:09:34.547
User : 01/06/2020 09:09:34.552
User : 01/06/2020 09:09:34.557
</code>```

Thanks for your answer.

How is it calculated PasswordAge ???

I wanted to use LastPasswordSet to find out if a password has changed but this data is not fixed and the comparison is not secure. By taking that milliseconds sometimes the second goes to the next.

Really strange that LastPasswordSet is not the data used to calculate PasswordAge and not vice versa

Hello i try this code but the property LastPasswordSet not exist

```<code>var user = new DirectoryEntry("WinNT://./toto");
var lastSet = user.LastPasswordSet.Value;
var lastSetNoMilliseconds = new DateTime(lastSet.Year, lastSet.Month, lastSet.Day, lastSet.Hour, lastSet.Minute, lastSet.Second, lastSet.Kind);
</code>```

答:
Windows doesn't actually expose any property that tells you when the password was last set. It does expose a property called PasswordAge, which you can see if you use DirectoryEntry (which is what UserPrincipal uses in the background anyway):

```<code>var user = new DirectoryEntry("WinNT://./toto");
Debug.WriteLine($"PasswordAge: {user.Properties["PasswordAge"][0]}");
</code>```

That PasswordAge value represents the number of seconds that have passed since the password was last changed. So if you want to convert that into the actual time that the password was changed, you have to subtract that value from the current time, which is what UserPrincipal will do for you when you access the LastPasswordSet property, as you can see in their code:

```<code>value = DateTime.UtcNow - new TimeSpan(0, 0, secondsLapsed);
</code>```

But since the PasswordAge only has seconds, that means that the millisecond value that you get comes from the current time.

So nothing is wrong. Just don't look at the millisecond value.

Update: If you are storing this value to compare later, you can copy the date without the milliseconds:

```<code>var lastSet = user.LastPasswordSet.Value;
var lastSetNoMilliseconds = new DateTime(lastSet.Year, lastSet.Month, lastSet.Day, lastSet.Hour, lastSet.Minute, lastSet.Second, lastSet.Kind);
</code>```

Body:
I try to get a LastPasswordSet datetime for a Windows local account "toto" with C#

This property value always change (millisecond or second).

Do you have any idea for fix it ? Do you have a same comportement ?

for (int i = 0; i < 100; i++)
{

    PrincipalContext context = new PrincipalContext(ContextType.Machine);
    UserPrincipal user = new UserPrincipal(context) { SamAccountName = "toto" };
    user = (UserPrincipal)new PrincipalSearcher(user).FindOne();
    Debug.WriteLine("User : " + user.LastPasswordSet.Value.ToString("dd/MM/yyyy HH:mm:ss.fff"));
}

User : 01/06/2020 09:09:34.475
User : 01/06/2020 09:09:34.479
User : 01/06/2020 09:09:34.484
User : 01/06/2020 09:09:34.489
User : 01/06/2020 09:09:34.494
User : 01/06/2020 09:09:34.499
User : 01/06/2020 09:09:34.504
User : 01/06/2020 09:09:34.509
User : 01/06/2020 09:09:34.513
User : 01/06/2020 09:09:34.519
User : 01/06/2020 09:09:34.524
User : 01/06/2020 09:09:34.528
User : 01/06/2020 09:09:34.533
User : 01/06/2020 09:09:34.538
User : 01/06/2020 09:09:34.542
User : 01/06/2020 09:09:34.547
User : 01/06/2020 09:09:34.552
User : 01/06/2020 09:09:34.557

Thanks for your answer.

How is it calculated PasswordAge ???

I wanted to use LastPasswordSet to find out if a password has changed but this data is not fixed and the comparison is not secure. By taking that milliseconds sometimes the second goes to the next.

Really strange that LastPasswordSet is not the data used to calculate PasswordAge and not vice versa

Hello i try this code but the property LastPasswordSet not exist

var user = new DirectoryEntry("WinNT://./toto");
var lastSet = user.LastPasswordSet.Value;
var lastSetNoMilliseconds = new DateTime(lastSet.Year, lastSet.Month, lastSet.Day, lastSet.Hour, lastSet.Minute, lastSet.Second, lastSet.Kind);

Body:
Windows doesn't actually expose any property that tells you when the password was last set. It does expose a property called PasswordAge, which you can see if you use DirectoryEntry (which is what UserPrincipal uses in the background anyway):

var user = new DirectoryEntry("WinNT://./toto");
Debug.WriteLine($"PasswordAge: {user.Properties["PasswordAge"][0]}");

That PasswordAge value represents the number of seconds that have passed since the password was last changed. So if you want to convert that into the actual time that the password was changed, you have to subtract that value from the current time, which is what UserPrincipal will do for you when you access the LastPasswordSet property, as you can see in their code:

value = DateTime.UtcNow - new TimeSpan(0, 0, secondsLapsed);

But since the PasswordAge only has seconds, that means that the millisecond value that you get comes from the current time.

So nothing is wrong. Just don't look at the millisecond value.

Update: If you are storing this value to compare later, you can copy the date without the milliseconds:

var lastSet = user.LastPasswordSet.Value;
var lastSetNoMilliseconds = new DateTime(lastSet.Year, lastSet.Month, lastSet.Day, lastSet.Hour, lastSet.Minute, lastSet.Second, lastSet.Kind);


问:
Which build tool is recommended with deno?
I've seen that deno does not anymore require package.json (supported by npm/yarn) to describe its dependencies.

But for build/run scripts, is package.json the proposed descriptor or is there any other build tool/descriptor format that better suits?

答:
Deno doesn't support package.json.

Currently, there's no built-in nor recommended build tool, but you can use any build tool of your preference: Make, npm scripts, etc.

There are some packages that aim to be a alternative to npm scripts for Deno, such as

velociraptor

denox


问:
How to move dataframe variable names to first row and add new variable names to multiple dataframes in a list?

library(purrr)
library(tibble)
library(dplyr)
```

<p>Starting list of dataframes</p>

```lst <- list(df1 = data.frame(X.1 = as.character(1:2),
                             heading = letters[1:2]),
            df2 =  data.frame(X.32 = as.character(3:4),
                              another.topic = paste("Line ", 1:2)))

lst
#> $df1
#>   X.1 heading
#> 1   1       a
#> 2   2       b
#>
#> $df2
#>   X.32 another.topic
#> 1    3       Line  1
#> 2    4       Line  2
```

<p>Expected "combined" dataframe, with  new consistent variable names, and old variable names in the first row of each constituent dataframe.</p>

```#>    id   h1            h2
#> 1 df1  X.1       heading
#> 2 df1    1             a
#> 3 df1    2             b
#> 4 df2 X.32 another.topic
#> 5 df2    3       Line  1
#> 6 df2    4       Line  2

```

<p><code>add_row</code> requires "Name-value pairs, passed on to tibble(). Values can be defined only for columns that already exist in .data and unset columns will get an NA value."</p>

<p>Which is what I think I have achieved with this:</p>

```df_nms <-
  map(lst, names) %>%
  map(set_names)

#> $df1
#>       X.1   heading
#>     "X.1" "heading"
#>
#> $df2
#>            X.32   another.topic
#>          "X.32" "another.topic"

```

<p>But I cannot tie up the last bit, using a purrr function to add the names to the head of each dataframe. I've tried numerous variations with <code>map2</code> and <code>pmap</code>  the closest I can get at present (if I treat <code>add_row</code> as a formula , prefixing it with <code>~</code> and remove the <code>.y</code> I get a new first row populated with NAs). I think I'm missing how to pass the name-value pairs to the add_row function.</p>

```map2(lst, df_nms, add_row(.x, .y, .before = 1)) %>%
  map(set_names, c("h1", "h2")) %>%
  map_dfr(bind_rows, .id = "id")
#> Error in add_row(.x, .y, .before = 1): object '.x' not found

```

A pointer to resolve this last step would be most appreciated.

答:
Not quite sure how to do this via purrr map functions, but here is an alternative,

```<code>library(dplyr)
bind_rows(lapply(lst, function(i){d1 <- as.data.frame(matrix(names(i), ncol = ncol(i)));
                                  rbind(d1, setNames(i, names(d1)))}), .id = 'id')

#   id   V1            V2
#1 df1  X.1       heading
#2 df1    1             a
#3 df1    2             b
#4 df2 X.32 another.topic
#5 df2    3       Line  1
#6 df2    4       Line  2
</code>```

Body:
library(purrr)
library(tibble)
library(dplyr)

Starting list of dataframes

lst <- list(df1 = data.frame(X.1 = as.character(1:2),
                             heading = letters[1:2]),
            df2 =  data.frame(X.32 = as.character(3:4),
                              another.topic = paste("Line ", 1:2)))

lst
#> $df1
#>   X.1 heading
#> 1   1       a
#> 2   2       b
#>
#> $df2
#>   X.32 another.topic
#> 1    3       Line  1
#> 2    4       Line  2

Expected "combined" dataframe, with  new consistent variable names, and old variable names in the first row of each constituent dataframe.

#>    id   h1            h2
#> 1 df1  X.1       heading
#> 2 df1    1             a
#> 3 df1    2             b
#> 4 df2 X.32 another.topic
#> 5 df2    3       Line  1
#> 6 df2    4       Line  2

add_row requires "Name-value pairs, passed on to tibble(). Values can be defined only for columns that already exist in .data and unset columns will get an NA value."

Which is what I think I have achieved with this:

df_nms <-
  map(lst, names) %>%
  map(set_names)

#> $df1
#>       X.1   heading
#>     "X.1" "heading"
#>
#> $df2
#>            X.32   another.topic
#>          "X.32" "another.topic"

But I cannot tie up the last bit, using a purrr function to add the names to the head of each dataframe. I've tried numerous variations with map2 and pmap  the closest I can get at present (if I treat add_row as a formula , prefixing it with ~ and remove the .y I get a new first row populated with NAs). I think I'm missing how to pass the name-value pairs to the add_row function.

map2(lst, df_nms, add_row(.x, .y, .before = 1)) %>%
  map(set_names, c("h1", "h2")) %>%
  map_dfr(bind_rows, .id = "id")
#> Error in add_row(.x, .y, .before = 1): object '.x' not found

A pointer to resolve this last step would be most appreciated.

Body:
Not quite sure how to do this via purrr map functions, but here is an alternative,

library(dplyr)
bind_rows(lapply(lst, function(i){d1 <- as.data.frame(matrix(names(i), ncol = ncol(i)));
                                  rbind(d1, setNames(i, names(d1)))}), .id = 'id')

#   id   V1            V2
#1 df1  X.1       heading
#2 df1    1             a
#3 df1    2             b
#4 df2 X.32 another.topic
#5 df2    3       Line  1
#6 df2    4       Line  2


问:
Hotfix on GitLab
I'm trying to understand GitLab's suggested flow on http://docs.gitlab.com/ee/workflow/gitlab_flow.html. But, I'm not really sure about this statement:

If you need to cherry-pick a commit with a hotfix it is common to
  develop it on a feature branch and merge it into master with a merge
  request, do not delete the feature branch. If master is good to go (it
  should be if you a practicing continuous delivery) you then merge it
  to the other branches.

Does it mean, there will be more than 1 commit in the master? For example, the first commit (actually merge request) is to test whether the fix is working, the second commit is when the first commit fails.

The other thing is, (given that we have a production branch) if we merge the hotfix into master, I think we have to deploy the other features on the master, isn't it? Otherwise, we do cherry pick the hotfix commits in the master into the production branch.

Actually the suggested flow is not as detail as another flow in http://nvie.com/posts/a-successful-git-branching-model/. So, it's a bit confusing.

答:
I experimented with the hotfix process in a test-hotfix repo available at https://github.com/oldsj/test-hotfix/commits/master

Basically as long as the hotfix branch is created from the prod branch it the process seems fairly straightforward, even if master is ahead of imp/prod.

Note: imp is what we refer to as "pre-production"

master (dev branch)

```<code>git init
echo "Hello wolrd" > hello.txt
git add -A .
git commit -m "add hello.txt"
git log
commit 66b1a08080f0db548da85471b4673c5a9f6d703f (HEAD -> master)

cat hello.txt
Hello wolrd

git checkout -b imp
git checkout -b prod
</code>```

Prod shows typo

```<code>cat hello.txt
Hello wolrd

git log
commit 66b1a08080f0db548da85471b4673c5a9f6d703f (HEAD -> prod, master, imp)
</code>```

Let's add some commits to master, ahead of prod

```<code>git checkout master
git log
commit 66b1a08080f0db548da85471b4673c5a9f6d703f (HEAD -> master, prod, imp)

echo "new stuff" >> newstuff.txt
git add -A .
git commit -m "add newstuff.txt"
git log
commit df1ca012262c26ab3a29d81b5cb6d46f6c1fc3cc (HEAD -> master)
commit 66b1a08080f0db548da85471b4673c5a9f6d703f (prod, imp)
</code>```

A user reported the typo in prod, let's hotfix by creating a new branch off of the prod branch:

```<code>git checkout prod
git log
commit 66b1a08080f0db548da85471b4673c5a9f6d703f (HEAD -> prod, imp)

git checkout -b hotfix
Switched to a new branch 'hotfix'
git log
commit 66b1a08080f0db548da85471b4673c5a9f6d703f (HEAD -> hotfix, prod, imp)

echo "Hello world" > hello.txt
git add -A .
git commit -m "fix typo"
git log
commit 1243123edc75e0abf349e1bb154d39c9f25dab2d (HEAD -> hotfix)

cat hello.txt
Hello world
</code>```

Cool our typo is fixed in the hotfix branch, lets merge to master and test in dev

```<code>git checkout master
git merge hotfix
git log
commit 2672d5059a55472132f02178c7f51d8b1af0f8ea (HEAD -> master)

> cat hello.txt
Hello world
</code>```

Looks good in dev! Lets merge to imp and prod

```<code>git checkout imp
git merge hotfix
git log
commit 1243123edc75e0abf349e1bb154d39c9f25dab2d (HEAD -> imp, hotfix)
cat hello.txt
Hello world

git checkout prod
git merge hotfix
git log
commit 1243123edc75e0abf349e1bb154d39c9f25dab2d (HEAD -> imp, hotfix)
cat hello.txt
Hello world

git branch -D hotfix
</code>```

Typo's fixed in prod after testing in lower environments by merging the "PR" to those environment branches
Now let's promote dev changes up (commit df1ca012262c26ab3a29d81b5cb6d46f6c1fc3cc)

```<code>git checkout master
git log
commit 2672d5059a55472132f02178c7f51d8b1af0f8ea (HEAD -> master, imp)
commit 1243123edc75e0abf349e1bb154d39c9f25dab2d (prod)
commit df1ca012262c26ab3a29d81b5cb6d46f6c1fc3cc
commit 66b1a08080f0db548da85471b4673c5a9f6d703f

git checkout imp
git merge master
git log
commit 2672d5059a55472132f02178c7f51d8b1af0f8ea (HEAD -> imp, master)
commit 1243123edc75e0abf349e1bb154d39c9f25dab2d (prod)
commit df1ca012262c26ab3a29d81b5cb6d46f6c1fc3cc
commit 66b1a08080f0db548da85471b4673c5a9f6d703f

cat newstuff.txt
new stuff
cat hello.txt
Hello world

git checkout prod
git merge imp
git log
commit 2672d5059a55472132f02178c7f51d8b1af0f8ea (HEAD -> prod, master, imp)
commit 1243123edc75e0abf349e1bb154d39c9f25dab2d
commit df1ca012262c26ab3a29d81b5cb6d46f6c1fc3cc
commit 66b1a08080f0db548da85471b4673c5a9f6d703f
</code>```

dev changes are now in imp and prod, along with the hotfix

```<code>cat hello.txt
Hello world
cat newstuff.txt
new stuff
</code>```

Title: Hotfix on GitLab

Body:
I experimented with the hotfix process in a test-hotfix repo available at https://github.com/oldsj/test-hotfix/commits/master

Basically as long as the hotfix branch is created from the prod branch it the process seems fairly straightforward, even if master is ahead of imp/prod.

Note: imp is what we refer to as "pre-production"

master (dev branch)

git init
echo "Hello wolrd" > hello.txt
git add -A .
git commit -m "add hello.txt"
git log
commit 66b1a08080f0db548da85471b4673c5a9f6d703f (HEAD -> master)

cat hello.txt
Hello wolrd

git checkout -b imp
git checkout -b prod

Prod shows typo

cat hello.txt
Hello wolrd

git log
commit 66b1a08080f0db548da85471b4673c5a9f6d703f (HEAD -> prod, master, imp)

Let's add some commits to master, ahead of prod

git checkout master
git log
commit 66b1a08080f0db548da85471b4673c5a9f6d703f (HEAD -> master, prod, imp)

echo "new stuff" >> newstuff.txt
git add -A .
git commit -m "add newstuff.txt"
git log
commit df1ca012262c26ab3a29d81b5cb6d46f6c1fc3cc (HEAD -> master)
commit 66b1a08080f0db548da85471b4673c5a9f6d703f (prod, imp)

A user reported the typo in prod, let's hotfix by creating a new branch off of the prod branch:

git checkout prod
git log
commit 66b1a08080f0db548da85471b4673c5a9f6d703f (HEAD -> prod, imp)

git checkout -b hotfix
Switched to a new branch 'hotfix'
git log
commit 66b1a08080f0db548da85471b4673c5a9f6d703f (HEAD -> hotfix, prod, imp)

echo "Hello world" > hello.txt
git add -A .
git commit -m "fix typo"
git log
commit 1243123edc75e0abf349e1bb154d39c9f25dab2d (HEAD -> hotfix)

cat hello.txt
Hello world

Cool our typo is fixed in the hotfix branch, lets merge to master and test in dev

git checkout master
git merge hotfix
git log
commit 2672d5059a55472132f02178c7f51d8b1af0f8ea (HEAD -> master)

> cat hello.txt
Hello world

Looks good in dev! Lets merge to imp and prod

git checkout imp
git merge hotfix
git log
commit 1243123edc75e0abf349e1bb154d39c9f25dab2d (HEAD -> imp, hotfix)
cat hello.txt
Hello world

git checkout prod
git merge hotfix
git log
commit 1243123edc75e0abf349e1bb154d39c9f25dab2d (HEAD -> imp, hotfix)
cat hello.txt
Hello world

git branch -D hotfix

Typo's fixed in prod after testing in lower environments by merging the "PR" to those environment branches
Now let's promote dev changes up (commit df1ca012262c26ab3a29d81b5cb6d46f6c1fc3cc)

git checkout master
git log
commit 2672d5059a55472132f02178c7f51d8b1af0f8ea (HEAD -> master, imp)
commit 1243123edc75e0abf349e1bb154d39c9f25dab2d (prod)
commit df1ca012262c26ab3a29d81b5cb6d46f6c1fc3cc
commit 66b1a08080f0db548da85471b4673c5a9f6d703f

git checkout imp
git merge master
git log
commit 2672d5059a55472132f02178c7f51d8b1af0f8ea (HEAD -> imp, master)
commit 1243123edc75e0abf349e1bb154d39c9f25dab2d (prod)
commit df1ca012262c26ab3a29d81b5cb6d46f6c1fc3cc
commit 66b1a08080f0db548da85471b4673c5a9f6d703f

cat newstuff.txt
new stuff
cat hello.txt
Hello world

git checkout prod
git merge imp
git log
commit 2672d5059a55472132f02178c7f51d8b1af0f8ea (HEAD -> prod, master, imp)
commit 1243123edc75e0abf349e1bb154d39c9f25dab2d
commit df1ca012262c26ab3a29d81b5cb6d46f6c1fc3cc
commit 66b1a08080f0db548da85471b4673c5a9f6d703f

dev changes are now in imp and prod, along with the hotfix

cat hello.txt
Hello world
cat newstuff.txt
new stuff


问:
JS apply function to all values of object
I have an object like this:

```<code>const player = {
  id: 123,
  country: 'GB',
  names: {
    key1: 'John Paul',
    key2: 'Johny Paul',
    key3: 'Johny-paul'
  }
}
</code>```

Then I want to apply a function to all names values:

```<code>const normalizeString = el => el.normalize('NFD').replace(/[\u0300-\u036f]/g, "");

const normalizedPlayer = {
    ...player,
    namesNormalized: Object.keys(player.names).map(k => ({[k]: normalizeString(player.names[k])}))
}
</code>```

But I get an array of objects instead of object:

```<code>{
  id: 123,
  country: 'GB',
  names: { key1: 'Jóhn Paul', key2: 'Johny Päul', key3: 'Johny-paul' },
  namesNormalized: [
    { key1: 'John Paul' },
    { key2: 'Johny Paul' },
    { key3: 'Johny paul' }
  ]
}
</code>```

I want namesNormalized like this:

```<code> {
    id: 123,
    country: 'GB',
    names: { key1: 'Jóhn Paul', key2: 'Johny Päul', key3: 'Johny-paul' },
    namesNormalized: {
     key1: 'John Paul',
     key2: 'Johny Paul',
     key3: 'Johny paul'
   }
 }
</code>```

答:
Another possibility is using Object.entries combined with Object.fromEntries.

This lets you avoid having to deal with reducing the properties as fromEntries turns the entries format back to an object.

From Entries works on pretty much all modern major browsers (Can I Use), but there is a shim for it if needed on older browsers.

const player = {
  id: 123,
  country: 'GB',
  names: {
    key1: 'Jóhn Paul',
    key2: 'Johny Päul',
    key3: 'Johny-paul'
  },
}
const normalizeString = el => el.normalize('NFD').replace(/[\u0300-\u036f]/g, "");
const normalizeObject = (obj) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, normalizeString(v)]))
const normalizedPlayer = {
  ...player,
  namesNormalized: normalizeObject(player.names)
}

console.log(normalizedPlayer)```

Body:
I have an object like this:

const player = {
  id: 123,
  country: 'GB',
  names: {
    key1: 'John Paul',
    key2: 'Johny Paul',
    key3: 'Johny-paul'
  }
}

Then I want to apply a function to all names values:

const normalizeString = el => el.normalize('NFD').replace(/[\u0300-\u036f]/g, "");

const normalizedPlayer = {
    ...player,
    namesNormalized: Object.keys(player.names).map(k => ({[k]: normalizeString(player.names[k])}))
}

But I get an array of objects instead of object:

{
  id: 123,
  country: 'GB',
  names: { key1: 'Jóhn Paul', key2: 'Johny Päul', key3: 'Johny-paul' },
  namesNormalized: [
    { key1: 'John Paul' },
    { key2: 'Johny Paul' },
    { key3: 'Johny paul' }
  ]
}

I want namesNormalized like this:

 {
    id: 123,
    country: 'GB',
    names: { key1: 'Jóhn Paul', key2: 'Johny Päul', key3: 'Johny-paul' },
    namesNormalized: {
     key1: 'John Paul',
     key2: 'Johny Paul',
     key3: 'Johny paul'
   }
 }