问:
Trying to insert value in class method
I'm trying to pass an argument from the get_name() to post() and I'm not sure how to do this correctly</p>
```<code>from bs4 import BeautifulSoup
import requests

webhook = 'my webhook'

class Item:
    def __init__(self, url):
        self.url = url
        self.page = requests.get(url)
        self.soup = BeautifulSoup(self.page.content, 'html.parser')

    def post(self):
        requests.post(webhook, json={'username' : 'scraper', 'content' : variable}) #how do i do this

    def get_name(self):
        name = self.soup.find('h2').get_text()
        post(name)

    def get_price(self):
        price = self.soup.find('span' {'class' : 'text-lg wait-for-i18n-format-render'})
        post(price)
</code>```

答:
The self in the class means that any variable/attribute attached to self can be accessed by any function attached to self anywhere inside the class scope. This means that you are not passing arguments to parameters of a function but instead you use the self identifier.

So with your code the variable and function calls inside the functions are local to the function. To give the variable class scope, attach them to self. eg

```<code>    def get_name(self):
        name = self.soup.find('h2').get_text()
        post(name)
</code>```

would become

```<code>    def get_name(self):
        self.name = self.soup.find('h2').get_text()
        self.post()
</code>```

then in def post(self): you would reference self.name to process.

Title: Trying to insert value in class method

Body:
I'm trying to pass an argument from the get_name() to post() and I'm not sure how to do this correctly

from bs4 import BeautifulSoup
import requests

webhook = 'my webhook'

class Item:
    def __init__(self, url):
        self.url = url
        self.page = requests.get(url)
        self.soup = BeautifulSoup(self.page.content, 'html.parser')

    def post(self):
        requests.post(webhook, json={'username' : 'scraper', 'content' : variable}) #how do i do this

    def get_name(self):
        name = self.soup.find('h2').get_text()
        post(name)

    def get_price(self):
        price = self.soup.find('span' {'class' : 'text-lg wait-for-i18n-format-render'})
        post(price)

Body:
The self in the class means that any variable/attribute attached to self can be accessed by any function attached to self anywhere inside the class scope. This means that you are not passing arguments to parameters of a function but instead you use the self identifier.

So with your code the variable and function calls inside the functions are local to the function. To give the variable class scope, attach them to self. eg

    def get_name(self):
        name = self.soup.find('h2').get_text()
        post(name)

would become

    def get_name(self):
        self.name = self.soup.find('h2').get_text()
        self.post()

then in def post(self): you would reference self.name to process.


来源: stackexchange

问:
How do I use build_full_result() in Boto3
I was Googling around to understand how boto3 paginator works, and found a solution that potentially doesn't require writing any logic with NextToken and While loops.

Still, I'm not quite sure what I'm getting when I'm using this:

client = boto3.client('ec2', region_name='eu-west-1')
results = (
   client.get_paginator('describe_instances')
   .paginate()
   .build_full_result()
)

print(results)
```
<p>I got a huge JSON output and I'm not sure whether I got what I wanted, which is basically the output of all of my EC2 instances.</p>
<p>I'm also not sure how to loop over it, I keep getting <code>TypeError: string indices must be integers</code> which didn't happen before when I used something like:</p>
<pre class="lang-py prettyprint-override"><code>for instance in response_iterator:
    instance = instance['Reservations'][0]
    instance_id = instance['Instances'][0]['InstanceId']
    print(instance_id)
</code>```

I would love to understand how to use the build_full_result() method.

I saw a post that says that it's not documented yet, pretty recent to now (as of writing this post).

答:
Interesting find.. this isn't mentioned anywhere in the latest version of boto3 documentation, however it does appear to properly return all available results.

Below is an example from Lambda that shows how to perform a simple loop through the response.. you can update the last two lines to handle the response syntax from EC2 describe instances.

```<code>import boto3

client = boto3.client('lambda')

results = (
   client.get_paginator('list_functions')
   .paginate()
   .build_full_result()
)

for result in results['Functions']:
    print(result['FunctionName'])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I was Googling around to understand how boto3 paginator works, and found a solution that potentially doesn't require writing any logic with NextToken and While loops.

Still, I'm not quite sure what I'm getting when I'm using this:

client = boto3.client('ec2', region_name='eu-west-1')
results = (
   client.get_paginator('describe_instances')
   .paginate()
   .build_full_result()
)

print(results)

I got a huge JSON output and I'm not sure whether I got what I wanted, which is basically the output of all of my EC2 instances.

I'm also not sure how to loop over it, I keep getting TypeError: string indices must be integers which didn't happen before when I used something like:

for instance in response_iterator:
    instance = instance['Reservations'][0]
    instance_id = instance['Instances'][0]['InstanceId']
    print(instance_id)

I would love to understand how to use the build_full_result() method.

I saw a post that says that it's not documented yet, pretty recent to now (as of writing this post).

Body:
Interesting find.. this isn't mentioned anywhere in the latest version of boto3 documentation, however it does appear to properly return all available results.

Below is an example from Lambda that shows how to perform a simple loop through the response.. you can update the last two lines to handle the response syntax from EC2 describe instances.

import boto3

client = boto3.client('lambda')

results = (
   client.get_paginator('list_functions')
   .paginate()
   .build_full_result()
)

for result in results['Functions']:
    print(result['FunctionName'])


问:
JSON request for envelope with single document, two signers, pre-fill fields
I have an envelope with a single document and two signers saved as a server-side template.  The signers execute the agreement in a specific order.  The document has a number of pre-fill fields in it.

I am trying to automate sending this agreement out using Integromat.  Unfortunately, Integromat's module doesn't allow for pre-fill fields in templates, leaving me to create the API request manually.  This is where I get stuck.

The closest I have come is the JSON request below, POSTed to:
…/v2.1/accounts/{accountId}/envelopes, with capitalised values filled in automatically:

```<code>{
  "templateId": "TEMPLATE_ID",
  "templateRoles": [
    {
      "email": "CLIENT_EMAIL",
      "name": "CLIENT_NAME",
      "roleName": "Recipient",
      "tabs": {
        "prefillTabs": {
          "textTabs": [{
            "tabLabel": "Prefill: Purpose",
            "value": "PURPOSE_FIELD_DATA"
          }]
        }
      }
    }, {
      "email": "STAFF_EMAIL",
      "name": "STAFF_NAME",
      "roleName": "Company"
    }
  ],
  "status": "sent"
}
</code>```

The response from the API is:

The operation failed with an error. [400] A Required field is
incomplete. TabId: GUI_HERE

What I can't figure out is how to get the pre-fill data submitted since it's not tied to a particular signer.  I have scoured the v2.1 API documentation but there is no scenario simple enough for this request.

Apologies if I am missing something obvious here; this is my first rodeo with DocuSign's API.

Do you have any idea what I am doing wrong or, better yet, what the body of the request should be for this (presumably) simple scenario?

答:
I just tried this with composite templates.
When I added the prefill tabs to a recipient I received the error

```<code>Error code: INVALID_TAB_OPERATION.

Message: The Tab specified is not valid for the requested operation.
PrefillTab not allowed for recipient.
</code>```

which makes sense since prefill tabs are associated with a document, not a recipient.

I tried by adding a document to the composite template, but that didn't work either.

I suggest that you use regular tabs. Mark them locked so they can't be changed. Mark them shared so every signer will see them. Then fill in their values as part of your Envelopes:create call.

Here's a live example of doing this. Note the text2 tab which is locked. (It should have the shared attribute set to true. You can add that from the Tabs/text toolbox on the left.)

Also see this blog post about templates.

Body:
I have an envelope with a single document and two signers saved as a server-side template.  The signers execute the agreement in a specific order.  The document has a number of pre-fill fields in it.

I am trying to automate sending this agreement out using Integromat.  Unfortunately, Integromat's module doesn't allow for pre-fill fields in templates, leaving me to create the API request manually.  This is where I get stuck.

The closest I have come is the JSON request below, POSTed to:
…/v2.1/accounts/{accountId}/envelopes, with capitalised values filled in automatically:

{
  "templateId": "TEMPLATE_ID",
  "templateRoles": [
    {
      "email": "CLIENT_EMAIL",
      "name": "CLIENT_NAME",
      "roleName": "Recipient",
      "tabs": {
        "prefillTabs": {
          "textTabs": [{
            "tabLabel": "Prefill: Purpose",
            "value": "PURPOSE_FIELD_DATA"
          }]
        }
      }
    }, {
      "email": "STAFF_EMAIL",
      "name": "STAFF_NAME",
      "roleName": "Company"
    }
  ],
  "status": "sent"
}

The response from the API is:

The operation failed with an error. [400] A Required field is
incomplete. TabId: GUI_HERE

What I can't figure out is how to get the pre-fill data submitted since it's not tied to a particular signer.  I have scoured the v2.1 API documentation but there is no scenario simple enough for this request.

Apologies if I am missing something obvious here; this is my first rodeo with DocuSign's API.

Do you have any idea what I am doing wrong or, better yet, what the body of the request should be for this (presumably) simple scenario?

Body:
I just tried this with composite templates.
When I added the prefill tabs to a recipient I received the error

Error code: INVALID_TAB_OPERATION.

Message: The Tab specified is not valid for the requested operation.
PrefillTab not allowed for recipient.

which makes sense since prefill tabs are associated with a document, not a recipient.

I tried by adding a document to the composite template, but that didn't work either.

I suggest that you use regular tabs. Mark them locked so they can't be changed. Mark them shared so every signer will see them. Then fill in their values as part of your Envelopes:create call.

Here's a live example of doing this. Note the text2 tab which is locked. (It should have the shared attribute set to true. You can add that from the Tabs/text toolbox on the left.)

Also see this blog post about templates.


问:
Setting Active Sheet via Sheets API
I have a Google Spreadsheet wherein I'm facilitating multiple rounds of voting.  The spreadsheet  has roughly 20 sheets total.  Each round of voting is it's own sheet, and when current round X is in motion, the sheet for Round X is made active, a second sheet 'Tabulations' is shown, and all other sheets are hidden.

I am using Google Apps Script and I have functions calling and manipulating data in the round sheets.  An example of one of the functions used in the Round X sheets is below:

```<code>function sendBallot(localCurrentRound) {
  var currentRoundSheet = ss.getSheetByName(localCurrentRound).activate();

  var sendBallot = currentRoundSheet.getRange("SendBallot").getValue();

  if (sendBallot == "Yes"){
    var maxNumVotes = currentRoundSheet.getRange("MaxNumVotes").getValue();

    var currentRoundCandidates = getCandidateRoster(localCurrentRound);
    populateBallotQuestions(localCurrentRound, maxNumVotes, currentRoundCandidates);

    ss.toast("Ballot Google Form Updated for " + localCurrentRound + "!!");
  }else {
    ss.toast("Send Ballot not ready !!");
  }
}
</code>```

I'd like to minimize the calls to the Spreadsheet service, so I am attempting to use Sheets API.  I've figured out all the batchget and batchUpdate calls, but I cannot figure out how to make the RoundX sheet active.  I looked at the documentation and can't figure out where the Active/SetActive property lies.

Any ideas?

Title: Setting Active Sheet via Sheets API

Body:
I have a Google Spreadsheet wherein I'm facilitating multiple rounds of voting.  The spreadsheet  has roughly 20 sheets total.  Each round of voting is it's own sheet, and when current round X is in motion, the sheet for Round X is made active, a second sheet 'Tabulations' is shown, and all other sheets are hidden.

I am using Google Apps Script and I have functions calling and manipulating data in the round sheets.  An example of one of the functions used in the Round X sheets is below:

function sendBallot(localCurrentRound) {
  var currentRoundSheet = ss.getSheetByName(localCurrentRound).activate();

  var sendBallot = currentRoundSheet.getRange("SendBallot").getValue();

  if (sendBallot == "Yes"){
    var maxNumVotes = currentRoundSheet.getRange("MaxNumVotes").getValue();

    var currentRoundCandidates = getCandidateRoster(localCurrentRound);
    populateBallotQuestions(localCurrentRound, maxNumVotes, currentRoundCandidates);

    ss.toast("Ballot Google Form Updated for " + localCurrentRound + "!!");
  }else {
    ss.toast("Send Ballot not ready !!");
  }
}

I'd like to minimize the calls to the Spreadsheet service, so I am attempting to use Sheets API.  I've figured out all the batchget and batchUpdate calls, but I cannot figure out how to make the RoundX sheet active.  I looked at the documentation and can't figure out where the Active/SetActive property lies.

Any ideas?

Body:
Read Values from active sheet with Sheets API version 4

function readValuesFromActiveSheet() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet();
  const r = Sheets.Spreadsheets.Values.get(ss.getId(),`${sh.getName()}!${sh.getDataRange().getA1Notation()}`);
  const o = JSON.parse(r);
  Logger.log(`Range: ${JSON.stringify(o.range)} Values: ${JSON.stringify(o.values)}`)
}

Execution log
1:51:52 PM  Notice  Execution started
1:51:51 PM  Info    Range: "Sheet0!A1:J21" Values: [["COL1","COL2","COL3","COL4","COL5","COL6","COL7","COL8","COL9","COL10"],["19","4","4","8","10","17","8","7","11","2"],["9","10","7","19","2","7","5","7","7","3"],["7","0","18","14","17","7","2","1","15","1"],["17","2","1","2","9","1","10","15","15","7"],["18","6","10","17","17","18","5","14","12","0"],["11","10","4","0","4","2","5","3","19","18"],["0","2","0","9","9","10","7","18","7","19"],["6","15","12","9","7","14","13","6","17","6"],["8","17","17","16","8","11","5","17","6","12"],["4","10","8","10","19","14","13","16","1","3"],["16","15","1","16","5","12","16","1","6","10"],["4","19","4","4","3","16","6","14","6","9"],["15","13","0","0","5","17","2","7","17","17"],["2","17","9","9","3","15","19","8","11","2"],["0","5","6","2","12","3","0","10","10","17"],["10","11","13","9","18","6","9","14","1","14"],["2","3","12","14","11","2","14","13","6","0"],["9","3","19","11","4","4","0","5","16","10"],["2","16","2","17","4","16","10","5","11","0"],["8","1","11","16","2","5","9","8","12","9"]]
1:51:53 PM  Notice  Execution completed

Read Multiple Sheets

function readvalues() {
  const ss = SpreadsheetApp.getActive();
  const sA = ['Sheet0', 'Sheet1', 'Sheet2'];
  const shts = ss.getSheets().filter(sh => ~sA.indexOf(sh.getName()));
  shts.forEach((sh, i) => {
    const r = Sheets.Spreadsheets.Values.get(ss.getId(), `${shts[i].getName()}!${shts[i].getDataRange().getA1Notation()}`);
    const o = JSON.parse(r);
    Logger.log(`Range: ${JSON.stringify(o.range)} Values: ${JSON.stringify(o.values)}`)
  });
}


问:
Using dynamic typing in D, a statically typed language
I was implementing a dynamic typing library for D when I ran across an interesting problem.

Right now, I've succeeded in making a function called dynamic() which returns a dynamic version of an object.

For example:

```<code>import std.stdio, std.dynamic.core;

class Foo
{
    string bar(string a) { return a ~ "OMG"; }
    int opUnary(string s)() if (s == "-") { return 0; }
}

void main(string[] argv)
{
    Dynamic d = dynamic(new Foo());
    Dynamic result = d.bar("hi");
    writeln(result);  // Uh-oh
}
</code>```

The problem I've run across is the fact that writeln tries to use compile-time reflection to figure out how to treat result.

What's the first thing it tries?  isInputRange!(typeof(result))

The trouble is, it returns true! Why? Because I have to assume that all members which it needs exist, unless I can prove otherwise at run time  -- which is too late. So the program tries to call front, popFront, and empty on result, crashing my program.

I can't think of a way to fix this. Does anyone have an idea?

答: what is wrong with using std.variant which implements all you need for dynamic typing (along with quite a bit of syntactic sugar)

ContentLicense: CC BY-SA 3.0

Body:
I was implementing a dynamic typing library for D when I ran across an interesting problem.

Right now, I've succeeded in making a function called dynamic() which returns a dynamic version of an object.

For example:

import std.stdio, std.dynamic.core;

class Foo
{
    string bar(string a) { return a ~ "OMG"; }
    int opUnary(string s)() if (s == "-") { return 0; }
}

void main(string[] argv)
{
    Dynamic d = dynamic(new Foo());
    Dynamic result = d.bar("hi");
    writeln(result);  // Uh-oh
}

The problem I've run across is the fact that writeln tries to use compile-time reflection to figure out how to treat result.

What's the first thing it tries?  isInputRange!(typeof(result))

The trouble is, it returns true! Why? Because I have to assume that all members which it needs exist, unless I can prove otherwise at run time  -- which is too late. So the program tries to call front, popFront, and empty on result, crashing my program.

I can't think of a way to fix this. Does anyone have an idea?


问:
Is there a way to read keypresses from the Enter key?
I have been fooling around in python (v3.9.10) and I have found no way to read keypresses from the enter key and have tkinter do something with that keypress. I am trying to make a dumb little program to show some numbers on my screen for school and want to be able to do it quickly. this is my code so far:

```<code>from tkinter import *

#DEFS
def submit():
    submitted=entrybox.get()
    display.config(text=submitted)

app=Tk()

entrybox=Entry(width=10)

entrybox.place(x=10,y=10)

#display label
display=Label(text=' ')
display.place(x=50,y=50)
display.config(font='Arial 72')

#submit button
subbutton=Button(text='SUBMIT',command=submit)
subbutton.place(x=70,y=10)
</code>```

(Sorry if my code looks really bad I am quite new to python and everything it has to offer)
(I am also sorry for sounding repetitive and/or dumb. Forums such as this aren't familiar to me either)

is there any way to read key presses from the enter key while allowing the rest of my tkinter stuff to run as intended? thanks in advance.

答:
How to bind and handle events

Use bind(sequence, func) method on your widget (like Button or even the root app Tk).

The parameter sequence is one of the predefined events, a string name for keys, mouse-events, etc.
The parameter func is a callback or handler function, given by name only (without parentheses or arguments), which must have one positional parameter for Event.

Demo

See this minimal example:

```<code>from tkinter import *

def callback(event):
    print(event)

def quit():   # did we miss something ?
    print("Escape was pressed. Quitting.. Bye!")
    exit()

app = Tk()
app.bind('<Return>', callback)  # on keypress of Enter or Return key
app.bind('<Enter>', callback)  # on mouse-pointer entering the widget - here the app's root window (not confuse with Enter key of keyboard)
app.bind('<Escape>', quit)  # on keypress of Escape key

app.mainloop()  # to start the main loop listening for events
</code>```

Prints after following keys pressed:

Enter key was pressed

Escape key was pressed

```<code><KeyPress event keysym=Return keycode=36 char='\r' x=-583 y=-309>
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.6/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
TypeError: quit() takes 0 positional arguments but 1 was given
</code>```

Note:

The Enter key was caught and bound callback/handler function (callback) invoked which prints the passed event.

The Escape key was caught and bound callback/handler function (quit) invoked. But since it hasn't the required parameter (like event) the invocation failed with a TypeError.

When adding the parameter def quit(event): it succeeds:

```<code><Enter event focus=True x=6 y=188>
<Enter event focus=True x=182 y=45>
<KeyPress event keysym=Return keycode=36 char='\r' x=-583 y=-309>
<Enter event state=Button1 focus=True x=123 y=68>
Escape was pressed. Quitting.. Bye!
</code>```

Note:

The <Enter> event is when the mouse-pointer enters the (visible) widget frame, here of the application's root window.

The <Escape> event exits the application

Further reading

RealPython: Python GUI Programming With Tkinter is a rich tutorial to learn more, especially on Using .bind().

Body:
I have been fooling around in python (v3.9.10) and I have found no way to read keypresses from the enter key and have tkinter do something with that keypress. I am trying to make a dumb little program to show some numbers on my screen for school and want to be able to do it quickly. this is my code so far:

from tkinter import *

#DEFS
def submit():
    submitted=entrybox.get()
    display.config(text=submitted)

app=Tk()

entrybox=Entry(width=10)

entrybox.place(x=10,y=10)

#display label
display=Label(text=' ')
display.place(x=50,y=50)
display.config(font='Arial 72')

#submit button
subbutton=Button(text='SUBMIT',command=submit)
subbutton.place(x=70,y=10)

(Sorry if my code looks really bad I am quite new to python and everything it has to offer)
(I am also sorry for sounding repetitive and/or dumb. Forums such as this aren't familiar to me either)

is there any way to read key presses from the enter key while allowing the rest of my tkinter stuff to run as intended? thanks in advance.

Body:
How to bind and handle events

Use bind(sequence, func) method on your widget (like Button or even the root app Tk).

The parameter sequence is one of the predefined events, a string name for keys, mouse-events, etc.
The parameter func is a callback or handler function, given by name only (without parentheses or arguments), which must have one positional parameter for Event.

Demo

See this minimal example:

from tkinter import *

def callback(event):
    print(event)

def quit():   # did we miss something ?
    print("Escape was pressed. Quitting.. Bye!")
    exit()

app = Tk()
app.bind('<Return>', callback)  # on keypress of Enter or Return key
app.bind('<Enter>', callback)  # on mouse-pointer entering the widget - here the app's root window (not confuse with Enter key of keyboard)
app.bind('<Escape>', quit)  # on keypress of Escape key

app.mainloop()  # to start the main loop listening for events

Prints after following keys pressed:

Enter key was pressed

Escape key was pressed

<KeyPress event keysym=Return keycode=36 char='\r' x=-583 y=-309>
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.6/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
TypeError: quit() takes 0 positional arguments but 1 was given

Note:

The Enter key was caught and bound callback/handler function (callback) invoked which prints the passed event.

The Escape key was caught and bound callback/handler function (quit) invoked. But since it hasn't the required parameter (like event) the invocation failed with a TypeError.

When adding the parameter def quit(event): it succeeds:

<Enter event focus=True x=6 y=188>
<Enter event focus=True x=182 y=45>
<KeyPress event keysym=Return keycode=36 char='\r' x=-583 y=-309>
<Enter event state=Button1 focus=True x=123 y=68>
Escape was pressed. Quitting.. Bye!

Note:

The <Enter> event is when the mouse-pointer enters the (visible) widget frame, here of the application's root window.

The <Escape> event exits the application

Further reading

RealPython: Python GUI Programming With Tkinter is a rich tutorial to learn more, especially on Using .bind().


问:
Vue app (data out of scope) - Data is not defined at Proxy.calc
*Greetings Stackoverflow peeps.

I am developing my first Vue app and having issues with using the find function to loop through my metals list to pull the specificGravity value based on a matching type prop.
It seems that the list is out of scope and I am unable to find a solution through good ole' Google, so I turn to you all.

TIA*

Error:

"vue@next:1751 Uncaught ReferenceError: data is not defined
at Proxy.calc (index.html:101:45)
at onClick (eval at compileToFunction (vue@next:15591:23), :142:35)
at callWithErrorHandling (vue@next:1688:24)
at callWithAsyncErrorHandling (vue@next:1697:23)
at HTMLButtonElement.invoker (vue@next:9486:15)"

```<code><script>
        var app = Vue.createApp({
            data: function() {

                return {

                    waxWeight: null,
                    isVisible: true,
                    buttonSize: null,
                    specificGravity: null,
                    metalType: null
                }
            },

            // <!-- COMPONENTS -->
            components: {
                    },

            // <!-- METHODS -->
            // `this` inside methods point to the current Vue instance
            methods: {
                calc: function (waxWeight, buttonSize, metalType) {

                    var waxWeight = waxWeight
                    var buttonSize = buttonSize
                    var metalType = metalType

                var metals = {metals:[
                    { type: 'silver', specificGravity: 10.3 },
                    { type: 'wGold14', specificGravity: 12.1 },
                    { type: 'wGold18', specificGravity: 11.5 },
                    { type: 'yGold14', specificGravity: 13.6 }]}

                    // method does not have access to data list
                    const specificGravity = data.metals.find(function(elem){
                        if(elem.name == metalType)

                        return elem.specificGravity;

                        alert(metalType)
                    });
                }
            },
        })
        app.mount('#app')
    </script>
</code>```

答:
Initial issue resolved here: https://codepen.io/pandemicprogrammer/pen/GROWqwR

I was referencing the array object incorrectly and had my JSON data in the wrong spot.

```<code>
methods: {
                calc: function (waxWeight, buttonSize, metalType) {
                    alert("test")

                    var waxWeight = waxWeight
                    var buttonSize = buttonSize
                    var metalType = metalType

                    var metals = {metals:[
                    { type: 'silver', specificGravity: 10.3 },
                    { type: 'wGold14', specificGravity: 12.1 },
                    { type: 'wGold18', specificGravity: 11.5 },
                    { type: 'yGold14', specificGravity: 13.6 }]}

                    const specificGravity =
                    metals.metals.find(function(elem){

                        if(elem.type == metalType) {

                            alert(elem.specificGravity)
                            return elem.specificGravity;
                        }

                    });
                }
            },

</code>```

Body:
Initial issue resolved here: https://codepen.io/pandemicprogrammer/pen/GROWqwR

I was referencing the array object incorrectly and had my JSON data in the wrong spot.

methods: {
                calc: function (waxWeight, buttonSize, metalType) {
                    alert("test")

                    var waxWeight = waxWeight
                    var buttonSize = buttonSize
                    var metalType = metalType

                    var metals = {metals:[
                    { type: 'silver', specificGravity: 10.3 },
                    { type: 'wGold14', specificGravity: 12.1 },
                    { type: 'wGold18', specificGravity: 11.5 },
                    { type: 'yGold14', specificGravity: 13.6 }]}

                    const specificGravity =
                    metals.metals.find(function(elem){

                        if(elem.type == metalType) {

                            alert(elem.specificGravity)
                            return elem.specificGravity;
                        }

                    });
                }
            },


问:
PRISM Navigation - Xamarin Forms - MasterDetail/FlyoutPage page setup, previous page nav links disabled when back button pressed?
So I built an app using Prism Library and Xamarin Forms and the Navigation flow starts with a MasterDetail page, like so.

```<code>NavigationService.NavigateAsync($"/{nameof(MainMenuPage)}/{nameof(NavigationPage)}/{nameof(DashboardPage)}");
</code>```

MainMenuPage

My MainMenuPage contains the Flyout page with a ListView of the MenuItems

```<code><FlyoutPage.Flyout>
    <NavigationPage
        NavigationPage.HasNavigationBar="false"
        Icon="{ StaticResource HamburgerIcon }"
        Style="{ StaticResource MainMenuStyle }"
        Title="{ grial:Translate PageTitleMainMenu }">
        <x:Arguments>
            <ContentPage>
                <Grid>
                    <BoxView
                        Style="{ StaticResource MainMenuOrModalBackgroundStyle }"
                        Opacity="1" />

                    <Image
                        Style="{ StaticResource MainMenuBackgroundImageStyle }" />

                    <Grid
                        grial:Effects.ApplyIOSSafeAreaAsPadding="Left,Right"
                        RowSpacing="0"
                        VerticalOptions="FillAndExpand">
                        <Grid.RowDefinitions>
                            <RowDefinition
                                    Height="Auto" />
                            <RowDefinition
                                    Height="*" />
                            <RowDefinition
                                    Height="Auto"/>
                        </Grid.RowDefinitions>

                        <local:BrandBlock
                                Grid.Row="0"
                                Grid.Column="0"
                                Margin="20,60,20,30"
                                VerticalOptions="Start"
                                HorizontalOptions="Start" />

                        <ListView
                                Margin="0,0,0,10"
                                Grid.Row="1"
                                SelectedItem="{ Binding SelectedMainMenuItem, Mode=TwoWay}"
                                ItemsSource="{ Binding MainMenuItems }"
                                VerticalOptions="FillAndExpand"
                                Style="{ StaticResource MainMenuListViewStyle }">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <ViewCell>
                                        <views:MainMenuItemTemplate />
                                    </ViewCell>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                            <ListView.Behaviors>
                                <behavior:EventToCommandBehavior EventName="ItemTapped"
                                                                 Command="{Binding NavigateCommand}"
                                                                 EventArgsParameterPath="Item">

                                </behavior:EventToCommandBehavior>
                            </ListView.Behaviors>
                        </ListView>

                        <views:ApplicationVersionTemplate Grid.Row="2" Margin="35,0,0,20" HorizontalOptions="Start" VerticalOptions="Start" />
                    </Grid>
                </Grid>
            </ContentPage>
        </x:Arguments>
    </NavigationPage>
</FlyoutPage.Flyout>

<FlyoutPage.Detail>
    <NavigationPage>
        <x:Arguments>
            <ContentPage>
                <Grid></Grid>
            </ContentPage>
        </x:Arguments>
    </NavigationPage>
</FlyoutPage.Detail>
</code>```

I'm navigating to the detail pages using the following format:

```<code>await NavigationService.NavigateAsync($"{nameof(NavigationPage)}/{SelectedMainMenuItem.PageName}", null, SelectedMainMenuItem.IsModal, SelectedMainMenuItem.IsAnimated);
</code>```

I noticed in a lot of the samples, the MasterDetailPage.Master node is in a ContentPage not a NavigationPage node like I'm doing. Is that what I'm doing wrong? It looks to me like NavigationPage is a child of Master here. Is that correct? Just trying to figure out why when I go back to a previous page (by pressing the back button in the navbar) the page is disabled, meaning the navigation links no longer work. My initial root page navigation is absolute, all the rest of the Navigate commands are relative.

Note - I changed the MasterDetailPage to FlyoutPage since the naming changed in Xamarin.Forms v5. This bug was happening before I changed the name to FlyoutPage.

答:
I don't know about FlyoutPage.Detail, but MasterDetailPage.Content should be left empty in xaml, it's filled automatically when navigating.

Also, with MasterDetailPage, I navigate to ../SomeOtherPage to add it to the stack (enable back button). Navigate to /MainPage/NavigationPage/AnotherPage to replace the stack (no back button).

Body:
So I built an app using Prism Library and Xamarin Forms and the Navigation flow starts with a MasterDetail page, like so.

NavigationService.NavigateAsync($"/{nameof(MainMenuPage)}/{nameof(NavigationPage)}/{nameof(DashboardPage)}");

MainMenuPage

My MainMenuPage contains the Flyout page with a ListView of the MenuItems

<FlyoutPage.Flyout>
    <NavigationPage
        NavigationPage.HasNavigationBar="false"
        Icon="{ StaticResource HamburgerIcon }"
        Style="{ StaticResource MainMenuStyle }"
        Title="{ grial:Translate PageTitleMainMenu }">
        <x:Arguments>
            <ContentPage>
                <Grid>
                    <BoxView
                        Style="{ StaticResource MainMenuOrModalBackgroundStyle }"
                        Opacity="1" />

                    <Image
                        Style="{ StaticResource MainMenuBackgroundImageStyle }" />

                    <Grid
                        grial:Effects.ApplyIOSSafeAreaAsPadding="Left,Right"
                        RowSpacing="0"
                        VerticalOptions="FillAndExpand">
                        <Grid.RowDefinitions>
                            <RowDefinition
                                    Height="Auto" />
                            <RowDefinition
                                    Height="*" />
                            <RowDefinition
                                    Height="Auto"/>
                        </Grid.RowDefinitions>

                        <local:BrandBlock
                                Grid.Row="0"
                                Grid.Column="0"
                                Margin="20,60,20,30"
                                VerticalOptions="Start"
                                HorizontalOptions="Start" />

                        <ListView
                                Margin="0,0,0,10"
                                Grid.Row="1"
                                SelectedItem="{ Binding SelectedMainMenuItem, Mode=TwoWay}"
                                ItemsSource="{ Binding MainMenuItems }"
                                VerticalOptions="FillAndExpand"
                                Style="{ StaticResource MainMenuListViewStyle }">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <ViewCell>
                                        <views:MainMenuItemTemplate />
                                    </ViewCell>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                            <ListView.Behaviors>
                                <behavior:EventToCommandBehavior EventName="ItemTapped"
                                                                 Command="{Binding NavigateCommand}"
                                                                 EventArgsParameterPath="Item">

                                </behavior:EventToCommandBehavior>
                            </ListView.Behaviors>
                        </ListView>

                        <views:ApplicationVersionTemplate Grid.Row="2" Margin="35,0,0,20" HorizontalOptions="Start" VerticalOptions="Start" />
                    </Grid>
                </Grid>
            </ContentPage>
        </x:Arguments>
    </NavigationPage>
</FlyoutPage.Flyout>

<FlyoutPage.Detail>
    <NavigationPage>
        <x:Arguments>
            <ContentPage>
                <Grid></Grid>
            </ContentPage>
        </x:Arguments>
    </NavigationPage>
</FlyoutPage.Detail>

I'm navigating to the detail pages using the following format:

await NavigationService.NavigateAsync($"{nameof(NavigationPage)}/{SelectedMainMenuItem.PageName}", null, SelectedMainMenuItem.IsModal, SelectedMainMenuItem.IsAnimated);

I noticed in a lot of the samples, the MasterDetailPage.Master node is in a ContentPage not a NavigationPage node like I'm doing. Is that what I'm doing wrong? It looks to me like NavigationPage is a child of Master here. Is that correct? Just trying to figure out why when I go back to a previous page (by pressing the back button in the navbar) the page is disabled, meaning the navigation links no longer work. My initial root page navigation is absolute, all the rest of the Navigate commands are relative.

Note - I changed the MasterDetailPage to FlyoutPage since the naming changed in Xamarin.Forms v5. This bug was happening before I changed the name to FlyoutPage.


问:
How to create a builder function that transforms key-value data, and is supplied with both the data and the structure/format of the output
This is a follow-up question to: How to build/transform an object from a previous object

Given data in a key-value format, I want to transform it into a new structure.

// given data example #1
const dataAnimals = {"monkeys": 10, "alligators": 20}

// given data example #2
const dataColors = {"red": 100, "green": 4, "yellow": 17}
```
<p>And the new structure of the <em>output</em> can be chosen from any prespecified format.
If we stick with <code>dataAnimals</code> as the input, there are three possible output formats:</p>
<p><em>structure type 1</em></p>
<pre class="lang-json prettyprint-override"><code>[
    {
        label: {
            en: "monkeys"
        },
        value: 10
    },
    {
        label: {
            en: "alligators"
        },
        value: 20
    }
]
</code>```

structure type 2

[
    {
        count: 10,
        label: {
            en: "monkeys"
        }
    },
    {
        count: 20,
        label: {
            en: "alligators"
        }
    }
]
```
<p><em>structure type 3</em></p>
<pre class="lang-json prettyprint-override"><code>[
    {
        count: 10,
        value: "monkeys"
    },
    {
        count: 20,
        value: "alligators"
    }
]
</code>```

I'm likely to have several more types of structures.

I wonder if there's a way to supply the chosen/desired structure (i.e., pass the structure to a builder function alongside the input data itself).

So far, using ramda I could only write 3 separate builder functions with the structure being hard-coded inside each:

const buildArr1 = R.pipe(R.toPairs, R.map(R.applySpec({value: R.nth(1), label: {en: R.nth(0)}})))
const buildArr2 = R.pipe(R.toPairs, R.map(R.applySpec({count: R.nth(1), label: {en: R.nth(0)}})))
const buildArr3 = R.pipe(R.toPairs, R.map(R.applySpec({value: R.nth(0), count: R.nth(1)})))

buildArr1(dataAnimals)
buildArr2(dataAnimals)
buildArr3(dataAnimals)
```
<p>The differences between <code>buildArr1()</code>, <code>buildArr2()</code>, and <code>buildArr3()</code> are subtle and only in terms of the structure inside <code>applySpec()</code>. So it got me thinking, whether it's possible to have just <em><strong>one</strong></em> function <code>buildArr()</code>, that takes as input both the data to transform and the format to be returned.</p>
<pre class="lang-js prettyprint-override"><code>// pseudo-code for desired code
buildArr(dataAnimals, structureType1)
// which will return
// [
//     {
//         label: {
//             en: "monkeys"
//         },
//         value: 10
//     },
//     {
//         label: {
//             en: "alligators"
//         },
//         value: 20
//     }
// ]

buildArr(dataAnimals, structureType2)

// [
//     {
//         count: 10,
//         label: {
//             en: "monkeys"
//         }
//     },
//     {
//         count: 20,
//         label: {
//             en: "alligators"
//         }
//     }
// ]
</code>```

Is there any proper way to do something like that? I'm also not sure what should be the nature of structureType1/structureType2 being passed. An object? Or rather a function that "knows to interact" with the input data?

Please note that while this question revolves around ramda, it seems (to me) to be broader than a specific library.

EDIT

User @Scott Sauyet has nicely pointed out that writing the individual builders (i.e., buildArr1(), buildArr2, etc.) could be achieved with plain JS. This speaks to my point above, that this isn't necessarily a ramda question.

const buildArr1PlainJS = (o) => ({data: Object .entries (o) .map (([k, v]) => ({value: v, label: {en: k}}))})
const buildArr2PlainJS = (o) => ({data: Object .entries (o) .map (([k, v]) => ({count: v, label: {en: k}}))})
const buildArr3PlainJS = (o) => ({data: Object .entries (o) .map (([k, v]) => ({value: k, count: v}))})
```

答:
I think you can do this fairly easily by passing in a formatting function to a generic processor.  It might look something like this:

// main function
const transform = (fn) => (o) => Object .entries (o) .map (([k, v]) => fn (k, v))

// formatting functions
const format1 = transform ((k, v) => ({label: {en: k}, value: v}))
const format2 = transform ((k, v) => ({count: v, label: {en: k}}))
const format3 = transform ((k, v) => ({count: v, value: k}))

// input data
const inputs = {
  dataAnimals: {"monkeys": 10, "alligators": 20},
  dataColors: {"red": 100, "green": 4, "yellow": 17},
};

// demo
Object .entries (inputs) .forEach (([name, input]) => [format1, format2, format3] .forEach ((format, i) =>
  console .log (`${name}, format ${i + 1}:`, format (input))
))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {max-height: 100% !important; top: 0}</code>```

Again, I don't see Ramda adding much value here, although we could of course do this  with Ramda's tools.  We might write:

const transform = (fn) => (o) => map (unapply (fn)) (toPairs (o))
```
<p>Or if you had a point-free fetish, even this:</p>
<pre class="lang-js prettyprint-override"><code>const transform = compose (flip (o) (toPairs), map, unapply)
</code>```

But I don't think these -- especially the latter -- add anything useful.

Body:
This is a follow-up question to: How to build/transform an object from a previous object

Given data in a key-value format, I want to transform it into a new structure.

// given data example #1
const dataAnimals = {"monkeys": 10, "alligators": 20}

// given data example #2
const dataColors = {"red": 100, "green": 4, "yellow": 17}

And the new structure of the output can be chosen from any prespecified format.
If we stick with dataAnimals as the input, there are three possible output formats:

structure type 1

[
    {
        label: {
            en: "monkeys"
        },
        value: 10
    },
    {
        label: {
            en: "alligators"
        },
        value: 20
    }
]

structure type 2

[
    {
        count: 10,
        label: {
            en: "monkeys"
        }
    },
    {
        count: 20,
        label: {
            en: "alligators"
        }
    }
]

structure type 3

[
    {
        count: 10,
        value: "monkeys"
    },
    {
        count: 20,
        value: "alligators"
    }
]

I'm likely to have several more types of structures.

I wonder if there's a way to supply the chosen/desired structure (i.e., pass the structure to a builder function alongside the input data itself).

So far, using ramda I could only write 3 separate builder functions with the structure being hard-coded inside each:

const buildArr1 = R.pipe(R.toPairs, R.map(R.applySpec({value: R.nth(1), label: {en: R.nth(0)}})))
const buildArr2 = R.pipe(R.toPairs, R.map(R.applySpec({count: R.nth(1), label: {en: R.nth(0)}})))
const buildArr3 = R.pipe(R.toPairs, R.map(R.applySpec({value: R.nth(0), count: R.nth(1)})))

buildArr1(dataAnimals)
buildArr2(dataAnimals)
buildArr3(dataAnimals)

The differences between buildArr1(), buildArr2(), and buildArr3() are subtle and only in terms of the structure inside applySpec(). So it got me thinking, whether it's possible to have just one function buildArr(), that takes as input both the data to transform and the format to be returned.

// pseudo-code for desired code
buildArr(dataAnimals, structureType1)
// which will return
// [
//     {
//         label: {
//             en: "monkeys"
//         },
//         value: 10
//     },
//     {
//         label: {
//             en: "alligators"
//         },
//         value: 20
//     }
// ]

buildArr(dataAnimals, structureType2)

// [
//     {
//         count: 10,
//         label: {
//             en: "monkeys"
//         }
//     },
//     {
//         count: 20,
//         label: {
//             en: "alligators"
//         }
//     }
// ]

Is there any proper way to do something like that? I'm also not sure what should be the nature of structureType1/structureType2 being passed. An object? Or rather a function that "knows to interact" with the input data?

Please note that while this question revolves around ramda, it seems (to me) to be broader than a specific library.

EDIT

User @Scott Sauyet has nicely pointed out that writing the individual builders (i.e., buildArr1(), buildArr2, etc.) could be achieved with plain JS. This speaks to my point above, that this isn't necessarily a ramda question.

const buildArr1PlainJS = (o) => ({data: Object .entries (o) .map (([k, v]) => ({value: v, label: {en: k}}))})
const buildArr2PlainJS = (o) => ({data: Object .entries (o) .map (([k, v]) => ({count: v, label: {en: k}}))})
const buildArr3PlainJS = (o) => ({data: Object .entries (o) .map (([k, v]) => ({value: k, count: v}))})

Body:
I think you can do this fairly easily by passing in a formatting function to a generic processor.  It might look something like this:

// main function
const transform = (fn) => (o) => Object .entries (o) .map (([k, v]) => fn (k, v))

// formatting functions
const format1 = transform ((k, v) => ({label: {en: k}, value: v}))
const format2 = transform ((k, v) => ({count: v, label: {en: k}}))
const format3 = transform ((k, v) => ({count: v, value: k}))

// input data
const inputs = {
  dataAnimals: {"monkeys": 10, "alligators": 20},
  dataColors: {"red": 100, "green": 4, "yellow": 17},
};

// demo
Object .entries (inputs) .forEach (([name, input]) => [format1, format2, format3] .forEach ((format, i) =>
  console .log (`${name}, format ${i + 1}:`, format (input))
))

.as-console-wrapper {max-height: 100% !important; top: 0}

Again, I don't see Ramda adding much value here, although we could of course do this  with Ramda's tools.  We might write:

const transform = (fn) => (o) => map (unapply (fn)) (toPairs (o))

Or if you had a point-free fetish, even this:

const transform = compose (flip (o) (toPairs), map, unapply)

But I don't think these -- especially the latter -- add anything useful.


问:
Add commas or spaces to group every three digits
I have a function to add commas to numbers:

```<code>function commafy( num ) {
  num.toString().replace( /\B(?=(?:\d{3})+)$/g, "," );
}
</code>```

Unfortunately, it doesn't like decimals very well. Given the following usage examples, what is the best way to extend my function?

```<code>commafy( "123" )                 // "123"
commafy( "1234" )                // "1234"
                                 // Don't add commas until 5 integer digits
commafy( "12345" )               // "12,345"
commafy( "1234567" )             // "1,234,567"
commafy( "12345.2" )             // "12,345.2"
commafy( "12345.6789" )          // "12,345.6789"
                                 // Again, nothing until 5
commafy( ".123456" )             // ".123 456"
                                 // Group with spaces (no leading digit)
commafy( "12345.6789012345678" ) // "12,345.678 901 234 567 8"
</code>```

Presumably the easiest way is to first split on the decimal point (if there is one). Where best to go from there?

答:
This is basically the same as the solution from Ghostoy, but it fixes an issue where numbers in the thousands are not handled properly. Changed '5' to '4':</p>
```<code>export function commafy(num) {
    const str = num.toString().split('.');
    if (str[0].length >= 4) {
        str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
    }
    if (str[1] && str[1].length >= 4) {
        str[1] = str[1].replace(/(\d{3})/g, '$1 ');
    }
    return str.join('.');
}
</code>```

Body:
I have a function to add commas to numbers:

function commafy( num ) {
  num.toString().replace( /\B(?=(?:\d{3})+)$/g, "," );
}

Unfortunately, it doesn't like decimals very well. Given the following usage examples, what is the best way to extend my function?

commafy( "123" )                 // "123"
commafy( "1234" )                // "1234"
                                 // Don't add commas until 5 integer digits
commafy( "12345" )               // "12,345"
commafy( "1234567" )             // "1,234,567"
commafy( "12345.2" )             // "12,345.2"
commafy( "12345.6789" )          // "12,345.6789"
                                 // Again, nothing until 5
commafy( ".123456" )             // ".123 456"
                                 // Group with spaces (no leading digit)
commafy( "12345.6789012345678" ) // "12,345.678 901 234 567 8"

Presumably the easiest way is to first split on the decimal point (if there is one). Where best to go from there?

Body:
This is basically the same as the solution from Ghostoy, but it fixes an issue where numbers in the thousands are not handled properly. Changed '5' to '4':

export function commafy(num) {
    const str = num.toString().split('.');
    if (str[0].length >= 4) {
        str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
    }
    if (str[1] && str[1].length >= 4) {
        str[1] = str[1].replace(/(\d{3})/g, '$1 ');
    }
    return str.join('.');
}


问:
GS base added up with offset does not correspond to gs:offset
When debugging Linux Kernel ran as QEMU guest with GDB I faced the following instruction:

```<code>mov    rcx,QWORD PTR gs:0x1fbc0
</code>```

The question is the rcx register does contain the gs base added up with the value 0x1fbc0. Here is what I figured out in gdb:

```<code>#Before execution of the instruction
(gdb) p/x $rcx
$10 = 0x0
(gdb) p/x $gs_base
$11 = 0xffff888237c80000

#Execution of the instruction
(gdb) si
vm_unmapped_area (info=info@entry=0xffffc90000eb7d70) at mm/mmap.c:2002

#Completely unclear value
(gdb) p/x $rcx
$12 = 0xffff888105e79980
</code>```

My first thought was that GDB reported the GS base incorrectly, but then I got the same from the rdmsr tool

```<code>$ sudo rdmsr -p 2 0xc0000101
ffff888237c80000
</code>```

Making things even more unclear.

Why doesn't gs:0x1fbc0 result in $gs_base + 0x1fbc0?

答:
mov with a memory source loads data from the linear address indicated by $gs_base + 0x1fbc0, it does not load the linear address itself into the destination.

To address some of your further comments, the qword ptr keywords for a MASM-style dialect indicate a memory access rather than loading an immediate. The rule that all memory accesses are wrapped in brackets [...] and everything else (immediate or register accesses) is not wrapped in brackets is a NASM-ism. In MASM a destination can have keywords {size} ptr or brackets [...] or just specify a variable name to indicate to the assembler to use a memory load. Absent any of those, or by specifying a variable name with an offset keyword prepended, it will encode so as to load an immediate number instead.

Even if your example was an immediate load it would just be mov rcx, 0x1fbc0 without gs as there is no immediate-to-register form instructions that include segment override prefixes with any effect whatsoever. You can technically put a gs prefix in front of such an instruction and it will generally still be decoded fine in practice. However, the gs prefix would serve no purpose then. A disassembler (like gdb's) would hopefully not display the source immediate operand of such an instruction with a gs: prefix.

Body:
When debugging Linux Kernel ran as QEMU guest with GDB I faced the following instruction:

mov    rcx,QWORD PTR gs:0x1fbc0

The question is the rcx register does contain the gs base added up with the value 0x1fbc0. Here is what I figured out in gdb:

#Before execution of the instruction
(gdb) p/x $rcx
$10 = 0x0
(gdb) p/x $gs_base
$11 = 0xffff888237c80000

#Execution of the instruction
(gdb) si
vm_unmapped_area (info=info@entry=0xffffc90000eb7d70) at mm/mmap.c:2002

#Completely unclear value
(gdb) p/x $rcx
$12 = 0xffff888105e79980

My first thought was that GDB reported the GS base incorrectly, but then I got the same from the rdmsr tool

$ sudo rdmsr -p 2 0xc0000101
ffff888237c80000

Making things even more unclear.

Why doesn't gs:0x1fbc0 result in $gs_base + 0x1fbc0?


问:
typescript Cannot add headers to a fetch api using react-native
I am using Fetch API from react-native and I am using typescript.
My code looks like this:

```<code>let responseLogin = await fetch('http://url_example', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: requestBody
    });
</code>```

But I get the following error where the header is:

```<code> Argument of type '{ method: string; headers: { 'Content-Type': string; }; body: string; }' is not assignable to parameter of type 'RequestInit'.
  Types of property 'headers' are incompatible.
    Type '{ 'Content-Type': string; }' is not assignable to type 'Headers | string[][]'.
      Object literal may only specify known properties, and ''Content-Type'' does not exist in type 'Headers | string[][]'.
</code>```

I have also tried to create a custom header but without any luck:

```<code>    let requestHeaders = new Headers();
        requestHeaders.set('Content-Type', 'application/json');
        // I have also tried adding this at the end but no luck
        // requestHeaders.get('Content-Type');
</code>```

How could I add a header to this? Because I cannot find any way to make this happen and I don't know what is the problem. If I test these in postman, I get a 200 response, here I get a 401 response.
I have also tried this library just to add custom headers: https://www.npmjs.com/package/fetch-headers

I use:
Visual studio code 1.81.1
"react-native": "0.50.0",
"typescript": "2.6.1"

答:
The accepted answer has the caveat that it doesn't handle the scenario where you encapsulate fetch into a function of your own that receives the same arguments as fetch and sets defaults to the headers property. For example:

```<code>async function myFetch(input: RequestInfo, init: RequestInit) {
  // set some headers here
  const res = await fetch(input, init)
  // return something from the response here, handle errors
}
</code>```

The problem with the resolved answer is that RequestInit.headers is of type HeadersInit whose definition is:

```<code>type HeadersInit = string[][] | Record<string, string> | Headers;
</code>```

When I try to set defaults for headers but still use headers passed by the calling function, I run into issues because of these possible multiple types that I need to deal with.

What I resolved out of complete exasperation is to define my own RequestInit type where headers is only Record<string, string>. I don't care about the other types, an object of string key/values IS fine.

```<code>

export interface MyRequestInit extends Omit<RequestInit, 'headers'> {
  headers?: Record<string, string>;
}

export async function fetchJson<JSON = unknown>(
  input: RequestInfo,
  init: MyRequestInit = {},
) {
  // set my own default headers here
  const res = await fetch(input, init)
  // ...
}
</code>```

Body:
I am using Fetch API from react-native and I am using typescript.
My code looks like this:

let responseLogin = await fetch('http://url_example', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: requestBody
    });

But I get the following error where the header is:

 Argument of type '{ method: string; headers: { 'Content-Type': string; }; body: string; }' is not assignable to parameter of type 'RequestInit'.
  Types of property 'headers' are incompatible.
    Type '{ 'Content-Type': string; }' is not assignable to type 'Headers | string[][]'.
      Object literal may only specify known properties, and ''Content-Type'' does not exist in type 'Headers | string[][]'.

I have also tried to create a custom header but without any luck:

    let requestHeaders = new Headers();
        requestHeaders.set('Content-Type', 'application/json');
        // I have also tried adding this at the end but no luck
        // requestHeaders.get('Content-Type');

How could I add a header to this? Because I cannot find any way to make this happen and I don't know what is the problem. If I test these in postman, I get a 200 response, here I get a 401 response.
I have also tried this library just to add custom headers: https://www.npmjs.com/package/fetch-headers

I use:
Visual studio code 1.81.1
"react-native": "0.50.0",
"typescript": "2.6.1"

Body:
The accepted answer has the caveat that it doesn't handle the scenario where you encapsulate fetch into a function of your own that receives the same arguments as fetch and sets defaults to the headers property. For example:

async function myFetch(input: RequestInfo, init: RequestInit) {
  // set some headers here
  const res = await fetch(input, init)
  // return something from the response here, handle errors
}

The problem with the resolved answer is that RequestInit.headers is of type HeadersInit whose definition is:

type HeadersInit = string[][] | Record<string, string> | Headers;

When I try to set defaults for headers but still use headers passed by the calling function, I run into issues because of these possible multiple types that I need to deal with.

What I resolved out of complete exasperation is to define my own RequestInit type where headers is only Record<string, string>. I don't care about the other types, an object of string key/values IS fine.

export interface MyRequestInit extends Omit<RequestInit, 'headers'> {
  headers?: Record<string, string>;
}

export async function fetchJson<JSON = unknown>(
  input: RequestInfo,
  init: MyRequestInit = {},
) {
  // set my own default headers here
  const res = await fetch(input, init)
  // ...
}


问:
Write into a file in S3 directly
I have a requirement where I need to write a long String log for each execution of my lambda function, this String is basically log having record of failed and success cases.
as this code is for lambda its not possible to create file in a physical location like local file directly and upload to s3. but I need to directly create a file and write the String in one go.
Thanks in advance.</p>

答:
AWS Lambda functions can write data to the /tmp/ directory. There is a 512MB limit, so delete any files before your Lambda function exits so that it is clear for the next function execution.

You can therefore create a 'local' file and upload it to Amazon S3.

Alternatively, you can use the Amazon S3 API to create an object (PutObject()) while specifying the Body content without creating an actual file. This might be easier for you.

By the way, if your Lambda function prints output, it will automatically be captured by the Lambda function and stored in CloudWatch Logs. It will be intermixed with other messages from Lambda (eg showing the amount of memory used), but it's an easy way to log information.

Title: Write into a file in S3 directly


问:
Get branch on Origin not on local
I ran in to a situation where I was working on two separate machines and ended up with the following:

Laptop A:

main

branch_a

branch_b

Laptop B:

main

branch_c

Origin:

main

branch_a

branch_b

branch_c

I am now done working on Laptop B and will continue working on Laptop A. How do I go about getting just branch_c locally on to my Laptop A and then working from there only?

答:
Not entirely sure I understand the question, but if you simply want to access branch_c on laptop A, here are the instructions.

First you must fetch, to get the latest on the remote server. Then checkout branch_c.

run the following:

```<code>git fetch
git checkout branch_c
</code>```

that is it

Title: Get branch on Origin not on local

Body:
Not entirely sure I understand the question, but if you simply want to access branch_c on laptop A, here are the instructions.

First you must fetch, to get the latest on the remote server. Then checkout branch_c.

run the following:

git fetch
git checkout branch_c

that is it


问:
Delete and replace Nan values with mean of the rows in pandas dataframe
I have a very big DataFrame that looks like:

```<code>    c1   c2    c3
0  NaN  1.0   NaN
1  NaN  NaN   NaN
2  3.0  6.0   9.0
3  NaN  7.0  10.0
...
</code>```

I want to:

1- Delete the rows with all "Nan" values. like the second row in the sample.

2- Replace all the "Nan" values in other rows with the mean of the rows.

Note: in the rows, we have different "Nan" values.
could you please help me with that? Thanks.

Also, this link does not solve my question:
Pandas Dataframe: Replacing NaN with row average

Here is a sample of my DataFrame:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame()
df['c1'] = [np.nan, np.nan, 3, np.nan]
df['c2'] = [1, np.nan, 6, 7]
df['c3'] = [np.nan, np.nan, 9, 10]
</code>```

Update:
When we don't want to consider the mean of all rows.
sample dataframe:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame()
df['id'] = [1, 2, 3, 4, 5]
df['c1'] = [np.nan, np.nan, 3, np.nan, 5]
df['c2'] = [1, np.nan, 3, 11, 5]
df['c3'] = [1, np.nan, 3, 11, np.nan]
df['c4'] = [3, np.nan, 3, 11, 5]

output:
df = pd.DataFrame()
df['id'] = [1,  3, 4, 5]
df['c1'] = [ 5/3, 3, 11, 5]
df['c2'] = [1,  3, 11, 5]
df['c3'] = [1,  3, 11, 5]
df['c4'] = [3,  3, 11, 5]
df
</code>```

For this part, I don't want to consider the value of id for calculating the mean of row.

答:
You could create a dictionary from the column names and row means and pass it to fillna to fill the NaN values. Then drop the NaN rows (which won't get filled in because all NaN rows have mean NaN).

```<code>out = df.fillna(dict.fromkeys(df.columns, df.mean(axis=1))).dropna()
</code>```

Another possibility is to transpose the DataFrame and use fillna to fill, then transpose back:

```<code>df_T = df.T
df_T.fillna(df_T.mean()).T.dropna()
</code>```

Output:

```<code>    c1   c2    c3
0  1.0  1.0   1.0
2  3.0  6.0   9.0
3  8.5  7.0  10.0
</code>```

Body:
I have a very big DataFrame that looks like:

    c1   c2    c3
0  NaN  1.0   NaN
1  NaN  NaN   NaN
2  3.0  6.0   9.0
3  NaN  7.0  10.0
...

I want to:

1- Delete the rows with all "Nan" values. like the second row in the sample.

2- Replace all the "Nan" values in other rows with the mean of the rows.

Note: in the rows, we have different "Nan" values.
could you please help me with that? Thanks.

Also, this link does not solve my question:
Pandas Dataframe: Replacing NaN with row average

Here is a sample of my DataFrame:

import pandas as pd
import numpy as np

df = pd.DataFrame()
df['c1'] = [np.nan, np.nan, 3, np.nan]
df['c2'] = [1, np.nan, 6, 7]
df['c3'] = [np.nan, np.nan, 9, 10]

Update:
When we don't want to consider the mean of all rows.
sample dataframe:

import pandas as pd
import numpy as np

df = pd.DataFrame()
df['id'] = [1, 2, 3, 4, 5]
df['c1'] = [np.nan, np.nan, 3, np.nan, 5]
df['c2'] = [1, np.nan, 3, 11, 5]
df['c3'] = [1, np.nan, 3, 11, np.nan]
df['c4'] = [3, np.nan, 3, 11, 5]

output:
df = pd.DataFrame()
df['id'] = [1,  3, 4, 5]
df['c1'] = [ 5/3, 3, 11, 5]
df['c2'] = [1,  3, 11, 5]
df['c3'] = [1,  3, 11, 5]
df['c4'] = [3,  3, 11, 5]
df

For this part, I don't want to consider the value of id for calculating the mean of row.

Body:
You could create a dictionary from the column names and row means and pass it to fillna to fill the NaN values. Then drop the NaN rows (which won't get filled in because all NaN rows have mean NaN).

out = df.fillna(dict.fromkeys(df.columns, df.mean(axis=1))).dropna()

Another possibility is to transpose the DataFrame and use fillna to fill, then transpose back:

df_T = df.T
df_T.fillna(df_T.mean()).T.dropna()

Output:

    c1   c2    c3
0  1.0  1.0   1.0
2  3.0  6.0   9.0
3  8.5  7.0  10.0


问:
Build a data frame from the existing data frame which has the distinct id
I have a data frame like in the figure.

I have multiple id with different columns.

I want to build another dataframe that only has the distinct id and also the dataframes has all the columns for that id.

could you help me with that? Thank you so much

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame()
df['id'] = [2, 3, 3,2,1]
df['c2'] = [1, 10, 6, 7, 4]
df['c3'] = [11, 23, 9, 10,23]
print(df)

dfn = pd.DataFrame()
dfn['id'] = [2, 3,1]
dfn['c2'] = [1, 10, 4]
dfn['c3'] = [11, 23, 23]
dfn['c4'] = [7, 6,  0]
dfn['c5'] = [10, 9,  0]
dfn
</code>```

The first one is that I have and the second one is that I want

答:
You can use set_index / unstack at starting point of the transformation to flatten your dataframe. You can execute the following code step-by-step to follow the transformation to your final dataframe:

```<code>out = (
    df.set_index('id').rename_axis(columns='col')
      .stack().rename('val').reset_index()
      .assign(col=lambda x: x.groupby('id').cumcount().add(2))
      .pivot_table('val', 'id', 'col', fill_value=0, sort=False)
      .add_prefix('c').reset_index().rename_axis(columns=None)
)
</code>```

Output:

```<code>>>> out
   id  c2  c3  c4  c5
0   2   1  11   7  10
1   3  10  23   6   9
2   1   4  23   0   0
</code>```

Body:
I have a data frame like in the figure.

I have multiple id with different columns.

I want to build another dataframe that only has the distinct id and also the dataframes has all the columns for that id.

could you help me with that? Thank you so much

import pandas as pd
import numpy as np

df = pd.DataFrame()
df['id'] = [2, 3, 3,2,1]
df['c2'] = [1, 10, 6, 7, 4]
df['c3'] = [11, 23, 9, 10,23]
print(df)

dfn = pd.DataFrame()
dfn['id'] = [2, 3,1]
dfn['c2'] = [1, 10, 4]
dfn['c3'] = [11, 23, 23]
dfn['c4'] = [7, 6,  0]
dfn['c5'] = [10, 9,  0]
dfn

The first one is that I have and the second one is that I want

Body:
You can use set_index / unstack at starting point of the transformation to flatten your dataframe. You can execute the following code step-by-step to follow the transformation to your final dataframe:

out = (
    df.set_index('id').rename_axis(columns='col')
      .stack().rename('val').reset_index()
      .assign(col=lambda x: x.groupby('id').cumcount().add(2))
      .pivot_table('val', 'id', 'col', fill_value=0, sort=False)
      .add_prefix('c').reset_index().rename_axis(columns=None)
)

Output:

>>> out
   id  c2  c3  c4  c5
0   2   1  11   7  10
1   3  10  23   6   9
2   1   4  23   0   0


问:
hasnext() for Python iterators?
Do Python iterators have a hasnext method?

答:
I think there are valid use cases for when you may want some sort of has_next functionality, in which case you should decorate an iterator with a has_next defined.

Combining concepts from the answers to this question here is my implementation of that which feels like a nice concise solution to me (python 3.9):

_EMPTY_BUF = object()

class BufferedIterator(Iterator[_T]):
    def __init__(self, real_it: Iterator[_T]):
        self._real_it = real_it
        self._buf = next(self._real_it, _EMPTY_BUF)

    def has_next(self):
        return self._buf is not _EMPTY_BUF

    def __next__(self) -> _T_co:
        v = self._buf
        self._buf = next(self._real_it, _EMPTY_BUF)
        if v is _EMPTY_BUF:
            raise StopIteration()
        return v

```

The main difference is that has_next is just a boolean expression, and also handles iterators with None values.

Added this to a gist here with tests and example usage.

Title: hasnext() for Python iterators?

Body:
I think there are valid use cases for when you may want some sort of has_next functionality, in which case you should decorate an iterator with a has_next defined.

Combining concepts from the answers to this question here is my implementation of that which feels like a nice concise solution to me (python 3.9):

_EMPTY_BUF = object()

class BufferedIterator(Iterator[_T]):
    def __init__(self, real_it: Iterator[_T]):
        self._real_it = real_it
        self._buf = next(self._real_it, _EMPTY_BUF)

    def has_next(self):
        return self._buf is not _EMPTY_BUF

    def __next__(self) -> _T_co:
        v = self._buf
        self._buf = next(self._real_it, _EMPTY_BUF)
        if v is _EMPTY_BUF:
            raise StopIteration()
        return v

The main difference is that has_next is just a boolean expression, and also handles iterators with None values.

Added this to a gist here with tests and example usage.


问:
What's the difference between git stash save and git stash push?
When should I use git stash save instead of git stash push and vice-versa?

答:
The push command is intended to always be used over the save command, as it is more flexible and uses more conventional command line arguments.  The save command is deprecated for these reasons.

Replacement

The push option was introduced in 2.13.0 in order to provide the command line arguments in a more conventional way than save does.

The rationale for this change was documented in the commit messages which added the command to Git:

f5727e2:

Introduce a new git stash push verb in addition to git stash save.  The
push verb is used to transition from the current command line arguments
to a more conventional way, in which the message is given as an argument
to the -m option.

This allows us to have pathspecs at the end of the command line
arguments like other Git commands do, so that the user can say which
subset of paths to stash (and leave others behind).

c0c0c82:

With the 'git stash save' interface, it was easily possible for users to
try to add a message which would start with "-", which 'git stash save'
would interpret as a command line argument, and fail.  […]

For 'stash push', messages are passed with the -m flag, avoiding this
potential pitfall.  Now only pathspecs starting with "-" would have to
be distinguished from command line parameters by using
"-- --<pathspec>".  This is fairly common in the git command line
interface, and we don't try to guess what the users wanted in the other
cases.

fd2ebf1:

'git stash push' has all functionality of 'git stash save',
with a nicer, more consistent user interface

Deprecation

The save command was officially deprecated in the 2.16.0 release of Git:

"git stash save" has been deprecated in favour of "git stash push".

The deprecation of save is explained in its documentation:

save [-p|--patch] [-S|--staged] [-k|--[no-]keep-index] [-u|--include-untracked] [-a|--all] [-q|--quiet] [<message>]

This option is deprecated in favour of git stash push. It differs from "stash push" in that it cannot take pathspec. Instead, all non-option arguments are concatenated to form the stash message.

Short form

In addition to the standard form of the command, push has a short form whereby "push" is omitted from the stash command.  The save command has no such equivalent.  Per the documentation:

For quickly making a snapshot, you can omit "push". In this mode, non-option arguments are not allowed to prevent a misspelled subcommand from making an unwanted stash entry. The two exceptions to this are stash -p which acts as alias for stash push -p and pathspec elements, which are allowed after a double hyphen -- for disambiguation.

git stash
git stash -p
```

Command comparison

From reading through the documentation, I think this should be a fairly complete comparison of the two commands:

push
save

git stash push
git stash save

git stash push -m <message>
git stash save <message> or git stash save -m <message>

git stash push -m <message> (message starting with "-")
git stash save -m <message>

git stash push [--] <pathspec>…
N/A (not possible)

git stash push --pathspec-from-file=<file>
N/A (not possible)

git stash
git stash save

git stash -p
git stash save -p

git stash -- <pathspec>…
N/A (not possible)

As shown in this comparison, the notable changes between save and push are:

A partial stash can be created using pathspecs using push, but not save.  The pathspec can be provided either as inline arguments or by using --.

The message can be provided as an inline argument with save, but must be provided by -m in push

Body:
The push command is intended to always be used over the save command, as it is more flexible and uses more conventional command line arguments.  The save command is deprecated for these reasons.

Replacement

The push option was introduced in 2.13.0 in order to provide the command line arguments in a more conventional way than save does.

The rationale for this change was documented in the commit messages which added the command to Git:

f5727e2:

Introduce a new git stash push verb in addition to git stash save.  The
push verb is used to transition from the current command line arguments
to a more conventional way, in which the message is given as an argument
to the -m option.

This allows us to have pathspecs at the end of the command line
arguments like other Git commands do, so that the user can say which
subset of paths to stash (and leave others behind).

c0c0c82:

With the 'git stash save' interface, it was easily possible for users to
try to add a message which would start with "-", which 'git stash save'
would interpret as a command line argument, and fail.  […]

For 'stash push', messages are passed with the -m flag, avoiding this
potential pitfall.  Now only pathspecs starting with "-" would have to
be distinguished from command line parameters by using
"-- --<pathspec>".  This is fairly common in the git command line
interface, and we don't try to guess what the users wanted in the other
cases.

fd2ebf1:

'git stash push' has all functionality of 'git stash save',
with a nicer, more consistent user interface

Deprecation

The save command was officially deprecated in the 2.16.0 release of Git:

"git stash save" has been deprecated in favour of "git stash push".

The deprecation of save is explained in its documentation:

save [-p|--patch] [-S|--staged] [-k|--[no-]keep-index] [-u|--include-untracked] [-a|--all] [-q|--quiet] [<message>]

This option is deprecated in favour of git stash push. It differs from "stash push" in that it cannot take pathspec. Instead, all non-option arguments are concatenated to form the stash message.

Short form

In addition to the standard form of the command, push has a short form whereby "push" is omitted from the stash command.  The save command has no such equivalent.  Per the documentation:

For quickly making a snapshot, you can omit "push". In this mode, non-option arguments are not allowed to prevent a misspelled subcommand from making an unwanted stash entry. The two exceptions to this are stash -p which acts as alias for stash push -p and pathspec elements, which are allowed after a double hyphen -- for disambiguation.

git stash
git stash -p

Command comparison

From reading through the documentation, I think this should be a fairly complete comparison of the two commands:

push
save

git stash push
git stash save

git stash push -m <message>
git stash save <message> or git stash save -m <message>

git stash push -m <message> (message starting with "-")
git stash save -m <message>

git stash push [--] <pathspec>…
N/A (not possible)

git stash push --pathspec-from-file=<file>
N/A (not possible)

git stash
git stash save

git stash -p
git stash save -p

git stash -- <pathspec>…
N/A (not possible)

As shown in this comparison, the notable changes between save and push are:

A partial stash can be created using pathspecs using push, but not save.  The pathspec can be provided either as inline arguments or by using --.

The message can be provided as an inline argument with save, but must be provided by -m in push


问:
How to get nodes credentials using jenkinsapi
I need to get credentials information (which credentials used) for node.

Currently I use this code that prints LOT of information but no credentials info that used for the node:

```<code>for node in get_server_instance().nodes._data['computer']:
    for i in node:
        print (i, node[i])
</code>```

Is there any way to reach credentials ?

Thanks

答: The only way is run grep "credentials" */config.xml on the server inside nodes directory</p>

Body:
I need to get credentials information (which credentials used) for node.

Currently I use this code that prints LOT of information but no credentials info that used for the node:

for node in get_server_instance().nodes._data['computer']:
    for i in node:
        print (i, node[i])

Is there any way to reach credentials ?

Thanks


问:
How to throw "The file is in use"
I have some files (.xml extensions) that my app requires them to be present as long as my application is open.

So, is there a cross-platform solution to mark these files as "File in use" so that the user cannot delete or modify them?

答:
Since you specify you need it to work cross-platform, you might want to use Qt with QFile::setPermissions and set it to QFileDevice::ReadOwner. Do note the platform-specifc notes the documentation makes. There is nothing similar in the C++ Standard Library as far as I am aware.

Edit: turns out I was wrong! Since C++17 can use std::filesystem::permissions and set the permissions to read-only.

Title: How to throw "The file is in use"


问:
Take chars from array and place them randomly to create String
I have got a char array (size 12) that can look like this:

```<code>{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'}
</code>```

And I would like to create (in the most efficient way) a String that would be the result of taking the characters from the array and ordering them ~randomly (let's use that word), for example:

```<code>“ahbejclfkdig”
</code>```

I tried solutions with StringBuffer and random placing, but there was the problem of positions repeating. Also, I tried Collections.shuffle, but I don’t quite get this one working. I also looked at linear feedback shift register, but I don’t think is appropriate here. It is quite simple case, I will not be operating on large numbers, so memory allocation and speed should not raise any major issues.

答:
I have tried the following piece of code... I guess you can use it in your scenario!</p>

```<code>String[] alphabets = new String[12];
int i = 0;
char[] arrayAlpha = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'};
for (char ch : arrayAlpha) {
   alphabets[i++] = String.valueOf(ch);
}

List<String> list = Arrays.asList(alphabets);
Collections.shuffle(list);

for (String alpha : list) {
    System.out.print(alpha + " ");
}
</code>```

Body:
I have got a char array (size 12) that can look like this:

{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'}

And I would like to create (in the most efficient way) a String that would be the result of taking the characters from the array and ordering them ~randomly (let's use that word), for example:

“ahbejclfkdig”

I tried solutions with StringBuffer and random placing, but there was the problem of positions repeating. Also, I tried Collections.shuffle, but I don’t quite get this one working. I also looked at linear feedback shift register, but I don’t think is appropriate here. It is quite simple case, I will not be operating on large numbers, so memory allocation and speed should not raise any major issues.

Body:
I have tried the following piece of code... I guess you can use it in your scenario!

String[] alphabets = new String[12];
int i = 0;
char[] arrayAlpha = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'};
for (char ch : arrayAlpha) {
   alphabets[i++] = String.valueOf(ch);
}

List<String> list = Arrays.asList(alphabets);
Collections.shuffle(list);

for (String alpha : list) {
    System.out.print(alpha + " ");
}


问:
How do I check if a value is of, or promotable to, a column type in pandas?
For example, suppose I have the following DataFrame.

```<code>import pandas as pd

df = pd.DataFrame([['a', 1.3, 10], ['b', 2, 20]], columns=['id', 'v1', 'v2'])
df = df.astype({col: 'category' for col in df.columns[df.dtypes == object]})

print(df)
print()
print(df.dtypes)

  id   v1  v2
0  a  1.3  10
1  b  2.0  20

id    category
v1     float64
v2       int64
</code>```

Given a value and a column identifier, I need to know whether the type of the value is compatible with the column.  (Of the same type or promotable.)

For category fields, I'd like to know if a value is in the category.  I can do something like

```<code>'x' in df['id'].unique()
</code>```

but there may be a more efficient way.

Thanks.

答:
Suppose you have a value x=4.3

you can simply compare like:

df.v1.dtype will give the data type of the particular column you want to compare (v1 in this case)

```<code>type(x)==df.v1.dtype
#output True
</code>```

Body:
For example, suppose I have the following DataFrame.

import pandas as pd

df = pd.DataFrame([['a', 1.3, 10], ['b', 2, 20]], columns=['id', 'v1', 'v2'])
df = df.astype({col: 'category' for col in df.columns[df.dtypes == object]})

print(df)
print()
print(df.dtypes)

  id   v1  v2
0  a  1.3  10
1  b  2.0  20

id    category
v1     float64
v2       int64

Given a value and a column identifier, I need to know whether the type of the value is compatible with the column.  (Of the same type or promotable.)

For category fields, I'd like to know if a value is in the category.  I can do something like

'x' in df['id'].unique()

but there may be a more efficient way.

Thanks.

Body:
Suppose you have a value x=4.3

you can simply compare like:

df.v1.dtype will give the data type of the particular column you want to compare (v1 in this case)

type(x)==df.v1.dtype
#output True


问:
I have a Terraform that creates a AWS RDS, aurora mysql, is there a way to create a table on the DB
I have a Terraform script that creates a  AWS RDS, aurora mysql cluster

```<code>module "cluster" {
  source  = "terraform-aws-modules/rds-aurora/aws"

  name           = var.cluster_name
  master_username = var.master_username
  master_password = var.master_password
  create_random_password = false
  database_name = var.database_name
  engine         = var.engine
  engine_version = var.engine_version
  instance_class = var.instance_class_r5
  instances = {
    one = {}
    2 = {
      instance_class = var.instance_class_r5_2
    }
  }

  vpc_id  = var.vpc_id
  subnets = ["subnet-XXXX", "subnet-XXXX", "subnet-XXXX"]

  allowed_security_groups = ["sg-XXXXXXXXXXXXXX"]
  allowed_cidr_blocks     = ["10.20.0.0/20", "144.121.18.66/32"]

  storage_encrypted   = true
  apply_immediately   = true
  monitoring_interval = 10

  db_parameter_group_name         = aws_db_parameter_group.credential.id
  db_cluster_parameter_group_name = aws_rds_cluster_parameter_group.credential.id
  publicly_accessible = true

}

resource "aws_db_parameter_group" "credential" {
  name        = "${var.cluster_name}-aurora-db-57-parameter-group"
  family      = "aurora-mysql5.7"
  description = "${var.cluster_name}-aurora-db-57-parameter-group"
  tags        = var.tags_required
}

resource "aws_rds_cluster_parameter_group" "credential" {
  name        = "${var.cluster_name}-aurora-57-cluster-parameter-group"
  family      = "aurora-mysql5.7"
  description = "${var.cluster_name}-aurora-57-cluster-parameter-group"
  tags        = var.tags_required
}
</code>```

This creates a database
I am using springboot, and usually with a databse the entity will create the table

```<code>@Entity
@Table(name="credential")
public class CredentialEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long credentialId;
</code>```

In my yml file I have set

```<code>spring:
    hibernate:
      ddl-auto: update
</code>```

But it does not create the table. So is there a way to create the table as part of the terraform script.

答:
I wouldn't recommend doing this, but if you want Terraform to deploy database structures you can try with:

```<code>resource "null_resource" "db_setup" {
  depends_on = [module.db, aws_security_group.rds_main, aws_default_security_group.default]
  provisioner "local-exec" {
    command = "mysql --host=${module.cluster.cluster_endpoint} --port=${module.cluster.cluster_port} --user=${module.cluster.cluster_master_username} --password=${module.cluster.cluster_master_password} --database=${module.cluster.cluster_database_name} < ${file(${path.module}/init/db_structure.sql)}"
  }
}
</code>```

(This snippet is based on this answer where you have a lot more examples)

Just note: Terraform manages infrastructure. When AWS provider does its work you can have MySQL provider to pick up and deploy admin stuff like users, roles, grants, etc. But tables within databases belong to application. There are other tools more suited for managing database objects. See if you could plug Flyway or Liquibase into your pipeline.

Body:
I have a Terraform script that creates a  AWS RDS, aurora mysql cluster

module "cluster" {
  source  = "terraform-aws-modules/rds-aurora/aws"

  name           = var.cluster_name
  master_username = var.master_username
  master_password = var.master_password
  create_random_password = false
  database_name = var.database_name
  engine         = var.engine
  engine_version = var.engine_version
  instance_class = var.instance_class_r5
  instances = {
    one = {}
    2 = {
      instance_class = var.instance_class_r5_2
    }
  }

  vpc_id  = var.vpc_id
  subnets = ["subnet-XXXX", "subnet-XXXX", "subnet-XXXX"]

  allowed_security_groups = ["sg-XXXXXXXXXXXXXX"]
  allowed_cidr_blocks     = ["10.20.0.0/20", "144.121.18.66/32"]

  storage_encrypted   = true
  apply_immediately   = true
  monitoring_interval = 10

  db_parameter_group_name         = aws_db_parameter_group.credential.id
  db_cluster_parameter_group_name = aws_rds_cluster_parameter_group.credential.id
  publicly_accessible = true

}

resource "aws_db_parameter_group" "credential" {
  name        = "${var.cluster_name}-aurora-db-57-parameter-group"
  family      = "aurora-mysql5.7"
  description = "${var.cluster_name}-aurora-db-57-parameter-group"
  tags        = var.tags_required
}

resource "aws_rds_cluster_parameter_group" "credential" {
  name        = "${var.cluster_name}-aurora-57-cluster-parameter-group"
  family      = "aurora-mysql5.7"
  description = "${var.cluster_name}-aurora-57-cluster-parameter-group"
  tags        = var.tags_required
}

This creates a database
I am using springboot, and usually with a databse the entity will create the table

@Entity
@Table(name="credential")
public class CredentialEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long credentialId;

In my yml file I have set

spring:
    hibernate:
      ddl-auto: update

But it does not create the table. So is there a way to create the table as part of the terraform script.

Body:
I wouldn't recommend doing this, but if you want Terraform to deploy database structures you can try with:

resource "null_resource" "db_setup" {
  depends_on = [module.db, aws_security_group.rds_main, aws_default_security_group.default]
  provisioner "local-exec" {
    command = "mysql --host=${module.cluster.cluster_endpoint} --port=${module.cluster.cluster_port} --user=${module.cluster.cluster_master_username} --password=${module.cluster.cluster_master_password} --database=${module.cluster.cluster_database_name} < ${file(${path.module}/init/db_structure.sql)}"
  }
}

(This snippet is based on this answer where you have a lot more examples)

Just note: Terraform manages infrastructure. When AWS provider does its work you can have MySQL provider to pick up and deploy admin stuff like users, roles, grants, etc. But tables within databases belong to application. There are other tools more suited for managing database objects. See if you could plug Flyway or Liquibase into your pipeline.


问:
nodejs reachable from internet via react application
I have a react app running on https and a nodejs running localhost:3001. my nodejs app does not capture data from react application.
What have I missed?

server.js (Nodejs)

```<code>const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const cors = require('cors');
const app = express();
const Excel = require('exceljs');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(cors());

app.get('/', ()=>{
 console.log('welcome to test')
})
app.post('/api/xcl', (req, res) =>{

const workbook = new Excel.Workbook();
workbook.xlsx.readFile('test.xlsx')
.then(() =>{
const workSheet = workbook.getWorksheet('test');
workSheet.addRow([req.body.fNamn, req.body.eNamn, req.body.oNamn, req.body.ePost,
req.body.dVal, req.body.kNamn]);
workbook.xlsx.writeFile('test.xlsx');
})
.catch(error => {
console.log(error.message);
});

const PORT = process.env.PORT || 3001
app.listen(PORT, () => console.info(`server has started on ${PORT}`))
</code>```

app.js (Reactjs)

```<code> axios.post('http://localhost/:3001/api/xcl', data)
        .then(res =>{
            setSent(true)
            console.log(res.data)
        })
        .catch(() => {
            console.log(err=>console.log(err.response.data));
        })
</code>```

I have declared the proxy   "proxy": "http://localhost:3001/" in package.json

React app runs on an iis site https://test.me:443

答:
If you have set proxy, you don't need to write http://localhost:3001 in your http request, try</p>
```<code>axios.post('/api/xcl', data)
        .then(res =>{
            setSent(true)
            console.log(res.data)
        })
        .catch(() => {
            console.log(err=>console.log(err.response.data));
        })
</code>```

Body:
I have a react app running on https and a nodejs running localhost:3001. my nodejs app does not capture data from react application.
What have I missed?

server.js (Nodejs)

const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const cors = require('cors');
const app = express();
const Excel = require('exceljs');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(cors());

app.get('/', ()=>{
 console.log('welcome to test')
})
app.post('/api/xcl', (req, res) =>{

const workbook = new Excel.Workbook();
workbook.xlsx.readFile('test.xlsx')
.then(() =>{
const workSheet = workbook.getWorksheet('test');
workSheet.addRow([req.body.fNamn, req.body.eNamn, req.body.oNamn, req.body.ePost,
req.body.dVal, req.body.kNamn]);
workbook.xlsx.writeFile('test.xlsx');
})
.catch(error => {
console.log(error.message);
});

const PORT = process.env.PORT || 3001
app.listen(PORT, () => console.info(`server has started on ${PORT}`))

app.js (Reactjs)

 axios.post('http://localhost/:3001/api/xcl', data)
        .then(res =>{
            setSent(true)
            console.log(res.data)
        })
        .catch(() => {
            console.log(err=>console.log(err.response.data));
        })

I have declared the proxy   "proxy": "http://localhost:3001/" in package.json

React app runs on an iis site https://test.me:443

Body:
If you have set proxy, you don't need to write http://localhost:3001 in your http request, try

axios.post('/api/xcl', data)
        .then(res =>{
            setSent(true)
            console.log(res.data)
        })
        .catch(() => {
            console.log(err=>console.log(err.response.data));
        })


问:
JQUERY Sorting an Array of Objects
I have an array that is holding a number of  objects.

Array:

```<code> var activeMembers=[];
</code>```

The DIV objects in the above array look like as follows - each was added one at a time:

```<code> <div id="mary" class="chatmember 1011"></div>
 <div id="steven" class="chatmember 1051"></div>
 <div id="adam" class="chatmember 1701"></div>
 <div id="bob" class="chatmember 1099"></div>
 <div id="peter" class="chatmember 1123"></div>
</code>```

Is there a quick way to sort theses DIV objects in the array by the ID from A-Z?

thx

答:
You can use the tinysort plugin )(http://plugins.jquery.com/project/TinySort)

e.g.

```<code>$("#parentName > div").tsort("",{attr:"id"});
</code>```

Title: JQUERY Sorting an Array of Objects

Body:
I have an array that is holding a number of  objects.

Array:

 var activeMembers=[];

The DIV objects in the above array look like as follows - each was added one at a time:

Is there a quick way to sort theses DIV objects in the array by the ID from A-Z?

thx

Body:
You can use the tinysort plugin )(http://plugins.jquery.com/project/TinySort)

e.g.

$("#parentName > div").tsort("",{attr:"id"});