问:
Warning: React does not recognize the `computedMatch` prop on a DOM element. This is the error I am getting in my react app
```<code>Warning: React does not recognize the `computedMatch` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `computedmatch` instead. If you accidentally passed it from a parent component, remove it from the DOM element.
    at div
    at Switch (http://localhost:3000/static/js/bundle.js:38973:29)
    at Router (http://localhost:3000/static/js/bundle.js:38402:30)
    at BrowserRouter (http://localhost:3000/static/js/bundle.js:38024:35)
    at NoteState (http://localhost:3000/static/js/bundle.js:1041:76)
    at div
    at App
</code>```

I am using bootstap, but I don't think it has anything to do with this error. Let me know if I am wrong.

答:
There is a tip for new beginners like you: Look at the error given, try to figure out what exactly the error is saying. Mostly you will get solutions from errors.

Here, the Solution is given in the error statement.

Body:
Warning: React does not recognize the `computedMatch` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `computedmatch` instead. If you accidentally passed it from a parent component, remove it from the DOM element.
    at div
    at Switch (http://localhost:3000/static/js/bundle.js:38973:29)
    at Router (http://localhost:3000/static/js/bundle.js:38402:30)
    at BrowserRouter (http://localhost:3000/static/js/bundle.js:38024:35)
    at NoteState (http://localhost:3000/static/js/bundle.js:1041:76)
    at div
    at App

I am using bootstap, but I don't think it has anything to do with this error. Let me know if I am wrong.


来源: stackexchange

问:
Displaying table view cell subview on right in RTL
I have a table view cell which displays a circle with checkmark and then text on the label besides it. All of this is done in the code without auto-layout. When I change the language to RTL, the label moves/displayed to right, but the custom circle/subview remains on the left.

Code:

```<code>override func formatCell(_ cell: UITableViewCell) {
    cell.selectionStyle = .none
    cell.textLabel?.text = title
    cell.accessoryType = .none
    cell.accessoryView = nil

    renderCircle(cell)
}

private func renderCircle(_ cell: UITableViewCell) {
    let circleDiameter = CGFloat(20)

    let y = (44.0 - circleDiameter) / 2.0
    var circleView = UIView(frame: CGRect(x: 16, y: y, width: circleDiameter, height: circleDiameter))

    if isPhoneRightToLeftLanguage() {
        let cellWidth = cell.frame.width - 16
        circleView = UIView(frame: CGRect(x: cellWidth, y: y, width: circleDiameter, height: circleDiameter))
    }

//        if isPhoneRightToLeftLanguage() {
//            circleView.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
//        }

    drawCircle(into: circleView, diameter: circleDiameter)
    cell.contentView.addSubview(circleView)

    cell.indentationLevel = 1
    cell.indentationWidth = circleDiameter + 14
}

private func drawCircle(into view: UIView, diameter: CGFloat) {
    let circlePath = CGPath(ellipseIn: CGRect(x: 0, y: 0, width: diameter, height: diameter), transform: nil)

    let circleLayer = CAShapeLayer()
    circleLayer.allowsEdgeAntialiasing = true
    circleLayer.path = circlePath
    circleLayer.lineWidth = 1.3
    circleLayer.strokeColor = color
    circleLayer.fillColor = isActive ? color : UIColor.white.cgColor
    circleLayer.backgroundColor = UIColor.white.cgColor

    view.layer.addSublayer(circleLayer)

    if isActive {
       let checkmarkPath = CGMutablePath()
       checkmarkPath.addLines(between: [
       CGPoint(x: 3.5, y: 10.5),
       CGPoint(x: 7.2, y: 14.2),
       CGPoint(x: 15.2, y: 6.2)
       ])

        let checkmarkLayer = CAShapeLayer()
        checkmarkLayer.allowsEdgeAntialiasing = true
        checkmarkLayer.path = checkmarkPath
        checkmarkLayer.lineWidth = 1.3
        checkmarkLayer.strokeColor = UIColor.white.cgColor
        checkmarkLayer.fillColor = nil

        view.layer.addSublayer(checkmarkLayer)
    }
}
</code>```

I tried adding this code which moves the circle to the right, but not after the label. It overrides the label.

```<code>if isPhoneRightToLeftLanguage() {
    let cellWidth = cell.frame.width - 16
    circleView = UIView(frame: CGRect(x: cellWidth, y: y, width: circleDiameter, height: circleDiameter))
}
</code>```

When the device is in RTL, when you look at the table view cell from the right, it should display circle first and then label. How do I fix it?

答:
You could use a custom subclass of UITableViewCell and lay out its subview relatively to leading and trailing anchors (instead of using left and right related anchors) – this gives you desired behavior out-of-the-box.

Here's a Playground example:

import UIKit

final class CustomCell: UITableViewCell {

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        backgroundColor = .green

        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = .red

        addSubview(view)
        NSLayoutConstraint.activate([view.heightAnchor.constraint(equalTo: heightAnchor),
                                     view.centerYAnchor.constraint(equalTo: centerYAnchor),
                                     view.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.3),
                                     view.trailingAnchor.constraint(equalTo: trailingAnchor)])
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

let cell = CustomCell()
cell.frame = CGRect(x: 0.0, y: 0.0, width: 200.0, height: 50.0)

UIView.appearance().semanticContentAttribute = .forceRightToLeft
let rtlCell = CustomCell()
rtlCell.frame = CGRect(x: 0.0, y: 0.0, width: 200.0, height: 50.0)
```

The output looks like this:

ContentLicense: CC BY-SA 4.0

Body:
I have a table view cell which displays a circle with checkmark and then text on the label besides it. All of this is done in the code without auto-layout. When I change the language to RTL, the label moves/displayed to right, but the custom circle/subview remains on the left.

Code:

override func formatCell(_ cell: UITableViewCell) {
    cell.selectionStyle = .none
    cell.textLabel?.text = title
    cell.accessoryType = .none
    cell.accessoryView = nil

    renderCircle(cell)
}

private func renderCircle(_ cell: UITableViewCell) {
    let circleDiameter = CGFloat(20)

    let y = (44.0 - circleDiameter) / 2.0
    var circleView = UIView(frame: CGRect(x: 16, y: y, width: circleDiameter, height: circleDiameter))

    if isPhoneRightToLeftLanguage() {
        let cellWidth = cell.frame.width - 16
        circleView = UIView(frame: CGRect(x: cellWidth, y: y, width: circleDiameter, height: circleDiameter))
    }

//        if isPhoneRightToLeftLanguage() {
//            circleView.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
//        }

    drawCircle(into: circleView, diameter: circleDiameter)
    cell.contentView.addSubview(circleView)

    cell.indentationLevel = 1
    cell.indentationWidth = circleDiameter + 14
}

private func drawCircle(into view: UIView, diameter: CGFloat) {
    let circlePath = CGPath(ellipseIn: CGRect(x: 0, y: 0, width: diameter, height: diameter), transform: nil)

    let circleLayer = CAShapeLayer()
    circleLayer.allowsEdgeAntialiasing = true
    circleLayer.path = circlePath
    circleLayer.lineWidth = 1.3
    circleLayer.strokeColor = color
    circleLayer.fillColor = isActive ? color : UIColor.white.cgColor
    circleLayer.backgroundColor = UIColor.white.cgColor

    view.layer.addSublayer(circleLayer)

    if isActive {
       let checkmarkPath = CGMutablePath()
       checkmarkPath.addLines(between: [
       CGPoint(x: 3.5, y: 10.5),
       CGPoint(x: 7.2, y: 14.2),
       CGPoint(x: 15.2, y: 6.2)
       ])

        let checkmarkLayer = CAShapeLayer()
        checkmarkLayer.allowsEdgeAntialiasing = true
        checkmarkLayer.path = checkmarkPath
        checkmarkLayer.lineWidth = 1.3
        checkmarkLayer.strokeColor = UIColor.white.cgColor
        checkmarkLayer.fillColor = nil

        view.layer.addSublayer(checkmarkLayer)
    }
}

I tried adding this code which moves the circle to the right, but not after the label. It overrides the label.

if isPhoneRightToLeftLanguage() {
    let cellWidth = cell.frame.width - 16
    circleView = UIView(frame: CGRect(x: cellWidth, y: y, width: circleDiameter, height: circleDiameter))
}

When the device is in RTL, when you look at the table view cell from the right, it should display circle first and then label. How do I fix it?

Body:
You could use a custom subclass of UITableViewCell and lay out its subview relatively to leading and trailing anchors (instead of using left and right related anchors) – this gives you desired behavior out-of-the-box.

Here's a Playground example:

import UIKit

final class CustomCell: UITableViewCell {

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        backgroundColor = .green

        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = .red

        addSubview(view)
        NSLayoutConstraint.activate([view.heightAnchor.constraint(equalTo: heightAnchor),
                                     view.centerYAnchor.constraint(equalTo: centerYAnchor),
                                     view.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.3),
                                     view.trailingAnchor.constraint(equalTo: trailingAnchor)])
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

let cell = CustomCell()
cell.frame = CGRect(x: 0.0, y: 0.0, width: 200.0, height: 50.0)

UIView.appearance().semanticContentAttribute = .forceRightToLeft
let rtlCell = CustomCell()
rtlCell.frame = CGRect(x: 0.0, y: 0.0, width: 200.0, height: 50.0)

The output looks like this:


问:
Impact of DC in Cassandra Cluster for Consistency ONE
I am learning Cassandra architecture & have set-up a Cassandra cluster in virtual machine like below:

```<code>Node_1 -> DC_1 -> Rack1 -> rf = 1
Node_2 and Node_3 -> DC_2 -> Rack1 -> rf = 1
</code>```

For Consistency Level ONE :

When Node_1 and Node_3 are down, select query fails on Node_2 (Warning from Cassandra console : Consistency One cannot be set; Error from cqlsh : NoHostAvailable)

When Node_1 and Node_2 are down, select query fails on Node_3 (Warning from Cassandra console : Consistency One cannot be set; Error from cqlsh : NoHostAvailable)

But When Node_2 and Node_3 are down, then select query passes on Node_1(Warning from Cassandra console : Consistency One cannot be set; Error from cqlsh : No Error, displays the table data)

Noticed same behaviour for write as well.

Does this behaviour have something to do with nodes being in same or different DCs? Please explain the reason for this mismatch.

答:
NoHostAvailable  comes up when replicas with the data are not up and cluster cannot respond the requested data. In your case you are writing one replica on each Datacenter (DC_1 and DC_2). So it might have happened that when you shut down following combo Node_1 (DC_1) and Node_2(DC_2) nodes or Node_1 (DC_1) and Node_3(DC_2) nodes, you are not getting all the requested data from the live nodes.
In case of Node_1 up you are sure that all your data will be retrieved since DC_1 contains 1 replica of data always and Node_1 is the only node in this datacenter. Hence you get the requested data.

Body:
I am learning Cassandra architecture & have set-up a Cassandra cluster in virtual machine like below:

Node_1 -> DC_1 -> Rack1 -> rf = 1
Node_2 and Node_3 -> DC_2 -> Rack1 -> rf = 1

For Consistency Level ONE :

When Node_1 and Node_3 are down, select query fails on Node_2 (Warning from Cassandra console : Consistency One cannot be set; Error from cqlsh : NoHostAvailable)

When Node_1 and Node_2 are down, select query fails on Node_3 (Warning from Cassandra console : Consistency One cannot be set; Error from cqlsh : NoHostAvailable)

But When Node_2 and Node_3 are down, then select query passes on Node_1(Warning from Cassandra console : Consistency One cannot be set; Error from cqlsh : No Error, displays the table data)

Noticed same behaviour for write as well.

Does this behaviour have something to do with nodes being in same or different DCs? Please explain the reason for this mismatch.


问:
(closed) Postman can't be opened properly
I'm trying to open my newly installed Postman when an error occurs which says something like this:

```<code>**Could not open Postman**
Error: Migration: IndexedDB schema migration failed. IndexedDb was not upgraded succesfully after `dexie.open`.
Please try restarting the app. If the issue persists, please refer to http://go.pstmn.io/troubleshoot-could-not-open
</code>```

As it says, the error really persists. The website above only provides suggestions like "reinstall the app" "upgrade the app", which are not really helpful. And as I dig into the Internet, it occurs to me that such error hardly happens (found nobody have the same question like me).

"IndexedDb" was mentioned in the error message, and I just know (from the Internet) that it's a nosql database provided by explorer. Maybe the problem can be solved by reinstalling the database, I guess?

答: disable hardware acceleration in the Postman menu in macOS, or the Help menu in Windows or Linux.

Body:
I'm trying to open my newly installed Postman when an error occurs which says something like this:

**Could not open Postman**
Error: Migration: IndexedDB schema migration failed. IndexedDb was not upgraded succesfully after `dexie.open`.
Please try restarting the app. If the issue persists, please refer to http://go.pstmn.io/troubleshoot-could-not-open

As it says, the error really persists. The website above only provides suggestions like "reinstall the app" "upgrade the app", which are not really helpful. And as I dig into the Internet, it occurs to me that such error hardly happens (found nobody have the same question like me).

"IndexedDb" was mentioned in the error message, and I just know (from the Internet) that it's a nosql database provided by explorer. Maybe the problem can be solved by reinstalling the database, I guess?


问:
Cloudfront with Websocket connection
I have been reading over the documentation here on connection a websocket service with a client through a cloudfront distribution but I am unable to understand where the upgrade to the websocket protocol will occur. Will the upgrade need to be handled by the server or will the cloudfront distribution handle changing the protocol to wss and respond with the connection?</p>

答:
The answer to my problem was a simple change to the Cloudfront Distribution.These headers needed be added so that my server (using express/express-ws) would receive the http request with the correct headers to validate the session and return with the upgraded protocol response for the client. (This was out of the box with express-ws and rxjs). I can post a coded example if needed.

Sec-WebSocket-Key

Sec-WebSocket-Version

Sec-WebSocket-Protocol

Title: Cloudfront with Websocket connection


问:
Filling a deck with Cards C#
I am tasked with Creating a functional deck of cards and I need a bit of guidance. I am making my method to fill the deck(an array) with card objects. I have the logic that will tell the loops when to change suits or ranks and I have made it to where the method will only fill the deck if the deck isn't already at 52 cards. What I need is a bit of guidance on where to proceed forward. I don't want answers, I want to learn why or why not what I have so far is incorrect and where I should proceed. I will put my code so far below.</p>
```<code>public static void FillDeckWithPlayingCards(Deck DeckToFill)
    {

        if (DeckToFill.DeckOfCards.Length != 52)
        {
            Deck deck = new Deck();
            PlayingCard [] FilledDeck =new PlayingCard [52];

            for (int i = 0; i < DeckToFill.DeckOfCards.Length; i++)
            {
                FilledDeck[i] = DeckToFill.DeckOfCards[i];
            }

            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 13; j++)
                {

                }

            }

    }
</code>```

答:
Since you are learning C# you might as well start thinking about data structures and encapsulation.

What is a PlayingCard? It should contain two properties, one for the suit and one for the face value, and since there can only take a finite number of possible values, it is natural you declare two enum structures to hold these values.

```<code>public enum SuitValue
{
    Clubs,
    Diamonds,
    Hearts,
    Spades
}

public enum FaceValue
{
    Ace = 1,
    Two = 2,
    Three = 3,
    Four = 4,
    Five = 5,
    Six = 6,
    Seven = 7,
    Eight = 8,
    Nine = 9,
    Ten = 10,
    Jack = 11,
    Queen = 12,
    King = 13
}
</code>```

and now we can define a PlayingCard with two properties. Since there are only certain valid cards, I am making the constructor of PlayingCard private, accepting those two values.

I am also adding a static method CreateStandardDeck() for the creation of the standard 52 card deck, just like your FillDeckWithPlayingCards() intended to do. All I needed to do is loop through all the values of suits and faces and added them to the array.

```<code>/// <summary>
/// Playing card object holds one suit value and one face value.
/// </summary>
public class PlayingCard
{
    /// <summary>
    /// Initializes a new playing card.
    /// </summary>
    PlayingCard(SuitValue suit, FaceValue value)
    {
        Suit=suit;
        Value=value;
    }

    public SuitValue Suit { get; }
    public FaceValue Value { get; }

    /// <summary>
    /// Creates a standard deck of cards as an array of PlayingCard.
    /// </summary>
    public static PlayingCard[] CreateStandardDeck()
    {
        SuitValue[] suits = Enum.GetValues(typeof(SuitValue)) as SuitValue[];
        FaceValue[] values = Enum.GetValues(typeof(FaceValue)) as FaceValue[];

        List<PlayingCard> cards = new List<PlayingCard>();
        for (int j = 0; j < values.Length; j++)
        {
            for (int i = 0; i < suits.Length; i++)
            {
                cards.Add(new PlayingCard(suits[i], values[j]));
            }
        }
        return cards.ToArray();
    }

    /// <summary>
    /// Returns a string representation of the card. The format is
    /// <code>[F S]</code> with F a code for face value, and S a code for suit value.
    /// </summary>
    public override string ToString()
    {
        string suit = Suit.ToString().Substring(0, 1);
        string face = Value>FaceValue.Ace && Value<FaceValue.Ten ? ((int)Value).ToString() : Value.ToString().Substring(0, 1);
        return $"[{face} {suit}]";
    }
}
</code>```

A Deck should hold an array of PlayingCard and also have methods for other functionality, such as shuffling.

```<code>/// <summary>
/// Deck objects holds an  array of PlayingCard and has to ability
/// to shuffle the cards.
/// </summary>
public class Deck
{
    /// <summary>
    /// Initializes a new deck of cards and fills them with standard values.
    /// </summary>
    public Deck()
    {
        Cards = PlayingCard.CreateStandardDeck();
    }
    public PlayingCard[] Cards { get; }

    static readonly Random rng = new Random();
    public void Shuffle(int repeat = 1)
    {
        for (int i = 0; i < repeat; i++)
        {
            Array.Sort(Cards, (a, b) => rng.NextDouble()<0.5 ? -1 : 1);
        }
    }

    public override string ToString()
    {
        const int wt = 12;
        var sb = new StringBuilder();
        int index = 0;
        while (index<Cards.Length)
        {
            sb.Append($"{Cards[index],wt} ");
            index++;
            if (index%4 == 0)
            {
                sb.AppendLine();
            }
        }
        return sb.ToString();
    }
}
</code>```

and finally, a little test program to see if it works as intended.

```<code>static class Program
{
    static void Main(string[] args)
    {
        Deck deck = new Deck();
        Console.WriteLine(deck);
    }
}
</code>```

with output

```<code>   [A C]        [A D]        [A H]        [A S]
   [2 C]        [2 D]        [2 H]        [2 S]
   [3 C]        [3 D]        [3 H]        [3 S]
   [4 C]        [4 D]        [4 H]        [4 S]
   [5 C]        [5 D]        [5 H]        [5 S]
   [6 C]        [6 D]        [6 H]        [6 S]
   [7 C]        [7 D]        [7 H]        [7 S]
   [8 C]        [8 D]        [8 H]        [8 S]
   [9 C]        [9 D]        [9 H]        [9 S]
   [T C]        [T D]        [T H]        [T S]
   [J C]        [J D]        [J H]        [J S]
   [Q C]        [Q D]        [Q H]        [Q S]
   [K C]        [K D]        [K H]        [K S]
</code>```

Note that the Shuffle() method works if you want to try it before writing to the console.

```<code>static class Program
{
    static void Main(string[] args)
    {
        Deck deck = new Deck();
        deck.Shuffle();
        Console.WriteLine(deck);
    }
}
</code>```

Title: Filling a deck with Cards C#

Body:
I am tasked with Creating a functional deck of cards and I need a bit of guidance. I am making my method to fill the deck(an array) with card objects. I have the logic that will tell the loops when to change suits or ranks and I have made it to where the method will only fill the deck if the deck isn't already at 52 cards. What I need is a bit of guidance on where to proceed forward. I don't want answers, I want to learn why or why not what I have so far is incorrect and where I should proceed. I will put my code so far below.

public static void FillDeckWithPlayingCards(Deck DeckToFill)
    {

        if (DeckToFill.DeckOfCards.Length != 52)
        {
            Deck deck = new Deck();
            PlayingCard [] FilledDeck =new PlayingCard [52];

            for (int i = 0; i < DeckToFill.DeckOfCards.Length; i++)
            {
                FilledDeck[i] = DeckToFill.DeckOfCards[i];
            }

            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 13; j++)
                {

                }

            }

    }

Body:
Since you are learning C# you might as well start thinking about data structures and encapsulation.

What is a PlayingCard? It should contain two properties, one for the suit and one for the face value, and since there can only take a finite number of possible values, it is natural you declare two enum structures to hold these values.

public enum SuitValue
{
    Clubs,
    Diamonds,
    Hearts,
    Spades
}

public enum FaceValue
{
    Ace = 1,
    Two = 2,
    Three = 3,
    Four = 4,
    Five = 5,
    Six = 6,
    Seven = 7,
    Eight = 8,
    Nine = 9,
    Ten = 10,
    Jack = 11,
    Queen = 12,
    King = 13
}

and now we can define a PlayingCard with two properties. Since there are only certain valid cards, I am making the constructor of PlayingCard private, accepting those two values.

I am also adding a static method CreateStandardDeck() for the creation of the standard 52 card deck, just like your FillDeckWithPlayingCards() intended to do. All I needed to do is loop through all the values of suits and faces and added them to the array.

/// <summary>
/// Playing card object holds one suit value and one face value.
/// </summary>
public class PlayingCard
{
    /// <summary>
    /// Initializes a new playing card.
    /// </summary>
    PlayingCard(SuitValue suit, FaceValue value)
    {
        Suit=suit;
        Value=value;
    }

    public SuitValue Suit { get; }
    public FaceValue Value { get; }

    /// <summary>
    /// Creates a standard deck of cards as an array of PlayingCard.
    /// </summary>
    public static PlayingCard[] CreateStandardDeck()
    {
        SuitValue[] suits = Enum.GetValues(typeof(SuitValue)) as SuitValue[];
        FaceValue[] values = Enum.GetValues(typeof(FaceValue)) as FaceValue[];

        List<PlayingCard> cards = new List<PlayingCard>();
        for (int j = 0; j < values.Length; j++)
        {
            for (int i = 0; i < suits.Length; i++)
            {
                cards.Add(new PlayingCard(suits[i], values[j]));
            }
        }
        return cards.ToArray();
    }

    /// <summary>
    /// Returns a string representation of the card. The format is
    /// <code>[F S]</code> with F a code for face value, and S a code for suit value.
    /// </summary>
    public override string ToString()
    {
        string suit = Suit.ToString().Substring(0, 1);
        string face = Value>FaceValue.Ace && Value<FaceValue.Ten ? ((int)Value).ToString() : Value.ToString().Substring(0, 1);
        return $"[{face} {suit}]";
    }
}

A Deck should hold an array of PlayingCard and also have methods for other functionality, such as shuffling.

/// <summary>
/// Deck objects holds an  array of PlayingCard and has to ability
/// to shuffle the cards.
/// </summary>
public class Deck
{
    /// <summary>
    /// Initializes a new deck of cards and fills them with standard values.
    /// </summary>
    public Deck()
    {
        Cards = PlayingCard.CreateStandardDeck();
    }
    public PlayingCard[] Cards { get; }

    static readonly Random rng = new Random();
    public void Shuffle(int repeat = 1)
    {
        for (int i = 0; i < repeat; i++)
        {
            Array.Sort(Cards, (a, b) => rng.NextDouble()<0.5 ? -1 : 1);
        }
    }

    public override string ToString()
    {
        const int wt = 12;
        var sb = new StringBuilder();
        int index = 0;
        while (index<Cards.Length)
        {
            sb.Append($"{Cards[index],wt} ");
            index++;
            if (index%4 == 0)
            {
                sb.AppendLine();
            }
        }
        return sb.ToString();
    }
}

and finally, a little test program to see if it works as intended.

static class Program
{
    static void Main(string[] args)
    {
        Deck deck = new Deck();
        Console.WriteLine(deck);
    }
}

with output

   [A C]        [A D]        [A H]        [A S]
   [2 C]        [2 D]        [2 H]        [2 S]
   [3 C]        [3 D]        [3 H]        [3 S]
   [4 C]        [4 D]        [4 H]        [4 S]
   [5 C]        [5 D]        [5 H]        [5 S]
   [6 C]        [6 D]        [6 H]        [6 S]
   [7 C]        [7 D]        [7 H]        [7 S]
   [8 C]        [8 D]        [8 H]        [8 S]
   [9 C]        [9 D]        [9 H]        [9 S]
   [T C]        [T D]        [T H]        [T S]
   [J C]        [J D]        [J H]        [J S]
   [Q C]        [Q D]        [Q H]        [Q S]
   [K C]        [K D]        [K H]        [K S]

Note that the Shuffle() method works if you want to try it before writing to the console.

static class Program
{
    static void Main(string[] args)
    {
        Deck deck = new Deck();
        deck.Shuffle();
        Console.WriteLine(deck);
    }
}


问:
Android - How can I measure performance of ListView and other Views?
How can I measure the FPS of my ListView?

See the slides 13-17 from http://code.google.com/events/io/2010/sessions/world-of-listview-android.html.

答: I don't know about calculating FPS (I guess that should be done system-wide and is not calculated per view), but you can use Hierarchy Viewer to profile performance of each View. It gives you time needed to measure, calculate layout of, and draw each View in milliseconds, and helps you to find slow View objects by showing yellow and red circles indicating bad performance.

ContentLicense: CC BY-SA 3.0


问:
Auth Guard - How to lazily call two observables?
In my auth guard, I want to first check the NGRX store by calling this.store.select(userStatus) which returns an Observable<boolean>, if the value is true, return true. If the value is false, I want to call this.userService.authCheck() which also returns an Observable<boolean> to finally determine what to return, how should I implement my canActivate(): Observable<boolean> {} method?

Thanks in advance!

答:
So you need to return an observable from canActivate that should emits a boolean value and you need to call one observable returning method first and check if it's returned true or if it's returned false then you need to call another method who will return true or false.

Your rxjs reciepe should look something like this :

function canActivate(
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
): Observable<boolean> {
  return this.store.select(userStatus).pipe(
    switchMap(d => d ? of(true) : this.userService.authCheck())
  );
}
```

Canactivate documentation can be found here

Body:
So you need to return an observable from canActivate that should emits a boolean value and you need to call one observable returning method first and check if it's returned true or if it's returned false then you need to call another method who will return true or false.

Your rxjs reciepe should look something like this :

function canActivate(
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
): Observable<boolean> {
  return this.store.select(userStatus).pipe(
    switchMap(d => d ? of(true) : this.userService.authCheck())
  );
}

Canactivate documentation can be found here


问:
Why is my fixed navbar ontop of my sticky navbar when i coded it in the bottom?
I'm trying to code one sticky bar and one fixed navbar right underneath the sticky with Bootstrap 5. I created one Navbar file with the sticky navbar code in it, and one FixedNav file with my fixed navbar code in it and brought in the Fixed navbar component inside my sticky navbar component. '

This is what it currently looks like, I want the opposite, yellow Nav on the bottom of white

At first, the fixed navbar was overlapping the sticky, and after researching I found out that setting the body with a padding-top:50px would fix it. However, I noticed that the solution only makes the sticky nav bar long enough to show below the fixed navbar, so now the fixed navbar is on top of the sticky navbar. How do I make it so that the sticky navbar is ON TOP of the fixed navbar?

There is another navbar called LogIn navbar which renders a new navbar once the user is logged in (wont be focusing on that, in case anyone gets confused with the ternary statement where I bring in the fixed nav component)

```<code> import React from "react";
import { connect } from "react-redux";
import { logout } from "../store";
import Fixed from "./fixedNav";
import LoginNav from "./LoginNav";

//temporary navBar without loggedIn function/difference
const tempUserId = 1;

const Navbar = ({ handleClick, isLoggedIn }) => (
  <div>
    <div>
      <nav
        className="navbar sticky-top navbar-light bg-light"
        style={{ backgroundColor: "#F0FFFF" }}
      >
        <div>
          <form className="d-flex">
            <input
              className="form-control me-2"
              type="search"
              placeholder="Search"
              aria-label="Search"
            />
            <button className="btn btn-sm btn-outline-secondary" type="submit">
              Search
            </button>
          </form>
        </div>
        <div>
          <a href="/" className="navbar-brand" />
          Grace Barker
        </div>

        <div>
          <ul className="nav justify-content-end">
            <li className="nav-item">
              <a className="nav-link active" aria-current="page" href="/">
                Contact Us
              </a>
            </li>
            <li className="nav-item">
              <a className="nav-link active" aria-current="page" href="/cart">
                Cart
              </a>
            </li>
          </ul>
        </div>
      </nav>
      {isLoggedIn ? (
        <LoginNav handleClick={handleClick} isLoggedIn={isLoggedIn} />
      ) : (
        <Fixed handleClick={handleClick} isLoggedIn={isLoggedIn} />
      )}
    </div>
  </div>
);
</code>```

FIXED NAVBAR CODE

```<code>import React from "react";
import { Link } from "react-router-dom";

const Fixed = ({ handleClick, isLoggedIn }) => (
  <div>
    <nav
      className=" navbar fixed-top navbar-expand-lg"
      style={{ backgroundColor: "#FFF8DC" }}
    >
      <div className="collapse navbar-collapse " id="navbarSupportedContent">
        <ul className="nav nav-tabs">
          <li className="nav-item ">
            <Link to="/home" className="nav-link ">
              Home
            </Link>
          </li>
          <li className="nav-item dropdown">
            <a
              className="nav-link dropdown-toggle "
              data-bs-toggle="dropdown"
              href="/"
              role="button"
              aria-expanded="false"
            >
              Dogs
            </a>
            <ul className="dropdown-menu">
              <li>
                <a className="dropdown-item " href="/dogs">
                  Available Dogs
                </a>
              </li>
              <li>
                <a className="dropdown-item " href="/">
                  Featured Dogs
                </a>
              </li>
            </ul>
          </li>
          <li className="nav-item">
            <Link to="/AboutUs" className="nav-link ">
              About Us
            </Link>
          </li>
        </ul>
      </div>

      <div>
        <ul className="nav justify-content-end">
          <li className="nav-item">
            <a className="nav-link active " aria-current="page" href="/users">
              Users
            </a>
          </li>
          <li className="nav-item">
            {isLoggedIn ? (
              <a
                className="nav-link active "
                aria-current="page"
                href="/home"
                onClick={handleClick}
              >
                LogOut
              </a>
            ) : (
              <a className="nav-link active " aria-current="page" href="/login">
                Login
              </a>
            )}
          </li>
        </ul>
      </div>
    </nav>
  </div>
);
export default Fixed;
</code>```

CSS

```<code>body {
</code>```

font-family: "Courier New", Courier, monospace;
padding-top: 50px;

}

答:
CSS position fixed is similar to position absolute, it hides everything under it. You can set z-index value to it to change its layer order. If you want to show the sticky nav bar just under the fixed one you have to give it a top value same as the height of fixed nav bar.

```<code>
#fixed-nav {
    position: fixed;
    top: 0;
    height: 72px;
    z-index: 100;
}

#sticky-nav {
    position: sticky;
    top: 72px; // same as the height of fixed nav bar.
    z-index: 200;
}

</code>```

Body:
I'm trying to code one sticky bar and one fixed navbar right underneath the sticky with Bootstrap 5. I created one Navbar file with the sticky navbar code in it, and one FixedNav file with my fixed navbar code in it and brought in the Fixed navbar component inside my sticky navbar component. '

This is what it currently looks like, I want the opposite, yellow Nav on the bottom of white

At first, the fixed navbar was overlapping the sticky, and after researching I found out that setting the body with a padding-top:50px would fix it. However, I noticed that the solution only makes the sticky nav bar long enough to show below the fixed navbar, so now the fixed navbar is on top of the sticky navbar. How do I make it so that the sticky navbar is ON TOP of the fixed navbar?

There is another navbar called LogIn navbar which renders a new navbar once the user is logged in (wont be focusing on that, in case anyone gets confused with the ternary statement where I bring in the fixed nav component)

 import React from "react";
import { connect } from "react-redux";
import { logout } from "../store";
import Fixed from "./fixedNav";
import LoginNav from "./LoginNav";

//temporary navBar without loggedIn function/difference
const tempUserId = 1;

const Navbar = ({ handleClick, isLoggedIn }) => (

          <form className="d-flex">
            <input
              className="form-control me-2"
              type="search"
              placeholder="Search"
              aria-label="Search"
            />
            <button className="btn btn-sm btn-outline-secondary" type="submit">
              Search
            </button>
          </form>

          Grace Barker

                Contact Us

                Cart

      {isLoggedIn ? (
        <LoginNav handleClick={handleClick} isLoggedIn={isLoggedIn} />
      ) : (
        <Fixed handleClick={handleClick} isLoggedIn={isLoggedIn} />
      )}

);

FIXED NAVBAR CODE

import React from "react";
import { Link } from "react-router-dom";

const Fixed = ({ handleClick, isLoggedIn }) => (

            <Link to="/home" className="nav-link ">
              Home
            </Link>

              Dogs

                  Available Dogs

                  Featured Dogs

            <Link to="/AboutUs" className="nav-link ">
              About Us
            </Link>

              Users

            {isLoggedIn ? (

                LogOut

            ) : (

                Login

            )}

);
export default Fixed;

CSS

body {

font-family: "Courier New", Courier, monospace;
padding-top: 50px;

}

Body:
CSS position fixed is similar to position absolute, it hides everything under it. You can set z-index value to it to change its layer order. If you want to show the sticky nav bar just under the fixed one you have to give it a top value same as the height of fixed nav bar.

#fixed-nav {
    position: fixed;
    top: 0;
    height: 72px;
    z-index: 100;
}

#sticky-nav {
    position: sticky;
    top: 72px; // same as the height of fixed nav bar.
    z-index: 200;
}


问:
"FIELD_ENCRYPTION_KEY must be defined in settings" - encrypted_model_fields error

Python 3.8.10

Django 4.0.2

django-encrypted-model-fields: 0.6.1

I am using encrypted_model_fields to encrypt a model field. The field I am encrypting is a password used to access a user account for another app via an api.

According to the docs I need to import the module and then wrap the model field as follows:

Models.py

```<code>from encrypted_model_fields.fields import EncryptedCharField
account_password = EncryptedCharField(models.CharField(max_length=20, blank=True))
</code>```

In addition to that I need to add a FIELD_ENCRYPTION_KEY to settings.py, which I have done, as per the docs.

Settings.py

```<code>FIELD_ENCRYPTION_KEY = os.environ.get('FIELD_ENCRYPTION_KEY')
</code>```

I have also added 'encrypted_model_fields' to installed apps in settings.py and the encryption key to .env, which is in place of the placeholder below..env:

```<code>export FIELD_ENCRYPTION_KEY=my_encryption_key_place_holder
</code>```

When I run makemigrations I receive the following error:

django.core.exceptions.ImproperlyConfigured: FIELD_ENCRYPTION_KEY must
be defined in settings

I have defined it - so why is it not found?

答:
It seems that the issue is with the django version 4 - cryptography has not been updated for the latest version of django. After trying multiple solutions for encrypting a model field using a number of modules that use cryptography I finally decided to just use secrets and Signer instead.

```<code>import secrets
from django.core.signing import Signer

foo = secrets.token_hex(16)
signer = Signer()
value = signer.sign(foo)
queryset = Model.objects.get(pk=foo_pk)
queryset.model_field = foo
queryset.save()
</code>```

documentation for Signer
documentation for secrets

Body:
Python 3.8.10

Django 4.0.2

django-encrypted-model-fields: 0.6.1

I am using encrypted_model_fields to encrypt a model field. The field I am encrypting is a password used to access a user account for another app via an api.

According to the docs I need to import the module and then wrap the model field as follows:

Models.py

from encrypted_model_fields.fields import EncryptedCharField
account_password = EncryptedCharField(models.CharField(max_length=20, blank=True))

In addition to that I need to add a FIELD_ENCRYPTION_KEY to settings.py, which I have done, as per the docs.

Settings.py

FIELD_ENCRYPTION_KEY = os.environ.get('FIELD_ENCRYPTION_KEY')

I have also added 'encrypted_model_fields' to installed apps in settings.py and the encryption key to .env, which is in place of the placeholder below..env:

export FIELD_ENCRYPTION_KEY=my_encryption_key_place_holder

When I run makemigrations I receive the following error:

django.core.exceptions.ImproperlyConfigured: FIELD_ENCRYPTION_KEY must
be defined in settings

I have defined it - so why is it not found?

Body:
It seems that the issue is with the django version 4 - cryptography has not been updated for the latest version of django. After trying multiple solutions for encrypting a model field using a number of modules that use cryptography I finally decided to just use secrets and Signer instead.

import secrets
from django.core.signing import Signer

foo = secrets.token_hex(16)
signer = Signer()
value = signer.sign(foo)
queryset = Model.objects.get(pk=foo_pk)
queryset.model_field = foo
queryset.save()

documentation for Signer
documentation for secrets


问:
How to push array in stdClass array in php
I have an array which I am getting from my database. For instance:

```<code>$db_record = $this->search_model->search_Employee();
foreach ($db_record as $db_data) {
    echo $db_data->phone_number;
}
</code>```

In above example I am able to fetch the record without any issue, but I want to add other data in $db_data afterwards.

```<code>foreach ($db_record as $db_data) {
    echo $db_data->phone_number;
    $db_data[]['new_value']='prashant';
}
</code>```

but $db_data[]['new_value']='prashant'; throwing below error

```<code>Cannot use object of type stdClass as array in
</code>```

It will great if someone can help me as struggeling more than 5 hours.

答:
```<code> foreach ($agent as $key => $value) {

   $value->any = 'ssds';
}
</code>```

try to use the $value instead key and object

Body:
I have an array which I am getting from my database. For instance:

$db_record = $this->search_model->search_Employee();
foreach ($db_record as $db_data) {
    echo $db_data->phone_number;
}

In above example I am able to fetch the record without any issue, but I want to add other data in $db_data afterwards.

foreach ($db_record as $db_data) {
    echo $db_data->phone_number;
    $db_data[]['new_value']='prashant';
}

but $db_data[]['new_value']='prashant'; throwing below error

Cannot use object of type stdClass as array in

It will great if someone can help me as struggeling more than 5 hours.

Body:
 foreach ($agent as $key => $value) {

   $value->any = 'ssds';
}

try to use the $value instead key and object


问:
get dominant color from URL image react-native
I am trying to retrieve the dominant color from an online image in a react-native project initialized with expo. I have tried every single color grab library and all of them either return an unfulfilled promise or something like this console output . Here is an example of how I would need it to work in the project. Any help would be greatly appreciated, thanks</p>
```<code>import ImageColors from 'react-native-image-colors'

const url = `https://website.com/image.png`

export default function App() {

    useEffect(() => {
        const fetchColors = async () => {
            const result = await ImageColors.getColors(url, {
                fallback: '#000000',
                quality: 'low',
            })

            switch (result.platform) {
                case 'android':
                    console.log(result)
                case 'web':
                    console.log(result)
                    break
                case 'ios':
                    console.log(result)
                    break
                default:
                    throw new Error('Unexpected platform')
            }

        }

        fetchColors()

    }, [])

    const handleClick = () => {

        //need to trigger color search here..

    }
}
</code>```

答:
To enable expo ready to use the react-native-image-colors we have to set up expo-dev-client.

So we have to install expo-dev-client and follow the official documentation.

Add Support for expo-dev-client

Body:
I am trying to retrieve the dominant color from an online image in a react-native project initialized with expo. I have tried every single color grab library and all of them either return an unfulfilled promise or something like this console output . Here is an example of how I would need it to work in the project. Any help would be greatly appreciated, thanks

import ImageColors from 'react-native-image-colors'

const url = `https://website.com/image.png`

export default function App() {

    useEffect(() => {
        const fetchColors = async () => {
            const result = await ImageColors.getColors(url, {
                fallback: '#000000',
                quality: 'low',
            })

            switch (result.platform) {
                case 'android':
                    console.log(result)
                case 'web':
                    console.log(result)
                    break
                case 'ios':
                    console.log(result)
                    break
                default:
                    throw new Error('Unexpected platform')
            }

        }

        fetchColors()

    }, [])

    const handleClick = () => {

        //need to trigger color search here..

    }
}


问:
Error launching Jupyter lab in new environment
After creating a new environment in Anaconda I installed Jupyter lab through the navigator. When I try to run, the following error message appears:

```<code>C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\notebookapp.py:73: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
_("Don't open the notebook in a browser after startup.")
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\notebookapp.py:89: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
_("Allow the notebook to be run from root user.")
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\traits.py:20: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_('Deprecated: Use minified JS file or not, mainly use during dev to avoid JS recompilation'),
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\traits.py:25: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_("Supply extra arguments that will be passed to Jinja environment."))
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\traits.py:29: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_("Extra variables to supply to jinja templates when rendering."),
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\traits.py:62: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_("""Path to search for custom.js, css""")
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\traits.py:74: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_("""Extra paths to search for serving jinja templates.
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\traits.py:85: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_("""extra paths to look for Javascript notebook extensions""")
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\traits.py:130: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_("""The MathJax.js configuration file that is to be used.""")
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\traits.py:143: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=(_("Dict of Python modules to load as notebook server extensions."
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\notebookapp.py:122: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
description = _("""The Jupyter HTML Notebook.
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\notebookapp.py:143: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_("""Path to search for custom.js, css""")
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\notebookapp.py:155: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_("""extra paths to look for Javascript notebook extensions""")
[I 2022-02-13 18:11:53.842 ServerApp] jupyterlab | extension was successfully linked.
[W 2022-02-13 18:11:54.449 ServerApp] 'ExtensionManager' object has no attribute '_extensions'
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\envs\Environment_1\Scripts\jupyter-lab-script.py", line 9, in
sys.exit(main())
File "C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\jupyter_server\extension\application.py", line 567, in launch_instance
serverapp = cls.initialize_server(argv=args)
File "C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\jupyter_server\extension\application.py", line 537, in initialize_server
serverapp.initialize(
File "C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\traitlets\config\application.py", line 88, in inner
return method(app, *args, **kwargs)
File "C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\jupyter_server\serverapp.py", line 2341, in initialize
point = self.extension_manager.extension_points[starter_extension]
File "C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\jupyter_server\extension\manager.py", line 303, in extension_points
for value in self.extensions.values()
File "C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\nbserver.py", line 80, in extensions
nb = self._extensions.get("nbclassic")
AttributeError: 'ExtensionManager' object has no attribute '_extensions'
</code>```

I've found the same error in some SO questions which all pointed me to this Github issue, which suggests that an updated verison of nbclassic should solve it.
I tried to install the latest version (actually it seems it was already installed when creating the environment) but the error persists.

Any suggestion?

答:
I had the same error message attempting to run jupyter lab today after updating everything on Anaconda. It did not affect jupyter notebook, so that may still work regardless.

What worked for me was running the following:

```<code>conda install -c conda-forge nbclassic=0.2.8
</code>```

Previously I tried the advice of others which had recommended:

```<code>conda install -c conda-forge nbclassic>=0.2.8
</code>```

It seems that version 0.2.8 works, however the current version (0.3.5) of nbclassic may be causing the error. Rolling back to 0.2.8 may also work for you.

Body:
After creating a new environment in Anaconda I installed Jupyter lab through the navigator. When I try to run, the following error message appears:

C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\notebookapp.py:73: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
_("Don't open the notebook in a browser after startup.")
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\notebookapp.py:89: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
_("Allow the notebook to be run from root user.")
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\traits.py:20: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_('Deprecated: Use minified JS file or not, mainly use during dev to avoid JS recompilation'),
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\traits.py:25: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_("Supply extra arguments that will be passed to Jinja environment."))
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\traits.py:29: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_("Extra variables to supply to jinja templates when rendering."),
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\traits.py:62: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_("""Path to search for custom.js, css""")
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\traits.py:74: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_("""Extra paths to search for serving jinja templates.
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\traits.py:85: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_("""extra paths to look for Javascript notebook extensions""")
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\traits.py:130: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_("""The MathJax.js configuration file that is to be used.""")
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\traits.py:143: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=(_("Dict of Python modules to load as notebook server extensions."
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\notebookapp.py:122: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
description = _("""The Jupyter HTML Notebook.
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\notebookapp.py:143: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_("""Path to search for custom.js, css""")
C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\notebookapp.py:155: FutureWarning: The alias `_()` will be deprecated. Use `_i18n()` instead.
help=_("""extra paths to look for Javascript notebook extensions""")
[I 2022-02-13 18:11:53.842 ServerApp] jupyterlab | extension was successfully linked.
[W 2022-02-13 18:11:54.449 ServerApp] 'ExtensionManager' object has no attribute '_extensions'
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\envs\Environment_1\Scripts\jupyter-lab-script.py", line 9, in
sys.exit(main())
File "C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\jupyter_server\extension\application.py", line 567, in launch_instance
serverapp = cls.initialize_server(argv=args)
File "C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\jupyter_server\extension\application.py", line 537, in initialize_server
serverapp.initialize(
File "C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\traitlets\config\application.py", line 88, in inner
return method(app, *args, **kwargs)
File "C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\jupyter_server\serverapp.py", line 2341, in initialize
point = self.extension_manager.extension_points[starter_extension]
File "C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\jupyter_server\extension\manager.py", line 303, in extension_points
for value in self.extensions.values()
File "C:\ProgramData\Anaconda3\envs\Environment_1\lib\site-packages\nbclassic\nbserver.py", line 80, in extensions
nb = self._extensions.get("nbclassic")
AttributeError: 'ExtensionManager' object has no attribute '_extensions'

I've found the same error in some SO questions which all pointed me to this Github issue, which suggests that an updated verison of nbclassic should solve it.
I tried to install the latest version (actually it seems it was already installed when creating the environment) but the error persists.

Any suggestion?

Body:
I had the same error message attempting to run jupyter lab today after updating everything on Anaconda. It did not affect jupyter notebook, so that may still work regardless.

What worked for me was running the following:

conda install -c conda-forge nbclassic=0.2.8

Previously I tried the advice of others which had recommended:

conda install -c conda-forge nbclassic>=0.2.8

It seems that version 0.2.8 works, however the current version (0.3.5) of nbclassic may be causing the error. Rolling back to 0.2.8 may also work for you.


问:
Python string.replace() not replacing characters
Some background information: We have an ancient web-based document database system where I work, almost entirely consisting of MS Office documents with the "normal" extensions (.doc, .xls, .ppt). They are all named based on some sort of arbitrary ID number (i.e. 1245.doc). We're switching to SharePoint and I need to rename all of these files and sort them into folders. I have a CSV file with all sorts of information (like which ID number corresponds to which document's title), so I'm using it to rename these files. I've written a short Python script that renames the ID number title.

However, some of the titles of the documents have slashes and other possibly bad characters to have in a title of a file, so I want to replace them with underscores:

```<code>bad_characters = ["/", "\\", ":", "(", ")", "<", ">", "|", "?", "*"]
for letter in bad_characters:
    filename = line[2].replace(letter, "_")
    foldername = line[5].replace(letter, "_")
</code>```

Example of line[2]: "Blah blah boring - meeting 2/19/2008.doc"

Example of line[5]: "Business meetings 2/2008"

When I add print letter inside of the for loop, it will print out the letter it's supposed to be replacing, but won't actually replace that character with an underscore like I want it to.

Is there anything I'm doing wrong here?

答:
Should use string.replace(str, fromStr, toStr)</p>

```<code>bad_characters = ["/", "\\", ":", "(", ")", "<", ">", "|", "?", "*"]
for letter in bad_characters:
    filename = string.replace(line[2], letter, "_")
    foldername = string.replace(line[5], letter, "_")
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Some background information: We have an ancient web-based document database system where I work, almost entirely consisting of MS Office documents with the "normal" extensions (.doc, .xls, .ppt). They are all named based on some sort of arbitrary ID number (i.e. 1245.doc). We're switching to SharePoint and I need to rename all of these files and sort them into folders. I have a CSV file with all sorts of information (like which ID number corresponds to which document's title), so I'm using it to rename these files. I've written a short Python script that renames the ID number title.

However, some of the titles of the documents have slashes and other possibly bad characters to have in a title of a file, so I want to replace them with underscores:

bad_characters = ["/", "\\", ":", "(", ")", "<", ">", "|", "?", "*"]
for letter in bad_characters:
    filename = line[2].replace(letter, "_")
    foldername = line[5].replace(letter, "_")

Example of line[2]: "Blah blah boring - meeting 2/19/2008.doc"

Example of line[5]: "Business meetings 2/2008"

When I add print letter inside of the for loop, it will print out the letter it's supposed to be replacing, but won't actually replace that character with an underscore like I want it to.

Is there anything I'm doing wrong here?

Body:
Should use string.replace(str, fromStr, toStr)

bad_characters = ["/", "\\", ":", "(", ")", "<", ">", "|", "?", "*"]
for letter in bad_characters:
    filename = string.replace(line[2], letter, "_")
    foldername = string.replace(line[5], letter, "_")


问:
Starting remote virtual interface (rvictl) on MacBook for packet trace of iPhone is failing without error
I am hoping for tips troubleshooting why rvictl is not working on my MacBook Pro. Running rvictl -s <udid> yields Starting device 000****0-0****5****D****E [FAILED] without telling me why it is failing or giving an error message.

I have identified my iPhone UDID as 000****0-0****5****D****E (censored) using xcrun xctrace list devices. I have updated my Xcode to version 13.2.1 and my iPhone to version 15.3.1. I have restarted both my laptop and my iPhone 11. My MacBook Pro is version 12.0.1. I have tried running sudo rvictl -s 000****0-0****5****D****E.

Is there a way to get more information from rvictl as to why it is failing? E.g. a verbose option? Any thoughts on what I could try to get to the bottom of this?

Thanks in advance!

答: Figured it out. Just restarting my computer was not good enough. I had to restart from System Preferences > Security & Privacy > General where there was a small Restart button. That definitely could have been made more clear in the documentation.


问:
Unexpected behavior of SpaCy matcher with negation
Somehow I have trouble understanding the negation in SpaCy matchers. I tried this code:

```<code>import spacy
from spacy.matcher import Matcher
import json

nlp = spacy.load('en_core_web_sm')
    #from spacy.tokenizer import Tokenizer
matcher = Matcher(nlp.vocab)

Sentence = "The cat is black"

negative_sentence = "The cat is not black"

test_pattern = '''
[
  [
    {
      "TEXT": "cat"
    },
    {
      "LEMMA": "be"
    },
    {
      "LOWER": "not",
      "OP": "!"

    },
    {
      "LOWER": "black"
    }
  ]
]
'''

db = json.loads(test_pattern)

matcher.add("TEST_PATTERNS", db)

'''*********************Validate matcher on positive sentence******************'''
doc = nlp(Sentence, matcher)

matches = matcher(doc)

if matches != []:
    print('Positive sentence identified')
else:
    print('Nothing found for positive sentence')

'''*********************Validate matcher on negative sentence******************'''
doc = nlp(negative_sentence, matcher)
matches = matcher(doc)

if matches != []:
    print('Negative sentence identified')
else:
    print('Nothing found for negative sentence')

</code>```

The result is:

Nothing found for positive sentence

Nothing found for negative sentence

I would expect that the sentence "The cat is black" would be a match. Furthermore, when I replace the ! with any other sign ("*", "?", or "+") it works as expected:

```<code>import spacy
from spacy.matcher import Matcher
import json

nlp = spacy.load('en_core_web_sm')
    #from spacy.tokenizer import Tokenizer
matcher = Matcher(nlp.vocab)

Sentence = "The cat is black"

negative_sentence = "The cat is not black"

test_pattern = '''
[
  [
    {
      "TEXT": "cat"
    },
    {
      "LEMMA": "be"
    },
    {
      "LOWER": "not",
      "OP": "?"

    },
    {
      "LOWER": "black"
    }
  ]
]
'''

db = json.loads(test_pattern)

matcher.add("TEST_PATTERNS", db)

'''*********************Validate matcher on positive sentence******************'''
doc = nlp(Sentence, matcher)

matches = matcher(doc)

if matches != []:
    print('Positive sentence identified')
else:
    print('Nothing found for positive sentence')

'''*********************Validate matcher on negative sentence******************'''
doc = nlp(negative_sentence, matcher)
matches = matcher(doc)

if matches != []:
    print('Negative sentence identified')
else:
    print('Nothing found for negative sentence')

</code>```

Result:

Positive sentence identified

Negative sentence identified

How can I use the negation and only identify "The cat is black" and not "The cat is not black".

The reason why like to of the "OP" is because there might also other words between "is" and "black" (e.g., "The cat is kind and black" and not "The cat is not kind and black" ).

Any help on understanding negation with SpaCy matchers is highly appreciated.

答:
Each dictionary in your match pattern corresponds to a token by default. With the ! operator it still corresponds to one token, just in a negative sense. With the * operator it corresponds to zero or more tokens, with + it's one or more tokens.

Looking at your original pattern, these are your tokens:

text: cat

lemma: be

text: not, op: !

lower: cat

Given the sentence "The cat is black", the match process works like this:

"the" matches nothing so we skip it.

"cat" matches your first token.

"is" matches your second token.

"black" matches your third token because it is not "not"

The sentence ends so there is no "cat" token, so the match fails.

When debugging patterns it's helpful to step through them like above.

For the other ops... * and ? work because "not" matches zero times. I would not expect + to work in the positive case.

The way you are trying to avoid matching negated things is kind of tricky. I would recommend you match all sentences with the relevant words first, ignoring negation, and then check if there is negation using the dependency parse.

Body:
Somehow I have trouble understanding the negation in SpaCy matchers. I tried this code:

import spacy
from spacy.matcher import Matcher
import json

nlp = spacy.load('en_core_web_sm')
    #from spacy.tokenizer import Tokenizer
matcher = Matcher(nlp.vocab)

Sentence = "The cat is black"

negative_sentence = "The cat is not black"

test_pattern = '''
[
  [
    {
      "TEXT": "cat"
    },
    {
      "LEMMA": "be"
    },
    {
      "LOWER": "not",
      "OP": "!"

    },
    {
      "LOWER": "black"
    }
  ]
]
'''

db = json.loads(test_pattern)

matcher.add("TEST_PATTERNS", db)

'''*********************Validate matcher on positive sentence******************'''
doc = nlp(Sentence, matcher)

matches = matcher(doc)

if matches != []:
    print('Positive sentence identified')
else:
    print('Nothing found for positive sentence')

'''*********************Validate matcher on negative sentence******************'''
doc = nlp(negative_sentence, matcher)
matches = matcher(doc)

if matches != []:
    print('Negative sentence identified')
else:
    print('Nothing found for negative sentence')

The result is:

Nothing found for positive sentence

Nothing found for negative sentence

I would expect that the sentence "The cat is black" would be a match. Furthermore, when I replace the ! with any other sign ("*", "?", or "+") it works as expected:

import spacy
from spacy.matcher import Matcher
import json

nlp = spacy.load('en_core_web_sm')
    #from spacy.tokenizer import Tokenizer
matcher = Matcher(nlp.vocab)

Sentence = "The cat is black"

negative_sentence = "The cat is not black"

test_pattern = '''
[
  [
    {
      "TEXT": "cat"
    },
    {
      "LEMMA": "be"
    },
    {
      "LOWER": "not",
      "OP": "?"

    },
    {
      "LOWER": "black"
    }
  ]
]
'''

db = json.loads(test_pattern)

matcher.add("TEST_PATTERNS", db)

'''*********************Validate matcher on positive sentence******************'''
doc = nlp(Sentence, matcher)

matches = matcher(doc)

if matches != []:
    print('Positive sentence identified')
else:
    print('Nothing found for positive sentence')

'''*********************Validate matcher on negative sentence******************'''
doc = nlp(negative_sentence, matcher)
matches = matcher(doc)

if matches != []:
    print('Negative sentence identified')
else:
    print('Nothing found for negative sentence')

Result:

Positive sentence identified

Negative sentence identified

How can I use the negation and only identify "The cat is black" and not "The cat is not black".

The reason why like to of the "OP" is because there might also other words between "is" and "black" (e.g., "The cat is kind and black" and not "The cat is not kind and black" ).

Any help on understanding negation with SpaCy matchers is highly appreciated.


问:
convert JSON with html table tag using JavaScript
I am trying to convert output from SQL Query which comes as a table. I have converted the table as JSON. Now I am in a process of converting the JSON to HTML Table so that I can use it for reporting.

Script is given below,

var value = '{"root":{"row":[{"DatabaseID":"21","fileid":"1","databaseName":"AutomationPortal","FileLogicalName":"AutomationPortal","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomationPortal.mdf","FileSizeMB":"100.00","SpaceUsedMB":"10.25","MaxfileSizeMB":"-0.01","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"},{"DatabaseID":"21","fileid":"3","databaseName":"AutomationPortal","FileLogicalName":"AutomatioPortal_01","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomatioPortal_01.ndf","FileSizeMB":"100.00","SpaceUsedMB":"0.06","MaxfileSizeMB":"130.00","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"}]}}'
        var data = JSON.parse(value);

        var tablearray = [];
        tablearray.push("

")
        var queryRow = data.root.row.length;

        var headerProperty = Object.keys(data.root.row[0]);

        for (i=0;i<headerProperty.length;i++){
            tablearray.push(""+headerProperty[i]+"	");
        }
        tablearray.push("
");
        //console.log(tablearray);
        for (i=0;i<queryRow;i++){
            tablearray.push("
")
            for (j=0;j<headerProperty.length;j++){
                // console.log(headerProperty[j]);
                // console.log(data.root.row[0].DatabaseID);
                // console.log(data.root.row[i].headerProperty[j]);
        tablearray.push(""+data.root.row[i].headerProperty[j]+"	");
            }
            tablearray.push("
");
        }
        tablearray.push("
");
        tablearray.join('');```

When I run the above script it gives me the following error, I am unable to fix the issue.

tablearray.push(""+data.root.row[i].headerProperty[j]+"");
                                                        ^

TypeError: Cannot read property '0' of undefined
      at Object. (C:\Users\convertjsontohtml.js:21:55)
      at Module._compile (internal/modules/cjs/loader.js:678:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10)
      at Module.load (internal/modules/cjs/loader.js:589:32)
      at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
      at Function.Module._load (internal/modules/cjs/loader.js:520:3)
      at Function.Module.runMain (internal/modules/cjs/loader.js:719:10)
      at startup (internal/bootstrap/node.js:228:19)
      at bootstrapNodeJSCore (internal/bootstrap/node.js:575:3)

The Output I am expecting is like ""

答:
This is my generic code to convert any json (containing Object add/or List). Building a table like this can be used to visualize our json and at times even use it in production code for debugging support.

const getType = obj => Object.prototype.toString.call(obj).slice(8, -1);
const isArray = obj => getType(obj) === 'Array';
const isMap = obj => getType(obj) === 'Object';
var buildList = function(data) {
  const keys = new Set();
  var str = "

";
  for (var i = 0; i < data.length; i++) {
    for (key in data[i]) {
      keys.add(key);
    }
  }
  for (key of keys) {
    str = str.concat('' + key + '	');
  }
  str = str.concat("
");
  for (var i = 0; i < data.length; i++) {
    str = str.concat('
');
    for (key of keys) {
      str = str.concat('');
      if (data[i][key]) {
        if (isMap(data[i][key])) {
          str = str.concat(buildMap(data[i][key]));
        } else if (isArray(data[i][key])) {
          str = str.concat(buildList(data[i][key]));
        } else {
          str = str.concat(data[i][key]);
        }
      }
      str = str.concat('	');
    }
    str = str.concat('
');
  }
  str = str.concat("
");
  return str;
}
var buildMap = function(data) {
  var str = "
";
  for (const key in data) {
    str = str.concat('
' + key + '	');
    if (isArray(data[key])) {
      str = str.concat(buildList(data[key]));
    } else if (isMap(data[key])) {
      str = str.concat(buildMap(data[key]));
    } else {
      str = str.concat(data[key]);
    }
    str = str.concat('
');
  }
  str = str.concat("
");
  return str;
}

var value = '{"root":{"row":[{"DatabaseID":"21","fileid":"1","databaseName":"AutomationPortal","FileLogicalName":"AutomationPortal","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomationPortal.mdf","FileSizeMB":"100.00","SpaceUsedMB":"10.25","MaxfileSizeMB":"-0.01","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"},{"DatabaseID":"21","fileid":"3","databaseName":"AutomationPortal","FileLogicalName":"AutomatioPortal_01","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomatioPortal_01.ndf","FileSizeMB":"100.00","SpaceUsedMB":"0.06","MaxfileSizeMB":"130.00","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"}]}}';
var data = JSON.parse(value);
var outHtml = "No Data found";
if (isArray(data)) {
  outHtml = buildList(data);
} else if (isMap(data)) {
  outHtml = buildMap(data);
}
document.getElementById("main").innerHTML = outHtml;</script>```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main"></div></code>```

Body:
I am trying to convert output from SQL Query which comes as a table. I have converted the table as JSON. Now I am in a process of converting the JSON to HTML Table so that I can use it for reporting.

Script is given below,

var value = '{"root":{"row":[{"DatabaseID":"21","fileid":"1","databaseName":"AutomationPortal","FileLogicalName":"AutomationPortal","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomationPortal.mdf","FileSizeMB":"100.00","SpaceUsedMB":"10.25","MaxfileSizeMB":"-0.01","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"},{"DatabaseID":"21","fileid":"3","databaseName":"AutomationPortal","FileLogicalName":"AutomatioPortal_01","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomatioPortal_01.ndf","FileSizeMB":"100.00","SpaceUsedMB":"0.06","MaxfileSizeMB":"130.00","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"}]}}'
        var data = JSON.parse(value);

        var tablearray = [];
        tablearray.push("

")
        var queryRow = data.root.row.length;

        var headerProperty = Object.keys(data.root.row[0]);

        for (i=0;i<headerProperty.length;i++){
            tablearray.push(""+headerProperty[i]+"	");
        }
        tablearray.push("
");
        //console.log(tablearray);
        for (i=0;i<queryRow;i++){
            tablearray.push("
")
            for (j=0;j<headerProperty.length;j++){
                // console.log(headerProperty[j]);
                // console.log(data.root.row[0].DatabaseID);
                // console.log(data.root.row[i].headerProperty[j]);
        tablearray.push(""+data.root.row[i].headerProperty[j]+"	");
            }
            tablearray.push("
");
        }
        tablearray.push("
");
        tablearray.join('');

When I run the above script it gives me the following error, I am unable to fix the issue.

tablearray.push(""+data.root.row[i].headerProperty[j]+"");
                                                        ^

TypeError: Cannot read property '0' of undefined
      at Object. (C:\Users\convertjsontohtml.js:21:55)
      at Module._compile (internal/modules/cjs/loader.js:678:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10)
      at Module.load (internal/modules/cjs/loader.js:589:32)
      at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
      at Function.Module._load (internal/modules/cjs/loader.js:520:3)
      at Function.Module.runMain (internal/modules/cjs/loader.js:719:10)
      at startup (internal/bootstrap/node.js:228:19)
      at bootstrapNodeJSCore (internal/bootstrap/node.js:575:3)

The Output I am expecting is like ""

Body:
This is my generic code to convert any json (containing Object add/or List). Building a table like this can be used to visualize our json and at times even use it in production code for debugging support.

const getType = obj => Object.prototype.toString.call(obj).slice(8, -1);
const isArray = obj => getType(obj) === 'Array';
const isMap = obj => getType(obj) === 'Object';
var buildList = function(data) {
  const keys = new Set();
  var str = "<table border==\"0\"><tr>";
  for (var i = 0; i < data.length; i++) {
    for (key in data[i]) {
      keys.add(key);
    }
  }
  for (key of keys) {
    str = str.concat('<td>' + key + '</td>');
  }
  str = str.concat("</tr>");
  for (var i = 0; i < data.length; i++) {
    str = str.concat('<tr>');
    for (key of keys) {
      str = str.concat('<td>');
      if (data[i][key]) {
        if (isMap(data[i][key])) {
          str = str.concat(buildMap(data[i][key]));
        } else if (isArray(data[i][key])) {
          str = str.concat(buildList(data[i][key]));
        } else {
          str = str.concat(data[i][key]);
        }
      }
      str = str.concat('</td>');
    }
    str = str.concat('</tr>');
  }
  str = str.concat("</table>");
  return str;
}
var buildMap = function(data) {
  var str = "<table border==\"0\">";
  for (const key in data) {
    str = str.concat('<tr><td>' + key + '</td><td>');
    if (isArray(data[key])) {
      str = str.concat(buildList(data[key]));
    } else if (isMap(data[key])) {
      str = str.concat(buildMap(data[key]));
    } else {
      str = str.concat(data[key]);
    }
    str = str.concat('</td></tr>');
  }
  str = str.concat("</table>");
  return str;
}

var value = '{"root":{"row":[{"DatabaseID":"21","fileid":"1","databaseName":"AutomationPortal","FileLogicalName":"AutomationPortal","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomationPortal.mdf","FileSizeMB":"100.00","SpaceUsedMB":"10.25","MaxfileSizeMB":"-0.01","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"},{"DatabaseID":"21","fileid":"3","databaseName":"AutomationPortal","FileLogicalName":"AutomatioPortal_01","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomatioPortal_01.ndf","FileSizeMB":"100.00","SpaceUsedMB":"0.06","MaxfileSizeMB":"130.00","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"}]}}';
var data = JSON.parse(value);
var outHtml = "No Data found";
if (isArray(data)) {
  outHtml = buildList(data);
} else if (isMap(data)) {
  outHtml = buildMap(data);
}
document.getElementById("main").innerHTML = outHtml;</script>

<div id="main"></div>


问:
Choose rectangles with maximal intersection area
In this problem r is a fixed positive integer. You are given N rectangles, all the same size, in the plane. The sides are either vertical or horizontal. We assume the area of the intersection of all N rectangles has non-zero area. The problem is how to find N-r of these rectangles, so as to maximize the area of the intersection. This problem arises in practical microscopy when one repeatedly images a given biological specimen, and alignment changes slightly during this process, due to physical reasons (e.g. differential expansion of parts of the microscope and camera). I have expressed the problem for dimension d=2. There is a similar problem for each d>0. For d=1, an O(N log(N)) solution is obtained by sorting the lefthand endpoints of the intervals. But let's stick with d=2. If r=1, one can again solve the problem in time O(N log(N)) by sorting coordinates of the corners.

So, is the original problem solved by solving first the case (N,1) obtaining N-1 rectangles, then solving the case (N-1,1), getting N-2 rectangles, and so on, until we reduce to N-r rectangles? I would be interested to see an explicit counter-example to this optimistic attempted procedure. It would be even more interesting if the procedure works (proof please!), but that seems over-optimistic.

If r is fixed at some value r>1, and N is large, is this problem in one of the NP classes?

Thanks for any thoughts about this.

David

答:
Since the intersection of axis-aligned rectangles is an axis-aligned rectangle, there are O(N4) possible intersections (O(N) lefts, O(N) rights, O(N) tops, O(N) bottoms). The obvious O(N5) algorithm is to try all of these, checking for each whether it's contained in at least N - r rectangles.

An improvement to O(N3) is to try all O(N2) intervals in the X dimension and run the 1D algorithm in the Y dimension on those rectangles that contain the given X-interval. (The rectangles need to be sorted only once.)

How large is N? I expect that fancy data structures might lead to an O(N2 log N) algorithm, but it wouldn't be worth your time if a cubic algorithm suffices.


问:
ERR_ACCESS_DENIED in webView in android
i have created a webview app for android studio. but didn't load the web url. the error is net::ERR_ACCESS_DENIED. can anyone help with this</p>

答:
I also wanted to add my observations on file access denied.

1. It can happens when you try to used files from storage i.e. internal memory or external memory.

Here you can do-

a)Declare tags in the manifest:

```<code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</code>```

b)  First you need to put these two lines when working with webview

```<code>webView.settings.allowContentAccess = true
webView.settings.allowFileAccess = true

In the last line of the webview you must use below statement

webView.loadUrl("file///....")

This is because, when you tried to loadUrl before allowContentAccess and
allowFileAccess it is not able to read the storage. So, first allow access
and the use loadurl. it will work perfectly fine every time.
</code>```

2. When you are working with online urls-

a) Put <uses-permission android:name="android.permission.INTERNET"/>
in manifest.

b) Use android:usesCleartextTraffic="true" inside application tag in manifest.

c) Also this snippet need to be added-

```<code>   webView.settings.allowContentAccess = true
   webView.settings.allowFileAccess = true
   webView.loadUrl("file///....")
</code>```

Hope your code works. Cheers :)

Title: ERR_ACCESS_DENIED in webView in android

Body:
I also wanted to add my observations on file access denied.

1. It can happens when you try to used files from storage i.e. internal memory or external memory.

Here you can do-

a)Declare tags in the manifest:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

b)  First you need to put these two lines when working with webview

webView.settings.allowContentAccess = true
webView.settings.allowFileAccess = true

In the last line of the webview you must use below statement

webView.loadUrl("file///....")

This is because, when you tried to loadUrl before allowContentAccess and
allowFileAccess it is not able to read the storage. So, first allow access
and the use loadurl. it will work perfectly fine every time.

2. When you are working with online urls-

a) Put <uses-permission android:name="android.permission.INTERNET"/>
in manifest.

b) Use android:usesCleartextTraffic="true" inside application tag in manifest.

c) Also this snippet need to be added-

   webView.settings.allowContentAccess = true
   webView.settings.allowFileAccess = true
   webView.loadUrl("file///....")

Hope your code works. Cheers :)


问:
Cannot set required attribute to antd design form element
The required field doesn't work for the antd design component. The form, therefore, submits the code below:

```<code>    <div className="col-md-12 text-center" style={{ backgroundColor: "#bdc5ff" }}>
        <Form.Item rules={[{ required: true }]}>
            <Form.Item name="dragger" valuePropName="fileList" noStyle rules={[{ required: true }]}>
                <Upload.Dragger
                    onChange={(e) => handleInputChange("file", e.file)}
                    beforeUpload={() => false}
                    name="files"
                    accept=".apng,.avif,.gif,.jpg,.jpeg,.jfif,.pjpeg,.pjp,.png,.svg,.webp"
                    action=""
                    rules={[{ required: true }]}
                >
                    <p className="ant-upload-drag-icon">
                        <InboxOutlined />
                    </p>
                    <p className="text-dark">Click or drag file to this area to upload</p>
                    <p className="text-muted">Support for PNG, JPG, GIF up to 10MB.</p>
                </Upload.Dragger>
            </Form.Item>
        </Form.Item>
    </div>
</code>```

In the doc here https://ant.design/components/form/v3 this should have worked
I am using the regular HTML form also

答:
You can to put form.item inside a Form component and add a submit button, below code will display "Please select a image" when you submit the form before uploading a image</p>
```<code>   <div
  className="col-md-12 text-center"
  style={{ backgroundColor: '#bdc5ff' }}
>
  <Form>
    <Form.Item>
      <Form.Item
        name="dragger"
        valuePropName="fileList"
        noStyle
        rules={[{ required: true, message: 'Please select a image' }]}
      >
        <Upload.Dragger
          onChange={(e) => handleInputChange('file', e.file)}
          beforeUpload={() => false}
          name="files"
          accept=".apng,.avif,.gif,.jpg,.jpeg,.jfif,.pjpeg,.pjp,.png,.svg,.webp"
          action=""
        >
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="text-dark">
            Click or drag file to this area to upload
          </p>
          <p className="text-muted">
            Support for PNG, JPG, GIF up to 10MB.
          </p>
        </Upload.Dragger>
      </Form.Item>
    </Form.Item>
    <Form.Item>
      <Button type="primary" htmlType="submit">
        Submit
      </Button>
    </Form.Item>
  </Form>
</div>
</code>```

Body:
The required field doesn't work for the antd design component. The form, therefore, submits the code below:

        <Form.Item rules={[{ required: true }]}>
            <Form.Item name="dragger" valuePropName="fileList" noStyle rules={[{ required: true }]}>
                <Upload.Dragger
                    onChange={(e) => handleInputChange("file", e.file)}
                    beforeUpload={() => false}
                    name="files"
                    accept=".apng,.avif,.gif,.jpg,.jpeg,.jfif,.pjpeg,.pjp,.png,.svg,.webp"
                    action=""
                    rules={[{ required: true }]}
                >

                        <InboxOutlined />

Click or drag file to this area to upload

Support for PNG, JPG, GIF up to 10MB.

                </Upload.Dragger>
            </Form.Item>
        </Form.Item>

In the doc here https://ant.design/components/form/v3 this should have worked
I am using the regular HTML form also

Body:
You can to put form.item inside a Form component and add a submit button, below code will display "Please select a image" when you submit the form before uploading a image

   <div
  className="col-md-12 text-center"
  style={{ backgroundColor: '#bdc5ff' }}
>
  <Form>
    <Form.Item>
      <Form.Item
        name="dragger"
        valuePropName="fileList"
        noStyle
        rules={[{ required: true, message: 'Please select a image' }]}
      >
        <Upload.Dragger
          onChange={(e) => handleInputChange('file', e.file)}
          beforeUpload={() => false}
          name="files"
          accept=".apng,.avif,.gif,.jpg,.jpeg,.jfif,.pjpeg,.pjp,.png,.svg,.webp"
          action=""
        >
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="text-dark">
            Click or drag file to this area to upload
          </p>
          <p className="text-muted">
            Support for PNG, JPG, GIF up to 10MB.
          </p>
        </Upload.Dragger>
      </Form.Item>
    </Form.Item>
    <Form.Item>
      <Button type="primary" htmlType="submit">
        Submit
      </Button>
    </Form.Item>
  </Form>
</div>


问:
React state is always undefined when invoke onClick event
So I have the following code:

```<code>export default function Component() {

  const [list, setList] = useState<JSX.Element[]>();
  const [active, setActive] = useState<JSX.Element>();

  useEffect(()=>{
    let startTab = <li key={"0000-0000-0000-0000"} onClick={() => onClick()}>Star 1</li>;
    let secondTab = <li key={"0001-0000-0000-0000"} onClick={() => onClick()}>Star 2</li>;

    setList(() => [startTab, secondTab]);
    setActive(() => startTab);
  },[])

  const onClick= () =>{
    console.log(list)
  }

  return (
    <div id="BodyMain" className={css["Body-container"]}>
      <div className={css["tab-header"]}>
        { (
          <ul className={css["navs"]}>
            {list?.map(tabItem => tabItem)}
          </ul>)
        }
      </div>
      <div className={css["tab-body"]}>{}</div>
    </div>
  );
}
</code>```

every time I invoke onClick function it just returns undefined!

Nevertheless, 'React Developer Tools' shows that indeed these states have values!!

I am unable to change the state from onClick function because it is always undefined. What did I do wrong? and how can I fix it?

答:
It happens because during first render list is undefined. And useEffect
captures onClick function with list as undefined. Since useEffect runs only once - list inside onClick will be always undefined. But if useEffect will run,
list will be updated too inside useEffect. And as @nam-h-nguyen said , really with count as a dependency useEffect will rerun and hence new value of list will be captured.

Body:
So I have the following code:

export default function Component() {

  const [list, setList] = useState<JSX.Element[]>();
  const [active, setActive] = useState<JSX.Element>();

  useEffect(()=>{
    let startTab =
 onClick()}>Star 1
;
    let secondTab =
 onClick()}>Star 2
;

    setList(() => [startTab, secondTab]);
    setActive(() => startTab);
  },[])

  const onClick= () =>{
    console.log(list)
  }

  return (

        { (

            {list?.map(tabItem => tabItem)}

)
        }

{}

  );
}

every time I invoke onClick function it just returns undefined!

Nevertheless, 'React Developer Tools' shows that indeed these states have values!!

I am unable to change the state from onClick function because it is always undefined. What did I do wrong? and how can I fix it?


问:
Ingress gives 502 error
If I run through the http load balancer example it works fine in my google container engine project.  When I run "kubectl describe ing" the backend is "HEALTHY".  If I then change the svc out to one that points to my app as shown here:

```<code>apiVersion: v1
kind: Service
metadata:
  name: app
  labels:
    name: app
spec:
  ports:
  - port: 8000
    name: http
    targetPort: 8000
  selector:
    name: app
  type: NodePort
</code>```

The app I'm running is django behind gunicorn and works just find if I make that a load balancer instead of a NodePort.

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: main-ingress
spec:
  backend:
    serviceName: app
    servicePort: 8000
</code>```

Now when I run "kubectl describe ing" the backend is listed as "UNHEALTHY" and all requests to the ingress IP give a 502.

Is the 502 a symptom of the bad health check?

What do I have to do to make the health check pass?  I'm pretty sure the container running my app is actually healthy.  I never set up a health check so I'm assuming I have to configure something that is not configured, but my googling hasn't gotten me anywhere.

答:
AWS ALB Ingress: The case where Deployment POD terminates TLS/SSL

One thing that's important: If the backend is implemented completely with Self-signed CERTS and is the entity terminating TLS, the Ingress object MUST know that fact in order to have its healthcheck to work properly as the default healthcheck is HTTP. For example, AWS's ALB will needs to know that in order to properly verify its own Healthcheck.

Verify if the Deployment, whose is being selected by the NodePort service, is terminating TLS/SSL (443, or any other port)

If the pod itself has a healthcheck spec, it should include that.

If there's no healthcheck specified in the POD, then you can verify if the ingress object is setting the proper protocol for the Ingress healthcheck itself.

For the case of AWS Ingress, it should use the annotations alb.ingress.kubernetes.io/healthcheck-protocol: HTTPS, and alb.ingress.kubernetes.io/healthcheck-path: /.

Ingress

For this example, the Deployment whose service forwards traffic to terminates TSL (The pod itself serves traffic with a self-signed cert).

For this reason, the healthcheck on / must specify the correct protocol and path.

# Example from https://docs.aws.amazon.com/eks/latest/userguide/alb-ingress.html
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    # https://kubernetes-sigs.github.io/aws-load-balancer-controller/guide/ingress/annotations/
    kubernetes.io/ingress.class: alb
    alb.ingress.kubernetes.io/load-balancer-attributes: access_logs.s3.enabled=false
    alb.ingress.kubernetes.io/backend-protocol: HTTPS
    alb.ingress.kubernetes.io/scheme: internet-facing
    alb.ingress.kubernetes.io/listen-ports: '[{"HTTPS": 443}]'
    alb.ingress.kubernetes.io/certificate-arn: arn:aws:acm:sa-east-1:806101772216:certificate/3db92ed3-5439-44e8-843d-fec0c9709501

    #### SOLUTION TO HTTPS Healthcheck From AWS ALB Ingress
    # https://stackoverflow.com/questions/64264889/argo-workflows-ui-not-working-with-aws-ingress-controller/64268995#64268995
    # As the backend is implemented with certificates, it MUST include the healthcheck using HTTPS
    alb.ingress.kubernetes.io/healthcheck-protocol: HTTPS
    alb.ingress.kubernetes.io/healthcheck-path: /
  name: argo-server-ingress
spec:
  rules:
  - host: argoflows-my-server.com
    http:
      paths:
      - pathType: Prefix
        path: "/*"
        backend:
          service:
            name: argo-server
            port:
              number: 2746
  tls:
  - hosts:
    secretName: argo-workflows-data-tls
```

Title: Ingress gives 502 error

Body:
If I run through the http load balancer example it works fine in my google container engine project.  When I run "kubectl describe ing" the backend is "HEALTHY".  If I then change the svc out to one that points to my app as shown here:

apiVersion: v1
kind: Service
metadata:
  name: app
  labels:
    name: app
spec:
  ports:
  - port: 8000
    name: http
    targetPort: 8000
  selector:
    name: app
  type: NodePort

The app I'm running is django behind gunicorn and works just find if I make that a load balancer instead of a NodePort.

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: main-ingress
spec:
  backend:
    serviceName: app
    servicePort: 8000

Now when I run "kubectl describe ing" the backend is listed as "UNHEALTHY" and all requests to the ingress IP give a 502.

Is the 502 a symptom of the bad health check?

What do I have to do to make the health check pass?  I'm pretty sure the container running my app is actually healthy.  I never set up a health check so I'm assuming I have to configure something that is not configured, but my googling hasn't gotten me anywhere.


问:
How to tokenize/parse data in an excel sheet using spacy
I'm trying to convert an excel sheet into a doc object using spacy, I spent the last couple of days trying to go around it but it seems a bit challenging.  I have opened the sheet in both openpyxl and pandas, I can read the excel sheet and output the content but I couldn't integrate spacy to create doc/token objects.

Is it possible to process excel sheets in spacy's pipeline?

Thank you!

答:
Spacy has no support for excel.
You could use pandas to read either the csv(if csv format)
or excel file
like

```<code>     import pandas as pd
     df = pd.read_csv(file)
</code>```

or

```<code>     df  = pd.read_excel(file)
</code>```

respectively.
Select required text column and iterate over  df 'column' values and pass them over to nlp() of spacy

Body:
Spacy has no support for excel.
You could use pandas to read either the csv(if csv format)
or excel file
like

     import pandas as pd
     df = pd.read_csv(file)

or

     df  = pd.read_excel(file)

respectively.
Select required text column and iterate over  df 'column' values and pass them over to nlp() of spacy