问:
I'm unable to use parsed variable from http request widget
I'm using Twilio Studio. Within I'm using the Make HTTP Request widget to hit an api endpoint.

After that I'm using a Say/Play widget to say one of the variables from Make HTTP Request. {{widgets.http_1.body}} works fine with api response:

```<code>{ "message": "Hello World", "completed": true }
</code>```

However, if I want to return {{widgets.http_1.parsed.message}} the say text portion for this will be empty.

What might be wrong here? I can see the endpoint I hit with the Make HTTP Request step returns a 200 & the json is valid.

Flow - Make HTTP Request - Say Widget

答:
Twilio developer evangelist here.

Your screenshot of the Say widget shows that you are using {{ widgets.http_1.body.parsed.message }}. When using the parsed data, you don't need the body in there, so it should just be:

```<code>{{ widgets.http_1.parsed.message }}
</code>```

Body:
I'm using Twilio Studio. Within I'm using the Make HTTP Request widget to hit an api endpoint.

After that I'm using a Say/Play widget to say one of the variables from Make HTTP Request. {{widgets.http_1.body}} works fine with api response:

{ "message": "Hello World", "completed": true }

However, if I want to return {{widgets.http_1.parsed.message}} the say text portion for this will be empty.

What might be wrong here? I can see the endpoint I hit with the Make HTTP Request step returns a 200 & the json is valid.

Flow - Make HTTP Request - Say Widget

Body:
Twilio developer evangelist here.

Your screenshot of the Say widget shows that you are using {{ widgets.http_1.body.parsed.message }}. When using the parsed data, you don't need the body in there, so it should just be:

{{ widgets.http_1.parsed.message }}


来源: stackexchange

问:
Indy 10 error when try to install a new version in Delphi XE3
I'm trying to install a new version of Indy 10 in Delphi XE3.

I'm using the Fullc_XE3.bat to compile the component, it works and finish OK, however, when I try to install dclIndyCore170.bpl I get the next popup error:

Procedure entry point not found @Idstack@TIdStackLocalAddressList@GetAddress$qqri in the dynamic link library D:\Entorno XE3\COMPONENTES\Indy-master\C17\Win32\Release\dclIndyCore170.bpl

I don't know what I'm doing wrong, I cleaned Delphi's Indy installation, deleting all indy files: dcp, dcu, pas, bpl.

Could you help me please?

答:
First off, if you are doing a DELPHI installation, you should NOT be using the Fullc_XE3.bat script at all. That script is meant only for a C++BUILDER installation instead (the c in the filename stands for C++).  For Delphi, simply open Indy's 5 .dpk packages (or the Indy170.groupproj project group) directly in the IDE and use the Project Manager's Compile and Install options.

Second, Delphi XE3 was released in September 2012, but TIdStackLocalAddressList was introduced in April 2013 for Indy 10.6.0 in XE4.  So, you have clearly NOT cleared out the old Indy version that shipped with XE3 before installing the new Indy version.  Your IDE is encountering an old binary that was left behind.

ContentLicense: CC BY-SA 4.0


问:
Lambda expression in ternary operator
I am trying to write following code but is throwing error:

```<code>a = [x if lambda x:  x%2 ==0 else 0 for x in range(10)]
print(a)
</code>```

The error is pointing at lambda statement. Is it illegal to use her? Of yes then why because all my function is returning is the Boolean True or False.

答:
lambda x:  x%2 ==0  is a function, not a condition.

Why not use this instead?

a = [x if x%2 == 0 else 0 for x in range(10)]
print(a)
```

Title: Lambda expression in ternary operator

Body:
I am trying to write following code but is throwing error:

a = [x if lambda x:  x%2 ==0 else 0 for x in range(10)]
print(a)

The error is pointing at lambda statement. Is it illegal to use her? Of yes then why because all my function is returning is the Boolean True or False.


问:
I couldn´t install react with npx create-react-app my-app?
I am trying to use npx create-react app but i have errors that is shown below:

```<code> npm ERR! could not determine executable to run

 npm ERR! A complete log of this run can be found in:
 npm ERR! C:\Users\user\AppData\Local\npm-cache\_logs\2022-02-08T13_57_59_084Z-debug-0.log
</code>```

I had this error after using a command in my windows terminal:

```<code>npm install -g create-react-app
</code>```

It throws:

```<code>npm WARN deprecated tar@2.2.2: This version of tar is no longer supported, and will not receive security updates. Please upgrade asap.

added 67 packages, and audited 69 packages in 15s

2 high severity vulnerabilities

Some issues need review, and may require choosing
a different dependency.

Run `npm audit` for details.
</code>```

答:
This seems like a similar issue to this question: npm WARN deprecated tar@2.2.2: This version of tar is no longer supported, and will not receive security updates. Please upgrade asap

The accepted answer was to update tar using the command npm i tar

Body:
I am trying to use npx create-react app but i have errors that is shown below:

 npm ERR! could not determine executable to run

 npm ERR! A complete log of this run can be found in:
 npm ERR! C:\Users\user\AppData\Local\npm-cache\_logs\2022-02-08T13_57_59_084Z-debug-0.log

I had this error after using a command in my windows terminal:

npm install -g create-react-app

It throws:

npm WARN deprecated tar@2.2.2: This version of tar is no longer supported, and will not receive security updates. Please upgrade asap.

added 67 packages, and audited 69 packages in 15s

2 high severity vulnerabilities

Some issues need review, and may require choosing
a different dependency.

Run `npm audit` for details.


问:
Image not showing up in README.md on GitHub
I am trying to add an image to the README.md in my repository using markdown below:

```<code>![ScreenShot](https://github.com/i-saumitra/Voice-controlled-MP3-Player/blob/master/screenshot.jpg)
</code>```

But the image is not showing when I visit my repository.
Instead the link to the image is showing up. Clicking the link will open the image in new window.

I have also tried using relative path:

```<code>![ScreenShot](screenshot.jpg)
</code>```

But this is giving page not found error.

What is the correct markdown to display image in README.md

Both README.md and image file are in same path/directory.

What is the correct way to display an image in github README.md?

Complete content of README.md file is as below:

```<code>Voice-controlled-MP3-Player
===========================

A MP3 player which accept voice command like PLAY, PAUSE, FORWARD, etc. Using C# and Microsoft Speech API.

![ScreenShot](https://github.com/i-saumitra/Voice-controlled-MP3-Player/blob/master/screenshot.jpg)
</code>```

答: It doesn;t work when there are any html tags just above the line where image is being imported. You can try removing the html code or add some blank lines for the image to show on Readme.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to add an image to the README.md in my repository using markdown below:

![ScreenShot](https://github.com/i-saumitra/Voice-controlled-MP3-Player/blob/master/screenshot.jpg)

But the image is not showing when I visit my repository.
Instead the link to the image is showing up. Clicking the link will open the image in new window.

I have also tried using relative path:

![ScreenShot](screenshot.jpg)

But this is giving page not found error.

What is the correct markdown to display image in README.md

Both README.md and image file are in same path/directory.

What is the correct way to display an image in github README.md?

Complete content of README.md file is as below:

Voice-controlled-MP3-Player
===========================

A MP3 player which accept voice command like PLAY, PAUSE, FORWARD, etc. Using C# and Microsoft Speech API.

![ScreenShot](https://github.com/i-saumitra/Voice-controlled-MP3-Player/blob/master/screenshot.jpg)


问:
using async/await with firebase
I'm trying to use async/await to get images from firebase storage, and this is my function:

```<code>import { ref as sRef, getDownloadURL } from "firebase/storage";
...
async getCharacterIconUrl(character) {
  return await getDownloadURL(sRef(storage, `characters/${character}/icon`));
}
</code>```

And then, I use this function here:

```<code>import { ref, child, get } from "firebase/database";
...
async componentDidMount() {
  const dbRef = ref(db);

  let snapshot = await get(child(dbRef, "en/characters"));
  if (snapshot.exists()) {
    let characters = Object.keys(snapshot.val()).map((key) => {
      return {
        _id: key,
        img: this.getCharacterIconUrl(key),
        ...snapshot.val()[key],
      };
    });
    this.setState({ characters: characters });
  } else {
    console.log("No data available");
  }
}
</code>```

The problem I have is that img inside characters is never resolved.

How can I solve this?

答:
Your getCharacterIconUrl function is async so you need to await it.

Try this...

const characters = await Promise.all(
  Object.entries(snapshot.val()).map(async ([_id, val]) => ({
    _id,
    img: await this.getCharacterIconUrl(_id),
    ...val,
  }))
)
this.setState({ characters });
```

Note that the .map() callback is also async. I'm also using Object.entries() since you want both keys and values.

Title: using async/await with firebase

Body:
I'm trying to use async/await to get images from firebase storage, and this is my function:

import { ref as sRef, getDownloadURL } from "firebase/storage";
...
async getCharacterIconUrl(character) {
  return await getDownloadURL(sRef(storage, `characters/${character}/icon`));
}

And then, I use this function here:

import { ref, child, get } from "firebase/database";
...
async componentDidMount() {
  const dbRef = ref(db);

  let snapshot = await get(child(dbRef, "en/characters"));
  if (snapshot.exists()) {
    let characters = Object.keys(snapshot.val()).map((key) => {
      return {
        _id: key,
        img: this.getCharacterIconUrl(key),
        ...snapshot.val()[key],
      };
    });
    this.setState({ characters: characters });
  } else {
    console.log("No data available");
  }
}

The problem I have is that img inside characters is never resolved.

How can I solve this?

Body:
Your getCharacterIconUrl function is async so you need to await it.

Try this...

const characters = await Promise.all(
  Object.entries(snapshot.val()).map(async ([_id, val]) => ({
    _id,
    img: await this.getCharacterIconUrl(_id),
    ...val,
  }))
)
this.setState({ characters });

Note that the .map() callback is also async. I'm also using Object.entries() since you want both keys and values.


问:
Google Apps Script web app. Use variable outside of an if forEach statement
I'm new to Javascript, I thought I was going ok but I can't figure out this problem.

I'm using Google Apps script to get data from my Google Sheets doc and if a name in column A matches "Sundries" then show the price in Column B.

My script works when I use alert inside the if forEach function but when I move alert outside of it, it breaks. I throws up alerts saying undefined, undefined, undefined, the correct price then undefined, undefined again.

I'm guessing it's something to do with forEach but I don't know away around it.

Here's the section of script that is my problem.

```<code>      document.addEventListener("DOMContentLoaded", afterSidebarLoads);

      //get the data from Google Sheets
      function getRates() {
        const sheet = SpreadsheetApp.openById("fwffwfwefewdwedwedwedwedwedwedwed").getSheetByName("tab name");
        return sheet.getRange(15, 1, sheet.getLastRow()-14, 2).getValues();
      }

      // runs the script
      function afterSidebarLoads() { // Function Part: 1
        google.script.run.withSuccessHandler(getSundriesyRate).getRates();
      }

      // here's my problem
      function getSundriesyRate(arrayOfArrays){ // Function Part: 2
        var sundriesRate = document.getElementById("sundries-rate");

        arrayOfArrays.forEach(function(r){ // r= one of the lines in the aray
          var div = document.createElement("div");
          if (r[0] === "Sundries") { // this does match
            var dhello = r[1].toLocaleString("en-GB", {style: "currency", currency: "GBP", minimumFractionDigits: 2});
            alert(dhello); // works
          } else {

          }
          alert(dhello); // doesn't work
        });
      }
</code>```

Thanks

答:
By create a variable outside the forEach loop and pass the value into the variable. then you will be able to use this variable outside the loop.
If you are expecting to return multiple values, you should use a array or dictionaries to store the data.</p>
```<code> document.addEventListener("DOMContentLoaded", afterSidebarLoads);
  //get the data from Google Sheets
  function getRates() {
    const sheet = SpreadsheetApp.openById("fwffwfwefewdwedwedwedwedwedwedwed").getSheetByName("tab name");
    return sheet.getRange(15, 1, sheet.getLastRow()-14, 2).getValues();
  }

  // runs the script
  function afterSidebarLoads() { // Function Part: 1
    google.script.run.withSuccessHandler(getSundriesyRate).getRates();
  }

  // here's my problem
  function getSundriesyRate(arrayOfArrays){ // Function Part: 2
    var sundriesRate = document.getElementById("sundries-rate");
    var dhello;
    arrayOfArrays.forEach(function(r){ // r= one of the lines in the aray
      var div = document.createElement("div");
      if (r[0] === "Sundries") { // this does match
        dhello = r[1].toLocaleString("en-GB", {style: "currency", currency: "GBP", minimumFractionDigits: 2});
        alert(dhello); // works
      } else {

      }
      //alert(dhello); // doesn't work (it's return undefined because in this forEach loop, it will go through every line of the array and it does not find the match , it returns nothing.)
    });
     alert(dhello);  // you can access this variable here.
  }
</code>```

Body:
I'm new to Javascript, I thought I was going ok but I can't figure out this problem.

I'm using Google Apps script to get data from my Google Sheets doc and if a name in column A matches "Sundries" then show the price in Column B.

My script works when I use alert inside the if forEach function but when I move alert outside of it, it breaks. I throws up alerts saying undefined, undefined, undefined, the correct price then undefined, undefined again.

I'm guessing it's something to do with forEach but I don't know away around it.

Here's the section of script that is my problem.

      document.addEventListener("DOMContentLoaded", afterSidebarLoads);

      //get the data from Google Sheets
      function getRates() {
        const sheet = SpreadsheetApp.openById("fwffwfwefewdwedwedwedwedwedwedwed").getSheetByName("tab name");
        return sheet.getRange(15, 1, sheet.getLastRow()-14, 2).getValues();
      }

      // runs the script
      function afterSidebarLoads() { // Function Part: 1
        google.script.run.withSuccessHandler(getSundriesyRate).getRates();
      }

      // here's my problem
      function getSundriesyRate(arrayOfArrays){ // Function Part: 2
        var sundriesRate = document.getElementById("sundries-rate");

        arrayOfArrays.forEach(function(r){ // r= one of the lines in the aray
          var div = document.createElement("div");
          if (r[0] === "Sundries") { // this does match
            var dhello = r[1].toLocaleString("en-GB", {style: "currency", currency: "GBP", minimumFractionDigits: 2});
            alert(dhello); // works
          } else {

          }
          alert(dhello); // doesn't work
        });
      }

Thanks

Body:
By create a variable outside the forEach loop and pass the value into the variable. then you will be able to use this variable outside the loop.
If you are expecting to return multiple values, you should use a array or dictionaries to store the data.

 document.addEventListener("DOMContentLoaded", afterSidebarLoads);
  //get the data from Google Sheets
  function getRates() {
    const sheet = SpreadsheetApp.openById("fwffwfwefewdwedwedwedwedwedwedwed").getSheetByName("tab name");
    return sheet.getRange(15, 1, sheet.getLastRow()-14, 2).getValues();
  }

  // runs the script
  function afterSidebarLoads() { // Function Part: 1
    google.script.run.withSuccessHandler(getSundriesyRate).getRates();
  }

  // here's my problem
  function getSundriesyRate(arrayOfArrays){ // Function Part: 2
    var sundriesRate = document.getElementById("sundries-rate");
    var dhello;
    arrayOfArrays.forEach(function(r){ // r= one of the lines in the aray
      var div = document.createElement("div");
      if (r[0] === "Sundries") { // this does match
        dhello = r[1].toLocaleString("en-GB", {style: "currency", currency: "GBP", minimumFractionDigits: 2});
        alert(dhello); // works
      } else {

      }
      //alert(dhello); // doesn't work (it's return undefined because in this forEach loop, it will go through every line of the array and it does not find the match , it returns nothing.)
    });
     alert(dhello);  // you can access this variable here.
  }


问:
Python: Join/Merge 2 dfs on Approximate Key Match
I have two DataFrames:

```<code>data = [['B100',30], ['C200',33], ['C201',11]]

data2 = [['B99/B100/B105','Yes'], ['C150/C200/C201','Yes'], ['D56/D500/D501','Yes']]

df_1 = pd.DataFrame(data, columns = ['code', 'value'])

df_2 = pd.DataFrame(data2, columns = ['code_agg', 'rating'])
</code>```

I need to pull in the rating from df_2 into df_1 using a partial match from the 'code' columns in each dataframe (df_1 only has a partial key/code). The result should look like this:

I have tried several methods, the most common error I get is "TypeError: 'Series' objects are mutable, thus they cannot be hashed"

I would greatly appreciate any help on this. thank you!

答:
```<code>df_1.merge(df_2.assign(code=df_2.code_agg.str.split('/')).explode('code'))
Out[]:
   code  value        code_agg rating
0  B100     30   B99/B100/B105    Yes
1  C200     33  C150/C200/C201    Yes
2  C201     11  C150/C200/C201    Yes
</code>```

Body:
I have two DataFrames:

data = [['B100',30], ['C200',33], ['C201',11]]

data2 = [['B99/B100/B105','Yes'], ['C150/C200/C201','Yes'], ['D56/D500/D501','Yes']]

df_1 = pd.DataFrame(data, columns = ['code', 'value'])

df_2 = pd.DataFrame(data2, columns = ['code_agg', 'rating'])

I need to pull in the rating from df_2 into df_1 using a partial match from the 'code' columns in each dataframe (df_1 only has a partial key/code). The result should look like this:

I have tried several methods, the most common error I get is "TypeError: 'Series' objects are mutable, thus they cannot be hashed"

I would greatly appreciate any help on this. thank you!


问:
Lines are not drawn in Kivy python
This is the code:

```<code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Color
from kivy.graphics import Line

class MainWidget(Widget):
    v_l_s=.1
    v_l_n=7
    Vertical_lines=[]
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.init_vertical_lines()
    def on_size(self,*args):
            self.update_vertical_lines()
    def init_vertical_lines(self):
        for num in range(0,self.v_l_n):
            self.Vertical_lines.append(Line())
    def update_vertical_lines(self):
        cener_x=int(self.width/2)
        before_lines=-(int(self.width/2))
        line_x=cener_x+before_lines*self.v_l_s
        for numb in range(0,self.v_l_n):
            with self.canvas:
                self.Vertical_lines[numb].points=[line_x,0,line_x,self.height]
            before_lines+=1

class GameApp(App):
    def build(self):
        return MainWidget()

GameApp().run()
</code>```

This  code  should  return 7 vertical lines but it  is  showing  nothing.  What should I  do  to  solve  it ?(Note-An error is coming in publishing the question so don't care about this Note)

答:
When you initially create the Line() instance, you are not doing in a canvas context. Just add with self.canvas: to the init_vertical_lines() method:

```<code>def init_vertical_lines(self):
    with self.canvas:
        for num in range(0, self.v_l_n):
            self.Vertical_lines.append(Line())
</code>```

Your code will then draw the 7 lines, but they are all in the same place (that's a different issue).

Title: Lines are not drawn in Kivy python

Body:
This is the code:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Color
from kivy.graphics import Line

class MainWidget(Widget):
    v_l_s=.1
    v_l_n=7
    Vertical_lines=[]
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.init_vertical_lines()
    def on_size(self,*args):
            self.update_vertical_lines()
    def init_vertical_lines(self):
        for num in range(0,self.v_l_n):
            self.Vertical_lines.append(Line())
    def update_vertical_lines(self):
        cener_x=int(self.width/2)
        before_lines=-(int(self.width/2))
        line_x=cener_x+before_lines*self.v_l_s
        for numb in range(0,self.v_l_n):
            with self.canvas:
                self.Vertical_lines[numb].points=[line_x,0,line_x,self.height]
            before_lines+=1

class GameApp(App):
    def build(self):
        return MainWidget()

GameApp().run()

This  code  should  return 7 vertical lines but it  is  showing  nothing.  What should I  do  to  solve  it ?(Note-An error is coming in publishing the question so don't care about this Note)

Body:
When you initially create the Line() instance, you are not doing in a canvas context. Just add with self.canvas: to the init_vertical_lines() method:

def init_vertical_lines(self):
    with self.canvas:
        for num in range(0, self.v_l_n):
            self.Vertical_lines.append(Line())

Your code will then draw the 7 lines, but they are all in the same place (that's a different issue).


答:
Since getCharacterIconUrl is an async function, it returns a promise. Therefore, your img field is a promise; combined with map(), that becomes like an array of promise. Therefore, we can use Promise.all() to resolve them

async componentDidMount() {
  const dbRef = ref(db);

  let snapshot = await get(child(dbRef, "en/characters"));
  if (snapshot.exists()) {
    let characterPromises = Object.keys(snapshot.val()).map(async (key) => {
      return {
        _id: key,
        img: await this.getCharacterIconUrl(key),
        ...snapshot.val()[key],
      };
    });
    this.setState({ characters: await Promise.all(characterPromises)});
  } else {
    console.log("No data available");
  }
}
```

Title: using async/await with firebase


问:
Update specific key/value of json object inside json array using MySQL syntax
I have MySQL 5.7.12 DB with a table that has a JSON column.

The data in the column as the following structure (json array may contain more than 2 json-objects:

[{"ste": "I", "tpe": "PS"}, {"ste": "I", "tpe": "PB"}]

I would like to craft an UPDATE query that changes the value of ste  where tpe=PB.

Here is my attempt:

UPDATE user SET ext = JSON_SET(JSON_SEARCH(ext, 'one', 'PB', NULL, '$**.tpe'), '$.tpe', 'A');

The output if the query should give:

[{"ste": "I", "tpe": "PS"}, {"ste": "A", "tpe": "PB"}]

It doesn't work - it updates the column to be:

"$[0].tpe"

How can I make this work?

EDIT

I think this makes more sense but still something wrong with syntax

```<code>UPDATE user SET ext = JSON_SET(ext->JSON_SEARCH(ext, 'one', 'PS', NULL, '$**.tpe'), '$.tpe', 'A');
</code>```

答:
If I understand question correctly ext column of user table has below value

```<code>[{"ste": "I", "tpe": "PS"}, {"ste": "I", "tpe": "PB"}]
</code>```

and ask is for UPDATE Query to modify 2nd index of value like below

```<code>[{"ste": "I", "tpe": "PS"}, {"ste": "A", "tpe": "PB"}]
</code>```

Recommended & Easy Solution based on Problem Statement considering json structure is fixed

Update Query based on Json array index

```<code>update user set ext = JSON_SET(ext, '$[1].ste', 'A') where primary_key = 'primary_key_criteria';

select ext from user where primary_key = 'primary_key_criteria';
</code>```

Output after Update

```<code>[{"ste": "I", "tpe": "PS"}, {"ste": "A", "tpe": "PB"}]
</code>```

Body:
I have MySQL 5.7.12 DB with a table that has a JSON column.

The data in the column as the following structure (json array may contain more than 2 json-objects:

[{"ste": "I", "tpe": "PS"}, {"ste": "I", "tpe": "PB"}]

I would like to craft an UPDATE query that changes the value of ste  where tpe=PB.

Here is my attempt:

UPDATE user SET ext = JSON_SET(JSON_SEARCH(ext, 'one', 'PB', NULL, '$**.tpe'), '$.tpe', 'A');

The output if the query should give:

[{"ste": "I", "tpe": "PS"}, {"ste": "A", "tpe": "PB"}]

It doesn't work - it updates the column to be:

"$[0].tpe"

How can I make this work?

EDIT

I think this makes more sense but still something wrong with syntax

UPDATE user SET ext = JSON_SET(ext->JSON_SEARCH(ext, 'one', 'PS', NULL, '$**.tpe'), '$.tpe', 'A');

Body:
If I understand question correctly ext column of user table has below value

[{"ste": "I", "tpe": "PS"}, {"ste": "I", "tpe": "PB"}]

and ask is for UPDATE Query to modify 2nd index of value like below

[{"ste": "I", "tpe": "PS"}, {"ste": "A", "tpe": "PB"}]

Recommended & Easy Solution based on Problem Statement considering json structure is fixed

Update Query based on Json array index

update user set ext = JSON_SET(ext, '$[1].ste', 'A') where primary_key = 'primary_key_criteria';

select ext from user where primary_key = 'primary_key_criteria';

Output after Update

[{"ste": "I", "tpe": "PS"}, {"ste": "A", "tpe": "PB"}]


问:
how can i change the status to archived classroom with apps script
```<code>function get_courses(student) {
  var optionalArgs = {
    studentId: student
  };
  var response = Classroom.Courses.list(optionalArgs);
  var courses = response.courses;
  var active_courses = [];
  if (courses && courses.length > 0) {
    for (i = 0; i < courses.length; i++) {
      var course = courses[i];
      if (course.courseState == "ACTIVE" && course.ownerId == "owwnerid") {
        active_courses.push(course);
        Logger.log('%s (%s)', course.name, course.courseState);
      }
    }
  } else {
    Logger.log('No courses found.');
  }
  Logger.log(active_courses);
}
</code>```

答:
In your script, how about the following modification?

From:

```<code>if (course.courseState == "ACTIVE" && course.ownerId == "owwnerid") {
  active_courses.push(course);
  Logger.log('%s (%s)', course.name, course.courseState);
}
</code>```

To:

```<code>if (course.courseState == "ACTIVE" && course.ownerId == "owwnerid") {
  active_courses.push(course);
  Logger.log('%s (%s)', course.name, course.courseState);
  Classroom.Courses.patch({courseState: "ARCHIVED"}, course.id, {updateMask: "courseState"}); // Added
}
</code>```

Reference:

Method: courses.patch

Body:
In your script, how about the following modification?

From:

if (course.courseState == "ACTIVE" && course.ownerId == "owwnerid") {
  active_courses.push(course);
  Logger.log('%s (%s)', course.name, course.courseState);
}

To:

if (course.courseState == "ACTIVE" && course.ownerId == "owwnerid") {
  active_courses.push(course);
  Logger.log('%s (%s)', course.name, course.courseState);
  Classroom.Courses.patch({courseState: "ARCHIVED"}, course.id, {updateMask: "courseState"}); // Added
}

Reference:

Method: courses.patch


问:
How to delete a Contact in Android 2.2 with name ?
I want to delete A Contact with special name.

I try below code to find my target :

```<code>public Cursor searchByName(String name)
    {
        try
        {
            ContentResolver cr = getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
            if (cur.getCount() > 0)
            {
                while (cur.moveToNext())
                {
                    //String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    String Name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
                    {
                        if(Name.equals(name))
                        {
                            return cur;
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
        return null;
    }
</code>```

and below Function to remove it :

```<code>public void removeContactByName(String name)
{
    try
    {
        Cursor cur = searchByName(name);
        if(cur!=null)
        {
            Uri uri ; // what should it be?
            getContentResolver().delete(uri,null, null);
        }
        else
        {
            Toast.makeText(getApplicationContext(), "Not Found",Toast.LENGTH_SHORT).show();
        }
    }
    catch (Exception e)
    {
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
    }
}
</code>```

but what should uri be?

答: you can search for the Contact by name, and get it _id, after that, delete it by _id

Body:
I want to delete A Contact with special name.

I try below code to find my target :

public Cursor searchByName(String name)
    {
        try
        {
            ContentResolver cr = getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
            if (cur.getCount() > 0)
            {
                while (cur.moveToNext())
                {
                    //String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    String Name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
                    {
                        if(Name.equals(name))
                        {
                            return cur;
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
        return null;
    }

and below Function to remove it :

public void removeContactByName(String name)
{
    try
    {
        Cursor cur = searchByName(name);
        if(cur!=null)
        {
            Uri uri ; // what should it be?
            getContentResolver().delete(uri,null, null);
        }
        else
        {
            Toast.makeText(getApplicationContext(), "Not Found",Toast.LENGTH_SHORT).show();
        }
    }
    catch (Exception e)
    {
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

but what should uri be?


问:
swiftui transition not work on extracted view
I just build a small pop up with .spring() animation that I want to use later in my app, but the back transition is not smooth. It simply disappear from the hierarchy. So here is my code:

```<code>struct TestPopUp: View {

@State var screen: Bool = false

var body: some View {
        ZStack {
            Color.white
                .edgesIgnoringSafeArea(.all)

            VStack {
                Button("Click") {
                    withAnimation(.spring()) {
                        screen.toggle()
                    }

                }
                .font(.largeTitle)

                if screen {
                    NewScreen(screen: $screen)
                        .padding(.top, 300)
                        .transition(.move(edge: .bottom))
                }
}

struct NewScreen: View {

    @Binding var screen: Bool

    var body: some View {
    ZStack(alignment: .topLeading) {
            Color.black
                .edgesIgnoringSafeArea(.all)

            Button {
                screen.toggle()
            } label: {
                Image(systemName: "xmark")
                    .foregroundColor(.white)
                    .font(.largeTitle)
                    .padding(20)
            }

        }
    }
}
</code>```

Transition popup

As you can see in the video, the view disappears. But I want the same transition backwards.

答:
You have to animate the transition both ways, in and out. Therefore, NewScreen becomes:

```<code>struct NewScreen: View {

    @Binding var screen: Bool

    var body: some View {
        ZStack(alignment: .topLeading) {
            Color.black
                .edgesIgnoringSafeArea(.all)

            Button {
                withAnimation(.spring()) { // Animate here!
                    screen.toggle()
                }
            } label: {
                Image(systemName: "xmark")
                    .foregroundColor(.white)
                    .font(.largeTitle)
                    .padding(20)
            }
        }
    }
}
</code>```

Body:
I just build a small pop up with .spring() animation that I want to use later in my app, but the back transition is not smooth. It simply disappear from the hierarchy. So here is my code:

struct TestPopUp: View {

@State var screen: Bool = false

var body: some View {
        ZStack {
            Color.white
                .edgesIgnoringSafeArea(.all)

            VStack {
                Button("Click") {
                    withAnimation(.spring()) {
                        screen.toggle()
                    }

                }
                .font(.largeTitle)

                if screen {
                    NewScreen(screen: $screen)
                        .padding(.top, 300)
                        .transition(.move(edge: .bottom))
                }
}

struct NewScreen: View {

    @Binding var screen: Bool

    var body: some View {
    ZStack(alignment: .topLeading) {
            Color.black
                .edgesIgnoringSafeArea(.all)

            Button {
                screen.toggle()
            } label: {
                Image(systemName: "xmark")
                    .foregroundColor(.white)
                    .font(.largeTitle)
                    .padding(20)
            }

        }
    }
}

Transition popup

As you can see in the video, the view disappears. But I want the same transition backwards.

Body:
You have to animate the transition both ways, in and out. Therefore, NewScreen becomes:

struct NewScreen: View {

    @Binding var screen: Bool

    var body: some View {
        ZStack(alignment: .topLeading) {
            Color.black
                .edgesIgnoringSafeArea(.all)

            Button {
                withAnimation(.spring()) { // Animate here!
                    screen.toggle()
                }
            } label: {
                Image(systemName: "xmark")
                    .foregroundColor(.white)
                    .font(.largeTitle)
                    .padding(20)
            }
        }
    }
}


答:
In order to utilize your lambda function within your list comprehension, simply define a variable to store the function:

```<code>func = lambda x: x % 2 == 0

a = [x if func(x) else 0 for x in range(10)]
print(a)
</code>```

Output:

```<code>[0, 0, 2, 0, 4, 0, 6, 0, 8, 0]
</code>```

Title: Lambda expression in ternary operator

Body:
In order to utilize your lambda function within your list comprehension, simply define a variable to store the function:

func = lambda x: x % 2 == 0

a = [x if func(x) else 0 for x in range(10)]
print(a)

Output:

[0, 0, 2, 0, 4, 0, 6, 0, 8, 0]


问:
AutoMapper map only needed fields
I use AutoMapper for mapping classes. I am struggling with the Automapper syntax.
I have domain classes:

```<code>        public class Club
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public DateTime OpenDate { get; set; }
            public IEnumerable<Team> Teams { get; set; }
        }

        public class Team
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Department { get; set; }
            public IEnumerable<Player> Players { get; set; }
        }

        public class Player
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Surname { get; set; }
            public int Age { get; set; }
            public string Address { get; set; }
        }
</code>```

Also i have dto classes:

```<code>        public class ClubDTO
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public DateTime OpenDate { get; set; }
            public IEnumerable<Team> TeamsDTO { get; set; }
        }

        public class TeamDTO
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Department { get; set; }
            public IEnumerable<Player> PlayersDTO { get; set; }
        }

        public class PlayerDTO
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Surname { get; set; }
            public int Age { get; set; }
            public string Address { get; set; }
        }
</code>```

I have mapping setting from DTO classes in domain classes:

```<code>CreateMap<PlayerDTO, Player>();
CreateMap<TeamDTO, Team>();
CreateMap<ClubDTO, Club>();
</code>```

I map ClubDTO class to Club:

```<code>...
 _mapper.Map(clubDto, club);
...
</code>```

How do I setting mapping only Player.Age and Player.Addres instead of all fields all classes?

答:
```<code> public class PlayerDTO
    {

        public int Age { get; set; }
        public string Address { get; set; }
    }

    var onlyAgeAndAdress=_mapper.Map(Player, PlayerDTO);
</code>```

you will get only ages and adresses.

Title: AutoMapper map only needed fields

Body:
I use AutoMapper for mapping classes. I am struggling with the Automapper syntax.
I have domain classes:

        public class Club
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public DateTime OpenDate { get; set; }
            public IEnumerable<Team> Teams { get; set; }
        }

        public class Team
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Department { get; set; }
            public IEnumerable<Player> Players { get; set; }
        }

        public class Player
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Surname { get; set; }
            public int Age { get; set; }
            public string Address { get; set; }
        }

Also i have dto classes:

        public class ClubDTO
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public DateTime OpenDate { get; set; }
            public IEnumerable<Team> TeamsDTO { get; set; }
        }

        public class TeamDTO
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Department { get; set; }
            public IEnumerable<Player> PlayersDTO { get; set; }
        }

        public class PlayerDTO
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Surname { get; set; }
            public int Age { get; set; }
            public string Address { get; set; }
        }

I have mapping setting from DTO classes in domain classes:

CreateMap<PlayerDTO, Player>();
CreateMap<TeamDTO, Team>();
CreateMap<ClubDTO, Club>();

I map ClubDTO class to Club:

...
 _mapper.Map(clubDto, club);
...

How do I setting mapping only Player.Age and Player.Addres instead of all fields all classes?

Body:
 public class PlayerDTO
    {

        public int Age { get; set; }
        public string Address { get; set; }
    }

    var onlyAgeAndAdress=_mapper.Map(Player, PlayerDTO);

you will get only ages and adresses.


问:
How to decrypt audio file in the form of stream in Flutter/Dart?
Project Requirement: Music player app which will download audio files, encrypt and save them. The audio files should be playable in the app only. No other app should be able to play the files. Nor the user should be able to copy the files.

Approach: I don't want the entire decryted audio file to exist at any moment. So I want to encrypt the audio file as soon as it is downloaded. Then when the file is to be played, I want it to be decrypted chunk-by-chunk and played. I believe this can be achieved by using stream. As far as I searched, a package named "just_audio" can play the audio from stream source.

Problem: I cannot find any encryption package for Flutter/Dart which will output the decrypted data in the form of a stream. This is the first time I am trying to implement encryption/decryption, so my knowledge is very poor in this regard.

Notes:

The encryption does not need to be heavy. A typical user not being able to copy the files and play them elsewhere would suffice.

Audio files are going to be large, some of them even hours in length.

I need all the usual functions of a music player (e.g. albums, playlists, progress bars with seeking function, etc.)

Options:

It will be best if there is a package which can do what I need, off the shelf.

To find a basic package and then modifying it into doing what is needed.

Some radically different solution, which takes entirely different path but provides all the solutions.

答:
if you're open to a 3rd package, don't reinvent the wheel..

try this here https://morioh.com/p/34a06006b299 with various CipherStream Options

If you can forego stream encryption and do it after you have the file then try this package, Credit: I used the sample from this answer by Hoaea Varghese

With AES all you need is the path to the file, and you can encrypt files or albums with something as simple as

```<code>encrypted_file_path = EncryptData.encrypt_file('your/file/path');
</code>```

With the code below

```<code>import 'dart:io';
import 'package:aes_crypt/aes_crypt.dart';

class EncryptData {
  static String encrypt_file(String path) {
    AesCrypt crypt = AesCrypt();
    crypt.setOverwriteMode(AesCryptOwMode.on);
    crypt.setPassword('my cool password');
    String encFilepath;
    try {
      encFilepath = crypt.encryptFileSync(path);
      print('The encryption has been completed successfully.');
      print('Encrypted file: $encFilepath');
    } catch (e) {
      if (e.type == AesCryptExceptionType.destFileExists) {
        print('The encryption has been completed unsuccessfully.');
        print(e.message);
      }
      else{
        return 'ERROR';
      }
    }
    return encFilepath;
  }

  static String decrypt_file(String path) {
    AesCrypt crypt = AesCrypt();
    crypt.setOverwriteMode(AesCryptOwMode.on);
    crypt.setPassword('my cool password');
    String decFilepath;
    try {
      decFilepath = crypt.decryptFileSync(path);
      print('The decryption has been completed successfully.');
      print('Decrypted file 1: $decFilepath');
      print('File content: ' + File(decFilepath).path);
    } catch (e) {
      if (e.type == AesCryptExceptionType.destFileExists) {
        print('The decryption has been completed unsuccessfully.');
        print(e.message);
      }
      else{
        return 'ERROR';
      }
    }
    return decFilepath;
  }
}
</code>```

Body:
if you're open to a 3rd package, don't reinvent the wheel..

try this here https://morioh.com/p/34a06006b299 with various CipherStream Options

If you can forego stream encryption and do it after you have the file then try this package, Credit: I used the sample from this answer by Hoaea Varghese

With AES all you need is the path to the file, and you can encrypt files or albums with something as simple as

encrypted_file_path = EncryptData.encrypt_file('your/file/path');

With the code below

import 'dart:io';
import 'package:aes_crypt/aes_crypt.dart';

class EncryptData {
  static String encrypt_file(String path) {
    AesCrypt crypt = AesCrypt();
    crypt.setOverwriteMode(AesCryptOwMode.on);
    crypt.setPassword('my cool password');
    String encFilepath;
    try {
      encFilepath = crypt.encryptFileSync(path);
      print('The encryption has been completed successfully.');
      print('Encrypted file: $encFilepath');
    } catch (e) {
      if (e.type == AesCryptExceptionType.destFileExists) {
        print('The encryption has been completed unsuccessfully.');
        print(e.message);
      }
      else{
        return 'ERROR';
      }
    }
    return encFilepath;
  }

  static String decrypt_file(String path) {
    AesCrypt crypt = AesCrypt();
    crypt.setOverwriteMode(AesCryptOwMode.on);
    crypt.setPassword('my cool password');
    String decFilepath;
    try {
      decFilepath = crypt.decryptFileSync(path);
      print('The decryption has been completed successfully.');
      print('Decrypted file 1: $decFilepath');
      print('File content: ' + File(decFilepath).path);
    } catch (e) {
      if (e.type == AesCryptExceptionType.destFileExists) {
        print('The decryption has been completed unsuccessfully.');
        print(e.message);
      }
      else{
        return 'ERROR';
      }
    }
    return decFilepath;
  }
}


问:
How to set an arbitrary z value for XY pairs in a series with gnuplot
I have a csv file with multiple XY data pairs. Each data pair is separated by one hour. I would like to graph these data pairs in one 3D graph so I can leverage the depth to better visualize the graph. can I set an arbitrary Z value for each XY data pair, where Z=hours?
I understand I could alter the CSV file to have a third column for each pair, but in my case it would be faster to simply arbitrate a z value for each pair (if possible). Thank you.

For example, 1:2 is hour 1, and 3:4 is hour 2, and so on...

答:
Gnuplot treats treats the row number as column 0, so a commands

```<code>set datafile separator comma
splot "data.csv" using 1:2:0
</code>```

would use the first two entries on each line as an x,y pair and assign the row number as z.   If by "arbitrary" you mean "some constant I pick beforehand", then you can place that value inside parentheses to indicate it is a numerical value rather than a column number:

```<code>FOO = 123.456
splot "data.csv" using 1:2:(FOO)
</code>```

Body:
Gnuplot treats treats the row number as column 0, so a commands

set datafile separator comma
splot "data.csv" using 1:2:0

would use the first two entries on each line as an x,y pair and assign the row number as z.   If by "arbitrary" you mean "some constant I pick beforehand", then you can place that value inside parentheses to indicate it is a numerical value rather than a column number:

FOO = 123.456
splot "data.csv" using 1:2:(FOO)


问:
ActionView::MissingTemplate during testing
I'm testing a rails controller and attempting to perform a get with the code:

```<code>delete :remove_logs, :id => 3
</code>```

And it consistently returns me an ActionView::MissingTemplate exception. I know that this is because there is no view associated with the get. There is a route for this method (from rake routes):

```<code>remove_logs        /devices/remove_logs/:id(.:format)            {:controller=>"devices", :action=>"remove_logs"}
</code>```

The function itself works perfectly for the actually webpage as it's being called with:

```<code><%= link_to "Remove History", remove_logs_path(device),
:class => "medium red button",  :confirm => 'This will remove all history from
this device. Are you sure?', :method => :delete %>
</code>```

So my question is, is there a way to bypass or trick the test to not attempt to access the view and just access the controller method? This isn't my system I'm testing so I really don't want to make a new blank view or anything similar.

答:
I think the problem may be related with the code in controller (remove_logs action) which usually has some code about redirecting to another url like bellow:

```<code>def destroy
  @tag = Tag.find(params[:id])
  @tag.destroy
  redirect_to :action => :index
end
</code>```

I test with Test::Unit in my rails app, and it goes fine when having redirecting code.

Body:
I'm testing a rails controller and attempting to perform a get with the code:

delete :remove_logs, :id => 3

And it consistently returns me an ActionView::MissingTemplate exception. I know that this is because there is no view associated with the get. There is a route for this method (from rake routes):

remove_logs        /devices/remove_logs/:id(.:format)            {:controller=>"devices", :action=>"remove_logs"}

The function itself works perfectly for the actually webpage as it's being called with:

<%= link_to "Remove History", remove_logs_path(device),
:class => "medium red button",  :confirm => 'This will remove all history from
this device. Are you sure?', :method => :delete %>

So my question is, is there a way to bypass or trick the test to not attempt to access the view and just access the controller method? This isn't my system I'm testing so I really don't want to make a new blank view or anything similar.

Body:
I think the problem may be related with the code in controller (remove_logs action) which usually has some code about redirecting to another url like bellow:

def destroy
  @tag = Tag.find(params[:id])
  @tag.destroy
  redirect_to :action => :index
end

I test with Test::Unit in my rails app, and it goes fine when having redirecting code.


问:
USGA Website - API and JSON - quit working - getting "error Invalid token"
Old Question on Stack Overflow< https://stackoverflow.com/questions/61073325/vba-xml-web-log-in-to-usga-ghin-website-not-working>

USGA Webiste https://www.ghin.com/login
Page 2 - USGA https://www.ghin.com/golfer-lookup/following

I built an Excel VBA app that uses the data collected from and API/JSON data-pull from the USGA website, of which I am an authorized USER with a valid account and password.  However, the code which I have used reliably for about 2 years is now generating a "Invalid Token Error".

The "Invalid Token Error" may be password related.  My prior code required no password input.  I have tired to build the password input into the input/response but as of yet no luck?

Any thoughts on you to solve "Invalid Token Error" and possibly, construct the password input on my part?  Here is may old code (Also posted on the Stack Overflow links above)

```<code>
Sub GetInformation()
    Const Url = "https://api2.ghin.com/api/v1/public/login.json?"
    Dim Http As New XMLHTTP60, ghinNum$, lastName$

    ghinNum = ""            'put your ghinNum here
    lastName = ""           'put your lastName here

    With Http
        .Open "GET", Url & "ghinNumber=" & ghinNum & "&lastName=" & lastName & "&remember_me=false", False
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"
        .setRequestHeader "Referer", "https://www.ghin.com/login"
        .send
    End With

    MsgBox Http.responseText
End Sub

</code>```

答:
I too have an app that used the GHIN API as well. It appears they simply removed their public endpoint (https://api2.ghin.com/api/v1/public). You now have to authenticate to get a token to use their API.

Here's a site with some really good documentation for the GHIN API: https://app.swaggerhub.com/apis-docs/GHIN/Admin/1.0

Sorry that's not the answer you wanted to hear, I'm sure.

EDIT: Now I have a GHIN and can log in. Here's my working Python code:

```<code>import requests
import json

ghinNum = "GHINID"
password = "GHINPASS"

headers = {
    "Content-Type": "application/json; charset=utf-8",
    "Accept": "application/json",
    }

data = {
    "user": {
        "email_or_ghin": ghinNum,
        "password": password,
        "remember_me": "true",
    },
    "token": "nonblank",
}

r = requests.post("https://api2.ghin.com/api/v1/golfer_login.json", headers=headers, json=data)

headers["Authorization"] = "Bearer " + r.json()["golfer_user"]["golfer_user_token"]

url = "https://api.ghin.com/api/v1/golfers/search.json?per_page=1&page=1&golfer_id=" + ghinNum

r = requests.get(url, headers=headers)

if r.status_code == 200:
    data = r.json()
    handicap_index = data['golfers'][0]['handicap_index']

    print(handicap_index)

else:
    print(r.status_code)
</code>```

Body:
Old Question on Stack Overflow< https://stackoverflow.com/questions/61073325/vba-xml-web-log-in-to-usga-ghin-website-not-working>

USGA Webiste https://www.ghin.com/login
Page 2 - USGA https://www.ghin.com/golfer-lookup/following

I built an Excel VBA app that uses the data collected from and API/JSON data-pull from the USGA website, of which I am an authorized USER with a valid account and password.  However, the code which I have used reliably for about 2 years is now generating a "Invalid Token Error".

The "Invalid Token Error" may be password related.  My prior code required no password input.  I have tired to build the password input into the input/response but as of yet no luck?

Any thoughts on you to solve "Invalid Token Error" and possibly, construct the password input on my part?  Here is may old code (Also posted on the Stack Overflow links above)

Sub GetInformation()
    Const Url = "https://api2.ghin.com/api/v1/public/login.json?"
    Dim Http As New XMLHTTP60, ghinNum$, lastName$

    ghinNum = ""            'put your ghinNum here
    lastName = ""           'put your lastName here

    With Http
        .Open "GET", Url & "ghinNumber=" & ghinNum & "&lastName=" & lastName & "&remember_me=false", False
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"
        .setRequestHeader "Referer", "https://www.ghin.com/login"
        .send
    End With

    MsgBox Http.responseText
End Sub

Body:
I too have an app that used the GHIN API as well. It appears they simply removed their public endpoint (https://api2.ghin.com/api/v1/public). You now have to authenticate to get a token to use their API.

Here's a site with some really good documentation for the GHIN API: https://app.swaggerhub.com/apis-docs/GHIN/Admin/1.0

Sorry that's not the answer you wanted to hear, I'm sure.

EDIT: Now I have a GHIN and can log in. Here's my working Python code:

import requests
import json

ghinNum = "GHINID"
password = "GHINPASS"

headers = {
    "Content-Type": "application/json; charset=utf-8",
    "Accept": "application/json",
    }

data = {
    "user": {
        "email_or_ghin": ghinNum,
        "password": password,
        "remember_me": "true",
    },
    "token": "nonblank",
}

r = requests.post("https://api2.ghin.com/api/v1/golfer_login.json", headers=headers, json=data)

headers["Authorization"] = "Bearer " + r.json()["golfer_user"]["golfer_user_token"]

url = "https://api.ghin.com/api/v1/golfers/search.json?per_page=1&page=1&golfer_id=" + ghinNum

r = requests.get(url, headers=headers)

if r.status_code == 200:
    data = r.json()
    handicap_index = data['golfers'][0]['handicap_index']

    print(handicap_index)

else:
    print(r.status_code)


问:
Difficult MySQL query (MySQL-8, Laravel)
I got a really difficult task for me, and I'm out of ideas. I use mysql-8, Laravel 8.

This is a structure of the tables:

user has many projects (every project has user_id field)

project has many selections (every selection has project_id field)

selection has one pump (selection has pump_id field), but it also has pumps_count field

pump has many price_lists (every price_list has pump_id field)

price_list and user also have country_id, currency_id, so we can say that pump has ONE price_list that corresponds to current user. (For example if current user has country_id = 1 and currency_id = 2 then we should select only price lists, where country_id = 1 and currency_id = 2 and there'll be only one)

projects and selections both have created_at field (timestamp).

So, the main goals:

For current user get total price of projects, grouped by months

For current user get total price of projects with 'increasing' grouped by months

users

id
country_id
currency_id

1
1
2

projects

id
created_at
name
user_id

1
2021-10-01 00:00:01
proj1
1

2
2021-11-01 00:00:01
proj2
1

3
2021-12-01 00:00:01
proj3
1

selections

id
created_at
project_id
pump_id
pumps_count

1
2021-10-02 00:00:01
1
1
2

2
2021-11-03 00:00:01
2
2
1

3
2021-11-04 00:00:01
1
1
3

4
2021-12-05 00:00:01
3
1
3

pumps

id

1

2

pumps_price_lists

pump_id
country_id
currency_id
price

1
1
2
100

2
1
2
500

Result for the first part:

year-month
total_projects_price

2021-10
200

2021-11
800

2021-12
300

Result for the second part:

year-month
total_projects_price_with_increasing

2021-10
200

2021-11
1000

2021-12
1300

Total price for project = total price of selections of the project.

Total price of selection = total pumps price of the selection.

Total pumps price of the selection = selection.pumps_count * pump price.

Pump price = pumps_price_lists.price for pump where county_id and currency_id are the same as user has.

I'm looking at this and really don't know where to even start. Project becomes quite big, so I would want the solution to not has joins, but any ideas are welcome.

I tried something like this with joins, but it doesn't seem work:

select
    selections.id as 'selection_id',
    DATE_FORMAT(selections.created_at, '%Y-%m') as 'month',
    pumps_price_lists.price,
    pumps_price_lists.currency_id as 'currency_id',
    sum(pumps_price_lists.price) over (ORDER by DATE_FORMAT(selections.created_at, '%Y-%m')) as 'sum'
from projects
join selections on selections.project_id = projects.id
join pumps on selections.pump_id = pumps.id
join pumps_price_lists on pumps_price_lists.pump_id = pumps.id
GROUP BY selections.id, pumps_price_lists.currency_id
```
<p>I also tried to do something with Laravel Eloquent, but stucked and don't know what to do next.</p>
<pre class="lang-php prettyprint-override"><code>Auth::user()->projects()
    ->with(['selections' => function ($query) {
        $query->select('id', 'pumps_count', 'pump_id', 'created_at', 'project_id');
    }, 'selections.pump' => function ($query) {
        $query->select('id');
    }, 'selections.pump.price_list', 'selections.pump.price_list.currency'
    ])->get(['id', 'created_at', 'user_id'])->...
</code>```

I hope my explanation was clear

答:
In SQL I would do it something like</p>
```<code>with data as
(select
DATE_FORMAT(selections.created_at, '%Y-%m') as m,
sum(price * pumps_count) as total_price
from users
left join projects on (projects.user_id = users.id)
left join selections on (selections.project_id = projects.id)
left join pumps_price_lists on (pumps_price_lists.pump_id = selections.pump_id)
where users.id = 1
group by m
)

select *, sum(total_price) over (order by m) as cumulative_price from data
</code>```

Body:
I got a really difficult task for me, and I'm out of ideas. I use mysql-8, Laravel 8.

This is a structure of the tables:

user has many projects (every project has user_id field)

project has many selections (every selection has project_id field)

selection has one pump (selection has pump_id field), but it also has pumps_count field

pump has many price_lists (every price_list has pump_id field)

price_list and user also have country_id, currency_id, so we can say that pump has ONE price_list that corresponds to current user. (For example if current user has country_id = 1 and currency_id = 2 then we should select only price lists, where country_id = 1 and currency_id = 2 and there'll be only one)

projects and selections both have created_at field (timestamp).

So, the main goals:

For current user get total price of projects, grouped by months

For current user get total price of projects with 'increasing' grouped by months

users

id
country_id
currency_id

1
1
2

projects

id
created_at
name
user_id

1
2021-10-01 00:00:01
proj1
1

2
2021-11-01 00:00:01
proj2
1

3
2021-12-01 00:00:01
proj3
1

selections

id
created_at
project_id
pump_id
pumps_count

1
2021-10-02 00:00:01
1
1
2

2
2021-11-03 00:00:01
2
2
1

3
2021-11-04 00:00:01
1
1
3

4
2021-12-05 00:00:01
3
1
3

pumps

id

1

2

pumps_price_lists

pump_id
country_id
currency_id
price

1
1
2
100

2
1
2
500

Result for the first part:

year-month
total_projects_price

2021-10
200

2021-11
800

2021-12
300

Result for the second part:

year-month
total_projects_price_with_increasing

2021-10
200

2021-11
1000

2021-12
1300

Total price for project = total price of selections of the project.

Total price of selection = total pumps price of the selection.

Total pumps price of the selection = selection.pumps_count * pump price.

Pump price = pumps_price_lists.price for pump where county_id and currency_id are the same as user has.

I'm looking at this and really don't know where to even start. Project becomes quite big, so I would want the solution to not has joins, but any ideas are welcome.

I tried something like this with joins, but it doesn't seem work:

select
    selections.id as 'selection_id',
    DATE_FORMAT(selections.created_at, '%Y-%m') as 'month',
    pumps_price_lists.price,
    pumps_price_lists.currency_id as 'currency_id',
    sum(pumps_price_lists.price) over (ORDER by DATE_FORMAT(selections.created_at, '%Y-%m')) as 'sum'
from projects
join selections on selections.project_id = projects.id
join pumps on selections.pump_id = pumps.id
join pumps_price_lists on pumps_price_lists.pump_id = pumps.id
GROUP BY selections.id, pumps_price_lists.currency_id

I also tried to do something with Laravel Eloquent, but stucked and don't know what to do next.

Auth::user()->projects()
    ->with(['selections' => function ($query) {
        $query->select('id', 'pumps_count', 'pump_id', 'created_at', 'project_id');
    }, 'selections.pump' => function ($query) {
        $query->select('id');
    }, 'selections.pump.price_list', 'selections.pump.price_list.currency'
    ])->get(['id', 'created_at', 'user_id'])->...

I hope my explanation was clear

Body:
In SQL I would do it something like

with data as
(select
DATE_FORMAT(selections.created_at, '%Y-%m') as m,
sum(price * pumps_count) as total_price
from users
left join projects on (projects.user_id = users.id)
left join selections on (selections.project_id = projects.id)
left join pumps_price_lists on (pumps_price_lists.pump_id = selections.pump_id)
where users.id = 1
group by m
)

select *, sum(total_price) over (order by m) as cumulative_price from data


问:
which storage type is good for large data when using dcc.Store()
when using dcc.Store() for large data, which storage type is good, memory, local or session?

I got an error of

```<code>IOPub data rate exceeded.
The notebook server will temporarily stop sending output
to the client in order to avoid crashing it.
To change this limit, set the config variable
`--NotebookApp.iopub_data_rate_limit`.

Current values:
NotebookApp.iopub_data_rate_limit=1000000.0 (bytes/sec)
NotebookApp.rate_limit_window=3.0 (secs)

</code>```

The webpage also crashes showing below figure:

答:
There are limitations to using dcc.Store. It stores the data in the browser, which is not ideal or even intended for large/very large datasets, as performance issues will arise. Here is a list of those limitations for the component.

If you intend to use visualise large datasets using Dash, I recommend a great tool that combines Django with Dash called django-plotly-dash. Essentially, you'll be handling the backend all in django using its model-view approach, and then building your dashboard in dash that will be integrated with the django backend. So rather than using dcc.Store to store any large datasets, you can query your database in the callbacks, hence visualising large datasets more efficiently.

Body:
when using dcc.Store() for large data, which storage type is good, memory, local or session?

I got an error of

IOPub data rate exceeded.
The notebook server will temporarily stop sending output
to the client in order to avoid crashing it.
To change this limit, set the config variable
`--NotebookApp.iopub_data_rate_limit`.

Current values:
NotebookApp.iopub_data_rate_limit=1000000.0 (bytes/sec)
NotebookApp.rate_limit_window=3.0 (secs)

The webpage also crashes showing below figure:


问:
php array with a index value of an array
I'm trying to have the $adjective array have a value that is from the $currentCount, but it's giving me an error.

it says syntax error. Thanks!

```<code>$currentCount = [0, 0, 0, 0, 0, 0];
$adjectives=["a","b","c","d","e"];

echo "<h1> The $adjectives[$currentCount[0]] ";
</code>```

答:
You should separate the string and the array variable with the index value because it's reading the square bracket [] as a string.

```<code>$currentCount = [0, 0, 0, 0, 0, 0];
$adjectives = ["a", "b", "c", "d", "e"];

echo "<h1> The " . $adjectives[$currentCount[0]];
</code>```

Body:
I'm trying to have the $adjective array have a value that is from the $currentCount, but it's giving me an error.

it says syntax error. Thanks!

$currentCount = [0, 0, 0, 0, 0, 0];
$adjectives=["a","b","c","d","e"];

echo "
 The $adjectives[$currentCount[0]] ";

Body:
You should separate the string and the array variable with the index value because it's reading the square bracket [] as a string.

$currentCount = [0, 0, 0, 0, 0, 0];
$adjectives = ["a", "b", "c", "d", "e"];

echo "<h1> The " . $adjectives[$currentCount[0]];


问:
Installing R package `MatchIt` in Anaconda Environment
I am attempting to install MatchIt - an R package - in an Anaconda environment. I keep getting error messages that I just don't understand.

I made sure that I had Rcpp installed in the same Conda environment and that I have Xcode installed on my machine. Still no luck. I was wondering if anyone had a solution.

```<code>devtools::install_github('kosukeimai/MatchIt')
Downloading GitHub repo kosukeimai/MatchIt@HEAD
✔  checking for file ‘/private/var/folders/cz/1d4gc7b13dsfknrnbr0tjz580000gn/T/RtmpYISSL1/remotes50d505ff397/kosukeimai-MatchIt-b3032e6/DESCRIPTION’ ...
─  preparing ‘MatchIt’:
✔  checking DESCRIPTION meta-information ...
─  cleaning src
─  installing the package to process help pages
         -----------------------------------
─  installing *source* package ‘MatchIt’ ...
   ** using staged installation
   ** libs
   x86_64-apple-darwin13.4.0-clang++ -std=gnu++11 -I"/opt/anaconda3/envs/pirate/lib/R/include" -DNDEBUG  -I'/opt/anaconda3/envs/pirate/lib/R/library/Rcpp/include' -I'/opt/anaconda3/envs/pirate/lib/R/library/RcppProgress/include' -D_FORTIFY_SOURCE=2 -isystem /opt/anaconda3/envs/pirate/include -mmacosx-version-min=10.9 -I/opt/anaconda3/envs/pirate/include   -fPIC  -march=core2 -mtune=haswell -mssse3 -ftree-vectorize -fPIC -fPIE -fstack-protector-strong -O2 -pipe -stdlib=libc++ -fvisibility-inlines-hidden  -fmessage-length=0 -isystem /opt/anaconda3/envs/pirate/include -fdebug-prefix-map=/Users/runner/miniforge3/conda-bld/r-base-split_1630154249442/work=/usr/local/src/conda/r-base-4.1.1 -fdebug-prefix-map=/opt/anaconda3/envs/pirate=/usr/local/src/conda-prefix  -Wall -pedantic -c RcppExports.cpp -o RcppExports.o
   /bin/sh: x86_64-apple-darwin13.4.0-clang++: command not found
   make: *** [RcppExports.o] Error 127
   ERROR: compilation failed for package ‘MatchIt’
─  removing ‘/private/var/folders/cz/1d4gc7b13dsfknrnbr0tjz580000gn/T/RtmpeKesPi/Rinst1a5f6063566d/MatchIt’
         -----------------------------------
   ERROR: package installation failed
Error: Failed to install 'MatchIt' from GitHub:
  System command 'R' failed, exit status: 1, stdout + stderr (last 10 lines):
E> * installing *source* package ‘MatchIt’ ...
E> ** using staged installation
E> ** libs
E> x86_64-apple-darwin13.4.0-clang++ -std=gnu++11 -I"/opt/anaconda3/envs/pirate/lib/R/include" -DNDEBUG  -I'/opt/anaconda3/envs/pirate/lib/R/library/Rcpp/include' -I'/opt/anaconda3/envs/pirate/lib/R/library/RcppProgress/include' -D_FORTIFY_SOURCE=2 -isystem /opt/anaconda3/envs/pirate/include -mmacosx-version-min=10.9 -I/opt/anaconda3/envs/pirate/include   -fPIC  -march=core2 -mtune=haswell -mssse3 -ftree-vectorize -fPIC -fPIE -fstack-protector-strong -O2 -pipe -stdlib=libc++ -fvisibility-inlines-hidden  -fmessage-length=0 -isystem /opt/anaconda3/envs/pirate/include -fdebug-prefix-map=/Users/runner/miniforge3/conda-bld/r-base-split_1630154249442/work=/usr/local/src/conda/r-base-4.1.1 -fdebug-prefix-map=/opt/anaconda3/envs/pirate=/usr/local/src/conda-prefix  -Wall -pedant
</code>```

I have also looked around on the Conda-forge channel to see if I could just conda install -c conda-forge r-MatchIt but no luck either.

答:
I ended up getting the package to install and compile but I am not exactly sure how.

I deleted then reinstalled Xcode.

I then accessed R in my conda environment via terminal and tried reinstalling the package that way with pgkbuild().

```<code>$ conda activate pirate
$ R
> pkgbuild::check_build_tools(devtools::install_github('kosukeimai/MatchIt'), debug = TRUE)

</code>```

I obviously don't really understand how any of the Clang compiling works, but if this can be useful for someone as clueless as I am, I guess the ole classic of deleting and reinstalling Xcode will do it.

Body:
I am attempting to install MatchIt - an R package - in an Anaconda environment. I keep getting error messages that I just don't understand.

I made sure that I had Rcpp installed in the same Conda environment and that I have Xcode installed on my machine. Still no luck. I was wondering if anyone had a solution.

devtools::install_github('kosukeimai/MatchIt')
Downloading GitHub repo kosukeimai/MatchIt@HEAD
✔  checking for file ‘/private/var/folders/cz/1d4gc7b13dsfknrnbr0tjz580000gn/T/RtmpYISSL1/remotes50d505ff397/kosukeimai-MatchIt-b3032e6/DESCRIPTION’ ...
─  preparing ‘MatchIt’:
✔  checking DESCRIPTION meta-information ...
─  cleaning src
─  installing the package to process help pages
         -----------------------------------
─  installing *source* package ‘MatchIt’ ...
   ** using staged installation
   ** libs
   x86_64-apple-darwin13.4.0-clang++ -std=gnu++11 -I"/opt/anaconda3/envs/pirate/lib/R/include" -DNDEBUG  -I'/opt/anaconda3/envs/pirate/lib/R/library/Rcpp/include' -I'/opt/anaconda3/envs/pirate/lib/R/library/RcppProgress/include' -D_FORTIFY_SOURCE=2 -isystem /opt/anaconda3/envs/pirate/include -mmacosx-version-min=10.9 -I/opt/anaconda3/envs/pirate/include   -fPIC  -march=core2 -mtune=haswell -mssse3 -ftree-vectorize -fPIC -fPIE -fstack-protector-strong -O2 -pipe -stdlib=libc++ -fvisibility-inlines-hidden  -fmessage-length=0 -isystem /opt/anaconda3/envs/pirate/include -fdebug-prefix-map=/Users/runner/miniforge3/conda-bld/r-base-split_1630154249442/work=/usr/local/src/conda/r-base-4.1.1 -fdebug-prefix-map=/opt/anaconda3/envs/pirate=/usr/local/src/conda-prefix  -Wall -pedantic -c RcppExports.cpp -o RcppExports.o
   /bin/sh: x86_64-apple-darwin13.4.0-clang++: command not found
   make: *** [RcppExports.o] Error 127
   ERROR: compilation failed for package ‘MatchIt’
─  removing ‘/private/var/folders/cz/1d4gc7b13dsfknrnbr0tjz580000gn/T/RtmpeKesPi/Rinst1a5f6063566d/MatchIt’
         -----------------------------------
   ERROR: package installation failed
Error: Failed to install 'MatchIt' from GitHub:
  System command 'R' failed, exit status: 1, stdout + stderr (last 10 lines):
E> * installing *source* package ‘MatchIt’ ...
E> ** using staged installation
E> ** libs
E> x86_64-apple-darwin13.4.0-clang++ -std=gnu++11 -I"/opt/anaconda3/envs/pirate/lib/R/include" -DNDEBUG  -I'/opt/anaconda3/envs/pirate/lib/R/library/Rcpp/include' -I'/opt/anaconda3/envs/pirate/lib/R/library/RcppProgress/include' -D_FORTIFY_SOURCE=2 -isystem /opt/anaconda3/envs/pirate/include -mmacosx-version-min=10.9 -I/opt/anaconda3/envs/pirate/include   -fPIC  -march=core2 -mtune=haswell -mssse3 -ftree-vectorize -fPIC -fPIE -fstack-protector-strong -O2 -pipe -stdlib=libc++ -fvisibility-inlines-hidden  -fmessage-length=0 -isystem /opt/anaconda3/envs/pirate/include -fdebug-prefix-map=/Users/runner/miniforge3/conda-bld/r-base-split_1630154249442/work=/usr/local/src/conda/r-base-4.1.1 -fdebug-prefix-map=/opt/anaconda3/envs/pirate=/usr/local/src/conda-prefix  -Wall -pedant

I have also looked around on the Conda-forge channel to see if I could just conda install -c conda-forge r-MatchIt but no luck either.

Body:
I ended up getting the package to install and compile but I am not exactly sure how.

I deleted then reinstalled Xcode.

I then accessed R in my conda environment via terminal and tried reinstalling the package that way with pgkbuild().

$ conda activate pirate
$ R
> pkgbuild::check_build_tools(devtools::install_github('kosukeimai/MatchIt'), debug = TRUE)

I obviously don't really understand how any of the Clang compiling works, but if this can be useful for someone as clueless as I am, I guess the ole classic of deleting and reinstalling Xcode will do it.


问:
Lambda expression in ternary operator
I am trying to write following code but is throwing error:

```<code>a = [x if lambda x:  x%2 ==0 else 0 for x in range(10)]
print(a)
</code>```

The error is pointing at lambda statement. Is it illegal to use her? Of yes then why because all my function is returning is the Boolean True or False.

答:
Aside from [x if x%2 == 0 else 0 for x in range(10)] being shorter, you can use a lambda, but you must call it.

Either with a default arg (x=x):

```<code>[x if (lambda x=x: x%2 ==0)() else 0 for x in range(10)]
</code>```

or by explicitely passing x:

```<code>[x if (lambda x: x%2 ==0)(x) else 0 for x in range(10)]
</code>```

Result for either case:

```<code>[0, 0, 2, 0, 4, 0, 6, 0, 8, 0]
</code>```

Title: Lambda expression in ternary operator

Body:
I am trying to write following code but is throwing error:

a = [x if lambda x:  x%2 ==0 else 0 for x in range(10)]
print(a)

The error is pointing at lambda statement. Is it illegal to use her? Of yes then why because all my function is returning is the Boolean True or False.

Body:
Aside from [x if x%2 == 0 else 0 for x in range(10)] being shorter, you can use a lambda, but you must call it.

Either with a default arg (x=x):

[x if (lambda x=x: x%2 ==0)() else 0 for x in range(10)]

or by explicitely passing x:

[x if (lambda x: x%2 ==0)(x) else 0 for x in range(10)]

Result for either case:

[0, 0, 2, 0, 4, 0, 6, 0, 8, 0]


问:
Pass Python bytes to C/C++ function using swig?
How do you pass a bytes value from Python (like data loaded from a file with open('my file.dat', 'rb').read()) to a C/C++ function using swig?

When I try using char * or uint8_t * and then a size parameter it gives me an error like this:

```<code>TypeError: in method 'processData', argument 3 of type 'char *'
</code>```

I've tried using %pybuffer_mutable_binary and %pybuffer_binary but they don't seem to change the definition of the wrapper and I still get the same error.

答:
Without code can't diagnose what is wrong, but likely you didn't declare %pybuffer lines before the function definitions.  If declared after the generated wrappers won't use them when processing the functions, which would explain "they don't seem to change the definition of the wrapper".

Here's a working example.  Note that passing an immutable item to a function that modifies the string will crash Python.  It would be nice if the commands from pybuffer.i type-checked the Python object for mutability.  If you want that don't use pybuffer.i.

test.i

%module test

%{
#include <stdlib.h>
#include <string.h>
%}

%include <pybuffer.i>
%pybuffer_mutable_string(char* str1)
%pybuffer_string(const char* str2)
%pybuffer_mutable_binary(char* str3, size_t size)
%pybuffer_binary(const char* str4, size_t size)

%inline %{
void funcms(char *str1) {
    strupr(str1);
}

size_t funcs(const char *str2) {
    return strlen(str2);
}

void funcmb(char* str3, size_t size) {
    memset(str3,'A',size);
}

size_t funcb(const char* str4, size_t size) {
    size_t tmp = 0;
    for(size_t i = 0; i < size; ++i)
        tmp += str4[i];
    return tmp % 256;
}
%}
```
<p>Demo:</p>
<pre class="lang-py prettyprint-override"><code>>>> import test
>>> b=bytearray(b'abc')  # mutable string (nul-terminated)
>>> test.funcms(b)
>>> b
bytearray(b'ABC')
>>> test.funcs(b'abc')   # immutable string (nul-terminated)
3
>>> b=bytearray(b'ab\0cd\0ef')  # mutable data (includes nulls)
>>> test.funcmb(b)
>>> b
bytearray(b'AAAAAAAA')
>>> test.funcb(b'ab\0cd\0ef')   # immutable data (compute byte checksum)
85
>>> sum(b'ab\0cd\0ef')%256      # verify result
85
</code>```

Body:
How do you pass a bytes value from Python (like data loaded from a file with open('my file.dat', 'rb').read()) to a C/C++ function using swig?

When I try using char * or uint8_t * and then a size parameter it gives me an error like this:

TypeError: in method 'processData', argument 3 of type 'char *'

I've tried using %pybuffer_mutable_binary and %pybuffer_binary but they don't seem to change the definition of the wrapper and I still get the same error.

Body:
Without code can't diagnose what is wrong, but likely you didn't declare %pybuffer lines before the function definitions.  If declared after the generated wrappers won't use them when processing the functions, which would explain "they don't seem to change the definition of the wrapper".

Here's a working example.  Note that passing an immutable item to a function that modifies the string will crash Python.  It would be nice if the commands from pybuffer.i type-checked the Python object for mutability.  If you want that don't use pybuffer.i.

test.i

%module test

%{
#include <stdlib.h>
#include <string.h>
%}

%include <pybuffer.i>
%pybuffer_mutable_string(char* str1)
%pybuffer_string(const char* str2)
%pybuffer_mutable_binary(char* str3, size_t size)
%pybuffer_binary(const char* str4, size_t size)

%inline %{
void funcms(char *str1) {
    strupr(str1);
}

size_t funcs(const char *str2) {
    return strlen(str2);
}

void funcmb(char* str3, size_t size) {
    memset(str3,'A',size);
}

size_t funcb(const char* str4, size_t size) {
    size_t tmp = 0;
    for(size_t i = 0; i < size; ++i)
        tmp += str4[i];
    return tmp % 256;
}
%}

Demo:

>>> import test
>>> b=bytearray(b'abc')  # mutable string (nul-terminated)
>>> test.funcms(b)
>>> b
bytearray(b'ABC')
>>> test.funcs(b'abc')   # immutable string (nul-terminated)
3
>>> b=bytearray(b'ab\0cd\0ef')  # mutable data (includes nulls)
>>> test.funcmb(b)
>>> b
bytearray(b'AAAAAAAA')
>>> test.funcb(b'ab\0cd\0ef')   # immutable data (compute byte checksum)
85
>>> sum(b'ab\0cd\0ef')%256      # verify result
85


问:
How can you populate a model including child collections from a stored procedure in EF Code First
I have a project using Entity Framework code first.

For various reasons one of the linq queries just doesnt perform well and I want to replace it with a stored procedure call.

The following code works fine for calling a stored procedure and converting the result into a List.

```<code>IEnumerable<Activity> activities =
    ((IObjectContextAdapter)MyContext)
       .ObjectContext.ExecuteStoreQuery<Activity>("GetActivities").ToList();
</code>```

However I also want some includes on the activity model to load one of the child collections on that object. For example Activity has a Virtual List collection. Is there a way I can in my stored procedure also return the Tags for each activity.

If I do the following does not work

```<code>SELECT
   Activities.ID,
   Activities.Name,
   Tags.ID,
   Tags.Name
FROM
   Activities
   LEFT JOIN ActivityTags ON ActivityTags.ActivityID = Activities.ID
   LEFT JOIN Tags ON Tags.ID = ActivityTags.TagID
</code>```

It errors in the C# saying its not a valid activity. If I remove the Tags bit from the stored procedure so it just selects from the Activities table it works fine.

I'm not sure if what I'm asking is possible with a stored procedure using the entity framework or not. If not I may have to resort to using the SqlCommand and building the model from my result set myself.

答: It is not possible. Automatic entity population works only for flat objects = you can populate Activity but not its relation. You must use standard ADO.NET if you want to load relations as well but in such case it would be better to modify your stored procedure to return separate result set for each table to reduce amount of transferred data.

Body:
I have a project using Entity Framework code first.

For various reasons one of the linq queries just doesnt perform well and I want to replace it with a stored procedure call.

The following code works fine for calling a stored procedure and converting the result into a List.

IEnumerable<Activity> activities =
    ((IObjectContextAdapter)MyContext)
       .ObjectContext.ExecuteStoreQuery<Activity>("GetActivities").ToList();

However I also want some includes on the activity model to load one of the child collections on that object. For example Activity has a Virtual List collection. Is there a way I can in my stored procedure also return the Tags for each activity.

If I do the following does not work

SELECT
   Activities.ID,
   Activities.Name,
   Tags.ID,
   Tags.Name
FROM
   Activities
   LEFT JOIN ActivityTags ON ActivityTags.ActivityID = Activities.ID
   LEFT JOIN Tags ON Tags.ID = ActivityTags.TagID

It errors in the C# saying its not a valid activity. If I remove the Tags bit from the stored procedure so it just selects from the Activities table it works fine.

I'm not sure if what I'm asking is possible with a stored procedure using the entity framework or not. If not I may have to resort to using the SqlCommand and building the model from my result set myself.


问:
Better NLog logger name for F# modules and GetCurrentClassLogger()
When I include NLog.LogManager.GetCurrentClassLogger() at the top of my F# modules, the name of the logger looks something like <StartupCode$NLogTest>.$Program. I would have hoped for something like NLogTest.TestModule.

How can I get a better logger name for my F# modules?

Here is a complete example:

Program.fs

```<code>namespace NLogTest

type TestClass() =
    let logger = NLog.LogManager.GetCurrentClassLogger()
    member _.Run() =
        logger.Info("Inside my class")

module TestModule =
    let logger = NLog.LogManager.GetCurrentClassLogger()
    let Run() =
        logger.Info("Inside my module")

module Program =
    [<EntryPoint>]
    let Main _ =
        TestClass().Run()
        TestModule.Run()
        0
</code>```

NLogTest.fsproj

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <None Include="NLog.config">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
    <Compile Include="Program.fs" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="NLog" Version="4.7.13" />
  </ItemGroup>
</Project>
</code>```

NLog.config

```<code><?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
        <target name="logconsole" xsi:type="Console" />
    </targets>
    <rules>
        <logger name="*" minlevel="Info" writeTo="logconsole" />
    </rules>
</nlog>
</code>```

Output

```<code>2022-02-08 18:43:52.6678|INFO|NLogTest.TestClass|Inside my class
2022-02-08 18:43:52.6997|INFO|<StartupCode$NLogTest>.$Program|Inside my module
</code>```

It's that last line that I would like to improve.

答:
Here are several options:

Create the logger inside every module function

```<code>module TestModule =
    let Run() =
        let logger = NLog.LogManager.GetCurrentClassLogger()
        logger.Info("Inside my module")
</code>```

Hard-code the logger name

```<code>module TestModule =
    let logger = NLog.LogManager.GetLogger("NLogTest.TestModule")
    let Run() =
        logger.Info("Inside my module")
</code>```

Use the nameof operator and make the module recursive

Does not include the namespace.

```<code>module rec TestModule =
    let logger = NLog.LogManager.GetLogger(nameof(TestModule))
    let Run() =
        logger.Info("Inside my module")
</code>```

Create a GetCurrentModuleLogger() extension1

Seems to work in lots of cases, but could probably be more robust.

```<code>[<AutoOpen>]
module NLogExtensions =
    open NLog
    type LogManager with
        static member GetCurrentModuleLogger() =
            let moduleFullName =
                System.Diagnostics.StackTrace(1, false)
                    .GetFrames().[0]
                    .GetMethod()
                    .DeclaringType
                    .FullName
            let moduleName = moduleFullName.Split("$") |> Seq.last
            LogManager.GetLogger(moduleName)
</code>```

1Thanks to the NLog.FSharp library for pointing me in this general direction.

Body:
When I include NLog.LogManager.GetCurrentClassLogger() at the top of my F# modules, the name of the logger looks something like <StartupCode$NLogTest>.$Program. I would have hoped for something like NLogTest.TestModule.

How can I get a better logger name for my F# modules?

Here is a complete example:

Program.fs

namespace NLogTest

type TestClass() =
    let logger = NLog.LogManager.GetCurrentClassLogger()
    member _.Run() =
        logger.Info("Inside my class")

module TestModule =
    let logger = NLog.LogManager.GetCurrentClassLogger()
    let Run() =
        logger.Info("Inside my module")

module Program =
    [<EntryPoint>]
    let Main _ =
        TestClass().Run()
        TestModule.Run()
        0

NLogTest.fsproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <None Include="NLog.config">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
    <Compile Include="Program.fs" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="NLog" Version="4.7.13" />
  </ItemGroup>
</Project>

NLog.config

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
        <target name="logconsole" xsi:type="Console" />
    </targets>
    <rules>
        <logger name="*" minlevel="Info" writeTo="logconsole" />
    </rules>
</nlog>

Output

2022-02-08 18:43:52.6678|INFO|NLogTest.TestClass|Inside my class
2022-02-08 18:43:52.6997|INFO|<StartupCode$NLogTest>.$Program|Inside my module

It's that last line that I would like to improve.

Body:
Here are several options:

Create the logger inside every module function

module TestModule =
    let Run() =
        let logger = NLog.LogManager.GetCurrentClassLogger()
        logger.Info("Inside my module")

Hard-code the logger name

module TestModule =
    let logger = NLog.LogManager.GetLogger("NLogTest.TestModule")
    let Run() =
        logger.Info("Inside my module")

Use the nameof operator and make the module recursive

Does not include the namespace.

module rec TestModule =
    let logger = NLog.LogManager.GetLogger(nameof(TestModule))
    let Run() =
        logger.Info("Inside my module")

Create a GetCurrentModuleLogger() extension1

Seems to work in lots of cases, but could probably be more robust.

[<AutoOpen>]
module NLogExtensions =
    open NLog
    type LogManager with
        static member GetCurrentModuleLogger() =
            let moduleFullName =
                System.Diagnostics.StackTrace(1, false)
                    .GetFrames().[0]
                    .GetMethod()
                    .DeclaringType
                    .FullName
            let moduleName = moduleFullName.Split("$") |> Seq.last
            LogManager.GetLogger(moduleName)

1Thanks to the NLog.FSharp library for pointing me in this general direction.


问:
Is there a better way to get XmlReader NodeType properties?
Based on this, it looks like each time I want to get a node element name, or a text value or whatever, I need to use switch-case.

So do I have to use something like this:

```<code>while (reader.Read())
{
    switch (reader.NodeType)
    {
        case XmlNodeType.Element:
        nodeName = reader.Name;
        break;
    }
}
</code>```

or am I missing something and it could be made shorter and more elegant (I need to use XmlReader, and am not in position to use LINQ to XML)? The idea of having to use all this switch-case mess everywhere just to get these small bits of information is not very appealing to me. Thank you.

答:
There is no casting beeing done, so as far as i can see you can just go:

```<code>while(reader.Read())
{
    nodeName = reader.Name;
}
</code>```

I believes nodes always have a name atleast, i might be wrong though, but afaik they do.

Body:
Based on this, it looks like each time I want to get a node element name, or a text value or whatever, I need to use switch-case.

So do I have to use something like this:

while (reader.Read())
{
    switch (reader.NodeType)
    {
        case XmlNodeType.Element:
        nodeName = reader.Name;
        break;
    }
}

or am I missing something and it could be made shorter and more elegant (I need to use XmlReader, and am not in position to use LINQ to XML)? The idea of having to use all this switch-case mess everywhere just to get these small bits of information is not very appealing to me. Thank you.

Body:
There is no casting beeing done, so as far as i can see you can just go:

while(reader.Read())
{
    nodeName = reader.Name;
}

I believes nodes always have a name atleast, i might be wrong though, but afaik they do.


答:
You should wrap the PHP part in the string with {}. Try this

```<code>$currentCount = [0, 0, 0, 0, 0, 0];
$adjectives=["a","b","c","d","e"];

echo "<h1> The {$adjectives[$currentCount[0]]} ";
</code>```

Title: php array with a index value of an array

Body:
You should wrap the PHP part in the string with {}. Try this

$currentCount = [0, 0, 0, 0, 0, 0];
$adjectives=["a","b","c","d","e"];

echo "<h1> The {$adjectives[$currentCount[0]]} ";


问:
Error when using GridLayout class in kivy for python window
Hello I'm learning kivy on python, window 11

Whenever I use GridLayout in "pnn.kv" file, I have this error "AssertionError"

For my code: I'm learning from this tutorial "https://www.youtube.com/watch?v=AS3b70pLYEU&list=PLzMcBGfZo4-kSJVMyYeOQ8CXJ3z1k7gHn&index=8"

Written version from the tutorial:
"main.py" file

```<code>from kivy.app import App
from kivy.uix.widget import Widget

class Layout(Widget):
    pass

class PnnApp(App):
    def build(self):
        return Layout()

if __name__ == "__main__":
    PnnApp().run()

</code>```

"pnn.kv" file:

```<code><Layout>
    GridLayout:
        cols: 1
        size: root.width, root.height

        GridLayout:
            cols: 2

            Label:
                text: "First Name: "
            TextInput:
                multiline: False

            Label:
                text: "Last Name: "
            TextInput:
                multiline: False

            Label:
                text: "Phone number: "
            TextInput:
                multiline: False

        Button:
            text: "Login"

</code>```

Thank you for helping :)

答: The problem is your class name. There is already a Layout class in Kivy. Try changing Layout to something else (maybe MyLayout) everywhere in your code and kv.

Body:
Hello I'm learning kivy on python, window 11

Whenever I use GridLayout in "pnn.kv" file, I have this error "AssertionError"

For my code: I'm learning from this tutorial "https://www.youtube.com/watch?v=AS3b70pLYEU&list=PLzMcBGfZo4-kSJVMyYeOQ8CXJ3z1k7gHn&index=8"

Written version from the tutorial:
"main.py" file

from kivy.app import App
from kivy.uix.widget import Widget

class Layout(Widget):
    pass

class PnnApp(App):
    def build(self):
        return Layout()

if __name__ == "__main__":
    PnnApp().run()

"pnn.kv" file:

<Layout>
    GridLayout:
        cols: 1
        size: root.width, root.height

        GridLayout:
            cols: 2

            Label:
                text: "First Name: "
            TextInput:
                multiline: False

            Label:
                text: "Last Name: "
            TextInput:
                multiline: False

            Label:
                text: "Phone number: "
            TextInput:
                multiline: False

        Button:
            text: "Login"

Thank you for helping :)