问:
UICollectionCellView delegate not being fired
A UICollectionView I have created doesn't want to fire a custom cell delegate.

The cells are displaying, and the test button accepts presses.

I have debugged the code and the cell.delegate is being assigned self.

I have researched this on google and I have come up with nothing. I think my code is ok but I must be missing something?

I would really appreciate any help.

```<code>//HomeControllerDelegateTesting.swift

import UIKit

class HomeControllerDelegateTesting: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, PostCellOptionsDelegate {

    var collectionView: UICollectionView! = nil

    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: self.createLayout())
        self.collectionView.register(PostCell.self, forCellWithReuseIdentifier: PostCell.reuseIdentifier)
        self.collectionView.backgroundColor = .systemBackground
        self.view.addSubview(collectionView)
        self.collectionView.dataSource = self
        self.collectionView.delegate = self

    }

    private func createLayout() -> UICollectionViewLayout {
        let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                             heightDimension: .fractionalHeight(1.0))
        let item = NSCollectionLayoutItem(layoutSize: itemSize)

        let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                               heightDimension: .estimated(300))
        let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize,
                                                         subitems: [item])
        let section = NSCollectionLayoutSection(group: group)

        let layout = UICollectionViewCompositionalLayout(section: section)
        return layout
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PostCell.reuseIdentifier, for: indexPath) as? PostCell else { fatalError("Cannot create cell") }

        cell.postTextLabel.text = "Test"
        cell.delegate = self
        //Test to eliminiate the button accepts events
        //cell.optionsButtons.addTarget(self, action: #selector(test), for: .touchUpInside)
        return cell
    }

    @objc func handlePostOptions(cell: PostCell) {
        print("123")
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3
    }
}

</code>```

```<code>//  PostCell.swift

import UIKit

protocol PostCellOptionsDelegate: class {
    func handlePostOptions(cell: PostCell)
}

class PostCell: UICollectionViewCell {
    static let reuseIdentifier = "list-cell-reuse-identifier"

    var delegate: PostCellOptionsDelegate?

    let usernameLabel: UILabel = {
        let label = UILabel()
        label.text = "Username"
        label.font = .boldSystemFont(ofSize: 15)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let postImageView: UIImageView = {
        let control = UIImageView()
        control.translatesAutoresizingMaskIntoConstraints = false
        control.contentMode = .scaleAspectFill
        control.clipsToBounds = true
        return control
    }()

    let postTextLabel: UILabel = {
        let label = UILabel()
        label.text = "Post text spanning multiple lines"
        label.font = .systemFont(ofSize: 15)
        label.numberOfLines = 0
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

//    private let optionsButtons: UIButton = {
//        let control = UIButton.systemButton(with: #imageLiteral(resourceName: "post_options"), target: self, action: #selector(handleOptions))
//        control.translatesAutoresizingMaskIntoConstraints = false
//        return control
//    }()

    let optionsButtons: UIButton = {
        let control = UIButton(type: .system)
        control.setTitle("Test", for: .normal)
        control.addTarget(self, action: #selector(handleOptions), for: .touchUpInside)
        control.translatesAutoresizingMaskIntoConstraints = false
        return control
    }()

    @objc fileprivate func handleOptions() {
        print("Handle options button")
        delegate?.handlePostOptions(cell: self)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupComponents()

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupComponents() {

        self.optionsButtons.heightAnchor.constraint(equalToConstant: 50).isActive = true

        let labelStack = UIStackView(arrangedSubviews: [optionsButtons])
        labelStack.translatesAutoresizingMaskIntoConstraints = false
        labelStack.axis = .horizontal
        labelStack.alignment = .fill
        labelStack.distribution = .fill
        labelStack.isLayoutMarginsRelativeArrangement = true
        labelStack.layoutMargins.left = 16
        labelStack.layoutMargins.right = 16
        labelStack.layoutMargins.top = 16
        labelStack.layoutMargins.bottom = 16

        let postTextLabelStack = UIStackView(arrangedSubviews: [postTextLabel])

        postTextLabelStack.translatesAutoresizingMaskIntoConstraints = false
        postTextLabelStack.axis = .vertical
        postTextLabelStack.alignment = .fill
        postTextLabelStack.distribution = .fill
        postTextLabelStack.isLayoutMarginsRelativeArrangement = true
        postTextLabelStack.layoutMargins.left = 16
        postTextLabelStack.layoutMargins.right = 16
        postTextLabelStack.layoutMargins.top = 16
        postTextLabelStack.layoutMargins.bottom = 16

        let stack = UIStackView(arrangedSubviews: [labelStack, postImageView, postTextLabelStack])
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.axis = .vertical
        stack.alignment = .fill
        stack.distribution = .fill
        stack.backgroundColor = .blue

        self.addSubview(stack)

        //postImageView.heightAnchor.constraint(equalTo: postImageView.widthAnchor).isActive = true

        stack.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        stack.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
        stack.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
        stack.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true

    }
}

</code>```

答:
The issue is that when the optionsButtons is created the self is still not initialized. Hence you need to make the button lazy var so that it could be loaded lazily when the optionsButtons is called and the UICollectionViewCell is initialized. Adding the target before self is initialized doesn't work.

To fix your issue, modify your optionsButtons declaration to lazy var, like this:

lazy var optionsButtons: UIButton = {
```

<p>OR</p>

<p>Add the target after the UICollectionViewCell is initialized, like this:</p>

<pre class="lang-swift prettyprint-override"><code>override init(frame: CGRect) {
    super.init(frame: frame)
    optionsButtons.addTarget(self, action: #selector(handleOptions), for: .touchUpInside)
    setupComponents()
}
</code>```

Body:
A UICollectionView I have created doesn't want to fire a custom cell delegate.

The cells are displaying, and the test button accepts presses.

I have debugged the code and the cell.delegate is being assigned self.

I have researched this on google and I have come up with nothing. I think my code is ok but I must be missing something?

I would really appreciate any help.

//HomeControllerDelegateTesting.swift

import UIKit

class HomeControllerDelegateTesting: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, PostCellOptionsDelegate {

    var collectionView: UICollectionView! = nil

    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: self.createLayout())
        self.collectionView.register(PostCell.self, forCellWithReuseIdentifier: PostCell.reuseIdentifier)
        self.collectionView.backgroundColor = .systemBackground
        self.view.addSubview(collectionView)
        self.collectionView.dataSource = self
        self.collectionView.delegate = self

    }

    private func createLayout() -> UICollectionViewLayout {
        let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                             heightDimension: .fractionalHeight(1.0))
        let item = NSCollectionLayoutItem(layoutSize: itemSize)

        let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                               heightDimension: .estimated(300))
        let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize,
                                                         subitems: [item])
        let section = NSCollectionLayoutSection(group: group)

        let layout = UICollectionViewCompositionalLayout(section: section)
        return layout
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PostCell.reuseIdentifier, for: indexPath) as? PostCell else { fatalError("Cannot create cell") }

        cell.postTextLabel.text = "Test"
        cell.delegate = self
        //Test to eliminiate the button accepts events
        //cell.optionsButtons.addTarget(self, action: #selector(test), for: .touchUpInside)
        return cell
    }

    @objc func handlePostOptions(cell: PostCell) {
        print("123")
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3
    }
}

//  PostCell.swift

import UIKit

protocol PostCellOptionsDelegate: class {
    func handlePostOptions(cell: PostCell)
}

class PostCell: UICollectionViewCell {
    static let reuseIdentifier = "list-cell-reuse-identifier"

    var delegate: PostCellOptionsDelegate?

    let usernameLabel: UILabel = {
        let label = UILabel()
        label.text = "Username"
        label.font = .boldSystemFont(ofSize: 15)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let postImageView: UIImageView = {
        let control = UIImageView()
        control.translatesAutoresizingMaskIntoConstraints = false
        control.contentMode = .scaleAspectFill
        control.clipsToBounds = true
        return control
    }()

    let postTextLabel: UILabel = {
        let label = UILabel()
        label.text = "Post text spanning multiple lines"
        label.font = .systemFont(ofSize: 15)
        label.numberOfLines = 0
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

//    private let optionsButtons: UIButton = {
//        let control = UIButton.systemButton(with: #imageLiteral(resourceName: "post_options"), target: self, action: #selector(handleOptions))
//        control.translatesAutoresizingMaskIntoConstraints = false
//        return control
//    }()

    let optionsButtons: UIButton = {
        let control = UIButton(type: .system)
        control.setTitle("Test", for: .normal)
        control.addTarget(self, action: #selector(handleOptions), for: .touchUpInside)
        control.translatesAutoresizingMaskIntoConstraints = false
        return control
    }()

    @objc fileprivate func handleOptions() {
        print("Handle options button")
        delegate?.handlePostOptions(cell: self)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupComponents()

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupComponents() {

        self.optionsButtons.heightAnchor.constraint(equalToConstant: 50).isActive = true

        let labelStack = UIStackView(arrangedSubviews: [optionsButtons])
        labelStack.translatesAutoresizingMaskIntoConstraints = false
        labelStack.axis = .horizontal
        labelStack.alignment = .fill
        labelStack.distribution = .fill
        labelStack.isLayoutMarginsRelativeArrangement = true
        labelStack.layoutMargins.left = 16
        labelStack.layoutMargins.right = 16
        labelStack.layoutMargins.top = 16
        labelStack.layoutMargins.bottom = 16

        let postTextLabelStack = UIStackView(arrangedSubviews: [postTextLabel])

        postTextLabelStack.translatesAutoresizingMaskIntoConstraints = false
        postTextLabelStack.axis = .vertical
        postTextLabelStack.alignment = .fill
        postTextLabelStack.distribution = .fill
        postTextLabelStack.isLayoutMarginsRelativeArrangement = true
        postTextLabelStack.layoutMargins.left = 16
        postTextLabelStack.layoutMargins.right = 16
        postTextLabelStack.layoutMargins.top = 16
        postTextLabelStack.layoutMargins.bottom = 16

        let stack = UIStackView(arrangedSubviews: [labelStack, postImageView, postTextLabelStack])
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.axis = .vertical
        stack.alignment = .fill
        stack.distribution = .fill
        stack.backgroundColor = .blue

        self.addSubview(stack)

        //postImageView.heightAnchor.constraint(equalTo: postImageView.widthAnchor).isActive = true

        stack.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        stack.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
        stack.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
        stack.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true

    }
}

Body:
The issue is that when the optionsButtons is created the self is still not initialized. Hence you need to make the button lazy var so that it could be loaded lazily when the optionsButtons is called and the UICollectionViewCell is initialized. Adding the target before self is initialized doesn't work.

To fix your issue, modify your optionsButtons declaration to lazy var, like this:

lazy var optionsButtons: UIButton = {

OR

Add the target after the UICollectionViewCell is initialized, like this:

override init(frame: CGRect) {
    super.init(frame: frame)
    optionsButtons.addTarget(self, action: #selector(handleOptions), for: .touchUpInside)
    setupComponents()
}


来源: stackexchange

问:
How does flex match the beginning of line anchor?
I've always wondered how the beginning of input anchor (^) was converted to a FSA in flex. I know that the end of line anchor ($) is matched by the expression r/\n where r is the expression to match. How's the beginning of input anchor matched? The only solution I see is to use start conditions. How can it be implemented in a program?

答:
The beginning of line anchor is matched by the pattern:

beginningOfLine    ^.

(a caret followed by a point)

Example (numbering lines of a text):

```<code>%{
int ln = 1;
%}

beginningOfLine ^.
newline \n

%%
{beginningOfLine} { if (ln == 1) {
                        printf ("%d \t", ln);
                        printf (yytext);
                        ln++;
                    }else{
                        printf (yytext);
                    }
                  }

{newline}         { printf ("\n");
                    printf ("%d \t", ln);
                    ln++; }

%%
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The beginning of line anchor is matched by the pattern:

beginningOfLine    ^.

(a caret followed by a point)

Example (numbering lines of a text):

%{
int ln = 1;
%}

beginningOfLine ^.
newline \n

%%
{beginningOfLine} { if (ln == 1) {
                        printf ("%d \t", ln);
                        printf (yytext);
                        ln++;
                    }else{
                        printf (yytext);
                    }
                  }

{newline}         { printf ("\n");
                    printf ("%d \t", ln);
                    ln++; }

%%

ContentLicense: CC BY-SA 4.0


问:
Java. groupingBy throw to classes
I cant write a collector that calculates the total sum of transactions (long type, not integer) by each account (i.e. by account number). The collector will be applied to a stream of transactions.
How to use groupingBy for this chain Transaction -> Account -> Number ?

```<code>class TransactionCollector {

public static Map<String, Long> getAccount2TransSum(List<Transaction> trans) {
    return trans.stream().collect(  // place code here
            }

static class Transaction {

    private final String uuid;
    private final Long sum;
    private final Account account;

    public Transaction(String uuid, Long sum, Account account) {
        this.uuid = uuid;
        this.sum = sum;
        this.account = account;
    }

    public String getUuid() {
        return uuid;
    }

    public Long getSum() {
        return sum;
    }

    public Account getAccount() {
        return account;
    }

    @Override
    public String toString() {
        return "Transaction{" +
                "uuid='" + uuid + '\'' +
                ", sum=" + sum +
                '}';
    }
}

static class Account {
    private final String number;
    private final Long balance;

    public Account(String number, Long balance) {
        this.number = number;
        this.balance = balance;
    }

    public String getNumber() {
        return number;
    }

    public Long getBalance() {
        return balance;
    }

    @Override
    public String toString() {
        return "Account{" +
                "number='" + number + '\'' +
                ", balance=" + balance +
                '}';
    }
}
</code>```

}

答:
You can use a downstream collector

```<code>trans.stream().collect(
  groupingBy(
    Transaction::getAccount,
    groupingBy(Account::getNumber)
  )
)
</code>```

This will first group the transactions by their accounts, and then by their numbers

EDIT:
It seems like you actually want the toMap collector

```<code>trans.stream().collect(
    toMap(
      t -> t.getAccount().getNumber(),
      t -> t.getSum()
    )
)
</code>```

Title: Java. groupingBy throw to classes

Body:
I cant write a collector that calculates the total sum of transactions (long type, not integer) by each account (i.e. by account number). The collector will be applied to a stream of transactions.
How to use groupingBy for this chain Transaction -> Account -> Number ?

class TransactionCollector {

public static Map<String, Long> getAccount2TransSum(List<Transaction> trans) {
    return trans.stream().collect(  // place code here
            }

static class Transaction {

    private final String uuid;
    private final Long sum;
    private final Account account;

    public Transaction(String uuid, Long sum, Account account) {
        this.uuid = uuid;
        this.sum = sum;
        this.account = account;
    }

    public String getUuid() {
        return uuid;
    }

    public Long getSum() {
        return sum;
    }

    public Account getAccount() {
        return account;
    }

    @Override
    public String toString() {
        return "Transaction{" +
                "uuid='" + uuid + '\'' +
                ", sum=" + sum +
                '}';
    }
}

static class Account {
    private final String number;
    private final Long balance;

    public Account(String number, Long balance) {
        this.number = number;
        this.balance = balance;
    }

    public String getNumber() {
        return number;
    }

    public Long getBalance() {
        return balance;
    }

    @Override
    public String toString() {
        return "Account{" +
                "number='" + number + '\'' +
                ", balance=" + balance +
                '}';
    }
}

}

Body:
You can use a downstream collector

trans.stream().collect(
  groupingBy(
    Transaction::getAccount,
    groupingBy(Account::getNumber)
  )
)

This will first group the transactions by their accounts, and then by their numbers

EDIT:
It seems like you actually want the toMap collector

trans.stream().collect(
    toMap(
      t -> t.getAccount().getNumber(),
      t -> t.getSum()
    )
)


问:
How can i make a plugin execute a command from another plugin?
i need help in developing pretty simple plugin for miencraft version 1.15.2

Plugin is made to check if user has allready logged for a first time if not:
i adds him to a hashmap (so it wont check him twice) and executes a command on a player to add give him permission from plugin LuckPerms.

I've found out that there is PluginCommand:
https://hub.spigotmc.org/javadocs/spigot/org/bukkit/command/PluginCommand.html
But im not quite sure how to use it to make it perform (as server):
/lp user playerName group add groupname

EDIT:
I just can't find how to execute a command so the player will get the permission.

Thanks for your time.

答:
in your use case the LuckPerms API would make sense to me.
You could use the API to set the Rank of the player loggin in.

```<code>LuckPerms api = LuckPermsProvider.get();
api.getUserManager().getUser(uuid).setPrimaryGroup("groupname");
</code>```

For more info check the Wiki

Body:
in your use case the LuckPerms API would make sense to me.
You could use the API to set the Rank of the player loggin in.

LuckPerms api = LuckPermsProvider.get();
api.getUserManager().getUser(uuid).setPrimaryGroup("groupname");

For more info check the Wiki


问:
Get label for given level of factor in R
Given this factor:

```<code>> str(some$factor)
 Factor w/ 398 levels "13:23","13:24",..: 1 2 3 4 5 6 7 8 9 10 ...

> levels(some$factor)
  [1] "13:23" "13:24" "13:25" "13:26" "13:27" ...

> labels(some$factor)
  [1] "1"   "2"   "3"   "4"   "5" ...
</code>```

how can I get a label (e.g. "2") for a given level (e.g. "13:24")?

答:
We can create an index with match to extract the corresponding labels in base R

```<code>labels(some$factor)[match("13:24", levels(some$factor))]
#[1] "2"
</code>```

data

```<code>some <- data.frame(factor  = c("13:23", "13:24", "13:25"), stringsAsFactors = TRUE)
</code>```

Body:
Given this factor:

> str(some$factor)
 Factor w/ 398 levels "13:23","13:24",..: 1 2 3 4 5 6 7 8 9 10 ...

> levels(some$factor)
  [1] "13:23" "13:24" "13:25" "13:26" "13:27" ...

> labels(some$factor)
  [1] "1"   "2"   "3"   "4"   "5" ...

how can I get a label (e.g. "2") for a given level (e.g. "13:24")?

Body:
We can create an index with match to extract the corresponding labels in base R

labels(some$factor)[match("13:24", levels(some$factor))]
#[1] "2"

data

some <- data.frame(factor  = c("13:23", "13:24", "13:25"), stringsAsFactors = TRUE)


问:
Migration Cordova to Capacitor - error: package android.support.v4.content does not exist
I'm trying to migrate my ionic app from cordova to capacitor.

But I'm getting an error in Android build.

```<code>android\capacitor-cordova-android-plugins\src\main\java\nl\xservices\plugins\FileProvider.java:4: error: package android.support.v4.content does not exist
public class FileProvider extends android.support.v4.content.FileProvider {
</code>```

Does anyone knows how to solve this problem?

答: try npx cap sync command after adding any plugins. That works for me.

Body:
I'm trying to migrate my ionic app from cordova to capacitor.

But I'm getting an error in Android build.

android\capacitor-cordova-android-plugins\src\main\java\nl\xservices\plugins\FileProvider.java:4: error: package android.support.v4.content does not exist
public class FileProvider extends android.support.v4.content.FileProvider {

Does anyone knows how to solve this problem?


问:
center the dots of the unorder list in html
I have tried to fix this, but the bullets are staying to the left, but text is formatting correctly. I used
text-align: center , but that only formats the text, and not the bullets. Here is my code:

<!DOCTYPE html>

Header Label

first

second

three

```
</div>
</div>
</p>

<p>It should look like below (here * represents bullets):</p>

```                                * first
                                * second
                                * third
```

答:
#inner {
  display: table;
  margin: 0 auto;
}

#outer {
  width: 100%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="outer">
  <div id="inner">
    <h1>Header Label</h1>
  </div>
  <div id="inner">
    <ul>
      <li>first</li>
      <li>second</li>
      <li>three</li>
    </ul>
  </div>
</div></code>```

Body:
I have tried to fix this, but the bullets are staying to the left, but text is formatting correctly. I used
text-align: center , but that only formats the text, and not the bullets. Here is my code:

<!DOCTYPE html>

Header Label

first

second

three

It should look like below (here * represents bullets):

                                * first
                                * second
                                * third

Body:
#inner {
  display: table;
  margin: 0 auto;
}

#outer {
  width: 100%
}

<div id="outer">
  <div id="inner">
    <h1>Header Label</h1>
  </div>
  <div id="inner">
    <ul>
      <li>first</li>
      <li>second</li>
      <li>three</li>
    </ul>
  </div>
</div>


问:
How to declare a variable in python without assigning a value?
I'm trying to create graphs of the Mandelbrot set.
I have managed to do this by iterating over a lot of points but this takes a lot of processing power, so I'm now trying to generate a polynomial by iterating f(z) = z**2 + c many times and then finding the roots for z = c, in order to generate a boundary of the set.

However I can't seem to get Python to generate the polynomial, any help would be much apprecaited.

Edit:Implemented azro's fix but now I get the error - TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'int'

Code so far:

```<code>import numpy as np

c = None

def f(z):
    return z**2 + c

eqn = c

for i in range(100):
    eqn = f(eqn)

np.roots(eqn)
</code>```

Body:
I'm trying to create graphs of the Mandelbrot set.
I have managed to do this by iterating over a lot of points but this takes a lot of processing power, so I'm now trying to generate a polynomial by iterating f(z) = z**2 + c many times and then finding the roots for z = c, in order to generate a boundary of the set.

However I can't seem to get Python to generate the polynomial, any help would be much apprecaited.

Edit:Implemented azro's fix but now I get the error - TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'int'

Code so far:

import numpy as np

c = None

def f(z):
    return z**2 + c

eqn = c

for i in range(100):
    eqn = f(eqn)

np.roots(eqn)

Body:
This is a very hard problem. Searching through literature, I only found this (which doesn't seem very reputable). However, it does seem to begin to create what you want. This is only up to 8 iterations. So the polynomial gets very complicated very fast. See the following code:

import matplotlib.pyplot as plt

coeff = [0, 1, 1, 2, 5, 14, 26, 44, 69, 94, 114, 116, 94, 60, 28, 8, 1]
coeff = [0, 1, 1, 2, 5, 14, 42, 132, 429, 1302, 3774, 10652, 29538, 80812, 218324, 582408, 1534301, 3993030, 10269590, 26108844, 65626918, 163107044, 400844588, 974083128, 2340595778, 5560968284, 13062923500, 30336029592, 69640352964, 158015533208, 354347339496, 785248461712, 1719477330477, 3720187393990, 7952125694214, 16792863663700, 35031835376454, 72188854953372, 146932182777116, 295372837865192, 586400982013486, 1149605839249820, 2225301467579844, 4252710138415640, 8022825031835276, 14938862548001560, 27452211062573400, 49778848242964944, 89054473147697354, 157160523515654628, 273551721580800380, 469540646039042536, 794643418760272876, 1325752376790240280, 2180053774442766712, 3532711259225506384, 5640327912922026260, 8870996681171366696, 13741246529612440920, 20959276151880728336, 31472438318100876584, 46514944583399578896, 67649247253332557392, 96791719611591962592, 136210493669590627493, 188481251186354006062, 256386228250001079082, 342743629811082484420, 450159936955994386738, 580706779030058464252, 735537050036491961156, 914470757914434625800, 1115597581733327913554, 1334957092752100409132, 1566365198635995978988, 1801452751402955781592, 2029966595320794439668, 2240353897304462193848, 2420609646335251593480, 2559320275988283588176, 2646791812246207696810, 2676118542978972739644, 2644036970936308845148, 2551425591643957182856, 2403354418943890067404, 2208653487832260558008, 1979045408073272278264, 1727958521630464742736, 1469189341596552030212, 1215604411161527170376, 978057923319151340728, 764655844340519788496, 580430565842543266504, 427417353874088245520, 305060580205223726864, 210835921361505594848, 140960183546144741182, 91071943593142473900, 56796799826096529620, 34150590308701283528, 19772322481956974532, 11008161481780603512, 5884917700519129288, 3016191418506637264, 1479594496462756340, 693434955498545848, 309881648709683160, 131760770157606224, 53181959591958024, 20324543852025936, 7333879739219600, 2490875091238112, 793548088258508, 236221241425176, 65418624260840, 16771945556496, 3958458557608, 854515874096, 167453394320, 29524775520, 4634116312, 639097008, 76185104, 7685024, 637360, 41696, 2016, 64, 1]

r = np.roots(coeff)

plt.plot(r.real, r.imag, '.')

I would suggest something more like the following (stolen and modified from here). This sounds like something you've already tried. But try changing the max iterations to get something that can run relatively fast (30 was fast and had relatively high resolution for me).

MAX_ITER = 30

def mandelbrot(c):
    z = 0
    n = 0
    while abs(z) <= 2 and n < MAX_ITER:
        z = z*z + c
        n += 1
    return n

# Image size (pixels)
WIDTH = 600
HEIGHT = 400

# Plot window
RE_START = -2
RE_END = 1
IM_START = -1
IM_END = 1

img = np.zeros((WIDTH, HEIGHT))
for x in range(0, WIDTH):
    for y in range(0, HEIGHT):
        # Convert pixel coordinate to complex number
        c = complex(RE_START + (x / WIDTH) * (RE_END - RE_START),
                    IM_START + (y / HEIGHT) * (IM_END - IM_START))
        # Compute the number of iterations
        m = mandelbrot(c)

        if m > MAX_ITER-1:
          img[x, y] = 1

plt.imshow(img.T, cmap='bone')


问:
How to set y-axis tick label in matplot lib
My Y-aixs tick labels are showing strange behaviour.
By default Y-axis has maximum limit as read from file but I could not increase the label size.
So I have inserted

```<code>ax2.tick_params(axis="y", labelsize=28)
</code>```

After inserting this line the Y-axis goes to 15 and the minor tick label are at the interval of 2.5 and appears as flots (example, 1 is appearing as 1.0)

I have tried with below to make the Y-axis labels integer but could not.

```<code>ax1.set_yticklabels(tick_labels.astype(int))
</code>```

I want to keep my Y-axis labels defaults but want to increase the label size.

I am getting below error

```<code>    ax1.set_yticklabels(tick_labels.astype(int))
NameError: name 'tick_labels' is not defined
</code>```

答:
You can try the following solution as per this answer</p>

```<code>import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

fig, ax = plt.subplots()

# your code here

# For minor ticks
ax.yaxis.set_minor_locator(MaxNLocator(integer=True))

# For major ticks
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
</code>```

Body:
My Y-aixs tick labels are showing strange behaviour.
By default Y-axis has maximum limit as read from file but I could not increase the label size.
So I have inserted

ax2.tick_params(axis="y", labelsize=28)

After inserting this line the Y-axis goes to 15 and the minor tick label are at the interval of 2.5 and appears as flots (example, 1 is appearing as 1.0)

I have tried with below to make the Y-axis labels integer but could not.

ax1.set_yticklabels(tick_labels.astype(int))

I want to keep my Y-axis labels defaults but want to increase the label size.

I am getting below error

    ax1.set_yticklabels(tick_labels.astype(int))
NameError: name 'tick_labels' is not defined

Body:
You can try the following solution as per this answer

import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

fig, ax = plt.subplots()

# your code here

# For minor ticks
ax.yaxis.set_minor_locator(MaxNLocator(integer=True))

# For major ticks
ax.yaxis.set_major_locator(MaxNLocator(integer=True))


答:
Change your button declaration to this:</p>

```<code>// make this a lazy var
lazy var optionsButtons: UIButton = {
    let control = UIButton(type: .system)
    control.setTitle("Test", for: .normal)
    // add self. to the selector
    control.addTarget(self, action: #selector(self.handleOptions), for: .touchUpInside)
    control.translatesAutoresizingMaskIntoConstraints = false
    return control
}()
</code>```

Title: UICollectionCellView delegate not being fired

Body:
Change your button declaration to this:

// make this a lazy var
lazy var optionsButtons: UIButton = {
    let control = UIButton(type: .system)
    control.setTitle("Test", for: .normal)
    // add self. to the selector
    control.addTarget(self, action: #selector(self.handleOptions), for: .touchUpInside)
    control.translatesAutoresizingMaskIntoConstraints = false
    return control
}()


问:
PHP/MySQL - Performance considerations querying (select only) 48k rows
I am currently attempting to build a web application that relies quite heavily on postcode data (supplied from OS CodePoint Open). The postcode database has 120 tables which breaks down the initial postcode prefix (i.e. SE, WS, B). Inside these tables there are between 11k - 48k rows with 3 fields (Postcode, Lat, Lng).

What I need to be able to do is for a user to come online, enter their postcode i.e. SE1 1LD which then selects the SE table, and converts the postcode into a lat / lng.

I am fine with doing this on a PHP level. My concern is.. well the huge number of rows that will be queried and whether it is going to grind my website to a halt?

If there are any techniques that I should know about, please do let me know.. I've never worked with tables with big numbers in!

Thanks :)

答:
If I understand correct, there is a SE table, a WS one, a B one, etc. In all, 120 tables with same structure (Postcode, Lat, Lng).

I strongly propose you normalize the tables.

You can have either one table:

```<code>postcode( prefix, postcode, lat, lng)
</code>```

or two:

```<code>postcode( prefixid , postcode, lat, lng )

prefix( prefixid, prefix )
</code>```

The postcode table will be slighly bigger than 11K-48K rows, about 30K x 120 = 3.6M rows but it will save you time for writing different queries for every prefix and quite complex ones if, for example, you want to search for latitude and longitude (imagine a query that searches in 120 tables).

If you are not convinced try to add a person table so you can add data for your users. How this table will be related to the postcode table(s) ?

EDIT

Since the prefix is just the first characters of the postcode which is also the primary key, there is no need for extra field or second table. I would simply combine the 120 tables into one:

```<code>postcode( postcode, lat, lng )
</code>```

Then queries like:

```<code>SELECT *
FROM postode
WHERE postcode = 'SE11LD'
</code>```

or

```<code>SELECT *
FROM postode
WHERE postcode LIKE 'SE%'
</code>```

will be fast, as they will be using the primary key index.

Body:
If I understand correct, there is a SE table, a WS one, a B one, etc. In all, 120 tables with same structure (Postcode, Lat, Lng).

I strongly propose you normalize the tables.

You can have either one table:

postcode( prefix, postcode, lat, lng)

or two:

postcode( prefixid , postcode, lat, lng )

prefix( prefixid, prefix )

The postcode table will be slighly bigger than 11K-48K rows, about 30K x 120 = 3.6M rows but it will save you time for writing different queries for every prefix and quite complex ones if, for example, you want to search for latitude and longitude (imagine a query that searches in 120 tables).

If you are not convinced try to add a person table so you can add data for your users. How this table will be related to the postcode table(s) ?

EDIT

Since the prefix is just the first characters of the postcode which is also the primary key, there is no need for extra field or second table. I would simply combine the 120 tables into one:

postcode( postcode, lat, lng )

Then queries like:

SELECT *
FROM postode
WHERE postcode = 'SE11LD'

or

SELECT *
FROM postode
WHERE postcode LIKE 'SE%'

will be fast, as they will be using the primary key index.


问:
Persistent layout in Next.js with TypeScript and HOC
I want to add a persistent layout to certain pages of my Next.js application. I found this article explaining a couple ways on how someone could do this. It seems pretty straightforward, however I have encountered the following two problems when using the recommended way of doing it:

I am using TypeScript and am not sure how to type it. For example, I have the following, which is working, but I obviously don't like using as any:

```<code>const getLayout =
    (Component as any).getLayout ||
    ((page: NextPage) => <SiteLayout children={page} />);
</code>```

I am using Apollo and so I am using a withApollo HOC (from here) for certain pages. Using this causes Component.getLayout to always be undefined. I don't have a good enough understanding of what is going on to know why this is happening (I can guess), so it's difficult to solve this by myself.

Since asking this question they have added a good example to their documentation

答:
I believe next.js provides a Component prop as a part of AppProps. This example should have what you are looking for.

You may need to assign getLayout after creating the component wrapped with withApollo:

```<code>import CustomLayout = CustomLayout;
const MyPage = () => (...);

const MyPageWithApollo = withApollo(MyPage);
MyPageWithApollo.Layout = CustomLayout;
export default MyPageWithApollo;
</code>```

Additionally, next.js has two examples you can use to achieve exactly this (not written in typescript though):

Dynamic App Layout

With Apollo

Body:
I want to add a persistent layout to certain pages of my Next.js application. I found this article explaining a couple ways on how someone could do this. It seems pretty straightforward, however I have encountered the following two problems when using the recommended way of doing it:

I am using TypeScript and am not sure how to type it. For example, I have the following, which is working, but I obviously don't like using as any:

const getLayout =
    (Component as any).getLayout ||
    ((page: NextPage) => <SiteLayout children={page} />);

I am using Apollo and so I am using a withApollo HOC (from here) for certain pages. Using this causes Component.getLayout to always be undefined. I don't have a good enough understanding of what is going on to know why this is happening (I can guess), so it's difficult to solve this by myself.

Since asking this question they have added a good example to their documentation

Body:
I believe next.js provides a Component prop as a part of AppProps. This example should have what you are looking for.

You may need to assign getLayout after creating the component wrapped with withApollo:

import CustomLayout = CustomLayout;
const MyPage = () => (...);

const MyPageWithApollo = withApollo(MyPage);
MyPageWithApollo.Layout = CustomLayout;
export default MyPageWithApollo;

Additionally, next.js has two examples you can use to achieve exactly this (not written in typescript though):

Dynamic App Layout

With Apollo


问:
Why is my code working fine when running in the console but not when used in the script?
When I tried the following code in my IDE and in the command prompt with python test.py, my text file was still empty afterward:

```<code>with open("test.txt", "r+") as file:
    file.write("Hello World")
</code>```

I was confused, because this worked before. So I tried the exact same code in the python console.
And voila, my text file test.txt now contained the string Hello World

When I changed the content of the text file manually and tried to read it again with the program, the output was the string I tried to write earlier to the text file.

Is there some kind of delay when trying to write and read to and from a file when using a script in comparison to using the python console?

答:
Try pass the absolute path of the file.

It should be like this

```<code>with open("/the/path/test.txt", "r+") as file:
    file.write("Hello World")
</code>```

Body:
When I tried the following code in my IDE and in the command prompt with python test.py, my text file was still empty afterward:

with open("test.txt", "r+") as file:
    file.write("Hello World")

I was confused, because this worked before. So I tried the exact same code in the python console.
And voila, my text file test.txt now contained the string Hello World

When I changed the content of the text file manually and tried to read it again with the program, the output was the string I tried to write earlier to the text file.

Is there some kind of delay when trying to write and read to and from a file when using a script in comparison to using the python console?

Body:
Try pass the absolute path of the file.

It should be like this

with open("/the/path/test.txt", "r+") as file:
    file.write("Hello World")


问:
How to programmatically get pages which is pending for approval?
I having a Site with multiple SubSite inherited,

each of the SubSite got a default Sharepoint approval workflow attached on Pages Library,

therefore, whenever the pages is submit for approval,

there will be a task created in Workflow Tasks List on each of the SubSite.

By using SPSiteDataQuery manage to query data from all the subsite in Workflow Tasks List, as per following example:

```<code>DataTable dt = null;
using (SPSite site = new SPSite("Site Url"))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPSiteDataQuery q = new SPSiteDataQuery();
        q.Lists = "<Lists ServerTemplate='107' />";
        q.Query = @"<OrderBy><FieldRef Name='Modified' Ascending='False' /></OrderBy>";
        q.ViewFields = "<FieldRef Name=\"Title\" />"\;
        q.Webs = "<Webs Scope='Recursive'/>";
        q.RowLimit = 20;

        dt = web.GetSiteData(q);
    }
}
return dt;
</code>```

whenever the page is pending for approval, the workflow status is Not Started and it is Completed when it is approved.

So if I query based on all workflow status equal Not Started, then it will return all results which is pending for approval?
and how can I get the pages Title and FileRefUrl?

thank you in advance for any advises.

答:
Personally, I would do this:</p>

```<code>        using (SPSite site = new SPSite(SharepointServerURL))
        {
            using (SPWeb web = site.OpenWeb())
            {
                SPFolder sitePages = web.Folders["/SitePages"];
                SPListItemCollection pages = sitePages.DocumentLibrary.Items;

                foreach (SPListItem page in pages)
                {
                    if (page.ModerationInformation.Status == SPModerationStatusType.Pending)
                    {
                        Console.WriteLine(page.Title + page.Url);
                    }
                }
            }
        }
</code>```

Body:
I having a Site with multiple SubSite inherited,

each of the SubSite got a default Sharepoint approval workflow attached on Pages Library,

therefore, whenever the pages is submit for approval,

there will be a task created in Workflow Tasks List on each of the SubSite.

By using SPSiteDataQuery manage to query data from all the subsite in Workflow Tasks List, as per following example:

DataTable dt = null;
using (SPSite site = new SPSite("Site Url"))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPSiteDataQuery q = new SPSiteDataQuery();
        q.Lists = "<Lists ServerTemplate='107' />";
        q.Query = @"<OrderBy><FieldRef Name='Modified' Ascending='False' /></OrderBy>";
        q.ViewFields = "<FieldRef Name=\"Title\" />"\;
        q.Webs = "<Webs Scope='Recursive'/>";
        q.RowLimit = 20;

        dt = web.GetSiteData(q);
    }
}
return dt;

whenever the page is pending for approval, the workflow status is Not Started and it is Completed when it is approved.

So if I query based on all workflow status equal Not Started, then it will return all results which is pending for approval?
and how can I get the pages Title and FileRefUrl?

thank you in advance for any advises.

Body:
Personally, I would do this:

        using (SPSite site = new SPSite(SharepointServerURL))
        {
            using (SPWeb web = site.OpenWeb())
            {
                SPFolder sitePages = web.Folders["/SitePages"];
                SPListItemCollection pages = sitePages.DocumentLibrary.Items;

                foreach (SPListItem page in pages)
                {
                    if (page.ModerationInformation.Status == SPModerationStatusType.Pending)
                    {
                        Console.WriteLine(page.Title + page.Url);
                    }
                }
            }
        }


问:
How to convert string object to Json in Nestjs
I want to convert this to json. I tried JSON.parse() but got this error

```<code>"{"status":"00","message":"OK","access_token":"2347682423567","customer":{"name":"John Doe","address":"Mr. John Doe 34 Tokai, leaflet. 7999.","util":"Demo Utility","minimumAmount":"13897"},"response_hash":"c43c9d74480f340f55156f6r5c56487v8w"}"
</code>```

There is the error

```<code>SyntaxError: Unexpected token  in JSON at position 0

</code>```

That means I have to remove the first double quote. I don't know how to do remove it.

How can achieve this and get a valid json?

The code here below

```<code> const url = `https://irecharge.com.ng/pwr_api_sandbox/v2/get_meter_info.php?vendor_code=${vendorcode}&reference_id=${reference_id}&meter=${meterNum}&disco=${discoName}&response_format=json&hash=${hash}`;

            const meterInfo = await this.httpService.get(url).toPromise();

            const data = meterInfo.data;

            const data = meterInfo.data;
            var ParsedData = JSON.parse(data.substring(1, data.length - 1))

            console.log(ParsedData);
            return ParsedData
    ```
I am supposed to pass response format, which should be json as you can see in the code

```

答:
That URL is returning valid JSON. (I added dummy values to get a response) source

That means I have to remove the first double quote. I don't know how to do remove it.

I would try to figure out where the extra quotes are coming from in the first place rather than remove it after the fact.

Body:
I want to convert this to json. I tried JSON.parse() but got this error

"{"status":"00","message":"OK","access_token":"2347682423567","customer":{"name":"John Doe","address":"Mr. John Doe 34 Tokai, leaflet. 7999.","util":"Demo Utility","minimumAmount":"13897"},"response_hash":"c43c9d74480f340f55156f6r5c56487v8w"}"

There is the error

SyntaxError: Unexpected token  in JSON at position 0

That means I have to remove the first double quote. I don't know how to do remove it.

How can achieve this and get a valid json?

The code here below

 const url = `https://irecharge.com.ng/pwr_api_sandbox/v2/get_meter_info.php?vendor_code=${vendorcode}&reference_id=${reference_id}&meter=${meterNum}&disco=${discoName}&response_format=json&hash=${hash}`;

            const meterInfo = await this.httpService.get(url).toPromise();

            const data = meterInfo.data;

            const data = meterInfo.data;
            var ParsedData = JSON.parse(data.substring(1, data.length - 1))

            console.log(ParsedData);
            return ParsedData
    ```
I am supposed to pass response format, which should be json as you can see in the code


问:
How to split a list which contains sentences into a list with words using Python?
I have a list with sentences in Python:

```<code>list1 = ["This is the first sentence", "This is the second", "This is the third"]
</code>```

I tried using split(" "):

```<code>sth = []
for i in list1:
    sth.append(i.split(" "))
</code>```

But this way I get a 2D array, which contains regular lists from the sentences with their words, so something like this:

```<code>[["This", "is", "the", "first", "sentence"], ["This", "is", "the", "second"], ["This", "is", "the", "third"]]
</code>```

I would like the outcome to be a regular list, this way:

```<code>["This", "is", "the", "first", "sentence", "This", "is", "the", "second", "This", "is", "the", "third"]
</code>```

How can I achieve this?

答:
You will have to use extend instead of append.

The basic difference between append and extend is that append is used to add one element at the end of the existing list while extend is used when we have to merge two list extend will iterate through the passed argument and add them to the existing list at a index of n+1,n+2,n+3…(where n is existing length of the list)

Here is the code:

list1 = ["This is the first sentence", "This is the second", "This is the third"]

sth = []
for i in list1:
    sth.extend(i.split(" "))   # Here is the change

```

<p>Here is the output from terminal:</p>

```>>> print(sth)
['This', 'is', 'the', 'first', 'sentence', 'This', 'is', 'the', 'second', 'This', 'is', 'the', 'third']
```

Body:
I have a list with sentences in Python:

list1 = ["This is the first sentence", "This is the second", "This is the third"]

I tried using split(" "):

sth = []
for i in list1:
    sth.append(i.split(" "))

But this way I get a 2D array, which contains regular lists from the sentences with their words, so something like this:

[["This", "is", "the", "first", "sentence"], ["This", "is", "the", "second"], ["This", "is", "the", "third"]]

I would like the outcome to be a regular list, this way:

["This", "is", "the", "first", "sentence", "This", "is", "the", "second", "This", "is", "the", "third"]

How can I achieve this?

Body:
You will have to use extend instead of append.

The basic difference between append and extend is that append is used to add one element at the end of the existing list while extend is used when we have to merge two list extend will iterate through the passed argument and add them to the existing list at a index of n+1,n+2,n+3…(where n is existing length of the list)

Here is the code:

list1 = ["This is the first sentence", "This is the second", "This is the third"]

sth = []
for i in list1:
    sth.extend(i.split(" "))   # Here is the change

Here is the output from terminal:

>>> print(sth)
['This', 'is', 'the', 'first', 'sentence', 'This', 'is', 'the', 'second', 'This', 'is', 'the', 'third']


问:
Rendering an array.map() in React
I am having a problem where I am trying to use array of data to render a
 element. In the code below the console logs are working fine, but the list items aren't appearing.

```<code>var Main = React.createClass({
  getInitialState: function(){
    return {
      data: dataRecent
    }
  },

  render: function(){
    return (
      <div>
        <ul>
          {
           this.state.data.map(function(item, i){
             console.log('test');
             <li>Test</li>
           })
         }
        </ul>
      </div>
    )
  }
});

ReactDOM.render(<Main />, document.getElementById('app'));
</code>```

What am I doing wrong? Please feel free to point out anything that isn't best practice.

答:
Dmitry Brin's answer worked for me, with one caveat. In my case, I needed to run a function between the list tags, which requires nested JSX braces. Example JSX below, which worked for me:

```<code>{this.props.data().map(function (object, i) { return <li>{JSON.stringify(object)}</li> })}
</code>```

If you don't use nested JSX braces, for example:

```<code>{this.props.data().map(function (object, i) { return <li>JSON.stringify(object)</li>})}
</code>```

then you get a list of "JSON.stringify(object)" in your HTML output, which probably isn't what you want.

Title: Rendering an array.map() in React

Body:
I am having a problem where I am trying to use array of data to render a
 element. In the code below the console logs are working fine, but the list items aren't appearing.

var Main = React.createClass({
  getInitialState: function(){
    return {
      data: dataRecent
    }
  },

  render: function(){
    return (

          {
           this.state.data.map(function(item, i){
             console.log('test');

Test

           })
         }

    )
  }
});

ReactDOM.render(, document.getElementById('app'));

What am I doing wrong? Please feel free to point out anything that isn't best practice.

Body:
Dmitry Brin's answer worked for me, with one caveat. In my case, I needed to run a function between the list tags, which requires nested JSX braces. Example JSX below, which worked for me:

{this.props.data().map(function (object, i) { return <li>{JSON.stringify(object)}</li> })}

If you don't use nested JSX braces, for example:

{this.props.data().map(function (object, i) { return <li>JSON.stringify(object)</li>})}

then you get a list of "JSON.stringify(object)" in your HTML output, which probably isn't what you want.


问:
Discord.py - Sending images without blocking other commands from running
I need to send a picture, but while It is loading I don't want other commands being blocked from running until it finishes.

Is there a way to do this?

Maybe with asyncio or online image API's?

Thanks in advance!

Note:

This is how I currently send Images:

```<code>await ctx.send(file=discord.File('pics\doni (14).jpg'))
</code>```

答: You don't need to, as every command is an async function, meaning a coroutine. I've tested with a bot code that runs a computationally heavy expression (3 ** 1000000 which takes 10+ seconds to run) and entered it in two separate channels at the same time. The outputs were almost exactly together (although slightly slower as the processor was loaded higher).

Body:
I need to send a picture, but while It is loading I don't want other commands being blocked from running until it finishes.

Is there a way to do this?

Maybe with asyncio or online image API's?

Thanks in advance!

Note:

This is how I currently send Images:

await ctx.send(file=discord.File('pics\doni (14).jpg'))


问:
jQuery sortable obtain 2 elements being swapped
I cannot find out how to obtain destination element with jQuery UI sortable.

```<code>    $("#pages").sortable({
        opacity: 0.6,
        update: function(event, ui) {
            var first = ui.item; // First element to swap
            var second = ???? // Second element to swap
            swapOnServer(first, second);
        }
    });
</code>```

All the options I've tried point to the element being dragged, but not the one it is swapped with: ui.item[0], event.srcElement, event.toElement.

Additionally, this points to the LIST (OL) element.

Saying second I mean following:

Original order is:

| 0 | 1 | 2 | 3 |

We drag element 1 and drop it in position 3. Which will end up with:

| 0 | 3 | 2 | 1 |

So the first element is 1 and the second is 3 (WRONG! See below).

UPDATE: I have realised that I got it wrong. The new order in this case will be.

| 0 | 2 | 3 | 1 |

As a result my question does not really makes sense. Thanks everybody for the help. I'll mark vote and mark an answer.

So the question is how to obtain the second element here?

THE CURRENT WORKAROUND (as there is no term as swapping in sortable) is below. It uses temporary array with orders.

```<code>    var prevPagesOrder = [];
    $("#pages").sortable({
        start: function(event, ui) {
            prevPagesOrder = $(this).sortable('toArray');
        },
        update: function(event, ui) {
            var currentOrder = $(this).sortable('toArray');
            var first = ui.item[0].id;
            var second = currentOrder[prevPagesOrder.indexOf(first)];
            swapOnServer(first, second);
        }
    });
</code>```

Thanks,

Dmitriy.

答:
You can use http://plugins.jquery.com/project/Swapable

but this is not too good plugin

ContentLicense: CC BY-SA 2.5

Body:
I cannot find out how to obtain destination element with jQuery UI sortable.

    $("#pages").sortable({
        opacity: 0.6,
        update: function(event, ui) {
            var first = ui.item; // First element to swap
            var second = ???? // Second element to swap
            swapOnServer(first, second);
        }
    });

All the options I've tried point to the element being dragged, but not the one it is swapped with: ui.item[0], event.srcElement, event.toElement.

Additionally, this points to the LIST (OL) element.

Saying second I mean following:

Original order is:

| 0 | 1 | 2 | 3 |

We drag element 1 and drop it in position 3. Which will end up with:

| 0 | 3 | 2 | 1 |

So the first element is 1 and the second is 3 (WRONG! See below).

UPDATE: I have realised that I got it wrong. The new order in this case will be.

| 0 | 2 | 3 | 1 |

As a result my question does not really makes sense. Thanks everybody for the help. I'll mark vote and mark an answer.

So the question is how to obtain the second element here?

THE CURRENT WORKAROUND (as there is no term as swapping in sortable) is below. It uses temporary array with orders.

    var prevPagesOrder = [];
    $("#pages").sortable({
        start: function(event, ui) {
            prevPagesOrder = $(this).sortable('toArray');
        },
        update: function(event, ui) {
            var currentOrder = $(this).sortable('toArray');
            var first = ui.item[0].id;
            var second = currentOrder[prevPagesOrder.indexOf(first)];
            swapOnServer(first, second);
        }
    });

Thanks,

Dmitriy.


问:
C++ pointer not null but cannot be freed
I'm implementing an open HashTable. My trouble arises in the destructor, where I iterate through all the buckets in an array, for each array I would delete all the nodes in a linked list.

        // Deallocate all buckets
        for (int i=0; i<maxBuckets; i++) {
            Cell * p = m_data[i];
            while (p != nullptr) {

                Cell * temp = p;
                p = p->next;
                delete temp;
            }
        }
        delete [] m_data;

```

But it reports pointer being freed was not allocated on the delete operation. What is going wrong here?

答:
The error is pretty clear. You tried to delete a value that was not returned by new.

What we don't know is if the value is the address of a non-allocated value, just uninitialized (garbage) or if you've corrupted the heap. You haven't provided information to determine that.

But you do know that the value you are trying to free is not correct, and you need to figure out where it came from.

Body:
I'm implementing an open HashTable. My trouble arises in the destructor, where I iterate through all the buckets in an array, for each array I would delete all the nodes in a linked list.

        // Deallocate all buckets
        for (int i=0; i<maxBuckets; i++) {
            Cell * p = m_data[i];
            while (p != nullptr) {

                Cell * temp = p;
                p = p->next;
                delete temp;
            }
        }
        delete [] m_data;

But it reports pointer being freed was not allocated on the delete operation. What is going wrong here?


问:
Call a function from a running process in C#

I have a program in C++ running on a computer and cannot change
the code (But I can see the source code).

Now, I want to call some methods from this running program/process using my C# project.

The C++ program changes its objects in runtime. So importing the dll is
not helpful in this case.

What is the best practice? Is it possible to get that process (by Process.GetProcessesByName) and somehow call a function of it in my c# project?

答:
If the function has 1 argument you can call the function by using CreateRemoteThread() and passing the single argument in the lpParameter parameter.  Pass the address of the function in lpStartAddress.

If the function takes multiple arguments you cannot call it externally using CreateRemoteThread().

To get the address of the function you can use GetProcAddress() which you will need to pinvoke, but this only works if the function is exported.

If it's not exported, you can hardcode the address which you find by reverse engineering.


问:
AWS EC2 instance not letting TCP connection
I have created an EC2 (Windows) instance on AWS. I want to run a TCP server on this EC2 on TCP port 7889
and want to connect to it from outside world.

I have edited the inbound traffic rule in security group and added TCP rule for 7889 from anywhere.

But unfortunately my TCP client socket can not reach the server through the public ip of the EC2 instance.

Please help.

Note: The same thing worked for me few years ago. My little search has shown me few things like , I need to create VPC, public and private subnets, internet gateway and route tables.Is it true? All these were not required earlier.Is it a new addition?

答:
Thank you for the responses. It was windows internal firewall as @Marcin  suggested.
Everything works now.</p>


问:
Use of undeclared identifier 'cardNum'
I'm using a function of the library CS50 on cs50's environment, and this is how you store a value on a variable gathering it with an input:

```<code>long i = get_long("Enter a long: ");
</code>```

Here comes my code:

```<code>#include <stdio.h>
#include <cs50.h>
#include <math.h>

int main(void)
{

do
{
    long cardNum = get_long("Card number:\n");
}
while (0 <= cardNum <= 9999999999999999);

if (340000000000000 <= cardNum <= 379999999999999)
{
</code>```

...and so on.

The issue WAS

use of undeclared identifier 'cardNum'

I've added:

```<code>long cardNum;
</code>```

BEFORE the do-while loop; PROBLEM SOLVED.

答:
You are using cardNum in the do block. Declare it outside the block of do and your error will be gone.

Correct way -

```<code>long cardNum = 0;
do
{
    cardNum = get_long("Card number:\n");
}
while (0 <= cardNum && cardNum <= 9999999999999999);
</code>```

In your case, you were getting error because cardNum is only scoped for do block and isn't visible inside the while because its scope ends as soon as it leaves the do block. This is why you are getting  use of undeclared identifier 'cardNum' as error. The compiler sees it as an undeclared variable inside the while() function.

NOTE : you are better off using long long int because maximum range of long is implementation based and might sometimes just be limited to 2,147,483,647 (most probably on 32 bit systems). You can also use int cardNum[20] or whatever your maximum limit is instead of 20.

Title: Use of undeclared identifier 'cardNum'

Body:
I'm using a function of the library CS50 on cs50's environment, and this is how you store a value on a variable gathering it with an input:

long i = get_long("Enter a long: ");

Here comes my code:

#include <stdio.h>
#include <cs50.h>
#include <math.h>

int main(void)
{

do
{
    long cardNum = get_long("Card number:\n");
}
while (0 <= cardNum <= 9999999999999999);

if (340000000000000 <= cardNum <= 379999999999999)
{

...and so on.

The issue WAS

use of undeclared identifier 'cardNum'

I've added:

long cardNum;

BEFORE the do-while loop; PROBLEM SOLVED.

Body:
You are using cardNum in the do block. Declare it outside the block of do and your error will be gone.

Correct way -

long cardNum = 0;
do
{
    cardNum = get_long("Card number:\n");
}
while (0 <= cardNum && cardNum <= 9999999999999999);

In your case, you were getting error because cardNum is only scoped for do block and isn't visible inside the while because its scope ends as soon as it leaves the do block. This is why you are getting  use of undeclared identifier 'cardNum' as error. The compiler sees it as an undeclared variable inside the while() function.

NOTE : you are better off using long long int because maximum range of long is implementation based and might sometimes just be limited to 2,147,483,647 (most probably on 32 bit systems). You can also use int cardNum[20] or whatever your maximum limit is instead of 20.


问:
Is it possible to check dimensions of image before uploading?
I have an upload control for uploading the images to the server, but before uploading I just want to make sure if the images are of correct dimensions.
Is there anything on client side that can be done with JavaScript?</p>

答:
An extension of @Klemen Tusar's anser for multiple files:

```<code>const loadImage = file => new Promise((resolve, reject) => {
    try {
        const image = new Image();

        image.onload = function () {
            resolve(this)
        };

        image.onerror = function () {
            reject("Invalid image. Please select an image file.");
        }

        image.src = window.URL.createObjectURL(file);
    } catch (e) {
        reject(e)
    }
})

const loadImagesArray = async files => {
    let images = Array(files.length)
    await Promise.all(files.map((file, i) => (async () => {
        const loadedImage = await loadImage(file)
        images[i] = loadedImage
    })()))
    return images
}
</code>```

Then you can check stuff on loaded images simply as follows:

```<code>const loadedImages = await loadImagesArray(e.currentTarget.files)
for(const loadedImage of loadedImages) {
    console.log(loadedImage.width, loadedImage.height)
}
</code>```

Body:
An extension of @Klemen Tusar's anser for multiple files:

const loadImage = file => new Promise((resolve, reject) => {
    try {
        const image = new Image();

        image.onload = function () {
            resolve(this)
        };

        image.onerror = function () {
            reject("Invalid image. Please select an image file.");
        }

        image.src = window.URL.createObjectURL(file);
    } catch (e) {
        reject(e)
    }
})

const loadImagesArray = async files => {
    let images = Array(files.length)
    await Promise.all(files.map((file, i) => (async () => {
        const loadedImage = await loadImage(file)
        images[i] = loadedImage
    })()))
    return images
}

Then you can check stuff on loaded images simply as follows:

const loadedImages = await loadImagesArray(e.currentTarget.files)
for(const loadedImage of loadedImages) {
    console.log(loadedImage.width, loadedImage.height)
}


问:
java reflection issue
I have this code:

```<code>public static final <TypeVO extends BaseVo> List<SelectItem> populateSelectBoxForType(
            final Class<TypeVO> voClass, final String fieldName) {
        List<SelectItem> listSelectBox = null;
        final List<TypeVO> vosList = GenericEjbProxyFactory
                .getGenericTopValueObjectProxy(voClass)
                .getAllValueObjects(null);
        System.out.println("loaded vosList!!!!");
        if (vosList != null) {
            listSelectBox = new ArrayList<SelectItem>();
            for (final TypeVO currVo : vosList) {
                listSelectBox.add(new SelectItem(currVo.getInternalId(), currVo.getName()));
            }
        }
        return listSelectBox;
    }
</code>```

As you see here, I'm using currVo.getName because always, currVo has a name property.

I want to be able to use also other fields from this currVo which has type as voClass, but not all currVo classes will contain this field so I have to use reflection to identify these getField method, something like:

```<code>for (final TypeVO currVo : vosList) {
                for (final Method m : voClass.getMethods()) {
                    if (m.getName().contains(fieldName)) {
                        listSelectBox.add(new SelectItem(
                                currVo.getInternalId(), currVo.m));
                    }
                }
            }
</code>```

What I do not know is HOW I can use that specific method's value when I find it, exactly like currVo.getName (because, of course, currVo.m is wrong)?

Eg: If fieldName is "Age" I want to put in the list: currVo.getAge()... I am simply blocked here...

答:
```<code>m.invoke(currVo);
</code>```

See also:

Method javadoc

Also note the correct way to look for a method as suggested by Nik and Bohemian.

Title: java reflection issue

Body:
I have this code:

public static final <TypeVO extends BaseVo> List<SelectItem> populateSelectBoxForType(
            final Class<TypeVO> voClass, final String fieldName) {
        List<SelectItem> listSelectBox = null;
        final List<TypeVO> vosList = GenericEjbProxyFactory
                .getGenericTopValueObjectProxy(voClass)
                .getAllValueObjects(null);
        System.out.println("loaded vosList!!!!");
        if (vosList != null) {
            listSelectBox = new ArrayList<SelectItem>();
            for (final TypeVO currVo : vosList) {
                listSelectBox.add(new SelectItem(currVo.getInternalId(), currVo.getName()));
            }
        }
        return listSelectBox;
    }

As you see here, I'm using currVo.getName because always, currVo has a name property.

I want to be able to use also other fields from this currVo which has type as voClass, but not all currVo classes will contain this field so I have to use reflection to identify these getField method, something like:

for (final TypeVO currVo : vosList) {
                for (final Method m : voClass.getMethods()) {
                    if (m.getName().contains(fieldName)) {
                        listSelectBox.add(new SelectItem(
                                currVo.getInternalId(), currVo.m));
                    }
                }
            }

What I do not know is HOW I can use that specific method's value when I find it, exactly like currVo.getName (because, of course, currVo.m is wrong)?

Eg: If fieldName is "Age" I want to put in the list: currVo.getAge()... I am simply blocked here...

Body:
m.invoke(currVo);

See also:

Method javadoc

Also note the correct way to look for a method as suggested by Nik and Bohemian.


问:
Replace column with another column in CSV on Python
I have this code that replaces a string for another string and I'm wondering if there's an easier way to do this. Instead of doing the .replace for each one, I want to just read a column and replace it with the column next to it instead of writing out .replace.

text = open('thecode.csv','r')
text = ''.join([i for i in text]) \
       .replace('Salam', 'Hello') \
       .replace('somebody', 'anybody') \

How can I go about this quicker if I have two columns that look like this:

```<code>Column1         Column2
Salam            Hello
somebody         anybody
</code>```

答:
This would be easier in Pandas.  </p>

```<code>import pandas as pd
df = pd.read_csv('thecode.csv')
df['Column1'] = df['Column2']
df.to_csv('fixed_output.csv', index=False)
</code>```

Body:
I have this code that replaces a string for another string and I'm wondering if there's an easier way to do this. Instead of doing the .replace for each one, I want to just read a column and replace it with the column next to it instead of writing out .replace.

text = open('thecode.csv','r')
text = ''.join([i for i in text]) \
       .replace('Salam', 'Hello') \
       .replace('somebody', 'anybody') \

How can I go about this quicker if I have two columns that look like this:

Column1         Column2
Salam            Hello
somebody         anybody

Body:
This would be easier in Pandas.

import pandas as pd
df = pd.read_csv('thecode.csv')
df['Column1'] = df['Column2']
df.to_csv('fixed_output.csv', index=False)


问:
Javascript fetch doesn't return despite correct URL
I've used JQuery in the past to do AJAX requests. I am trying to now use fetch and I am struggling.

My code is very simple, and it calls a C# backend. The back end break point is hit, so I don't believe there is any issue with the URL

```<code>this.get = function (url) {
    return getData(url);
};

async function getData(url = '') {
    const response = await fetch(url, {
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        mode: 'same-origin', // no-cors, *cors, same-origin
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        redirect: 'follow',
        referrerPolicy: 'no-referrer'
    });

    return await response.json(); // BREAK POINT NEVER HIT
}
</code>```

In the browsers dev tools, I put a break point at the line const response = await fetch(url, { and another on the return await response.json;

The first break is hit. The second never hits. I don't see any error message or exception.

How do I find out what is going on?

Looking at the response, it shows it's pending a promise

EDIT

It seems as if my program is not waiting with await... My understanding is the code should not progress until it has received (waited) for a response. What is happening is, as soon as it hits the await, it seems to exit the function. The breakpoint on return await response.json() does eventually get hit, but await is acting like a new thread.

答:
The issue was, I returning a promise, so everything was not synchronous...

As soon as I changed it to

```<code>async function getData (url = '', successCallback){
    ….
    success(await response.json());
}
</code>```

it worked fine

Body:
I've used JQuery in the past to do AJAX requests. I am trying to now use fetch and I am struggling.

My code is very simple, and it calls a C# backend. The back end break point is hit, so I don't believe there is any issue with the URL

this.get = function (url) {
    return getData(url);
};

async function getData(url = '') {
    const response = await fetch(url, {
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        mode: 'same-origin', // no-cors, *cors, same-origin
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        redirect: 'follow',
        referrerPolicy: 'no-referrer'
    });

    return await response.json(); // BREAK POINT NEVER HIT
}

In the browsers dev tools, I put a break point at the line const response = await fetch(url, { and another on the return await response.json;

The first break is hit. The second never hits. I don't see any error message or exception.

How do I find out what is going on?

Looking at the response, it shows it's pending a promise

EDIT

It seems as if my program is not waiting with await... My understanding is the code should not progress until it has received (waited) for a response. What is happening is, as soon as it hits the await, it seems to exit the function. The breakpoint on return await response.json() does eventually get hit, but await is acting like a new thread.

Body:
The issue was, I returning a promise, so everything was not synchronous...

As soon as I changed it to

async function getData (url = '', successCallback){
    ….
    success(await response.json());
}

it worked fine


答:
Try this:

```<code>list1 = ["This is the first sentence", "This is the second", "This is the third"]
l1 = []
for i in list1:
    l2 = i.split()
    for j in range(len(l2)):
        l1.append(l2[j])
print(l1)
</code>```

output:

```<code>['This', 'is', 'the', 'first', 'sentence', 'This', 'is', 'the', 'second', 'This', 'is', 'the', 'third']
</code>```

Title: How to split a list which contains sentences into a list with words using Python?

Body:
Try this:

list1 = ["This is the first sentence", "This is the second", "This is the third"]
l1 = []
for i in list1:
    l2 = i.split()
    for j in range(len(l2)):
        l1.append(l2[j])
print(l1)

output:

['This', 'is', 'the', 'first', 'sentence', 'This', 'is', 'the', 'second', 'This', 'is', 'the', 'third']


问:
Emacs stop working in Mac OSX Catalina. How to fix?
I keep getting this error:

emacs dyld: Library not loaded:
/usr/local/opt/libffi/lib/libffi.6.dylib   Referenced from:
/usr/local/opt/p11-kit/lib/libp11-kit.0.dylib   Reason: image not
found Abort trap: 6

I tried to reinstall with brew reinstall emacs, brew install libffi, brew link libffi. Nothing helps.

答:
I had a similar problem installing from source,

```<code>brew reinstall p11-kit
</code>```

was the fix for me

Body:
I had a similar problem installing from source,

brew reinstall p11-kit

was the fix for me


问:
How to set the active profile when creating Spring context programmatically?
tl;dr: how to create a Spring context based on an annotation-based configuration class, while supplying active profiles?

I am trying to create a Spring context using a class with the configuration specified using annotations.

```<code>org.springframework.context.ApplicationContext context =
    new org.springframework.context.annotation.AnnotationConfigApplicationContext( com.initech.ReleaserConfig.class );
</code>```

However when it starts up it crashes because it cannot find a required bean, but that bean does exist : albeit only under a certain profile "myProfile".

How do I specify the active profile? I have a feeling I need to use one the org.springframework.context.annotation.AnnotationConfigApplicationContext(org.springframework.beans.factory.support.DefaultListableBeanFactory) constructor but I'm not sure which ones is appropriate.

PS- I am not using Spring Boot, but am on Spring 4.2.4.RELEASE.

答:
If you want classpath:resources/application-${spring.profiles.active}.yml to be working, setting system properties before refreshing is the way to go.

```<code>AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.getEnvironment().getSystemProperties().put(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
applicationContext.scan("com.sample");
applicationContext.refresh();
</code>```

Body:
tl;dr: how to create a Spring context based on an annotation-based configuration class, while supplying active profiles?

I am trying to create a Spring context using a class with the configuration specified using annotations.

org.springframework.context.ApplicationContext context =
    new org.springframework.context.annotation.AnnotationConfigApplicationContext( com.initech.ReleaserConfig.class );

However when it starts up it crashes because it cannot find a required bean, but that bean does exist : albeit only under a certain profile "myProfile".

How do I specify the active profile? I have a feeling I need to use one the org.springframework.context.annotation.AnnotationConfigApplicationContext(org.springframework.beans.factory.support.DefaultListableBeanFactory) constructor but I'm not sure which ones is appropriate.

PS- I am not using Spring Boot, but am on Spring 4.2.4.RELEASE.

Body:
If you want classpath:resources/application-${spring.profiles.active}.yml to be working, setting system properties before refreshing is the way to go.

AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.getEnvironment().getSystemProperties().put(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
applicationContext.scan("com.sample");
applicationContext.refresh();


答: may I suggest using Pandas? read your file using pd.read_csv simply create a Series from your new column and replace it with the column in the correction position where you want. don't foreget to use to_csv at the end to write the result.

Title: Replace column with another column in CSV on Python


问:
React "can't perform state update on unmounted component" with timeout
Questions about this warning have been asked and answered countless times on the Internet, yet - maybe actually because of that - I'm having difficulty finding a comment which touches on my own situation.

I'm working on an autosave feature, whereby when you start typing into the component's form it starts a timer. On completion, a) it dispatches an action (which is working fine) and b) it clears the timer state so that next time the user types it knows it can start a new one.

The issue comes when I unmount the component before the timer is complete: when it does expire I get the Can't perform a React state update on an unmounted component warning as I try to clear the timer state.

Now, just about all the solutions I've found online for this suggest I should create an isMounted state variable and check it before running the relevant setAutosave(null) state call. Except that - as far as I'm aware - the nature of Javascript timers means that the values available to the setTimeout callback (or Promise callback, for that matter) are those when the timer was started - when of course, the component was mounted.

Effectively, I'm stuck between a) the autosave feature requiring a state reset if the component is mounted, b) React demanding that the state reset cannot occur if the component isn't mounted, and c) the timer preventing any checking (that I can think of) of whether the component is or isn't mounted. Any ideas?

```<code>const { dispatch } = useContext(MyContext)
const [autosave, setAutosave] = useState(null)

const save = () => {
  clearTimeout(autosave) // in case you manually submit the form
  setAutosave(null)
  dispatch({ type: "SAVE" }) // this line works fine
}

const onChange = () => {
  if (!autosave) {
    const timeoutId = setTimeout(save, 30000)
    setAutosave(timeoutId)
  }
}

<form onChange={onChange} onSubmit={save}>
...
</code>```

答: I am not sure though, Try change your state using componentWillUnmount if your component is class-based component and useEffect functional components

Body:
Questions about this warning have been asked and answered countless times on the Internet, yet - maybe actually because of that - I'm having difficulty finding a comment which touches on my own situation.

I'm working on an autosave feature, whereby when you start typing into the component's form it starts a timer. On completion, a) it dispatches an action (which is working fine) and b) it clears the timer state so that next time the user types it knows it can start a new one.

The issue comes when I unmount the component before the timer is complete: when it does expire I get the Can't perform a React state update on an unmounted component warning as I try to clear the timer state.

Now, just about all the solutions I've found online for this suggest I should create an isMounted state variable and check it before running the relevant setAutosave(null) state call. Except that - as far as I'm aware - the nature of Javascript timers means that the values available to the setTimeout callback (or Promise callback, for that matter) are those when the timer was started - when of course, the component was mounted.

Effectively, I'm stuck between a) the autosave feature requiring a state reset if the component is mounted, b) React demanding that the state reset cannot occur if the component isn't mounted, and c) the timer preventing any checking (that I can think of) of whether the component is or isn't mounted. Any ideas?

const { dispatch } = useContext(MyContext)
const [autosave, setAutosave] = useState(null)

const save = () => {
  clearTimeout(autosave) // in case you manually submit the form
  setAutosave(null)
  dispatch({ type: "SAVE" }) // this line works fine
}

const onChange = () => {
  if (!autosave) {
    const timeoutId = setTimeout(save, 30000)
    setAutosave(timeoutId)
  }
}

<form onChange={onChange} onSubmit={save}>
...


问:
Problem with saving values from function in C++
Im bad with pointers and references so i have a question why in function hoffman the values are good and fine but when im trying see them out of function hoffman in main() i cant see almost none of this values.
This is my code:

```<code>#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

struct element {
char letter;
int number;
string code;
element *left;
element *right;
};

bool my_cmp(const element& a, const element& b)
{
  return a.number<b.number;
}

void hoffman(element &tab)
{
   if(tab.left!=NULL)
   {
    tab.left->code=tab.code;
    tab.left->code.push_back('0');
    if(tab.left->letter!=' ')
    {
        cout<<tab.left->letter<<" "<<tab.left->code<<endl;
    }
    hoffman(*tab.left);
}
if(tab.right!=NULL)
{
    tab.right->code=tab.code;
    tab.right->code.push_back('1');
    if(tab.right->letter!=' ')
    {
        cout<<tab.right->letter<<" "<<tab.right->code<<endl;
    }
    hoffman(*tab.right);
     }
    }

 int main()
 {
string C="abcdefghijklmnopqestuvwxyz",text;
int T[26]={0};
vector<element> tab;
cin>>text;
int rozmiar=text.length();
int rozm=0;
for(int i=0;i<rozmiar;i++)
{
    for(int j=0;j<26;j++)
    {
        if(text[i]==C[j])
        {
            T[j]++;
            break;
        }
    }
}
for(int j=0;j<26;j++)
{
    if(T[j]!=0)
    {
        tab.push_back({C[j],T[j],"",NULL,NULL});
    }
}

sort(tab.begin(),tab.end(),my_cmp);

while((rozm+1)!=tab.size())
{
    tab.push_back({' ',tab[rozm].number+tab[rozm+1].number,"",&tab[rozm],&tab[rozm+1]});
    rozm+=2;
    sort(tab.begin()+rozm,tab.end(),my_cmp);
}

hoffman(tab[tab.size()-1]);
cout<<endl;

for(int i=0;i<tab.size();i++)
{
    if(tab[i].letter!=' ') cout<<tab[i].letter<<" = "<<tab[i].code<<endl;
}

return 0;
</code>```

}

In function hoffman im assigning string code to every element of struct but i cant see it out of function using the last loop, any ideas?

答:
This code is wrong

```<code>tab.push_back({' ',tab[rozm].number+tab[rozm+1].number,"",&tab[rozm],&tab[rozm+1]});
</code>```

You are taking pointers to elements in your vector and pushing back items onto the vector. The problem with this is that if the vector reallocates all your pointers become invalid.

Simplest fix would be to use indexes instead of pointers and pass your vector to the hoffman routine.

Body:
Im bad with pointers and references so i have a question why in function hoffman the values are good and fine but when im trying see them out of function hoffman in main() i cant see almost none of this values.
This is my code:

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

struct element {
char letter;
int number;
string code;
element *left;
element *right;
};

bool my_cmp(const element& a, const element& b)
{
  return a.numbercode=tab.code;
    tab.left->code.push_back('0');
    if(tab.left->letter!=' ')
    {
        cout<<tab.left->letter<<" "<<tab.left->code<<endl;
    }
    hoffman(*tab.left);
}
if(tab.right!=NULL)
{
    tab.right->code=tab.code;
    tab.right->code.push_back('1');
    if(tab.right->letter!=' ')
    {
        cout<<tab.right->letter<<" "<<tab.right->code<<endl;
    }
    hoffman(*tab.right);
     }
    }

 int main()
 {
string C="abcdefghijklmnopqestuvwxyz",text;
int T[26]={0};
vector<element> tab;
cin>>text;
int rozmiar=text.length();
int rozm=0;
for(int i=0;i<rozmiar;i++)
{
    for(int j=0;j<26;j++)
    {
        if(text[i]==C[j])
        {
            T[j]++;
            break;
        }
    }
}
for(int j=0;j<26;j++)
{
    if(T[j]!=0)
    {
        tab.push_back({C[j],T[j],"",NULL,NULL});
    }
}

sort(tab.begin(),tab.end(),my_cmp);

while((rozm+1)!=tab.size())
{
    tab.push_back({' ',tab[rozm].number+tab[rozm+1].number,"",&tab[rozm],&tab[rozm+1]});
    rozm+=2;
    sort(tab.begin()+rozm,tab.end(),my_cmp);
}

hoffman(tab[tab.size()-1]);
cout<<endl;

for(int i=0;i<tab.size();i++)
{
    if(tab[i].letter!=' ') cout<<tab[i].letter<<" = "<<tab[i].code<<endl;
}

return 0;

}

In function hoffman im assigning string code to every element of struct but i cant see it out of function using the last loop, any ideas?

Body:
This code is wrong

tab.push_back({' ',tab[rozm].number+tab[rozm+1].number,"",&tab[rozm],&tab[rozm+1]});

You are taking pointers to elements in your vector and pushing back items onto the vector. The problem with this is that if the vector reallocates all your pointers become invalid.

Simplest fix would be to use indexes instead of pointers and pass your vector to the hoffman routine.


问:
Python model for correcting the input data
I need to build a model by taking historic data of a list of fixed length having text of fixed values for each index.

Example: [ABC,BCD,CDE,DEF,EFG]

The model should correct the input new list if there is some invalid value and return the most appropriate value for that column.

Example: if the input is:

[ABC,BCD,CDZ,DEF,EFG]

it should return

[ABC,BCD,CDE,DEF,EFG].

I am struck with this.Can anyone please help me? Thanks in advance.

答:
Is this what you are looking for / ?</p>

```<code>a = ['ABC','BCD','CDE','DEF','EFG']
b = ['ABC','BCD','CDZ','DEF','EFG']
c = []
for idx, b_ in enumerate(b):
    if b_ not in a :
            c.append(a[idx])
    else:
            c.append(b_)

print(c)

>>> ['ABC', 'BCD', 'CDE', 'DEF', 'EFG']
</code>```

Body:
Is this what you are looking for / ?

a = ['ABC','BCD','CDE','DEF','EFG']
b = ['ABC','BCD','CDZ','DEF','EFG']
c = []
for idx, b_ in enumerate(b):
    if b_ not in a :
            c.append(a[idx])
    else:
            c.append(b_)

print(c)

>>> ['ABC', 'BCD', 'CDE', 'DEF', 'EFG']