问:
Reset stepper in UITableViewCell (Swift)
I have problem with my UIStepper. I do a counting game and for each time I press "new Competition" I want the stepper to reset the value. I have tried a lot of different way without no result.

What should I do?

```<code>class GameRoundTableViewCell: UITableViewCell {

    @IBOutlet weak var scoreLabel: UILabel!
    @IBOutlet weak var stepper: UIStepper!

    var index: IndexPath?

    var player : Player?

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    @IBAction func StepperCounter(_ sender: UIStepper) {
        player?.score = Int(sender.value)
        scoreLabel.text = String(Int(sender.value))

    }

}
</code>```

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

    @IBOutlet weak var previewButton: UIButton!
    var currentCompetitionsIndex = 0
    @IBOutlet weak var nextCompetition: UIButton!
    var gameRoundTableViewcell = "GameRoundTableViewcell"
    @IBOutlet weak var tabelViewGameRound: UITableView!
    let gameCellId = "GameCellId"
    var players : [Player]? = []
    var scoreLabel2 = GameRoundTableViewCell()
    var stepper2 = GameRoundTableViewCell()

    var questions : [Comepetitions]?
    @IBOutlet weak var textFieldCompInfo: UITextView!
    @IBOutlet weak var headingLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        nextCompetition.layer.cornerRadius = 26
        nextCompetition.clipsToBounds = true

        if let competition = questions?[currentCompetitionsIndex] {
            textFieldCompInfo?.text = competition.comepetitionsInfo
            headingLabel.text = competition.comepetitionsOption
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return players!.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell  {
        let cell = tableView.dequeueReusableCell(withIdentifier: gameCellId, for: indexPath as IndexPath) as! GameRoundTableViewCell

        cell.textLabel?.text = players?[indexPath.row].name
        if let score = players?[indexPath.row].score {
            cell.scoreLabel?.text = String(score)
            // cell.scoreLabel?.text =  "\(String(describing: person.score))"
        }
        cell.player = players?[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    func refresh(){
        tabelViewGameRound.reloadData()
    }

    @IBAction func previewCompeition(_ sender: UIButton)  {

        guard let quest = questions else {return}

        if currentCompetitionsIndex - 1 < quest.count  {
            currentCompetitionsIndex -= 1
            textFieldCompInfo.text = quest[currentCompetitionsIndex].comepetitionsInfo
            headingLabel.text = quest[currentCompetitionsIndex].comepetitionsOption

        } else {
            currentCompetitionsIndex = 0
            performSegue(withIdentifier: "resultSegue", sender: nil)
        }
        if currentCompetitionsIndex == 0{
            previewButton.isHidden = true
        }
    }

**//When I Press this button I want to reset the stepper.**

    @IBAction func newCompetition(_ sender: UIButton)  {

        guard let players = players else {return}

        for player in players {
            player.scoreForEachRound.append(player.score)
            player.score = 0
        }
        tabelViewGameRound.reloadData()
        guard let quest = questions else {return}

        if currentCompetitionsIndex + 1 < quest.count  {
            currentCompetitionsIndex += 1
            textFieldCompInfo.text = quest[currentCompetitionsIndex].comepetitionsInfo
            headingLabel.text = quest[currentCompetitionsIndex].comepetitionsOption
        } else {
            currentCompetitionsIndex = 0
            performSegue(withIdentifier: "resultSegue", sender: nil)
        }
        if currentCompetitionsIndex > 0{
            previewButton.isHidden = false
        }

    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        let vc = segue.destination as! FinalResultViewController
        vc.finalResualt = self.players
    }
}
</code>```

答:
I assume you observe the following behavior that the display in the scoreLabel gets out of sync with the stepper control. This missing sync occurs in two situations:

When you scroll in the table view (reuse of dequeued cells)

When you reset all the player's scores

The reason for this is that you only update the scoreLabel, but do not reset the stepper. Both controls are independend from each other, e.g. resetting the one will not influence the other. Therefore the stepper keeps the old (invalid) value, and when it's pressed, it will continue updating the label with that value.

You need to do the following: in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath), also set the stepper to the current count:

```<code>if let score = players?[indexPath.row].score {
    cell.scoreLabel.text = String(score)
    cell.stepper.value = score
}
</code>```

Body:
I have problem with my UIStepper. I do a counting game and for each time I press "new Competition" I want the stepper to reset the value. I have tried a lot of different way without no result.

What should I do?

class GameRoundTableViewCell: UITableViewCell {

    @IBOutlet weak var scoreLabel: UILabel!
    @IBOutlet weak var stepper: UIStepper!

    var index: IndexPath?

    var player : Player?

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    @IBAction func StepperCounter(_ sender: UIStepper) {
        player?.score = Int(sender.value)
        scoreLabel.text = String(Int(sender.value))

    }

}

class GameViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var previewButton: UIButton!
    var currentCompetitionsIndex = 0
    @IBOutlet weak var nextCompetition: UIButton!
    var gameRoundTableViewcell = "GameRoundTableViewcell"
    @IBOutlet weak var tabelViewGameRound: UITableView!
    let gameCellId = "GameCellId"
    var players : [Player]? = []
    var scoreLabel2 = GameRoundTableViewCell()
    var stepper2 = GameRoundTableViewCell()

    var questions : [Comepetitions]?
    @IBOutlet weak var textFieldCompInfo: UITextView!
    @IBOutlet weak var headingLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        nextCompetition.layer.cornerRadius = 26
        nextCompetition.clipsToBounds = true

        if let competition = questions?[currentCompetitionsIndex] {
            textFieldCompInfo?.text = competition.comepetitionsInfo
            headingLabel.text = competition.comepetitionsOption
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return players!.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell  {
        let cell = tableView.dequeueReusableCell(withIdentifier: gameCellId, for: indexPath as IndexPath) as! GameRoundTableViewCell

        cell.textLabel?.text = players?[indexPath.row].name
        if let score = players?[indexPath.row].score {
            cell.scoreLabel?.text = String(score)
            // cell.scoreLabel?.text =  "\(String(describing: person.score))"
        }
        cell.player = players?[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    func refresh(){
        tabelViewGameRound.reloadData()
    }

    @IBAction func previewCompeition(_ sender: UIButton)  {

        guard let quest = questions else {return}

        if currentCompetitionsIndex - 1 < quest.count  {
            currentCompetitionsIndex -= 1
            textFieldCompInfo.text = quest[currentCompetitionsIndex].comepetitionsInfo
            headingLabel.text = quest[currentCompetitionsIndex].comepetitionsOption

        } else {
            currentCompetitionsIndex = 0
            performSegue(withIdentifier: "resultSegue", sender: nil)
        }
        if currentCompetitionsIndex == 0{
            previewButton.isHidden = true
        }
    }

**//When I Press this button I want to reset the stepper.**

    @IBAction func newCompetition(_ sender: UIButton)  {

        guard let players = players else {return}

        for player in players {
            player.scoreForEachRound.append(player.score)
            player.score = 0
        }
        tabelViewGameRound.reloadData()
        guard let quest = questions else {return}

        if currentCompetitionsIndex + 1 < quest.count  {
            currentCompetitionsIndex += 1
            textFieldCompInfo.text = quest[currentCompetitionsIndex].comepetitionsInfo
            headingLabel.text = quest[currentCompetitionsIndex].comepetitionsOption
        } else {
            currentCompetitionsIndex = 0
            performSegue(withIdentifier: "resultSegue", sender: nil)
        }
        if currentCompetitionsIndex > 0{
            previewButton.isHidden = false
        }

    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        let vc = segue.destination as! FinalResultViewController
        vc.finalResualt = self.players
    }
}

Body:
I assume you observe the following behavior that the display in the scoreLabel gets out of sync with the stepper control. This missing sync occurs in two situations:

When you scroll in the table view (reuse of dequeued cells)

When you reset all the player's scores

The reason for this is that you only update the scoreLabel, but do not reset the stepper. Both controls are independend from each other, e.g. resetting the one will not influence the other. Therefore the stepper keeps the old (invalid) value, and when it's pressed, it will continue updating the label with that value.

You need to do the following: in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath), also set the stepper to the current count:

if let score = players?[indexPath.row].score {
    cell.scoreLabel.text = String(score)
    cell.stepper.value = score
}


来源: stackexchange

问:
How can I add exception for when user inputs a negative number
I'm trying to add an exception to recognise when someone inputs a negative number, and respond with something to say you can only input a positive number

```<code>print('How many cats do you have?')
numCats = input()
try:
    if int(numCats) >=4:
        print('Thats a lot of cats.')
    else:
        print('Thats not that many cats.')
except ValueError:
    print('You did not enter a number.')
</code>```

At the moment it will respond to the user inputting a string instead of an integer but I want it to be able to respond to the user inputting something like -4 by printing 'You cant use negative numbers'.

Totally new to Python, so any advice on how to add this in would be very much appreciated, thank you.

答:
Define your own exception class, which you can choose to catch or not:</p>

```<code>class NegativeNumberException(Exception):
    pass

print('How many cats do you have?')
try:
    numCats = int(input())
    if numCats >=4:
        print('Thats a lot of cats.')
    elif numCats < 0:
        raise NegativeNumberException()
    else:
        print('Thats not that many cats.')
except ValueError:
    print('You did not enter a number.')
except NegativeNumberException as e:
    print("You entered a negative number.")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to add an exception to recognise when someone inputs a negative number, and respond with something to say you can only input a positive number

print('How many cats do you have?')
numCats = input()
try:
    if int(numCats) >=4:
        print('Thats a lot of cats.')
    else:
        print('Thats not that many cats.')
except ValueError:
    print('You did not enter a number.')

At the moment it will respond to the user inputting a string instead of an integer but I want it to be able to respond to the user inputting something like -4 by printing 'You cant use negative numbers'.

Totally new to Python, so any advice on how to add this in would be very much appreciated, thank you.

Body:
Define your own exception class, which you can choose to catch or not:

class NegativeNumberException(Exception):
    pass

print('How many cats do you have?')
try:
    numCats = int(input())
    if numCats >=4:
        print('Thats a lot of cats.')
    elif numCats < 0:
        raise NegativeNumberException()
    else:
        print('Thats not that many cats.')
except ValueError:
    print('You did not enter a number.')
except NegativeNumberException as e:
    print("You entered a negative number.")


问:
How to use apply/custom function to two linked dataframes with conditions imposed on columns
I have two dataframes df1 and df2 which are as follows:

df1

    A   B   C
0   Y1  X1  1000
1   Y2  X2  3000
2   Y3  X1  2000
3   Y4  X1  5000
4   Y5  X3  7000
5   Y6  X4  1500
6   Y7  X2  1200
7   Y8  X4  1100
df2

      K    L   M   N
0   Y1  X1  40  2020-06
1   Y1  X1  30  2020-05
2   Y2  X2  50  2020-01
3   Y1  X1  90  2020-04
4   Y3  X1  10  2020-06
5   Y2  X2  40  2020-04
6   Y3  X1  55  2020-03
7   Y4  X1  12  2019
8   Y5  X3  80  2020-04
9   Y5  X3  60  2020-05
10  Y6  X4  90  2020-06
11  Y7  X2  30  2020-03
12  Y8  X4  50  2020-02
13  Y7  X2  60  2020-01
```

<p>What I want from two above data frame is that I want to add a new column to the df1 by imposing condition to the column <strong>N</strong> of second dataframe i.e add rows of same type of whose value is <= 2020-05(year-week string format). The desired output I want is :</p>

<pre class="lang-py prettyprint-override"><code>df3 = pd.DataFrame({"A":["Y1","Y2","Y3","Y4","Y5","Y7","Y8"],
                    "B":["X1","X2","X1","X1","X3","X2","X4"],
                    "C":[1000,3000,2000,5000,7000,1200,1100],
                    "P":[30+90,50+40,55,12,80+60,30+60,50]})

df3

     A  B     C     P
0   Y1  X1  1000    120
1   Y2  X2  3000    90
2   Y3  X1  2000    55
3   Y4  X1  5000    12
4   Y5  X3  7000    140
5   Y7  X2  1200    90
6   Y8  X4  1100    50
</code>```

That is by imposed condition,I add rows which satisfy the conditions of df2 (except column N) and then finally add a column P to the df1.

For simplicity I took an example, actual data set is big.
Can anyone help me to write a function to obtain my desired output, or how can I use an apply function or iterrows etc. I am new to programming and I got stuck.
Help appreciated.

答:
You could first filter out rows that do not follow your conditions on column N, and then groupby & sum on column M to obtain your values for column P:</p>

```<code>df_tmp = df2.query("N < 13").groupby([K, L])["M"].sum()
df3 = df1.join(df_tmp, how="left").fillna(0)
</code>```

Body:
I have two dataframes df1 and df2 which are as follows:

df1

    A   B   C
0   Y1  X1  1000
1   Y2  X2  3000
2   Y3  X1  2000
3   Y4  X1  5000
4   Y5  X3  7000
5   Y6  X4  1500
6   Y7  X2  1200
7   Y8  X4  1100
df2

      K    L   M   N
0   Y1  X1  40  2020-06
1   Y1  X1  30  2020-05
2   Y2  X2  50  2020-01
3   Y1  X1  90  2020-04
4   Y3  X1  10  2020-06
5   Y2  X2  40  2020-04
6   Y3  X1  55  2020-03
7   Y4  X1  12  2019
8   Y5  X3  80  2020-04
9   Y5  X3  60  2020-05
10  Y6  X4  90  2020-06
11  Y7  X2  30  2020-03
12  Y8  X4  50  2020-02
13  Y7  X2  60  2020-01

What I want from two above data frame is that I want to add a new column to the df1 by imposing condition to the column N of second dataframe i.e add rows of same type of whose value is <= 2020-05(year-week string format). The desired output I want is :

df3 = pd.DataFrame({"A":["Y1","Y2","Y3","Y4","Y5","Y7","Y8"],
                    "B":["X1","X2","X1","X1","X3","X2","X4"],
                    "C":[1000,3000,2000,5000,7000,1200,1100],
                    "P":[30+90,50+40,55,12,80+60,30+60,50]})

df3

     A  B     C     P
0   Y1  X1  1000    120
1   Y2  X2  3000    90
2   Y3  X1  2000    55
3   Y4  X1  5000    12
4   Y5  X3  7000    140
5   Y7  X2  1200    90
6   Y8  X4  1100    50

That is by imposed condition,I add rows which satisfy the conditions of df2 (except column N) and then finally add a column P to the df1.

For simplicity I took an example, actual data set is big.
Can anyone help me to write a function to obtain my desired output, or how can I use an apply function or iterrows etc. I am new to programming and I got stuck.
Help appreciated.

Body:
You could first filter out rows that do not follow your conditions on column N, and then groupby & sum on column M to obtain your values for column P:

df_tmp = df2.query("N < 13").groupby([K, L])["M"].sum()
df3 = df1.join(df_tmp, how="left").fillna(0)


问:
conversion of html to xml format
```<code>Converting html to xml. In our project html UI render automatically
and based on that ui we create xml it is possible to change xml in our
own style using (html which created dynamically)

note: 1.html not always well formed
      2.In dynamic html how traverse the entire html tree bcoz we didnt know exact structure
      3.using id i wont be traverse bcoz all are generated automatically.
</code>```

Anyone give simple example which is very useful for ours.

答:
Sounds like someone's doing homework...

I would traverse the dom. You can google that. It will make sure your result is valid HTML and makes it so you don't have to write any sort of parser.

Here's an old, albeit still useful example:
http://www.permadi.com/tutorial/domTree/index.html

ContentLicense: CC BY-SA 3.0

Title: conversion of html to xml format

Body:
Converting html to xml. In our project html UI render automatically
and based on that ui we create xml it is possible to change xml in our
own style using (html which created dynamically)

note: 1.html not always well formed
      2.In dynamic html how traverse the entire html tree bcoz we didnt know exact structure
      3.using id i wont be traverse bcoz all are generated automatically.

Anyone give simple example which is very useful for ours.


问:
What is the best way to send a GET request to the server in vanilla JavaScript?
What is the best way to send a GET request to the server in vanilla JavaScript?</p>

答:
You can try with Fetch

function request() {
            fetch('http://example.com/movies.json')
                .then(function(response) {
                    console.log(response.json())
                })
                .then(function(myJson) {
                    console.log(myJson);
                });
        }

        request()```


问:
Stop AVPlayer and restart MP3 file again
I want to start, pause and stop (same as restart) my mp3 File and I'm using AVPlayer. I get the files from a server.

To start the song I do:

```<code>[self.player start];
</code>```

To pause I do:

```<code>[self.player pause];
</code>```

but when I want to stop the song and reload it, so that the song starts from the beginning when the User clicks on the "start button" next time, I have no idea what to do.

I tried something like this:

```<code>[self.player pause];
self.player = nil;
</code>```

But then the player is nil of course and I can't restart the file again without a new initialization. Any ideas how to stop it?

答:
seek#to has a completion handler.

```<code>p?.seek(to: .zero)
p?.rate = 1
</code>```

is not really correct. You can get audio jitter.

```<code>p?.seek(to: .zero) { [weak self] _ in
    self?.p?.rate = 1
}
</code>```

is probably what you want.

If it is already playing, and you just do the seek and nothing else, again you could get the jitters.

You are probably best to

```<code>p?.rate = 0
p?.seek(to: .zero) { [weak self] _ in
    self?.p?.rate = 1
}
</code>```

If it's a really important app, you'll also have to consider the error condition in the seek completion.

Body:
I want to start, pause and stop (same as restart) my mp3 File and I'm using AVPlayer. I get the files from a server.

To start the song I do:

[self.player start];

To pause I do:

[self.player pause];

but when I want to stop the song and reload it, so that the song starts from the beginning when the User clicks on the "start button" next time, I have no idea what to do.

I tried something like this:

[self.player pause];
self.player = nil;

But then the player is nil of course and I can't restart the file again without a new initialization. Any ideas how to stop it?

Body:
seek#to has a completion handler.

p?.seek(to: .zero)
p?.rate = 1

is not really correct. You can get audio jitter.

p?.seek(to: .zero) { [weak self] _ in
    self?.p?.rate = 1
}

is probably what you want.

If it is already playing, and you just do the seek and nothing else, again you could get the jitters.

You are probably best to

p?.rate = 0
p?.seek(to: .zero) { [weak self] _ in
    self?.p?.rate = 1
}

If it's a really important app, you'll also have to consider the error condition in the seek completion.


问:
Docker in MacOs is very slow
I have this docker-compose.yml:

```<code>version: "3.1"
services:

    memcached:
      image: memcached:alpine
      container_name: universal-memcached2

    redis:
      image: redis:alpine
      container_name: universal-redis2

    mariadb:
      image: mariadb:10.4
      container_name: universal-mariadb2
      working_dir: /application
      volumes:
        - .:/application
        - "../data/db:/var/lib/mysql" # skasowac
      environment:
        - MYSQL_ROOT_PASSWORD=Haslo
        - MYSQL_DATABASE=sample
        - MYSQL_USER=user
        - MYSQL_PASSWORD=Haslo
      ports:
        - "8083:3306"

    webserver:
      image: nginx:alpine
      container_name: universal-webserver2
      working_dir: /application
      volumes:
          - .:/application
          - ./phpdocker/nginx/nginx.conf:/etc/nginx/conf.d/default.conf
      ports:
       - "8080:80"

    php-fpm:
      build: phpdocker/php-fpm
      container_name: universal-php-fpm2
      working_dir: /application
      volumes:
        - .:/application
        - ./phpdocker/php-fpm/php-ini-overrides.ini:/etc/php/7.3/fpm/conf.d/99-overrides.ini

    volumes:
        generated:
        var:
        static:

    phpmyadmin:
      image: phpmyadmin/phpmyadmin
      links:
        - mariadb
      environment:
        PMA_HOST: mariadb
        PMA_PORT: 3306
      ports:
        - '8081:80'
</code>```

When I run my newest project in symfony 4 on it, it works very slowly... :(

I have new MacOs and Docker Desktop.
I'm currently learning the Symfony and Laravel framework, but this is very slow for Docker. It is not even working on it.

How can I repair it?

答:
As mentioned in other answers, the issue comes down to the way Docker interacts with the file system on OSX.

I found a great article on how to make things a lot faster on OSX:

https://vivait.co.uk/labs/docker-for-mac-performance-using-nfs

From the article, the real solution is to change the file system to use NFS, but as I know nothing about Docker (it was set up for me at work), I opted to use an option available in newer versions of Docker

I added :delegated to all of the options under volumes in docker-compose.yml. After restarting my containers, every was nearly twice as fast as before. Not as fast as native, but fast enough.

Example from article:

```<code>app:
    build:
        context: .
        dockerfile: ./docker/app/Dockerfile
    working_dir: /app
    user: "www-data"
    volumes:
        - ./:/app:delegated
        - ./:/another_folder:delegated
</code>```

The NFS example is quite long and requires basically copying half of the article so I won't add it in, but this :delegated solution is good place to start.

Title: Docker in MacOs is very slow

Body:
I have this docker-compose.yml:

version: "3.1"
services:

    memcached:
      image: memcached:alpine
      container_name: universal-memcached2

    redis:
      image: redis:alpine
      container_name: universal-redis2

    mariadb:
      image: mariadb:10.4
      container_name: universal-mariadb2
      working_dir: /application
      volumes:
        - .:/application
        - "../data/db:/var/lib/mysql" # skasowac
      environment:
        - MYSQL_ROOT_PASSWORD=Haslo
        - MYSQL_DATABASE=sample
        - MYSQL_USER=user
        - MYSQL_PASSWORD=Haslo
      ports:
        - "8083:3306"

    webserver:
      image: nginx:alpine
      container_name: universal-webserver2
      working_dir: /application
      volumes:
          - .:/application
          - ./phpdocker/nginx/nginx.conf:/etc/nginx/conf.d/default.conf
      ports:
       - "8080:80"

    php-fpm:
      build: phpdocker/php-fpm
      container_name: universal-php-fpm2
      working_dir: /application
      volumes:
        - .:/application
        - ./phpdocker/php-fpm/php-ini-overrides.ini:/etc/php/7.3/fpm/conf.d/99-overrides.ini

    volumes:
        generated:
        var:
        static:

    phpmyadmin:
      image: phpmyadmin/phpmyadmin
      links:
        - mariadb
      environment:
        PMA_HOST: mariadb
        PMA_PORT: 3306
      ports:
        - '8081:80'

When I run my newest project in symfony 4 on it, it works very slowly... :(

I have new MacOs and Docker Desktop.
I'm currently learning the Symfony and Laravel framework, but this is very slow for Docker. It is not even working on it.

How can I repair it?

Body:
As mentioned in other answers, the issue comes down to the way Docker interacts with the file system on OSX.

I found a great article on how to make things a lot faster on OSX:

https://vivait.co.uk/labs/docker-for-mac-performance-using-nfs

From the article, the real solution is to change the file system to use NFS, but as I know nothing about Docker (it was set up for me at work), I opted to use an option available in newer versions of Docker

I added :delegated to all of the options under volumes in docker-compose.yml. After restarting my containers, every was nearly twice as fast as before. Not as fast as native, but fast enough.

Example from article:

app:
    build:
        context: .
        dockerfile: ./docker/app/Dockerfile
    working_dir: /app
    user: "www-data"
    volumes:
        - ./:/app:delegated
        - ./:/another_folder:delegated

The NFS example is quite long and requires basically copying half of the article so I won't add it in, but this :delegated solution is good place to start.


答:
Using the XMLHttpRequest (XHR) Object.

Code example:

```<code>const http = new XMLHttpRequest();
const url='/test';
http.open("GET", url);
http.send();

http.onreadystatechange = (e) => {
  console.log('done')
}
</code>```

Title: What is the best way to send a GET request to the server in vanilla JavaScript?

Body:
Using the XMLHttpRequest (XHR) Object.

Code example:

const http = new XMLHttpRequest();
const url='/test';
http.open("GET", url);
http.send();

http.onreadystatechange = (e) => {
  console.log('done')
}


答:
In vanilla javascript, you can use the fetch API.</p>

```<code>fetch('http://example.com/movies.json')
  .then((response) => {
    return response.json();
  })
  .then((myJson) => {
    console.log(myJson);
  });
</code>```

Body: What is the best way to send a GET request to the server in vanilla JavaScript?

Body:
In vanilla javascript, you can use the fetch API.

fetch('http://example.com/movies.json')
  .then((response) => {
    return response.json();
  })
  .then((myJson) => {
    console.log(myJson);
  });


答:
I'm not sure if we can claim here a "best way",
but you can use

XMLHttpRequest

or if you want to use a library

Axios


问:
T-Test in Python for multiple group comparisons
I would like to conduct a simple t-test in python, but I would like to compare all possible groups to each other. Let's say I have the following data:

```<code>import pandas as pd

data = {'Category': ['cat3','cat2','cat1','cat2','cat1','cat2','cat1','cat2','cat1','cat1','cat1','cat2','cat3','cat3'],
        'values': [4,1,2,3,1,2,3,1,2,3,5,1,6,3]}
my_data = pd.DataFrame(data)
</code>```

And I want to calculate the p-value based on a t-test for all possible category combinations, which are:

```<code>cat1 vs. cat2
cat2 vs. cat3
cat1 vs. cat3
</code>```

I can do this manually via:

```<code>from scipy import stats

cat1 = my_data.loc[my_data['Category'] == 'cat1', 'values']
cat2 = my_data.loc[my_data['Category'] == 'cat2', 'values']
cat3 = my_data.loc[my_data['Category'] == 'cat3', 'values']

print(stats.ttest_ind(cat1,cat2).pvalue)
print(stats.ttest_ind(cat2,cat3).pvalue)
print(stats.ttest_ind(cat1,cat3).pvalue)
</code>```

But is there a more simple and straightforward way to do this? The amount of categories might differ from case to case, so the number of t-tests that need to be calculated will also differ...

The final output should be a DataFrame with one row for each comparison and the values: category1 | category2 | p-value, in this case it should look like:

```<code>cat1 | cat2 | 0.16970867501294376
cat2 | cat3 | 0.0170622126550303
cat1 | cat3 | 0.13951958313684434
</code>```

答:
Consider iterating through itertools.combinations across categories:

```<code>from itertools import combinations
...

def ttest_run(c1, c2):
    results = stats.ttest_ind(cat1, cat2)
    df = pd.DataFrame({'categ1': c1,
                       'categ2': c2,
                       'tstat': results.statistic,
                       'pvalue': results.pvalue},
                       index = [0])
    return df

df_list = [ttest_run(i, j) for i, j in combinations(mydata['Category'].unique().tolist(), 2)]

final_df = pd.concat(df_list, ignore_index = True)
</code>```

Body:
I would like to conduct a simple t-test in python, but I would like to compare all possible groups to each other. Let's say I have the following data:

import pandas as pd

data = {'Category': ['cat3','cat2','cat1','cat2','cat1','cat2','cat1','cat2','cat1','cat1','cat1','cat2','cat3','cat3'],
        'values': [4,1,2,3,1,2,3,1,2,3,5,1,6,3]}
my_data = pd.DataFrame(data)

And I want to calculate the p-value based on a t-test for all possible category combinations, which are:

cat1 vs. cat2
cat2 vs. cat3
cat1 vs. cat3

I can do this manually via:

from scipy import stats

cat1 = my_data.loc[my_data['Category'] == 'cat1', 'values']
cat2 = my_data.loc[my_data['Category'] == 'cat2', 'values']
cat3 = my_data.loc[my_data['Category'] == 'cat3', 'values']

print(stats.ttest_ind(cat1,cat2).pvalue)
print(stats.ttest_ind(cat2,cat3).pvalue)
print(stats.ttest_ind(cat1,cat3).pvalue)

But is there a more simple and straightforward way to do this? The amount of categories might differ from case to case, so the number of t-tests that need to be calculated will also differ...

The final output should be a DataFrame with one row for each comparison and the values: category1 | category2 | p-value, in this case it should look like:

cat1 | cat2 | 0.16970867501294376
cat2 | cat3 | 0.0170622126550303
cat1 | cat3 | 0.13951958313684434

Body:
Consider iterating through itertools.combinations across categories:

from itertools import combinations
...

def ttest_run(c1, c2):
    results = stats.ttest_ind(cat1, cat2)
    df = pd.DataFrame({'categ1': c1,
                       'categ2': c2,
                       'tstat': results.statistic,
                       'pvalue': results.pvalue},
                       index = [0])
    return df

df_list = [ttest_run(i, j) for i, j in combinations(mydata['Category'].unique().tolist(), 2)]

final_df = pd.concat(df_list, ignore_index = True)


问:
OCaml Typechecking Problem When Using Two Parameterized Modules
I have two modules, Graph and Game, which are parametrized by other modules. They also contain functions f and g which cause typechecking problems when I use them in a testing module. I left out lots of the code that is not important for this problem.

Here is a Graph module that has some module AbstractUSet. AbstractUSet.t is used a lot in the original code. The function f shall later take another function and do some work. The problem is, that the other function comes from another module and has a different type.

```<code>module UTYPE = sig
  type t
  val compare : t -> t -> int
end

module type GRAPH = sig
  module U : UTYPE
  module AbstractUSet : Set.S
  val f : (AbstractUSet.t -> AbstractUSet.t) -> AbstractUSet.t -> AbstractUSet.t
end

module Graph (UA : UTYPE) : (GRAPH with module U=UA) = struct
  module U=UA
  module AbstractUSet = Set.Make(struct type t=U.t let compare=U.compare end)
  let f g uset = g uset
end

</code>```

The other module is the Game module. It does lots of things with AbstractVSet.t. It contains the function g that shall later be input for the function f from the Graph module.

```<code>module type GAME_PIECE = sig
  type t
  val compare : t -> t -> int
end

module type GAME = sig
  module P : GAME_PIECE
  module AbstractVSet : Set.S
  val g : AbstractVSet.t -> AbstractVSet.t
end

module GameInstance (NA : GAME_PIECE) : (GAME with module P=NA) = struct
  module P = NA
  module AbstractVSet = Set.Make(struct type t=P.t let compare=P.compare end)
  let g vset = vset
end
</code>```

And this is my module for testing. In the very end, both UTYPE and GAME_PIECE are the same, but I can't make that clear to OCaml. I've commented the lines that don't typecheck. The compiler says there are clashes between MyGame.AbstractVSet.t and MyGraph.AbstractUSet.t.

```<code>module TestGame = struct
  include(Game(struct type t=string let compare=compare end))
end

module TestGraph = struct
  include(Graph(struct type t=string let compare=compare end))
end

module Test = struct
  module MyGame = TestGame
  module MyGraph = TestGraph
  let stringlist = ["a";"b"]
  let uset = MyGraph.uset_from_ulist stringlist // works fine
  let vset = MyGame.vset_from_vlist stringlist // works fine
  let result = MyGraph.f (MyGame.g) vset // does not typecheck!
end
</code>```

If you ask, why I'm using so many modules: The project is a lot bigger than this code extract, and it is intended to be like this ;)
Can anyone help me how I can make it clear to the OCaml compiler that both UTYPE and GAME_PIECE are the same in the Test module??
Thanks a lot for your help!!!

答:
The first issue is that your abstract set modules are different: the result of two functor applications in OCaml are only equals if the functor applications are applied to exactly the same named modules. For instance, in

```<code>module A = struct type t = int end
module F(X:sig type t end) = struct type t end
module FA = F(A)
module B = A
module FA' = F(B)
module C = F(struct type t end)
</code>```

The types FA.t and Fa'.t are the same

```<code>let f (x:FA.t): FA'.t = x
</code>```

But the types C.t and FA.t are different:

```<code>let f (x:C.t): FA'.t = x
Error: This expression has type C.t but an expression was expected of type
         FA'.t
</code>```

But this part can be fixed by not using anonymous structure when they are unnecessary:

```<code>module Graph (UA : UTYPE) : (GRAPH with module U=UA) = struct
  module U=UA
  module AbstractUSet = Set.Make(U)
  let f g uset = g uset
end
</code>```

Then, you are left with the "problem" that Game(M).AbstractUSet and
Graph(M).AbstractUSet defines two distinct types. (Note that this probably the right behavior outside of tests). For the test, one option is to simply expose the information that those modules are the result of functor applications. For instance, one can redefine the GAME module type (and GameInstance functor) to:

```<code>
module type GAME = sig
  type set
  module P : GAME_PIECE
  module AbstractVSet: Set.S with type t = set
  val g : AbstractVSet.t -> AbstractVSet.t
end

module GameInstance (NA : GAME_PIECE) :
(GAME with type set:= Set.Make(NA).t and module P=NA) = struct
  module P = NA
  module AbstractVSet = Set.Make(NA)
  let g vset = vset
end
</code>```

Here, we have ketp the information that GameInstance(M).AbstractVSet.t is the
same type as Set.Make(M).t.

Combined wit the same operation on the graph part:

```<code>module type GRAPH = sig
  type set
  module U : UTYPE
  module AbstractUSet : Set.S with type t = set
  val f : (AbstractUSet.t -> AbstractUSet.t) -> AbstractUSet.t -> AbstractUSet.t
end

module Graph (UA : UTYPE) :
(GRAPH with type set := Set.Make(UA).t and module U=UA) = struct
  module U=UA
  module AbstractUSet = Set.Make(UA)
  let f g uset = g uset
end
</code>```

we are preserving enough type information to keep the equality for the test:

```<code>module TestGame = GameInstance(String)
module TestGraph = Graph(String)

module Test = struct
  module MyGame = TestGame
  module MyGraph = TestGraph
  let result vset = MyGraph.f (MyGame.g) vset (* does typecheck *)
end
</code>```

Body:
I have two modules, Graph and Game, which are parametrized by other modules. They also contain functions f and g which cause typechecking problems when I use them in a testing module. I left out lots of the code that is not important for this problem.

Here is a Graph module that has some module AbstractUSet. AbstractUSet.t is used a lot in the original code. The function f shall later take another function and do some work. The problem is, that the other function comes from another module and has a different type.

module UTYPE = sig
  type t
  val compare : t -> t -> int
end

module type GRAPH = sig
  module U : UTYPE
  module AbstractUSet : Set.S
  val f : (AbstractUSet.t -> AbstractUSet.t) -> AbstractUSet.t -> AbstractUSet.t
end

module Graph (UA : UTYPE) : (GRAPH with module U=UA) = struct
  module U=UA
  module AbstractUSet = Set.Make(struct type t=U.t let compare=U.compare end)
  let f g uset = g uset
end

The other module is the Game module. It does lots of things with AbstractVSet.t. It contains the function g that shall later be input for the function f from the Graph module.

module type GAME_PIECE = sig
  type t
  val compare : t -> t -> int
end

module type GAME = sig
  module P : GAME_PIECE
  module AbstractVSet : Set.S
  val g : AbstractVSet.t -> AbstractVSet.t
end

module GameInstance (NA : GAME_PIECE) : (GAME with module P=NA) = struct
  module P = NA
  module AbstractVSet = Set.Make(struct type t=P.t let compare=P.compare end)
  let g vset = vset
end

And this is my module for testing. In the very end, both UTYPE and GAME_PIECE are the same, but I can't make that clear to OCaml. I've commented the lines that don't typecheck. The compiler says there are clashes between MyGame.AbstractVSet.t and MyGraph.AbstractUSet.t.

module TestGame = struct
  include(Game(struct type t=string let compare=compare end))
end

module TestGraph = struct
  include(Graph(struct type t=string let compare=compare end))
end

module Test = struct
  module MyGame = TestGame
  module MyGraph = TestGraph
  let stringlist = ["a";"b"]
  let uset = MyGraph.uset_from_ulist stringlist // works fine
  let vset = MyGame.vset_from_vlist stringlist // works fine
  let result = MyGraph.f (MyGame.g) vset // does not typecheck!
end

If you ask, why I'm using so many modules: The project is a lot bigger than this code extract, and it is intended to be like this ;)
Can anyone help me how I can make it clear to the OCaml compiler that both UTYPE and GAME_PIECE are the same in the Test module??
Thanks a lot for your help!!!

Body:
The first issue is that your abstract set modules are different: the result of two functor applications in OCaml are only equals if the functor applications are applied to exactly the same named modules. For instance, in

module A = struct type t = int end
module F(X:sig type t end) = struct type t end
module FA = F(A)
module B = A
module FA' = F(B)
module C = F(struct type t end)

The types FA.t and Fa'.t are the same

let f (x:FA.t): FA'.t = x

But the types C.t and FA.t are different:

let f (x:C.t): FA'.t = x
Error: This expression has type C.t but an expression was expected of type
         FA'.t

But this part can be fixed by not using anonymous structure when they are unnecessary:

module Graph (UA : UTYPE) : (GRAPH with module U=UA) = struct
  module U=UA
  module AbstractUSet = Set.Make(U)
  let f g uset = g uset
end

Then, you are left with the "problem" that Game(M).AbstractUSet and
Graph(M).AbstractUSet defines two distinct types. (Note that this probably the right behavior outside of tests). For the test, one option is to simply expose the information that those modules are the result of functor applications. For instance, one can redefine the GAME module type (and GameInstance functor) to:

module type GAME = sig
  type set
  module P : GAME_PIECE
  module AbstractVSet: Set.S with type t = set
  val g : AbstractVSet.t -> AbstractVSet.t
end

module GameInstance (NA : GAME_PIECE) :
(GAME with type set:= Set.Make(NA).t and module P=NA) = struct
  module P = NA
  module AbstractVSet = Set.Make(NA)
  let g vset = vset
end

Here, we have ketp the information that GameInstance(M).AbstractVSet.t is the
same type as Set.Make(M).t.

Combined wit the same operation on the graph part:

module type GRAPH = sig
  type set
  module U : UTYPE
  module AbstractUSet : Set.S with type t = set
  val f : (AbstractUSet.t -> AbstractUSet.t) -> AbstractUSet.t -> AbstractUSet.t
end

module Graph (UA : UTYPE) :
(GRAPH with type set := Set.Make(UA).t and module U=UA) = struct
  module U=UA
  module AbstractUSet = Set.Make(UA)
  let f g uset = g uset
end

we are preserving enough type information to keep the equality for the test:

module TestGame = GameInstance(String)
module TestGraph = Graph(String)

module Test = struct
  module MyGame = TestGame
  module MyGraph = TestGraph
  let result vset = MyGraph.f (MyGame.g) vset (* does typecheck *)
end


问:
what is the difference between system and acceptance testing as a tester? what extra test cases will acceptance testing produce?
I read some of the previous answers of similar questions on here but i am not satisfied. So both System and acceptance testing evaluates the system against the requirements.

Acceptence testing is for the users/customers and they decide if they will accept the system. But acceptance testing is allso for us testers... here i am abit confused of what extra test cases i will produce in the acceptance-phase that i did not already produce in the system phase?

答:
It's important to know that all testing phases have overlap. This is done by design both to cover any gaps in the previous test phrase, but to also test the same thing from different points of view.

System testing checks the complete system against a list of requirements. Acceptance testing checks the complete system against what the user wants, possibly by actually using it. And as we all know, what the requirements say and what the user wants can be two different things. The important difference is who is driving the tests: the developers or the users.

Wikipedia has a good explanation about the difference between User Acceptance Testing and System Testing.

User acceptance testing (UAT) consists of a process of verifying that a solution works for the user. It is not system testing (ensuring software does not crash and meets documented requirements), but rather ensures that the solution will work for the user (i.e., tests that the user accepts the solution); software vendors often refer to this as "Beta testing".

This testing should be undertaken by a subject-matter expert (SME), preferably the owner or client of the solution under test, and provide a summary of the findings for confirmation to proceed after trial or review. In software development, UAT as one of the final stages of a project often occurs before a client or customer accepts the new system. Users of the system perform tests in line with what would occur in real-life scenarios.[9]

The analogy to beta testing is a good one: in the process of using the software beta testers will run all sorts of scenarios you didn't think of. Often these will not be in the requirements. They might have been forgotten, or assumed, or too detailed, or simply not conceived of, or bugs (especially concurrency bugs).

"The system crashed when we added the 257th user."

"I was editing a document while someone else deleted it, and the
document was resurrected. It should still be deleted."

"If I hit escape while saving the document I get two copies of the document."

"The text is hard to read in dark mode."

"Acceptance testing" is sometimes done by the development team on behalf of the users. The on-site customer will write up a set of acceptance tests from a black box perspective which the team will have to implement. These can become regression tests.

"Sort 10,000 documents by name in less than 1 second."

"All columns must be sortable both ascending and descending."

"The site must follow sections X, Y, and Z of WCAG 2.1"

This sort of acceptance testing by the development team is sometimes a surrogate for User Acceptance Testing, or it can be done prior to UAT to ensure the software is in as good a shape as possible before being presented to the customer for acceptance.


问:
Use of stroke-dashoffset
I have an arrow that I want to animate so I read about animations and I noticed I can achieve this with css keyframes and svg.

So basically I want to draw an arrow from 0 to 100%, so I have a path like:

```<code> <path class="showUp" fill="#4C9FDC" stroke="#000000" stroke-width= "0" d="M165.15 204.15l-4.49-4.49c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01c-2.13 2.13-2.14 5.59-.01 7.72l.01.01 9.09 9.09a4.418 4.418 0 0 0 6.24 0l50.28-50.28c2.12-2.1 2.13-5.53.03-7.65l-.03-.03c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01-45.66 45.63z"/>
</code>```

And I want to animate with stroke like:

```<code>@keyframes Arrow {
 from {
    stroke-dashoffset: 1000;
  }
  to {
    stroke-dashoffset: 0;
  }
}

.showUp {
  stroke-dasharray: 1000;
  stroke-dashoffset: 1000;
  animation: Arrow 5s linear forwards;
}
</code>```

CodePen

But it just doing nothing. What am I doing wrong there? Regards

答:
You probably have already figured it out how to achieve what you were looking for, but here's a working pen I created. As you can see, in order to see the stroke animation, I had to remove the fill of the arrow by setting it to "transparent".

For the stroke-dasharray and stroke-dashoffset values, I simply played around with the numbers until I was satisfiied with the behavior, but a more solid approach is using JavaScript as mentioned by @enxaneta.
For a more detailed explanation on how SVG line animation works in general, you can reference this article on CSS-Tricks.

Finally, if you're interested in knowing how to animate the fill attribute, you can find a few working examples on this thread.

Hope it helped, have fun with SVGs!

Title: Use of stroke-dashoffset

Body:
I have an arrow that I want to animate so I read about animations and I noticed I can achieve this with css keyframes and svg.

So basically I want to draw an arrow from 0 to 100%, so I have a path like:

 <path class="showUp" fill="#4C9FDC" stroke="#000000" stroke-width= "0" d="M165.15 204.15l-4.49-4.49c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01c-2.13 2.13-2.14 5.59-.01 7.72l.01.01 9.09 9.09a4.418 4.418 0 0 0 6.24 0l50.28-50.28c2.12-2.1 2.13-5.53.03-7.65l-.03-.03c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01-45.66 45.63z"/>

And I want to animate with stroke like:

@keyframes Arrow {
 from {
    stroke-dashoffset: 1000;
  }
  to {
    stroke-dashoffset: 0;
  }
}

.showUp {
  stroke-dasharray: 1000;
  stroke-dashoffset: 1000;
  animation: Arrow 5s linear forwards;
}

CodePen

But it just doing nothing. What am I doing wrong there? Regards


问:
Server.UrlEncode vs. HttpUtility.UrlEncode
Is there a difference between Server.UrlEncode and HttpUtility.UrlEncode?</p>

答: The same, Server.UrlEncode() calls HttpUtility.UrlEncode()

OwnerDisplayName: Manu

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Andrew Robinson


问:
Why am I getting an unexpected Error in Snowflake PUT load?
I am trying to load a local csv file to my staging area in Snowflake, and am using:

```<code>PUT file:'//Users/mark 1/Downloads/pp-complete.csv' @~ auto_compress=true;
</code>```

But I keep getting the error:

SQL compilation error: parse error line 1 at position 9 near '39'.
  syntax error line 1 at position 74 unexpected '

As far as I can tell, there's nothing 'wrong' with the SCV file. It opens fine in SublimeEdit and Excel, and I can't see anything 'funny' in there to account for this.

Am stuck now.

Thanks,
Mark

答:
I think you don't need single quotes, and an extra slash:

```<code>PUT 'file:///Users/mark 1/Downloads/pp-complete.csv' @~ auto_compress=true;
</code>```

Refer to the examples here

EDIT: I realize you probably do need the quotes because of the space in your file name. but I think the issue is the missing slash

Body:
I am trying to load a local csv file to my staging area in Snowflake, and am using:

PUT file:'//Users/mark 1/Downloads/pp-complete.csv' @~ auto_compress=true;

But I keep getting the error:

SQL compilation error: parse error line 1 at position 9 near '39'.
  syntax error line 1 at position 74 unexpected '

As far as I can tell, there's nothing 'wrong' with the SCV file. It opens fine in SublimeEdit and Excel, and I can't see anything 'funny' in there to account for this.

Am stuck now.

Thanks,
Mark

Body:
I think you don't need single quotes, and an extra slash:

PUT 'file:///Users/mark 1/Downloads/pp-complete.csv' @~ auto_compress=true;

Refer to the examples here

EDIT: I realize you probably do need the quotes because of the space in your file name. but I think the issue is the missing slash


问:
java streams: easiest way to find adjacent value match
How would it be possible to convert this iterative block of code to streams?</p>

```<code>Integer prev = -1;
boolean adjacentPair = false;

for(Integer num : numberList) {
    if (num.equals(prev)) {
        adjacentNumberSame = true;
        break;
    }
    prev = num;
}
return adjacentNumberSame
</code>```

答:
You can use reduce operation. Example code:

```<code>public static void main(String[] args) {
    List<Integer> list = Arrays.asList(1, 2, 2, 3);
    class Result {
        boolean adjacentPair = false;
        Integer prevItem = null;
    }
    boolean adjacentPair = list.stream().reduce(new Result(),
            (result, item) -> {
                result.adjacentPair = result.adjacentPair || item.equals(result.prevItem);
                result.prevItem = item;
                return result;
            },
            (result1, result2) -> {
                throw new UnsupportedOperationException();
            }
    ).adjacentPair;
    System.out.println(adjacentPair);
}
</code>```

class Result holds intermediate result. adjacentPair field indicates whether adjacent pair has been encountered. prevItem field holds value of the previous item which is compared on the next iteration. Third argument to this function is combiner, it's used for parallel streams and this example works with serial streams.

Body:
How would it be possible to convert this iterative block of code to streams?

Integer prev = -1;
boolean adjacentPair = false;

for(Integer num : numberList) {
    if (num.equals(prev)) {
        adjacentNumberSame = true;
        break;
    }
    prev = num;
}
return adjacentNumberSame

Body:
You can use reduce operation. Example code:

public static void main(String[] args) {
    List<Integer> list = Arrays.asList(1, 2, 2, 3);
    class Result {
        boolean adjacentPair = false;
        Integer prevItem = null;
    }
    boolean adjacentPair = list.stream().reduce(new Result(),
            (result, item) -> {
                result.adjacentPair = result.adjacentPair || item.equals(result.prevItem);
                result.prevItem = item;
                return result;
            },
            (result1, result2) -> {
                throw new UnsupportedOperationException();
            }
    ).adjacentPair;
    System.out.println(adjacentPair);
}

class Result holds intermediate result. adjacentPair field indicates whether adjacent pair has been encountered. prevItem field holds value of the previous item which is compared on the next iteration. Third argument to this function is combiner, it's used for parallel streams and this example works with serial streams.


问:
Twig returns true even if not in array (checked field)
I am probably doing it wrong but I am running through an array of values like this.

    {% for checkboxDataKey, checkboxData in checkbox %}

                <input class="form-check-input checkbox-questionlist" type="checkbox"
            {% if checkboxDataKey in values %} checked {% endif %}
            data-report-id="{{ reportId }}" name="{{ name }}" value="{{ checkboxDataKey }}" id="{{(name)}}-{{checkboxDataKey}}">

            {{ checkboxData.answer }}

    {% endfor %}

```

<p>It is checking if the checkboxDataKey is in the value array. This is working until I add the <code>different</code> value to the array (it is named <code>different</code>).</p>

<pre class="lang-php prettyprint-override"><code> array(2) { [0]=> string(1) "3" [1]=> string(9) "different" }
</code>```

When this is selected the first checkbox is also checked and I cannot find out why, since the value 0 is not in the array.

When I look at the checkbox row keys
array(5) { [0]=> int(0) [1]=> int(1) [2]=> int(2) [3]=> int(3) [4]=> int(4) } they are integers.

答:
It was indeed an PHP problem. When I ran an in_array function it returned an true. So I had to do this, to tackle it.

 foreach ($fields['answers'] as $key => $value) {
            $options[$key] = array_merge($value, ['checked' => in_array((string)$key, $values)]);
        }

```

Body:
I am probably doing it wrong but I am running through an array of values like this.

    {% for checkboxDataKey, checkboxData in checkbox %}

                <input class="form-check-input checkbox-questionlist" type="checkbox"
            {% if checkboxDataKey in values %} checked {% endif %}
            data-report-id="{{ reportId }}" name="{{ name }}" value="{{ checkboxDataKey }}" id="{{(name)}}-{{checkboxDataKey}}">

            {{ checkboxData.answer }}

    {% endfor %}

It is checking if the checkboxDataKey is in the value array. This is working until I add the different value to the array (it is named different).

 array(2) { [0]=> string(1) "3" [1]=> string(9) "different" }

When this is selected the first checkbox is also checked and I cannot find out why, since the value 0 is not in the array.

When I look at the checkbox row keys
array(5) { [0]=> int(0) [1]=> int(1) [2]=> int(2) [3]=> int(3) [4]=> int(4) } they are integers.


问:
How do I fix math operation type errors with Swift?
I've ben experimenting with Swift UI and I keep running into issues with simple math operations like divide or negate throwing type errors. It seems to come up more when I start using a function that uses CGFloat. I tried doing specific casting, but that doesn't seem to help, I just get the message "Ambiguous reference to member '-'" and I don't understand where the ambiguity is coming from.

This is the SwiftUI code I'm trying to use:

   var body: some View {
        let baseHeight:CGFloat = 300.0

        let transparentColor:Color = Color.white.opacity(Double(0.0))

        return ScrollView(.vertical){
            VStack(alignment: HorizontalAlignment.leading) {
                    MapView()
                    .frame(height: baseHeight)
                    .offset(y: 0)

                    GeometryReader { geometry in
                        HStack {
                            CircleView<TitleView>(fillColor: transparentColor, scale: baseHeight / min(CGFloat(1) + CGFloat(geometry.frame(in: .global).minY), baseHeight)) {
                                TitleView(city: self.selectedCity)
                            }
                            .frame(minWidth: CGFloat(0), maxWidth: .infinity, minHeight: baseHeight, maxHeight: baseHeight)
                            .offset(y: -baseHeight) // Here I get the error "Ambiguous reference to member '-'"
                        }.frame(maxWidth: .infinity)
                    }

                Spacer().padding(.bottom, baseHeight / 3.0)

                    ForEach(cities) { city in
                        Text(city.name)
                            .padding()
                            .onTapGesture {
                                $selectedCity = city
                        }
                    }

                    Spacer()
                }
        }.edgesIgnoringSafeArea(.all)

    }
```

This is what it looks like:

How can I a) fix this, b) prevent it from happening again, c) understand why this is happening?

Thanks

答: The issue was with the onTapGesture line, that was invalid apparently, and made the math error show up. I replaced it with a button to handle the click instead. Really misleading errors, but hopefully that’s fixed with newer versions of Xcode. </p>

Body:
I've ben experimenting with Swift UI and I keep running into issues with simple math operations like divide or negate throwing type errors. It seems to come up more when I start using a function that uses CGFloat. I tried doing specific casting, but that doesn't seem to help, I just get the message "Ambiguous reference to member '-'" and I don't understand where the ambiguity is coming from.

This is the SwiftUI code I'm trying to use:

   var body: some View {
        let baseHeight:CGFloat = 300.0

        let transparentColor:Color = Color.white.opacity(Double(0.0))

        return ScrollView(.vertical){
            VStack(alignment: HorizontalAlignment.leading) {
                    MapView()
                    .frame(height: baseHeight)
                    .offset(y: 0)

                    GeometryReader { geometry in
                        HStack {
                            CircleView<TitleView>(fillColor: transparentColor, scale: baseHeight / min(CGFloat(1) + CGFloat(geometry.frame(in: .global).minY), baseHeight)) {
                                TitleView(city: self.selectedCity)
                            }
                            .frame(minWidth: CGFloat(0), maxWidth: .infinity, minHeight: baseHeight, maxHeight: baseHeight)
                            .offset(y: -baseHeight) // Here I get the error "Ambiguous reference to member '-'"
                        }.frame(maxWidth: .infinity)
                    }

                Spacer().padding(.bottom, baseHeight / 3.0)

                    ForEach(cities) { city in
                        Text(city.name)
                            .padding()
                            .onTapGesture {
                                $selectedCity = city
                        }
                    }

                    Spacer()
                }
        }.edgesIgnoringSafeArea(.all)

    }

This is what it looks like:

How can I a) fix this, b) prevent it from happening again, c) understand why this is happening?

Thanks


答:
Firstly, homogeneity, completeness and v measure score are calculated as follows:

C and K are two random variables. In your case, C is the labels true, while K is the label predicted.
If h = 1, it means that H(C|K) = 0, as H(C) is always less than 0. If H(C|K) = 0, it means that random variable C is completely determined by given random variable K, you can see more detailed definition on conditional entropy. So in your first case, why h = 1? Because when I give a value of random variable K (labels predicted), I know what the random variable C (labels true) will be. If k equals 6, I know c is 0. If k is 1, c is 1, etc. So when talking about the second case, why h != 1 or c != 1. Because even though there is a perfect match between 1 to 0, but there are no perfect match for other classes. If I give k is 1, I know c is 0. But when I give k is 0, I'm not sure whether c is 1 or 2. Thus, the homogeneity score or in reverse, completeness score, you can think about that, will not be 1.

Title: Calculate accuracy score of kmeans model

Body:
This works as expected and returns 1 for one of the groups.

from sklearn import metrics

labels_true = [0, 0, 0, 1, 1, 1]
labels_pred = [6, 6, 6, 1, 2, 2]

metrics.homogeneity_completeness_v_measure(labels_true, labels_pred)

(1.0, 0.6853314789615865, 0.8132898335036762)

But this returns 0.75 for all 3 groups while I expected "1.0" for one of the groups like the example mentioned above.

y = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]

labels = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 2, 2, 2, 0, 2, 2, 2,
       2, 2, 2, 0, 0, 2, 2, 2, 2, 0, 2, 0, 2, 0, 2, 2, 0, 0, 2, 2, 2, 2,
       2, 0, 2, 2, 2, 2, 0, 2, 2, 2, 0, 2, 2, 2, 0, 2, 2, 0]

metrics.homogeneity_completeness_v_measure(y, labels)

(0.7514854021988339, 0.7649861514489816, 0.7581756800057786)

Expected 1 in one of the groups above!

Update:

As you can see, one of the groups matches with the other and therefore one of the values should have been 1 instead of 0.75 accuracy that I get for all 3 groups. This is not expected!

from collections import Counter

Counter(y)
Counter(labels)

Counter({0: 50, 1: 50, 2: 50})
Counter({1: 50, 0: 62, 2: 38})


问:
event start-end into hot encoding in python
I have a pandas dataframe with 2 columns "type" and "sign" as follows

```<code>    type    sign
0   open    A
1   open    B
2   open    D
3   close   B
4   close   D
5   open    B
6   close   B
7   close   A
</code>```

"A" + "open" means that event A has started happening. "A" + "close" means that event A has stopped.
I need to vectorize it, when time is a major issue (the list is actually about 40 million lines long).
Kind of like one-hot-encoding, but i need "1" to exist if and only if an event is "active".
for example, for this case the results should be:

```<code>    A   B   C   D   type    sign
0   1   0   0   0   open    A
1   1   1   0   0   open    B
2   1   1   0   1   open    D
3   1   0   0   1   close   B
4   1   0   0   0   close   D
5   1   1   0   0   open    B
6   1   0   0   0   close   B
7   0   0   0   0   close   A
</code>```

Ideas?
thanks

答:
For your data, you can just do a for loop:

```<code>for sign in 'ABCD':
    df[sign] = (df['type'].where(df['sign'].eq(sign))
                 .ffill()
                 .eq('open')
                 .astype(int)
               )
</code>```

Output:

```<code>    type sign  A  B  C  D
0   open    A  1  0  0  0
1   open    B  1  1  0  0
2   open    D  1  1  0  1
3  close    B  1  0  0  1
4  close    D  1  0  0  0
5   open    B  1  1  0  0
6  close    B  1  0  0  0
7  close    A  0  0  0  0
</code>```

Body:
I have a pandas dataframe with 2 columns "type" and "sign" as follows

    type    sign
0   open    A
1   open    B
2   open    D
3   close   B
4   close   D
5   open    B
6   close   B
7   close   A

"A" + "open" means that event A has started happening. "A" + "close" means that event A has stopped.
I need to vectorize it, when time is a major issue (the list is actually about 40 million lines long).
Kind of like one-hot-encoding, but i need "1" to exist if and only if an event is "active".
for example, for this case the results should be:

    A   B   C   D   type    sign
0   1   0   0   0   open    A
1   1   1   0   0   open    B
2   1   1   0   1   open    D
3   1   0   0   1   close   B
4   1   0   0   0   close   D
5   1   1   0   0   open    B
6   1   0   0   0   close   B
7   0   0   0   0   close   A

Ideas?
thanks

Body:
For your data, you can just do a for loop:

for sign in 'ABCD':
    df[sign] = (df['type'].where(df['sign'].eq(sign))
                 .ffill()
                 .eq('open')
                 .astype(int)
               )

Output:

    type sign  A  B  C  D
0   open    A  1  0  0  0
1   open    B  1  1  0  0
2   open    D  1  1  0  1
3  close    B  1  0  0  1
4  close    D  1  0  0  0
5   open    B  1  1  0  0
6  close    B  1  0  0  0
7  close    A  0  0  0  0


问:
Using Argo for microservices deployment
I would like to deploy my microservices into the kubernetes cluster with CI/CD tool.
I just get started to learn the concept of CI/CD and would like to create an environment to see
how does it work in pratice.

According to my understanding, the deployment should look as follows:

As I've described above, I would like to deploy microservices into the K8S cluster
and I've found https://argoproj.github.io. I think, this is what I am looking for.

Argo provides different tools, for example the Workflow, but for what is the Workflow good for? When I would use Workflow, then ArgoCD is unnecessary? Or use Workflow inside ArgoCD?

How to trigger a workflow automatically, when some changes happen on the Git repository?

答:
Why Argo Workflows?

In a typical CD setup you would need to execute multiple steps and tie them together and create a pipeline. Argo workflow provides that functionality. The value proposition of argo is that each step in the workflow is a container and argo itself runs natively on kubernetes.

When I would use Workflow, then ArgoCD is unnecessary? Or use Workflow
  inside ArgoCD?

ArgoCD is only necessary to deploy/sync changes in the application artifacts to the kubernetes cluster. Typically you would need to deploy changes at the end of the workflow but this can be different based on your use case.

How to trigger a workflow automatically, when some changes happen on
  the Git repository?

You can use argoEvents to trigger argo workflow. Check the doc on git based trigger.

Title: Using Argo for microservices deployment


问:
Angular 8 / Material : subform not showing errors
I created a form with a conditional subform this way:

In the parent form:

```<code><form [formGroup]="layerFormGroup" (submit)="submit()" #f="ngForm">
  ...
  <div *ngIf="layerFormGroup.value.mode == 'features'">
    <app-edit-layer-features formControlName="modeFormGroup"></app-edit-layer-features>
  </div>
</code>```

with the TS:

```<code>ngOnInit() {

  this.layerFormGroup = this.formBuilder.group({
    ...
    modeFormGroup: ['', Validators.required]
  });
}

public submit() {

  if (!this.layerFormGroup.valid) {
    return;
  }
</code>```

Then the child form is:

```<code><ng-container [formGroup]="modeFormGroup">
<mat-horizontal-stepper>

    <mat-step label="Collection" [stepControl]="modeFormGroup">
        <mat-form-field>
            <mat-label>Collection</mat-label>
            <mat-select formControlName="collectionCtrl">
                <mat-option value="col1">col1</mat-option>
                <mat-option value="col2">col2</mat-option>
            </mat-select>
        </mat-form-field>
        <div>
            <button mat-button matStepperNext type="button">Next</button>
        </div>
    </mat-step>

    <mat-step label="Rendered geometry" [stepControl]="modeFormGroup">
        <mat-form-field>
            <mat-label>Rendered geometry</mat-label>
            <mat-select formControlName="geometryCtrl">
                <mat-option value="geoshape">a geopoint</mat-option>
                <mat-option value="geopoint">a geoshape</mat-option>
            </mat-select>
        </mat-form-field>
        <div>
            <button mat-button matStepperNext type="button">Next</button>
        </div>
    </mat-step>

</mat-horizontal-stepper>
</code>```

and finally the child view:

```<code>@Component({
selector: 'app-edit-layer-features',
templateUrl: './edit-layer-features.component.html',
styleUrls: ['./edit-layer-features.component.scss'],
providers: [
  {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => EditLayerFeaturesComponent),
    multi: true
  },
  {
    provide: NG_VALIDATORS,
    useExisting: forwardRef(() => EditLayerFeaturesComponent),
    multi: true
  }
]
})
// ControlValueAccessor: see https://christianlydemann.com/form-validation-with-controlvalueaccessor/
export class EditLayerFeaturesComponent implements OnInit, ControlValueAccessor, Validator {

  public modeFormGroup: FormGroup = this.formBuilder.group({
    collectionCtrl: ['', Validators.required],
    geometryCtrl: ['', Validators.required],
  });

  constructor(
    private formBuilder: FormBuilder) { }

  ngOnInit() {
  }

  public onTouched: () => void = () => { };

  writeValue(obj: any): void {
    if (obj) {
      this.modeFormGroup.patchValue(obj, { emitEvent: false });
      this.onTouched();
    }
  }
  registerOnChange(fn: any): void {
    this.modeFormGroup.valueChanges.subscribe(fn);
  }
  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
  setDisabledState?(isDisabled: boolean): void {
    isDisabled ? this.modeFormGroup.disable() : this.modeFormGroup.enable();
  }
  validate(control: AbstractControl): import('@angular/forms').ValidationErrors {
    return this.modeFormGroup.valid ? null : { invalidForm: { valid: false, message: 'Features fields are invalid' } };
  }
  registerOnValidatorChange?(fn: () => void): void {
    this.modeFormGroup.valueChanges.subscribe(fn);
  }
}
</code>```

The issue is the following: when I call the submit() method in the parent form, then the mat-error tags are added in the parent form but not in the child form, i.a. validation errors are shown in the parent form but not in the child one.

After some tests, I found out that calling

```<code>this.modeFormGroup.markAllAsTouched()
</code>```

in the child form will indeed show the child errors. Anyway I this should be called from the parent submit() method and I can't find how to do it (this.layerFormGroup.get('modeFormGroup').valid doesn't do the job).

I feel like I am missing something related to material, any clue?

Thx.

Edit 1 : I created a stackblitz where you can see the problem : https://stackblitz.com/edit/angular-eldyyc . If you only choose the mode = Features and you click on save layer then only the name is displayed as an error, not the subform fields

答:
The problem is the communication between the components and the reference to the original parent form group. You see, you create the form group in the parent component with modeFormGroup as a nested form group without any controls. Then you don't pass the reference to the layerFormGroup to the child component.

On the other hand, in the child component you create local property modeFormGroup. This modeFormGroup is not the same as the modeFormGroup in layerFormGroup.

this.layerFormGroup = this.formBuilder.group({
      name: ['', Validators.required],
      mode: ['', Validators.required],
      id: [''],
      modeFormGroup: this.formBuilder.group({})  //not the same as in the child component
});
```

<p>Note that <code>modeFormGroup</code> is an empty form group, without any controls. Now, in the child component, you create the child form group as:</p>

<pre class="lang-js prettyprint-override"><code>// totally different form group
public modeFormGroup: FormGroup = this.formBuilder.group({
    collectionCtrl: ['', Validators.required],
    geometryCtrl: ['', Validators.required]
});
</code>```

What you need to do is, once the child component is initialized, within the ngOnInit() function to emit the created form group with EventEmitter, and assign the form group to the modeFormGroup control in the parent form group.

I edited your stackblitz

Body:
I created a form with a conditional subform this way:

In the parent form:

<form [formGroup]="layerFormGroup" (submit)="submit()" #f="ngForm">
  ...

    <app-edit-layer-features formControlName="modeFormGroup"></app-edit-layer-features>

with the TS:

ngOnInit() {

  this.layerFormGroup = this.formBuilder.group({
    ...
    modeFormGroup: ['', Validators.required]
  });
}

public submit() {

  if (!this.layerFormGroup.valid) {
    return;
  }

Then the child form is:

<ng-container [formGroup]="modeFormGroup">
<mat-horizontal-stepper>

    <mat-step label="Collection" [stepControl]="modeFormGroup">
        <mat-form-field>
            <mat-label>Collection</mat-label>
            <mat-select formControlName="collectionCtrl">
                <mat-option value="col1">col1</mat-option>
                <mat-option value="col2">col2</mat-option>
            </mat-select>
        </mat-form-field>

            <button mat-button matStepperNext type="button">Next</button>

    </mat-step>

    <mat-step label="Rendered geometry" [stepControl]="modeFormGroup">
        <mat-form-field>
            <mat-label>Rendered geometry</mat-label>
            <mat-select formControlName="geometryCtrl">
                <mat-option value="geoshape">a geopoint</mat-option>
                <mat-option value="geopoint">a geoshape</mat-option>
            </mat-select>
        </mat-form-field>

            <button mat-button matStepperNext type="button">Next</button>

    </mat-step>

</mat-horizontal-stepper>

and finally the child view:

@Component({
selector: 'app-edit-layer-features',
templateUrl: './edit-layer-features.component.html',
styleUrls: ['./edit-layer-features.component.scss'],
providers: [
  {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => EditLayerFeaturesComponent),
    multi: true
  },
  {
    provide: NG_VALIDATORS,
    useExisting: forwardRef(() => EditLayerFeaturesComponent),
    multi: true
  }
]
})
// ControlValueAccessor: see https://christianlydemann.com/form-validation-with-controlvalueaccessor/
export class EditLayerFeaturesComponent implements OnInit, ControlValueAccessor, Validator {

  public modeFormGroup: FormGroup = this.formBuilder.group({
    collectionCtrl: ['', Validators.required],
    geometryCtrl: ['', Validators.required],
  });

  constructor(
    private formBuilder: FormBuilder) { }

  ngOnInit() {
  }

  public onTouched: () => void = () => { };

  writeValue(obj: any): void {
    if (obj) {
      this.modeFormGroup.patchValue(obj, { emitEvent: false });
      this.onTouched();
    }
  }
  registerOnChange(fn: any): void {
    this.modeFormGroup.valueChanges.subscribe(fn);
  }
  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
  setDisabledState?(isDisabled: boolean): void {
    isDisabled ? this.modeFormGroup.disable() : this.modeFormGroup.enable();
  }
  validate(control: AbstractControl): import('@angular/forms').ValidationErrors {
    return this.modeFormGroup.valid ? null : { invalidForm: { valid: false, message: 'Features fields are invalid' } };
  }
  registerOnValidatorChange?(fn: () => void): void {
    this.modeFormGroup.valueChanges.subscribe(fn);
  }
}

The issue is the following: when I call the submit() method in the parent form, then the mat-error tags are added in the parent form but not in the child form, i.a. validation errors are shown in the parent form but not in the child one.

After some tests, I found out that calling

this.modeFormGroup.markAllAsTouched()

in the child form will indeed show the child errors. Anyway I this should be called from the parent submit() method and I can't find how to do it (this.layerFormGroup.get('modeFormGroup').valid doesn't do the job).

I feel like I am missing something related to material, any clue?

Thx.

Edit 1 : I created a stackblitz where you can see the problem : https://stackblitz.com/edit/angular-eldyyc . If you only choose the mode = Features and you click on save layer then only the name is displayed as an error, not the subform fields

Body:
The problem is the communication between the components and the reference to the original parent form group. You see, you create the form group in the parent component with modeFormGroup as a nested form group without any controls. Then you don't pass the reference to the layerFormGroup to the child component.

On the other hand, in the child component you create local property modeFormGroup. This modeFormGroup is not the same as the modeFormGroup in layerFormGroup.

this.layerFormGroup = this.formBuilder.group({
      name: ['', Validators.required],
      mode: ['', Validators.required],
      id: [''],
      modeFormGroup: this.formBuilder.group({})  //not the same as in the child component
});

Note that modeFormGroup is an empty form group, without any controls. Now, in the child component, you create the child form group as:

// totally different form group
public modeFormGroup: FormGroup = this.formBuilder.group({
    collectionCtrl: ['', Validators.required],
    geometryCtrl: ['', Validators.required]
});

What you need to do is, once the child component is initialized, within the ngOnInit() function to emit the created form group with EventEmitter, and assign the form group to the modeFormGroup control in the parent form group.

I edited your stackblitz


问:
JUnit Test with Mockito - How to Mock javax.ws.rs.client.ClientRequestContext?
I have a class that implements javax.ws.rs.client.ClientRequestFilter:

```<code>public class CustomFilter implements ClientRequestFilter {

@Override
public void filter(ClientRequestContext context) throws IOException {
    URI newUri = ... //replace a new uri
    context.setUri(URI.create(newUri));

    if (context.getMethod == "POST") {
        context.setMethod("GET");
        context.getHeaders().putSingle("ID","some string");
    }
}
</code>```

What I want is somehow to mock the ClientRequestContext. I want to compare that after calling the filter() function:

The new uri is set correctly.

The new http method is set correctly.

A new header "ID" is set with "some string" for the context.

As I tried to figure out, I can only mock the getter methods, and I do not know how to mock ClientRequestContext properly and use my CustomerFilter class to call the real function filter() to change values of the ClientRequestContext object since it is an interface. Could you help me to achieve the 3 requirements?

答:
You can use argument mockito matchers and/or argument captors. Or you cat write a stub for request context and spy on it:</p>

```<code>package test;

import org.junit.Test;

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import java.io.IOException;
import java.net.URI;

import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.CoreMatchers.*;
import static org.mockito.Mockito.*;

public class ClientRequestContextTest {

    abstract static class ClientRequestContextStub implements ClientRequestContext {
        MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
        URI uri = null;
        String method = null;
        ClientRequestContextStub(){}
        @Override public String getMethod() { return method; }
        @Override public void setMethod(String method) { this.method = method; }
        @Override public URI getUri() { return uri; }
        @Override public void setUri(URI uri) { this.uri = uri; }
        @Override public MultivaluedMap<String, Object> getHeaders() { return headers; }
    }

    static class CustomFilter implements ClientRequestFilter {
        private String newUri = null;
        CustomFilter(String newUri) { this.newUri = newUri; }
        @Override
        public void filter(ClientRequestContext context) throws IOException {
            context.setUri(URI.create(newUri));
            if (context.getMethod().equals("POST")) {
                context.setMethod("GET");
                context.getHeaders().putSingle("ID", "some string");
            }
        }
    }

    @Test
    public void checkCustomFilter() throws IOException {
        URI newUriValue = URI.create("https://user:password@localhost:12345/suffix");
        ClientRequestContext context = spy(ClientRequestContextStub.class);
        context.setUri(URI.create("localhost:8080"));
        context.setMethod("POST");
        assertThat(context.getMethod(), equalTo("POST"));
        assertThat(context.getUri().toString(), equalTo("localhost:8080"));
        assertThat(context.getHeaders().size(), equalTo(0));
        new CustomFilter(newUriValue.toString()).filter(context);
        assertThat(context.getMethod(), equalTo("GET"));
        assertThat(context.getUri(), equalTo(newUriValue));
        assertThat(context.getHeaders().size(), equalTo(1));
        assertThat(context.getHeaders().getFirst("ID").toString(), is("some string"));
    }
}

</code>```

Body:
I have a class that implements javax.ws.rs.client.ClientRequestFilter:

public class CustomFilter implements ClientRequestFilter {

@Override
public void filter(ClientRequestContext context) throws IOException {
    URI newUri = ... //replace a new uri
    context.setUri(URI.create(newUri));

    if (context.getMethod == "POST") {
        context.setMethod("GET");
        context.getHeaders().putSingle("ID","some string");
    }
}

What I want is somehow to mock the ClientRequestContext. I want to compare that after calling the filter() function:

The new uri is set correctly.

The new http method is set correctly.

A new header "ID" is set with "some string" for the context.

As I tried to figure out, I can only mock the getter methods, and I do not know how to mock ClientRequestContext properly and use my CustomerFilter class to call the real function filter() to change values of the ClientRequestContext object since it is an interface. Could you help me to achieve the 3 requirements?

Body:
You can use argument mockito matchers and/or argument captors. Or you cat write a stub for request context and spy on it:

package test;

import org.junit.Test;

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import java.io.IOException;
import java.net.URI;

import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.CoreMatchers.*;
import static org.mockito.Mockito.*;

public class ClientRequestContextTest {

    abstract static class ClientRequestContextStub implements ClientRequestContext {
        MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
        URI uri = null;
        String method = null;
        ClientRequestContextStub(){}
        @Override public String getMethod() { return method; }
        @Override public void setMethod(String method) { this.method = method; }
        @Override public URI getUri() { return uri; }
        @Override public void setUri(URI uri) { this.uri = uri; }
        @Override public MultivaluedMap<String, Object> getHeaders() { return headers; }
    }

    static class CustomFilter implements ClientRequestFilter {
        private String newUri = null;
        CustomFilter(String newUri) { this.newUri = newUri; }
        @Override
        public void filter(ClientRequestContext context) throws IOException {
            context.setUri(URI.create(newUri));
            if (context.getMethod().equals("POST")) {
                context.setMethod("GET");
                context.getHeaders().putSingle("ID", "some string");
            }
        }
    }

    @Test
    public void checkCustomFilter() throws IOException {
        URI newUriValue = URI.create("https://user:password@localhost:12345/suffix");
        ClientRequestContext context = spy(ClientRequestContextStub.class);
        context.setUri(URI.create("localhost:8080"));
        context.setMethod("POST");
        assertThat(context.getMethod(), equalTo("POST"));
        assertThat(context.getUri().toString(), equalTo("localhost:8080"));
        assertThat(context.getHeaders().size(), equalTo(0));
        new CustomFilter(newUriValue.toString()).filter(context);
        assertThat(context.getMethod(), equalTo("GET"));
        assertThat(context.getUri(), equalTo(newUriValue));
        assertThat(context.getHeaders().size(), equalTo(1));
        assertThat(context.getHeaders().getFirst("ID").toString(), is("some string"));
    }
}


问:
C - charting a bar graph using 2D array - wont chart negative values
Hello everyone and thanks for taking your time to read this. I am doing an exercise where I'm given an array of integers and each integer represents the "height" of one bar in the chart. Negative values mean that the bar extends below the horizontal axis. So, if I am given an array of 4 integers, there would exactly be 4 bars in the chart.

I used a 2D array of characters to try to complete this exercise.

note: the text of the exercise says that there should be two spaces between each bar in the graph, so that's why I increment the j control variable by three in each pass.

I am having problems with the negative values. No matter what I do, the negative values won't print out on the screen.

What I have tried is the following: I determined the width of the graph by multiplying the array size by three. I then set all fields of the 2D array to spaces except for the horizontal line in the middle.

The outer, j loop iterates through the columns of the matrix. I have only one loop for this because, in every pass through the j loop we start in the 10th row.

the k loop actually does the plotting. The loop goes from zero to number-1, leaving a space for the asterisk at the top (or bottom).

I have two if statements checking if the number is <0 or >0, because in those two instances the bar is supposed to show up differently.

Here is my code:

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

int main()
{

    char mat[30][40];
    int i,j, size=0, m=20, n=40;

    int arr[7] = {1,2,-3,4,-5,6,-7};
    size=7;

    n=size*3; // n is the width of the graph

    for(i=0; i<m; i++) {          // I set all fields of the 2D array to spaces
        for(j=0; j<n; j++) {      // except for the horizontal line
            if(i==10) mat[i][j]='-';
            else mat[i][j]=' ';
        }
    }
    int k;
    int position=0; // position is the variable I use to iterate through the array
    int l;

    for(j=0; j<n; j+=3) {
        l=10;

        for( k = 0; k<arr[position]-1; k++) {
            if(arr[position]==0) {
                mat[10][j] = '*';    // if the height is zero, put an asterisk
            }

            else if((arr[position])<0) {

                l++;                    // if the number is negative,
                mat[l][j]='|';          // the bar extends below the horizontal line
            }

            else if(arr[position]>0) {

                l--;              // if the number is positive, the bar extends above the
                mat[l][j] = '|';  // horizontal line
            }

        }

        if(arr[position]>0) mat[l-1][j]='*';  //every bar ends with an asterisk
        else if(arr[position]<0) {
            mat[l+1][j]='*';
        }

        position++;  // jump to the next element in array

    }

    for(i=0; i<m; i++) {
        for(j=0; j<n; j++) {
            printf("%c",mat[i][j]);
        }
        printf("\n");
    }

    return 0;
}
</code>```

For negative numbers it just does not work. Furthermore I have made some tests and the condition else if((arr[position])<0)
is never fulfilled and I don't know why. What it does is it puts an asterisk below the horizontal line but that's about it.

Thank you for reading!

答:
You can use for( k = 0; k < abs(arr[position]) - 1; k++) otherwise if arr[position] is a negative number or 0 the loop won't execute when there are negative numbers int the arr[position].

#include <stdlib.h> is needed.

You also need to move clause for the 0 values  to the outer for loop for them to be printed on the graph.

Working sample

Body:
Hello everyone and thanks for taking your time to read this. I am doing an exercise where I'm given an array of integers and each integer represents the "height" of one bar in the chart. Negative values mean that the bar extends below the horizontal axis. So, if I am given an array of 4 integers, there would exactly be 4 bars in the chart.

I used a 2D array of characters to try to complete this exercise.

note: the text of the exercise says that there should be two spaces between each bar in the graph, so that's why I increment the j control variable by three in each pass.

I am having problems with the negative values. No matter what I do, the negative values won't print out on the screen.

What I have tried is the following: I determined the width of the graph by multiplying the array size by three. I then set all fields of the 2D array to spaces except for the horizontal line in the middle.

The outer, j loop iterates through the columns of the matrix. I have only one loop for this because, in every pass through the j loop we start in the 10th row.

the k loop actually does the plotting. The loop goes from zero to number-1, leaving a space for the asterisk at the top (or bottom).

I have two if statements checking if the number is <0 or >0, because in those two instances the bar is supposed to show up differently.

Here is my code:

#include <stdio.h>

int main()
{

    char mat[30][40];
    int i,j, size=0, m=20, n=40;

    int arr[7] = {1,2,-3,4,-5,6,-7};
    size=7;

    n=size*3; // n is the width of the graph

    for(i=0; i<m; i++) {          // I set all fields of the 2D array to spaces
        for(j=0; j<n; j++) {      // except for the horizontal line
            if(i==10) mat[i][j]='-';
            else mat[i][j]=' ';
        }
    }
    int k;
    int position=0; // position is the variable I use to iterate through the array
    int l;

    for(j=0; j<n; j+=3) {
        l=10;

        for( k = 0; k<arr[position]-1; k++) {
            if(arr[position]==0) {
                mat[10][j] = '*';    // if the height is zero, put an asterisk
            }

            else if((arr[position])<0) {

                l++;                    // if the number is negative,
                mat[l][j]='|';          // the bar extends below the horizontal line
            }

            else if(arr[position]>0) {

                l--;              // if the number is positive, the bar extends above the
                mat[l][j] = '|';  // horizontal line
            }

        }

        if(arr[position]>0) mat[l-1][j]='*';  //every bar ends with an asterisk
        else if(arr[position]<0) {
            mat[l+1][j]='*';
        }

        position++;  // jump to the next element in array

    }

    for(i=0; i<m; i++) {
        for(j=0; j<n; j++) {
            printf("%c",mat[i][j]);
        }
        printf("\n");
    }

    return 0;
}

For negative numbers it just does not work. Furthermore I have made some tests and the condition else if((arr[position])<0)
is never fulfilled and I don't know why. What it does is it puts an asterisk below the horizontal line but that's about it.

Thank you for reading!


问:
PHP Countdown Timer Problem?
I have coded a simple PHP Countdown Timer using this code:

```<code>list($date,$time)=explode(" ",$compounddate);
list($thour,$tminute,$tsecond)=explode(":",$time);
list($tyear,$tmonth,$tday)=explode(":",$date);
$date=str_replace(":","/",$date);
$target = mktime($thour,$tminute,$tsecond,$tmonth,$tday,$tyear) ;

$today = time () ;

$difference =($target-$today) ;

$days = floor(abs($difference/86400));

$hours = floor(abs($difference%86400/3600));

$minutes =floor(abs($difference%3600/60));

$seconds = floor(abs($difference%60));

$date = date("F d, Y ",strtotime($date));
$time = date("g:i:s A",strtotime($time));
$past_future="";
$boolpast_future=true;
if($difference<0) {
$past_future="<strong> Time since ".$date." at ".$time.": </strong>";
$boolpast_future=false;
}
else {
$past_future="<strong> Countdown to ".$date." at ".$time.": </strong>";
$boolpast_future=true;
}
}
</code>```

($thour, $tminute, etc mean target hour, target minute...)

However, this code does not calculate the countdown time properly. How to fix this? Thanks!

答:
```<code>date_default_timezone_set('Asia/Tokyo');

$target = new DateTime('2011-06-01 05:00:00');
$now = new DateTime;
$diff = $target->diff($now);

if ($target > $now) {
    echo $diff->format('%a days, %h hours, %i minutes to go');
} else {
    echo $diff->format('%a days, %h hours, %i minutes too late');
}
</code>```

Title: PHP Countdown Timer Problem?

Body:
I have coded a simple PHP Countdown Timer using this code:

list($date,$time)=explode(" ",$compounddate);
list($thour,$tminute,$tsecond)=explode(":",$time);
list($tyear,$tmonth,$tday)=explode(":",$date);
$date=str_replace(":","/",$date);
$target = mktime($thour,$tminute,$tsecond,$tmonth,$tday,$tyear) ;

$today = time () ;

$difference =($target-$today) ;

$days = floor(abs($difference/86400));

$hours = floor(abs($difference%86400/3600));

$minutes =floor(abs($difference%3600/60));

$seconds = floor(abs($difference%60));

$date = date("F d, Y ",strtotime($date));
$time = date("g:i:s A",strtotime($time));
$past_future="";
$boolpast_future=true;
if($difference<0) {
$past_future=" Time since ".$date." at ".$time.": ";
$boolpast_future=false;
}
else {
$past_future=" Countdown to ".$date." at ".$time.": ";
$boolpast_future=true;
}
}

($thour, $tminute, etc mean target hour, target minute...)

However, this code does not calculate the countdown time properly. How to fix this? Thanks!


问:
Show jobs over 3 BUSINESS DAYS old
Can someone offer any help on how I would amend the SQL code to show jobs that are over 3 BUSINESS DAYS old?

I have the following code:

```<code>select
central_enquiry.enquiry_number,
central_enquiry.enquiry_time,
central_enquiry.officer_code,
type_of_service.service_code,
type_of_service.service_name,
enquiry_subject. subject_code,
enquiry_subject.subject_name,
central_site.site_name,
central_enquiry.enquiry_address,
central_enquiry.enquiry_desc,
enquiry_status.enq_status_code,
enquiry_status.enq_status_name,
central_enquiry.log_effective_date,
central_enquiry.follow_up_date,

CASE
when round((SYSDATE - central_enquiry.enquiry_time),2) >=3 then 'Over 3 days'
else ''
end as Days_since_reported

from
central_enquiry
inner join enquiry_subject on enquiry_subject.subject_code = central_enquiry.subject_code
inner join type_of_service on type_of_service.service_code = enquiry_subject.service_code
inner join enquiry_status_log on central_enquiry.enquiry_number = enquiry_status_log.enquiry_number and central_enquiry.enquiry_log_number = enquiry_status_log.enquiry_log_number
inner join enquiry_status on enquiry_status.enq_status_code = enquiry_status_log.enq_status_code
inner join central_site on central_site.site_code = central_enquiry.site_code

where
type_of_service.service_code = 'ECPE' and
round((SYSDATE - central_enquiry.enquiry_time),2) >=3 and
central_enquiry.officer_code = 'BSO' and
central_enquiry.outstanding_flag = 'Y'

order by central_enquiry.enquiry_number
</code>```

This shows me all jobs that have been logged more than 3 days ago based on the current date.

```<code>where  round((SYSDATE - central_enquiry.enquiry_time),2) >=3
</code>```

However I want this to only show me the jobs that have been logged more than 3 BUSINESS days ago - so if a job was logged on Thursday 13th Feb - it would only show in the report when it was past the same time on Tuesday 18th Feb.

答:
You need to manipulate your condition as following:

```<code>where round((SYSDATE - central_enquiry.enquiry_time),2)
- case when to_char(SYSDATE,'dy') in ('mon','tue') then 2 else 0 end >=3
</code>```

Cheers!!

Title: Show jobs over 3 BUSINESS DAYS old

Body:
Can someone offer any help on how I would amend the SQL code to show jobs that are over 3 BUSINESS DAYS old?

I have the following code:

select
central_enquiry.enquiry_number,
central_enquiry.enquiry_time,
central_enquiry.officer_code,
type_of_service.service_code,
type_of_service.service_name,
enquiry_subject. subject_code,
enquiry_subject.subject_name,
central_site.site_name,
central_enquiry.enquiry_address,
central_enquiry.enquiry_desc,
enquiry_status.enq_status_code,
enquiry_status.enq_status_name,
central_enquiry.log_effective_date,
central_enquiry.follow_up_date,

CASE
when round((SYSDATE - central_enquiry.enquiry_time),2) >=3 then 'Over 3 days'
else ''
end as Days_since_reported

from
central_enquiry
inner join enquiry_subject on enquiry_subject.subject_code = central_enquiry.subject_code
inner join type_of_service on type_of_service.service_code = enquiry_subject.service_code
inner join enquiry_status_log on central_enquiry.enquiry_number = enquiry_status_log.enquiry_number and central_enquiry.enquiry_log_number = enquiry_status_log.enquiry_log_number
inner join enquiry_status on enquiry_status.enq_status_code = enquiry_status_log.enq_status_code
inner join central_site on central_site.site_code = central_enquiry.site_code

where
type_of_service.service_code = 'ECPE' and
round((SYSDATE - central_enquiry.enquiry_time),2) >=3 and
central_enquiry.officer_code = 'BSO' and
central_enquiry.outstanding_flag = 'Y'

order by central_enquiry.enquiry_number

This shows me all jobs that have been logged more than 3 days ago based on the current date.

where  round((SYSDATE - central_enquiry.enquiry_time),2) >=3

However I want this to only show me the jobs that have been logged more than 3 BUSINESS days ago - so if a job was logged on Thursday 13th Feb - it would only show in the report when it was past the same time on Tuesday 18th Feb.

Body:
You need to manipulate your condition as following:

where round((SYSDATE - central_enquiry.enquiry_time),2)
- case when to_char(SYSDATE,'dy') in ('mon','tue') then 2 else 0 end >=3

Cheers!!


问:
Mojo $c->reply->exception vs die?
They seem to do the same thing.

```<code>$c->reply->exception('foo');
return;
</code>```

vs

```<code>die "foo\n";
</code>```

Should I chose one over the other?

答:
The latter is easier to read, can be trapped at the appropriate level if needed, and can include stack traces and context in development mode via automatic Mojo::Exception wrapping. It also will act appropriately in a promise handler or async sub, causing the promise to be rejected.

You can see exactly how it's handled here ($next->() is the call to the dispatch chain): https://metacpan.org/source/SRI/Mojolicious-8.33/lib/Mojolicious.pm#L208-214

Title: Mojo $c->reply->exception vs die?

Body:
They seem to do the same thing.

$c->reply->exception('foo');
return;

vs

die "foo\n";

Should I chose one over the other?