问:
Displaying a Base64 images from a database via PHP
I have this database that contains images as strings. Those strings look something like this:

```<code>data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...
</code>```

I need to create a link that will display this image. Like something.com/?id=27 is an image. All the images are in jpeg format. Here's what I've tried but didn't work:

```<code><?php
  $host = "smth";
  $user = "smth";
  $pass = "smth";
  $db_name = "smth";
  $dbh = new PDO("mysql:host=$host;dbname=$db_name", $user, $pass);
  $dbh->exec("SET NAMES utf8");
  $q = $dbh->prepare("select content from img where id = :id");
  $q->execute(array(':id'=>$_GET['id']));
  $row = $q->fetch(PDO::FETCH_BOTH);
  header("Content-type: image/jpeg");
  echo $row['content'];
?>
</code>```

The data is being fetched correctly but the image is not displayed.

I need to be able to use this link like this  and I do NOT want this solution:

Thanks!

答: If you are dealing with data stored in a PostgreSQL database bytea field you will receive a stream when fetching the PDO. To process the data any further first transform the stream to usual data like this: $stream = $row['content']; rewind($stream); $data=stream_get_contents($stream);

Body:
I have this database that contains images as strings. Those strings look something like this:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...

I need to create a link that will display this image. Like something.com/?id=27 is an image. All the images are in jpeg format. Here's what I've tried but didn't work:

<?php
  $host = "smth";
  $user = "smth";
  $pass = "smth";
  $db_name = "smth";
  $dbh = new PDO("mysql:host=$host;dbname=$db_name", $user, $pass);
  $dbh->exec("SET NAMES utf8");
  $q = $dbh->prepare("select content from img where id = :id");
  $q->execute(array(':id'=>$_GET['id']));
  $row = $q->fetch(PDO::FETCH_BOTH);
  header("Content-type: image/jpeg");
  echo $row['content'];
?>

The data is being fetched correctly but the image is not displayed.

I need to be able to use this link like this  and I do NOT want this solution:

Thanks!


来源: stackexchange

问:
MongoDB the difference between db.getCollection.find and db.tablename.find?
What is the difference between:

```<code>db.getCollection('booking').find()
</code>```

and

```<code>db.booking.find()
</code>```

Are they exactly the same, or when should I use which one?

```<code>db.getCollection('booking').find({_id:"0J0DR"})

db.booking.find({_id:"0J0DR"})
</code>```

答: In addition to the previous answers, on the shell, they might be exactly the same but in real IDE (like PyCharm), db.getCollection(collectionName) gives you back the whole doculment even with out the find() method.</p>

ContentLicense: CC BY-SA 3.0

Body:
What is the difference between:

db.getCollection('booking').find()

and

db.booking.find()

Are they exactly the same, or when should I use which one?

db.getCollection('booking').find({_id:"0J0DR"})

db.booking.find({_id:"0J0DR"})

ContentLicense: CC BY-SA 4.0


问:
Show controls on a Audio() object created in javascript
I have an Audio() object created in javascript like this:

const audio = new Audio();

After giving it the atributes like .source and audio.controls = true I couldn't find the controls in my page.

What I want to do is show the controls of that audio on a
 in the HTML

答:
Not sure what you did but setting the controls to true shows the element in the document.

An image showing the audio controls working

If someone else has a similar problem, try inspecting in the hierarchy if one of the ancestors is hidden.

https://codepen.io/blfunex/pen/ZELRQbL


问:
array sorting php
I've an array like this

```
Array
(

[0] => Array

        (
            [result] => Array
                (
                    [0] => Array
                        (
                            [type] => ABC
                            [id] => 123232
                            [name] => Apple

                        )

                    [1] => Array
                        (
                            [type] => DEF
                            [id] => 2323232
                            [name] => Banana

                        )

                )

            [title] => Cool
            [rank] => 2
        )

  [1] => Array
        (
            [result] => Array
                (
                    [0] => Array
                        (
                            [type] => ZX
                            [id] => 3223
                            [name] => Danny

                        )

                    [1] => Array
                        (
                            [type] => QWER
                            [id] => 2323232
                            [name] => Cactus

                        )

                )

            [title] => Hot
            [rank] => 1
        )

[3]..
[4]..and son on
```

I would like to sort by rank, is there any quick sort method in PHP to do that?

答:
You can use the usort function:

```<code>function cmp($a, $b) {
    return $a['rank'] - $b['rank'];
}

$arr = /* your array */

usort($arr, "cmp");
</code>```

See it

To sort on rank in descending order (question asked in comments), you just reverse the order in the compare function:

```<code>function cmp($a, $b) {
    return $b['rank'] - $a['rank'];
           ^^           ^^
}
</code>```

Title: array sorting php

Body:
I've an array like this

Array
(

[0] => Array

        (
            [result] => Array
                (
                    [0] => Array
                        (
                            [type] => ABC
                            [id] => 123232
                            [name] => Apple

                        )

                    [1] => Array
                        (
                            [type] => DEF
                            [id] => 2323232
                            [name] => Banana

                        )

                )

            [title] => Cool
            [rank] => 2
        )

  [1] => Array
        (
            [result] => Array
                (
                    [0] => Array
                        (
                            [type] => ZX
                            [id] => 3223
                            [name] => Danny

                        )

                    [1] => Array
                        (
                            [type] => QWER
                            [id] => 2323232
                            [name] => Cactus

                        )

                )

            [title] => Hot
            [rank] => 1
        )

[3]..
[4]..and son on

I would like to sort by rank, is there any quick sort method in PHP to do that?

Body:
You can use the usort function:

function cmp($a, $b) {
    return $a['rank'] - $b['rank'];
}

$arr = /* your array */

usort($arr, "cmp");

See it

To sort on rank in descending order (question asked in comments), you just reverse the order in the compare function:

function cmp($a, $b) {
    return $b['rank'] - $a['rank'];
           ^^           ^^
}


问:
TypeError: undefined is not an object (evaluating 'events[genre][0]')
I'm trying to create a custom array but the for loop cannot evaluate events[genre][0].name as events has not been set yet due to the async nature of firebase. Is there any way to only execute the for loop once the data has been set or any workaround for this?</p>

```<code>const Finalized = (props) => {
  const [events, setEvents] = React.useState([]);
  const testEvents = ["arts", "leisure", "sports"];

  React.useEffect(() => {
    firebase
      .database()
      .ref("events")
      .once("value")
      .then((snapshot) => {
        setEvents(snapshot.val());
      });
  });

  let dataJson = {};
  for (i = 0; i < testEvents.length; i++) {
    let genre = testEvents[i];
    dataJson.time = "09:00";
    dataJson.title = "Event" + i;
    dataJson.description = <Text>{events[genre][0].name} </Text>;  //cannot be evaluated as undefined
  }
  console.log(dataJson);
</code>```

答:
First of all you must not execute the useEffect without any dependency specially since its sets a state within it, otherwise your App will go into an infinite loop

Secondly, you can have a loading state before actually using the resolved data

```<code>const Finalized = (props) => {
  const [events, setEvents] = React.useState([]);
  const [isLoading, setIsLoading] = React.useState(true);
  const testEvents = ["arts", "leisure", "sports"];

  React.useEffect(() => {
    firebase
      .database()
      .ref("events")
      .once("value")
      .then((snapshot) => {
        setEvents(snapshot.val());
        setIsLoading(false);
      });
  }, []); // executed on initial render

  if(isLoading) {
     return <div>Loading...</div>
  }
  let dataJson = {};
  for (i = 0; i < testEvents.length; i++) {
    let genre = testEvents[i];
    dataJson.time = "09:00";
    dataJson.title = "Event" + i;
    dataJson.description = <Text>{events[genre][0].name} </Text>;  //cannot be evaluated as undefined
  }
  console.log(dataJson);
</code>```

Body:
I'm trying to create a custom array but the for loop cannot evaluate events[genre][0].name as events has not been set yet due to the async nature of firebase. Is there any way to only execute the for loop once the data has been set or any workaround for this?

const Finalized = (props) => {
  const [events, setEvents] = React.useState([]);
  const testEvents = ["arts", "leisure", "sports"];

  React.useEffect(() => {
    firebase
      .database()
      .ref("events")
      .once("value")
      .then((snapshot) => {
        setEvents(snapshot.val());
      });
  });

  let dataJson = {};
  for (i = 0; i < testEvents.length; i++) {
    let genre = testEvents[i];
    dataJson.time = "09:00";
    dataJson.title = "Event" + i;
    dataJson.description = <Text>{events[genre][0].name} </Text>;  //cannot be evaluated as undefined
  }
  console.log(dataJson);

Body:
First of all you must not execute the useEffect without any dependency specially since its sets a state within it, otherwise your App will go into an infinite loop

Secondly, you can have a loading state before actually using the resolved data

const Finalized = (props) => {
  const [events, setEvents] = React.useState([]);
  const [isLoading, setIsLoading] = React.useState(true);
  const testEvents = ["arts", "leisure", "sports"];

  React.useEffect(() => {
    firebase
      .database()
      .ref("events")
      .once("value")
      .then((snapshot) => {
        setEvents(snapshot.val());
        setIsLoading(false);
      });
  }, []); // executed on initial render

  if(isLoading) {
     return <div>Loading...</div>
  }
  let dataJson = {};
  for (i = 0; i < testEvents.length; i++) {
    let genre = testEvents[i];
    dataJson.time = "09:00";
    dataJson.title = "Event" + i;
    dataJson.description = <Text>{events[genre][0].name} </Text>;  //cannot be evaluated as undefined
  }
  console.log(dataJson);


问:
Notify object references with some property changed
I need to notify object references with property changed, check the following code:

```<code>Public Class Symbol
    Implements INotifyPropertyChanged

    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

    Private Sub NotifyPropertyChanged(<Runtime.CompilerServices.CallerMemberName> Optional ByVal propertyName As String = Nothing)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
    End Sub

    Private _Price As Decimal
    Public Property Price() As Decimal
        Get
            Return _Price
        End Get
        Set(ByVal value As Decimal)
            If Not (value = _Price) Then
                _Price = value
                NotifyPropertyChanged()
            End If

        End Set
    End Property
End Class
</code>```

```<code>Public Class Position
    Public Symbol As Symbol

    Public Sub New(symbol As Symbol)
        Me.Symbol = symbol
    End Sub

    Public Sub PriceChanged()
        Debug.Print($"New Price {Symbol.Price}")
    End Sub

End Class
</code>```

How do I get the PriceChanged to start when Symbol price changed?

答:
The obvious solution is to declare the Symbol field WithEvents. You can then include that field in a Handles clause, just as you do with controls on a form. You can use the navigation bar at the top of the code window to generate the event handler, just as do with controls on a form:

Public Class Position

    Private WithEvents _symbol As Symbol

    Public Property Symbol As Symbol
        Get
            Return _symbol
        End Get
        Set
            _symbol = value
        End Set
    End Property

    Public Sub New(symbol As Symbol)
        Me.Symbol = symbol
    End Sub

    Public Sub Symbol_PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Handles _symbol.PropertyChanged
        Debug.Print($"New Price {Symbol.Price}")
    End Sub

End Class
```

I took the liberty of implementing the rest of the class properly too.

Body:
I need to notify object references with property changed, check the following code:

Public Class Symbol
    Implements INotifyPropertyChanged

    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

    Private Sub NotifyPropertyChanged(<Runtime.CompilerServices.CallerMemberName> Optional ByVal propertyName As String = Nothing)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
    End Sub

    Private _Price As Decimal
    Public Property Price() As Decimal
        Get
            Return _Price
        End Get
        Set(ByVal value As Decimal)
            If Not (value = _Price) Then
                _Price = value
                NotifyPropertyChanged()
            End If

        End Set
    End Property
End Class

Public Class Position
    Public Symbol As Symbol

    Public Sub New(symbol As Symbol)
        Me.Symbol = symbol
    End Sub

    Public Sub PriceChanged()
        Debug.Print($"New Price {Symbol.Price}")
    End Sub

End Class

How do I get the PriceChanged to start when Symbol price changed?

Body:
The obvious solution is to declare the Symbol field WithEvents. You can then include that field in a Handles clause, just as you do with controls on a form. You can use the navigation bar at the top of the code window to generate the event handler, just as do with controls on a form:

Public Class Position

    Private WithEvents _symbol As Symbol

    Public Property Symbol As Symbol
        Get
            Return _symbol
        End Get
        Set
            _symbol = value
        End Set
    End Property

    Public Sub New(symbol As Symbol)
        Me.Symbol = symbol
    End Sub

    Public Sub Symbol_PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Handles _symbol.PropertyChanged
        Debug.Print($"New Price {Symbol.Price}")
    End Sub

End Class

I took the liberty of implementing the rest of the class properly too.


问:
Find the sum of the first n num
I have an array with numbers. Find the sum of the first N elements to the first zero. Task must be completed with
Example: - summarize the first 3 elements, because next is the element with the number 0.</p>

答:
You could iterate with a short circuit and check the value and add the value if not zero.

This approach does not search for zero in advance and needs only a single loop in the worst case.

var array = [10, 20, 3, 0, 16, 35, 1],
    sum = 0;

array.every(v => (sum += v, v));

console.log(sum);```

Title: Find the sum of the first n num


问:
Resizing Window in Tkinter
I've tried searching at why I can't get the content to stay centered as I resize the window larger but not quite understanding what I'm doing wrong.

From what I understand setting a weight to columnconfigure and rowconfigure will scale how much the content expands with the window but currently the enlarging the window keeps the content in the top left, can someone please help me understand where I'm going wrong?

```<code>def calculate():
    try:
        numValue = 100*float(num.get())/8
        num.set(str("%.2f"%numValue))
    except ValueError:
        num.set("Please enter a positive integer")
        pass

num = StringVar()

num_entry = ttk.Entry(mainframe, width=20, textvariable=ozone)
num_entry.grid(column=2, row=1, sticky=(W, E))
num_entry.rowconfigure(0, weight=1)
num_entry.columnconfigure(0, weight=2)

ttk.Label(mainframe, text="Number:").grid(column=1, row=1, sticky=E)

ttk.Label(mainframe, textvariable=num).grid(column=2, row=7, sticky=(S))
ttk.Button(mainframe, width=20, text="Calculate Number", command=calculate).grid(column=2, row=5, sticky=W)

for child in mainframe.winfo_children():
    child.grid_configure(padx=5, pady=10)

root.mainloop()
</code>```

答:
Set rowconfigure and columnconfigure for your frame and root, not for entry and other widgets. You already put your widgets in frame, so don't use sticky.

```<code>(...)

mainframe = Frame(root, width=500, height=500, background='green')
mainframe.grid(row=0, column=0)
mainframe.grid_rowconfigure(0, weight=1)
mainframe.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)

num_entry = ttk.Entry(mainframe, width=20, textvariable='ozone')
num_entry.grid(column=2, row=1)
# num_entry.rowconfigure(0, weight=1) not like this
# num_entry.columnconfigure(0, weight=2)
(...)
</code>```

Title: Resizing Window in Tkinter

Body:
I've tried searching at why I can't get the content to stay centered as I resize the window larger but not quite understanding what I'm doing wrong.

From what I understand setting a weight to columnconfigure and rowconfigure will scale how much the content expands with the window but currently the enlarging the window keeps the content in the top left, can someone please help me understand where I'm going wrong?

def calculate():
    try:
        numValue = 100*float(num.get())/8
        num.set(str("%.2f"%numValue))
    except ValueError:
        num.set("Please enter a positive integer")
        pass

num = StringVar()

num_entry = ttk.Entry(mainframe, width=20, textvariable=ozone)
num_entry.grid(column=2, row=1, sticky=(W, E))
num_entry.rowconfigure(0, weight=1)
num_entry.columnconfigure(0, weight=2)

ttk.Label(mainframe, text="Number:").grid(column=1, row=1, sticky=E)

ttk.Label(mainframe, textvariable=num).grid(column=2, row=7, sticky=(S))
ttk.Button(mainframe, width=20, text="Calculate Number", command=calculate).grid(column=2, row=5, sticky=W)

for child in mainframe.winfo_children():
    child.grid_configure(padx=5, pady=10)

root.mainloop()

Body:
Set rowconfigure and columnconfigure for your frame and root, not for entry and other widgets. You already put your widgets in frame, so don't use sticky.

(...)

mainframe = Frame(root, width=500, height=500, background='green')
mainframe.grid(row=0, column=0)
mainframe.grid_rowconfigure(0, weight=1)
mainframe.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)

num_entry = ttk.Entry(mainframe, width=20, textvariable='ozone')
num_entry.grid(column=2, row=1)
# num_entry.rowconfigure(0, weight=1) not like this
# num_entry.columnconfigure(0, weight=2)
(...)


问:
Edit text according to select input
I'm developing an RFQ interface for an OTC desk. I try to return price for a specific cryptocurrency that is selected with <v-select>, I'm trying to send a GET request to price endpoint for selected cryptocurrency.

For example, if cryptocurrency is BTC I want the client to send a GET request to api.endpoint/price/BTCUSDT.

Select input:

```<code><v-select
 v-model="yousendselect"
 :items="itemsYouSend"
 :rules="[v => !!v || 'Item is required']"
 label="You send"
 required
></v-select>
</code>```

Items (cryptocurrencies):

```<code>      item: [
        'Bitcoin',
        'Ethereum',
        'Litecoin',
        'Ripple',
      ],
</code>```

```<code>Bitcoin => BTCUSDT
Ethereum => ETHUSDT
Litecoin => LTCUSDT
Ripple => XRPUSDT
</code>```

I find some sources that can help to send a GET request but I didn't figure how to send GET request to endpoint depending on select input.

Where price is going to take place is:

```<code><v-text-field
 v-model="yougetamount"
 label="{{ price }}"
 type="number"
 name="yougetamount"
 required
></v-text-field>
</code>```

答:
you can watch on your property yousendselect:

```<code>watch: {
yousendselect(value){
// check and make your request

}
}
</code>```

Title: Edit text according to select input

Body:
I'm developing an RFQ interface for an OTC desk. I try to return price for a specific cryptocurrency that is selected with <v-select>, I'm trying to send a GET request to price endpoint for selected cryptocurrency.

For example, if cryptocurrency is BTC I want the client to send a GET request to api.endpoint/price/BTCUSDT.

Select input:

<v-select
 v-model="yousendselect"
 :items="itemsYouSend"
 :rules="[v => !!v || 'Item is required']"
 label="You send"
 required
></v-select>

Items (cryptocurrencies):

      item: [
        'Bitcoin',
        'Ethereum',
        'Litecoin',
        'Ripple',
      ],

Bitcoin => BTCUSDT
Ethereum => ETHUSDT
Litecoin => LTCUSDT
Ripple => XRPUSDT

I find some sources that can help to send a GET request but I didn't figure how to send GET request to endpoint depending on select input.

Where price is going to take place is:

<v-text-field
 v-model="yougetamount"
 label="{{ price }}"
 type="number"
 name="yougetamount"
 required
></v-text-field>

Body:
you can watch on your property yousendselect:

watch: {
yousendselect(value){
// check and make your request

}
}


问:
Is x.224 specification freely available?
I need to implement a simple probe that uses "open" microsoft rdp protocol. But that protocol refers to x.224 specification and ITU want money in order to download it. Is it any free version of x.224 protocol available?</p>

答:
X.244 is not a RDP Protocol, RDP is a MS protocol like ICA used by Citrix.

When you will perform a RDP connection, MS use this protocol to connect to the servers.

I took the sniffing when performing RDP to MS 2003 / 2008 to confirm the same.

39 12:12:56 10.130.35.164 10.130.35.226 X.224 Connection Request (0xe0)

41 12:12:56 10.130.35.226 10.130.35.164 X.224 Connection Confirm (0xd0)

293 12:13:30 10.130.35.164 10.130.35.226 X.224 Connection Request (0xe0)

295 12:13:30 10.130.35.226 10.130.35.164 X.224 Connection Confirm (0xd0)

Hope this helps..

Cheers!!

Dhruv

ContentLicense: CC BY-SA 2.5


问:
Cannot layout CALayer frame correctly
I'm trying to set the frame of some CALayers but when I run this code they appear shifted to the right.

The frame coordinates and the shadows are correct.
I use this class as a UIView class from a view in storyboard.

```<code>class Shadows: UIView {

    let darkShadow = CALayer()
    let lightShadow = CALayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    override func layoutSublayers(of layer: CALayer) {
        super.layoutSublayers(of: layer)
        shadows()
    }

    private func shadows() {
        let cornerRadius: CGFloat = 30
        let shadowRadius: CGFloat = 8

        layer.cornerRadius = cornerRadius
        layer.masksToBounds = false

        darkShadow.frame = frame
        darkShadow.backgroundColor = UIColor.white.cgColor
        darkShadow.shadowColor = UIColor.black.cgColor
        darkShadow.cornerRadius = cornerRadius
        darkShadow.shadowOffset = CGSize(width: shadowRadius, height: shadowRadius)
        darkShadow.shadowOpacity = 0.2
        darkShadow.shadowRadius = shadowRadius
        layer.insertSublayer(darkShadow, at: 0)

        lightShadow.frame = frame
        lightShadow.backgroundColor = UIColor.white.cgColor
        lightShadow.shadowColor = UIColor.white.cgColor
        lightShadow.cornerRadius = cornerRadius
        lightShadow.shadowOffset = CGSize(width: -shadowRadius, height: -shadowRadius)
        lightShadow.shadowOpacity = 0.7
        lightShadow.shadowRadius = shadowRadius
        layer.insertSublayer(lightShadow, at: 0)
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
}
</code>```

答:
Here is the simple fix for your issue provide the bounds instead of the frame as the frame for the CALayer, here's how:

darkShadow.frame = bounds
```

To understand how this works you need to know the basics of UIKit layout and the difference between frame and bounds (You might wanna google this). In simple words, frame is the coordinates of the view with respect to super and bounds is with respect to itself.

Note: (I'm adding this here just as a guideline) It's a common beginner mistake. There are plenty of online resources that explain the difference between frame and bounds. Although you might find it a bit overwhelming in the beginning you will get to know the difference eventually. Here are the ones I found useful and could be helpful for you as well :- Youtube Video of Saun Alen and Article from hacking with swift.

Title: Cannot layout CALayer frame correctly

Body:
I'm trying to set the frame of some CALayers but when I run this code they appear shifted to the right.

The frame coordinates and the shadows are correct.
I use this class as a UIView class from a view in storyboard.

class Shadows: UIView {

    let darkShadow = CALayer()
    let lightShadow = CALayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    override func layoutSublayers(of layer: CALayer) {
        super.layoutSublayers(of: layer)
        shadows()
    }

    private func shadows() {
        let cornerRadius: CGFloat = 30
        let shadowRadius: CGFloat = 8

        layer.cornerRadius = cornerRadius
        layer.masksToBounds = false

        darkShadow.frame = frame
        darkShadow.backgroundColor = UIColor.white.cgColor
        darkShadow.shadowColor = UIColor.black.cgColor
        darkShadow.cornerRadius = cornerRadius
        darkShadow.shadowOffset = CGSize(width: shadowRadius, height: shadowRadius)
        darkShadow.shadowOpacity = 0.2
        darkShadow.shadowRadius = shadowRadius
        layer.insertSublayer(darkShadow, at: 0)

        lightShadow.frame = frame
        lightShadow.backgroundColor = UIColor.white.cgColor
        lightShadow.shadowColor = UIColor.white.cgColor
        lightShadow.cornerRadius = cornerRadius
        lightShadow.shadowOffset = CGSize(width: -shadowRadius, height: -shadowRadius)
        lightShadow.shadowOpacity = 0.7
        lightShadow.shadowRadius = shadowRadius
        layer.insertSublayer(lightShadow, at: 0)
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
}

Body:
Here is the simple fix for your issue provide the bounds instead of the frame as the frame for the CALayer, here's how:

darkShadow.frame = bounds

To understand how this works you need to know the basics of UIKit layout and the difference between frame and bounds (You might wanna google this). In simple words, frame is the coordinates of the view with respect to super and bounds is with respect to itself.

Note: (I'm adding this here just as a guideline) It's a common beginner mistake. There are plenty of online resources that explain the difference between frame and bounds. Although you might find it a bit overwhelming in the beginning you will get to know the difference eventually. Here are the ones I found useful and could be helpful for you as well :- Youtube Video of Saun Alen and Article from hacking with swift.


问:
Is there a way to schedule a post on gatsby?
I'm using gatsby-transformer-remark on gatsbyjs to create posts and I want to schedule some post. Can this be done?</p>

答:
I see two main ways of doing this. Either rebuild the site on a schedule or hide the posts in your UI code (I wouldn't recommend that, but might be easier to do):

Have a cron job every X minutes that will build & deploy your Gatsby site. In your build logic (most likely your code at gatsby-node.js) only build pages / posts that you want to go live at the given time of the build. Using filtering on your GraphQL query, you could only build posts that have a publication date equal or superior to the current time.

In your posts, using a "publicationDate" field (name is up to you), set that field for when you want the blog post to go live and in your app hide any posts that aren't supposed to be live. This will kinda work, but posts will still exist and if you have a sitemap for example, they'll show there.


问:
What should be the data type of field 'email' in Postgresql database in pgadmin 4?
You can see that I am getting 'No results found' when searching for varchar.

I need to know the data type that I should select for 'email' in postgresql database.

答: In the past I used text or varchar or character varying


问:
Time complexity of Python Function Involving List Operations
When I plot the time taken for the following algorithm for different size input, the time complexity appears to be polynomial. I'm not sure which operations account for this.

I'm assuming it's to do with list(s), del l[i] and l[::-1], but I'm not clear what the complexity of these is individually. Can anyone please explain?

Also, is there a way to optimize the algorithm without completely changing the approach? (I know there is a way to bring it down to linear time complexity by using "double-ended pincer-movement".)

```<code>def palindrome_index(s):
    for i, c in enumerate(s):
        l = list(s)
        del l[i]
        if l[::-1] == l:
            return i
    return -1
</code>```

答:
All of these are linear "O(n)":

```<code>list(s)
</code>```

list(s) creates a new list from s. To do that, it has to go through all elements in s, so its time is proportional to the length of s.

```<code>l[::-1]
</code>```

Just like list(s), l[::-1] creates a new list with the same elements as l, but in different order. It has to touch each element once, so its time is proportional to the length of l.

```<code>del l[i]
</code>```

In order to delete an element at position i, the element which was at position i+1 has to be moved to position i, then element which was at i+2 has to be moved to position i+1 etc. So, if you are deleting the first element (del l[0]), it has to touch move elements of the list and if you are deleting the last (del l[-1]), it just has to remove the last. On average, it will move n/2 elements, so it is also linear.

Body:
When I plot the time taken for the following algorithm for different size input, the time complexity appears to be polynomial. I'm not sure which operations account for this.

I'm assuming it's to do with list(s), del l[i] and l[::-1], but I'm not clear what the complexity of these is individually. Can anyone please explain?

Also, is there a way to optimize the algorithm without completely changing the approach? (I know there is a way to bring it down to linear time complexity by using "double-ended pincer-movement".)

def palindrome_index(s):
    for i, c in enumerate(s):
        l = list(s)
        del l[i]
        if l[::-1] == l:
            return i
    return -1

Body:
All of these are linear "O(n)":

list(s)

list(s) creates a new list from s. To do that, it has to go through all elements in s, so its time is proportional to the length of s.

l[::-1]

Just like list(s), l[::-1] creates a new list with the same elements as l, but in different order. It has to touch each element once, so its time is proportional to the length of l.

del l[i]

In order to delete an element at position i, the element which was at position i+1 has to be moved to position i, then element which was at i+2 has to be moved to position i+1 etc. So, if you are deleting the first element (del l[0]), it has to touch move elements of the list and if you are deleting the last (del l[-1]), it just has to remove the last. On average, it will move n/2 elements, so it is also linear.


问:
How to make the non visible part of a Gallery to be null
I have used gallery widget to display downloaded images.But unfortunately I am running into out of memory situation. So I am trying to null the invisible part of the gallery so that I can save my memory. Is it possible to hide the non visible parts of the gallery.
Any help is appreciated.</p>

答:
Memory Issues is not because of Gallery, its because of adapter I guess that you are using Gallery itself use concept of recycling views that are non visible so its not responsible for out of memory.

What I think is you are creating an adapter of bitmaps and that is what causing errors.


问:
Remove everything after the first whitespace in pandas dataframe
Here is the dataframe:

```<code>     State  RegionName
0    NY     New York
1    CA     Los Angeles
2    IL     Chicago 865
3    PA     Philadelphia Wrin
4    AZ     Phoenix City
</code>```

I want the output to look like this:

```<code>     State   RegionName
0    NY      New
1    CA      Los
2    IL      Chicago
3    PA      Philadelphia
4    AZ      Phoenix
</code>```

How to do it without using for loops ??

答:
You can replace extra words by '' using str.replace

```<code>df["RegionName"] = df.RegionName.str.replace('\s.*','')
df
     RegionName state
0           New    NY
1           Los    CA
2       Chicago    IL
3  Philadelphia    PA
4       Phoenix    AZ
</code>```

Body:
Here is the dataframe:

     State  RegionName
0    NY     New York
1    CA     Los Angeles
2    IL     Chicago 865
3    PA     Philadelphia Wrin
4    AZ     Phoenix City

I want the output to look like this:

     State   RegionName
0    NY      New
1    CA      Los
2    IL      Chicago
3    PA      Philadelphia
4    AZ      Phoenix

How to do it without using for loops ??

Body:
You can replace extra words by '' using str.replace

df["RegionName"] = df.RegionName.str.replace('\s.*','')
df
     RegionName state
0           New    NY
1           Los    CA
2       Chicago    IL
3  Philadelphia    PA
4       Phoenix    AZ


问:
Wrap every letter in a span by JS, But except some character, & they must be add with just first one letter?
i want to Wrap every letter in a span, But except some character (#, -, @,), But they must be add with just first one letter?

For Examplet my line is :

A Man Walks-3 Km daily from his#Bicycle@His hometown surroun-near.

& After split charactors into span tag by JS, it looks like this: Okay

|A| |M|a|n| |W|a|l|k|s|-|3| |K|m |d|a|i|l|y| |f|r|o|m |h|i|s|#|B|i|c|y|c|l|e|@|H|i|s| |h|o|m|e|t|o|w|n| |s|u|r|r|o|u|n|-|n|e|a|r|.|

But i want to skip (-, #, @) to with just first one letter like after  the split will be like :

|A| |M|a|n| |W|a|l|k|s-|3| |K|m |d|a|i|l|y| |f|r|o|m |h|i|s#|B|i|c|y|c|l|e@|H|i|s| |h|o|m|e|t|o|w|n| |s|u|r|r|o|u|n-|n|e|a|r.|

Here is my CodePen: https://codepen.io/rksbhl/pen/KKdOrbo

This is Complete code:

```<code>    <style>
        .rks1 {
font-weight: 900;
font-size: 2.5em;
font-family: rr;
}

.rks1 .letter {
display: inline-block;
line-height: 1em;
border: 1px solid gray;
}

.word {
background-color: #CFF;
white-space: nowrap;
}

.span {
border: 1px solid red;
}
    </style>

<h1 class="rks1">A Man Walks-3 Km daily from his #Bicycle @His hometown surroun-near.</h1>

    <script type="text/javascript">
        // Wrap every letter in a span
 var textWrapper = document.querySelector('.rks1');
textWrapper.innerHTML = textWrapper.textContent.replace(/(\S*)/g, function(m) {
  return `<span class="word">`
    + m.replace(/\S/g, "<span class='letter'>$&</span>")
    + `</span>`;
});
    </script>

</code>```

i want this result as like this:

答:
You can change your inner regex from \S to \S(-|#|@)? to also take an optional char that is -, # or @ (or any more you want to add, separated with |)

Before that though, you want to catch space+char and swap them to make them move from the previous word with something like .replace(/ (-|#|@){1}/g, s => s[1]+s[0])

// Wrap every letter in a span
var textWrapper = document.querySelector('.rks1');

textWrapper.innerHTML = textWrapper.textContent.replace(/ (-|#|@){1}/g, s => s[1]+s[0]).replace(/(\S*)/g, m => {
  return `<span class="word">` +
    m.replace(/\S(-|#|@)?/g, "$&") +
    `</span>`;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.rks1 {
  font-weight: 900;
  font-size: 2.5em;
  font-family: rr;
}

.rks1 .letter {
  display: inline-block;
  line-height: 1em;
  border: 1px solid gray;
}

.word {
  background-color: #CFF;
  white-space: nowrap;
}

.span {
  border: 1px solid red;
}</code>```

A Man Walks-3 Km daily from his #Bicycle @His hometown surroun-near.
```
</div>
</div>
</p>

<p>Version 2 as requested:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Wrap every letter in a span
var textWrapper = document.querySelector('.rks1');

textWrapper.innerHTML = textWrapper.textContent.replace(/(\S*)/g, m => {
  return `<span class="word">` +
    m.replace(/(-|#|@)?\S(-|#|@)?/g, "<span class='letter'>$&</span>") +
    `</span>`;
});</code>```

.rks1 {
  font-weight: 900;
  font-size: 2.5em;
  font-family: rr;
}

.rks1 .letter {
  display: inline-block;
  line-height: 1em;
  border: 1px solid gray;
}

.word {
  background-color: #CFF;
  white-space: nowrap;
}

.span {
  border: 1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>

<h1 class="rks1">A Man Walks-3 Km daily from his #Bicycle @His hometown surroun-near.</h1></code>```

Body:
i want to Wrap every letter in a span, But except some character (#, -, @,), But they must be add with just first one letter?

For Examplet my line is :

A Man Walks-3 Km daily from his#Bicycle@His hometown surroun-near.

& After split charactors into span tag by JS, it looks like this: Okay

|A| |M|a|n| |W|a|l|k|s|-|3| |K|m |d|a|i|l|y| |f|r|o|m |h|i|s|#|B|i|c|y|c|l|e|@|H|i|s| |h|o|m|e|t|o|w|n| |s|u|r|r|o|u|n|-|n|e|a|r|.|

But i want to skip (-, #, @) to with just first one letter like after  the split will be like :

|A| |M|a|n| |W|a|l|k|s-|3| |K|m |d|a|i|l|y| |f|r|o|m |h|i|s#|B|i|c|y|c|l|e@|H|i|s| |h|o|m|e|t|o|w|n| |s|u|r|r|o|u|n-|n|e|a|r.|

Here is my CodePen: https://codepen.io/rksbhl/pen/KKdOrbo

This is Complete code:

A Man Walks-3 Km daily from his #Bicycle @His hometown surroun-near.

i want this result as like this:

Body:
You can change your inner regex from \S to \S(-|#|@)? to also take an optional char that is -, # or @ (or any more you want to add, separated with |)

Before that though, you want to catch space+char and swap them to make them move from the previous word with something like .replace(/ (-|#|@){1}/g, s => s[1]+s[0])

// Wrap every letter in a span
var textWrapper = document.querySelector('.rks1');

textWrapper.innerHTML = textWrapper.textContent.replace(/ (-|#|@){1}/g, s => s[1]+s[0]).replace(/(\S*)/g, m => {
  return `<span class="word">` +
    m.replace(/\S(-|#|@)?/g, "<span class='letter'>$&</span>") +
    `</span>`;
});

.rks1 {
  font-weight: 900;
  font-size: 2.5em;
  font-family: rr;
}

.rks1 .letter {
  display: inline-block;
  line-height: 1em;
  border: 1px solid gray;
}

.word {
  background-color: #CFF;
  white-space: nowrap;
}

.span {
  border: 1px solid red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>

<h1 class="rks1">A Man Walks-3 Km daily from his #Bicycle @His hometown surroun-near.</h1>

Version 2 as requested:

// Wrap every letter in a span
var textWrapper = document.querySelector('.rks1');

textWrapper.innerHTML = textWrapper.textContent.replace(/(\S*)/g, m => {
  return `<span class="word">` +
    m.replace(/(-|#|@)?\S(-|#|@)?/g, "<span class='letter'>$&</span>") +
    `</span>`;
});

.rks1 {
  font-weight: 900;
  font-size: 2.5em;
  font-family: rr;
}

.rks1 .letter {
  display: inline-block;
  line-height: 1em;
  border: 1px solid gray;
}

.word {
  background-color: #CFF;
  white-space: nowrap;
}

.span {
  border: 1px solid red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>

<h1 class="rks1">A Man Walks-3 Km daily from his #Bicycle @His hometown surroun-near.</h1>


问:
How can I divide (y) ticks into left and right sides accroding their values to make it visible?
I have this visualization:

And the problem is this: I need to divide y ticks into two groups to see them clearly.

I could use major and minor ticks, but then I wouldn't see all values.

I know that I can just plot it without plt.yticks(), but as I said before, all values must be on the plot.

Is it real to do such thing via build-in tool(-s)?

答:
On the Y axis leave rather default labels.
Your image is clutterer partially also with Y ticks, as I suppose,
copied from the source values. So it is better not to mess around with
ticks (especially not the way you did it).

If you want to precisely indicate the height of each bar, use
annotations. Something like:

```<code>ax = s.plot.bar(rot=0, width=0.7)
ax.set_ylim(0, s.max() * 1.15)
for p in ax.patches:
    w = p.get_height()
    ax.annotate(f'{w:.2f}', xy=(p.get_x() + p.get_width() / 2, w + 3),
        ha='center')
</code>```

For the above code and data roughly similar to yours I got:

Body:
On the Y axis leave rather default labels.
Your image is clutterer partially also with Y ticks, as I suppose,
copied from the source values. So it is better not to mess around with
ticks (especially not the way you did it).

If you want to precisely indicate the height of each bar, use
annotations. Something like:

ax = s.plot.bar(rot=0, width=0.7)
ax.set_ylim(0, s.max() * 1.15)
for p in ax.patches:
    w = p.get_height()
    ax.annotate(f'{w:.2f}', xy=(p.get_x() + p.get_width() / 2, w + 3),
        ha='center')

For the above code and data roughly similar to yours I got:


问:
Question regarding multi-threaded environment of servlet
If there is a servlet, inside a servlet container such as Websphere. The servlet are executed by some threads. I would like to ask, what does the threads share? How variables are shared between them?

Do they have a local copy of the following variables?

1) private/protected/public final Semaphore permits = new Semaphore(50);

2) private/protected/public final static Semaphore permits = new Semaphore(50);

3) private/protected/public Semaphore permits = new Semaphore(50);

4) private/protected/public static Semaphore permits = new Semaphore(50);

How should I declare the semaphore so that I can use semaphore to control them? I don't want them to have each of them a copy of the semaphore. Thanks.

答: Servlets should be threadsafe. Meaning if they have any state, they should be synchronized. Try avoiding saving some state inside servlets. They should contain only business/controller logic. Any state you want to save, put them in servletcontext/request/session which are synchronized by the container.</p>


问:
How to prevent sqlite3 to Auto-Increment the Primary Key if Null value is specified?
So, I am creating a simple GUI in Python using Tkinter.

Now, when the user leaves the Roll Number (i.e. primary key) label widget empty and tries to insert the data, I will be inserting None instead of an empty string and I want to throw an Error but instead the data gets inserted with an auto-incremented Roll Number value. I don't want the Primary Key to get inserted if the Roll Number label widget is left empty.

This the code I am using for Creating the Table

```<code>c.execute("""
    CREATE TABLE students(
    enroll_no integer NOT NULL PRIMARY KEY,
    first_name text NOT NULL,
    middle_name text,
    last_name text,
    course text NOT NULL,
    semester integer NOT NULL
    )
""")
</code>```

And this the code for Inserting into the Table

```<code>    try:
        c.execute("INSERT INTO students VALUES (:inp_rn, :inp_fn, :inp_mn, :inp_ln, :inp_course, :inp_semester)",
            {
                'inp_rn':inp_rn.get() if inp_rn.get() != "" else None,
                'inp_fn':inp_fn.get() if inp_fn.get() != "" else None,
                'inp_mn':inp_mn.get() if inp_mn.get() != "" else None,
                'inp_ln':inp_ln.get() if inp_ln.get() != "" else None,
                'inp_course':inp_course.get() if inp_course.get() != "" else None,
                'inp_semester':inp_semester.get() if inp_semester.get() != "" else None
            }
        )
    except sqlite3.IntegrityError:
        messagebox.showerror("Insertion Failed","Insertion Failed")
</code>```

答:
Use a simple if, else statement to tackle this error. Let entrybox related to roll no. be e1. Paste all the blocks of database after and paste it below else block, Please consider upvoting too

```<code>if e1.get() == '':
   messagebox.showerror('Please Fill','Please specify roll number to proceed')
else:
................
................
</code>```

To simply check if an a variable is int() or not, you can use .isdigit() which returns a boolean. First assign a variable to your e1.get() then follow as here. Remeber that only pure digit can be used, any use of hyphen(-) or special characters will result in execution of else block :)

```<code>checking = e1.get()
if checking.isdigit() == True:
    .........
else:
    messagebox.showerror('Integrity Error','It must be a integer')
</code>```

OwnerDisplayName: anon

Body:
So, I am creating a simple GUI in Python using Tkinter.

Now, when the user leaves the Roll Number (i.e. primary key) label widget empty and tries to insert the data, I will be inserting None instead of an empty string and I want to throw an Error but instead the data gets inserted with an auto-incremented Roll Number value. I don't want the Primary Key to get inserted if the Roll Number label widget is left empty.

This the code I am using for Creating the Table

c.execute("""
    CREATE TABLE students(
    enroll_no integer NOT NULL PRIMARY KEY,
    first_name text NOT NULL,
    middle_name text,
    last_name text,
    course text NOT NULL,
    semester integer NOT NULL
    )
""")

And this the code for Inserting into the Table

    try:
        c.execute("INSERT INTO students VALUES (:inp_rn, :inp_fn, :inp_mn, :inp_ln, :inp_course, :inp_semester)",
            {
                'inp_rn':inp_rn.get() if inp_rn.get() != "" else None,
                'inp_fn':inp_fn.get() if inp_fn.get() != "" else None,
                'inp_mn':inp_mn.get() if inp_mn.get() != "" else None,
                'inp_ln':inp_ln.get() if inp_ln.get() != "" else None,
                'inp_course':inp_course.get() if inp_course.get() != "" else None,
                'inp_semester':inp_semester.get() if inp_semester.get() != "" else None
            }
        )
    except sqlite3.IntegrityError:
        messagebox.showerror("Insertion Failed","Insertion Failed")

Body:
Use a simple if, else statement to tackle this error. Let entrybox related to roll no. be e1. Paste all the blocks of database after and paste it below else block, Please consider upvoting too

if e1.get() == '':
   messagebox.showerror('Please Fill','Please specify roll number to proceed')
else:
................
................

To simply check if an a variable is int() or not, you can use .isdigit() which returns a boolean. First assign a variable to your e1.get() then follow as here. Remeber that only pure digit can be used, any use of hyphen(-) or special characters will result in execution of else block :)

checking = e1.get()
if checking.isdigit() == True:
    .........
else:
    messagebox.showerror('Integrity Error','It must be a integer')


问:
terminal partitioning for each of subprocesses prints
Say we have multiple subprocesses like the following which has some results printed in real time to sys.stdout or sys.stderr.

```<code>proc1 = subprocess.Popen(['cmd1'],
                         env=venv1,
                         stdout=sys.stdout,
                         stderr=sys.stderr,
                         )

proc2 = subprocess.Popen(['cmd2'],
                         env=venv2,
                         stdout=sys.stdout,
                         stderr=sys.stderr,
                         )
</code>```

However, after executing this script in the terminal, while looking at what is being printed, it is not easy to distinguish which print is from the first process and which is from the second.

Is there a solution for this to see the stdout of each process separately, like if the terminal screen could be partitioned and each partition would have shown the printing results from each process?

答:
I have written for you a curses application which will do what you request: divide the terminal window into a number of partitions and then watch the different output streams in the different partitions.

The function watch_fd_in_panes will take a list of lists, where the sub-lists specify which file descriptors to watch inside each partition.

Here is what your example calling code will look like:

```<code>import subprocess
from watcher import watch_fds_in_panes

proc1 = subprocess.Popen('for i in `seq 30`; do date; sleep 1 ; done',
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         )

# this process also writes something on stderr
proc2 = subprocess.Popen('ls -l /asdf; for i in `seq 20`; do echo $i; sleep 0.5; done',
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         )

proc3 = subprocess.Popen(['echo', 'hello'],
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         )

try:
    watch_fds_in_panes([[proc1.stdout.fileno(), proc1.stderr.fileno()],
                        [proc2.stdout.fileno(), proc2.stderr.fileno()],
                        [proc3.stdout.fileno(), proc3.stderr.fileno()]],
                       sleep_at_end=3.)
except KeyboardInterrupt:
    print("interrupted")
    proc1.kill()
    proc2.kill()
    proc3.kill()
</code>```

To run it you will need these two files:

panes.py

```<code>import curses

class Panes:
    """
    curses-based app that divides the screen into a number of scrollable
    panes and lets the caller write text into them
    """

    def start(self, num_panes):
        "set up the panes and initialise the app"

        # curses init
        self.num = num_panes
        self.stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()

        # split the screen into number of panes stacked vertically,
        # drawing some horizontal separator lines
        scr_height, scr_width = self.stdscr.getmaxyx()
        div_ys = [scr_height * i // self.num for i in range(1, self.num)]
        for y in div_ys:
            self.stdscr.addstr(y, 0, '-' * scr_width)
        self.stdscr.refresh()

        # 'boundaries' contains y coords of separator lines including notional
        # separator lines above and below everything, and then the panes
        # occupy the spaces between these
        boundaries = [-1] + div_ys + [scr_height]
        self.panes = []
        for i in range(self.num):
            top = boundaries[i] + 1
            bottom = boundaries[i + 1] - 1
            height = bottom - top + 1
            width = scr_width
            # create a scrollable pad for this pane, of height at least
            # 'height' (could be more to retain some scrollback history)
            pad = curses.newpad(height, width)
            pad.scrollok(True)
            self.panes.append({'pad': pad,
                               'coords': [top, 0, bottom, width],
                               'height': height})

    def write(self, pane_num, text):
        "write text to the specified pane number (from 0 to num_panes-1)"

        pane = self.panes[pane_num]
        pad = pane['pad']
        y, x = pad.getyx()
        pad.addstr(y, x, text)
        y, x = pad.getyx()
        view_top = max(y - pane['height'], 0)
        pad.refresh(view_top, 0, *pane['coords'])

    def end(self):
        "restore the original terminal behaviour"

        curses.nocbreak()
        self.stdscr.keypad(0)
        curses.echo()
        curses.endwin()
</code>```

and watcher.py

```<code>import os
import select
import time

from panes import Panes

def watch_fds_in_panes(fds_by_pane, sleep_at_end=0):
    """
    Use panes to watch output from a number of fds that are writing data.

    fds_by_pane contains a list of lists of fds to watch in each pane.
    """
    panes = Panes()
    npane = len(fds_by_pane)
    panes.start(npane)
    pane_num_for_fd = {}
    active_fds = []
    data_tmpl = {}
    for pane_num, pane_fds in enumerate(fds_by_pane):
        for fd in pane_fds:
            active_fds.append(fd)
            pane_num_for_fd[fd] = pane_num
            data_tmpl[fd] = bytes()
    try:
        while active_fds:
            all_data = data_tmpl.copy()
            timeout = None
            while True:
                fds_read, _, _ = select.select(active_fds, [], [], timeout)
                timeout = 0
                if fds_read:
                    for fd in fds_read:
                        data = os.read(fd, 1)
                        if data:
                            all_data[fd] += data
                        else:
                            active_fds.remove(fd)  # saw EOF
                else:
                    # no more data ready to read
                    break
            for fd, data in all_data.items():
                if data:
                    strng = data.decode('utf-8')
                    panes.write(pane_num_for_fd[fd], strng)
    except KeyboardInterrupt:
        panes.end()
        raise

    time.sleep(sleep_at_end)
    panes.end()
</code>```

Finally, here is a screenshot of the above code in action:

In this example, we are monitoring both stdout and stderr of each process in the relevant partition.  In the screenshot, the line that proc2 wrote to stderr before the start of the loop (regarding /asdf) has appeared after the first line that proc2 wrote to stdout during the first iteration of the loop (i.e. the 1 which has since scrolled off the top of the partition), but this is cannot be controlled because they were written to different pipes.

Body:
Say we have multiple subprocesses like the following which has some results printed in real time to sys.stdout or sys.stderr.

proc1 = subprocess.Popen(['cmd1'],
                         env=venv1,
                         stdout=sys.stdout,
                         stderr=sys.stderr,
                         )

proc2 = subprocess.Popen(['cmd2'],
                         env=venv2,
                         stdout=sys.stdout,
                         stderr=sys.stderr,
                         )

However, after executing this script in the terminal, while looking at what is being printed, it is not easy to distinguish which print is from the first process and which is from the second.

Is there a solution for this to see the stdout of each process separately, like if the terminal screen could be partitioned and each partition would have shown the printing results from each process?

Body:
I have written for you a curses application which will do what you request: divide the terminal window into a number of partitions and then watch the different output streams in the different partitions.

The function watch_fd_in_panes will take a list of lists, where the sub-lists specify which file descriptors to watch inside each partition.

Here is what your example calling code will look like:

import subprocess
from watcher import watch_fds_in_panes

proc1 = subprocess.Popen('for i in `seq 30`; do date; sleep 1 ; done',
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         )

# this process also writes something on stderr
proc2 = subprocess.Popen('ls -l /asdf; for i in `seq 20`; do echo $i; sleep 0.5; done',
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         )

proc3 = subprocess.Popen(['echo', 'hello'],
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         )

try:
    watch_fds_in_panes([[proc1.stdout.fileno(), proc1.stderr.fileno()],
                        [proc2.stdout.fileno(), proc2.stderr.fileno()],
                        [proc3.stdout.fileno(), proc3.stderr.fileno()]],
                       sleep_at_end=3.)
except KeyboardInterrupt:
    print("interrupted")
    proc1.kill()
    proc2.kill()
    proc3.kill()

To run it you will need these two files:

panes.py

import curses

class Panes:
    """
    curses-based app that divides the screen into a number of scrollable
    panes and lets the caller write text into them
    """

    def start(self, num_panes):
        "set up the panes and initialise the app"

        # curses init
        self.num = num_panes
        self.stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()

        # split the screen into number of panes stacked vertically,
        # drawing some horizontal separator lines
        scr_height, scr_width = self.stdscr.getmaxyx()
        div_ys = [scr_height * i // self.num for i in range(1, self.num)]
        for y in div_ys:
            self.stdscr.addstr(y, 0, '-' * scr_width)
        self.stdscr.refresh()

        # 'boundaries' contains y coords of separator lines including notional
        # separator lines above and below everything, and then the panes
        # occupy the spaces between these
        boundaries = [-1] + div_ys + [scr_height]
        self.panes = []
        for i in range(self.num):
            top = boundaries[i] + 1
            bottom = boundaries[i + 1] - 1
            height = bottom - top + 1
            width = scr_width
            # create a scrollable pad for this pane, of height at least
            # 'height' (could be more to retain some scrollback history)
            pad = curses.newpad(height, width)
            pad.scrollok(True)
            self.panes.append({'pad': pad,
                               'coords': [top, 0, bottom, width],
                               'height': height})

    def write(self, pane_num, text):
        "write text to the specified pane number (from 0 to num_panes-1)"

        pane = self.panes[pane_num]
        pad = pane['pad']
        y, x = pad.getyx()
        pad.addstr(y, x, text)
        y, x = pad.getyx()
        view_top = max(y - pane['height'], 0)
        pad.refresh(view_top, 0, *pane['coords'])

    def end(self):
        "restore the original terminal behaviour"

        curses.nocbreak()
        self.stdscr.keypad(0)
        curses.echo()
        curses.endwin()

and watcher.py

import os
import select
import time

from panes import Panes

def watch_fds_in_panes(fds_by_pane, sleep_at_end=0):
    """
    Use panes to watch output from a number of fds that are writing data.

    fds_by_pane contains a list of lists of fds to watch in each pane.
    """
    panes = Panes()
    npane = len(fds_by_pane)
    panes.start(npane)
    pane_num_for_fd = {}
    active_fds = []
    data_tmpl = {}
    for pane_num, pane_fds in enumerate(fds_by_pane):
        for fd in pane_fds:
            active_fds.append(fd)
            pane_num_for_fd[fd] = pane_num
            data_tmpl[fd] = bytes()
    try:
        while active_fds:
            all_data = data_tmpl.copy()
            timeout = None
            while True:
                fds_read, _, _ = select.select(active_fds, [], [], timeout)
                timeout = 0
                if fds_read:
                    for fd in fds_read:
                        data = os.read(fd, 1)
                        if data:
                            all_data[fd] += data
                        else:
                            active_fds.remove(fd)  # saw EOF
                else:
                    # no more data ready to read
                    break
            for fd, data in all_data.items():
                if data:
                    strng = data.decode('utf-8')
                    panes.write(pane_num_for_fd[fd], strng)
    except KeyboardInterrupt:
        panes.end()
        raise

    time.sleep(sleep_at_end)
    panes.end()

Finally, here is a screenshot of the above code in action:

In this example, we are monitoring both stdout and stderr of each process in the relevant partition.  In the screenshot, the line that proc2 wrote to stderr before the start of the loop (regarding /asdf) has appeared after the first line that proc2 wrote to stdout during the first iteration of the loop (i.e. the 1 which has since scrolled off the top of the partition), but this is cannot be controlled because they were written to different pipes.


问:
Mongoose schema + nodejs
I'm kinda new in mongodb and i'm in trouble
I can't reach a data from my mongo database

```<code>const mongoose = require('mongoose');

const Team = new mongoose.Schema({
    name: String,
});

const MatchsSchema = new mongoose.Schema({
    begin_at: Date,
    number_of_games: Number,
    name: String,
    tournament: {
        name: String,
    },
    opponents: {
        type: [Team],
        default: undefined
    },
});

const Matchs = mongoose.model('matchs', MatchsSchema);

module.exports = Matchs;
</code>```

I am trying to access with this code witch is return my "data" :

```<code>console.log(element.opponents[0]);
</code>```

data returned

but when i want to access with .name the value is undefined

```<code>console.log(element.opponents[0].name);
</code>```

database schema : db

I have an collection named "teams" in my db.
What is the problems ? I think i'm not that far...

答:
It might be an overlook but try...</p>

```<code>console.log(element.opponents[0].opponent.name);
</code>```

Title: Mongoose schema + nodejs

Body:
I'm kinda new in mongodb and i'm in trouble
I can't reach a data from my mongo database

const mongoose = require('mongoose');

const Team = new mongoose.Schema({
    name: String,
});

const MatchsSchema = new mongoose.Schema({
    begin_at: Date,
    number_of_games: Number,
    name: String,
    tournament: {
        name: String,
    },
    opponents: {
        type: [Team],
        default: undefined
    },
});

const Matchs = mongoose.model('matchs', MatchsSchema);

module.exports = Matchs;

I am trying to access with this code witch is return my "data" :

console.log(element.opponents[0]);

data returned

but when i want to access with .name the value is undefined

console.log(element.opponents[0].name);

database schema : db

I have an collection named "teams" in my db.
What is the problems ? I think i'm not that far...

Body:
It might be an overlook but try...

console.log(element.opponents[0].opponent.name);


问:
How can I stop outputting text, when a condition is met?
I wrote this code to tell me if a bitcoin is below to a certain value, but the problem is that when i run this code, It keeps spamming either conditions "okay" or "not okay". so I'm wondering how can i stop this process, so that when it's below target, it'll just say not okay and stop outputting until price of bitcoin rises.</p>

```<code>target = 9440
while True:
    with urllib.request.urlopen("https://api.coindesk.com/v1/bpi/currentprice.json") as url:
        data = json.loads(url.read().decode())
    price = float(data.get('bpi').get('USD').get('rate').replace(",", ""))
    if price <= target:
        print("Not okay\n")
    else:
        print("Okay\n")
</code>```

答:
Since you have two possible states, "okay" and "not okay" you need to use a variable that keeps the state of previous query. If previousState was the same as the current state do nothing, if they're different print the text.
Here's some code that should solve the problem:

```<code>target = 9440
previousState = false; // use true as "okay" and false as "not okay"
while True:
    with urllib.request.urlopen("https://api.coindesk.com/v1/bpi/currentprice.json") as url:
        data = json.loads(url.read().decode())
    price = float(data.get('bpi').get('USD').get('rate').replace(",", ""))
    if ((price <= target) and (previousState == true)):
        print("Not okay\n")
    elif((price >= target) and (previousState == false)):
        print("Okay\n")
</code>```

Body:
I wrote this code to tell me if a bitcoin is below to a certain value, but the problem is that when i run this code, It keeps spamming either conditions "okay" or "not okay". so I'm wondering how can i stop this process, so that when it's below target, it'll just say not okay and stop outputting until price of bitcoin rises.

target = 9440
while True:
    with urllib.request.urlopen("https://api.coindesk.com/v1/bpi/currentprice.json") as url:
        data = json.loads(url.read().decode())
    price = float(data.get('bpi').get('USD').get('rate').replace(",", ""))
    if price <= target:
        print("Not okay\n")
    else:
        print("Okay\n")

Body:
Since you have two possible states, "okay" and "not okay" you need to use a variable that keeps the state of previous query. If previousState was the same as the current state do nothing, if they're different print the text.
Here's some code that should solve the problem:

target = 9440
previousState = false; // use true as "okay" and false as "not okay"
while True:
    with urllib.request.urlopen("https://api.coindesk.com/v1/bpi/currentprice.json") as url:
        data = json.loads(url.read().decode())
    price = float(data.get('bpi').get('USD').get('rate').replace(",", ""))
    if ((price <= target) and (previousState == true)):
        print("Not okay\n")
    elif((price >= target) and (previousState == false)):
        print("Okay\n")


问:
Scikit - Linear Regression - Extracting Metrics

Python 3

scikit-learn-0.23.1

numpy-1.18.4

scipy-1.4.1

Is it possible to extract the number of iterations it took to fit the regression model (by Gradient Descent)? Aside from the general model evaluation metrics, I don't see anything related to iteration number.

```<code>regressor = LinearRegression()
regressor.fit(xtr, ytr)

print('Mean Absolute Error:', metrics.mean_absolute_error(yt, y_pred))
print('Mean Squared Error:', metrics.mean_squared_error(yt, y_pred))
print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(yt, y_pred)))
</code>```

Scikit documentation showing all possible metric modules

答:
As Pointed out by Gilad, no iterations are involved to calculate the linear regression problem using OLS . I am guessing here that you are trying to achieve the linear regression model using Gradient Descent. For the later one, number of iterations are defined prior the execution.

So to use the Gradient Descent, you can manually write the algorithm (Another link) or you can use the Ridge Regression or Lasso Regression from the Sklearn. Here there is an n_iter paramter by which you can achieve the number of iterations it took to determine the coefs.

class sklearn.linear_model.Ridge(alpha=1.0, *, fit_intercept=True, normalize=False, copy_X=True, max_iter=None, tol=0.001, solver='auto', random_state=None)

Attributes

n_iter : _None or ndarray of shape (n_targets,)
Actual number of iterations for each target. Available only for sag and lsqr solvers. Other solvers will return None.

Note : You can define the solver as sag or saga to use the gradient Descent method.

Body:
Python 3

scikit-learn-0.23.1

numpy-1.18.4

scipy-1.4.1

Is it possible to extract the number of iterations it took to fit the regression model (by Gradient Descent)? Aside from the general model evaluation metrics, I don't see anything related to iteration number.

regressor = LinearRegression()
regressor.fit(xtr, ytr)

print('Mean Absolute Error:', metrics.mean_absolute_error(yt, y_pred))
print('Mean Squared Error:', metrics.mean_squared_error(yt, y_pred))
print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(yt, y_pred)))

Scikit documentation showing all possible metric modules


问:
How can multiple unconnected async events await a single promise
I have a system where I need an id from a server to handle events. I should only fetch the id if/when the first event happens, but after that, I need to use the same id for each subsequent event. I know how to use async-await etc. so I have some code like this

```<code>var id = "";
async function handleEvent(e) {
    if (! id ) {
        let response = await fetch(URL)
        if (response.ok) {
            let json = await response.json();
            id = json.id ;
        }
    }
    // use id to handle event
}
</code>```

But my problem is that I could receive multiple events before I receive a response, so I get multiple overlapping calls to fetch a new id.

How can I have multiple asynchronous calls to handleEvent, with the first one processing the fetch and any subsequent call waiting for it to complete to access the result?

答:
The solution to this turned out to be a little different from the previous answers. I thought I would post how I made it work in the end. The answers from @phil and @vaelin really helped me to figure this out.

Here was my solution...

```<code>class IDManager {
    async fetchID (resolve,reject ) {
        const response = await fetch( URL, { } ) ;
        const id = await response.json() ;
        resolve( id );
    }
    async getID() {
        if ( this.id === undefined ) {
            if ( this.promise === undefined ) {
                var self = this;
                this.promise = new Promise( this.fetchID ).then( function(id) { self.id = id;} );
            }
            await this.promise;
        }
        return this.id;
    }
}
</code>```

The problem was that awaiting the fetch the getID call took a couple of seconds. During that time there were often multiple calls to getID, all of which initiated another fetch. I avoided that by wrapping the fetch and response.json calls in another promise which was created instantly, and so avoided the duplicates.

Body:
I have a system where I need an id from a server to handle events. I should only fetch the id if/when the first event happens, but after that, I need to use the same id for each subsequent event. I know how to use async-await etc. so I have some code like this

var id = "";
async function handleEvent(e) {
    if (! id ) {
        let response = await fetch(URL)
        if (response.ok) {
            let json = await response.json();
            id = json.id ;
        }
    }
    // use id to handle event
}

But my problem is that I could receive multiple events before I receive a response, so I get multiple overlapping calls to fetch a new id.

How can I have multiple asynchronous calls to handleEvent, with the first one processing the fetch and any subsequent call waiting for it to complete to access the result?

Body:
The solution to this turned out to be a little different from the previous answers. I thought I would post how I made it work in the end. The answers from @phil and @vaelin really helped me to figure this out.

Here was my solution...

class IDManager {
    async fetchID (resolve,reject ) {
        const response = await fetch( URL, { } ) ;
        const id = await response.json() ;
        resolve( id );
    }
    async getID() {
        if ( this.id === undefined ) {
            if ( this.promise === undefined ) {
                var self = this;
                this.promise = new Promise( this.fetchID ).then( function(id) { self.id = id;} );
            }
            await this.promise;
        }
        return this.id;
    }
}

The problem was that awaiting the fetch the getID call took a couple of seconds. During that time there were often multiple calls to getID, all of which initiated another fetch. I avoided that by wrapping the fetch and response.json calls in another promise which was created instantly, and so avoided the duplicates.


问:
Running two functions in parallel and for the same time
I have implemented a sampler and  a clock. I want to run the sampler and clock in parallel and at the same time I want the sampler to return it's end time to clock so that clock runs for that much time. These two functions are in some other module and it is being called from other module.

code for clock:

```<code>    def clock_generator(self, freq, end_time):

        time_period = 1 / (freq)
        clock = 0
        while time.time<end_time:
            clock = 1
            time.sleep(((time_period) / 2))
            clock = 0
            time.sleep(((time_period) / 2))
</code>```

code for sampler:

```<code>     def data_sample(self, path, result_file_name, time_index, formatted_data, time_period):

        start_time = time.time()

        """perform few operations"""

        end_time = time.time()
        return end_time
</code>```

答:
you must learn what thread is
i prepare this one to learn in this tutrial

but for your question and if you know what thread is what mention here can help you

Body:
I have implemented a sampler and  a clock. I want to run the sampler and clock in parallel and at the same time I want the sampler to return it's end time to clock so that clock runs for that much time. These two functions are in some other module and it is being called from other module.

code for clock:

    def clock_generator(self, freq, end_time):

        time_period = 1 / (freq)
        clock = 0
        while time.time<end_time:
            clock = 1
            time.sleep(((time_period) / 2))
            clock = 0
            time.sleep(((time_period) / 2))

code for sampler:

     def data_sample(self, path, result_file_name, time_index, formatted_data, time_period):

        start_time = time.time()

        """perform few operations"""

        end_time = time.time()
        return end_time


问:
weird variable hoisting in javascript
so we know that variables declared with the var keyword are hoisted and if we try to access their value before they have been initialized we get undefined. However, In the code below logging the name variable logs the function and not undefined why ?

console.log(name);
console.log(lol);

var name = function(args = "Hello World"){
    console.log(args)
}

var lol = function(args = "Hello world") {
    console.log(args)
}
```

<p>the output is </p>

```function(args = "Hello World"){
    console.log(args)
}
```

<p>and</p>

```main.js:57 undefined
```

why isnt name variable undefined ?

答:
The window which is the root scope already has a name property. Try the following and look at the output in your console. If you click the link the page that opens has MyWin as the output for name.

HTML (test.html)

```<code><head>
    <title>test</title>
</head>

<body>
    <a href="test.html" target="MyWin">Click me!</a>
    <script src="test.js"></script>
</body>

</html>
</code>```

Javascript (test.js)

```<code>console.log("name", name);
console.log("notname", notname);
console.log("lol", lol);

var notname = function (args = "Hello World") {
    console.log(args)
}

var lol = function (args = "Hello world") {
    console.log(args)
}
</code>```

Title: weird variable hoisting in javascript

Body:
so we know that variables declared with the var keyword are hoisted and if we try to access their value before they have been initialized we get undefined. However, In the code below logging the name variable logs the function and not undefined why ?

console.log(name);
console.log(lol);

var name = function(args = "Hello World"){
    console.log(args)
}

var lol = function(args = "Hello world") {
    console.log(args)
}

the output is

function(args = "Hello World"){
    console.log(args)
}

and

main.js:57 undefined

why isnt name variable undefined ?

Body:
The window which is the root scope already has a name property. Try the following and look at the output in your console. If you click the link the page that opens has MyWin as the output for name.

HTML (test.html)

<head>
    <title>test</title>
</head>

<body>
    <a href="test.html" target="MyWin">Click me!</a>
    <script src="test.js"></script>
</body>

</html>

Javascript (test.js)

console.log("name", name);
console.log("notname", notname);
console.log("lol", lol);

var notname = function (args = "Hello World") {
    console.log(args)
}

var lol = function (args = "Hello world") {
    console.log(args)
}


问:
swiftUI how to disabled a button for 2sec?
i have a bug, if i click on button before the animation before the card flip back. i think for me the best it would be to disable the button for 2 sec, but i made some research and didnt find anything!</p>

```<code>struct CardBack: View {
    var body: some View {

      Image("back_card")
        .resizable()
        .aspectRatio(contentMode: .fit)
        .frame(width: 250)
    }
}

struct ContentView: View {

   @State var flipped = false

   @State private var cardsFront = ["bigCard1", "bigCard2", "bigCard3", "bigCard4", "bigCard5" ]

   @State private var cardBack = "back_card"

    @State private var disablled = true

    var body: some View {
        VStack {
            Spacer()
            ZStack {

            Image(flipped ? self.cardsFront.randomElement()! : self.cardBack)
              .resizable()
              .aspectRatio(contentMode: .fit)
              .frame(width: 250)
              .rotation3DEffect(Angle(degrees: flipped ? 180 : 0 ), axis: (x: 0, y: 1, z: 0))
            }

            Spacer()
            HStack {
                Button(action: {
                    withAnimation(.spring()) {
                        self.flipped.toggle()
                    }
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        withAnimation(.spring()) {
                            self.flipped.toggle()
                        }
                    }

                }) {
                    Image("circle")
                        .renderingMode(.original)
                }

                Button(action: {

                }) {
                    Image("plus")
                        .renderingMode(.original)
                }
</code>```

答:
iOS 13, Swift 5

You can set the button as disabled initially and then enable it using the same sort of logic I used here.

import SwiftUI

```<code>struct ContentView: View {
@State var changeColor = false

var body: some View {
    TextView(changeColor: $changeColor)
}
}

struct TextView: View {
@Binding var changeColor: Bool
var body: some View {

Text("Hello World")
    .foregroundColor(changeColor ? Color.black: Color.red)
    .onAppear {
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            self.changeColor.toggle()
        }
    }
}
}
</code>```

You are almost there, you just need to use the .appear tag in your code to do this.

Body:
i have a bug, if i click on button before the animation before the card flip back. i think for me the best it would be to disable the button for 2 sec, but i made some research and didnt find anything!

struct CardBack: View {
    var body: some View {

      Image("back_card")
        .resizable()
        .aspectRatio(contentMode: .fit)
        .frame(width: 250)
    }
}

struct ContentView: View {

   @State var flipped = false

   @State private var cardsFront = ["bigCard1", "bigCard2", "bigCard3", "bigCard4", "bigCard5" ]

   @State private var cardBack = "back_card"

    @State private var disablled = true

    var body: some View {
        VStack {
            Spacer()
            ZStack {

            Image(flipped ? self.cardsFront.randomElement()! : self.cardBack)
              .resizable()
              .aspectRatio(contentMode: .fit)
              .frame(width: 250)
              .rotation3DEffect(Angle(degrees: flipped ? 180 : 0 ), axis: (x: 0, y: 1, z: 0))
            }

            Spacer()
            HStack {
                Button(action: {
                    withAnimation(.spring()) {
                        self.flipped.toggle()
                    }
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        withAnimation(.spring()) {
                            self.flipped.toggle()
                        }
                    }

                }) {
                    Image("circle")
                        .renderingMode(.original)
                }

                Button(action: {

                }) {
                    Image("plus")
                        .renderingMode(.original)
                }

Body:
iOS 13, Swift 5

You can set the button as disabled initially and then enable it using the same sort of logic I used here.

import SwiftUI

struct ContentView: View {
@State var changeColor = false

var body: some View {
    TextView(changeColor: $changeColor)
}
}

struct TextView: View {
@Binding var changeColor: Bool
var body: some View {

Text("Hello World")
    .foregroundColor(changeColor ? Color.black: Color.red)
    .onAppear {
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            self.changeColor.toggle()
        }
    }
}
}

You are almost there, you just need to use the .appear tag in your code to do this.


问:
Replacing '?' with nothing
I have "?35249509094742" in a column and I want to remove '?' from it so as to have a number "35249509094742". Why I cannot remove the '?' with

```<code>df8.replace({ "IMEI1": "?" }, 0)
</code>```

I have also tried

```<code>df8.replace({ "IMEI1": "?35249509094742" }, 35249509094742)
</code>```

After using I am using code

```<code>df8["IMEI1"] = df8["IMEI1"].astype("int64")
</code>```

to convert the column to float from object.
I am getting error

```<code>invalid literal for int() with base 10: '?35249509094742
</code>```

答:
We have at first:

```<code>df8={'IMEI1':"?35249509094742"}
print(df8)
</code>```

Replace using:

```<code>df8['IMEI1']=df8['IMEI1'].replace('?','')
print(df8)
</code>```

Title: Replacing '?' with nothing

Body:
I have "?35249509094742" in a column and I want to remove '?' from it so as to have a number "35249509094742". Why I cannot remove the '?' with

df8.replace({ "IMEI1": "?" }, 0)

I have also tried

df8.replace({ "IMEI1": "?35249509094742" }, 35249509094742)

After using I am using code

df8["IMEI1"] = df8["IMEI1"].astype("int64")

to convert the column to float from object.
I am getting error

invalid literal for int() with base 10: '?35249509094742

Body:
We have at first:

df8={'IMEI1':"?35249509094742"}
print(df8)

Replace using:

df8['IMEI1']=df8['IMEI1'].replace('?','')
print(df8)


问:
TypeError: Cannot read property 'find' of undefined(8:38)
I've Solved A Problem That Says ReferenceError: member is not defined But Now I'm Getting The Following Problem TypeError: Cannot read property 'find' of undefined I Think That They've Changed The find Property To Another Property But I'm Not Sure What's The New Property So... Someone HELP !

My Code :

```<code>1: const discord = require("discord.js");
2: const config = require('../config.json');
3:
4: module.exports.run = async (bot, message, args) => {
5:
6:     let target = message.guild.member(message.mentions.users.first());
7:     let reason = args.slice(1).join(' ');
8:     let logs = message.guild.channel.find(channel => channel.name === "⚠server_logs");
9:
10:    // member.guild.channels.cache.find('⚠server_logs', config.logsChannel);
11:
12:    if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('you don\'t have permissions to use this command!s');
13:
14:    if (!target) return message.reply('please specify a member to ban!');
15:    if (!reason) return message.reply('please specify a reason for this ban!');
16:    if (!logs) return message.reply(`please create a channel called ${config.logsChannel} to log the bans!`);
17:
18:    let embed = new discord.RichEmbed()
19:         .setColor('RANDOM')
20:         .setThumbnail(target.user.avatarURL)
21:         .addField('Banned Member', `${target.user.username} with an ID: ${target.user,id}`)
22:         .addField('Banned By', `${message.author.username} with an ID: ${message.author.id}`)
23:         .addField('Banned Time', message.createdAt)
24:         .addField('Banned At', message.channel)
25:         .addField('Banned Reason', reason)
26:         .addFooter('Banned user information', target.user.displayAvatarURL);
27:
28:    message.channel.send(`${target.user.username} was banned by ${message.author} for ${reason}`);
29:    target.ban(reason);
30:    logs.send(embed);
31: };
32:
33: module.exports.help = {
34:     name: 'ban'
35: };
</code>```

答:
let logs = message.guild.channel.find

It has to be: "let logs = message.guild.channels.cache.find" , like in your comment i think

Body:
I've Solved A Problem That Says ReferenceError: member is not defined But Now I'm Getting The Following Problem TypeError: Cannot read property 'find' of undefined I Think That They've Changed The find Property To Another Property But I'm Not Sure What's The New Property So... Someone HELP !

My Code :

1: const discord = require("discord.js");
2: const config = require('../config.json');
3:
4: module.exports.run = async (bot, message, args) => {
5:
6:     let target = message.guild.member(message.mentions.users.first());
7:     let reason = args.slice(1).join(' ');
8:     let logs = message.guild.channel.find(channel => channel.name === "⚠server_logs");
9:
10:    // member.guild.channels.cache.find('⚠server_logs', config.logsChannel);
11:
12:    if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('you don\'t have permissions to use this command!s');
13:
14:    if (!target) return message.reply('please specify a member to ban!');
15:    if (!reason) return message.reply('please specify a reason for this ban!');
16:    if (!logs) return message.reply(`please create a channel called ${config.logsChannel} to log the bans!`);
17:
18:    let embed = new discord.RichEmbed()
19:         .setColor('RANDOM')
20:         .setThumbnail(target.user.avatarURL)
21:         .addField('Banned Member', `${target.user.username} with an ID: ${target.user,id}`)
22:         .addField('Banned By', `${message.author.username} with an ID: ${message.author.id}`)
23:         .addField('Banned Time', message.createdAt)
24:         .addField('Banned At', message.channel)
25:         .addField('Banned Reason', reason)
26:         .addFooter('Banned user information', target.user.displayAvatarURL);
27:
28:    message.channel.send(`${target.user.username} was banned by ${message.author} for ${reason}`);
29:    target.ban(reason);
30:    logs.send(embed);
31: };
32:
33: module.exports.help = {
34:     name: 'ban'
35: };


问:
How to sign a JWT using RS256 with RSA private key
I am using the jose-jwt library and want to create a signed JWT in C# using the RS256 algorithm for encryption. I have no experience with cryptography, so please excuse my ignorance. I see the following example in the docs:

```<code>var payload = new Dictionary<string, object>()
{
    { "sub", "mr.x@contoso.com" },
    { "exp", 1300819380 }
};

var privateKey=new X509Certificate2("my-key.p12", "password", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey as RSACryptoServiceProvider;

string token=Jose.JWT.Encode(payload, privateKey, JwsAlgorithm.RS256);
</code>```

which shows the use of a p12 file, but how do I use an RSA key file of the form below? I am looking at the docs for X509Certificate2, but I see no option for RSA private keys. It appears to only accept PKCS7, which I understand to be public keys.

```<code>-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUp
wmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ5
1s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQABAoGAFijko56+qGyN8M0RVyaRAXz++xTqHBLh
3tx4VgMtrQ+WEgCjhoTwo23KMBAuJGSYnRmoBZM3lMfTKevIkAidPExvYCdm5dYq3XToLkkLv5L2
pIIVOFMDG+KESnAFV7l2c+cnzRMW0+b6f8mR1CJzZuxVLL6Q02fvLi55/mbSYxECQQDeAw6fiIQX
GukBI4eMZZt4nscy2o12KyYner3VpoeE+Np2q+Z3pvAMd/aNzQ/W9WaI+NRfcxUJrmfPwIGm63il
AkEAxCL5HQb2bQr4ByorcMWm/hEP2MZzROV73yF41hPsRC9m66KrheO9HPTJuo3/9s5p+sqGxOlF
L0NDt4SkosjgGwJAFklyR1uZ/wPJjj611cdBcztlPdqoxssQGnh85BzCj/u3WqBpE2vjvyyvyI5k
X6zk7S0ljKtt2jny2+00VsBerQJBAJGC1Mg5Oydo5NwD6BiROrPxGo2bpTbu/fhrT8ebHkTz2epl
U9VQQSQzY1oZMVX8i1m5WUTLPz2yLJIBQVdXqhMCQBGoiuSoSjafUhV7i1cEGpb88h5NBYZzWXGZ
37sJ5QsW+sJyoNde3xH8vdXhzU7eT82D6X/scw9RZz+/6rCJ4p0=
-----END RSA PRIVATE KEY-----
</code>```

Finally, what is the difference between the two options listed in the docs, and how do I choose between the two?

-------------------------- OPTION 1 --------------------------

RS-* and PS-* family

CLR:

RS256, RS384, RS512 and PS256, PS384, PS512 signatures require
  RSACryptoServiceProvider (usually private) key of corresponding
  length. CSP need to be forced to use Microsoft Enhanced RSA and AES
  Cryptographic Provider. Which usually can be done be re-importing
  RSAParameters. See http://clrsecurity.codeplex.com/discussions/243156
  for details.

-------------------------- OPTION 2 --------------------------

CORECLR: RS256, RS384, RS512 signatures require RSA (usually private) key of corresponding length.

答:
Using BouncyCastle and Jose nuget package, the following code works for me. </p>

```<code>public static string CreateToken(Dictionary<string, object> payload)
{
  string jwt = string.Empty;
  RsaPrivateCrtKeyParameters keyPair;

  var cert = ConfigurationManager.AppSettings["cert"];
  /// cert begins -----BEGIN PRIVATE KEY----- and ends with -END PRIVATE KEY-----";

  using (var sr = new StringReader(cert))
  {
    PemReader pr = new PemReader(sr);
    keyPair = (RsaPrivateCrtKeyParameters)pr.ReadObject();
  }

  RSAParameters rsaParams = DotNetUtilities.ToRSAParameters(keyPair);

  using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
  {
    rsa.ImportParameters(rsaParams);

    jwt = Jose.JWT.Encode(payload, rsa, Jose.JwsAlgorithm.RS256);
  }

  return jwt;
}
</code>```

Body:
I am using the jose-jwt library and want to create a signed JWT in C# using the RS256 algorithm for encryption. I have no experience with cryptography, so please excuse my ignorance. I see the following example in the docs:

var payload = new Dictionary<string, object>()
{
    { "sub", "mr.x@contoso.com" },
    { "exp", 1300819380 }
};

var privateKey=new X509Certificate2("my-key.p12", "password", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey as RSACryptoServiceProvider;

string token=Jose.JWT.Encode(payload, privateKey, JwsAlgorithm.RS256);

which shows the use of a p12 file, but how do I use an RSA key file of the form below? I am looking at the docs for X509Certificate2, but I see no option for RSA private keys. It appears to only accept PKCS7, which I understand to be public keys.

-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUp
wmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ5
1s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQABAoGAFijko56+qGyN8M0RVyaRAXz++xTqHBLh
3tx4VgMtrQ+WEgCjhoTwo23KMBAuJGSYnRmoBZM3lMfTKevIkAidPExvYCdm5dYq3XToLkkLv5L2
pIIVOFMDG+KESnAFV7l2c+cnzRMW0+b6f8mR1CJzZuxVLL6Q02fvLi55/mbSYxECQQDeAw6fiIQX
GukBI4eMZZt4nscy2o12KyYner3VpoeE+Np2q+Z3pvAMd/aNzQ/W9WaI+NRfcxUJrmfPwIGm63il
AkEAxCL5HQb2bQr4ByorcMWm/hEP2MZzROV73yF41hPsRC9m66KrheO9HPTJuo3/9s5p+sqGxOlF
L0NDt4SkosjgGwJAFklyR1uZ/wPJjj611cdBcztlPdqoxssQGnh85BzCj/u3WqBpE2vjvyyvyI5k
X6zk7S0ljKtt2jny2+00VsBerQJBAJGC1Mg5Oydo5NwD6BiROrPxGo2bpTbu/fhrT8ebHkTz2epl
U9VQQSQzY1oZMVX8i1m5WUTLPz2yLJIBQVdXqhMCQBGoiuSoSjafUhV7i1cEGpb88h5NBYZzWXGZ
37sJ5QsW+sJyoNde3xH8vdXhzU7eT82D6X/scw9RZz+/6rCJ4p0=
-----END RSA PRIVATE KEY-----

Finally, what is the difference between the two options listed in the docs, and how do I choose between the two?

-------------------------- OPTION 1 --------------------------

RS-* and PS-* family

CLR:

RS256, RS384, RS512 and PS256, PS384, PS512 signatures require
  RSACryptoServiceProvider (usually private) key of corresponding
  length. CSP need to be forced to use Microsoft Enhanced RSA and AES
  Cryptographic Provider. Which usually can be done be re-importing
  RSAParameters. See http://clrsecurity.codeplex.com/discussions/243156
  for details.

-------------------------- OPTION 2 --------------------------

CORECLR: RS256, RS384, RS512 signatures require RSA (usually private) key of corresponding length.

Body:
Using BouncyCastle and Jose nuget package, the following code works for me.

public static string CreateToken(Dictionary<string, object> payload)
{
  string jwt = string.Empty;
  RsaPrivateCrtKeyParameters keyPair;

  var cert = ConfigurationManager.AppSettings["cert"];
  /// cert begins -----BEGIN PRIVATE KEY----- and ends with -END PRIVATE KEY-----";

  using (var sr = new StringReader(cert))
  {
    PemReader pr = new PemReader(sr);
    keyPair = (RsaPrivateCrtKeyParameters)pr.ReadObject();
  }

  RSAParameters rsaParams = DotNetUtilities.ToRSAParameters(keyPair);

  using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
  {
    rsa.ImportParameters(rsaParams);

    jwt = Jose.JWT.Encode(payload, rsa, Jose.JwsAlgorithm.RS256);
  }

  return jwt;
}


问:
How can i get value from URL in java script
http://localhost:3000/admin/parking/airportParkingPriorityUpdate/xyz

How do i get value "XYZ" from the url using javascript

答:
```<code>const list = location.href.split('/');
list[list.length-1]
</code>```


问:
How to create rich domain objects while maintaing persistence ignorance?
First off, I am using web forms without any ORM framework.

I have been struggling with how to make my domain objects as "smart" and "rich" as they can be without allowing them access to my service and repository layer.  My most recent attempt was in creating a model for gift certificates for a online store.

The main recurring issues that I am seeing is that:

More and more logic keeps being introduced in the service layer.  All the calls to the repository must pass through the service layer and each time the parameters are validated (eg - exists in db, etc). As a result my service layer is growing, but my domain objects just have some simple contractual validations.  Even object validation is in the service layer since if the ID of the item is null, it will check the db to ensure that the code is unique.  IHMO, the consumer of the system should not care if the functionality they need deals with persistence or not.

I have a separate POCO for transaction log entries for when a gift certificate is redeemed.  I assume that I should put a list or collection of these transactions as a property of my Gift Certificate model, but I am still unsure of when that property should be filled.  Do I add a separate method on the service for loading the transactions into a object on demand (eg - LoadTransactions(gc object)) or should the transactions be automatically loaded any time a existing gift certificate or list of gift certificates are requested (or maybe a option in the getGCs to load transactions as well)

What about computed fields like "Available Balance"... should I even have properties like this on my object?  Anytime I am working with the object, I will need to keep updating that property to insure it is  up to date.  Right now I simply have a service method GetBalanceByCode(gc code).

Even actions like redeeming a gift certificate are basically 100% data-centric (take some input parameters, validate them and add a transaction log entry to db).

答:
More and more logic keeps being
  introduced in the service layer (...)
  Even object validation is in the
  service layer (...)

Validation is not the best candidate as domain model element. Input (my personal preference is that it's represented as commands) should be validated at application service level. Domain logic should model how business work and assume that all the arguments are valid. Good candidates for domain logic are computations for example: you want to have them in one single place and have them well tested.

I have a separate POCO for transaction
  log entries for when a gift
  certificate is redeemed.

This kind of object is known as Event. You can learn about Events from Eric Evans 'What I learnt since the Blue Book' presentation. Event is basically an entity which is immutable. Events are quite often aggregates on their own because usually there's lots of them. By making them aggregates, you don't have any problems with lazy loading them as part of other objects's collection.

What about computed fields like
  "Available Balance"... should I even
  have properties like this on my
  object?

Computed properties are kind of logic that naturally fits in domain model, however it's debatable if a better approach is to compute the value each time or compute it when object changes and persist it in the DB.

Even actions like redeeming a gift
  certificate are basically 100%
  data-centric (take some input
  parameters, validate them and add a
  transaction log entry to db).

This action would be modeled as creating a CertificateRedeemed event. This event would be probably created by Certificate aggregate or some other object.  This blog post by Udi Dahan can be helpful