问:
React Native - [Unhandled promise rejection: Error: Signup Error]
I get this intentional error because I'm using the same email to register. It says I'm not handling the rejection; can someone explain why because I have a .catch() which should catch any errors that were thrown

Error code:

```<code>[Unhandled promise rejection: Error: Signup Error]
- node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
- node_modules\promise\setimmediate\core.js:123:25 in setImmediate$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:146:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:194:17 in _callImmediatesPass
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:458:30 in callImmediates
* [native code]:null in callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:407:6 in __callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:143:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:142:17 in __guard$argument_0
* [native code]:null in flushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
</code>```

from this fetch().then().catch() code:

```<code> fetch(
      "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[ API KEY ]",
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password, returnSecureToken: true }),
      }
    )
      .then((res) => {
        if (!res.ok) {
          throw new Error("Signup Error");
        } else {
          const resData = res.json();
          return resData;
        }
      })
      .then((resData) => {
        console.log({ resData });
        dispatch({ type: SIGNUP });
      })
      .catch((err) => {
        console.log({ errHere: err });
        throw err;
      });
</code>```

The try{}catch(){} code that does work:

```<code>try {
      const res = await fetch(
        "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[ API KEY ]",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ email, password, returnSecureToken: true }),
        }
      );

      if (!res.ok) {
        throw new Error("Signup Error");
      }

      const resData = await res.json();

      console.log({ resData });
    } catch (err) {
      throw err;
    }
</code>```

I've redone this code with try catch and it works but this puzzles me, so I need to know why it doesn't work with the .then().catch() handlers

The React code is this:

```<code>const signupHandler = useCallback(async () => {
    console.log(formState.inputValues.email, formState.inputValues.password);
    dispatch(
      signup(formState.inputValues.email, formState.inputValues.password)
    )
      .then(() => {
        console.log("OK!");
      })
      .catch((err) => {
        console.log({ errOutside: err });
      });
  }, [dispatch]);
</code>```

and as I said it works with the try catch method.

答:
I'm not 100% sure of this since i'm used to try catch, but it could be because you are not actually handling the promise rejection:

in your then

```<code>  .then((res) => {
            if (!res.ok) {
              throw new Error("Signup Error");
            } else {
              const resData = res.json();
              return resData;
            }
          }, (reject) => {
             // handle this
          })
</code>```

Body:
I get this intentional error because I'm using the same email to register. It says I'm not handling the rejection; can someone explain why because I have a .catch() which should catch any errors that were thrown

Error code:

[Unhandled promise rejection: Error: Signup Error]
- node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
- node_modules\promise\setimmediate\core.js:123:25 in setImmediate$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:146:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:194:17 in _callImmediatesPass
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:458:30 in callImmediates
* [native code]:null in callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:407:6 in __callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:143:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:142:17 in __guard$argument_0
* [native code]:null in flushedQueue
* [native code]:null in callFunctionReturnFlushedQueue

from this fetch().then().catch() code:

 fetch(
      "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[ API KEY ]",
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password, returnSecureToken: true }),
      }
    )
      .then((res) => {
        if (!res.ok) {
          throw new Error("Signup Error");
        } else {
          const resData = res.json();
          return resData;
        }
      })
      .then((resData) => {
        console.log({ resData });
        dispatch({ type: SIGNUP });
      })
      .catch((err) => {
        console.log({ errHere: err });
        throw err;
      });

The try{}catch(){} code that does work:

try {
      const res = await fetch(
        "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[ API KEY ]",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ email, password, returnSecureToken: true }),
        }
      );

      if (!res.ok) {
        throw new Error("Signup Error");
      }

      const resData = await res.json();

      console.log({ resData });
    } catch (err) {
      throw err;
    }

I've redone this code with try catch and it works but this puzzles me, so I need to know why it doesn't work with the .then().catch() handlers

The React code is this:

const signupHandler = useCallback(async () => {
    console.log(formState.inputValues.email, formState.inputValues.password);
    dispatch(
      signup(formState.inputValues.email, formState.inputValues.password)
    )
      .then(() => {
        console.log("OK!");
      })
      .catch((err) => {
        console.log({ errOutside: err });
      });
  }, [dispatch]);

and as I said it works with the try catch method.

Body:
I'm not 100% sure of this since i'm used to try catch, but it could be because you are not actually handling the promise rejection:

in your then

  .then((res) => {
            if (!res.ok) {
              throw new Error("Signup Error");
            } else {
              const resData = res.json();
              return resData;
            }
          }, (reject) => {
             // handle this
          })


来源: stackexchange

问:
Redux Selector or Effect
Please help me to make the decision, regarding which technique to use.

I have a big list (up to million rows) that is kept in redux state.
Once user types in filter criterion, I want to apply filter and show filtered data (actually piece of it with react virtualized).

I do understand that ideally this is a use case for simple selector (or memoized reselect).

The problem that I see: filtering itself may take 2-3 seconds, thus, I have to use debounce. For debounce  i have to use middleware, because debouncing is asynchronous and impure.

Can effect (epic) take data from state and act as asynchronous selector? Or maybe there are some patterns for implementing debounce in selector?

Appreciate any advices.

答:
I have a big list (up to million rows) that is kept in redux state.

Really? You're doing blunder mistake. This will consume huge memory. And some browser may not respond them correctly.

So, I would suggest you to apply filtering from database results. On each filter being applied, the application will need to get the results from the database say upto 10, 20, 50, or 100.

With this sense, you can keep using redux or use memoized effect depending on your application logic/complexity. Both will work fine without worrying about debounce method.

ContentLicense: CC BY-SA 4.0

Title: Redux Selector or Effect


问:
Assembling a CUDA Project
I have been scanning the site for questions regarding large CUDA projects and I have found some good replies, anyway I have some doubts yet.

My program, for now(it is still half-way from being complete), outputs some arrays, that are then input for Thrust library functions.

So my main doubt is:

1-Given that I am using CUDA C, I have thrust functions declared as extern "C". I was unsure of the correct way to declare those functions in the header files, and after some googling I found the following code, which I wanted to be sure is right:

```<code>extern "C" {
void compact(float*intxc,float*intyc,float*intzc);
void sort(float*intxc,float*intyc,float*intzc);
}
</code>```

2- I have seen some posts here in the forum, that used "Main.cpp" as the main file, is it wrong to use a "Main.cu" file or is it indifferent?

Edit: After some thought(and advice), I really think the older questions were a bit dull.

Thanks in advance and thanks talonmies for the advice

答:
There's no need to declare your functions extern "C" in the most recent (post 2.3) versions of CUDA.  Besides, those functions are just C functions, they have nothing to do with CUDA.

You can have your main function in a .cu file or a .cpp file.  If you do the former, it must be compiled by nvcc.  If you do the latter, it should be compiled by your C++ compiler.  The file need not be named "Main".

ContentLicense: CC BY-SA 3.0

Title: Assembling a CUDA Project

Body:
I have been scanning the site for questions regarding large CUDA projects and I have found some good replies, anyway I have some doubts yet.

My program, for now(it is still half-way from being complete), outputs some arrays, that are then input for Thrust library functions.

So my main doubt is:

1-Given that I am using CUDA C, I have thrust functions declared as extern "C". I was unsure of the correct way to declare those functions in the header files, and after some googling I found the following code, which I wanted to be sure is right:

extern "C" {
void compact(float*intxc,float*intyc,float*intzc);
void sort(float*intxc,float*intyc,float*intzc);
}

2- I have seen some posts here in the forum, that used "Main.cpp" as the main file, is it wrong to use a "Main.cu" file or is it indifferent?

Edit: After some thought(and advice), I really think the older questions were a bit dull.

Thanks in advance and thanks talonmies for the advice


问:
send value in text input react native
native,

here I take the value from the first page.

```<code>constructor(){
        super();
        this.state = {
            selectPickup:'',
        }
    }

ongNavigationDetail = ()=>{
        let params = {
            pickup : this.state.selectPickup
        }
        console.log(params)
        // send to third page
    }

  render() {
    const  userLocation  = this.props.navigation.getParam('pickup'); // get value from first page
    return (
         <CardItem header>
         {/* <Text style={{ fontSize: 12}}>{userLocation}</Text> */}
         <Input  onChangeText={userLocation => this.setState({selectPickup:userLocation})} value={userLocation}/>
         </CardItem>

    <Button block info style={styles.MainBtn} onPress={this.ongNavigationDetail}>
      <Text style={styles.btnText}>Next</Text>
    </Button>
    )}
</code>```

on the second page, here I take the value userLocation to send a third trip but when I console the value is undifined, where is the explosion?

答:
I think currently, your navigation object doesn't have access to getParams function. Maybe you can access it simply like this.

```<code> this.pros.navigation.route.params
</code>```

Title: send value in text input react native

Body:
native,

here I take the value from the first page.

constructor(){
        super();
        this.state = {
            selectPickup:'',
        }
    }

ongNavigationDetail = ()=>{
        let params = {
            pickup : this.state.selectPickup
        }
        console.log(params)
        // send to third page
    }

  render() {
    const  userLocation  = this.props.navigation.getParam('pickup'); // get value from first page
    return (
         <CardItem header>
         {/* <Text style={{ fontSize: 12}}>{userLocation}</Text> */}
         <Input  onChangeText={userLocation => this.setState({selectPickup:userLocation})} value={userLocation}/>
         </CardItem>

    <Button block info style={styles.MainBtn} onPress={this.ongNavigationDetail}>
      <Text style={styles.btnText}>Next</Text>
    </Button>
    )}

on the second page, here I take the value userLocation to send a third trip but when I console the value is undifined, where is the explosion?

Body:
I think currently, your navigation object doesn't have access to getParams function. Maybe you can access it simply like this.

 this.pros.navigation.route.params


问:
Amazon MWS - request signature calculated does not match the signature provided
Getting the following error message from https://mws.amazonservices.com/:

```<code><Type>Sender</Type>
<Code>SignatureDoesNotMatch</Code>
−
<Message>
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
</Message>
</code>```

Here is the VB.net code I am using to calculate the request.  I have removed the SecretKey and AWSAccessKeyId for security reasons.

```<code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim sURL As String = "https://mws.amazonservices.com/"

        Dim sRequest As String = ""
        sRequest &= "Acknowledged=" & Server.UrlEncode("false")
        sRequest &= "&Action=" & Server.UrlEncode("GetReportList")
        sRequest &= "&AWSAccessKeyId=" & Server.UrlEncode("REMOVED-FOR-SECURITY")
        sRequest &= "&Marketplace=" & Server.UrlEncode("REMOVED-FOR-SECURITY")
        sRequest &= "&Merchant=" & Server.UrlEncode("REMOVED-FOR-SECURITY")
        sRequest &= "&SignatureMethod=" & Server.UrlEncode("HmacSHA256")
        sRequest &= "&SignatureVersion=" & Server.UrlEncode("2")
        sRequest &= "&Timestamp=" & Server.UrlEncode(DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssCST"))
        sRequest &= "&Version=" & Server.UrlEncode("2009-01-01")

        Dim StringToSign As String = "GET\n" & "mws.amazonservices.com\n" & "/\n" & sRequest
        sRequest &= "&Signature=" & Server.UrlEncode(HashString(StringToSign))

        Response.Write("<a href=""" & sURL & "?" & sRequest & """>Click here</a>")

    End Sub

    Public Shared Function HashString(ByVal StringToHash As String) As String
        Dim myEncoder As New System.Text.UTF8Encoding
        Dim Key() As Byte = myEncoder.GetBytes("REMOVED-FOR-SECURITY")
        Dim XML() As Byte = myEncoder.GetBytes(StringToHash)
        Dim myHMACSHA256 As New System.Security.Cryptography.HMACSHA256(Key)
        Dim HashCode As Byte() = myHMACSHA256.ComputeHash(XML)
        Return Convert.ToBase64String(HashCode)
    End Function
</code>```

答: 1 more answer to the stack: trying to stream data & setting -1 as content length also shows this error</p>

ContentLicense: CC BY-SA 2.5

Body:
Getting the following error message from https://mws.amazonservices.com/:

<Type>Sender</Type>
SignatureDoesNotMatch
−
<Message>
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
</Message>

Here is the VB.net code I am using to calculate the request.  I have removed the SecretKey and AWSAccessKeyId for security reasons.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim sURL As String = "https://mws.amazonservices.com/"

        Dim sRequest As String = ""
        sRequest &= "Acknowledged=" & Server.UrlEncode("false")
        sRequest &= "&Action=" & Server.UrlEncode("GetReportList")
        sRequest &= "&AWSAccessKeyId=" & Server.UrlEncode("REMOVED-FOR-SECURITY")
        sRequest &= "&Marketplace=" & Server.UrlEncode("REMOVED-FOR-SECURITY")
        sRequest &= "&Merchant=" & Server.UrlEncode("REMOVED-FOR-SECURITY")
        sRequest &= "&SignatureMethod=" & Server.UrlEncode("HmacSHA256")
        sRequest &= "&SignatureVersion=" & Server.UrlEncode("2")
        sRequest &= "&Timestamp=" & Server.UrlEncode(DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssCST"))
        sRequest &= "&Version=" & Server.UrlEncode("2009-01-01")

        Dim StringToSign As String = "GET\n" & "mws.amazonservices.com\n" & "/\n" & sRequest
        sRequest &= "&Signature=" & Server.UrlEncode(HashString(StringToSign))

        Response.Write("Click here")

    End Sub

    Public Shared Function HashString(ByVal StringToHash As String) As String
        Dim myEncoder As New System.Text.UTF8Encoding
        Dim Key() As Byte = myEncoder.GetBytes("REMOVED-FOR-SECURITY")
        Dim XML() As Byte = myEncoder.GetBytes(StringToHash)
        Dim myHMACSHA256 As New System.Security.Cryptography.HMACSHA256(Key)
        Dim HashCode As Byte() = myHMACSHA256.ComputeHash(XML)
        Return Convert.ToBase64String(HashCode)
    End Function


问:
When extending a class and using properties of original class what do you put inside of super()
This is how I thought the code should work but it doesn't pass.

```<code>class Rectangle {
  constructor(w, h) {
    this.w = w;
    this.h = h;
  }
}

Rectangle.prototype.area = function() {
    return(this.w * this.h)
}

class Square extends Rectangle{
    constructor(w, h) {
        super(w, h)
        this.w = w;
        this.h = h;
     }
}
</code>```

I thought that when using super to receive parameters from original class you need to put them in the new constructor?
But when I change class Square like this it passes.  I don't understand?

```<code>class Square extends Rectangle{
    constructor(s) {
        super(s)
        this.w = s;
        this.h = s;
     }
</code>```

答:
You need to pass the arguments that the parent constructor expects, in your case you will need to pass a height and a width. How to get these values is up to you. For a square, it makes sense to pass the same value for both parameters. You do no need to assign .w and .h yourself in the Square constructor, the Rectangle constructor already creates these properties. So it just be just

```<code>class Square extends Rectangle {
    constructor(s) {
        super(s, s)
    }
}
</code>```

Body:
This is how I thought the code should work but it doesn't pass.

class Rectangle {
  constructor(w, h) {
    this.w = w;
    this.h = h;
  }
}

Rectangle.prototype.area = function() {
    return(this.w * this.h)
}

class Square extends Rectangle{
    constructor(w, h) {
        super(w, h)
        this.w = w;
        this.h = h;
     }
}

I thought that when using super to receive parameters from original class you need to put them in the new constructor?
But when I change class Square like this it passes.  I don't understand?

class Square extends Rectangle{
    constructor(s) {
        super(s)
        this.w = s;
        this.h = s;
     }

Body:
You need to pass the arguments that the parent constructor expects, in your case you will need to pass a height and a width. How to get these values is up to you. For a square, it makes sense to pass the same value for both parameters. You do no need to assign .w and .h yourself in the Square constructor, the Rectangle constructor already creates these properties. So it just be just

class Square extends Rectangle {
    constructor(s) {
        super(s, s)
    }
}


问:
Python unittest only running the first test and not the others
I am new to unittesting and trying to write tests for my code. In my test file, I have defined a test class and have two small tests for my file. However, when I run the file, only the first test runs.

Furthermore, the code I am importing the tests from, in separate functions than the one I am testing, is generating some plots, and those plots are being generated before the test is ran now.

Is there a way I could only run the tests, without having the file I'm importing the functions to be tested from run?

This is my code for the test class :

```<code>import unittest
from Expense import set_day_of_the_week
from Expense import add_two_expenses

class Heart_Rate_Model_Tests(unittest.TestCase):

    def test_assign_initial_values(self):
        day_returned = set_day_of_the_week('Monday')
        self.assertEqual(day_return, 'Monday')

    def test_add_two_expense(self):
        food_expense = 12
        drink_expense = 5
        expense_sum = add_two_expense(food_expense, drink_expense)
        self.assertEqual(17, expense_sum)

if __name__ == '__main__':
    unittest.main()

</code>```

The output obtained from the tests is :

```<code>Ran 1 test in 0.001s
OK

</code>```

I have made changes to the first test to make it fail, and it does fail, therefore I'm sure it's the only test that is being ran, but changes made to it are seen

答: Writing a new test file has fixed the issue. I'm still not sure what it was, I'm assuming it was a configuration error on my side, leaving this here if somebody in the future has a similar issue</p>

Body:
I am new to unittesting and trying to write tests for my code. In my test file, I have defined a test class and have two small tests for my file. However, when I run the file, only the first test runs.

Furthermore, the code I am importing the tests from, in separate functions than the one I am testing, is generating some plots, and those plots are being generated before the test is ran now.

Is there a way I could only run the tests, without having the file I'm importing the functions to be tested from run?

This is my code for the test class :

import unittest
from Expense import set_day_of_the_week
from Expense import add_two_expenses

class Heart_Rate_Model_Tests(unittest.TestCase):

    def test_assign_initial_values(self):
        day_returned = set_day_of_the_week('Monday')
        self.assertEqual(day_return, 'Monday')

    def test_add_two_expense(self):
        food_expense = 12
        drink_expense = 5
        expense_sum = add_two_expense(food_expense, drink_expense)
        self.assertEqual(17, expense_sum)

if __name__ == '__main__':
    unittest.main()

The output obtained from the tests is :

Ran 1 test in 0.001s
OK

I have made changes to the first test to make it fail, and it does fail, therefore I'm sure it's the only test that is being ran, but changes made to it are seen


问:
jquery: using OR with .click()?
I need help trying to figure out how to use .click() function for two different attributes.

```<code>$('#prev').click(function() {}
</code>```

and

```<code>$('#image').click(function() {}
</code>```

So how would I do an OR statement if user clicks on #prev and #image without writing two identical scripts?

Thanks!

答:
You could:

```<code>$('#prev, #image').click(function() {});
</code>```

or

```<code>function mine() {}
$('#prev').click(function() { mine(); });
$('#image').click(function() { mine(); });
</code>```

Title: jquery: using OR with .click()?

Body:
I need help trying to figure out how to use .click() function for two different attributes.

$('#prev').click(function() {}

and

$('#image').click(function() {}

So how would I do an OR statement if user clicks on #prev and #image without writing two identical scripts?

Thanks!

Body:
You could:

$('#prev, #image').click(function() {});

or

function mine() {}
$('#prev').click(function() { mine(); });
$('#image').click(function() { mine(); });


问:
How to get unique values from table() function in R
I have a data frame which 31 columns. In column of Year (named "Anos"), I have rows which years are repeated and when I use table(df$Anos), I get frequency of years. I need only years with 12 observations (12 months).

Example:

freq_years <- table(df$Anos)
freq_years
Result:
2009 2010 2011 2012 2013 2014 2015 2017 2018 2019 2020
  10   12   12    3   11    6    8   12   12   12    5

How to get automatically in a new variable only years with freq = 12? (maybe like 2010,2011,2018,2019)

答:
Here is a tidyverse version. Depending on your use with the other 30 columns in your data frame, keeping the data as df2 might be useful.

```<code>install.packages("dplyr")
install.packages("magrittr")
library("magrittr")
library("dplyr")
#create example dataset
df <- data.frame("Anos" = c(rep(2009,10),
                            rep(2010,12),
                            rep(2011,12),
                            rep(2012,3),
                            rep(2013,11),
                            rep(2014,6),
                            rep(2015,8),
                            rep(2016,12),
                            rep(2017,12)))

head(df)

# count number of years by row and filter to those with only 12
df2 <- df %>% group_by(Anos) %>% count() %>% filter(n == 12)

head(df2)

# create variable with list of years that have exactly 12 rows
variable <- df2$Anos

variable
</code>```

Body:
Here is a tidyverse version. Depending on your use with the other 30 columns in your data frame, keeping the data as df2 might be useful.

install.packages("dplyr")
install.packages("magrittr")
library("magrittr")
library("dplyr")
#create example dataset
df <- data.frame("Anos" = c(rep(2009,10),
                            rep(2010,12),
                            rep(2011,12),
                            rep(2012,3),
                            rep(2013,11),
                            rep(2014,6),
                            rep(2015,8),
                            rep(2016,12),
                            rep(2017,12)))

head(df)

# count number of years by row and filter to those with only 12
df2 <- df %>% group_by(Anos) %>% count() %>% filter(n == 12)

head(df2)

# create variable with list of years that have exactly 12 rows
variable <- df2$Anos

variable


问:
Need to add Spaces at certain Indexes
So this is data i have,

```<code>s = [2, 8, 15, 23, 28, 43, 47, 55, 63, 72, 79, 82, 89, 97, 102, 112, 120, 125, 131, 141, 148, 156, 163, 167, 180, 188, 193, 210, 222, 227]
</code>```

These are the index position where i need to add spaces,

```<code>d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'
</code>```

My overall goal is split the string in such a way that the Shotforms and the Longforms are seperated,

For EX: This is the output I'm trying to get

CC Carbon Copy CAI Computer Aided Instruction
```

<p>and so on.....</p>

<p>I have calculated the indexes by doing this,</p>

```s = []
for i in range(0, len(d)):
    if d[i].isupper() and d[i+1].islower() and d[i+2].islower():
        s.append(i)
```

<p>When I individually try and add the space using the index, I get an output,</p>

```d[0:s[0]] + ' ' + d[s[0]:]
```

<p>I get the following, which is correct</p>

<pre class="lang-none prettyprint-override"><code>'CC CarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTube
</code>```

But, when I try and iterate over the indexes, i get List out of Range

```<code>temp = []
for i in s:
    print(i)
    temp.append(d[0:s[i]] + ' ' + d[s[i]:])

Traceback (most recent call last):
  File "<input>", line 4, in <module>
IndexError: list index out of range
</code>```

答:
You should first build a list with all the words, based on index. Then, the join function will do the job.

```<code>s = [2, 8, 15, 23, 28, 43, 47, 55, 63, 72, 79, 82, 89, 97, 102, 112, 120, 125, 131, 141, 148, 156, 163, 167, 180, 188, 193, 210, 222, 227]
d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'

last_elem = 0
lst = []
for el in s:
    lst.append(d[last_elem:el])
    last_elem = el
' '.join(lst)
</code>```

output:
'CC Carbon CopyCAI Computer Aided InstructionCDMA Code Division Multiple AccessCRT Cathode Ray TubeCAD Computer Aided DesignCADD Computer Aided Design DraftingCD Compact DiskCDRW Compact Disk RewritableCAM Computer Aided ManufacturingCROM Computerized Range'

Title: Need to add Spaces at certain Indexes

Body:
So this is data i have,

s = [2, 8, 15, 23, 28, 43, 47, 55, 63, 72, 79, 82, 89, 97, 102, 112, 120, 125, 131, 141, 148, 156, 163, 167, 180, 188, 193, 210, 222, 227]

These are the index position where i need to add spaces,

d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'

My overall goal is split the string in such a way that the Shotforms and the Longforms are seperated,

For EX: This is the output I'm trying to get

CC Carbon Copy CAI Computer Aided Instruction

and so on.....

I have calculated the indexes by doing this,

s = []
for i in range(0, len(d)):
    if d[i].isupper() and d[i+1].islower() and d[i+2].islower():
        s.append(i)

When I individually try and add the space using the index, I get an output,

d[0:s[0]] + ' ' + d[s[0]:]

I get the following, which is correct

'CC CarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTube

But, when I try and iterate over the indexes, i get List out of Range

temp = []
for i in s:
    print(i)
    temp.append(d[0:s[i]] + ' ' + d[s[i]:])

Traceback (most recent call last):
  File "<input>", line 4, in <module>
IndexError: list index out of range

Body:
You should first build a list with all the words, based on index. Then, the join function will do the job.

s = [2, 8, 15, 23, 28, 43, 47, 55, 63, 72, 79, 82, 89, 97, 102, 112, 120, 125, 131, 141, 148, 156, 163, 167, 180, 188, 193, 210, 222, 227]
d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'

last_elem = 0
lst = []
for el in s:
    lst.append(d[last_elem:el])
    last_elem = el
' '.join(lst)

output:
'CC Carbon CopyCAI Computer Aided InstructionCDMA Code Division Multiple AccessCRT Cathode Ray TubeCAD Computer Aided DesignCADD Computer Aided Design DraftingCD Compact DiskCDRW Compact Disk RewritableCAM Computer Aided ManufacturingCROM Computerized Range'


问:
Default UNIX permissions of Mongodb files in the hard drive
I noticed that the files in the data/ directory, hosting the databases and collections, are the r permission for others.

So basically, anyone can read the data! Isn't it strange, or is it something I'm missing?

I found no solution to change this behavior in the mondodb configuration (ubuntu 18.04). When you search mongodb file permissions, you will find threads about user permissions inside the database.

Thank you!

答:
When you launch mongod you need to specify a path to the data directory, and this directory must already exist.

You can set the permissions on this directory to deny world-read access by running:

```<code>chmod o-rwx /path/to/data/dir
</code>```

Normally this would be done prior to the first start of mongod.

Once this is done, none of the files in the data directory will be world-readable regardless of their individual permissions.

MongoDB does not need  to have a provision to do this because it never creates the data directory.

A different way of accomplishing similar end result is to use umask, but changing permissions on data directory generally would be more reliable.

Body:
When you launch mongod you need to specify a path to the data directory, and this directory must already exist.

You can set the permissions on this directory to deny world-read access by running:

chmod o-rwx /path/to/data/dir

Normally this would be done prior to the first start of mongod.

Once this is done, none of the files in the data directory will be world-readable regardless of their individual permissions.

MongoDB does not need  to have a provision to do this because it never creates the data directory.

A different way of accomplishing similar end result is to use umask, but changing permissions on data directory generally would be more reliable.


问:
How to use Dependency Injection on a application class in .Net Core for an Entity Framework Pooled Context to achieve multi-tenant implementation?
I have implemented an application which makes use of .Net Core 3.1 and Entity Framework.

The application uses entity framework dbcontext pooling, utilizing the Pomelo mysql ef library.

```<code>services.AddDbContextPool<myDbContext>(
            options => options
                .UseMySql(Configuration.GetConnectionString("DefaultConnection"),
                mysqlOptions =>
                {
                    mysqlOptions.MaxBatchSize(MySqlConfig.EfBatchSize);
                    mysqlOptions.EnableRetryOnFailure();
                    if (MySqlConfig.EfRetryOnFailure > 0)
                    {
                        mysqlOptions.EnableRetryOnFailure(MySqlConfig.EfRetryOnFailure, TimeSpan.FromSeconds(5), null);
                    }
                }
        ).UseLoggerFactory(consoleLoggerFactory));
</code>```

What is important to note is the use of the AddDbContextPool
Please see here: https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.entityframeworkservicecollectionextensions.adddbcontextpool?view=efcore-3.1

When using Context Pooling, your application is required to have a single constructor with DbContextOptions.  ie: I cannot inject another object (in my case, I need a application service class for listing allowed tenants, and other claims related logic...) into this class, otherwise pooling cannot be used.

```<code>public myDbContext(DbContextOptions<myDbContext> options)
            : base(options)
        {
        }
</code>```

Another caveat is that I utilize the HttpContextAccessor to access the claims on the User which is authenticated, which include the Tenants allowed to be accessed by that user which of course is accessed via Dependency Injection as well.
The Authentication and Claims are retrieved via openid ultimately retrieving claims as Active Directory Groups, so I do not and would not have this info in the DB either as it originates from Active Directory...

The guts of this question is really, how can i access the HttpContext within my DbContext in order to implement a global filter for multi-tenant support in my application, and still use the DB Context Pooling.

I can achieve this by removing pooling, and make use of DI as normal via the constructor, but that is not what i'm after.  I need to keep pooling, and implement the multi-tenant feature.

答:
First, if your tenants are in different databases, DbContext pooling simply won't work. After a DbContext has been opened, it's connected to a single database.  It's a minor performance feature, so it's not a great loss.

If you're setting query filters, you can probably make it work by simply not directly injecting a DbContext into your controllers, instead injecting a pre-configured bundle of services.  And this also lets you centralize the code to rreconfigure the DbContext for the current tenant.  EG:

```<code>public class ServiceContext
{
    MyDbContext dbContext;
    HttpContext httpContext;
    IConfiguration config;
    public ServiceContext(MyDbContext dbContext, IHttpContextAccessor httpContextAccessor, IConfiguration config)
    {
        this.dbContext = dbContext;
        this.httpContext = httpContextAccessor.HttpContext;
        this.config = config;
        //use the httpContext to reconfigure the DbContext for single-tenant access
    }

    public HttpContext HttpContext { get => httpContext; set => throw new NotImplementedException(); }
    public MyDbContext DbContext { get => dbContext; }
    public IConfiguration Configuration { get => config; }

}
</code>```

Body:
I have implemented an application which makes use of .Net Core 3.1 and Entity Framework.

The application uses entity framework dbcontext pooling, utilizing the Pomelo mysql ef library.

services.AddDbContextPool<myDbContext>(
            options => options
                .UseMySql(Configuration.GetConnectionString("DefaultConnection"),
                mysqlOptions =>
                {
                    mysqlOptions.MaxBatchSize(MySqlConfig.EfBatchSize);
                    mysqlOptions.EnableRetryOnFailure();
                    if (MySqlConfig.EfRetryOnFailure > 0)
                    {
                        mysqlOptions.EnableRetryOnFailure(MySqlConfig.EfRetryOnFailure, TimeSpan.FromSeconds(5), null);
                    }
                }
        ).UseLoggerFactory(consoleLoggerFactory));

What is important to note is the use of the AddDbContextPool
Please see here: https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.entityframeworkservicecollectionextensions.adddbcontextpool?view=efcore-3.1

When using Context Pooling, your application is required to have a single constructor with DbContextOptions.  ie: I cannot inject another object (in my case, I need a application service class for listing allowed tenants, and other claims related logic...) into this class, otherwise pooling cannot be used.

public myDbContext(DbContextOptions<myDbContext> options)
            : base(options)
        {
        }

Another caveat is that I utilize the HttpContextAccessor to access the claims on the User which is authenticated, which include the Tenants allowed to be accessed by that user which of course is accessed via Dependency Injection as well.
The Authentication and Claims are retrieved via openid ultimately retrieving claims as Active Directory Groups, so I do not and would not have this info in the DB either as it originates from Active Directory...

The guts of this question is really, how can i access the HttpContext within my DbContext in order to implement a global filter for multi-tenant support in my application, and still use the DB Context Pooling.

I can achieve this by removing pooling, and make use of DI as normal via the constructor, but that is not what i'm after.  I need to keep pooling, and implement the multi-tenant feature.

Body:
First, if your tenants are in different databases, DbContext pooling simply won't work. After a DbContext has been opened, it's connected to a single database.  It's a minor performance feature, so it's not a great loss.

If you're setting query filters, you can probably make it work by simply not directly injecting a DbContext into your controllers, instead injecting a pre-configured bundle of services.  And this also lets you centralize the code to rreconfigure the DbContext for the current tenant.  EG:

public class ServiceContext
{
    MyDbContext dbContext;
    HttpContext httpContext;
    IConfiguration config;
    public ServiceContext(MyDbContext dbContext, IHttpContextAccessor httpContextAccessor, IConfiguration config)
    {
        this.dbContext = dbContext;
        this.httpContext = httpContextAccessor.HttpContext;
        this.config = config;
        //use the httpContext to reconfigure the DbContext for single-tenant access
    }

    public HttpContext HttpContext { get => httpContext; set => throw new NotImplementedException(); }
    public MyDbContext DbContext { get => dbContext; }
    public IConfiguration Configuration { get => config; }

}


问:
Create a schedule in Django
I’m working on Django project “management system for clinic” and I have no idea how to create a schedule for doctors.

For example administrator makes an appointment for patient. I want him to see a schedule of doctor and which time is placed or free.

As I understand I should create model “Time” and connect it with a doctor, but I don’t really know what should I do after this. Thanks for your help!

答: Create a function for the scheduling in your views.py file</p>

Title: Create a schedule in Django


问:
Web request handler in .net core not found?
Basically I migrate from .framework to .core then I faced one error, Web request handler is not found. I searched alternate methods for .netcore here.

Is there any other method of registering web request handler?

```<code>error

Severity    Code    Description Project File    Line    Suppression State
Error   CS0246  The type or namespace name 'WebRequestHandler' could not be found
(are you missing a using directive or an assembly reference?)
</code>```

```<code>public HttpClient ConfigureHttpClient(Configuration.Configuration config)
{
    WebRequestHandler mtlsHandler = new WebRequestHandler
    {
        UseProxy = true,
        UseCookies = false,
        CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore),
        AuthenticationLevel = AuthenticationLevel.MutualAuthRequired,
        AllowAutoRedirect = false
    };
}
</code>```

答:
In .netcore an equivalent would be HttpClientHandler, described here. For some of the reasons mentioned in the post you have referenced already, HttpClientHandler exposes less options than WebRequestHandler.

Below is the code that configures HttpClient in a manner similar to your example, using HttpClientHandler:

var mtlsHandler = new HttpClientHandler {
   UseProxy = true,
   UseCookies = false,
   AllowAutoRedirect = false
   // CachePolicy = ... not supported and set to HttpRequestLevel.BypassCache equivalent, see https://github.com/dotnet/runtime/issues/21799
   // AuthenticationLevel = ... need to implement it yourself by deriving from HttpClientHandler, see https://stackoverflow.com/questions/43272530/whats-the-alternative-to-webrequesthandler-in-net-core
};

var httpClient = new HttpClient(mtlsHandler);
```

Unfortunately there are 2 unresolved aspects remaining, both which require to do your own custom implementation on top of HttpClientHandler:

No support for CachePolicy other than BypassCache equivalent, discussed here.

No support for AuthenticationLevel, discussed here.

Body:
Basically I migrate from .framework to .core then I faced one error, Web request handler is not found. I searched alternate methods for .netcore here.

Is there any other method of registering web request handler?

error

Severity    Code    Description Project File    Line    Suppression State
Error   CS0246  The type or namespace name 'WebRequestHandler' could not be found
(are you missing a using directive or an assembly reference?)

public HttpClient ConfigureHttpClient(Configuration.Configuration config)
{
    WebRequestHandler mtlsHandler = new WebRequestHandler
    {
        UseProxy = true,
        UseCookies = false,
        CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore),
        AuthenticationLevel = AuthenticationLevel.MutualAuthRequired,
        AllowAutoRedirect = false
    };
}

Body:
In .netcore an equivalent would be HttpClientHandler, described here. For some of the reasons mentioned in the post you have referenced already, HttpClientHandler exposes less options than WebRequestHandler.

Below is the code that configures HttpClient in a manner similar to your example, using HttpClientHandler:

var mtlsHandler = new HttpClientHandler {
   UseProxy = true,
   UseCookies = false,
   AllowAutoRedirect = false
   // CachePolicy = ... not supported and set to HttpRequestLevel.BypassCache equivalent, see https://github.com/dotnet/runtime/issues/21799
   // AuthenticationLevel = ... need to implement it yourself by deriving from HttpClientHandler, see https://stackoverflow.com/questions/43272530/whats-the-alternative-to-webrequesthandler-in-net-core
};

var httpClient = new HttpClient(mtlsHandler);

Unfortunately there are 2 unresolved aspects remaining, both which require to do your own custom implementation on top of HttpClientHandler:

No support for CachePolicy other than BypassCache equivalent, discussed here.

No support for AuthenticationLevel, discussed here.


问:
Getting error request for member 'length' in 'rw_ssid', which is of non-class type 'char*'
I have a public function save that accepts rw_ssid and rw_pswd char type variable in the file configuration.cpp

```<code>namespace Eeprom
{

void configuration::initialize(){
    EEPROM.begin(512);
}

void configuration::save(char* rw_ssid, char* rw_pswd) {
    for (int i = 0; i < 128; ++i) {
      EEPROM.write(i, 0);
      delay(10);
    }
    for (int i = 0; i < rw_ssid.length(); ++i) {
      EEPROM.write(i, rw_ssid[i]);
    }
    for (int i = 0; i < rw_pswd.length(); ++i) {
      EEPROM.write(32 + i, rw_pswd[i]);
    }

    EEPROM.commit();
    Serial.println("Written to EEPROM!");
    Serial.print("SSID: ");
    Serial.println(rw_ssid);
    Serial.print("PASS: ");
    Serial.println(rw_pswd);
    Funcs::connection::connectWifi(rw_ssid, rw_pswd);
    Serial.print("IP connection: ");
    Serial.println(WiFi.localIP());
  }

void configuration::save(char* rw_ssid, char* rw_pswd) {
    for (int i = 0; i < 128; ++i) {
      EEPROM.write(i, 0);
      delay(10);
    }
    for (int i = 0; i < rw_ssid.length(); ++i) {
      EEPROM.write(i, rw_ssid[i]);
    }
    for (int i = 0; i < rw_pswd.length(); ++i) {
      EEPROM.write(32 + i, rw_pswd[i]);
    }

    EEPROM.commit();
    Serial.println("Written to EEPROM!");
    Serial.print("SSID: ");
    Serial.println(rw_ssid);
    Serial.print("PASS: ");
    Serial.println(rw_pswd);
    Funcs::connection::connectWifi(rw_ssid, rw_pswd);
    Serial.print("IP connection: ");
    Serial.println(WiFi.localIP());
  }
}
</code>```

and then I have its header file

configuration.h

```<code>namespace Eeprom
{
  class configuration
  {
    public:
      static void initialize();
      static char* read();
      static void save(char* recvd_ssid, char* recvd_pass);
  };
}
</code>```

On compile I am getting this error:

```<code>sketch/configuration.cpp: In static member function 'static void Eeprom::configuration::save(char*, char*)':
configuration.cpp:19: error: request for member 'length' in 'rw_ssid', which is of non-class type 'char*'
     for (int i = 0; i < rw_ssid.length(); ++i) {
                                 ^
configuration.cpp:22: error: request for member 'length' in 'rw_pswd', which is of non-class type 'char*'
     for (int i = 0; i < rw_pswd.length(); ++i) {
                                 ^
configuration.cpp:34: error: 'WiFi' was not declared in this scope
     Serial.println(WiFi.localIP());
                    ^
sketch/configuration.cpp: In static member function 'static char* Eeprom::configuration::read()':
configuration.cpp:41: error: expected identifier before numeric constant
     char* read_ssid_pswd = [2];
                             ^
sketch/configuration.cpp: In lambda function:
configuration.cpp:41: error: expected '{' before ';' token
     char* read_ssid_pswd = [2];
                               ^
sketch/configuration.cpp: In static member function 'static char* Eeprom::configuration::read()':
configuration.cpp:41: error: cannot convert 'Eeprom::configuration::read()::__lambda0' to 'char*' in initialization
configuration.cpp:55: error: invalid conversion from 'char*' to 'char' [-fpermissive]
       read_ssid_pswd[0] = rw_ssid;
                         ^
configuration.cpp:56: error: invalid conversion from 'char*' to 'char' [-fpermissive]
       read_ssid_pswd[1] = rw_pswd;
                         ^
exit status 1
request for member 'length' in 'rw_ssid', which is of non-class type 'char*'
</code>```

I am a novice in cpp, and learning by doing it.

答: char* has no length method. either you need strlen(rw_ssid) or you should use std::string

Body:
I have a public function save that accepts rw_ssid and rw_pswd char type variable in the file configuration.cpp

namespace Eeprom
{

void configuration::initialize(){
    EEPROM.begin(512);
}

void configuration::save(char* rw_ssid, char* rw_pswd) {
    for (int i = 0; i < 128; ++i) {
      EEPROM.write(i, 0);
      delay(10);
    }
    for (int i = 0; i < rw_ssid.length(); ++i) {
      EEPROM.write(i, rw_ssid[i]);
    }
    for (int i = 0; i < rw_pswd.length(); ++i) {
      EEPROM.write(32 + i, rw_pswd[i]);
    }

    EEPROM.commit();
    Serial.println("Written to EEPROM!");
    Serial.print("SSID: ");
    Serial.println(rw_ssid);
    Serial.print("PASS: ");
    Serial.println(rw_pswd);
    Funcs::connection::connectWifi(rw_ssid, rw_pswd);
    Serial.print("IP connection: ");
    Serial.println(WiFi.localIP());
  }

void configuration::save(char* rw_ssid, char* rw_pswd) {
    for (int i = 0; i < 128; ++i) {
      EEPROM.write(i, 0);
      delay(10);
    }
    for (int i = 0; i < rw_ssid.length(); ++i) {
      EEPROM.write(i, rw_ssid[i]);
    }
    for (int i = 0; i < rw_pswd.length(); ++i) {
      EEPROM.write(32 + i, rw_pswd[i]);
    }

    EEPROM.commit();
    Serial.println("Written to EEPROM!");
    Serial.print("SSID: ");
    Serial.println(rw_ssid);
    Serial.print("PASS: ");
    Serial.println(rw_pswd);
    Funcs::connection::connectWifi(rw_ssid, rw_pswd);
    Serial.print("IP connection: ");
    Serial.println(WiFi.localIP());
  }
}

and then I have its header file

configuration.h

namespace Eeprom
{
  class configuration
  {
    public:
      static void initialize();
      static char* read();
      static void save(char* recvd_ssid, char* recvd_pass);
  };
}

On compile I am getting this error:

sketch/configuration.cpp: In static member function 'static void Eeprom::configuration::save(char*, char*)':
configuration.cpp:19: error: request for member 'length' in 'rw_ssid', which is of non-class type 'char*'
     for (int i = 0; i < rw_ssid.length(); ++i) {
                                 ^
configuration.cpp:22: error: request for member 'length' in 'rw_pswd', which is of non-class type 'char*'
     for (int i = 0; i < rw_pswd.length(); ++i) {
                                 ^
configuration.cpp:34: error: 'WiFi' was not declared in this scope
     Serial.println(WiFi.localIP());
                    ^
sketch/configuration.cpp: In static member function 'static char* Eeprom::configuration::read()':
configuration.cpp:41: error: expected identifier before numeric constant
     char* read_ssid_pswd = [2];
                             ^
sketch/configuration.cpp: In lambda function:
configuration.cpp:41: error: expected '{' before ';' token
     char* read_ssid_pswd = [2];
                               ^
sketch/configuration.cpp: In static member function 'static char* Eeprom::configuration::read()':
configuration.cpp:41: error: cannot convert 'Eeprom::configuration::read()::__lambda0' to 'char*' in initialization
configuration.cpp:55: error: invalid conversion from 'char*' to 'char' [-fpermissive]
       read_ssid_pswd[0] = rw_ssid;
                         ^
configuration.cpp:56: error: invalid conversion from 'char*' to 'char' [-fpermissive]
       read_ssid_pswd[1] = rw_pswd;
                         ^
exit status 1
request for member 'length' in 'rw_ssid', which is of non-class type 'char*'

I am a novice in cpp, and learning by doing it.


问:
Run jest tests in docker-compose with mongodb and redis
I've an application which uses mongodb and redis.

I want to execute tests on docker-compose, but every time i ran test I get the following error.

Command: docker-compose -p tests run --rm main npm run test

Error:

```<code> FAIL  test/content/document/content.document.test.ts
  ● Test suite failed to run

    Cannot find module 'request'

      at node_modules/request-promise-native/lib/rp.js:8:12
      at module.exports (node_modules/stealthy-require/lib/index.js:62:23)
      at Object.<anonymous> (node_modules/request-promise-native/lib/rp.js:7:15)
</code>```

I tried to install request but no success.

The tests run successfully local without docker-compose.

docker-compose.yml:

```<code>version: '3.7'

services:
  main:
    build:
      context: .
      target: development
    volumes:
      - .:/usr/src/app
      - /usr/src/app/node_modules
    ports:
      - 8080:8080
    command: npm run start:dev
    networks:
      - webnet
    depends_on:
      - redis
      - mongodb

  redis:
    container_name: redis
    image: redis:5
    networks:
      - webnet

  mongodb:
    container_name: mongodb
    environment:
      - MONGO_INITDB_DATABASE=database
      - MONGO_INITDB_ROOT_USERNAME=username
      - MONGO_INITDB_ROOT_PASSWORD=password
    image: mongo:4.2.6
    restart: always
    networks:
      - webnet
    ports:
      - '27017:27017'

networks:
  webnet:
</code>```

Dockerfile:

```<code># https://blog.logrocket.com/containerized-development-nestjs-docker/

FROM node:10.20.1-alpine3.11 As development

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install --only=development

COPY . .

RUN npm run build

FROM node:10.20.1-alpine3.11 as production

ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}

WORKDIR /usr/src/app

ENV PORT=8080

COPY package*.json ./

RUN npm install --only=production

COPY . .

COPY --from=development /usr/src/app/dist ./dist

CMD ["node", "dist/main"]
</code>```

package.json

```<code>{
  "name": "jest-docker",
  "version": "0.0.1",
  "private": true,
  "description": "",
  "license": "MIT",
  "author": "",
  "main": "dist/main.js",
  "scripts": {
    "prebuild": "rimraf dist",
    "build": "nest build",
    "build:docker": "docker build -t paperbot .",
    "deploy": "npm run build && gcloud app deploy --quiet",
    "docker": "PORT=8080 docker-compose up --build --rm -V",
    "start": "NODE_PATH=. npm run start:prod",
    "start:dev": "PORT=8080 NODE_PATH=. nest start --watch",
    "start:prod": "NODE_PATH=. node dist/main.js",
    "test": "NODE_PATH=. ts-node ./dck",
    "test:docker": "docker-compose -p tests run --rm main npm run test"
  },
  "dependencies": {
    "@nestjs/bull": "^0.1.1",
    "@nestjs/common": "^6.11.11",
    "@nestjs/config": "^0.4.2",
    "@nestjs/core": "^6.11.11",
    "@nestjs/cqrs": "^7.0.0",
    "@nestjs/platform-express": "^6.11.11",
    "@slack/bolt": "^2.1.1",
    "bull": "^3.14.0",
    "class-transformer": "^0.2.3",
    "class-validator": "^0.12.2",
    "embedly": "^2.1.1",
    "express": "^4.17.1",
    "js-video-url-parser": "^0.4.1",
    "mongodb": "^3.5.8",
    "node-nlp": "^4.4.0",
    "raw-body": "^2.4.1",
    "reflect-metadata": "^0.1.12",
    "rxjs": "^6.5.5",
    "tsscmp": "^1.0.6",
    "unfluff": "^3.2.0"
  },
  "devDependencies": {
    "@nestjs/cli": "^7.2.0",
    "@nestjs/testing": "^6.11.11",
    "@release-it/conventional-changelog": "^1.1.4",
    "@testdeck/jest": "^0.1.0",
    "@types/bull": "^3.13.0",
    "@types/express": "^4.17.6",
    "@types/jest": "^23.3.13",
    "@types/mongodb": "^3.5.18",
    "@types/node": "^10.17.24",
    "@types/qs": "^6.9.3",
    "@types/supertest": "^2.0.9",
    "@types/tsscmp": "^1.0.0",
    "@typescript-eslint/eslint-plugin": "^3.0.2",
    "@typescript-eslint/parser": "^3.0.2",
    "concurrently": "^4.1.2",
    "dockest": "^2.0.2",
    "eslint": "^7.1.0",
    "eslint-config-prettier": "^6.11.0",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-json-format": "^2.0.1",
    "eslint-plugin-prettier": "^3.1.3",
    "jest": "^26.0.1",
    "jest-sonar-reporter": "^2.0.0",
    "prettier": "^1.19.1",
    "release-it": "^13.6.1",
    "rimraf": "^2.7.1",
    "supertest": "^3.4.1",
    "ts-jest": "^26.0.0",
    "ts-node": "8.1.0",
    "tsconfig-paths": "3.8.0",
    "typescript": "^3.9.3"
  },
  "engines": {
    "node": ">=10.0.0"
  },
  "jestSonar": {
    "reportPath": "coverage",
    "reportFile": "test-reporter.xml",
    "indent": 2
  }
}

</code>```

I tried also with Dockest and got the same error.

答:
As you can see, request module is not part of dependencies as well devDependencies, please run

```<code>npm install request --production
</code>```

Body:
I've an application which uses mongodb and redis.

I want to execute tests on docker-compose, but every time i ran test I get the following error.

Command: docker-compose -p tests run --rm main npm run test

Error:

 FAIL  test/content/document/content.document.test.ts
  ● Test suite failed to run

    Cannot find module 'request'

      at node_modules/request-promise-native/lib/rp.js:8:12
      at module.exports (node_modules/stealthy-require/lib/index.js:62:23)
      at Object.<anonymous> (node_modules/request-promise-native/lib/rp.js:7:15)

I tried to install request but no success.

The tests run successfully local without docker-compose.

docker-compose.yml:

version: '3.7'

services:
  main:
    build:
      context: .
      target: development
    volumes:
      - .:/usr/src/app
      - /usr/src/app/node_modules
    ports:
      - 8080:8080
    command: npm run start:dev
    networks:
      - webnet
    depends_on:
      - redis
      - mongodb

  redis:
    container_name: redis
    image: redis:5
    networks:
      - webnet

  mongodb:
    container_name: mongodb
    environment:
      - MONGO_INITDB_DATABASE=database
      - MONGO_INITDB_ROOT_USERNAME=username
      - MONGO_INITDB_ROOT_PASSWORD=password
    image: mongo:4.2.6
    restart: always
    networks:
      - webnet
    ports:
      - '27017:27017'

networks:
  webnet:

Dockerfile:

# https://blog.logrocket.com/containerized-development-nestjs-docker/

FROM node:10.20.1-alpine3.11 As development

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install --only=development

COPY . .

RUN npm run build

FROM node:10.20.1-alpine3.11 as production

ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}

WORKDIR /usr/src/app

ENV PORT=8080

COPY package*.json ./

RUN npm install --only=production

COPY . .

COPY --from=development /usr/src/app/dist ./dist

CMD ["node", "dist/main"]

package.json

{
  "name": "jest-docker",
  "version": "0.0.1",
  "private": true,
  "description": "",
  "license": "MIT",
  "author": "",
  "main": "dist/main.js",
  "scripts": {
    "prebuild": "rimraf dist",
    "build": "nest build",
    "build:docker": "docker build -t paperbot .",
    "deploy": "npm run build && gcloud app deploy --quiet",
    "docker": "PORT=8080 docker-compose up --build --rm -V",
    "start": "NODE_PATH=. npm run start:prod",
    "start:dev": "PORT=8080 NODE_PATH=. nest start --watch",
    "start:prod": "NODE_PATH=. node dist/main.js",
    "test": "NODE_PATH=. ts-node ./dck",
    "test:docker": "docker-compose -p tests run --rm main npm run test"
  },
  "dependencies": {
    "@nestjs/bull": "^0.1.1",
    "@nestjs/common": "^6.11.11",
    "@nestjs/config": "^0.4.2",
    "@nestjs/core": "^6.11.11",
    "@nestjs/cqrs": "^7.0.0",
    "@nestjs/platform-express": "^6.11.11",
    "@slack/bolt": "^2.1.1",
    "bull": "^3.14.0",
    "class-transformer": "^0.2.3",
    "class-validator": "^0.12.2",
    "embedly": "^2.1.1",
    "express": "^4.17.1",
    "js-video-url-parser": "^0.4.1",
    "mongodb": "^3.5.8",
    "node-nlp": "^4.4.0",
    "raw-body": "^2.4.1",
    "reflect-metadata": "^0.1.12",
    "rxjs": "^6.5.5",
    "tsscmp": "^1.0.6",
    "unfluff": "^3.2.0"
  },
  "devDependencies": {
    "@nestjs/cli": "^7.2.0",
    "@nestjs/testing": "^6.11.11",
    "@release-it/conventional-changelog": "^1.1.4",
    "@testdeck/jest": "^0.1.0",
    "@types/bull": "^3.13.0",
    "@types/express": "^4.17.6",
    "@types/jest": "^23.3.13",
    "@types/mongodb": "^3.5.18",
    "@types/node": "^10.17.24",
    "@types/qs": "^6.9.3",
    "@types/supertest": "^2.0.9",
    "@types/tsscmp": "^1.0.0",
    "@typescript-eslint/eslint-plugin": "^3.0.2",
    "@typescript-eslint/parser": "^3.0.2",
    "concurrently": "^4.1.2",
    "dockest": "^2.0.2",
    "eslint": "^7.1.0",
    "eslint-config-prettier": "^6.11.0",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-json-format": "^2.0.1",
    "eslint-plugin-prettier": "^3.1.3",
    "jest": "^26.0.1",
    "jest-sonar-reporter": "^2.0.0",
    "prettier": "^1.19.1",
    "release-it": "^13.6.1",
    "rimraf": "^2.7.1",
    "supertest": "^3.4.1",
    "ts-jest": "^26.0.0",
    "ts-node": "8.1.0",
    "tsconfig-paths": "3.8.0",
    "typescript": "^3.9.3"
  },
  "engines": {
    "node": ">=10.0.0"
  },
  "jestSonar": {
    "reportPath": "coverage",
    "reportFile": "test-reporter.xml",
    "indent": 2
  }
}

I tried also with Dockest and got the same error.

Body:
As you can see, request module is not part of dependencies as well devDependencies, please run

npm install request --production


问:
Extracting title from link in Python (Beautiful soup)
I am new to Python and I'm looking to extract the title from a link. So far I have the following but have hit a dead end:</p>

```<code>import requests
from bs4 import BeautifulSoup
page = requests.get("http://books.toscrape.com/")
soup = BeautifulSoup(page.content, 'html.parser')
books = soup.find("section")
book_list = books.find_all(class_="product_pod")
tonight = book_list[0]

for book in book_list:
    price = book.find(class_="price_color").get_text()
    title = book.find('a')
    print (price)
    print (title.contents[0])

</code>```

答:
To extract title from links, you can use title attribute.

Fore example:

```<code>import requests
from bs4 import BeautifulSoup
page = requests.get("http://books.toscrape.com/")
soup = BeautifulSoup(page.content, 'html.parser')

for a in soup.select('h3 > a'):
    print(a['title'])
</code>```

Prints:

```<code>A Light in the Attic
Tipping the Velvet
Soumission
Sharp Objects
Sapiens: A Brief History of Humankind
The Requiem Red
The Dirty Little Secrets of Getting Your Dream Job
The Coming Woman: A Novel Based on the Life of the Infamous Feminist, Victoria Woodhull
The Boys in the Boat: Nine Americans and Their Epic Quest for Gold at the 1936 Berlin Olympics
The Black Maria
Starving Hearts (Triangular Trade Trilogy, #1)
Shakespeare's Sonnets
Set Me Free
Scott Pilgrim's Precious Little Life (Scott Pilgrim #1)
Rip it Up and Start Again
Our Band Could Be Your Life: Scenes from the American Indie Underground, 1981-1991
Olio
Mesaerion: The Best Science Fiction Stories 1800-1849
Libertarianism for Beginners
It's Only the Himalayas
</code>```

Body:
I am new to Python and I'm looking to extract the title from a link. So far I have the following but have hit a dead end:

import requests
from bs4 import BeautifulSoup
page = requests.get("http://books.toscrape.com/")
soup = BeautifulSoup(page.content, 'html.parser')
books = soup.find("section")
book_list = books.find_all(class_="product_pod")
tonight = book_list[0]

for book in book_list:
    price = book.find(class_="price_color").get_text()
    title = book.find('a')
    print (price)
    print (title.contents[0])

Body:
To extract title from links, you can use title attribute.

Fore example:

import requests
from bs4 import BeautifulSoup
page = requests.get("http://books.toscrape.com/")
soup = BeautifulSoup(page.content, 'html.parser')

for a in soup.select('h3 > a'):
    print(a['title'])

Prints:

A Light in the Attic
Tipping the Velvet
Soumission
Sharp Objects
Sapiens: A Brief History of Humankind
The Requiem Red
The Dirty Little Secrets of Getting Your Dream Job
The Coming Woman: A Novel Based on the Life of the Infamous Feminist, Victoria Woodhull
The Boys in the Boat: Nine Americans and Their Epic Quest for Gold at the 1936 Berlin Olympics
The Black Maria
Starving Hearts (Triangular Trade Trilogy, #1)
Shakespeare's Sonnets
Set Me Free
Scott Pilgrim's Precious Little Life (Scott Pilgrim #1)
Rip it Up and Start Again
Our Band Could Be Your Life: Scenes from the American Indie Underground, 1981-1991
Olio
Mesaerion: The Best Science Fiction Stories 1800-1849
Libertarianism for Beginners
It's Only the Himalayas


问:
How do i use my incremented value inside inside an other component
For school i need to make an react app, it is my first time using, html, css, javascript and react and now i am stuck on part where i have to post the data to an API. My part is to create a page where people can select skittles and when they press oke. The data is send.

I created a single Selector

```<code>import React, { Component } from "react";
export default class Selector extends Component {
    state = {
        value: this.props.selector.value,
    };

    handleIncrement = () => {
        this.setState({ value: this.state.value + 1 });
        console.log(this.state.value);
    };

    handleDecrement = () => {
        this.setState({ value: this.state.value - 1 });
    };

    render() {
        return (
            <div>
                {this.props.children}
                <span>{this.state.value}</span>
                <button
                    onClick={this.handleIncrement}
                    className="btn btn-secondary btn-sm m-2"
                >
                    +
                </button>
                <button
                    onClick={this.handleDecrement}
                    className="btn btn-secondary btn-sm m-2"
                >
                    -
                </button>
                <button
                    onClick={() =>
                        this.setState({
                            value: 0,
                        })
                    }
                    className="btn btn-danger btn-sm m-2"
                >
                    Reset
                </button>
            </div>
        );
    }
}
</code>```

From the one selector i made multiple selectors

```<code>import React, { Component } from "react";
import Selector from "./selector";
import axios from "axios";

export default class Selectors extends Component {
    state = {
        skittleSelectors: [
            { id: 1, value: 0, color: "Green", availability: 0 },
            { id: 2, value: 0, color: "Red", availability: 0 },
            { id: 3, value: 0, color: "Yellow", availability: 0 },
            { id: 4, value: 0, color: "Purple", availability: 0 },
            { id: 5, value: 0, color: "Orange", availability: 0 },
        ],
    };

postData(){
        const greenSelector = this.state.skittleSelectors.findIndex(
            (element) => element.color === "Green"
        );
        let greenValue = this.state.skittleSelectors[greenSelector].value;
        console.log(greenValue);
    };

render() {
        return (
            <div>
                <button onClick={this.postData}>POSTDATA</button>
                {this.state.skittleSelectors.map((selector) => (
                    <Selector
                        key={selector.id}
                        selector={selector}
                        onReset={this.handleReset}
                    >
                        <p>{selector.color}:</p>
                        <p>amount availible: {selector.availability}</p>
                    </Selector>
                ))}
            </div>
        );
    }
}

</code>```

Now my question

When I log the values inside the handleIncrement() of the single selector it is correcly displayed in the console. But i want to use that data in the Selectors page. but when i try to log it there it simply said 0 because of the initial value.

how can i solve this. I have tried to use the post inside the Selector.jsx, but thats not correct I think and I still cant get it to work. I tried somewhat here and there by using the componentDidMount() and componendDitUpdate(), but with no succes.

So how can I use my updated stated inside the postData method from my Selectors file. I hope you guys can help me out here, after 1 day I am completely stuck.

Thank you in advance.

答:
I have fixed your code. Actually, you need to pass changed value from Selector to Selectors that is what I have done using onChangedValue props. Moreover, I have changed setState as when you change your state using your current state you should use prevState

Selectors Component

```<code>import React, {Component} from "react";
import axios from "axios";
import Selector from "./Selector";

export default class Selectors extends Component {
    state = {
        skittleSelectors: [
            {id: 1, value: 0, color: "Green", availability: 0},
            {id: 2, value: 0, color: "Red", availability: 0},
            {id: 3, value: 0, color: "Yellow", availability: 0},
            {id: 4, value: 0, color: "Purple", availability: 0},
            {id: 5, value: 0, color: "Orange", availability: 0},
        ],
    };

    postData = () => {
        const greenSelector = this.state.skittleSelectors.findIndex(
            (element) => element.color === "Green"
        );
        let greenValue = this.state.skittleSelectors[greenSelector].value;
        console.log(greenValue);
    };

    onChangedValue = (selector, value) => {
        this.setState(prevState => {
            let currentItem = this.state.skittleSelectors.find(s => s.id === selector.id);
            currentItem.value = value;
            return{ skittleSelectors: [...this.state.skittleSelectors] }
        }, console.log(this.state.skittleSelectors, 'skittleSelectors'));

    };

    render() {
        return (
            <div>
                <button onClick={this.postData}>POSTDATA</button>
                {this.state.skittleSelectors.map((selector) => (
                    <Selector
                        key={selector.id}
                        selector={selector}
                        onReset={this.handleReset}
                        onChangedValue={this.onChangedValue}
                    >
                        <p>{selector.color}:</p>
                        <p>amount availible: {selector.availability}</p>
                    </Selector>
                ))}
            </div>
        );
    }
}
</code>```

Selector Component

```<code>import React, {Component} from "react";

export default class Selector extends Component {
    state = {
        value: this.props.selector.value,
    };

    handleIncrement = () => {
        this.setState(prevState => {
            return {value: prevState.value + 1}
        }, () => this.props.onChangedValue(this.props.selector, this.state.value));
    };

    handleDecrement = () => {
        this.setState(prevState => {
            return {value: prevState.value - 1}
        }, () => this.props.onChangedValue(this.props.selector, this.state.value));
    };

    render() {
        return (
            <div>
                {this.props.children}
                <span>{this.state.value}</span>
                <button
                    onClick={this.handleIncrement}
                    className="btn btn-secondary btn-sm m-2"
                >
                    +
                </button>
                <button
                    onClick={this.handleDecrement}
                    className="btn btn-secondary btn-sm m-2"
                >
                    -
                </button>
                <button
                    onClick={() =>
                        this.setState({
                            value: 0,
                        })
                    }
                    className="btn btn-danger btn-sm m-2"
                >
                    Reset
                </button>
            </div>
        );
    }
}
</code>```

Body:
For school i need to make an react app, it is my first time using, html, css, javascript and react and now i am stuck on part where i have to post the data to an API. My part is to create a page where people can select skittles and when they press oke. The data is send.

I created a single Selector

import React, { Component } from "react";
export default class Selector extends Component {
    state = {
        value: this.props.selector.value,
    };

    handleIncrement = () => {
        this.setState({ value: this.state.value + 1 });
        console.log(this.state.value);
    };

    handleDecrement = () => {
        this.setState({ value: this.state.value - 1 });
    };

    render() {
        return (

                {this.props.children}
                {this.state.value}
                <button
                    onClick={this.handleIncrement}
                    className="btn btn-secondary btn-sm m-2"
                >
                    +
                </button>
                <button
                    onClick={this.handleDecrement}
                    className="btn btn-secondary btn-sm m-2"
                >
                    -
                </button>
                <button
                    onClick={() =>
                        this.setState({
                            value: 0,
                        })
                    }
                    className="btn btn-danger btn-sm m-2"
                >
                    Reset
                </button>

        );
    }
}

From the one selector i made multiple selectors

import React, { Component } from "react";
import Selector from "./selector";
import axios from "axios";

export default class Selectors extends Component {
    state = {
        skittleSelectors: [
            { id: 1, value: 0, color: "Green", availability: 0 },
            { id: 2, value: 0, color: "Red", availability: 0 },
            { id: 3, value: 0, color: "Yellow", availability: 0 },
            { id: 4, value: 0, color: "Purple", availability: 0 },
            { id: 5, value: 0, color: "Orange", availability: 0 },
        ],
    };

postData(){
        const greenSelector = this.state.skittleSelectors.findIndex(
            (element) => element.color === "Green"
        );
        let greenValue = this.state.skittleSelectors[greenSelector].value;
        console.log(greenValue);
    };

render() {
        return (

                <button onClick={this.postData}>POSTDATA</button>
                {this.state.skittleSelectors.map((selector) => (
                    <Selector
                        key={selector.id}
                        selector={selector}
                        onReset={this.handleReset}
                    >

{selector.color}:

amount availible: {selector.availability}

                    </Selector>
                ))}

        );
    }
}

Now my question

When I log the values inside the handleIncrement() of the single selector it is correcly displayed in the console. But i want to use that data in the Selectors page. but when i try to log it there it simply said 0 because of the initial value.

how can i solve this. I have tried to use the post inside the Selector.jsx, but thats not correct I think and I still cant get it to work. I tried somewhat here and there by using the componentDidMount() and componendDitUpdate(), but with no succes.

So how can I use my updated stated inside the postData method from my Selectors file. I hope you guys can help me out here, after 1 day I am completely stuck.

Thank you in advance.

Body:
I have fixed your code. Actually, you need to pass changed value from Selector to Selectors that is what I have done using onChangedValue props. Moreover, I have changed setState as when you change your state using your current state you should use prevState

Selectors Component

import React, {Component} from "react";
import axios from "axios";
import Selector from "./Selector";

export default class Selectors extends Component {
    state = {
        skittleSelectors: [
            {id: 1, value: 0, color: "Green", availability: 0},
            {id: 2, value: 0, color: "Red", availability: 0},
            {id: 3, value: 0, color: "Yellow", availability: 0},
            {id: 4, value: 0, color: "Purple", availability: 0},
            {id: 5, value: 0, color: "Orange", availability: 0},
        ],
    };

    postData = () => {
        const greenSelector = this.state.skittleSelectors.findIndex(
            (element) => element.color === "Green"
        );
        let greenValue = this.state.skittleSelectors[greenSelector].value;
        console.log(greenValue);
    };

    onChangedValue = (selector, value) => {
        this.setState(prevState => {
            let currentItem = this.state.skittleSelectors.find(s => s.id === selector.id);
            currentItem.value = value;
            return{ skittleSelectors: [...this.state.skittleSelectors] }
        }, console.log(this.state.skittleSelectors, 'skittleSelectors'));

    };

    render() {
        return (
            <div>
                <button onClick={this.postData}>POSTDATA</button>
                {this.state.skittleSelectors.map((selector) => (
                    <Selector
                        key={selector.id}
                        selector={selector}
                        onReset={this.handleReset}
                        onChangedValue={this.onChangedValue}
                    >
                        <p>{selector.color}:</p>
                        <p>amount availible: {selector.availability}</p>
                    </Selector>
                ))}
            </div>
        );
    }
}

Selector Component

import React, {Component} from "react";

export default class Selector extends Component {
    state = {
        value: this.props.selector.value,
    };

    handleIncrement = () => {
        this.setState(prevState => {
            return {value: prevState.value + 1}
        }, () => this.props.onChangedValue(this.props.selector, this.state.value));
    };

    handleDecrement = () => {
        this.setState(prevState => {
            return {value: prevState.value - 1}
        }, () => this.props.onChangedValue(this.props.selector, this.state.value));
    };

    render() {
        return (
            <div>
                {this.props.children}
                <span>{this.state.value}</span>
                <button
                    onClick={this.handleIncrement}
                    className="btn btn-secondary btn-sm m-2"
                >
                    +
                </button>
                <button
                    onClick={this.handleDecrement}
                    className="btn btn-secondary btn-sm m-2"
                >
                    -
                </button>
                <button
                    onClick={() =>
                        this.setState({
                            value: 0,
                        })
                    }
                    className="btn btn-danger btn-sm m-2"
                >
                    Reset
                </button>
            </div>
        );
    }
}


问:
rbind RStudio adding third row name to existing matrix
After a long time, I decided to come back to coding in R. As of now, I am just going through the tutorials for remembering the things I learned a year ago:D

Everything was fine until I came across with cbind and rbind function.

enter image description here

Could you please advise me what can be done to set third row name for xxbigger matrix?
I actually want to resolve this in line 23.
My question for you guys is: How to define thrid row name for xxbigger matrix in one line?

Thank you,

P.S. Don't put sarcastic comments, so I can come back to this website again:)

答:
We could do this more simple way

```<code>xxbigger <- rbind(xxbig, `#3` = c(84, 24, 68))
</code>```

Or in the OP's code, change the indexing outside the row.names

```<code>row.names(xxbigger)[3] <- "#3"
</code>```

Body:
We could do this more simple way

xxbigger <- rbind(xxbig, `#3` = c(84, 24, 68))

Or in the OP's code, change the indexing outside the row.names

row.names(xxbigger)[3] <- "#3"


答:
By just modifying your existing code you can use the alt text which contains the book titles in your example. </p>

```<code>print (title.contents[0].attrs["alt"])
</code>```

Title: Extracting title from link in Python (Beautiful soup)

Body:
By just modifying your existing code you can use the alt text which contains the book titles in your example.

print (title.contents[0].attrs["alt"])


答:
Try something like this:</p>

```<code>$('#prev, #image').click(function() {...});
</code>```

Title: jquery: using OR with .click()?

Body:
I need help trying to figure out how to use .click() function for two different attributes.

$('#prev').click(function() {}

and

$('#image').click(function() {}

So how would I do an OR statement if user clicks on #prev and #image without writing two identical scripts?

Thanks!

Body:
Try something like this:

$('#prev, #image').click(function() {...});


问:
Apache HUE, can login using REST API, but the rest doesn't work
I'm struggling with Apache HUE Rest API and django csrf.

The problem is that I can kind-a login, but the rest doesn't work. I always get redirected to login page. Seems like server doesn't like my csrftoken or sessionid cookie.

I have absolutely no idea why.
Here is my login code:

val accessToken = getAccessToken(Http(s"$baseUrl/accounts/login/?next=/").asString)
    val response =
      Http(s"$baseUrl/accounts/login/")
        .postForm(Seq(
          "username" -> username,
          "password" -> password,
          "csrfmiddlewaretoken" -> accessToken.csrftoken.getValue,
          "next" -> "/"
        ))
        .cookie(accessToken.csrftoken)
        .asString
    getAccessToken(response) // wrapper for cookies and headers from response
```

<p>Now I try just to get page from HUE protected with csrf</p>

<pre class="lang-scala prettyprint-override"><code> def getDir(hdfsPathDirParent: String): Unit = {
    val accessToken = login()
    val response = Http(s"$baseUrl/filebrowser/view=$hdfsPathDirParent")
      .cookie(accessToken.csrftoken) // retrieved after login
      .cookie(accessToken.sessionid) // retrieved after login
      .header("X-CSRFToken", accessToken.csrftoken.getValue)
      .header("Host", "localhost:8888")
      .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
      .header("Connection", "keep-alive")
      .header("Sec-Fetch-Dest", "empty")
      .header("Sec-Fetch-Mode", "cors")
      .header("Sec-Fetch-Site", "same-origin")
      //.header("Sec-Fetch-User", "?1")
      .header("Upgrade-Insecure-Requests", "1")
      .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36")
      .header("Accept-Encoding", "gzip, deflate, br")

      .header("Accept-Language", "en,en-US;q=0.9,ru;q=0.8")
      .header("Cache-Control", "max-age=0")
      .header("X-Requested-With", "XMLHttpRequest")

      .asString

</code>```

I literally copy-pasted all tokens from Google Chrome debug panel. It doesn't work

```<code>[30/May/2020 05:19:29 -0700] access       WARNING  172.17.0.1 test_user - "POST /accounts/login/ HTTP/1.1" -- Successful login for user: test_user
[30/May/2020 05:19:29 -0700] middleware   INFO     Redirecting to login page: /filebrowser/view=/user/test_user
[30/May/2020 05:19:29 -0700] access       INFO     172.17.0.1 -anon- - "GET /filebrowser/view=/user/test_user HTTP/1.1" -- login redirection
</code>```

So I do pass login form, but the rest doesn't work. Can't find what I miss...

Their code example doesn't work

```<code>http://cloudera.github.io/hue/latest/developer/api/
</code>```

答:
It doesn't seem to be intuitive
but

def getDir(accessToken: CookiesAndHeaders, hdfsPathDirParent: String): (String, CookiesAndHeaders) = {
    val req = Http(s"$baseUrl/filebrowser/view=$hdfsPathDirParent")
      .cookie(accessToken.sessionid)
    val response = req.asString
```

just DO NOT* pass csrftoken as cookie, use ONLY sessionid sessionid Cookie.
I have no idea why, but it helped...

Body:
I'm struggling with Apache HUE Rest API and django csrf.

The problem is that I can kind-a login, but the rest doesn't work. I always get redirected to login page. Seems like server doesn't like my csrftoken or sessionid cookie.

I have absolutely no idea why.
Here is my login code:

val accessToken = getAccessToken(Http(s"$baseUrl/accounts/login/?next=/").asString)
    val response =
      Http(s"$baseUrl/accounts/login/")
        .postForm(Seq(
          "username" -> username,
          "password" -> password,
          "csrfmiddlewaretoken" -> accessToken.csrftoken.getValue,
          "next" -> "/"
        ))
        .cookie(accessToken.csrftoken)
        .asString
    getAccessToken(response) // wrapper for cookies and headers from response

Now I try just to get page from HUE protected with csrf

 def getDir(hdfsPathDirParent: String): Unit = {
    val accessToken = login()
    val response = Http(s"$baseUrl/filebrowser/view=$hdfsPathDirParent")
      .cookie(accessToken.csrftoken) // retrieved after login
      .cookie(accessToken.sessionid) // retrieved after login
      .header("X-CSRFToken", accessToken.csrftoken.getValue)
      .header("Host", "localhost:8888")
      .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
      .header("Connection", "keep-alive")
      .header("Sec-Fetch-Dest", "empty")
      .header("Sec-Fetch-Mode", "cors")
      .header("Sec-Fetch-Site", "same-origin")
      //.header("Sec-Fetch-User", "?1")
      .header("Upgrade-Insecure-Requests", "1")
      .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36")
      .header("Accept-Encoding", "gzip, deflate, br")

      .header("Accept-Language", "en,en-US;q=0.9,ru;q=0.8")
      .header("Cache-Control", "max-age=0")
      .header("X-Requested-With", "XMLHttpRequest")

      .asString

I literally copy-pasted all tokens from Google Chrome debug panel. It doesn't work

[30/May/2020 05:19:29 -0700] access       WARNING  172.17.0.1 test_user - "POST /accounts/login/ HTTP/1.1" -- Successful login for user: test_user
[30/May/2020 05:19:29 -0700] middleware   INFO     Redirecting to login page: /filebrowser/view=/user/test_user
[30/May/2020 05:19:29 -0700] access       INFO     172.17.0.1 -anon- - "GET /filebrowser/view=/user/test_user HTTP/1.1" -- login redirection

So I do pass login form, but the rest doesn't work. Can't find what I miss...

Their code example doesn't work

http://cloudera.github.io/hue/latest/developer/api/

Body:
It doesn't seem to be intuitive
but

def getDir(accessToken: CookiesAndHeaders, hdfsPathDirParent: String): (String, CookiesAndHeaders) = {
    val req = Http(s"$baseUrl/filebrowser/view=$hdfsPathDirParent")
      .cookie(accessToken.sessionid)
    val response = req.asString

just DO NOT* pass csrftoken as cookie, use ONLY sessionid sessionid Cookie.
I have no idea why, but it helped...


问:
Session lock causes ASP.Net websites to be slow
I just discovered that every request in an ASP.Net web application gets a Session lock at the beginning of a request, and then releases it at the end of the request!

In case the implications of this are lost on you, as it was for me at first, this basically means the following:

Any time an ASP.Net webpage is taking a long time to load (maybe due to a slow database call or whatever), and the user decides they want to navigate to a different page because they are tired of waiting, they can't! The ASP.Net session lock forces the new page request to wait until the original request has finished its painfully slow load. Arrrgh.

Anytime an UpdatePanel is loading slowly, and the user decides to navigate to a different page before the UpdatePanel has finished updating... they can't! The ASP.Net session lock forces the new page request to wait until the original request has finished its painfully slow load. Double Arrrgh!

So what are the options?  So far I have come up with:

Implement a Custom SessionStateDataStore, which ASP.Net supports.  I haven't found too many out there to copy, and it seems kind of high risk and easy to mess up.

Keep track of all requests in progress, and if a request comes in from the same user, cancel the original request.  Seems kind of extreme, but it would work (I think).

Don't use Session!  When I need some kind of state for the user, I could just use Cache instead, and key items on the authenticated username, or some such thing. Again seems kind of extreme.

I really can't believe that the ASP.Net Microsoft team would have left such a huge performance bottleneck in the framework at version 4.0! Am I missing something obvious? How hard would it be to use a ThreadSafe collection for the Session?

答:
After struggling with all available options, I ended up writing a JWT token based SessionStore provider (the session travels inside a cookie, and no backend storage is needed).

http://www.drupalonwindows.com/en/content/token-sessionstate

Advantages:

Drop-in replacement, no changes to your code are needed

Scale better
than any other centralized store, as no session storage backend is
needed.

Faster than any other session storage, as no data needs to be
retrieved from any session storage

Consumes no server resources for
session storage.

Default non-blocking implementation: concurrent
request won't block each other and hold a lock on the session

Horizontally scale your application: because the session data travels
with the request itself you can have multiple web heads without
worrying about session sharing.


答:
you can use it:

```<code>import requests
from bs4 import BeautifulSoup
page = requests.get("http://books.toscrape.com/")
soup = BeautifulSoup(page.content, 'html.parser')
books = soup.find("section")
book_list = books.find_all(class_="product_pod")
tonight = book_list[0]

for book in book_list:
    price = book.find(class_="price_color").get_text()
    title = book.select_one('a img')['alt']
    print (title)
</code>```

Output:

```<code>A Light in the Attic
Tipping the Velvet
Soumission
Sharp Objects
Sapiens: A Brief History of Humankind
The Requiem Red...
</code>```

Body:
you can use it:

import requests
from bs4 import BeautifulSoup
page = requests.get("http://books.toscrape.com/")
soup = BeautifulSoup(page.content, 'html.parser')
books = soup.find("section")
book_list = books.find_all(class_="product_pod")
tonight = book_list[0]

for book in book_list:
    price = book.find(class_="price_color").get_text()
    title = book.select_one('a img')['alt']
    print (title)

Output:

A Light in the Attic
Tipping the Velvet
Soumission
Sharp Objects
Sapiens: A Brief History of Humankind
The Requiem Red...


问:
Unable to add Tableview cell value to JSON Parameter, coming nil why? in swift
I am adding tableview cell label text to phNumArray, in tableview i am getting all values but when i try to pass in service call then its coming nill why?

```<code> class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

@IBOutlet weak var joinersTableView: UITableView!

var tablcellArray  = [String]()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: Namescell = tableView.dequeueReusableCell(withIdentifier: "Namescell") as! Namescell
    cell.empRoleLbl.text = empTeftfield.text

    tablcellArray.append((cell.empRoleLbl.text!))

    print("employee names array \(tablcellArray)")// here coming all appende values

    return cell
}

func getPostData(params: [String:Any]) -> Data? {
        return try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
        DispatchQueue.main.async {

        self.joinersTableView.reloadData()
        }
    }

    func callPostApi() {
        print("tableview emp values\(tablcellArray)")// here array values not coming

        let url            = URL(string: "http://itaag-env-1/")!
        var request        = URLRequest(url: url)
        request.httpMethod = "POST"

        print("appende values \(tablcellArray)")
        try? request.setMultipartFormData(["contactsList": "\(tablcellArray)"], encoding: .utf8)
        DispatchQueue.main.async {
                           self.joinersTableView.reloadData()
                           }
        URLSession.shared.dataTask(with: request) { data, _, _ in
            if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {

            }
        }.resume()
    }
  }
</code>```

in tableview cellfor row appended values coming.. but when i try to bring that array in callPostApi func then tablcellArray showing nil why?

please share your knowledge, please try to solve this error.

答:
firstly change

```<code>var tablcellArray  = [String]()
</code>```

to

```<code>var tablcellArray  = [String]
</code>```

then in your cellForRowAt try to access your data such as

```<code>let empTeftfield =  tablcellArray[indexPath.row]
</code>```

if this line prints correctly

```<code>cell.empRoleLbl.text = empTeftfield.text
</code>```

this should work.

if not prints your value reload tableview after fetching data from api. you shouldnt add values to your array in your conditions.

Body:
I am adding tableview cell label text to phNumArray, in tableview i am getting all values but when i try to pass in service call then its coming nill why?

 class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

@IBOutlet weak var joinersTableView: UITableView!

var tablcellArray  = [String]()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: Namescell = tableView.dequeueReusableCell(withIdentifier: "Namescell") as! Namescell
    cell.empRoleLbl.text = empTeftfield.text

    tablcellArray.append((cell.empRoleLbl.text!))

    print("employee names array \(tablcellArray)")// here coming all appende values

    return cell
}

func getPostData(params: [String:Any]) -> Data? {
        return try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
        DispatchQueue.main.async {

        self.joinersTableView.reloadData()
        }
    }

    func callPostApi() {
        print("tableview emp values\(tablcellArray)")// here array values not coming

        let url            = URL(string: "http://itaag-env-1/")!
        var request        = URLRequest(url: url)
        request.httpMethod = "POST"

        print("appende values \(tablcellArray)")
        try? request.setMultipartFormData(["contactsList": "\(tablcellArray)"], encoding: .utf8)
        DispatchQueue.main.async {
                           self.joinersTableView.reloadData()
                           }
        URLSession.shared.dataTask(with: request) { data, _, _ in
            if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {

            }
        }.resume()
    }
  }

in tableview cellfor row appended values coming.. but when i try to bring that array in callPostApi func then tablcellArray showing nil why?

please share your knowledge, please try to solve this error.

Body:
firstly change

var tablcellArray  = [String]()

to

var tablcellArray  = [String]

then in your cellForRowAt try to access your data such as

let empTeftfield =  tablcellArray[indexPath.row]

if this line prints correctly

cell.empRoleLbl.text = empTeftfield.text

this should work.

if not prints your value reload tableview after fetching data from api. you shouldnt add values to your array in your conditions.