问:
Setting contentInset of WKWebView scrollView causes page jump to top
After setting contentInset of WKWebView, I found if I use default swipe gesture to navigate between pages, WKWebView will not reserve the contentInset and just jump to the top, does anyone know how to resolve that? Thanks!

My sample code:

```<code>import UIKit
import WebKit

class ViewController: UIViewController {

    private lazy var webView: WKWebView = {
        let view = WKWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
        view.allowsBackForwardNavigationGestures = true
        view.scrollView.contentInsetAdjustmentBehavior = .never
        view.scrollView.contentInset = UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0)

        view.navigationDelegate = self
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.view.addSubview(self.webView)

        if let url = URL(string: "http://www.wikipedia.org") {
            self.webView.load(URLRequest(url: url))
        }
    }

}
</code>```

答:
If you set contentInset for a scrollview of WKWebView, you need set another property of WKWebview with same value.
view.setValue(UIEdgeInsets, forKey: "_obscuredInsets")

Refer to : https://opensource.apple.com/source/WebKit2/WebKit2-7600.1.4.11.10/ChangeLog

```<code>private lazy var webView: WKWebView = {
        let view = WKWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
        view.allowsBackForwardNavigationGestures = true
        view.scrollView.contentInsetAdjustmentBehavior = .never
        let edgeInsets = UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0)
        view.setValue(edgeInsets, forKey: "_obscuredInsets")
        view.scrollView.contentInset = edgeInsets
        return view
    }()
</code>```

If you set contentInsetAdjustmentBehavior = .automatic, there will have a extra edge of status bar. You also need to add the status bar height to obscuredInsets.

```<code>view.scrollView.contentInsetAdjustmentBehavior = . automatic
webView.scrollView.contentInset = UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0)
webView.setValue(UIEdgeInsets(top: 50 + 44, left: 0, bottom: 0, right: 0), forKey: "_obscuredInsets")
</code>```

44 is the height of status bar(safeArea).

Checked the newest WKWebView: https://github.com/WebKit/webkit/blob/master/Source/WebKit/UIProcess/API/Cocoa/WKWebView.mm

Now need add an extra property: _haveSetObscuredInsets

webView.setValue(true, forKey: "_haveSetObscuredInsets")

Body:
After setting contentInset of WKWebView, I found if I use default swipe gesture to navigate between pages, WKWebView will not reserve the contentInset and just jump to the top, does anyone know how to resolve that? Thanks!

My sample code:

import UIKit
import WebKit

class ViewController: UIViewController {

    private lazy var webView: WKWebView = {
        let view = WKWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
        view.allowsBackForwardNavigationGestures = true
        view.scrollView.contentInsetAdjustmentBehavior = .never
        view.scrollView.contentInset = UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0)

        view.navigationDelegate = self
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.view.addSubview(self.webView)

        if let url = URL(string: "http://www.wikipedia.org") {
            self.webView.load(URLRequest(url: url))
        }
    }

}

Body:
If you set contentInset for a scrollview of WKWebView, you need set another property of WKWebview with same value.
view.setValue(UIEdgeInsets, forKey: "_obscuredInsets")

Refer to : https://opensource.apple.com/source/WebKit2/WebKit2-7600.1.4.11.10/ChangeLog

private lazy var webView: WKWebView = {
        let view = WKWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
        view.allowsBackForwardNavigationGestures = true
        view.scrollView.contentInsetAdjustmentBehavior = .never
        let edgeInsets = UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0)
        view.setValue(edgeInsets, forKey: "_obscuredInsets")
        view.scrollView.contentInset = edgeInsets
        return view
    }()

If you set contentInsetAdjustmentBehavior = .automatic, there will have a extra edge of status bar. You also need to add the status bar height to obscuredInsets.

view.scrollView.contentInsetAdjustmentBehavior = . automatic
webView.scrollView.contentInset = UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0)
webView.setValue(UIEdgeInsets(top: 50 + 44, left: 0, bottom: 0, right: 0), forKey: "_obscuredInsets")

44 is the height of status bar(safeArea).

Checked the newest WKWebView: https://github.com/WebKit/webkit/blob/master/Source/WebKit/UIProcess/API/Cocoa/WKWebView.mm

Now need add an extra property: _haveSetObscuredInsets

webView.setValue(true, forKey: "_haveSetObscuredInsets")


来源: stackexchange

问:
How do I get this javascript to run every second?
How do I get this javascript to run every second?

source code:

```<code><script type="text/javascript">
$(function() {
    //More Button
    $('.more').live("click",function()  {
        var ID = $(this).attr("id");
        if(ID) {
            $("#more"+ID).html('<img src="moreajax.gif" />');

            $.ajax({
                type: "POST",
                url: "ajax_more.php",
                data: "lastmsg="+ ID,
                cache: false,
                success: function(html){
                    $("ol#updates").prepend(html);
                    $("#more"+ID).remove();
                }
            });
        } else {
            $(".morebox").html('no posts to display');
        }

        return false;

    });
});

</script>
</code>```

答:
Use setInterval() to run a piece of code every x milliseconds.

You can wrap the code you want to run every second in a function called runFunction.

So it would be:

```<code>var t=setInterval(runFunction,1000);
</code>```

And to stop it, you can run:

```<code>clearInterval(t);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Use setInterval() to run a piece of code every x milliseconds.

You can wrap the code you want to run every second in a function called runFunction.

So it would be:

var t=setInterval(runFunction,1000);

And to stop it, you can run:

clearInterval(t);

ContentLicense: CC BY-SA 3.0


问:
Determine if individuals in a dataframe met a certain condition in a given time period in R
I have data which looks like this

```<code>pop_df <- data.frame(
  uniq_ID = c("AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
              "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234",
              "AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
              "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234",
              "AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
              "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234",
              "AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
              "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234"),
  Quarter = c((rep("20170101",20)), (rep("20170401",20)), (rep("20170701",20)), (rep("20171001",20))),
  contact = sample(c(0,1), replace = T, size = 80),
  )
</code>```

This is a list of unique IDs, the quarter (ie three month period in the year), and whether or not they made contact with a doctor in that quarter.
What I want to know is if someone made contact in the entire year of 2017, based on the value of "contact".
So, for each unique ID, if contact == 1 in any quarter, then they made contact in 2017.

My desired output is a new variable, called contact_year, where the value is 1 for each unique ID if that unique ID made contact in any quarter.

Thanks.

答:
An option would be to group by 'uniq_ID' and check if there are any 'contact'

```<code>library(dplyr)
pop_df %>%
   group_by(uniq_ID) %>%
   mutate(contact_year = as.integer(any(as.logical(contact))))
</code>```

In the OP's example there was only 2017 data.  If it also includes other dates, we can create a logical index with &

```<code>pop_df %>%
    group_by(uniq_ID) %>%
    mutate(contact_year = as.integer(any(as.logical(contact) &
                               substr(Quarter, 1, 4) == 2017)))
</code>```

Body:
I have data which looks like this

pop_df <- data.frame(
  uniq_ID = c("AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
              "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234",
              "AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
              "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234",
              "AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
              "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234",
              "AFG1234", "WED1234", "POJ1234", "DER234", "QWE1234", "BGR1234", "ABC1234", "DSE1234", "UHJ1234", "POI234",
              "EDC1234", "BGT1234", "MJI1234", "WEX1234", "FGH1234", "UJN1234", "LOK1234", "DRT1234", "URD1234", "MVR1234"),
  Quarter = c((rep("20170101",20)), (rep("20170401",20)), (rep("20170701",20)), (rep("20171001",20))),
  contact = sample(c(0,1), replace = T, size = 80),
  )

This is a list of unique IDs, the quarter (ie three month period in the year), and whether or not they made contact with a doctor in that quarter.
What I want to know is if someone made contact in the entire year of 2017, based on the value of "contact".
So, for each unique ID, if contact == 1 in any quarter, then they made contact in 2017.

My desired output is a new variable, called contact_year, where the value is 1 for each unique ID if that unique ID made contact in any quarter.

Thanks.

Body:
An option would be to group by 'uniq_ID' and check if there are any 'contact'

library(dplyr)
pop_df %>%
   group_by(uniq_ID) %>%
   mutate(contact_year = as.integer(any(as.logical(contact))))

In the OP's example there was only 2017 data.  If it also includes other dates, we can create a logical index with &

pop_df %>%
    group_by(uniq_ID) %>%
    mutate(contact_year = as.integer(any(as.logical(contact) &
                               substr(Quarter, 1, 4) == 2017)))


问:
How to fix "CondaValueError: Invalid environment name" in conda terminal when I use "conda env export"?
I want to export my conda environment by using conda env export > xxx.yml,but it doesn't work.

My conda environment is created by specify the --prefix, it names "E:/Envs/DRF".To export it, I use conda activate E:/Envs/DRF make it activated.And then I use conda env export > xxx.yml,it doesn't work and I get some Error below.

Firstly,activate it:

```<code>E:\WorkSpace\PyCharm\CET6Cat>conda activate E:/Envs/DRF
</code>```

And then I wanna export it to .yml file:

```<code>(E:\Envs\DRF) E:\WorkSpace\PyCharm\CET6Cat>conda env export > environment.yml
WARNING: The conda.compat module is deprecated and will be removed in a future r
elease.
WARNING: The conda.compat module is deprecated and will be removed in a future r
elease.

CondaValueError: Invalid environment name: 'E:\Envs\DRF'
  Characters not allowed: ('/', ' ', ':')
</code>```

It doesn't work!

答:
Try

```<code>conda env export --prefix /home/..../tfpy37 > dependency.yml
</code>```

Here tfpy37 is my conda environment name located in my ubuntu directory  /home/....

Body:
I want to export my conda environment by using conda env export > xxx.yml,but it doesn't work.

My conda environment is created by specify the --prefix, it names "E:/Envs/DRF".To export it, I use conda activate E:/Envs/DRF make it activated.And then I use conda env export > xxx.yml,it doesn't work and I get some Error below.

Firstly,activate it:

E:\WorkSpace\PyCharm\CET6Cat>conda activate E:/Envs/DRF

And then I wanna export it to .yml file:

(E:\Envs\DRF) E:\WorkSpace\PyCharm\CET6Cat>conda env export > environment.yml
WARNING: The conda.compat module is deprecated and will be removed in a future r
elease.
WARNING: The conda.compat module is deprecated and will be removed in a future r
elease.

CondaValueError: Invalid environment name: 'E:\Envs\DRF'
  Characters not allowed: ('/', ' ', ':')

It doesn't work!

Body:
Try

conda env export --prefix /home/..../tfpy37 > dependency.yml

Here tfpy37 is my conda environment name located in my ubuntu directory  /home/....


问:
list.copy() not creating an true copy
I'm trying to write a little bit of code to complete an exercise on codewars link

Part of what I want to do is loop through a list of lists that are representing the sudoku grid and replace 0's with a list of possible numbers.

My problem is that even when I use list.copy() to hold the original puzzle any changes I make to the original list (not the copy) still changes the copy.

How can this be happening?

Below is my code:

```<code>def sudoku(puzzle):

    # copy the puzzle to be able to save original positions that are changeable
    pc = puzzle.copy()

    puzzle = pns(puzzle)

    return puzzle

def pns(puzzle):
    for y in range(len(puzzle)):
        for x in range(len(puzzle[0])):

            pn = set(range(1,len(puzzle) + 1))

            for row_idx in range(len(puzzle)):
                for col_idx in range(len(puzzle[row_idx])):

                    skip_bool = True
                    if puzzle[y][x] != 0 and type(puzzle[y][x]) == type(1):
                        skip_bool = False

                    if row_idx == y and col_idx != x and type(puzzle[row_idx][col_idx]) != type([0]):
                        if puzzle[row_idx][col_idx] in pn:
                            pn.remove(puzzle[row_idx][col_idx])

                    if col_idx == x and row_idx != y and type(puzzle[row_idx][col_idx]) !=  type([0]):
                        if puzzle[row_idx][col_idx] in pn:
                            pn.remove(puzzle[row_idx][col_idx])
            pn = list(pn)

            if len(pn) == 1:
                puzzle[y][x] = pn[0]

            elif len(pn) == 0:
                puzzle[y][x] = False

            elif skip_bool:
                puzzle[y][x] = pn

    return puzzle
</code>```

Expected output from:

```<code>print(pc)
print(puzzle)

</code>```

```<code>[5, 3, 0, 0, 7, 0, 0, 0, 0]
[6, 0, 0, 1, 9, 5, 0, 0, 0]
[0, 9, 8, 0, 0, 0, 0, 6, 0]
[8, 0, 0, 0, 6, 0, 0, 0, 3]
[4, 0, 0, 8, 0, 3, 0, 0, 1]
[7, 0, 0, 0, 2, 0, 0, 0, 6]
[0, 6, 0, 0, 0, 0, 2, 8, 0]
[0, 0, 0, 4, 1, 9, 0, 0, 5]
[0, 0, 0, 0, 8, 0, 0, 7, 9]

[5, 3, [1, 2, 4, 6, 9], [2, 6, 9], 7, [1, 2, 4, 6, 8], [1, 4, 6, 8, 9], [1, 2, 4, 9], [2, 4, 8]]
[6, [2, 4, 7, 8], [2, 3, 4, 7], 1, 9, 5, [3, 4, 7, 8], [2, 3, 4], [2, 4, 7, 8]]
[[1, 2, 3], 9, 8, [2, 3, 5, 7], [3, 4, 5], [1, 2, 4, 7], [1, 3, 4, 5, 7], 6, [2, 4, 7]]
[8, [1, 2, 4, 5, 7], [1, 2, 4, 5, 7, 9], [2, 5, 7, 9], 6, [1, 2, 4, 7], [1, 4, 5, 7, 9], [1, 2, 4, 5, 9], 3]
[4, [2, 5, 7], [2, 5, 6, 7, 9], 8, 5, 3, [6, 7, 9], [2, 9], 1]
[7, [1, 4, 5, 8], [1, 3, 4, 5, 9], [3, 5, 9], 2, [1, 4, 8], [1, 3, 4, 5, 8, 9], [1, 3, 4, 5, 9], 6]
[[1, 3, 9], 6, [1, 3, 4, 5, 7, 9], [3, 5, 7, 9], [3, 4], [1, 4, 7], 2, 8, [4, 7]]
[[2, 3], [2, 7, 8], [2, 3, 6, 7], 4, 1, 9, [3, 6, 7, 8], [2, 3], 5]
[[1, 2, 3], [1, 2, 4, 5], [1, 2, 3, 4, 5, 6], [2, 3, 5, 6], 8, [1, 2, 4, 6], [1, 3, 4, 5, 6], 7, 9]

</code>```

What I actually get back is 2 copies of the second list.

答:
For nested structures, .copy() only will create a copy of the top-level objects, but the references contained within will still be the same references.

You probably want copy.deepcopy().

Title: list.copy() not creating an true copy

Body:
I'm trying to write a little bit of code to complete an exercise on codewars link

Part of what I want to do is loop through a list of lists that are representing the sudoku grid and replace 0's with a list of possible numbers.

My problem is that even when I use list.copy() to hold the original puzzle any changes I make to the original list (not the copy) still changes the copy.

How can this be happening?

Below is my code:

def sudoku(puzzle):

    # copy the puzzle to be able to save original positions that are changeable
    pc = puzzle.copy()

    puzzle = pns(puzzle)

    return puzzle

def pns(puzzle):
    for y in range(len(puzzle)):
        for x in range(len(puzzle[0])):

            pn = set(range(1,len(puzzle) + 1))

            for row_idx in range(len(puzzle)):
                for col_idx in range(len(puzzle[row_idx])):

                    skip_bool = True
                    if puzzle[y][x] != 0 and type(puzzle[y][x]) == type(1):
                        skip_bool = False

                    if row_idx == y and col_idx != x and type(puzzle[row_idx][col_idx]) != type([0]):
                        if puzzle[row_idx][col_idx] in pn:
                            pn.remove(puzzle[row_idx][col_idx])

                    if col_idx == x and row_idx != y and type(puzzle[row_idx][col_idx]) !=  type([0]):
                        if puzzle[row_idx][col_idx] in pn:
                            pn.remove(puzzle[row_idx][col_idx])
            pn = list(pn)

            if len(pn) == 1:
                puzzle[y][x] = pn[0]

            elif len(pn) == 0:
                puzzle[y][x] = False

            elif skip_bool:
                puzzle[y][x] = pn

    return puzzle

Expected output from:

print(pc)
print(puzzle)

[5, 3, 0, 0, 7, 0, 0, 0, 0]
[6, 0, 0, 1, 9, 5, 0, 0, 0]
[0, 9, 8, 0, 0, 0, 0, 6, 0]
[8, 0, 0, 0, 6, 0, 0, 0, 3]
[4, 0, 0, 8, 0, 3, 0, 0, 1]
[7, 0, 0, 0, 2, 0, 0, 0, 6]
[0, 6, 0, 0, 0, 0, 2, 8, 0]
[0, 0, 0, 4, 1, 9, 0, 0, 5]
[0, 0, 0, 0, 8, 0, 0, 7, 9]

[5, 3, [1, 2, 4, 6, 9], [2, 6, 9], 7, [1, 2, 4, 6, 8], [1, 4, 6, 8, 9], [1, 2, 4, 9], [2, 4, 8]]
[6, [2, 4, 7, 8], [2, 3, 4, 7], 1, 9, 5, [3, 4, 7, 8], [2, 3, 4], [2, 4, 7, 8]]
[[1, 2, 3], 9, 8, [2, 3, 5, 7], [3, 4, 5], [1, 2, 4, 7], [1, 3, 4, 5, 7], 6, [2, 4, 7]]
[8, [1, 2, 4, 5, 7], [1, 2, 4, 5, 7, 9], [2, 5, 7, 9], 6, [1, 2, 4, 7], [1, 4, 5, 7, 9], [1, 2, 4, 5, 9], 3]
[4, [2, 5, 7], [2, 5, 6, 7, 9], 8, 5, 3, [6, 7, 9], [2, 9], 1]
[7, [1, 4, 5, 8], [1, 3, 4, 5, 9], [3, 5, 9], 2, [1, 4, 8], [1, 3, 4, 5, 8, 9], [1, 3, 4, 5, 9], 6]
[[1, 3, 9], 6, [1, 3, 4, 5, 7, 9], [3, 5, 7, 9], [3, 4], [1, 4, 7], 2, 8, [4, 7]]
[[2, 3], [2, 7, 8], [2, 3, 6, 7], 4, 1, 9, [3, 6, 7, 8], [2, 3], 5]
[[1, 2, 3], [1, 2, 4, 5], [1, 2, 3, 4, 5, 6], [2, 3, 5, 6], 8, [1, 2, 4, 6], [1, 3, 4, 5, 6], 7, 9]

What I actually get back is 2 copies of the second list.


问:
How can I make a form with custom check boxes that will direct me to different html files on submit form?
I have a form with custom check boxes that I want to hold references to my other html pages. I want the user to select one of the check boxes and then hit the start button at the bottom. What should happen is it will take the user to the html file that was attached to the checkbox. I know this probably didnt make sense so go to the web version of the site to get an idea of what I am trying to do.</p>

```<code>    <form method="post">
    <div class="form-row">
        <div class="col-sm-1">
        </div>
        <div class="col-sm">
            <div class="media">
                <img src="https://www.mometrix.com/academy/wp-content/uploads/2017/12/Algebra-I-1024x683.jpg" class="mr-3" alt="" width="150" height="150">
                <div class="media-body">
                    <h5 class="mt-0">Algebra</h5>
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="customSwitch1" name="AL">
                        <label class="custom-control-label" for="customSwitch1"></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm">
            <div class="media">
                <img src="https://www.wikihow.com/images/thumb/a/ae/Find-Area-and-Perimeter-Step-7-Version-2.jpg/aid3987529-v4-728px-Find-Area-and-Perimeter-Step-7-Version-2.jpg" class="mr-3" alt="..." width="150" height="150">
                <div class="media-body">
                    <h5 class="mt-0">Area & Perimeter</h5>
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="customSwitch2" name="AP">
                        <label class="custom-control-label" for="customSwitch2"></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-12">
        </div>
    </div>
    <div class="form-row">
        <div class="col-sm-1">
        </div>
        <div class="col-sm">
            <div class="media">
                <img src="https://www.mathsisfun.com/numbers/images/arithmetic.svg" class="mr-3" alt="..." width="150" height="150">
                <div class="media-body">
                    <h5 class="mt-0">Arithmetic</h5>
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="customSwitch3" name="AR">
                        <label class="custom-control-label" for="customSwitch3"></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm">
            <div class="media">
                <img src="https://www.mathsisfun.com/algebra/images/exponent-8-2.svg" class="mr-3" alt="..." width="150" height="150">
                <div class="media-body">
                    <h5 class="mt-0">Exponents</h5>
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="customSwitch4" name="EX">
                        <label class="custom-control-label" for="customSwitch4"></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-12">
        </div>
    </div>
    <div class="form-row">
        <div class="col-sm-1">
        </div>
        <div class="col-sm">
            <div class="media">
                <img src="https://dmzn2b8hkpq8b.cloudfront.net/images/products/515x515/S411589.jpg" class="mr-3" alt="..." width="150" height="150">
                <div class="media-body">
                    <h5 class="mt-0">Geometric Solids</h5>
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="customSwitch5" name="GS">
                        <label class="custom-control-label" for="customSwitch5"></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm">
            <div class="media">
                <img src="data:image/png;base64,[encoded data, 11644 characters]" class="mr-3" alt="..." width="150" height="150">
                <div class="media-body">
                    <h5 class="mt-0">Probability</h5>
                    <div class="">
                        <input type="checkbox" class="custom-control-input" id="customSwitch6" name="PR">
                        <label class="custom-control-label" for="customSwitch6"></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-12">
        </div>
    </div>
    <div class="form-row">
        <div class="col-sm-1">
        </div>
        <div class="col-sm">
            <div class="media">
                <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDvygQLpB_G08iwALHg6N6rIEm1abgLnEQKZF0Qn6QOZFQDYWP" class="mr-3" alt="..." width="150" height="150">
                <div class="media-body">
                    <h5 class="mt-0">Systems of Equations</h5>
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="customSwitch7" name="SE">
                        <label class="custom-control-label" for="customSwitch7"></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm">
            <div class="media">
                <img src="http://home.windstream.net/okrebs/Ch8-28.gif" class="mr-3" alt="..." width="150" height="150">
                <div class="media-body">
                    <h5 class="mt-0">Trig Statements</h5>
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="customSwitch8" name="TR">
                        <label class="custom-control-label" for="customSwitch8"></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-12">
        </div>
    </div>
    <center>
        <button type="submit" class="btn btn-outline-success">Start</button>
    </center>
</form>
</code>```

答:
I made some minor changes

1 _ adding data-page to each checkbox with page url.

2 _ addind ID to the form

document.addEventListener("DOMContentLoaded", function()
{
  const
    MyForm       = document.getElementById('My-Form'),
    all_checkBox = document.querySelectorAll('#My-Form input[type=checkbox]'),
    SubmitBt     = document.querySelector('#My-Form button[type=submit]');

  all_checkBox.forEach(chkBx=>{ chkBx.onchange = ChkBxChanged })

  SubmitBt.disabled = true;

  function ChkBxChanged(e)
  {
    MyForm.action = '';
    SubmitBt.disabled = true;

    if ( this.checked )
    {
      MyForm.action     = this.dataset.page;
      SubmitBt.disabled = false;

      all_checkBox.forEach(cb=>{
        if (cb!=this) cb.checked = false   // only one should be checked
      })
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="My-Form" action="" method="POST" >

  <h5 class="mt-0">Algebra</h5>
  <input type="checkbox" class="custom-control-input" id="customSwitch1" name="AL" data-page="Algebra.html" >

  <h5 class="mt-0">Area & Perimeter</h5>
  <input type="checkbox" class="custom-control-input" id="customSwitch2" name="AP" data-page="Area_Perimeter.html" >

  <h5 class="mt-0">Arithmetic</h5>
  <input type="checkbox" class="custom-control-input" id="customSwitch3" name="AR" data-page="Arithmetic.html" >

  <h5 class="mt-0">Exponents</h5>
  <input type="checkbox" class="custom-control-input" id="customSwitch4" name="EX" data-page="Exponents.html" >

  <h5 class="mt-0">Geometric Solids</h5>
  <input type="checkbox" class="custom-control-input" id="customSwitch5" name="GS" data-page="Geometric_Solids.html" >

  <h5 class="mt-0">Probability</h5>
  <input type="checkbox" class="custom-control-input" id="customSwitch6" name="PR" data-page="Probability.html" >

  <h5 class="mt-0">Systems of Equations</h5>
  <input type="checkbox" class="custom-control-input" id="customSwitch7" name="SE" data-page="Equations.html" >

  <h5 class="mt-0">Trig Statements</h5>
  <input type="checkbox" class="custom-control-input" id="customSwitch8" name="TR" data-page="Trig_Statements.html" >

  <button type="submit" class="btn btn-outline-success">Start</button>

</form></code>```

Body:
I have a form with custom check boxes that I want to hold references to my other html pages. I want the user to select one of the check boxes and then hit the start button at the bottom. What should happen is it will take the user to the html file that was attached to the checkbox. I know this probably didnt make sense so go to the web version of the site to get an idea of what I am trying to do.

    <form method="post">

Algebra

                        <input type="checkbox" class="custom-control-input" id="customSwitch1" name="AL">

Area & Perimeter

                        <input type="checkbox" class="custom-control-input" id="customSwitch2" name="AP">

Arithmetic

                        <input type="checkbox" class="custom-control-input" id="customSwitch3" name="AR">

Exponents

                        <input type="checkbox" class="custom-control-input" id="customSwitch4" name="EX">

Geometric Solids

                        <input type="checkbox" class="custom-control-input" id="customSwitch5" name="GS">

                <img src="data:image/png;base64,[encoded data, 11644 characters]" class="mr-3" alt="..." width="150" height="150">

Probability

                        <input type="checkbox" class="custom-control-input" id="customSwitch6" name="PR">

Systems of Equations

                        <input type="checkbox" class="custom-control-input" id="customSwitch7" name="SE">

Trig Statements

                        <input type="checkbox" class="custom-control-input" id="customSwitch8" name="TR">

        <button type="submit" class="btn btn-outline-success">Start</button>

</form>

Body:
I made some minor changes

1 _ adding data-page to each checkbox with page url.

2 _ addind ID to the form

document.addEventListener("DOMContentLoaded", function()
{
  const
    MyForm       = document.getElementById('My-Form'),
    all_checkBox = document.querySelectorAll('#My-Form input[type=checkbox]'),
    SubmitBt     = document.querySelector('#My-Form button[type=submit]');

  all_checkBox.forEach(chkBx=>{ chkBx.onchange = ChkBxChanged })

  SubmitBt.disabled = true;

  function ChkBxChanged(e)
  {
    MyForm.action = '';
    SubmitBt.disabled = true;

    if ( this.checked )
    {
      MyForm.action     = this.dataset.page;
      SubmitBt.disabled = false;

      all_checkBox.forEach(cb=>{
        if (cb!=this) cb.checked = false   // only one should be checked
      })
    }
  }
})

<form id="My-Form" action="" method="POST" >

  <h5 class="mt-0">Algebra</h5>
  <input type="checkbox" class="custom-control-input" id="customSwitch1" name="AL" data-page="Algebra.html" >

  <h5 class="mt-0">Area &amp; Perimeter</h5>
  <input type="checkbox" class="custom-control-input" id="customSwitch2" name="AP" data-page="Area_Perimeter.html" >

  <h5 class="mt-0">Arithmetic</h5>
  <input type="checkbox" class="custom-control-input" id="customSwitch3" name="AR" data-page="Arithmetic.html" >

  <h5 class="mt-0">Exponents</h5>
  <input type="checkbox" class="custom-control-input" id="customSwitch4" name="EX" data-page="Exponents.html" >

  <h5 class="mt-0">Geometric Solids</h5>
  <input type="checkbox" class="custom-control-input" id="customSwitch5" name="GS" data-page="Geometric_Solids.html" >

  <h5 class="mt-0">Probability</h5>
  <input type="checkbox" class="custom-control-input" id="customSwitch6" name="PR" data-page="Probability.html" >

  <h5 class="mt-0">Systems of Equations</h5>
  <input type="checkbox" class="custom-control-input" id="customSwitch7" name="SE" data-page="Equations.html" >

  <h5 class="mt-0">Trig Statements</h5>
  <input type="checkbox" class="custom-control-input" id="customSwitch8" name="TR" data-page="Trig_Statements.html" >

  <button type="submit" class="btn btn-outline-success">Start</button>

</form>


问:
How to covert "12:00 PM" into Date object in JavaScript?
```<code>var time = "12:00 PM"
var startTime = Date.parse(time); // output is NaN
alert(startTime);
</code>```

How to convert a string time into time object in JavaScript?

Required output = Thu Aug 14 2014 12:00:00 GMT+0530 (IST)

Because i need to compare startTime with current time...

答:
Cleaning up/consolidating/testing edge cases, of what Phil suggested above:

const militaryTime = (time, date = new Date()) => {
  const parts = time.trim().match(/(\d+):(\d+)\s?((am|AM)|(pm|PM))/)
  const p = {
    hours: parseInt(parts[1]),
    minutes: parseInt(parts[2]),
    period: parts[3].toLowerCase()
  }

  if (p.hours === 12) {
    if (p.period === 'am') {
      date.setHours(p.hours - 12, p.minutes)
    }
    if (p.period === 'pm') {
      date.setHours(p.hours, p.minutes)
    }
  } else {
    if (p.period === 'am') {
      date.setHours(p.hours, p.minutes)
    }
    if (p.period === 'pm') {
      date.setHours(p.hours + 12, p.minutes)
    }
  }

  return date
}

militaryTime('  4:00 am    ') // Thu May 30 2019 04:00:48 GMT-0400 (Eastern Daylight Time)
militaryTime('4:00pm') // Thu May 30 2019 16:00:42 GMT-0400 (Eastern Daylight Time)

militaryTime('12:00am') // Thu May 30 2019 00:00:25 GMT-0400 (Eastern Daylight Time)
militaryTime('12:00pm') // Thu May 30 2019 12:00:46 GMT-0400 (Eastern Daylight Time)
```

Body:
var time = "12:00 PM"
var startTime = Date.parse(time); // output is NaN
alert(startTime);

How to convert a string time into time object in JavaScript?

Required output = Thu Aug 14 2014 12:00:00 GMT+0530 (IST)

Because i need to compare startTime with current time...


问:
How to read black text on black background image through tesseract OCR?
I have black text on black background image and I want to read it through OCR. Unfortunately, OCR can not read it perfectly. The image look like this.
I want to convert RGBA value that less than (90, 90, 90, 255) to (255, 255, 255, 255) so it turn B & W. What's the code to convert it?

答:
What you need to do is make the whole image black and white before letting tesseract do its job.

Read image

```<code>import cv2
im_gray = cv2.imread('your_image_here', cv2.IMREAD_GRAYSCALE)
</code>```

Make it grayscale

```<code>(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
</code>```

"which determines the threshold automatically from the image using Otsu's method, or if you already know the threshold you can use:"

```<code>thresh = 127
im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]
</code>```

Write to disk

```<code>cv2.imwrite('bw_image.png', im_bw)
</code>```

Taken from here

Body:
What you need to do is make the whole image black and white before letting tesseract do its job.

Read image

import cv2
im_gray = cv2.imread('your_image_here', cv2.IMREAD_GRAYSCALE)

Make it grayscale

(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

"which determines the threshold automatically from the image using Otsu's method, or if you already know the threshold you can use:"

thresh = 127
im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]

Write to disk

cv2.imwrite('bw_image.png', im_bw)

Taken from here


问:
Caching Images in Angular
I am having around 300 designs and I am loading all at a time. I would like to cache those images instead of calling server everytime. (My desings won't change most of the time). Below is the code, of how I am loading them. What would be the best approach to cache them.

app-thumbnail is a different component where I am only loading image.

```<code> <div *ngFor="let design of designs">
      <div (click)="showDesignDetails(design.designId)">
          <app-thumbnail [designId]="design.designId"></app-thumbnail>
      </div>
    </div>
</code>```

答:
I can think of two ways:

1) Application Cache Manifest. According to the documentation,

Developers can use the Application Cache (AppCache) interface to
  specify resources that the browser should cache and make available to
  offline users. Applications that are cached load and work correctly
  even if users click the refresh button when they are offline.

2) Service Workers. Through the use of service workers, you can cache various types of resources, including images and network requests.

Though this brings me to the topic of using Progressive Web Applications (PWA). Since you are using Angular, you can easily set it up as a PWA (which is based on the usage of service workers) by following the official Angular guide for setting up service workers.

Title: Caching Images in Angular

Body:
I am having around 300 designs and I am loading all at a time. I would like to cache those images instead of calling server everytime. (My desings won't change most of the time). Below is the code, of how I am loading them. What would be the best approach to cache them.

app-thumbnail is a different component where I am only loading image.

          <app-thumbnail [designId]="design.designId"></app-thumbnail>


问:
AZCopy, see errors and failed transfer info
when using AZCopy to download files, how do I get information about what files failed to transfer, and what the error was? All I get is a message stating how many files failed.

```<code>sudo azcopy \
    --source <url> \
    --destination <path> \
    --source-key <key> \
    --include "<something>" \
    --recursive
</code>```

I did see this post AZCopy Get list of failed transfer files, but the --V parameteter isn't recognized.

I also tried

--verbose < path> \

but it's not recognizing the path parameter, either with or without quotation marks.

答:
I use the AzCopy V10 for my linux and window system. It will gives a log file with all the messages. You can download AzCopy V10 from here: Download AzCopy.

For example, I download all files tb5.text from my Azure Blob storage in  linux, run the azcopy command, I can see all the message from the log file.
My Azcopy command:

```<code>./azcopy copy https://**.blob.core.windows.net/mycontainer/tb5.text /home/leon/azcopy_linux_amd64_10.1.2
</code>```

You can open the log files and get all the info:

I also tried download the file this the error, AzCopy V10 will shows the error directly:

Hope this helps.

Body:
when using AZCopy to download files, how do I get information about what files failed to transfer, and what the error was? All I get is a message stating how many files failed.

sudo azcopy \
    --source <url> \
    --destination <path> \
    --source-key <key> \
    --include "<something>" \
    --recursive

I did see this post AZCopy Get list of failed transfer files, but the --V parameteter isn't recognized.

I also tried

--verbose < path> \

but it's not recognizing the path parameter, either with or without quotation marks.

Body:
I use the AzCopy V10 for my linux and window system. It will gives a log file with all the messages. You can download AzCopy V10 from here: Download AzCopy.

For example, I download all files tb5.text from my Azure Blob storage in  linux, run the azcopy command, I can see all the message from the log file.
My Azcopy command:

./azcopy copy https://**.blob.core.windows.net/mycontainer/tb5.text /home/leon/azcopy_linux_amd64_10.1.2

You can open the log files and get all the info:

I also tried download the file this the error, AzCopy V10 will shows the error directly:

Hope this helps.


问:
How to generate random non-overlapping polygons without free spaces
I need to generate random non-overlapping polygons without free spaces (. They can have any shape.

The only thing I found is an example that uses p5.js to create only non-overlapping circles, but free spaces are present.

Does anyone know how to do it?

// Uses P5.js for canvas creation and drawing
function setup() {
  var circles = [],
      circle = {},
      overlapping = false,
      NumCircles = 4000,
      protection = 1000,
      counter = 0,
      canvasWidth = window.innerWidth,
      canvasHeight = window.innerHeight;

  createCanvas(canvasWidth, canvasHeight);

  // populate circles array
  // brute force method continues until # of circles target is reached
  // or until the protection value is reached
  while (circles.length < NumCircles &&
         counter < protection) {
    circle = {
      x: random(width),
      y: random(height),
      r: random(3, 36)
    };
    overlapping = false;

    // check that it is not overlapping with any existing circle
    // another brute force approach
    for (var i = 0; i < circles.length; i++) {
      var existing = circles[i];
      var d = dist(circle.x, circle.y, existing.x, existing.y)
      if (d < circle.r + existing.r) {
        // They are overlapping
        overlapping = true;
        // do not add to array
        break;
      }
    }

    // add valid circles to array
    if (!overlapping) {
      circles.push(circle);
    }

    counter++;
  }

  // circles array is complete
  // draw canvas once
  background("#233")
  fill("#2AC1A6");
  noStroke();
  for (var i = 0; i < circles.length; i++) {
    ellipse(circles[i].x, circles[i].y,
            circles[i].r*2, circles[i].r*2);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  padding: 0;
  margin: 0;
}</code>```

```

答:
Your question is not very specific...

random non-overlapping polygons without free spaces

Rectangles are polygons, let's make a bunch of those with random sizes and colors

Here is a starting point:

canvas = document.getElementById('c');
ctx = canvas.getContext('2d');

var colors = ["red", "blue", "orange", "green", "yellow"]
h = Math.floor(canvas.height / Math.floor(Math.random() * 15 + 4))

for (y = 0; y < canvas.height; y += h) {
  w = Math.floor(canvas.width / Math.floor(Math.random() * 15 + 4))
  for (x = 0; x < canvas.width; x += w) {
    c = colors[Math.floor(Math.random() * 10) % 5]
    draw(x, y, w, h, c)
  }
}

function draw(x, y, w, h, color) {
  ctx.beginPath();
  ctx.rect(x, y, w, h)
  ctx.stroke();
  ctx.fillStyle = color
  ctx.fill();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="c"></canvas></code>```

Here is a function to help you draw "random" polygons:

var ctx = document.getElementById('c').getContext('2d');

function polygon(sides, size, Xcenter, Ycenter, offset) {
  ctx.beginPath();
  ctx.moveTo(Xcenter + size * Math.cos(offset), Ycenter + size * Math.sin(offset));
  for (var i = 1; i <= sides; i += 1) {
    x = Xcenter + size * Math.cos(i * 2 * Math.PI / sides +offset)
    y = Ycenter + size * Math.sin(i * 2 * Math.PI / sides +offset)
    ctx.lineTo(x, y);
  }
  ctx.stroke();
}

arr = [3, 4, 5, 6, 7];
arr.sort(() => Math.random() - 0.5);
for (var i = 1; i <= 5; i += 1) {
  offset = Math.random() * 5
  polygon(arr[i-1], 40, 85*i, 60, offset)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="c" width=600></canvas></code>```

Body:
I need to generate random non-overlapping polygons without free spaces (. They can have any shape.

The only thing I found is an example that uses p5.js to create only non-overlapping circles, but free spaces are present.

Does anyone know how to do it?

// Uses P5.js for canvas creation and drawing
function setup() {
  var circles = [],
      circle = {},
      overlapping = false,
      NumCircles = 4000,
      protection = 1000,
      counter = 0,
      canvasWidth = window.innerWidth,
      canvasHeight = window.innerHeight;

  createCanvas(canvasWidth, canvasHeight);

  // populate circles array
  // brute force method continues until # of circles target is reached
  // or until the protection value is reached
  while (circles.length < NumCircles &&
         counter < protection) {
    circle = {
      x: random(width),
      y: random(height),
      r: random(3, 36)
    };
    overlapping = false;

    // check that it is not overlapping with any existing circle
    // another brute force approach
    for (var i = 0; i < circles.length; i++) {
      var existing = circles[i];
      var d = dist(circle.x, circle.y, existing.x, existing.y)
      if (d < circle.r + existing.r) {
        // They are overlapping
        overlapping = true;
        // do not add to array
        break;
      }
    }

    // add valid circles to array
    if (!overlapping) {
      circles.push(circle);
    }

    counter++;
  }

  // circles array is complete
  // draw canvas once
  background("#233")
  fill("#2AC1A6");
  noStroke();
  for (var i = 0; i < circles.length; i++) {
    ellipse(circles[i].x, circles[i].y,
            circles[i].r*2, circles[i].r*2);
  }
}

* {
  padding: 0;
  margin: 0;
}

Body:
Your question is not very specific...

random non-overlapping polygons without free spaces

Rectangles are polygons, let's make a bunch of those with random sizes and colors

Here is a starting point:

canvas = document.getElementById('c');
ctx = canvas.getContext('2d');

var colors = ["red", "blue", "orange", "green", "yellow"]
h = Math.floor(canvas.height / Math.floor(Math.random() * 15 + 4))

for (y = 0; y < canvas.height; y += h) {
  w = Math.floor(canvas.width / Math.floor(Math.random() * 15 + 4))
  for (x = 0; x < canvas.width; x += w) {
    c = colors[Math.floor(Math.random() * 10) % 5]
    draw(x, y, w, h, c)
  }
}

function draw(x, y, w, h, color) {
  ctx.beginPath();
  ctx.rect(x, y, w, h)
  ctx.stroke();
  ctx.fillStyle = color
  ctx.fill();
}

<canvas id="c"></canvas>

Here is a function to help you draw "random" polygons:

var ctx = document.getElementById('c').getContext('2d');

function polygon(sides, size, Xcenter, Ycenter, offset) {
  ctx.beginPath();
  ctx.moveTo(Xcenter + size * Math.cos(offset), Ycenter + size * Math.sin(offset));
  for (var i = 1; i <= sides; i += 1) {
    x = Xcenter + size * Math.cos(i * 2 * Math.PI / sides +offset)
    y = Ycenter + size * Math.sin(i * 2 * Math.PI / sides +offset)
    ctx.lineTo(x, y);
  }
  ctx.stroke();
}

arr = [3, 4, 5, 6, 7];
arr.sort(() => Math.random() - 0.5);
for (var i = 1; i <= 5; i += 1) {
  offset = Math.random() * 5
  polygon(arr[i-1], 40, 85*i, 60, offset)
}

<canvas id="c" width=600></canvas>


问:
My input is not working in React, onChange looks good too
My input element doesn't let me type into it, it will show up, with the value i want, but I cannot delete or edit anything in the input. Everything is spelled correctly from what I have seen.

I've been googling and have searched multiple SO forms, none have been able to help me. Which is why I am asking now

```<code>const GuestName =(props)=>{
    if(props.isEditing){
        return(
        <form>
        <input type='text' className='edit-guest-input'
         value={props.guestName} onChange={e => props.editGuest(e.target.value)}/>
         </form>
        )
    }

    return (
    <span>{props.guestName}</span>
    )
}
</code>```

the above is the input that will not work

```<code>  editGuest=(id, name)=>{
    this.setState({
      guest: this.state.guest.map((guest) =>{
        if(id===guest.id){
          return{
            ...guest,
            name
          }}
          return guest
      })
    })
  }
</code>```

this is the code for the onChange event.

```<code>const GuestList =(props)=>

    <div>

        <ul>
            {props.guest.filter( guest => !props.filterUnconfirmedGuest || guest.isConfirmed)
            .map((guest, index) =>   <Guest
                            key={index}
                            guestName={guest.guestName}
                            toggleGuestConfirmed={props.toggleGuestConfirmed}
                            isConfirmed={guest.isConfirmed}
                            toggleEditGuest={()=> props.toggleEditGuest(guest.id)}
                            isEditing={guest.isEditing}
                            editGuest={editedName=> props.editGuest(editedName, guest.id)}
                            removeGuest={()=> props.removeGuest(guest.id)}
                                />)}
       </ul>
    </div>
</code>```

The first argument is passed in here

Probably a minor issue that I am too tired to notice lol. Any help is appreciated, thank you for your time!

答: I think in editGuest it should be  guestName: name :)

Body:
My input element doesn't let me type into it, it will show up, with the value i want, but I cannot delete or edit anything in the input. Everything is spelled correctly from what I have seen.

I've been googling and have searched multiple SO forms, none have been able to help me. Which is why I am asking now

const GuestName =(props)=>{
    if(props.isEditing){
        return(
        <form>
        <input type='text' className='edit-guest-input'
         value={props.guestName} onChange={e => props.editGuest(e.target.value)}/>
         </form>
        )
    }

    return (
    {props.guestName}
    )
}

the above is the input that will not work

  editGuest=(id, name)=>{
    this.setState({
      guest: this.state.guest.map((guest) =>{
        if(id===guest.id){
          return{
            ...guest,
            name
          }}
          return guest
      })
    })
  }

this is the code for the onChange event.

const GuestList =(props)=>

            {props.guest.filter( guest => !props.filterUnconfirmedGuest || guest.isConfirmed)
            .map((guest, index) =>   <Guest
                            key={index}
                            guestName={guest.guestName}
                            toggleGuestConfirmed={props.toggleGuestConfirmed}
                            isConfirmed={guest.isConfirmed}
                            toggleEditGuest={()=> props.toggleEditGuest(guest.id)}
                            isEditing={guest.isEditing}
                            editGuest={editedName=> props.editGuest(editedName, guest.id)}
                            removeGuest={()=> props.removeGuest(guest.id)}
                                />)}

The first argument is passed in here

Probably a minor issue that I am too tired to notice lol. Any help is appreciated, thank you for your time!


问:
Cocoa: Mount SMB folder with FSMountServerVolumeSync
Could someone post a snippet on the correct syntax for using this? Thanks. </p>

ContentLicense: CC BY-SA 2.5


问:
How do I generate a predictable random stream in hierarchy in c#?
I am making a procedural game with hierarchy.

So object A will have 10 children.

Each child will have 10 children and so on.

Now suppose I want to give each child a random colour, and a random position (assume these are given by integers).

Therefor let X be the "ID" of an object.

Let COLOUR and POSITION be enums of type PROPERTY.

Then I want to generate random integers:

```<code>int GenerateRandomInteger(PROPERTY P, int childNumber);
</code>```

So I can use:

```<code>int N = parentObject.GenerateRandomInteger(COLOUR, 7);
</code>```

For example.

Any ideas how to go about this?

答:
In this case, GetRandomInteger should be implemented as a hash function. A hash function takes arbitrary data (here, the values of P and childNumber) and outputs a hash code. For the purposes of a game:

The hash function should have the avalanche property, meaning that every bit of the input affects every bit of the hash code.

Good hash functions here include MurmurHash3 and xxHash.

This answer also assumes that childNumber is unique throughout the application, rather than unique for a given parent.

The resulting hash code can then be used to generate a pseudorandom color and a position (for example, the first 24 bits of the hash code can be extracted and treated as a 8-bit-per-component RGB color). But further details on how this will work will depend on what programming language you're using and what ranges are acceptable for colors and positions, which you didn't specify in your question (there are several languages that use ints and enums, for example).

Body:
I am making a procedural game with hierarchy.

So object A will have 10 children.

Each child will have 10 children and so on.

Now suppose I want to give each child a random colour, and a random position (assume these are given by integers).

Therefor let X be the "ID" of an object.

Let COLOUR and POSITION be enums of type PROPERTY.

Then I want to generate random integers:

int GenerateRandomInteger(PROPERTY P, int childNumber);

So I can use:

int N = parentObject.GenerateRandomInteger(COLOUR, 7);

For example.

Any ideas how to go about this?


问:
How to find if a youtube channel is currently live streaming without using search?
I'm working on a website to load multiple youtube channels live streams. At first i was trying to figure out a way to do this without utilizing youtube's api but have decided to give in.

To find whether a channel is live streaming and to get the live stream links I've been using:

```<code>https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={CHANNEL_ID}&eventType=live&maxResults=10&type=video&key={API_KEY}
</code>```

However with the minimum quota being 10000 and each search being worth 100, Im only able to do about 100 searches before I exceed my quota limit which doesn't help at all. I ended up exceeding the quota limit in about 10 minutes. :(

Does anyone know of a better way to figure out if a channel is currently live streaming and what the live stream links are, using as minimal quota points as possible?

I want to reload youtube data for each user every 3 minutes, save it into a database, and display the information using my own api to save server resources as well as quota points.

Hopefully someone has a good solution to this problem!

If nothing can be done about links just determining if the user is live without using 100 quota points each time would be a big help.

答:
Since the question only specified that Search API quotas should not be used in finding out if the channel is streaming, I thought I would share a sort of work-around method. It might require a bit more work than a simple API call, but it reduces API quota use to practically nothing:

I used a simple Perl GET request to retrieve a Youtube channel's main page. Several unique elements are found in the HTML of a channel page that is streaming live:

The number of live viewers tag, e.g.
753 watching
. The LIVE NOW
badge tag: Live now.

To ascertain whether a channel is currently streaming live requires a simple match to see if the unique HTML tag is contained in the GET request results. Something like: if ($get_results =~ /$unique_html/) (Perl). Then, an API call can be made only to a channel ID that is actually streaming, in order to obtain the video ID of the stream.

The advantage of this is that you already know the channel is streaming, instead of using thousands of quota points to find out. My test script successfully identifies whether a channel is streaming, by looking in the HTML code for:  (note the weird extra spaces in the code from Youtube).

I don't know what language OP is using, or I would help with a basic GET request in that language. I used Perl, and included browser headers, User Agent and cookies, to look like a normal computer visit.

Youtube's robots.txt doesn't seem to forbid crawling a channel's main page, only the community page of a channel.

Let me know what you think about the pros and cons of this method, and please comment with what might be improved rather than disliking if you find a flaw. Thanks, happy coding!

2020 UPDATE
The yt-badge-live seems to have been deprecated, it no longer reliably shows whether the channel is streaming. Instead, I now check the HTML for this string:

{"text":" watching"}

If I get a match, it means the page is streaming. (Non-streaming channels don't contain this string.) Again, note the weird extra whitespace. I also escape all the quotation marks since I'm using Perl.

Body:
I'm working on a website to load multiple youtube channels live streams. At first i was trying to figure out a way to do this without utilizing youtube's api but have decided to give in.

To find whether a channel is live streaming and to get the live stream links I've been using:

https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={CHANNEL_ID}&eventType=live&maxResults=10&type=video&key={API_KEY}

However with the minimum quota being 10000 and each search being worth 100, Im only able to do about 100 searches before I exceed my quota limit which doesn't help at all. I ended up exceeding the quota limit in about 10 minutes. :(

Does anyone know of a better way to figure out if a channel is currently live streaming and what the live stream links are, using as minimal quota points as possible?

I want to reload youtube data for each user every 3 minutes, save it into a database, and display the information using my own api to save server resources as well as quota points.

Hopefully someone has a good solution to this problem!

If nothing can be done about links just determining if the user is live without using 100 quota points each time would be a big help.

Body:
Since the question only specified that Search API quotas should not be used in finding out if the channel is streaming, I thought I would share a sort of work-around method. It might require a bit more work than a simple API call, but it reduces API quota use to practically nothing:

I used a simple Perl GET request to retrieve a Youtube channel's main page. Several unique elements are found in the HTML of a channel page that is streaming live:

The number of live viewers tag, e.g. <li>753 watching</li>. The LIVE NOW
badge tag: <span class="yt-badge  yt-badge-live" >Live now</span>.

To ascertain whether a channel is currently streaming live requires a simple match to see if the unique HTML tag is contained in the GET request results. Something like: if ($get_results =~ /$unique_html/) (Perl). Then, an API call can be made only to a channel ID that is actually streaming, in order to obtain the video ID of the stream.

The advantage of this is that you already know the channel is streaming, instead of using thousands of quota points to find out. My test script successfully identifies whether a channel is streaming, by looking in the HTML code for: <span class="yt-badge  yt-badge-live" > (note the weird extra spaces in the code from Youtube).

I don't know what language OP is using, or I would help with a basic GET request in that language. I used Perl, and included browser headers, User Agent and cookies, to look like a normal computer visit.

Youtube's robots.txt doesn't seem to forbid crawling a channel's main page, only the community page of a channel.

Let me know what you think about the pros and cons of this method, and please comment with what might be improved rather than disliking if you find a flaw. Thanks, happy coding!

2020 UPDATE
The yt-badge-live seems to have been deprecated, it no longer reliably shows whether the channel is streaming. Instead, I now check the HTML for this string:

{"text":" watching"}

If I get a match, it means the page is streaming. (Non-streaming channels don't contain this string.) Again, note the weird extra whitespace. I also escape all the quotation marks since I'm using Perl.


问:
How to compile OpenVINO-Code in OpenFOAM?
I am currently using OpenVINO's inference engine for Deep Learning Inference in the field of Computational Fluid Dynamics. The CFD-software I am using is OpenFOAM, it does not support CMake, instead the user must use so called wmake.

In order to compile code for a Third Party software like OpenVINO I have to provide all required header files and libraries for the compilation. However I am not sure how to find out all those reqired by OpenVINO's inference engine.

Can somebody explain me how to find out the correct headers to include and libraries to link?

Thanks in advance!

答:
To compile project with OpenVino you would need

Includes: OV_LOCATION\deployment_tools\inference_engine\include

Libraries: OV_LOCATION\deployment_tools\inference_engine\lib

To run on CPU, from OV_LOCATION\deployment_tools\inference_engine\bin you would need: inference_engine, mkl_tiny_tbb, MKLDNNPlugin, tbb shared libraries.


问:
error accessing Kafka Cluster that is secured through SASL PLAINTEXT using KafkaTool
So I have secured a kafka cluster through below security mechanism in server.properties and added respective kafka and zookeeper jaas.config files

```<code>security.inter.broker.protocol=SASL_PLAINTEXT
sasl.mechanism.inter.broker.protocol=PLAIN
</code>```

and using below command to start the kafka tool

kafkatool -J -Djava.security.auth.login.config=client_jaas.config

where client_jaas.config consists of below content

```<code>sasl.mechanism=PLAIN
# Configure SASL_SSL if SSL encryption is enabled, otherwise configure SASL_PLAINTEXT
security.protocol=SASL_PLAINTEXT

sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required \
  username="admin" \
  password="password";
</code>```

Kafkatool gets launched successfully cluster is being connected but when click on topic  to see list of all the topic it gives me below error

Configured to use PLAINTTEXT but broker 0 does not support it.

Below is the content of the server_jaas.config file

```<code>KafkaServer {
  org.apache.kafka.common.security.plain.PlainLoginModule required
  username="admin"
  password="password"
  user_admin="password";
};

Client {
  org.apache.kafka.common.security.plain.PlainLoginModule required
  username="admin"
  password="password";
};
</code>```

Below are the listeners details in the server.properties file

```<code>listeners=SASL_PLAINTEXT://0.0.0.0:9092
advertised.listeners=SASL_PLAINTEXT://:9092
</code>```

If I see the full error log of kafaktool, of the output of command kafkatool -J-Djava.security.auth.login.config=client_jaas.config, below is what I see

```<code>01/Jun/2019 13:40:30.436 INFO  com.kafkatool.ui.MainApp - Starting application : Kafka Tool
01/Jun/2019 13:40:30.437 INFO  com.kafkatool.ui.MainApp - Version : 2.0.4
01/Jun/2019 13:40:30.437 INFO  com.kafkatool.ui.MainApp - Built : Feb 21, 2019
01/Jun/2019 13:40:30.438 INFO  com.kafkatool.ui.MainApp - user.home : /home/vivek
01/Jun/2019 13:40:30.438 INFO  com.kafkatool.ui.MainApp - user.dir : /opt/kafkatool2
01/Jun/2019 13:40:30.438 INFO  com.kafkatool.ui.MainApp - os.name : Linux
01/Jun/2019 13:40:30.438 INFO  com.kafkatool.ui.MainApp - java.runtime.version : 1.8.0_191-8u191-b12-2ubuntu0.18.04.1-b12
01/Jun/2019 13:40:30.439 INFO  com.kafkatool.ui.MainApp - max memory=1305 MB
01/Jun/2019 13:40:30.439 INFO  com.kafkatool.ui.MainApp - available processors=4
01/Jun/2019 13:40:30.440 INFO  com.kafkatool.ui.MainApp - java.security.auth.login.config=client_jaas.config
01/Jun/2019 13:40:30.443 INFO  com.kafkatool.ui.MainApp - java.security.auth.login.config exists = false
01/Jun/2019 13:40:30.449 INFO  com.kafkatool.common.ExternalDecoderManager - Finding plugins in directory /opt/kafkatool2/plugins
01/Jun/2019 13:40:30.449 INFO  com.kafkatool.common.ExternalDecoderManager - Found files in plugin directory, count=1
01/Jun/2019 13:40:30.450 INFO  com.kafkatool.ui.MainApp - Loading user settings
01/Jun/2019 13:40:30.497 INFO  com.kafkatool.ui.MainApp - Loading server group settings
01/Jun/2019 13:40:30.500 INFO  com.kafkatool.ui.MainApp - Loading server connection settings
01/Jun/2019 13:40:39.854 INFO  org.I0Itec.zkclient.ZkEventThread - Starting ZkClient event thread.
01/Jun/2019 13:40:39.862 INFO  org.apache.zookeeper.ZooKeeper - Client environment:zookeeper.version=3.3.3-1203054, built on 11/17/2011 05:47 GMT
01/Jun/2019 13:40:39.862 INFO  org.apache.zookeeper.ZooKeeper - Client environment:host.name=anakata
01/Jun/2019 13:40:39.863 INFO  org.apache.zookeeper.ZooKeeper - Client environment:java.version=1.8.0_191
01/Jun/2019 13:40:39.863 INFO  org.apache.zookeeper.ZooKeeper - Client environment:java.vendor=Oracle Corporation
01/Jun/2019 13:40:39.863 INFO  org.apache.zookeeper.ZooKeeper - Client environment:java.home=/usr/lib/jvm/java-8-openjdk-amd64/jre
01/Jun/2019 13:40:39.863 INFO  org.apache.zookeeper.ZooKeeper - Client environment:java.class.path=/opt/kafkatool2/.install4j/i4jruntime.jar:/opt/kafkatool2/lib/glazedlists.jar:/opt/kafkatool2/lib/gson-2.3.1.jar:/opt/kafkatool2/lib/jgoodies-common-1.6.0.jar:/opt/kafkatool2/lib/jgoodies-looks-2.5.3.jar:/opt/kafkatool2/lib/jide-oss.jar:/opt/kafkatool2/lib/jline.jar:/opt/kafkatool2/lib/jopt-simple.jar:/opt/kafkatool2/lib/kafka-clients.jar:/opt/kafkatool2/lib/kafka.jar:/opt/kafkatool2/lib/log4j.jar:/opt/kafkatool2/lib/lz4.jar:/opt/kafkatool2/lib/metrics-core.jar:/opt/kafkatool2/lib/netty.jar:/opt/kafkatool2/lib/ofjar.jar:/opt/kafkatool2/lib/quaqua.jar:/opt/kafkatool2/lib/scala-library.jar:/opt/kafkatool2/lib/scala-parser-combinators.jar:/opt/kafkatool2/lib/scala-xml.jar:/opt/kafkatool2/lib/slf4j-api.jar:/opt/kafkatool2/lib/slf4j-log4j12.jar:/opt/kafkatool2/lib/snappy.jar:/opt/kafkatool2/lib/zkclient.jar:/opt/kafkatool2/lib/zookeeper.jar
01/Jun/2019 13:40:39.864 INFO  org.apache.zookeeper.ZooKeeper - Client environment:java.library.path=/usr/java/packages/lib/amd64:/usr/lib/x86_64-linux-gnu/jni:/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu:/usr/lib/jni:/lib:/usr/lib
01/Jun/2019 13:40:39.864 INFO  org.apache.zookeeper.ZooKeeper - Client environment:java.io.tmpdir=/tmp
01/Jun/2019 13:40:39.864 INFO  org.apache.zookeeper.ZooKeeper - Client environment:java.compiler=<NA>
01/Jun/2019 13:40:39.864 INFO  org.apache.zookeeper.ZooKeeper - Client environment:os.name=Linux
01/Jun/2019 13:40:39.865 INFO  org.apache.zookeeper.ZooKeeper - Client environment:os.arch=amd64
01/Jun/2019 13:40:39.865 INFO  org.apache.zookeeper.ZooKeeper - Client environment:os.version=4.15.0-48-generic
01/Jun/2019 13:40:39.865 INFO  org.apache.zookeeper.ZooKeeper - Client environment:user.name=vivek
01/Jun/2019 13:40:39.866 INFO  org.apache.zookeeper.ZooKeeper - Client environment:user.home=/home/vivek
01/Jun/2019 13:40:39.882 INFO  org.apache.zookeeper.ZooKeeper - Client environment:user.dir=/opt/kafkatool2
01/Jun/2019 13:40:39.884 INFO  org.apache.zookeeper.ZooKeeper - Initiating client connection, connectString=localhost:2181 sessionTimeout=30000 watcher=org.I0Itec.zkclient.ZkClient@60b5eeff
01/Jun/2019 13:40:39.917 INFO  org.apache.zookeeper.ClientCnxn - Opening socket connection to server localhost/127.0.0.1:2181
01/Jun/2019 13:40:39.927 INFO  org.apache.zookeeper.ClientCnxn - Socket connection established to localhost/127.0.0.1:2181, initiating session
01/Jun/2019 13:40:39.947 INFO  org.apache.zookeeper.ClientCnxn - Session establishment complete on server localhost/127.0.0.1:2181, sessionid = 0x100097569c60010, negotiated timeout = 30000
01/Jun/2019 13:40:39.949 INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (SyncConnected)
01/Jun/2019 13:40:40.024 INFO  com.kafkatool.model.Broker - Parsing endpoint SASL_PLAINTEXT://anakata:9092
01/Jun/2019 13:40:40.025 INFO  com.kafkatool.model.KafkaMapper - Getting brokers from zookeeper, found 1
01/Jun/2019 13:40:40.025 INFO  org.I0Itec.zkclient.ZkEventThread - Terminate ZkClient event thread.
01/Jun/2019 13:40:40.044 INFO  org.apache.zookeeper.ZooKeeper - Session: 0x100097569c60010 closed
01/Jun/2019 13:40:40.044 INFO  org.apache.zookeeper.ClientCnxn - EventThread shut down
01/Jun/2019 13:40:40.046 ERROR com.kafkatool.model.Broker - Configured to use PLAINTEXT but broker 0 does not support it. Configured types {SASL_PLAINTEXT=BrokerEndpoint{protocol='SASL_PLAINTEXT', host='anakata', port=9092}}
01/Jun/2019 13:40:40.048 ERROR com.kafkatool.model.KafkaMapper - Error getting topics
java.lang.Exception: Configured to use PLAINTEXT but broker 0 does not support it.
    at com.kafkatool.model.Broker.getSecurityTypeConnectString(Broker.java:169)
    at com.kafkatool.model.KafkaMapper.getProperties(KafkaMapper.java:258)
    at com.kafkatool.model.KafkaMapper.getNewConsumer(KafkaMapper.java:1100)
    at com.kafkatool.model.KafkaMapper.getNewConsumer(KafkaMapper.java:1095)
    at com.kafkatool.model.KafkaMapper.getNewConsumer(KafkaMapper.java:1085)
    at com.kafkatool.model.KafkaMapper.getTopics(KafkaMapper.java:420)
    at com.kafkatool.model.ServerConnection.getTopics(ServerConnection.java:221)
    at com.kafkatool.model.ServerConnection.hasTopic(ServerConnection.java:203)
    at com.kafkatool.model.KafkaMapper.startPoller(KafkaMapper.java:105)
    at com.kafkatool.model.ServerConnection.connectInt(ServerConnection.java:336)
    at com.kafkatool.model.ServerConnection.connect(ServerConnection.java:315)
    at com.kafkatool.common.AsyncServerConnector.run(AsyncServerConnector.java:43)
    at java.lang.Thread.run(Thread.java:748)
01/Jun/2019 13:40:40.052 ERROR com.kafkatool.model.KafkaMapper - Error starting consumer offset poller
java.lang.Exception: Configured to use PLAINTEXT but broker 0 does not support it.
    at com.kafkatool.model.Broker.getSecurityTypeConnectString(Broker.java:169)
    at com.kafkatool.model.KafkaMapper.getProperties(KafkaMapper.java:258)
    at com.kafkatool.model.KafkaMapper.getNewConsumer(KafkaMapper.java:1100)
    at com.kafkatool.model.KafkaMapper.getNewConsumer(KafkaMapper.java:1095)
    at com.kafkatool.model.KafkaMapper.getNewConsumer(KafkaMapper.java:1085)
    at com.kafkatool.model.KafkaMapper.getTopics(KafkaMapper.java:420)
    at com.kafkatool.model.ServerConnection.getTopics(ServerConnection.java:221)
    at com.kafkatool.model.ServerConnection.hasTopic(ServerConnection.java:203)
    at com.kafkatool.model.KafkaMapper.startPoller(KafkaMapper.java:105)
    at com.kafkatool.model.ServerConnection.connectInt(ServerConnection.java:336)
    at com.kafkatool.model.ServerConnection.connect(ServerConnection.java:315)
    at com.kafkatool.common.AsyncServerConnector.run(AsyncServerConnector.java:43)

</code>```

答:
The comment line in your client_jaas.config does actually contain a clue on this:

Configure SASL_SSL if SSL encryption is enabled, otherwise configure SASL_PLAINTEXT

There seems to be a conflict in the 2 config settings you've provided.

In server.properties, you've mentioned:

security.inter.broker.protocol=SASL_PLAINTEXT

whereas in your client_jaas.config, you've mentioned:

security.protocol=SASL_SSL

Try changing this to SASL_PLAINTEXT.

Hope this helps!

Body:
So I have secured a kafka cluster through below security mechanism in server.properties and added respective kafka and zookeeper jaas.config files

security.inter.broker.protocol=SASL_PLAINTEXT
sasl.mechanism.inter.broker.protocol=PLAIN

and using below command to start the kafka tool

kafkatool -J -Djava.security.auth.login.config=client_jaas.config

where client_jaas.config consists of below content

sasl.mechanism=PLAIN
# Configure SASL_SSL if SSL encryption is enabled, otherwise configure SASL_PLAINTEXT
security.protocol=SASL_PLAINTEXT

sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required \
  username="admin" \
  password="password";

Kafkatool gets launched successfully cluster is being connected but when click on topic  to see list of all the topic it gives me below error

Configured to use PLAINTTEXT but broker 0 does not support it.

Below is the content of the server_jaas.config file

KafkaServer {
  org.apache.kafka.common.security.plain.PlainLoginModule required
  username="admin"
  password="password"
  user_admin="password";
};

Client {
  org.apache.kafka.common.security.plain.PlainLoginModule required
  username="admin"
  password="password";
};

Below are the listeners details in the server.properties file

listeners=SASL_PLAINTEXT://0.0.0.0:9092
advertised.listeners=SASL_PLAINTEXT://:9092

If I see the full error log of kafaktool, of the output of command kafkatool -J-Djava.security.auth.login.config=client_jaas.config, below is what I see

01/Jun/2019 13:40:30.436 INFO  com.kafkatool.ui.MainApp - Starting application : Kafka Tool
01/Jun/2019 13:40:30.437 INFO  com.kafkatool.ui.MainApp - Version : 2.0.4
01/Jun/2019 13:40:30.437 INFO  com.kafkatool.ui.MainApp - Built : Feb 21, 2019
01/Jun/2019 13:40:30.438 INFO  com.kafkatool.ui.MainApp - user.home : /home/vivek
01/Jun/2019 13:40:30.438 INFO  com.kafkatool.ui.MainApp - user.dir : /opt/kafkatool2
01/Jun/2019 13:40:30.438 INFO  com.kafkatool.ui.MainApp - os.name : Linux
01/Jun/2019 13:40:30.438 INFO  com.kafkatool.ui.MainApp - java.runtime.version : 1.8.0_191-8u191-b12-2ubuntu0.18.04.1-b12
01/Jun/2019 13:40:30.439 INFO  com.kafkatool.ui.MainApp - max memory=1305 MB
01/Jun/2019 13:40:30.439 INFO  com.kafkatool.ui.MainApp - available processors=4
01/Jun/2019 13:40:30.440 INFO  com.kafkatool.ui.MainApp - java.security.auth.login.config=client_jaas.config
01/Jun/2019 13:40:30.443 INFO  com.kafkatool.ui.MainApp - java.security.auth.login.config exists = false
01/Jun/2019 13:40:30.449 INFO  com.kafkatool.common.ExternalDecoderManager - Finding plugins in directory /opt/kafkatool2/plugins
01/Jun/2019 13:40:30.449 INFO  com.kafkatool.common.ExternalDecoderManager - Found files in plugin directory, count=1
01/Jun/2019 13:40:30.450 INFO  com.kafkatool.ui.MainApp - Loading user settings
01/Jun/2019 13:40:30.497 INFO  com.kafkatool.ui.MainApp - Loading server group settings
01/Jun/2019 13:40:30.500 INFO  com.kafkatool.ui.MainApp - Loading server connection settings
01/Jun/2019 13:40:39.854 INFO  org.I0Itec.zkclient.ZkEventThread - Starting ZkClient event thread.
01/Jun/2019 13:40:39.862 INFO  org.apache.zookeeper.ZooKeeper - Client environment:zookeeper.version=3.3.3-1203054, built on 11/17/2011 05:47 GMT
01/Jun/2019 13:40:39.862 INFO  org.apache.zookeeper.ZooKeeper - Client environment:host.name=anakata
01/Jun/2019 13:40:39.863 INFO  org.apache.zookeeper.ZooKeeper - Client environment:java.version=1.8.0_191
01/Jun/2019 13:40:39.863 INFO  org.apache.zookeeper.ZooKeeper - Client environment:java.vendor=Oracle Corporation
01/Jun/2019 13:40:39.863 INFO  org.apache.zookeeper.ZooKeeper - Client environment:java.home=/usr/lib/jvm/java-8-openjdk-amd64/jre
01/Jun/2019 13:40:39.863 INFO  org.apache.zookeeper.ZooKeeper - Client environment:java.class.path=/opt/kafkatool2/.install4j/i4jruntime.jar:/opt/kafkatool2/lib/glazedlists.jar:/opt/kafkatool2/lib/gson-2.3.1.jar:/opt/kafkatool2/lib/jgoodies-common-1.6.0.jar:/opt/kafkatool2/lib/jgoodies-looks-2.5.3.jar:/opt/kafkatool2/lib/jide-oss.jar:/opt/kafkatool2/lib/jline.jar:/opt/kafkatool2/lib/jopt-simple.jar:/opt/kafkatool2/lib/kafka-clients.jar:/opt/kafkatool2/lib/kafka.jar:/opt/kafkatool2/lib/log4j.jar:/opt/kafkatool2/lib/lz4.jar:/opt/kafkatool2/lib/metrics-core.jar:/opt/kafkatool2/lib/netty.jar:/opt/kafkatool2/lib/ofjar.jar:/opt/kafkatool2/lib/quaqua.jar:/opt/kafkatool2/lib/scala-library.jar:/opt/kafkatool2/lib/scala-parser-combinators.jar:/opt/kafkatool2/lib/scala-xml.jar:/opt/kafkatool2/lib/slf4j-api.jar:/opt/kafkatool2/lib/slf4j-log4j12.jar:/opt/kafkatool2/lib/snappy.jar:/opt/kafkatool2/lib/zkclient.jar:/opt/kafkatool2/lib/zookeeper.jar
01/Jun/2019 13:40:39.864 INFO  org.apache.zookeeper.ZooKeeper - Client environment:java.library.path=/usr/java/packages/lib/amd64:/usr/lib/x86_64-linux-gnu/jni:/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu:/usr/lib/jni:/lib:/usr/lib
01/Jun/2019 13:40:39.864 INFO  org.apache.zookeeper.ZooKeeper - Client environment:java.io.tmpdir=/tmp
01/Jun/2019 13:40:39.864 INFO  org.apache.zookeeper.ZooKeeper - Client environment:java.compiler=<NA>
01/Jun/2019 13:40:39.864 INFO  org.apache.zookeeper.ZooKeeper - Client environment:os.name=Linux
01/Jun/2019 13:40:39.865 INFO  org.apache.zookeeper.ZooKeeper - Client environment:os.arch=amd64
01/Jun/2019 13:40:39.865 INFO  org.apache.zookeeper.ZooKeeper - Client environment:os.version=4.15.0-48-generic
01/Jun/2019 13:40:39.865 INFO  org.apache.zookeeper.ZooKeeper - Client environment:user.name=vivek
01/Jun/2019 13:40:39.866 INFO  org.apache.zookeeper.ZooKeeper - Client environment:user.home=/home/vivek
01/Jun/2019 13:40:39.882 INFO  org.apache.zookeeper.ZooKeeper - Client environment:user.dir=/opt/kafkatool2
01/Jun/2019 13:40:39.884 INFO  org.apache.zookeeper.ZooKeeper - Initiating client connection, connectString=localhost:2181 sessionTimeout=30000 watcher=org.I0Itec.zkclient.ZkClient@60b5eeff
01/Jun/2019 13:40:39.917 INFO  org.apache.zookeeper.ClientCnxn - Opening socket connection to server localhost/127.0.0.1:2181
01/Jun/2019 13:40:39.927 INFO  org.apache.zookeeper.ClientCnxn - Socket connection established to localhost/127.0.0.1:2181, initiating session
01/Jun/2019 13:40:39.947 INFO  org.apache.zookeeper.ClientCnxn - Session establishment complete on server localhost/127.0.0.1:2181, sessionid = 0x100097569c60010, negotiated timeout = 30000
01/Jun/2019 13:40:39.949 INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (SyncConnected)
01/Jun/2019 13:40:40.024 INFO  com.kafkatool.model.Broker - Parsing endpoint SASL_PLAINTEXT://anakata:9092
01/Jun/2019 13:40:40.025 INFO  com.kafkatool.model.KafkaMapper - Getting brokers from zookeeper, found 1
01/Jun/2019 13:40:40.025 INFO  org.I0Itec.zkclient.ZkEventThread - Terminate ZkClient event thread.
01/Jun/2019 13:40:40.044 INFO  org.apache.zookeeper.ZooKeeper - Session: 0x100097569c60010 closed
01/Jun/2019 13:40:40.044 INFO  org.apache.zookeeper.ClientCnxn - EventThread shut down
01/Jun/2019 13:40:40.046 ERROR com.kafkatool.model.Broker - Configured to use PLAINTEXT but broker 0 does not support it. Configured types {SASL_PLAINTEXT=BrokerEndpoint{protocol='SASL_PLAINTEXT', host='anakata', port=9092}}
01/Jun/2019 13:40:40.048 ERROR com.kafkatool.model.KafkaMapper - Error getting topics
java.lang.Exception: Configured to use PLAINTEXT but broker 0 does not support it.
    at com.kafkatool.model.Broker.getSecurityTypeConnectString(Broker.java:169)
    at com.kafkatool.model.KafkaMapper.getProperties(KafkaMapper.java:258)
    at com.kafkatool.model.KafkaMapper.getNewConsumer(KafkaMapper.java:1100)
    at com.kafkatool.model.KafkaMapper.getNewConsumer(KafkaMapper.java:1095)
    at com.kafkatool.model.KafkaMapper.getNewConsumer(KafkaMapper.java:1085)
    at com.kafkatool.model.KafkaMapper.getTopics(KafkaMapper.java:420)
    at com.kafkatool.model.ServerConnection.getTopics(ServerConnection.java:221)
    at com.kafkatool.model.ServerConnection.hasTopic(ServerConnection.java:203)
    at com.kafkatool.model.KafkaMapper.startPoller(KafkaMapper.java:105)
    at com.kafkatool.model.ServerConnection.connectInt(ServerConnection.java:336)
    at com.kafkatool.model.ServerConnection.connect(ServerConnection.java:315)
    at com.kafkatool.common.AsyncServerConnector.run(AsyncServerConnector.java:43)
    at java.lang.Thread.run(Thread.java:748)
01/Jun/2019 13:40:40.052 ERROR com.kafkatool.model.KafkaMapper - Error starting consumer offset poller
java.lang.Exception: Configured to use PLAINTEXT but broker 0 does not support it.
    at com.kafkatool.model.Broker.getSecurityTypeConnectString(Broker.java:169)
    at com.kafkatool.model.KafkaMapper.getProperties(KafkaMapper.java:258)
    at com.kafkatool.model.KafkaMapper.getNewConsumer(KafkaMapper.java:1100)
    at com.kafkatool.model.KafkaMapper.getNewConsumer(KafkaMapper.java:1095)
    at com.kafkatool.model.KafkaMapper.getNewConsumer(KafkaMapper.java:1085)
    at com.kafkatool.model.KafkaMapper.getTopics(KafkaMapper.java:420)
    at com.kafkatool.model.ServerConnection.getTopics(ServerConnection.java:221)
    at com.kafkatool.model.ServerConnection.hasTopic(ServerConnection.java:203)
    at com.kafkatool.model.KafkaMapper.startPoller(KafkaMapper.java:105)
    at com.kafkatool.model.ServerConnection.connectInt(ServerConnection.java:336)
    at com.kafkatool.model.ServerConnection.connect(ServerConnection.java:315)
    at com.kafkatool.common.AsyncServerConnector.run(AsyncServerConnector.java:43)


问:
How to generate sample data based of weighted base values
Using SQL, I need to generate some sample data of N rows based off some base values which have assigned weights.

For example: if my base values and their corresponding weights are:

a-1,

b-2,

c-3,

d-4,

e-5

And if the sample size required is 15, then the rowset returned should have:

5 rows of e,

4 rows of d,

3 rows of c,

2 rows of b.

and  1 row of a

for a total of 15 rows.

答:
You need a way to generate the rows, such as a numbers table.  Assuming you have that, the problem is then just arithmetic (basically).

The following works fine if the number of rows is an exact multiple of the sum of the weights:

```<code>select *
from (select t.*, sum(weight) over () as sum_weight,
             sum(weight) over (order by rand()) as running_weight
      from t
     ) t join
     n
     on n.n % sum_weight >= running_weight - weight and
        n.n % sum_weight < running_weight
where n.n <= 15
order by value;
</code>```

Here is a db<>fiddle.  The Fiddle uses SQL Server, but this is basically standard SQL.

Body:
You need a way to generate the rows, such as a numbers table.  Assuming you have that, the problem is then just arithmetic (basically).

The following works fine if the number of rows is an exact multiple of the sum of the weights:

select *
from (select t.*, sum(weight) over () as sum_weight,
             sum(weight) over (order by rand()) as running_weight
      from t
     ) t join
     n
     on n.n % sum_weight >= running_weight - weight and
        n.n % sum_weight < running_weight
where n.n <= 15
order by value;

Here is a db<>fiddle.  The Fiddle uses SQL Server, but this is basically standard SQL.


问:
ORM vs Handcoded Data Access Layer
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

```
 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)
```

Hand Coded Advantages

```
 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only
```

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

答:
I've used Subsonic for a couple of largish projects. I'm not advocating the use of one ORM over another, but I wouldnt do another database-related project without one. The ability to regenerate the entire db access layer whenever I change the database structure, the ability to add features in one place that affect the entire DB layer.

The thing is that you have to understand how it interacts with the database, otherwise you run the risk of writing (severely) under-performing code. Your ORM tool might give you a nice object-oriented view of your data, but you might find you're streaming whole tables to the client in order to do simple processing. The database is good at relating and filtering data, so make sure it still has that job. Ironically, Subsonic's lack of joins (in the version I used), helped with that, because it forced me to create DB Views to combine data where needed.

A friend of mine worked with a guy who developed an in-house ORM tool. It had the nice feature of locally caching everything that you could possibly want from the database, done by walking through the foreign keys. The downside was that reading one column from one row in the DB resulted in an excess of 11,000 select statements.

OwnerDisplayName: Frustrating Developments

Title: ORM vs Handcoded Data Access Layer

Body:
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)

Hand Coded Advantages

 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

LastEditorDisplayName: Frustrating Developments

OwnerDisplayName: geofftnz


问:
Django template iterating over list
I have a list created in Django view:

```<code>list = [ elem1, elem2, ..., elemN ]
</code>```

The list is variable length: it can contain 0-6 elements. I want to iterate over the list in the template, but I would like the loop to run always 6 times, yielding None or empty string for non-existing elements.

I tried something like this:

```<code>{% for i in "0123456" %}
    {{ list.i }}
{% endfor %}
</code>```

but this obviously doesn't work. I know I could do this in the view, but I would like to have this in the template. Is is possible?

答:
You can add an if statement checking if it is your 6th time through the loop.

```<code>{% for item in someList %}
{% if forloop.counter <= 6 %}
{{ item }}
{% endif %}
{% endfor %}
</code>```

http://docs.djangoproject.com/en/1.3/ref/templates/builtins/#for in the docs.
Of course, if your list is very long then this is not optimal. I would also suggest processing the list in views.py and then passing it to the template. Logic should stay in the views if possible.

This gives you control over the number of loops done. To completely solve your problem you will need some addtional logic but see my note above regarding this.

Title: Django template iterating over list

Body:
I have a list created in Django view:

list = [ elem1, elem2, ..., elemN ]

The list is variable length: it can contain 0-6 elements. I want to iterate over the list in the template, but I would like the loop to run always 6 times, yielding None or empty string for non-existing elements.

I tried something like this:

{% for i in "0123456" %}
    {{ list.i }}
{% endfor %}

but this obviously doesn't work. I know I could do this in the view, but I would like to have this in the template. Is is possible?

Body:
You can add an if statement checking if it is your 6th time through the loop.

{% for item in someList %}
{% if forloop.counter <= 6 %}
{{ item }}
{% endif %}
{% endfor %}

http://docs.djangoproject.com/en/1.3/ref/templates/builtins/#for in the docs.
Of course, if your list is very long then this is not optimal. I would also suggest processing the list in views.py and then passing it to the template. Logic should stay in the views if possible.

This gives you control over the number of loops done. To completely solve your problem you will need some addtional logic but see my note above regarding this.


答:
You can transform your gray pixels in white pixels with a simple transformation.
If you don't want to use open cv and your image is one channel (gray scale) numpy array:

threshold = 60 # try something between 30 and 150
vect_func = np.vectorize(lambda x: 0 if x == threshold else 255)
black_white_img = vect_func(gray_scale_image)
```

Title: How to read black text on black background image through tesseract OCR?

Body:
I have black text on black background image and I want to read it through OCR. Unfortunately, OCR can not read it perfectly. The image look like this.
I want to convert RGBA value that less than (90, 90, 90, 255) to (255, 255, 255, 255) so it turn B & W. What's the code to convert it?


问:
Doing cumulative sums over multiple variables in dplyr
My data looks like this:

```<code>library(tidyverse)
Date <- c(rep("5/22/19", 3), rep("5/23/19", 3), rep("5/24/19", 3))
Source <- rep(c("Control", "A", "B"), 3)
ValueA <- c(12080, 12012, 11944, 13345, 13342, 13422, 16226, 16045, 16221)
ValueB <- c(11, 9, 13, 11, 9, 7, 12, 9, 15)
df <- tibble(Date, Source, ValueA, ValueB)

df
# A tibble: 9 x 4
  Date    Source  ValueA ValueB
  <chr>   <chr>    <dbl>  <dbl>
1 5/22/19 Control  12080     11
2 5/22/19 A        12012      9
3 5/22/19 B        11944     13
4 5/23/19 Control  13345     11
5 5/23/19 A        13342      9
6 5/23/19 B        13422      7
7 5/24/19 Control  16226     12
8 5/24/19 A        16045      9
9 5/24/19 B        16221     15
</code>```

What I want is, cumulative sums by both Date and Source. So the output would look like:

```<code>  Date    Source  ValueA ValueB
1 5/22/19 Control  12080     11
2 5/22/19 A        12012      9
3 5/22/19 B        11944     13
4 5/23/19 Control  25425     22
5 5/23/19 A        25354     18
6 5/23/19 B        25366     20
7 5/24/19 Control  41651     34
8 5/24/19 A        41399     27
9 5/24/19 B        41587     35
</code>```

However, when I use this code:

```<code>df <- df %>%
  group_by(Date, Source) %>%
  summarize(
    ValueA = sum(ValueA, na.rm = TRUE),
    ValueB = sum(ValueB, na.rm = TRUE),
    Cum_A = cumsum(ValueA, na.rm = TRUE),
    Cum_B = cumsum(ValueB, na.rm = TRUE)
  )
</code>```

I get the error

```<code>Error in cumsum(ValueA, na.rm = TRUE) :
  2 arguments passed to 'cumsum' which requires 1
</code>```

I assume the cumsum function is not designed to handle multiple grouping variables. So how do I get the result that I want?

答:
I think you just need to use group_by(Source). See if this does what you are looking for.

Some notes:

It is optional to keep Source in arrange(); removing it will recreate the data you asked for above. I am including it so the cumsum() result is more obvious

Given your current dataset (no dupes of Source or Date), aggregation isn't required and mutate() will do the trick

cumsum() doesn't take a na.rm argument but you can substitute a 0 with replace_na()

df <-
  tibble(
    Date = rep(c("5/22/19", "5/23/19", "5/24/19"), each = 3),
    Source = rep(c("Control", "A", "B"), 3),
    ValueA = c(12080, 12012, 11944, 13345, 13342, 13422, 16226, 16045, 16221),
    ValueB = c(11, 9, 13, NA, 9, 7, 12, 9, 15)
  )

df %>%
  arrange(Source, Date) %>%
  group_by(Source) %>%
  mutate(
    Cum_A = cumsum(replace_na(ValueA, 0)),
    Cum_B = cumsum(replace_na(ValueB, 0))
  ) %>%
  ungroup()

# Date    Source  ValueA ValueB Cum_A Cum_B
# 5/22/19 A        12012      9 12012     9
# 5/23/19 A        13342      9 25354    18
# 5/24/19 A        16045      9 41399    27
# -----------------------------------------
# 5/22/19 B        11944     13 11944    13
# 5/23/19 B        13422      7 25366    20
# 5/24/19 B        16221     15 41587    35
# -----------------------------------------
# 5/22/19 Control  12080     11 12080    11
# 5/23/19 Control  13345     NA 25425    11
# 5/24/19 Control  16226     12 41651    34
```

Body:
My data looks like this:

library(tidyverse)
Date <- c(rep("5/22/19", 3), rep("5/23/19", 3), rep("5/24/19", 3))
Source <- rep(c("Control", "A", "B"), 3)
ValueA <- c(12080, 12012, 11944, 13345, 13342, 13422, 16226, 16045, 16221)
ValueB <- c(11, 9, 13, 11, 9, 7, 12, 9, 15)
df <- tibble(Date, Source, ValueA, ValueB)

df
# A tibble: 9 x 4
  Date    Source  ValueA ValueB
  <chr>   <chr>    <dbl>  <dbl>
1 5/22/19 Control  12080     11
2 5/22/19 A        12012      9
3 5/22/19 B        11944     13
4 5/23/19 Control  13345     11
5 5/23/19 A        13342      9
6 5/23/19 B        13422      7
7 5/24/19 Control  16226     12
8 5/24/19 A        16045      9
9 5/24/19 B        16221     15

What I want is, cumulative sums by both Date and Source. So the output would look like:

  Date    Source  ValueA ValueB
1 5/22/19 Control  12080     11
2 5/22/19 A        12012      9
3 5/22/19 B        11944     13
4 5/23/19 Control  25425     22
5 5/23/19 A        25354     18
6 5/23/19 B        25366     20
7 5/24/19 Control  41651     34
8 5/24/19 A        41399     27
9 5/24/19 B        41587     35

However, when I use this code:

df <- df %>%
  group_by(Date, Source) %>%
  summarize(
    ValueA = sum(ValueA, na.rm = TRUE),
    ValueB = sum(ValueB, na.rm = TRUE),
    Cum_A = cumsum(ValueA, na.rm = TRUE),
    Cum_B = cumsum(ValueB, na.rm = TRUE)
  )

I get the error

Error in cumsum(ValueA, na.rm = TRUE) :
  2 arguments passed to 'cumsum' which requires 1

I assume the cumsum function is not designed to handle multiple grouping variables. So how do I get the result that I want?


问:
Class Methods and Properties not getting displayed in Visual Studio 2019
I have a Web API project in which none of the class methods and the properties are getting shown as tree list (structure) in Visual Studio. Even the .Net classes are not getting loaded. I am encountering this issue only in this project. Other projects from the same solution is working fine. Please find the screen shot for more info

答:
I resolved this by upgrading my Nuget package of DotNetCompilerPlatform to 2.0.1 and I removed the Import Project Tag which was mapping to old DotNetCompilerPlatform version in csproj file.

After this everything is working as normal like other projects.


问:
How to ensure static shapes in Tensorflow model for easy OpenVINO conversion?
I'm trying to optimize and convert a tensorflow model to OpenVINO IR. It hasn't been very successful because of the problems I'm facing with input shapes. So I'm planning to remodel the whole model with static shapes. The model I'm trying to work on is Tacotron by keithito.

How do I ensure all the nodes in my model will have static shapes?

Will just setting the input placeholder nodes to a fixed shape allow tensorflow to infer and fix the shapes of all other nodes?

答:
You can have dynamic shapes in TF model and provide static shape while cnverting model with ModelOptimizer. Example for input data of size 256x256 with 3 channels.

python mo_tf.py --input_shape [1,256,256,3] --input_model model.pb