问:
Expose endpoint with native query without creating entity
I want to run some native queries and expose the results through endpoints, but I want to do this without having to create all the entities. I just want the data obtained from the database to be exposed as it comes.

I found some suggestions at: Create spring repository without entity

However, I was not able to make them work. I'm very new to Spring.

I tried Maciej Kowalski's solution like this:

Interface:

```<code>public interface CustomNativeRepository {
    Object runNativeQuery();
}
</code>```

Implementation:

```<code>@Repository
public class CustomNativeRepositoryImpl implements CustomNativeRepository {

    @Autowired
    private EntityManager entityManager;

    @Override
    public Object runNativeQuery() {
        return entityManager.createNativeQuery(
                """
                SELECT 1 as col1, 2 as col2, 3 as col3
                UNION ALL SELECT 4, 5, 6
                UNION ALL SELECT 7, 8, 9
                """
                )
        .getResultList();
    }
}
</code>```

However, no endpoints were exposed, as happens when you extend CrudRepository. Should I have done something else with CustomNativeRepositoryImpl? I don't know how to proceed.

I also tried Gagarwa's solution:

RootEntity:

```<code>@Entity
public class RootEntity {
    @Id
    private Integer id;
}
</code>```

RootEntityRepository:

```<code>@Repository
public interface RootEntityRepository extends JpaRepository<RootEntity, Integer> {

    @Query(value = """
            SELECT 1 as col1, 2 as col2, 3 as col3
            UNION ALL SELECT 4, 5, 6
            UNION ALL SELECT 7, 8, 9""",
            nativeQuery = true)
    public Collection<Object> findFromCustomQuery();

}
</code>```

The endpoint http://localhost:8080/rootEntities was exposed, but when I accessed it, I got the exception: "Relation root_entity does not exist". So, I created the table in the database:

```<code>create table root_entity(
    id SERIAL PRIMARY KEY
)
</code>```

After that, the endpoint worked, and returned an empty array (the table root_entity is empty in the database).

I tried to access the endpoint: http://localhost:8080/rootEntities/search/findFromCustomQuery, but I got an exception (Couldn't find PersistentEntity for type class).

Again, I was not able to make it work.

After trying a lot, I made some progress doing the following:

```<code>@RestController
public class CustomQueryController {

    @Autowired
    private EntityManager entityManager;

    @GetMapping("/myEndpoint")
    @ResponseBody
    public Object runNativeQuery() {

        return ResponseEntity
                .ok()
                .body(
                    entityManager.createNativeQuery(
                        """
                        SELECT 1 as col1, 2 as col2, 3 as col3
                        UNION ALL SELECT 4, 5, 6
                        UNION ALL SELECT 7, 8, 9
                        """
                    ).getResultList()
                );
    }
}
</code>```

With the code above, I can access http://localhost:8080/myEndpoint and see the result of the query.

However, the endpoint didn't appear in the endpoints listing that is showed in http://localhost:8080/. I had to type it manually in the browser. I would like the endpoint to be exposed in order to see it in Swagger.

Also, I have a feeling that there must be a better way to do this. And I want to learn.

I would like help to:

Get a solution that works and exposes the endpoint.

Understand what I did wrong and how to implement Kowalski's and Gagarwa's solutions.

Being able to expose the endpoint for the last solution (CustomQueryController).

Thanks in advance!

答:
I tried the first example that you have put here and it worked for me. But there is a bit of change. I have used  PersistenceContext.

To return a Link as response I have used Link of WebMvcLinkBuilder.

Solution

In the below example I have used two tables Employee and Address in PostgresSQL . Both have area_code in common.

Interface

```<code>public interface CustomNativeRepository {
     List<Object> runNativeQuery(Integer name);
}
</code>```

Repository

```<code>@Repository
public class CustomNativeRepositoryImpl implements CustomNativeRepository {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<Object> runNativeQuery(Integer areaCode) {
        Query query = entityManager.createNativeQuery(
                "Select e.first_name as name from employees e where e.area_code = ? "
                       + "union all " +
                "Select a.address as address from address a where a.area_code = ?");
        query.setParameter(1, areaCode);
        query.setParameter(2, areaCode);
        List<Object> response = query.getResultList();
        logger.info("Response from database: {}", response);
        return response;
    }
}
</code>```

RestEndpoint Layer

```<code>@GetMapping(path ="/employee/{areaCode}")
public ResponseEntity<?> getEmployeeByCode(@PathVariable(value = "areaCode") Integer areaCode) throws NoSuchMethodException {
    List<Object> response = customCustomerRepository.runNativeQuery(areaCode);
    Link link = WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(EmployeeController.class).getEmployeeByCode(areaCode)).withSelfRel();
    return ResponseEntity.ok().body(CollectionModel.of(response, link));
}
</code>```

Few examples which may help. link1   link2

Note: I have not created any Entity classes in my code base.

Body:
I want to run some native queries and expose the results through endpoints, but I want to do this without having to create all the entities. I just want the data obtained from the database to be exposed as it comes.

I found some suggestions at: Create spring repository without entity

However, I was not able to make them work. I'm very new to Spring.

I tried Maciej Kowalski's solution like this:

Interface:

public interface CustomNativeRepository {
    Object runNativeQuery();
}

Implementation:

@Repository
public class CustomNativeRepositoryImpl implements CustomNativeRepository {

    @Autowired
    private EntityManager entityManager;

    @Override
    public Object runNativeQuery() {
        return entityManager.createNativeQuery(
                """
                SELECT 1 as col1, 2 as col2, 3 as col3
                UNION ALL SELECT 4, 5, 6
                UNION ALL SELECT 7, 8, 9
                """
                )
        .getResultList();
    }
}

However, no endpoints were exposed, as happens when you extend CrudRepository. Should I have done something else with CustomNativeRepositoryImpl? I don't know how to proceed.

I also tried Gagarwa's solution:

RootEntity:

@Entity
public class RootEntity {
    @Id
    private Integer id;
}

RootEntityRepository:

@Repository
public interface RootEntityRepository extends JpaRepository<RootEntity, Integer> {

    @Query(value = """
            SELECT 1 as col1, 2 as col2, 3 as col3
            UNION ALL SELECT 4, 5, 6
            UNION ALL SELECT 7, 8, 9""",
            nativeQuery = true)
    public Collection<Object> findFromCustomQuery();

}

The endpoint http://localhost:8080/rootEntities was exposed, but when I accessed it, I got the exception: "Relation root_entity does not exist". So, I created the table in the database:

create table root_entity(
    id SERIAL PRIMARY KEY
)

After that, the endpoint worked, and returned an empty array (the table root_entity is empty in the database).

I tried to access the endpoint: http://localhost:8080/rootEntities/search/findFromCustomQuery, but I got an exception (Couldn't find PersistentEntity for type class).

Again, I was not able to make it work.

After trying a lot, I made some progress doing the following:

@RestController
public class CustomQueryController {

    @Autowired
    private EntityManager entityManager;

    @GetMapping("/myEndpoint")
    @ResponseBody
    public Object runNativeQuery() {

        return ResponseEntity
                .ok()
                .body(
                    entityManager.createNativeQuery(
                        """
                        SELECT 1 as col1, 2 as col2, 3 as col3
                        UNION ALL SELECT 4, 5, 6
                        UNION ALL SELECT 7, 8, 9
                        """
                    ).getResultList()
                );
    }
}

With the code above, I can access http://localhost:8080/myEndpoint and see the result of the query.

However, the endpoint didn't appear in the endpoints listing that is showed in http://localhost:8080/. I had to type it manually in the browser. I would like the endpoint to be exposed in order to see it in Swagger.

Also, I have a feeling that there must be a better way to do this. And I want to learn.

I would like help to:

Get a solution that works and exposes the endpoint.

Understand what I did wrong and how to implement Kowalski's and Gagarwa's solutions.

Being able to expose the endpoint for the last solution (CustomQueryController).

Thanks in advance!

Body:
I tried the first example that you have put here and it worked for me. But there is a bit of change. I have used  PersistenceContext.

To return a Link as response I have used Link of WebMvcLinkBuilder.

Solution

In the below example I have used two tables Employee and Address in PostgresSQL . Both have area_code in common.

Interface

public interface CustomNativeRepository {
     List<Object> runNativeQuery(Integer name);
}

Repository

@Repository
public class CustomNativeRepositoryImpl implements CustomNativeRepository {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<Object> runNativeQuery(Integer areaCode) {
        Query query = entityManager.createNativeQuery(
                "Select e.first_name as name from employees e where e.area_code = ? "
                       + "union all " +
                "Select a.address as address from address a where a.area_code = ?");
        query.setParameter(1, areaCode);
        query.setParameter(2, areaCode);
        List<Object> response = query.getResultList();
        logger.info("Response from database: {}", response);
        return response;
    }
}

RestEndpoint Layer

@GetMapping(path ="/employee/{areaCode}")
public ResponseEntity<?> getEmployeeByCode(@PathVariable(value = "areaCode") Integer areaCode) throws NoSuchMethodException {
    List<Object> response = customCustomerRepository.runNativeQuery(areaCode);
    Link link = WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(EmployeeController.class).getEmployeeByCode(areaCode)).withSelfRel();
    return ResponseEntity.ok().body(CollectionModel.of(response, link));
}

Few examples which may help. link1   link2

Note: I have not created any Entity classes in my code base.


来源: stackexchange

问:
make a windows 7 machine crash on BSOD
I'm trying to write a windows debug utility and I would need to automatically crash a Windows  machine and make a Blue Screen Of Death appear.

I can obviously kill the csrss.exe process from the task manager, but the command TASKKILL /F /IM csrss.exe in a .bat file doesn't work.

Is there another way to make a Windows machine crash on bsod? Maybe some external library able to kill any process.

I would prefer to use a command line approach since I'm more familiar with it.

答:
If you really want to crash your PC, execute:

```<code>C:/con/con
</code>```

or

```<code>C:/con
</code>```

ContentLicense: CC BY-SA 3.0

Title: make a windows 7 machine crash on BSOD

Body:
If you really want to crash your PC, execute:

C:/con/con

or

C:/con

ContentLicense: CC BY-SA 4.0


问:
How to view all the services running on AWS?
How would I be able to view all the services running on aws. I have been charged some $$$, so what to close the services that are running. Most of the $ are being charged for KMS(Key Management System). When I go inside the KMS from aws console there's nothing.

Please Help!!!!

答:
Firstly, go to Billing Dashboard. It open as "AWS Billing Dashboard" (notice  ../billing/home in the url).

If you want to view all different aws-services you have been consuming, along with their bills. From the left-pan menu, navigate to => Cost Explorer -> Launch Cost Explorer.
Here you can find bills according to your months, regions, service-type, usage-type, etc. with charges based on different services.

If you want to view your cumulative bill (regarding all usage of aws services), from the left-pane menu go to Bills.


问:
How to make a container extend to the bottom without adding more length

body {
@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@1,300&display=swap');

background: linear-gradient(to right, yellow, black);

}
.middle-checklist-box-social {
    position: relative;
    top: 0;
    margin: 0 auto;
    height: 35%;
    width: 50%;
    background-color: white;
    padding: 10px 10px 10px 10px;
    bottom: 0%;
}

.checkbox-label-class {
    font-size: 20px;
    font-family: 'Roboto Mono', monospace;
    vertical-align: text-bottom;
}

.giannisCheckbox {
    height: 18px;
    width: 18px;
}

.chkbxLowerLine {
    position: initial;
    height: 2px;
    width: 90%;
    background-color: grey;
    margin-top: 5px;
    margin-bottom: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="middle-checklist-box-social">

    <div class="middle-checklist-box-social">
        <label class="container" >
            <input id="chkbx001" class="giannisCheckbox" type="checkbox" >
            <span class="checkbox-label-class">Social Studies Unit 8 Review (Graded)</span>
        </label>
        <!-- Put in a grey line that seperates the checkbox from the others  -->
        <p class="chkbxLowerLine"></p>
        <!-- New Checkbox here under the line  -->
        <label class="container" >
            <input id="chkbx002" class="giannisCheckbox" type="checkbox">
            <span class="checkbox-label-class">Georgia 3.2.1. GO Project</span>
        </label>

    </div>

</div></code>```

I want a column in the middle to extend to the bottom of the page.  without adding more page content or space where you don't have to scroll to the bottom. I looked around for clues or if anyone has solved this, but of no luck.

I have tried 100vh, but it adds more content making me scroll down which I don't want.

Here is the picture because there is a lot of code in it, but I have position relative,

But I want the end of the white box with the checkbox to reach the bottom of the page

答:
You should have the container's container be 100vh with display flex, and then let flexbox take care of your heights.

Example :

```<code>.container{
    display: flex;
    flex-direction: column;
}

.notExtendingChild{
    /* whatever */
}

.extendingChild{
    flex-grow: 1
}
</code>```

Body:
body {
@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@1,300&display=swap');

background: linear-gradient(to right, yellow, black);

}
.middle-checklist-box-social {
    position: relative;
    top: 0;
    margin: 0 auto;
    height: 35%;
    width: 50%;
    background-color: white;
    padding: 10px 10px 10px 10px;
    bottom: 0%;
}

.checkbox-label-class {
    font-size: 20px;
    font-family: 'Roboto Mono', monospace;
    vertical-align: text-bottom;
}

.giannisCheckbox {
    height: 18px;
    width: 18px;
}

.chkbxLowerLine {
    position: initial;
    height: 2px;
    width: 90%;
    background-color: grey;
    margin-top: 5px;
    margin-bottom: 5px;
}

            <input id="chkbx001" class="giannisCheckbox" type="checkbox" >
            Social Studies Unit 8 Review (Graded)

            <input id="chkbx002" class="giannisCheckbox" type="checkbox">
            Georgia 3.2.1. GO Project

I want a column in the middle to extend to the bottom of the page.  without adding more page content or space where you don't have to scroll to the bottom. I looked around for clues or if anyone has solved this, but of no luck.

I have tried 100vh, but it adds more content making me scroll down which I don't want.

Here is the picture because there is a lot of code in it, but I have position relative,

But I want the end of the white box with the checkbox to reach the bottom of the page

Body:
You should have the container's container be 100vh with display flex, and then let flexbox take care of your heights.

Example :

.container{
    display: flex;
    flex-direction: column;
}

.notExtendingChild{
    /* whatever */
}

.extendingChild{
    flex-grow: 1
}


问:
Creating your own header file in C
Can anyone explain how to create a header file in C with a simple example from beginning to end.</p>

答:
foo.h

```<code>#ifndef FOO_H_   /* Include guard */
#define FOO_H_

int foo(int x);  /* An example function declaration */

#endif // FOO_H_
</code>```

foo.c

```<code>#include "foo.h"  /* Include the header (not strictly necessary here) */

int foo(int x)    /* Function definition */
{
    return x + 5;
}
</code>```

main.c

```<code>#include <stdio.h>
#include "foo.h"  /* Include the header here, to obtain the function declaration */

int main(void)
{
    int y = foo(3);  /* Use the function here */
    printf("%d\n", y);
    return 0;
}
</code>```

To compile using GCC

```<code>gcc -o my_app main.c foo.c
</code>```

Title: Creating your own header file in C

Body:
foo.h

#ifndef FOO_H_   /* Include guard */
#define FOO_H_

int foo(int x);  /* An example function declaration */

#endif // FOO_H_

foo.c

#include "foo.h"  /* Include the header (not strictly necessary here) */

int foo(int x)    /* Function definition */
{
    return x + 5;
}

main.c

#include <stdio.h>
#include "foo.h"  /* Include the header here, to obtain the function declaration */

int main(void)
{
    int y = foo(3);  /* Use the function here */
    printf("%d\n", y);
    return 0;
}

To compile using GCC

gcc -o my_app main.c foo.c


问:
how to specify which font to use in googlefonts with css
i have imported two fonts in my website Montserrat Extra-light 200 and Montserrat Medium 500 but when i type

font-family: 'Montserrat Extra-light 200', sans-serif;

it apllies the Montserrat Medium 500 font but i want to apply the Montserrat Extra-light 200
but there i an another text which shout use Montserrat Medium 500 so i cant remove one font

so is there any way which Montserrat to use in a specific text

here is my html and css code

#section1_text1 {
  font-family: "Montserrat", sans-serif;
}

#section1_text2 {
  font-family: "Montserrat", sans-serif;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/test/styles.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@200;400&display=swap" rel="stylesheet">
    <title>Document</title>
</head>

<body>
    <main>
        <div id="section1">
            <h3 id="section1_text1">Almost before we knew it, we had left the ground.</h3>
            <h2 id="section1_text2">Agile Way Of Development</h2>
        </div>
    </main>
</body>

</html></code>```

so i want to specify which font to use at a specifec text

答:
Your HTML and CSS is correct. You only need to add the font-weight to make sure you can use specific font weight for your chosen font.

styles.css

```<code>#section1_text1 {
  font-family: "Montserrat", sans-serif;
  font-weight: 200;
}

#section1_text2 {
  font-family: "Montserrat", sans-serif;
  font-weight: 400;
}
</code>```

HTML

```<code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/test/styles.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@200;400&display=swap" rel="stylesheet">
    <title>Document</title>
</head>

<body>
    <main>
        <div id="section1">
            <h3 id="section1_text1">Almost before we knew it, we had left the ground.</h3>
            <h2 id="section1_text2">Agile Way Of Development</h2>
        </div>
    </main>
</body>

</html>
</code>```

Body:
i have imported two fonts in my website Montserrat Extra-light 200 and Montserrat Medium 500 but when i type

font-family: 'Montserrat Extra-light 200', sans-serif;

it apllies the Montserrat Medium 500 font but i want to apply the Montserrat Extra-light 200
but there i an another text which shout use Montserrat Medium 500 so i cant remove one font

so is there any way which Montserrat to use in a specific text

here is my html and css code

#section1_text1 {
  font-family: "Montserrat", sans-serif;
}

#section1_text2 {
  font-family: "Montserrat", sans-serif;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/test/styles.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@200;400&display=swap" rel="stylesheet">
    <title>Document</title>

Almost before we knew it, we had left the ground.

Agile Way Of Development

so i want to specify which font to use at a specifec text

Body:
Your HTML and CSS is correct. You only need to add the font-weight to make sure you can use specific font weight for your chosen font.

styles.css

#section1_text1 {
  font-family: "Montserrat", sans-serif;
  font-weight: 200;
}

#section1_text2 {
  font-family: "Montserrat", sans-serif;
  font-weight: 400;
}

HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/test/styles.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@200;400&display=swap" rel="stylesheet">
    <title>Document</title>
</head>

<body>
    <main>
        <div id="section1">
            <h3 id="section1_text1">Almost before we knew it, we had left the ground.</h3>
            <h2 id="section1_text2">Agile Way Of Development</h2>
        </div>
    </main>
</body>

</html>


问:
Using for and if loops in Google Apps Script
Dear programming Community,

at first I need to state, that I am not quite experienced in VBA and programming in general.

What is my problem? I have created a topic list in google sheets in order to collect topics for our monthly meeting among members in a little dance club. That list has a few columns (A: date of creation of topic; B: topic; C: Name of creator; ...). Since it is hard to force all the people to use the same format for the date (column A; some use the year, others not, ...), I decided to lock the entire column A (read-only) and put a formular there in all cells that looks in the adjacent cell in column B and sets the current date, if someone types in a new topic (=if(B2="";"";Now()). Here the problem is, that google sheets (and excel) does then always update the date, when you open the file a few days later again. I tried to overcome this problem by using a circular reference, but that doesn't work either. So now I am thinking of creating a little function (macro) that gets triggered when the file is closed.

Every cell in Column B (Topic) in the range from row 2 to 1000 (row 1 is headline) shall be checked if someone created a new topic (whether or not its empty). If it is not empty, the Date in the adjacent cell (Column A) shall be copied and reinserted just as the value (to get rid of the formular in that cell). Since it also can happen, that someone has created a topic, but a few days later decides to delete it again, in that case the formular for the date shall be inserted again. I thought to solve this with an If-Then-Else loop (If B is not empty, then copy/paste A, else insert formula in A) in a For loop (checking rows 1 - 1000). This is what I have so far, but unfortunately does not work. Could someone help me out here?

Thanks in advance and best regards,
Harry

```<code> function NeuerTest () {
  var ss=SpreadsheetApp.getActive();
  var s=ss.getSheetByName('Themenspeicher');
  var thema = s.getCell(i,2);
  var datum = s.getCell(i,1);
    for (i=2;i<=100;i++) {
     if(thema.isBlank){
          }
      else {
        datum.copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
      }}
  }
</code>```

答:
The suggested approach is to limit the calls to the Spreadsheet API, therefore instead of getting every cell, get all the data at once.</p>
```<code>// this gets all the data in the Sheet
const allRows = s.getDataRange().getValues()

// here we will store what is written back into the sheet
const output = []

// now go through each row
allRows.forEach( (row, ind) => {

  const currentRowNumber = ind+1

  // check if column b is empty
  if( !row[1] || row[1]= "" ){
    // it is, therefore add a row with a formula
    output.push( ["=YOUR_FORMULA_HERE"] )

  } else {
    // keep the existing value
    output.push( [row[0]] )
  }
})
</code>```

Body:
Dear programming Community,

at first I need to state, that I am not quite experienced in VBA and programming in general.

What is my problem? I have created a topic list in google sheets in order to collect topics for our monthly meeting among members in a little dance club. That list has a few columns (A: date of creation of topic; B: topic; C: Name of creator; ...). Since it is hard to force all the people to use the same format for the date (column A; some use the year, others not, ...), I decided to lock the entire column A (read-only) and put a formular there in all cells that looks in the adjacent cell in column B and sets the current date, if someone types in a new topic (=if(B2="";"";Now()). Here the problem is, that google sheets (and excel) does then always update the date, when you open the file a few days later again. I tried to overcome this problem by using a circular reference, but that doesn't work either. So now I am thinking of creating a little function (macro) that gets triggered when the file is closed.

Every cell in Column B (Topic) in the range from row 2 to 1000 (row 1 is headline) shall be checked if someone created a new topic (whether or not its empty). If it is not empty, the Date in the adjacent cell (Column A) shall be copied and reinserted just as the value (to get rid of the formular in that cell). Since it also can happen, that someone has created a topic, but a few days later decides to delete it again, in that case the formular for the date shall be inserted again. I thought to solve this with an If-Then-Else loop (If B is not empty, then copy/paste A, else insert formula in A) in a For loop (checking rows 1 - 1000). This is what I have so far, but unfortunately does not work. Could someone help me out here?

Thanks in advance and best regards,
Harry

 function NeuerTest () {
  var ss=SpreadsheetApp.getActive();
  var s=ss.getSheetByName('Themenspeicher');
  var thema = s.getCell(i,2);
  var datum = s.getCell(i,1);
    for (i=2;i<=100;i++) {
     if(thema.isBlank){
          }
      else {
        datum.copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
      }}
  }

Body:
The suggested approach is to limit the calls to the Spreadsheet API, therefore instead of getting every cell, get all the data at once.

// this gets all the data in the Sheet
const allRows = s.getDataRange().getValues()

// here we will store what is written back into the sheet
const output = []

// now go through each row
allRows.forEach( (row, ind) => {

  const currentRowNumber = ind+1

  // check if column b is empty
  if( !row[1] || row[1]= "" ){
    // it is, therefore add a row with a formula
    output.push( ["=YOUR_FORMULA_HERE"] )

  } else {
    // keep the existing value
    output.push( [row[0]] )
  }
})


问:
Angular 12 aws-sdk 2.910.0 Error: Module not found: Error: Can't resolve 'util' in '.\.\.\node_modules\aws-sdk\lib'
Prior to moving from Angular 11 to 12 the following error did not occur and the application was able to use the aws-sdk library to access my S3 buckets:

```<code>./node_modules/aws-sdk/lib/event_listeners.js:572:21-44 - Error: Module not found: Error: Can't resolve 'util' in 'S:\Source\sttutter-ui\node_modules\aws-sdk\lib'
Did you mean './util'?
Requests that should resolve in the current directory need to start with './'.
Requests that start with a name are treated as module requests and resolve within module directories (S:/Source/sttutter-ui, node_modules).
If changing the source code is not an option there is also a resolve options called 'preferRelative' which tries to resolve these kind of requests in the current directory too.

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'
        - install 'util'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "util": false }

</code>```

package.json

```<code>{
  "name": "x",
  "version": "0.0.0",
  "license": "commercial",
  "private": true,
  "engines": {
    "node": ">= 10.0.0"
  },
  "dependencies": {
    "@angular/animations": "~12.0.1",
    "@angular/common": "~12.0.1",
    "@angular/compiler": "~12.0.1",
    "@angular/core": "~12.0.1",
    "@angular/forms": "~12.0.1",
    "@angular/platform-browser": "~12.0.1",
    "@angular/platform-browser-dynamic": "~12.0.1",
    "@angular/router": "~12.0.1",
    "@ng-bootstrap/ng-bootstrap": "^9.1.1",
    "@ngrx/store": "^12.0.0",
    "aws-sdk": "^2.910.0",
    "ngrx-store-freeze": "^0.2.4",
    "ngrx-store-logger": "^0.2.4",
    "prando": "^6.0.1",
    "rxjs": "~6.6.0",
    "tslib": "^2.1.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.0.1",
    "@angular/cli": "~12.0.1",
    "@angular/compiler-cli": "~12.0.1",
    "@types/jasmine": "~3.6.0",
    "@types/node": "^12.11.1",
    "jasmine-core": "~3.7.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "typescript": "~4.2.3"
  },
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  }
}
</code>```

I've tried deleting the node_modules directory and running npm install

Search the web about this error seems to suggest that this is a webpack issue... Based upon these conversations I'm not sure how to get this working again.

Should I switch to aws-sdk-js even though aws-sdk was working up and until today?

Suggestions regarding how to resolve this issue sought

Thanks!

答:
Angular 12 moved to Webpack 5 which does not include polyfills for node.js anymore.

To avoid adding missing polyfills on your own, use this Webpack plugin: https://www.npmjs.com/package/node-polyfill-webpack-plugin

It includes all polyfills which have been removed with Webpack 5.

Install the package and configure the Webpack plugin as described and the issue should be solved.

Body:
Prior to moving from Angular 11 to 12 the following error did not occur and the application was able to use the aws-sdk library to access my S3 buckets:

./node_modules/aws-sdk/lib/event_listeners.js:572:21-44 - Error: Module not found: Error: Can't resolve 'util' in 'S:\Source\sttutter-ui\node_modules\aws-sdk\lib'
Did you mean './util'?
Requests that should resolve in the current directory need to start with './'.
Requests that start with a name are treated as module requests and resolve within module directories (S:/Source/sttutter-ui, node_modules).
If changing the source code is not an option there is also a resolve options called 'preferRelative' which tries to resolve these kind of requests in the current directory too.

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'
        - install 'util'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "util": false }

package.json

{
  "name": "x",
  "version": "0.0.0",
  "license": "commercial",
  "private": true,
  "engines": {
    "node": ">= 10.0.0"
  },
  "dependencies": {
    "@angular/animations": "~12.0.1",
    "@angular/common": "~12.0.1",
    "@angular/compiler": "~12.0.1",
    "@angular/core": "~12.0.1",
    "@angular/forms": "~12.0.1",
    "@angular/platform-browser": "~12.0.1",
    "@angular/platform-browser-dynamic": "~12.0.1",
    "@angular/router": "~12.0.1",
    "@ng-bootstrap/ng-bootstrap": "^9.1.1",
    "@ngrx/store": "^12.0.0",
    "aws-sdk": "^2.910.0",
    "ngrx-store-freeze": "^0.2.4",
    "ngrx-store-logger": "^0.2.4",
    "prando": "^6.0.1",
    "rxjs": "~6.6.0",
    "tslib": "^2.1.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.0.1",
    "@angular/cli": "~12.0.1",
    "@angular/compiler-cli": "~12.0.1",
    "@types/jasmine": "~3.6.0",
    "@types/node": "^12.11.1",
    "jasmine-core": "~3.7.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "typescript": "~4.2.3"
  },
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  }
}

I've tried deleting the node_modules directory and running npm install

Search the web about this error seems to suggest that this is a webpack issue... Based upon these conversations I'm not sure how to get this working again.

Should I switch to aws-sdk-js even though aws-sdk was working up and until today?

Suggestions regarding how to resolve this issue sought

Thanks!


问:
_CastError (Null check operator used on a null value) from SQFLITE Flutter
I am trying to call this fetchall() method from totalprice() method, but every time it throws this error.

Here is my fetchall() method -

```<code>    Future<List<CartModel>>? fetchall() async {
    List<Map<String, Object?>>? map = await database?.query(tablename);
    List<CartModel> cartproducts = [];
    CartModel singleproduct = CartModel();

    for (Map<String, Object?> i in map!) {
      cartproducts.add(CartModel.fromJson(i));
      singleproduct = CartModel.fromJson(i);
      a = a + singleproduct.price!.toInt();
    }

    return cartproducts;
</code>```

and this is the totalprice() method -

```<code>      Future<int> totalprice() async {
        int totalprice = 0;
        List<CartModel>? products = await fetchall();
        if (products != null) {
          for (var i in products) {
            totalprice = (totalprice + i.price!.toInt() * i.quantity!.toInt());
          }
        }
        return totalprice;
</code>```

Thanks for any little help.

答:
Your line

List<Map<String, Object?>>? map = await database?.query(tablename);
```
<p>Is probably assigning a <code>null</code> value to your <code>map</code> variable which your are later using with a null check operator <code>!</code> which means that you are sure that it's not null, but the type <code>List<Map<String, Object?>>?</code> in the mentioned line gives it the ability to be null.</p>
<p>You can solve this by adding a null check before using the <code>map</code> variable like so</p>
<pre class="lang-dart prettyprint-override"><code>Future<List<CartModel>>? fetchall() async {
    List<Map<String, Object?>>? map = await database?.query(tablename);
    List<CartModel> cartproducts = [];
    CartModel singleproduct = CartModel();

    if(map != null)
     for (Map<String, Object?> i in map!) {
       cartproducts.add(CartModel.fromJson(i));
       singleproduct = CartModel.fromJson(i);
       a = a + singleproduct.price!.toInt();
     }
    }

    return cartproducts;
}
</code>```

Additional advice

For better code quality and readability, please follow variable naming conventions. For dart, make sure are your variables and methods are camelCase

so instead of fetchall => fetchAll

instead of cartproducts => cartProducts

instead of singleproduct => singleProduct

And so on...

Body:
I am trying to call this fetchall() method from totalprice() method, but every time it throws this error.

Here is my fetchall() method -

    Future<List<CartModel>>? fetchall() async {
    List<Map<String, Object?>>? map = await database?.query(tablename);
    List<CartModel> cartproducts = [];
    CartModel singleproduct = CartModel();

    for (Map<String, Object?> i in map!) {
      cartproducts.add(CartModel.fromJson(i));
      singleproduct = CartModel.fromJson(i);
      a = a + singleproduct.price!.toInt();
    }

    return cartproducts;

and this is the totalprice() method -

      Future<int> totalprice() async {
        int totalprice = 0;
        List<CartModel>? products = await fetchall();
        if (products != null) {
          for (var i in products) {
            totalprice = (totalprice + i.price!.toInt() * i.quantity!.toInt());
          }
        }
        return totalprice;

Thanks for any little help.

Body:
Your line

List<Map<String, Object?>>? map = await database?.query(tablename);

Is probably assigning a null value to your map variable which your are later using with a null check operator ! which means that you are sure that it's not null, but the type List<Map<String, Object?>>? in the mentioned line gives it the ability to be null.

You can solve this by adding a null check before using the map variable like so

Future<List<CartModel>>? fetchall() async {
    List<Map<String, Object?>>? map = await database?.query(tablename);
    List<CartModel> cartproducts = [];
    CartModel singleproduct = CartModel();

    if(map != null)
     for (Map<String, Object?> i in map!) {
       cartproducts.add(CartModel.fromJson(i));
       singleproduct = CartModel.fromJson(i);
       a = a + singleproduct.price!.toInt();
     }
    }

    return cartproducts;
}

Additional advice

For better code quality and readability, please follow variable naming conventions. For dart, make sure are your variables and methods are camelCase

so instead of fetchall => fetchAll

instead of cartproducts => cartProducts

instead of singleproduct => singleProduct

And so on...


问:
HTML and XSLT transformation
I have simple question,

Can I use XSLT to transform HTML to other HTML.

If it's possible, how i should do this?

答: You could try TagSoup (http://vrici.lojban.org/~cowan/XML/tagsoup/]1) for messy HTML and plug your XSLT into that.</p>

Title: HTML and XSLT transformation


问:
JavaScript clipboardData void Text
I am using the below code to copy data from the clipboard into my form and submit. Previously this was very limited to only images on browsers, now browsers allow everything from files to text. The problem is when text is copied, it thinks its a file and wants to submit.

Is there a way to void all types of text being pasted?

```<code>const fileInput = document.getElementById("document_attachment_doc");

window.addEventListener('paste', e => {
  fileInput.files = e.clipboardData.files;
  document.getElementById("new_document_attachment").submit();
});
</code>```

答:
What I did find is that the form submit is triggered due to the paste even if there ae no files and just plain text. A workaround was to check that the file count in the clipboard was more than 0. If there is text in the clipboard its 0.</p>
```<code> window.addEventListener('paste', e => {
  if (e.clipboardData.files.length > 0){
    fileInput.files = e.clipboardData.files;
    document.getElementById("new_document_attachment").submit();
   }
 });
</code>```

Title: JavaScript clipboardData void Text

Body:
I am using the below code to copy data from the clipboard into my form and submit. Previously this was very limited to only images on browsers, now browsers allow everything from files to text. The problem is when text is copied, it thinks its a file and wants to submit.

Is there a way to void all types of text being pasted?

const fileInput = document.getElementById("document_attachment_doc");

window.addEventListener('paste', e => {
  fileInput.files = e.clipboardData.files;
  document.getElementById("new_document_attachment").submit();
});

Body:
What I did find is that the form submit is triggered due to the paste even if there ae no files and just plain text. A workaround was to check that the file count in the clipboard was more than 0. If there is text in the clipboard its 0.

 window.addEventListener('paste', e => {
  if (e.clipboardData.files.length > 0){
    fileInput.files = e.clipboardData.files;
    document.getElementById("new_document_attachment").submit();
   }
 });


问:
are there any functions for closing turtle graphics's window?
so I want my program to do some lines of code then open turtle window do some staff, close it, do some code again and open turtle window. I have tried turtle.clear(), turtle.reset(), turtle.resetscreen(), turtle.clearscreen(), turtle.exitonclick(), but none of it clears entirely, close it and when I need it again, gives me ability to open it.
so can you help me.

答:
```<code>import turtle, time
screen = turtle.Screen()
turtle.color('orange')
turtle.pensize(3)
turtle.circle(75)

time.sleep(5)

# close
screen.bye()
# or turtle.Screen().bye()
</code>```


问:
MSB() LSB() popcount() in numba
I have a program that uses numba and needs to use MSB() LSB() POPCOUNT() etc
I can't seem to find any reference to these in relation to numba, how does one get these builtin function like python's bit_length() working with numba?</p>
```<code>Unknown attribute 'bit_length' of type int64

File "v.py", line 116:
def msb(x):
    return int(int(x).bit_length()) - 1
    ^
</code>```

答:
Numba does not provide a popcount function yet. While this function can be implemented, it will definitively not be user-friendly (it required to delves into the way Numba works and deals with the LLVM-Lite JIT), not portable either (dependent of the target architecture). For more informations please read the documentation about intrinsics and this post. If you really want to take this path, then please note that while a new intrinsic function can be implemented in Numba for your needs, popcount appears not to be supported yet be the LLVM-Lite JIT wrapping layer and AFAIK the only solution is to call inline assembly directly from LLVM-Lite which is neither simple nor portable (it does not even work on all x86-64 CPUs)...

bit_length is a method of int objects that only make sense on variable-sized integers but Numba does not use such type (like Numpy) because of they very big overhead compared to native fixed-size numbers.

Numpy will soon add a popcount function and this function will likely be implemented by Numba later but this is not yet the case. This is certainly the best solution for future readers.

Hopefully, there is a way to get a relatively fast code using Bit Twiddling Hacks although it will certainly not produce a code as fast as instructions like popcnt available on most x86-64 recent processors. For example, a popcount on unsigned 32-bit integers can be implemented using the following code in Numba:

```<code>import numba as nb

# The signature is critical for the function to be correct
@nb.njit('int_(uint32)')
def popcount(v):
    v = v - ((v >> 1) & 0x55555555)
    v = (v & 0x33333333) + ((v >> 2) & 0x33333333)
    c = np.uint32((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24
    return c

# Returns 17
popcount(0b00110101_00011110_00111010_11101001)
</code>```

On my machine, this is very fast, especially if the above function is put in in a loop that can be automatically vectorized since the JIT can use AVX-2 SIMD instructions: it takes about ~4 cycle/int without on my machine and ~1.5 cycle/int with AVX-2.

The same thing applies for the MSB and LSB. Note that bit twiddling hacks with integers having fewer bits should results in a faster generated code (especially due to SIMD and the need for fewer instructions).

Title: MSB() LSB() popcount() in numba

Body:
I have a program that uses numba and needs to use MSB() LSB() POPCOUNT() etc
I can't seem to find any reference to these in relation to numba, how does one get these builtin function like python's bit_length() working with numba?

Unknown attribute 'bit_length' of type int64

File "v.py", line 116:
def msb(x):
    return int(int(x).bit_length()) - 1
    ^

Body:
Numba does not provide a popcount function yet. While this function can be implemented, it will definitively not be user-friendly (it required to delves into the way Numba works and deals with the LLVM-Lite JIT), not portable either (dependent of the target architecture). For more informations please read the documentation about intrinsics and this post. If you really want to take this path, then please note that while a new intrinsic function can be implemented in Numba for your needs, popcount appears not to be supported yet be the LLVM-Lite JIT wrapping layer and AFAIK the only solution is to call inline assembly directly from LLVM-Lite which is neither simple nor portable (it does not even work on all x86-64 CPUs)...

bit_length is a method of int objects that only make sense on variable-sized integers but Numba does not use such type (like Numpy) because of they very big overhead compared to native fixed-size numbers.

Numpy will soon add a popcount function and this function will likely be implemented by Numba later but this is not yet the case. This is certainly the best solution for future readers.

Hopefully, there is a way to get a relatively fast code using Bit Twiddling Hacks although it will certainly not produce a code as fast as instructions like popcnt available on most x86-64 recent processors. For example, a popcount on unsigned 32-bit integers can be implemented using the following code in Numba:

import numba as nb

# The signature is critical for the function to be correct
@nb.njit('int_(uint32)')
def popcount(v):
    v = v - ((v >> 1) & 0x55555555)
    v = (v & 0x33333333) + ((v >> 2) & 0x33333333)
    c = np.uint32((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24
    return c

# Returns 17
popcount(0b00110101_00011110_00111010_11101001)

On my machine, this is very fast, especially if the above function is put in in a loop that can be automatically vectorized since the JIT can use AVX-2 SIMD instructions: it takes about ~4 cycle/int without on my machine and ~1.5 cycle/int with AVX-2.

The same thing applies for the MSB and LSB. Note that bit twiddling hacks with integers having fewer bits should results in a faster generated code (especially due to SIMD and the need for fewer instructions).


问:
Why this program to sort array doesnt work?
Im trying to learn C and I'm doing this program to sort an array but It doesn't work and I'm not sure why, I tested each function and works well, someone knows if its a problem of variables or something?

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

#define N 5

int V[5] = { -383, 386, 277, 415, 293 };

void displayArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        printf("%d ", arr[i]);
}

int maxim(int v[], int n)
{
    int i, m;
    m = v[0];
    /*
    Find maxim element
    */
    for (i = 1; i < n; i++)
        if (v[i] > m)
            m = v[i];
    /*
    Search element position
    */
    for (i = 0; i < N; i++)
        if (v[i] == m)
            return i;
}

void sort(int v[], int n)
{
    int i, pos, t;
    for (i = 0; i < n; i++)
        pos = maxim(v, n - i);

        /*
        Swap elements
        */
        t = v[n - 1 - i];
        v[n - 1 - i] = v[pos];
        v[pos] = t;
}

int main()
{
    displayArray(V, N);
    sort(V, N);
    printf("\n");
    displayArray(V, N);
    return 0;
}
</code>```

The output is

-383 386 277 415 293 - Original Array

21900 386 277 415 293 - 'Sorted' Array

答:
First fix your maxim function. Its purpose is to find the maximum index of a  sequence v of magnitude n. Therefore, remembering the maximum value in m is irrelevant; you want to remember where it resides :

```<code>int maxim(int v[], int n)
{
    int m=0;
    for (int i=1; i<n; ++i)
    {
        if (v[m] < v[i])
            m = i; // save new max location
    }
    return m;
}
</code>```

After that, the sort, which is completely wrong. This:

```<code>int i, pos, t;
for (i = 0; i < n; i++)
    pos = maxim(v, n - i);
</code>```

is pointless. It calculates, and overwrites, pos repeatedly until the last iteration, which is the only one that is processed with:

```<code>t = v[n - 1 - i];
v[n - 1 - i] = v[pos];
v[pos] = t;
</code>```

E..g, you sort one element, and then exit your sort. You need to sort them all, starting with the full segment, then reducing the size of the segment by one with each iteration after you swap the most-maximum element into position for that segment.

```<code>void sort(int v[], int n)
{
    for (int i=0; i<(n-1); ++i)
    {
        int m = maxim(v, (n-i)); // max of this segment
        int tmp = v[m];
        v[m] = v[n-i-1];
        v[n-i-1] = tmp;
    }
}
</code>```

Body:
Im trying to learn C and I'm doing this program to sort an array but It doesn't work and I'm not sure why, I tested each function and works well, someone knows if its a problem of variables or something?

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

#define N 5

int V[5] = { -383, 386, 277, 415, 293 };

void displayArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        printf("%d ", arr[i]);
}

int maxim(int v[], int n)
{
    int i, m;
    m = v[0];
    /*
    Find maxim element
    */
    for (i = 1; i < n; i++)
        if (v[i] > m)
            m = v[i];
    /*
    Search element position
    */
    for (i = 0; i < N; i++)
        if (v[i] == m)
            return i;
}

void sort(int v[], int n)
{
    int i, pos, t;
    for (i = 0; i < n; i++)
        pos = maxim(v, n - i);

        /*
        Swap elements
        */
        t = v[n - 1 - i];
        v[n - 1 - i] = v[pos];
        v[pos] = t;
}

int main()
{
    displayArray(V, N);
    sort(V, N);
    printf("\n");
    displayArray(V, N);
    return 0;
}

The output is

-383 386 277 415 293 - Original Array

21900 386 277 415 293 - 'Sorted' Array

Body:
First fix your maxim function. Its purpose is to find the maximum index of a  sequence v of magnitude n. Therefore, remembering the maximum value in m is irrelevant; you want to remember where it resides :

int maxim(int v[], int n)
{
    int m=0;
    for (int i=1; i<n; ++i)
    {
        if (v[m] < v[i])
            m = i; // save new max location
    }
    return m;
}

After that, the sort, which is completely wrong. This:

int i, pos, t;
for (i = 0; i < n; i++)
    pos = maxim(v, n - i);

is pointless. It calculates, and overwrites, pos repeatedly until the last iteration, which is the only one that is processed with:

t = v[n - 1 - i];
v[n - 1 - i] = v[pos];
v[pos] = t;

E..g, you sort one element, and then exit your sort. You need to sort them all, starting with the full segment, then reducing the size of the segment by one with each iteration after you swap the most-maximum element into position for that segment.

void sort(int v[], int n)
{
    for (int i=0; i<(n-1); ++i)
    {
        int m = maxim(v, (n-i)); // max of this segment
        int tmp = v[m];
        v[m] = v[n-i-1];
        v[n-i-1] = tmp;
    }
}


问:
How to make a pivot table from a dataframe with multiple columns?
Please help me.

My dataframe looks like this:

date
account
action

2021-01-11
504
login

2021-01-11
504
edit_profile

2021-01-11
504
logout

2021-01-12
11
login

2021-01-12
11
login

2021-01-14
303
edit_profile

2021-01-14
303
logout

What I want to achieve is this:

date
account
login
edit_profile
logout

2021-01-11
504
1
1
1

2021-01-12
11
2
0
0

2021-01-14
303
0
1
1

The first thing I thought about was pivot table, but the problem is that I don't have total count for certain 'account's daily actions. How to count the number of occurrences within a time range for each value? Please help.

答:
Could this work?

Get the piece of dataframe during a certain period of time:

```<code>new_df = df[start_date < df['date'] < end_date]
</code>```

new_df now has all the rows during a certain period of time.
Get all the unique account values:

```<code>accounts = new_df['account'].unique()
</code>```

Then create a for loop to go through all of the accounts action:

```<code># Dataframe that keeps track of the actions
actions_df

for  account in accounts:
    # Get all the rows with certain user
    user_df = new_df[new_df['account'] == account]
    # We now have all the rows that has certain account in user_df
    for action in user_df['action']:
        if action == "login":
            actions_df[action_df['account'] == account]['login'] += 1
</code>```

Now we have all the actions in action_df dataframe

Hope this helps in any way!

Body:
Could this work?

Get the piece of dataframe during a certain period of time:

new_df = df[start_date < df['date'] < end_date]

new_df now has all the rows during a certain period of time.
Get all the unique account values:

accounts = new_df['account'].unique()

Then create a for loop to go through all of the accounts action:

# Dataframe that keeps track of the actions
actions_df

for  account in accounts:
    # Get all the rows with certain user
    user_df = new_df[new_df['account'] == account]
    # We now have all the rows that has certain account in user_df
    for action in user_df['action']:
        if action == "login":
            actions_df[action_df['account'] == account]['login'] += 1

Now we have all the actions in action_df dataframe

Hope this helps in any way!


问:
Changing background color of selected item in recyclerview
How to change the background color of only selected view in my recycle view example?only the background color of clicked itemview needs to be changed.
Only one selected item must be displayed with background color change at a time and the rest needs to be as before selecting.
here is my code :

MainActivity

```<code>public class MainActivity extends AppCompatActivity {
RecyclerView rv1;
    private  final String android_versions[]={
                "Donut",
                "Eclair",
                "Froyo",
                "Gingerbread",
                "Honeycomb",
                "Ice Cream Sandwich",
                "Jelly Bean",
                "KitKat",
                "Lollipop",
                "Marshmallow"
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }

    private  void initViews(){
        rv1=(RecyclerView)findViewById(R.id.recyclerView1);
        rv1.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(getApplicationContext());
        rv1.setLayoutManager(layoutManager);

        RecyclerDataAdapter rda=new RecyclerDataAdapter(rv1,getApplicationContext(),android_versions);
        rv1.setAdapter(rda);
    }
}
</code>```

RecyclerDataadapter

```<code>public class RecyclerDataAdapter extends RecyclerView.Adapter<RecyclerDataAdapter.ViewHolder> {

private String android_versionnames[];
    private Context context1;

    private RecyclerView mRecyclerView;

    public RecyclerDataAdapter(RecyclerView recylcerView,Context context,String android_versionnames[]){
        this.android_versionnames=android_versionnames;
        this.context1=context;
mRecyclerView=recylcerView;
        setHasStableIds(true);
        System.out.println("Inside dataadapter,Android names : \n ");
        for(int i=0;i<android_versionnames.length;i++){
            System.out.println("\n"+android_versionnames[i]);
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.tv1.setText(android_versionnames[position]);
    }

    @Override
    public int getItemCount() {
        return android_versionnames.length;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView tv1;
        LinearLayout row_linearlayout;
        RecyclerView rv2;

        public ViewHolder(final View itemView) {
            super(itemView);
            tv1=(TextView)itemView.findViewById(R.id.txtView1);
            row_linearlayout=(LinearLayout)itemView.findViewById(R.id.row_linrLayout);
            rv2=(RecyclerView)itemView.findViewById(R.id.recyclerView1);
            /*itemView.setBackgroundColor(0x00000000);//to transparent*/

        }
    }
}
</code>```

答:
The response from @Sudhanshu Vohra above was the best in my case and much simpler.
I did minor changes to handle the new selection and previous selection to adjust the display.

I modified it as:

```<code>     //Handle selected item and previous selection
       if (lastSelectedIndex != -1) {
             notifyItemChanged(lastSelectedIndex);
        }

        notifyItemChanged(bindingAdapterPosition);
       lastSelectedIndex = bindingAdapterPosition;
</code>```

Now I refresh only two items, rather than the entire list and it works like a charm. Thank you.

Body:
How to change the background color of only selected view in my recycle view example?only the background color of clicked itemview needs to be changed.
Only one selected item must be displayed with background color change at a time and the rest needs to be as before selecting.
here is my code :

MainActivity

public class MainActivity extends AppCompatActivity {
RecyclerView rv1;
    private  final String android_versions[]={
                "Donut",
                "Eclair",
                "Froyo",
                "Gingerbread",
                "Honeycomb",
                "Ice Cream Sandwich",
                "Jelly Bean",
                "KitKat",
                "Lollipop",
                "Marshmallow"
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }

    private  void initViews(){
        rv1=(RecyclerView)findViewById(R.id.recyclerView1);
        rv1.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(getApplicationContext());
        rv1.setLayoutManager(layoutManager);

        RecyclerDataAdapter rda=new RecyclerDataAdapter(rv1,getApplicationContext(),android_versions);
        rv1.setAdapter(rda);
    }
}

RecyclerDataadapter

public class RecyclerDataAdapter extends RecyclerView.Adapter<RecyclerDataAdapter.ViewHolder> {

private String android_versionnames[];
    private Context context1;

    private RecyclerView mRecyclerView;

    public RecyclerDataAdapter(RecyclerView recylcerView,Context context,String android_versionnames[]){
        this.android_versionnames=android_versionnames;
        this.context1=context;
mRecyclerView=recylcerView;
        setHasStableIds(true);
        System.out.println("Inside dataadapter,Android names : \n ");
        for(int i=0;i<android_versionnames.length;i++){
            System.out.println("\n"+android_versionnames[i]);
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.tv1.setText(android_versionnames[position]);
    }

    @Override
    public int getItemCount() {
        return android_versionnames.length;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView tv1;
        LinearLayout row_linearlayout;
        RecyclerView rv2;

        public ViewHolder(final View itemView) {
            super(itemView);
            tv1=(TextView)itemView.findViewById(R.id.txtView1);
            row_linearlayout=(LinearLayout)itemView.findViewById(R.id.row_linrLayout);
            rv2=(RecyclerView)itemView.findViewById(R.id.recyclerView1);
            /*itemView.setBackgroundColor(0x00000000);//to transparent*/

        }
    }
}

Body:
The response from @Sudhanshu Vohra above was the best in my case and much simpler.
I did minor changes to handle the new selection and previous selection to adjust the display.

I modified it as:

     //Handle selected item and previous selection
       if (lastSelectedIndex != -1) {
             notifyItemChanged(lastSelectedIndex);
        }

        notifyItemChanged(bindingAdapterPosition);
       lastSelectedIndex = bindingAdapterPosition;

Now I refresh only two items, rather than the entire list and it works like a charm. Thank you.


问:
Adding single value to speciifc dataframe column
I have a dataframe like:

```<code>principalDf =

    |   x   ||   y   ||   z   ||   values   |
    |  x0   ||  y0   ||  z0   ||   areal    |
    |  x1   ||  y1   ||  z1   ||   aimag    |
    |  x2   ||  y2   ||  z2   ||   breal    |
    |  x3   ||  y3   ||  z3   ||   bimag    |
</code>```

I want to produce:

```<code>frobprincipalDf =

|       x       ||       y       ||       z       ||   values   |
|sqrt(x0^2+x1^2)||sqrt(y0^2+y1^2)||sqrt(z0^2+z1^2)||     a      |
|sqrt(x2^2+x3^2)||sqrt(y2^2+y3^2)||sqrt(z2^2+z3^2)||     b      |
</code>```

I'm generating the required x, y and z data by:

```<code>frobprincipalDf = pd.DataFrame(columns=principalDf.columns)

for col in principalDf.columns[:-1]:
    for index in range(0,len(principalDf),2):
        frobnorm = np.sqrt(principalDf[col].iloc[index]**2+principalDf[col].iloc[index+1]**2)
        print(frobnorm)
</code>```

How can I add frobnorm to a specific col in the newly created frobprincipalDf?

Is there a better way to do this than nested for loops?

It should be generalisable for any value name, such that if another value begins with a, it will not 'group' them together.

It looks as though the below is a complete solution to the initial problem of even-index pairs of rows addition. This is slightly modified answer of quasi-human's answer. The secondary problem of adding a single value to a specific df column is still there though.

```<code>frobprincipalDf = np.sqrt(principalDf[['x', 'y', 'z']].shift() ** 2 + principalDf[['x', 'y', 'z']] ** 2)
frobprincipalDf = pd.concat([frobprincipalDf,principalDf['values'].str[:2]], axis=1)
frobprincipalDf = frobprincipalDf[frobprincipalDf.index % 2 == 1].reset_index(drop=True)
</code>```

答:
You could use groupby+agg:

import numpy as np

group = df['values'].str.extract('(.*)(?:real|imag)', expand=False)
# 0    a
# 1    a
# 2    b
# 3    b

(df.select_dtypes('number')
   .groupby(group)
   .agg(lambda x: np.sqrt((x**2).sum()))
   .reset_index()
)
```
<p>example input:</p>
```    x   y   z values
0   1   2   3  areal
1   4   5   6  aimag
2   7   8   9  breal
3  10  11  12  bimag
```
<p>output:</p>
```  values          x          y          z
0      a   4.123106   5.385165   6.708204
1      b  12.206556  13.601471  15.000000
```

Body:
I have a dataframe like:

principalDf =

    |   x   ||   y   ||   z   ||   values   |
    |  x0   ||  y0   ||  z0   ||   areal    |
    |  x1   ||  y1   ||  z1   ||   aimag    |
    |  x2   ||  y2   ||  z2   ||   breal    |
    |  x3   ||  y3   ||  z3   ||   bimag    |

I want to produce:

frobprincipalDf =

|       x       ||       y       ||       z       ||   values   |
|sqrt(x0^2+x1^2)||sqrt(y0^2+y1^2)||sqrt(z0^2+z1^2)||     a      |
|sqrt(x2^2+x3^2)||sqrt(y2^2+y3^2)||sqrt(z2^2+z3^2)||     b      |

I'm generating the required x, y and z data by:

frobprincipalDf = pd.DataFrame(columns=principalDf.columns)

for col in principalDf.columns[:-1]:
    for index in range(0,len(principalDf),2):
        frobnorm = np.sqrt(principalDf[col].iloc[index]**2+principalDf[col].iloc[index+1]**2)
        print(frobnorm)

How can I add frobnorm to a specific col in the newly created frobprincipalDf?

Is there a better way to do this than nested for loops?

It should be generalisable for any value name, such that if another value begins with a, it will not 'group' them together.

It looks as though the below is a complete solution to the initial problem of even-index pairs of rows addition. This is slightly modified answer of quasi-human's answer. The secondary problem of adding a single value to a specific df column is still there though.

frobprincipalDf = np.sqrt(principalDf[['x', 'y', 'z']].shift() ** 2 + principalDf[['x', 'y', 'z']] ** 2)
frobprincipalDf = pd.concat([frobprincipalDf,principalDf['values'].str[:2]], axis=1)
frobprincipalDf = frobprincipalDf[frobprincipalDf.index % 2 == 1].reset_index(drop=True)

Body:
You could use groupby+agg:

import numpy as np

group = df['values'].str.extract('(.*)(?:real|imag)', expand=False)
# 0    a
# 1    a
# 2    b
# 3    b

(df.select_dtypes('number')
   .groupby(group)
   .agg(lambda x: np.sqrt((x**2).sum()))
   .reset_index()
)

example input:

    x   y   z values
0   1   2   3  areal
1   4   5   6  aimag
2   7   8   9  breal
3  10  11  12  bimag

output:

  values          x          y          z
0      a   4.123106   5.385165   6.708204
1      b  12.206556  13.601471  15.000000


问:
React connection to Django
There is a built React project with the following file structure:
img or:

```<code>dist
| assets
| | css
| | | appPage.blablabla.css
| | img
| | | mainPanel
| | | palettePanel
| | | structuralPanel
| | | workingSpace
| js
| | appPage.blablabla.js
| app.html
</code>```

app.html - main html file

js - folder with js file

assets - foler with folders with some static files

How can I include it to my django app?

答: You must manually configure the react app with webpack if you wish to have the react app in your Django folder. Or you can host it as a static website by running npm run build in react project and put build folder to static folder in your Django folder. Or you can separate both. As server and client.

Title: React connection to Django

Body:
There is a built React project with the following file structure:
img or:

dist
| assets
| | css
| | | appPage.blablabla.css
| | img
| | | mainPanel
| | | palettePanel
| | | structuralPanel
| | | workingSpace
| js
| | appPage.blablabla.js
| app.html

app.html - main html file

js - folder with js file

assets - foler with folders with some static files

How can I include it to my django app?


问:
Inheritance problem in C#
I'm refactoring some code and want to classes a bit higher in the inheritance chain be a bit more strict with their parameters. As I'm not sure I'm explaining this correctly, here's what I've got:

```<code>public interface ISvdPredictor
{
    List<string> Users { get; set; }
    List<string> Artists { get; set; }
    float PredictRating(ISvdModel model, string user, string artist);
    float PredictRating(ISvdModel model, int userIndex, int artistIndex);
}
</code>```

ISvdPredictor uses ISvdModel:

```<code>public interface ISvdModel
{
    float[,] UserFeatures { get; set; }
    float[,] ArtistFeatures { get; set; }
}
</code>```

Now I want to implement another variation:

```<code>public interface IBiasSvdPredictor : ISvdPredictor
{
    float PredictRating(IBiasSvdModel model, string user, string artist);
    float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex);
}
</code>```

Which uses IBiasSvdModel which derives from ISvdModel:

```<code>public interface IBiasSvdModel : ISvdModel
{
    float GlobalAverage { get; set; }
    float[] UserBias { get; set; }
    float[] ArtistBias { get; set; }
}
</code>```

IBiasSvdPredictor will not work with ISvdModel.

The problem is that when I implement IBiasSvdPredictor I'd have to implement 2 pairs of PredictRating methods. One from ISvdPredictor and the other from IBiasSvdPredictor. What do I need to do to be able to just implement those from IBiasSvdPredictor?

I've tried generics as well, but couldn't restrict the PredictRating for BiasSvdPredictor to IBiasSvdModel using the where directive. I may be doing this all wrong so any suggestion might help. I think you get what I'm trying to do.

EDIT: If anyone needs more context see https://github.com/gligoran/RecommendationSystem. I'm writing this code for my thesis for BSc.

答:
You have to implement all four methods. They have different signatures and thus are considered to be different. However, you can have one delegate to the other, and sometimes using explicit implementation helps with that.

```<code>public class Foo : IBiasSvdPredictor {
    public float PredictRating(IBiasSvdModel, string user, string artist) { .... }

    // this is an expicit implementation of ISvdPredictor's method. You satisfy
    // the interface, but this method is not a public part of the class. You have to
    // cast the object to ISvdPredictor in order to use this method.
    float ISvdPredictor.PredictRating(ISvdModel model, string user, string artist) {
        this.PredictRating((IBiasSvdModel)model, user, artist);
    }
}
</code>```

This of course will not work if the ISvdModel is not actually an IBiasSvdModel.

Title: Inheritance problem in C#

Body:
I'm refactoring some code and want to classes a bit higher in the inheritance chain be a bit more strict with their parameters. As I'm not sure I'm explaining this correctly, here's what I've got:

public interface ISvdPredictor
{
    List<string> Users { get; set; }
    List<string> Artists { get; set; }
    float PredictRating(ISvdModel model, string user, string artist);
    float PredictRating(ISvdModel model, int userIndex, int artistIndex);
}

ISvdPredictor uses ISvdModel:

public interface ISvdModel
{
    float[,] UserFeatures { get; set; }
    float[,] ArtistFeatures { get; set; }
}

Now I want to implement another variation:

public interface IBiasSvdPredictor : ISvdPredictor
{
    float PredictRating(IBiasSvdModel model, string user, string artist);
    float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex);
}

Which uses IBiasSvdModel which derives from ISvdModel:

public interface IBiasSvdModel : ISvdModel
{
    float GlobalAverage { get; set; }
    float[] UserBias { get; set; }
    float[] ArtistBias { get; set; }
}

IBiasSvdPredictor will not work with ISvdModel.

The problem is that when I implement IBiasSvdPredictor I'd have to implement 2 pairs of PredictRating methods. One from ISvdPredictor and the other from IBiasSvdPredictor. What do I need to do to be able to just implement those from IBiasSvdPredictor?

I've tried generics as well, but couldn't restrict the PredictRating for BiasSvdPredictor to IBiasSvdModel using the where directive. I may be doing this all wrong so any suggestion might help. I think you get what I'm trying to do.

EDIT: If anyone needs more context see https://github.com/gligoran/RecommendationSystem. I'm writing this code for my thesis for BSc.

Body:
You have to implement all four methods. They have different signatures and thus are considered to be different. However, you can have one delegate to the other, and sometimes using explicit implementation helps with that.

public class Foo : IBiasSvdPredictor {
    public float PredictRating(IBiasSvdModel, string user, string artist) { .... }

    // this is an expicit implementation of ISvdPredictor's method. You satisfy
    // the interface, but this method is not a public part of the class. You have to
    // cast the object to ISvdPredictor in order to use this method.
    float ISvdPredictor.PredictRating(ISvdModel model, string user, string artist) {
        this.PredictRating((IBiasSvdModel)model, user, artist);
    }
}

This of course will not work if the ISvdModel is not actually an IBiasSvdModel.


问:
Change Next.js background color with TailwindCSS
I recently started with Next.js and TailwindCSS and I wanted to change the background of my page. It is probably a really simple thing to do but I can't figure it out how to do. You can't add classes to the body tag in Next.js right? I tried to wrap the Component in the _app.tsx with a div but that is also wrapped inside a different div, so the background color isn't the full height.

How should I set the background color for my application and is it also possible to overrule it for a single page?

答:
Add it using your stylesheet (styles/globals.css in case of the official example):

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  body {
    @apply bg-slate-900;
  }
}
```
<hr />
<p>You can also create a custom document:</p>
```// pages/_document.js

import { Html, Head, Main, NextScript } from 'next/document'

const Document = () => (

      <NextScript />

)

export default Document
```

If you want to do it on per-page basis, refer this: vercel/next.js#12325 (comment)

Body:
Add it using your stylesheet (styles/globals.css in case of the official example):

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  body {
    @apply bg-slate-900;
  }
}

You can also create a custom document:

// pages/_document.js

import { Html, Head, Main, NextScript } from 'next/document'

const Document = () => (
  <Html>
    <Head />
    <body className="bg-slate-900">
      <Main />
      <NextScript />
    </body>
  </Html>
)

export default Document

If you want to do it on per-page basis, refer this: vercel/next.js#12325 (comment)


问:
Your current user or role does not have access to Kubernetes objects on this EKS cluster
Don't know if this is an error from AWS or something. I created an IAM user and gave it full admin policies. I then used this user to create an EKS cluster using the eksctl CLI but when I logging to AWS console with the root user I got the below error while trying to access the cluster nodes.

Your current user or role does not have access to Kubernetes objects on this EKS cluster
This may be due to the current user or role not having Kubernetes RBAC permissions to describe cluster resources or not having an entry in the cluster’s auth config map.

I have these questions

Does not the root user have full access to view every resource from the console?

If the above is true, does it mean when I create a resource from the CLI I must login with the same user to view it?

Or is there way I could attach policies to the root user? Didn't see anything like in the console.

AWS itself does not recommend creating access keys for root user and using it for programmable access, so I'm so confused right now. Someone help

All questions I have seen so far and the link to the doc here are talking about a user or role created in the AWS IAM and not the root user.

答:
I had this issue today, and solved it by combining answers here. The aws-auth config after it worked looks like this:</p>
```<code>apiVersion: v1
data:
  mapRoles: |
    - groups:
      - system:bootstrappers
      - system:nodes
      rolearn: arn:aws:iam::671177010163:role/eksctl-manu-eks-new2-nodegroup-ng-NodeInstanceRole-1NYUHVMYFP2TK
      username: system:node:{{EC2PrivateDNSName}}
  mapUsers: "- groups: \n  - system:masters\n  userarn: arn:aws:iam::671177010163:root\n"
kind: ConfigMap
metadata:
  creationTimestamp: "2022-02-13T11:03:30Z"
  name: aws-auth
  namespace: kube-system
  resourceVersion: "11362"
  uid: ac36a1d9-76bc-40dc-95f0-b1e7934357
</code>```

Body:
I had this issue today, and solved it by combining answers here. The aws-auth config after it worked looks like this:

apiVersion: v1
data:
  mapRoles: |
    - groups:
      - system:bootstrappers
      - system:nodes
      rolearn: arn:aws:iam::671177010163:role/eksctl-manu-eks-new2-nodegroup-ng-NodeInstanceRole-1NYUHVMYFP2TK
      username: system:node:{{EC2PrivateDNSName}}
  mapUsers: "- groups: \n  - system:masters\n  userarn: arn:aws:iam::671177010163:root\n"
kind: ConfigMap
metadata:
  creationTimestamp: "2022-02-13T11:03:30Z"
  name: aws-auth
  namespace: kube-system
  resourceVersion: "11362"
  uid: ac36a1d9-76bc-40dc-95f0-b1e7934357


问:
Adding just a left side border decoration
I'm aware of this post how to assign a border to e.g. a Container.

Unfortunately, I failed to find a hint how to only draw the left edge of a Container as a border.

How to assign a border only to one edge of a Widget / Container?

答:
You can add one side border like so

Container(
  decoration: BoxDecoration(
     border: Border(left: BorderSide(width: 1, color: Colors.red)
  ),
  child: //...,
)
```

There are also right, top, and bottom params

Body:
You can add one side border like so

Container(
  decoration: BoxDecoration(
     border: Border(left: BorderSide(width: 1, color: Colors.red)
  ),
  child: //...,
)

There are also right, top, and bottom params


问:
How to transform the ticker just like ‘EURUSD’ to ‘EUR_USD’?
I got the ticker from syminfo.ticker just like ‘EURUSD’,and sent to oanda through autoview but not accepted because the ticker shall be ‘EUR_USD’.

How do I add ‘_’ in the middle of ticker in pine-script?

Thanks.

答:
I try to use this code to solve the adding "_" problem.Is it correct?</p>
```<code>var symbol = str.substring(syminfo.ticker,0, str.length(syminfo.ticker)-str.length(syminfo.currency)) + '_' + syminfo.currency
</code>```

Body:
I try to use this code to solve the adding "_" problem.Is it correct?

var symbol = str.substring(syminfo.ticker,0, str.length(syminfo.ticker)-str.length(syminfo.currency)) + '_' + syminfo.currency


答:
```<code>pos = maxim(v, n - i);
</code>```

should be

```<code>pos = maxim(v, n);
</code>```

Title: Why this program to sort array doesnt work?

Body:
pos = maxim(v, n - i);

should be

pos = maxim(v, n);


问:
Django REST Framework - Define extra arguments using the @action decorator
I'm wondering if would be possible to define extra arguments using the action decorator:

```<code>class UserViewSet(viewsets.ModelViewSet):
    """
    A viewset that provides the standard actions
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

    @action(methods=['post'], detail=True)
    def follow(self, request, pk=None):
        user = self.get_object()
        target_user = ???
        Follow.objects.create(user=user, target=target_user)
        return Response(status=status.HTTP_204_NO_CONTENT)
</code>```

What I want to achieve is matching the following path: api/users/{id}/follow/{target_id}

The follow action will be used to let an user with ID id following another user with ID target_id.

UPDATE:

Since it seems like it's not possible to pass extra args, right now I'm POSTing data as a list of user IDs to be followed:

The serializer to validate data:

```<code>class FollowSerializer(serializers.ModelSerializer):
    user_ids = serializers.ListField(child=serializers.IntegerField(min_value=1), required=False, help_text='User target IDs')
</code>```

The action:

```<code>    @action(detail=True, methods=['post'])
    def follow(self, request, pk=None):
        user = self.get_object()
        serializer = FollowSerializer(data=request.data)
        if serializer.is_valid():
            serializer.data['user_ids']
            for user_id in user_ids:
                target_user = User.objects.get(pk=user_id)
                Follow.objects.create(user=user, target=target_user)
            return Response(status=status.HTTP_204_NO_CONTENT)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code>```

The problem with my solution is that on the auto-generated doc page I'm seeing the form with the UserSerializer fields.

UPDATE 2:

The following trick let the auto-generated doc page shows the right form:

```<code>class UserViewSet(viewsets.ModelViewSet):
    """
    A viewset that provides the standard actions
    """
    queryset = User.objects.all()

    def get_serializer_class(self):
        if self.action == 'follow':
            return FollowSerializer
        else:
            return UserSerializer

    @action(methods=['post'], detail=True)
    def follow(self, request, pk=None):
        ...
</code>```

答:
Indeed you can accept extra kwargs as follows DRF 3.13.x without touching routers, neat DRF:

@action(detail=True, methods=['delete'], url_name='media-delete',
        url_path='delete_media/(?P<media_pk>[^/.]+)')
def delete_media(self, request, pk=None, media_pk=None):
    # do your logic
    return Response({}, status=status.HTTP_202_ACCEPTED)
```

this will automatically override the default router extra route in response to @action wrapper with ModelViewSet registered routes.

Body:
I'm wondering if would be possible to define extra arguments using the action decorator:

class UserViewSet(viewsets.ModelViewSet):
    """
    A viewset that provides the standard actions
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

    @action(methods=['post'], detail=True)
    def follow(self, request, pk=None):
        user = self.get_object()
        target_user = ???
        Follow.objects.create(user=user, target=target_user)
        return Response(status=status.HTTP_204_NO_CONTENT)

What I want to achieve is matching the following path: api/users/{id}/follow/{target_id}

The follow action will be used to let an user with ID id following another user with ID target_id.

UPDATE:

Since it seems like it's not possible to pass extra args, right now I'm POSTing data as a list of user IDs to be followed:

The serializer to validate data:

class FollowSerializer(serializers.ModelSerializer):
    user_ids = serializers.ListField(child=serializers.IntegerField(min_value=1), required=False, help_text='User target IDs')

The action:

    @action(detail=True, methods=['post'])
    def follow(self, request, pk=None):
        user = self.get_object()
        serializer = FollowSerializer(data=request.data)
        if serializer.is_valid():
            serializer.data['user_ids']
            for user_id in user_ids:
                target_user = User.objects.get(pk=user_id)
                Follow.objects.create(user=user, target=target_user)
            return Response(status=status.HTTP_204_NO_CONTENT)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

The problem with my solution is that on the auto-generated doc page I'm seeing the form with the UserSerializer fields.

UPDATE 2:

The following trick let the auto-generated doc page shows the right form:

class UserViewSet(viewsets.ModelViewSet):
    """
    A viewset that provides the standard actions
    """
    queryset = User.objects.all()

    def get_serializer_class(self):
        if self.action == 'follow':
            return FollowSerializer
        else:
            return UserSerializer

    @action(methods=['post'], detail=True)
    def follow(self, request, pk=None):
        ...

Body:
Indeed you can accept extra kwargs as follows DRF 3.13.x without touching routers, neat DRF:

@action(detail=True, methods=['delete'], url_name='media-delete',
        url_path='delete_media/(?P<media_pk>[^/.]+)')
def delete_media(self, request, pk=None, media_pk=None):
    # do your logic
    return Response({}, status=status.HTTP_202_ACCEPTED)

this will automatically override the default router extra route in response to @action wrapper with ModelViewSet registered routes.


问:
How to update 2 JCombo Boxs
I have 2 Jcombo Boxs: which is combo1 and combo2

I choose combo1 and I can get information for combo2 but The problem is I can get informatiob for combo2 but it is not updated. I also try to use updata.UI() but it doesn't help.

This is the code in side

```<code>public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox)e.getSource();
    String uname1 = (String)cb.getSelectedItem();

        combo2 = update(uname1);
        combo2.updateUI();

}
</code>```

This is code inside update

```<code>protected JComboBox update(String name) {
    JComboBox tmp = new JComboBox();
    //Read Content from XML file (University is bigger than Year)
    NodeList nList = doc.getElementsByTagName("University");
    System.out.println("Inside Fn " + name);
    for(int i = 0 ; i < nList.getLength();i++) {
        Element el = (Element)nList.item(i);
        if(name.contentEquals(el.getAttributeNode("name").getNodeValue()))
        {
            NodeList tmpyList = el.getElementsByTagName("Year");
            for(int j = 0 ; j < tmpyList.getLength();j++)
            {
                Element yl = (Element)tmpyList.item(j);
                System.out.println(yl.getAttribute("yr"));
                tmp.addItem(yl.getAttribute("yr"));
            }
        }
    }
    return tmp; //Return ComboBox to combo2
}
</code>```

Thank you for your kindness, I try to use your code but it is not work (It still not update), please help me

This is my constructor

```<code>public JFrameExample() {
    String[] comboboxdefault = { "Select" };

    JComboBox combo1 = Universitylist();
    JComboBox combo2 = new JComboBox(comboboxdefault);
    JComboBox combo3 = new JComboBox(comboboxdefault);

    uList.addActionListener(this);
    yList.addActionListener(this);
    dList.addActionListener(this);

    JPanel student_information = new JPanel(new GridLayout(0,1));
    uList.setName("University List");
    yList.setName("Year List");

    // University List

    student_information.add(combo1);
    // Database Year List

    student_information.add(combo2);
    // Programme List

    student_information.add(combo3);
    //Add Components to this container, using the default FlowLayout.
    add(student_information);

}
</code>```

This is the combo2 Update it is return String Array

```<code>protected String[] updateyList(String name)
{
    String[] tmp = null;

           //Read from XML file
    for(int i = 0 ; i < nList.getLength();i++) {
        Element el = (Element)nList.item(i);
        if(name.contentEquals(el.getAttributeNode("name").getNodeValue()))
        {
            NodeList tmpyList = el.getElementsByTagName("Year");
            tmp = new String[tmpyList.getLength()];
            for(int j = 0 ; j < tmpyList.getLength();j++)
            {
                Element yl = (Element)tmpyList.item(j);
                //Add to String Array
                tmp[j] = yl.getAttribute("yr");
            }
        }
    }

    return tmp;
}
</code>```

In the Action Perform

```<code>public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox)e.getSource();
    String uname1 = (String)cb.getSelectedItem();
    System.out.println(cb.getName()); // To make sure I got the combo1.
    try {
        //I change to the model method
        DefaultComboBoxModel model = new DefaultComboBoxModel(  updateyList(uname1) );
        System.out.println(model.getSize());
        combo2 = new JComboBox(); // If I don't have this line it will throw  error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        combo2.setModel(model);

    } catch (ParserConfigurationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (SAXException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

}
</code>```

And this is for creating GUI function

```<code>private static void createAndShowLoginGUI() {

   //Create and set up the window.
    JFrame frame = new JFrame("Login");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create and set up the content pane.
    JFrameExample newContentPane = new JFrameExample();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}
</code>```

This is main function

```<code>public static void main(String[] args)
{
    //Schedule a job for the event-dispatching thread:

    //creating and showing this application's GUI.

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowLoginGUI();
        }
    });
}
</code>```

I think I did something wrong but I don't know where

答:
There is no need to use the updateUI() method.

If you want to change the data in the second combo box then you should change the model (DON'T create a new combo box):

```<code>comboBox2.setModel(...);
</code>```

It will repaint itself automaitcally. You can create a DefaultComboBoxModel and add the data directly to it.

Edit:

```<code>import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class ComboBoxTwo extends JFrame implements ActionListener
{
    private JComboBox mainComboBox;
    private JComboBox subComboBox;
    private Hashtable subItems = new Hashtable();

    public ComboBoxTwo()
    {
        String[] items = { "Select Item", "Color", "Shape", "Fruit" };
        mainComboBox = new JComboBox( items );
        mainComboBox.addActionListener( this );

        //  prevent action events from being fired when the up/down arrow keys are used
        mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
        getContentPane().add( mainComboBox, BorderLayout.WEST );

        //  Create sub combo box with multiple models

        subComboBox = new JComboBox();
        subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
        getContentPane().add( subComboBox, BorderLayout.EAST );

        String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
        subItems.put(items[1], subItems1);

        String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
        subItems.put(items[2], subItems2);

        String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
        subItems.put(items[3], subItems3);
//      mainComboBox.setSelectedIndex(1);
    }

    public void actionPerformed(ActionEvent e)
    {
        String item = (String)mainComboBox.getSelectedItem();
        Object o = subItems.get( item );

        if (o == null)
        {
            subComboBox.setModel( new DefaultComboBoxModel() );
        }
        else
        {
            subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
        }
    }

    public static void main(String[] args)
    {
        JFrame frame = new ComboBoxTwo();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
     }
}
</code>```

Title: How to update 2 JCombo Boxs

Body:
I have 2 Jcombo Boxs: which is combo1 and combo2

I choose combo1 and I can get information for combo2 but The problem is I can get informatiob for combo2 but it is not updated. I also try to use updata.UI() but it doesn't help.

This is the code in side

public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox)e.getSource();
    String uname1 = (String)cb.getSelectedItem();

        combo2 = update(uname1);
        combo2.updateUI();

}

This is code inside update

protected JComboBox update(String name) {
    JComboBox tmp = new JComboBox();
    //Read Content from XML file (University is bigger than Year)
    NodeList nList = doc.getElementsByTagName("University");
    System.out.println("Inside Fn " + name);
    for(int i = 0 ; i < nList.getLength();i++) {
        Element el = (Element)nList.item(i);
        if(name.contentEquals(el.getAttributeNode("name").getNodeValue()))
        {
            NodeList tmpyList = el.getElementsByTagName("Year");
            for(int j = 0 ; j < tmpyList.getLength();j++)
            {
                Element yl = (Element)tmpyList.item(j);
                System.out.println(yl.getAttribute("yr"));
                tmp.addItem(yl.getAttribute("yr"));
            }
        }
    }
    return tmp; //Return ComboBox to combo2
}

Thank you for your kindness, I try to use your code but it is not work (It still not update), please help me

This is my constructor

public JFrameExample() {
    String[] comboboxdefault = { "Select" };

    JComboBox combo1 = Universitylist();
    JComboBox combo2 = new JComboBox(comboboxdefault);
    JComboBox combo3 = new JComboBox(comboboxdefault);

    uList.addActionListener(this);
    yList.addActionListener(this);
    dList.addActionListener(this);

    JPanel student_information = new JPanel(new GridLayout(0,1));
    uList.setName("University List");
    yList.setName("Year List");

    // University List

    student_information.add(combo1);
    // Database Year List

    student_information.add(combo2);
    // Programme List

    student_information.add(combo3);
    //Add Components to this container, using the default FlowLayout.
    add(student_information);

}

This is the combo2 Update it is return String Array

protected String[] updateyList(String name)
{
    String[] tmp = null;

           //Read from XML file
    for(int i = 0 ; i < nList.getLength();i++) {
        Element el = (Element)nList.item(i);
        if(name.contentEquals(el.getAttributeNode("name").getNodeValue()))
        {
            NodeList tmpyList = el.getElementsByTagName("Year");
            tmp = new String[tmpyList.getLength()];
            for(int j = 0 ; j < tmpyList.getLength();j++)
            {
                Element yl = (Element)tmpyList.item(j);
                //Add to String Array
                tmp[j] = yl.getAttribute("yr");
            }
        }
    }

    return tmp;
}

In the Action Perform

public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox)e.getSource();
    String uname1 = (String)cb.getSelectedItem();
    System.out.println(cb.getName()); // To make sure I got the combo1.
    try {
        //I change to the model method
        DefaultComboBoxModel model = new DefaultComboBoxModel(  updateyList(uname1) );
        System.out.println(model.getSize());
        combo2 = new JComboBox(); // If I don't have this line it will throw  error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        combo2.setModel(model);

    } catch (ParserConfigurationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (SAXException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

}

And this is for creating GUI function

private static void createAndShowLoginGUI() {

   //Create and set up the window.
    JFrame frame = new JFrame("Login");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create and set up the content pane.
    JFrameExample newContentPane = new JFrameExample();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

This is main function

public static void main(String[] args)
{
    //Schedule a job for the event-dispatching thread:

    //creating and showing this application's GUI.

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowLoginGUI();
        }
    });
}

I think I did something wrong but I don't know where

Body:
There is no need to use the updateUI() method.

If you want to change the data in the second combo box then you should change the model (DON'T create a new combo box):

comboBox2.setModel(...);

It will repaint itself automaitcally. You can create a DefaultComboBoxModel and add the data directly to it.

Edit:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class ComboBoxTwo extends JFrame implements ActionListener
{
    private JComboBox mainComboBox;
    private JComboBox subComboBox;
    private Hashtable subItems = new Hashtable();

    public ComboBoxTwo()
    {
        String[] items = { "Select Item", "Color", "Shape", "Fruit" };
        mainComboBox = new JComboBox( items );
        mainComboBox.addActionListener( this );

        //  prevent action events from being fired when the up/down arrow keys are used
        mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
        getContentPane().add( mainComboBox, BorderLayout.WEST );

        //  Create sub combo box with multiple models

        subComboBox = new JComboBox();
        subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
        getContentPane().add( subComboBox, BorderLayout.EAST );

        String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
        subItems.put(items[1], subItems1);

        String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
        subItems.put(items[2], subItems2);

        String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
        subItems.put(items[3], subItems3);
//      mainComboBox.setSelectedIndex(1);
    }

    public void actionPerformed(ActionEvent e)
    {
        String item = (String)mainComboBox.getSelectedItem();
        Object o = subItems.get( item );

        if (o == null)
        {
            subComboBox.setModel( new DefaultComboBoxModel() );
        }
        else
        {
            subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
        }
    }

    public static void main(String[] args)
    {
        JFrame frame = new ComboBoxTwo();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
     }
}