问:
Scrapy Scraping tag objects and aggregating values
I am trying to learn how to do web scraping and scrapy seems like a good place to start.
I figured out how to scrape basic text info from tags but now I want to scrape information from the tag itself. Below is an example.
I am using this url: https://www.net-a-porter.com/ca/en/product/1100692/chloe/roy-day-small-leather-and-suede-shoulder-bag

and I want to scrape the name and price of the bag. when looking at the DOM structure there's 2 tags:

```<code><h2 class="product-name">
<nap-price class="product-price" price:{...}>
</code>```

I want to scrape the text value of the h2 tag and the price object inside the nap-price tag

and generate an object like this:

```<code>{
name: "from <h2> tag"
price: "price object from <nap-price> tag"
}

</code>```

currently i can take the name from the h2 tag and I can get the entirety of the nap-price tag but how do I target just the price object? and then aggregate them into one object?

答:
You can use ::attr(), pass the name of the attribute that you want the value of. Then parse the JSON string to a Python object:

```<code>import json

price = response.css('nap-price::attr(price)').get()
obj = json.loads(price)

print(obj)
# {"currency":"USD","divisor":100,"amount":185000}
</code>```

Body:
I am trying to learn how to do web scraping and scrapy seems like a good place to start.
I figured out how to scrape basic text info from tags but now I want to scrape information from the tag itself. Below is an example.
I am using this url: https://www.net-a-porter.com/ca/en/product/1100692/chloe/roy-day-small-leather-and-suede-shoulder-bag

and I want to scrape the name and price of the bag. when looking at the DOM structure there's 2 tags:

<nap-price class="product-price" price:{...}>

I want to scrape the text value of the h2 tag and the price object inside the nap-price tag

and generate an object like this:

{
name: "from
 tag"
price: "price object from <nap-price> tag"
}

currently i can take the name from the h2 tag and I can get the entirety of the nap-price tag but how do I target just the price object? and then aggregate them into one object?

Body:
You can use ::attr(), pass the name of the attribute that you want the value of. Then parse the JSON string to a Python object:

import json

price = response.css('nap-price::attr(price)').get()
obj = json.loads(price)

print(obj)
# {"currency":"USD","divisor":100,"amount":185000}


来源: stackexchange

问:
Confused about the terminology when using the orientation sensor in Android
I've written a small app that outputs the roll, pitch, and azimuth returned from the device's sensor.  However, I'm having difficulty understanding the numbers it returns.

Imagine that the user is holding his smartphone in portrait mode with the screen directly in front of him (the pose someone would be using to snap a photograph).  He then jams a pencil through the middle of the screen and rotates the device around that pencil.  If I wanted to detect when the user rotated to exactly 90 degrees around that pencil (relative to it's starting position), which should I be interested in: roll, pitch, or azimuth?

The answer would seem to be obvious after a little experimentation or reading the Google docs.  However, all three numbers change at approximately the same rate during my tests, so I'm thoroughly confused.

答:
Why not use the accelerometer instead?

I think that's a better solution for you, when you want to detect the rotation of the phone.

Using the accelerometer will give you this result:

When holding the phone as in your example, one of the x, y or z values will be either -9.82 or 9.82 depending which way you hold the phone.  Let's say x is -9.82, and when it rotates the value will increase until it hits 0 and then y will start increase/decrease depending om the rotation.  When y is either -9.82 or 9.82 you've rotated the phone 90 degrees, and if x goes from -9.82 to 9.82 you've rotated 180 degrees.

ContentLicense: CC BY-SA 3.0


问:
How to evaluate a symbolic expression in different ways?
I have a list of symbolic expressions, like below:

```<code>import numpy as np
import sympy
s = sympy.Symbol('s')
x = [ s, s+1, 10*s**2, 5]
</code>```

After adding the elements by using "sum":

```<code>y = sum (x)
</code>```

I will get: 10*s**2 + 2*s + 6
I want to evaluate this expression for each of the elements of the list below:

```<code>s = [1, 2 , 3 , 4 , 5]
</code>```

I know that I can define a function like below:

```<code>def F (s):

    F = 10*s**2 + 2*s + 6
    return F
f_dis = [F(value )for value in s]
</code>```

and it will give the result I'm looking for: [18, 50, 102, 174, 266]
However, my problem is that I have to define the F and write the expression in my code. Is there any other way that I can evaluate the sum (x) without writing the F = 10*s**2 + 2*s + 6 inside my code?
I can not copy and paste the result of sum (x) inside my code.

答:
An alternative solution is using fun.evalf to evaluate your function. You can create the function by adding all the terms using Add, SymPy's Advanced Expression Manipulation

```<code>import numpy as np
from sympy import Symbol, Add

s = Symbol('s')
x = [s, s+1, 10*s**2, 5]
s_values = [1, 2 , 3 , 4 , 5]
fun = Add(*x) # Create a function by adding all terms. * is to unpack all the values

def F(fun, v):
    return fun.evalf(subs={s: v}) # Evaluate the function at s=v

f_dis = [F(fun, v) for v in s_values]

# [18.0000000000000,
#  50.0000000000000,
#  102.000000000000,
#  174.000000000000,
#  266.000000000000]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a list of symbolic expressions, like below:

import numpy as np
import sympy
s = sympy.Symbol('s')
x = [ s, s+1, 10*s**2, 5]

After adding the elements by using "sum":

y = sum (x)

I will get: 10*s**2 + 2*s + 6
I want to evaluate this expression for each of the elements of the list below:

s = [1, 2 , 3 , 4 , 5]

I know that I can define a function like below:

def F (s):

    F = 10*s**2 + 2*s + 6
    return F
f_dis = [F(value )for value in s]

and it will give the result I'm looking for: [18, 50, 102, 174, 266]
However, my problem is that I have to define the F and write the expression in my code. Is there any other way that I can evaluate the sum (x) without writing the F = 10*s**2 + 2*s + 6 inside my code?
I can not copy and paste the result of sum (x) inside my code.

Body:
An alternative solution is using fun.evalf to evaluate your function. You can create the function by adding all the terms using Add, SymPy's Advanced Expression Manipulation

import numpy as np
from sympy import Symbol, Add

s = Symbol('s')
x = [s, s+1, 10*s**2, 5]
s_values = [1, 2 , 3 , 4 , 5]
fun = Add(*x) # Create a function by adding all terms. * is to unpack all the values

def F(fun, v):
    return fun.evalf(subs={s: v}) # Evaluate the function at s=v

f_dis = [F(fun, v) for v in s_values]

# [18.0000000000000,
#  50.0000000000000,
#  102.000000000000,
#  174.000000000000,
#  266.000000000000]


问:
WebAPI C# HttpPost variable is empty
I have a webapi method defined like the following in a controller:

```<code>[Authorize]
[HttpPost]
[Route("api/Resources/{resourceID:int}/VerifyUrl")] //Custom Routing
public object VerifyResourceURL([FromBody]string url, int resourceID)
</code>```

When I call it with jquery ajax the variable url is always null, why?

(resourceID has the correct value)

```<code>$.ajax({
    url: '/api/resources/15/VerifyUrl',
    type: "POST",
    async: true,
    dataType: "json",
    data: { url: 'some-url-to-verify' },
    success: function (data) {
        if (data.Exist === false) {
            urlIsValid = true;
        }
        else {
            alert('URL already exist');
            urlIsValid = false;
        }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log("Status: " + textStatus, "Error: " + errorThrown);
    }
});
</code>```

答:
I have sample code and you can try something like this </p>

```<code>//JavaScript
     var command = {
                    url: $("#txtOrigin").val()
                };

        $.ajax({
            type: "POST",
            url: "/api/booking",
            contentType: "application/json",
            data: JSON.stringify(command),
            dataType: "text",
            success: Created,
            error: Failed
        });

//C# MVC Controller
public async Task<IActionResult> Create([FromBody] CreateBookingCommand command)
{

}
</code>```

Title: WebAPI C# HttpPost variable is empty

Body:
I have a webapi method defined like the following in a controller:

[Authorize]
[HttpPost]
[Route("api/Resources/{resourceID:int}/VerifyUrl")] //Custom Routing
public object VerifyResourceURL([FromBody]string url, int resourceID)

When I call it with jquery ajax the variable url is always null, why?

(resourceID has the correct value)

$.ajax({
    url: '/api/resources/15/VerifyUrl',
    type: "POST",
    async: true,
    dataType: "json",
    data: { url: 'some-url-to-verify' },
    success: function (data) {
        if (data.Exist === false) {
            urlIsValid = true;
        }
        else {
            alert('URL already exist');
            urlIsValid = false;
        }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log("Status: " + textStatus, "Error: " + errorThrown);
    }
});

Body:
I have sample code and you can try something like this

//JavaScript
     var command = {
                    url: $("#txtOrigin").val()
                };

        $.ajax({
            type: "POST",
            url: "/api/booking",
            contentType: "application/json",
            data: JSON.stringify(command),
            dataType: "text",
            success: Created,
            error: Failed
        });

//C# MVC Controller
public async Task<IActionResult> Create([FromBody] CreateBookingCommand command)
{

}


问:
Import from csv file in vs code
I want to change my code from read and process from a string of sentence into read from a csv file, and process line by line.

This is my program in VS Code.

import paralleldots
paralleldots.set_api_key("API KEY")

# for single sentence
text="Come on, lets play together"
lang_code="en"
response=paralleldots.sentiment(text,lang_code)
print(response)
```

I expect the output is run for each line of sentence in a specific csv file, instead of just from a string of sentence.

答:
```<code>fp = open('C:/Users/User/Desktop/hj.txt',encoding='utf-8' ,errors='ignore' ) # Open file on read mode
lines = fp.read().split("\n") # Create a list containing all lines
fp.close() # Close file
print(lines)
#print("----------------------------------------------...------\n")

print("\nThe emotion analysis results for each sentence in the file .txt :")
print("------------------------------------------------...------\n")
response=paralleldots.batch_emotion(lines)
print(response)
</code>```

<p>This worked well. </p>

Title: Import from csv file in vs code

Body:
I want to change my code from read and process from a string of sentence into read from a csv file, and process line by line.

This is my program in VS Code.

import paralleldots
paralleldots.set_api_key("API KEY")

# for single sentence
text="Come on, lets play together"
lang_code="en"
response=paralleldots.sentiment(text,lang_code)
print(response)

I expect the output is run for each line of sentence in a specific csv file, instead of just from a string of sentence.

Body:
fp = open('C:/Users/User/Desktop/hj.txt',encoding='utf-8' ,errors='ignore' ) # Open file on read mode
lines = fp.read().split("\n") # Create a list containing all lines
fp.close() # Close file
print(lines)
#print("----------------------------------------------...------\n")

print("\nThe emotion analysis results for each sentence in the file .txt :")
print("------------------------------------------------...------\n")
response=paralleldots.batch_emotion(lines)
print(response)

This worked well.


问:
Index out of range, but I know the columns are there
EDIT: Found a workaround not using dynamically created tables.

I'm dynamically creating tables using DataGridView in C#. I'm trying to set the column 0 AutoSizeMode but I get the error that index is out of range. However, without ever trying to access columns with code, all my data is displayed properly in the cells, in two columns like it should be.

I tried turning off AutoGenerateColumns, but then I have no data at all.

```<code>DataGridView mainTable = new DataGridView();
DataTable table = new DataTable();
table.Columns.Add("A");
table.Columns.Add("B");

// ... skipping the part where I populate the data in the table, I know the entire data is truly there...

mainTable.DataSource = table;
mainTable.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
</code>```

答:
I am confident the reason the line of code…

```<code>mainTable.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
</code>```

fails is because the DataGridView mainTable has NOT yet been added to the form.

Any UI commands issued BEFORE the DataGridView is added to the form will be ignored.

Adding the DataGridView to the form BEFORE you try and change its columns should work as expected. The posted code does NOT show when the grid is added to the form.

```<code>DataGridView mainTable = new DataGridView();
DataTable table = new DataTable();
table.Columns.Add("A");
table.Columns.Add("B");
// ... skipping the part where I populate the data in the table, I know the entire data is truly there...
mainTable.DataSource = table;
this.Controls.Add(mainTable); // <- UI commands not ignored
mainTable.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
</code>```

Body:
EDIT: Found a workaround not using dynamically created tables.

I'm dynamically creating tables using DataGridView in C#. I'm trying to set the column 0 AutoSizeMode but I get the error that index is out of range. However, without ever trying to access columns with code, all my data is displayed properly in the cells, in two columns like it should be.

I tried turning off AutoGenerateColumns, but then I have no data at all.

DataGridView mainTable = new DataGridView();
DataTable table = new DataTable();
table.Columns.Add("A");
table.Columns.Add("B");

// ... skipping the part where I populate the data in the table, I know the entire data is truly there...

mainTable.DataSource = table;
mainTable.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

Body:
I am confident the reason the line of code…

mainTable.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

fails is because the DataGridView mainTable has NOT yet been added to the form.

Any UI commands issued BEFORE the DataGridView is added to the form will be ignored.

Adding the DataGridView to the form BEFORE you try and change its columns should work as expected. The posted code does NOT show when the grid is added to the form.

DataGridView mainTable = new DataGridView();
DataTable table = new DataTable();
table.Columns.Add("A");
table.Columns.Add("B");
// ... skipping the part where I populate the data in the table, I know the entire data is truly there...
mainTable.DataSource = table;
this.Controls.Add(mainTable); // <- UI commands not ignored
mainTable.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;


问:
How to sort tan array in ascending order and display the sorted array in a JTextArea
I'm trying to make a program which allows a user to insert marks into an array and sort them. How do I do this?

```<code>private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
    String newMark;
    newMark  = userText.getText().substring(0, 1).toUpperCase() + userText.getText().substring(1);
    if (Integer.parseInt(newMark) <= 100 && Integer.parseInt(newMark) >= 0) {
        studentMarks = new ArrayList<Integer>();
        studentMarks.add(Integer.parseInt(newMark));
        markDisplay.append(studentMarks +"\n");
    } else {
        markDisplay.append("Only marks between \n 0 and 100 are accepted. \n");
    }
}

private void sortButtonActionPerformed(java.awt.event.ActionEvent evt) {
    studentMarksSorted = new ArrayList<Integer>();
    studentMarksSorted = studentMarks;
    Collections.sort(studentMarksSorted);
    markDisplay.setText(studentMarksSorted + "\n");
}
</code>```

I expected the output to be the marks the user inputted in descending numeric order, replacing the original unsorted list, but instead, the output was just the last number that the user added to the array.

答:
but instead the output was just the last number that the user added to the array.

```<code>studentMarks = new ArrayList<Integer>();
studentMarks.add(Integer.parseInt(newMark));
</code>```

Well, you create a new ArrayList every time you add a mark.

So of course you only have a single number.

The ArrayList should be created once in the constructor of your class and then you just add new Integer values to the ArrayList.

```<code>studentMarksSorted = new ArrayList<Integer>();
studentMarksSorted = studentMarks;
</code>```

And there is no need for doing the above. That does not copy the data from one ArrayList to another. If you want to keep track of the original marks and the sorted marks, then you need to manually copy the Integers from one ArrayList to the other.

Body:
I'm trying to make a program which allows a user to insert marks into an array and sort them. How do I do this?

private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
    String newMark;
    newMark  = userText.getText().substring(0, 1).toUpperCase() + userText.getText().substring(1);
    if (Integer.parseInt(newMark) <= 100 && Integer.parseInt(newMark) >= 0) {
        studentMarks = new ArrayList<Integer>();
        studentMarks.add(Integer.parseInt(newMark));
        markDisplay.append(studentMarks +"\n");
    } else {
        markDisplay.append("Only marks between \n 0 and 100 are accepted. \n");
    }
}

private void sortButtonActionPerformed(java.awt.event.ActionEvent evt) {
    studentMarksSorted = new ArrayList<Integer>();
    studentMarksSorted = studentMarks;
    Collections.sort(studentMarksSorted);
    markDisplay.setText(studentMarksSorted + "\n");
}

I expected the output to be the marks the user inputted in descending numeric order, replacing the original unsorted list, but instead, the output was just the last number that the user added to the array.

Body:
but instead the output was just the last number that the user added to the array.

studentMarks = new ArrayList<Integer>();
studentMarks.add(Integer.parseInt(newMark));

Well, you create a new ArrayList every time you add a mark.

So of course you only have a single number.

The ArrayList should be created once in the constructor of your class and then you just add new Integer values to the ArrayList.

studentMarksSorted = new ArrayList<Integer>();
studentMarksSorted = studentMarks;

And there is no need for doing the above. That does not copy the data from one ArrayList to another. If you want to keep track of the original marks and the sorted marks, then you need to manually copy the Integers from one ArrayList to the other.


问:
Why doesn't my String comparison code work?
this code throws

Error "Exception in thread "main"
  java.lang.ArrayIndexOutOfBoundsException: 0

at basic2.compareStrPractice.main(compareStrPractice.java:15)"

```<code>int i;
    char[] chr1 = {};
    char[] chr2 = {};
    String s1 = "man";
    String s2 = "nam";

        for ( i= 0; i<s1.length(); i++){

            chr1[i] = (char)s1.charAt(i);
            chr2[i] = (char)s2.charAt(i);

        }
        if ((chr1[0] == chr2[2]) && (chr1[1] == chr2[1]) && (chr1[2] == chr2[0])){

            System.out.println("They are Palindrom!");
        }

}
</code>```

i want to print the statement. but it throws ArrayOutOfBoundary Error.

答:
You should also first check the lengths to ensure they are the same.  Otherwise, you may get another ArrayIndexOutOfBoundsException. This will happen when you use the longer string's length to index the shorter character array.

Since for longer strings you don't want to have many comparisons in a single if statement you should use a loop and compare starting at the beginning of one array and at the end of the other.  So if the length is 5  you would compare characters at 0 and 4, then 1 and 3, then 2, and 2, then 3, and 1 and so forth.

Here are some other tips that might help.  You don't need to create empty arrays and fill them.  String provides that capability.

char[] chr1 = s1.toCharArray();

In fact, you don't need to assign to a String variable.

char[] chr1 = "man".toCharArray();

And just in case you ever want to assign to an array of String instead of char you can do this to hold an array of single character strings.

String[] str1 = "abcdefghijklmnopqrstuvwxyz".split("");

Body:
this code throws

Error "Exception in thread "main"
  java.lang.ArrayIndexOutOfBoundsException: 0

at basic2.compareStrPractice.main(compareStrPractice.java:15)"

int i;
    char[] chr1 = {};
    char[] chr2 = {};
    String s1 = "man";
    String s2 = "nam";

        for ( i= 0; i<s1.length(); i++){

            chr1[i] = (char)s1.charAt(i);
            chr2[i] = (char)s2.charAt(i);

        }
        if ((chr1[0] == chr2[2]) && (chr1[1] == chr2[1]) && (chr1[2] == chr2[0])){

            System.out.println("They are Palindrom!");
        }

}

i want to print the statement. but it throws ArrayOutOfBoundary Error.


问:
Discord.js: Cannot Read Property "Name" of Null - How do I fix this?
I figured out how to make my Discord bot send an image to a certain channel whenever a specific user plays a specific game, but I have another problem.

When the application closes, I get this error saying, "Cannot read property 'name' of null." How do I fix this?

I haven't tried anything because I don't know anything about how I should use null.

```<code>// Game Detector \\
client.on("presenceUpdate", (oldMember, newMember) => {
if(newMember.id === '406742915352756235') {
    if(newMember.presence.game.name === 'ROBLOX') { // New Example: ROBLOX
        console.log('ROBLOX detected!');
        client.channels.get('573671522116304901').send('**Joining Game:**', {
            files: [
                "https://cdn.discordapp.com/attachments/567519197052272692/579177282283896842/rblx1.png"
                ]
            });
        }
    }
});
</code>```

I expected the code to work, even when the application closes. Instead, it cannot read name of null. How can I fix this error?

答:
This error is most likely thrown when the user stops playing a game, because newMember.presence.game will logically be null. Then, when  you try to read name of newMember.presence.game, you receive your error.

Use this revised code:

client.on('presenceUpdate', (oldMember, newMember) => {
  if (newMember.id !== '406742915352756235') return; // only check for this user

  if (newMember.presence.game && newMember.presence.game.name === 'ROBLOX') {
    console.log('ROBLOX detected.');

    const channel = client.channels.get('573671522116304901');
    if (!channel) return console.log('Unable to find channel.');

    channel.send('**Joining Game:**', {
      files: ['https://cdn.discordapp.com/attachments/567519197052272692/579177282283896842/rblx1.png']
    }).catch(console.error);
  }
});
```

Body:
I figured out how to make my Discord bot send an image to a certain channel whenever a specific user plays a specific game, but I have another problem.

When the application closes, I get this error saying, "Cannot read property 'name' of null." How do I fix this?

I haven't tried anything because I don't know anything about how I should use null.

// Game Detector \\
client.on("presenceUpdate", (oldMember, newMember) => {
if(newMember.id === '406742915352756235') {
    if(newMember.presence.game.name === 'ROBLOX') { // New Example: ROBLOX
        console.log('ROBLOX detected!');
        client.channels.get('573671522116304901').send('**Joining Game:**', {
            files: [
                "https://cdn.discordapp.com/attachments/567519197052272692/579177282283896842/rblx1.png"
                ]
            });
        }
    }
});

I expected the code to work, even when the application closes. Instead, it cannot read name of null. How can I fix this error?


问:
Getting Cell Value from Closed Workbooks in a Directory - How to Loop Through All Existing Files?
I have a working code to retrieve a specific cell in a closed workbook when I specify the directory. I'm trying to get this code to loop through all the existing workbooks in said directory, retrieving the same cell from each file.

This is the code I have so far with the loop (I'm including the function used as well):

```<code>Private Function GetValueFromClosedWorkbook(path, file, sheet, ref)
    Dim arg As String, xFolder As String

    If Right(path, 1) <> "\" Then path = path & "\"

    If Dir(path & file) = "" Then
        GetValueFromClosedWorkbook = "File not found."
        Exit Function
    End If

    arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
    Range(ref).Address(, , xlR1C1)         'create the argument
    GetValueFromClosedWorkbook = ExecuteExcel4Macro(arg)
End Function

Sub TestGetValueFromClosedWorkbook()
    Dim p As String, xFolder As String
    Dim s As String, a As String, f(1 To 2) As String, z As Long

    xFolder = "\\generic path"

    For z = 1 To 2
        s = "Sheet1"
        a = "A1"
        p = xFolder '& "\*.xlsx"
        f(z) = Dir(p & "\*.xlsx")

        Do While f(z) <> ""
            ActiveSheet.Range("A" & (z + 7)) = GetValueFromClosedWorkbook(p, f(z), s, a)
            f(z) = Dir()
        Loop
    Next z
End Sub
</code>```

This gets the correct cell, and then pastes in the active worksheet in cell A8.

The only issue is that when it loops through the second file, it still gets the cell from the first file. Why is that happening? Or how can I ensure that the second loop it retrieves the cell from the second workbook?

答:
The loops were a bit messed up, and you were overwriting the values. Please see below corrected code:

Sub TestGetValueFromClosedWorkbook()

    Dim p As String, xFolder As String

    Dim s As String, a As String, f As String, z As Long

    xFolder = "\\generic path"

    s = "Sheet1"
    a = "A1"
    p = xFolder '& "\*.xlsx"

    f = Dir(p & "\*.xlsx")
    Do While f <> ""

        ActiveSheet.Range("A" & (z + 7)) = GetValueFromClosedWorkbook(p, f, s, a)

        f = Dir()
        z = z + 1
    Loop
End Sub
```

Body:
I have a working code to retrieve a specific cell in a closed workbook when I specify the directory. I'm trying to get this code to loop through all the existing workbooks in said directory, retrieving the same cell from each file.

This is the code I have so far with the loop (I'm including the function used as well):

Private Function GetValueFromClosedWorkbook(path, file, sheet, ref)
    Dim arg As String, xFolder As String

    If Right(path, 1) <> "\" Then path = path & "\"

    If Dir(path & file) = "" Then
        GetValueFromClosedWorkbook = "File not found."
        Exit Function
    End If

    arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
    Range(ref).Address(, , xlR1C1)         'create the argument
    GetValueFromClosedWorkbook = ExecuteExcel4Macro(arg)
End Function

Sub TestGetValueFromClosedWorkbook()
    Dim p As String, xFolder As String
    Dim s As String, a As String, f(1 To 2) As String, z As Long

    xFolder = "\\generic path"

    For z = 1 To 2
        s = "Sheet1"
        a = "A1"
        p = xFolder '& "\*.xlsx"
        f(z) = Dir(p & "\*.xlsx")

        Do While f(z) <> ""
            ActiveSheet.Range("A" & (z + 7)) = GetValueFromClosedWorkbook(p, f(z), s, a)
            f(z) = Dir()
        Loop
    Next z
End Sub

This gets the correct cell, and then pastes in the active worksheet in cell A8.

The only issue is that when it loops through the second file, it still gets the cell from the first file. Why is that happening? Or how can I ensure that the second loop it retrieves the cell from the second workbook?


问:
collectionView didSlectRow bug
Hello on a specific viewController of my project i have a UICollectionView with a custom class cell. But i have a big problem this that func :

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("tapped on a cell")
    }
```

when is click on a cell and instant realease (normal click) it does nothing, just nothing.

if i press and hold about 1s without release the finger it become grey, highlighted

And if i press and hold at least 3 seconds release the finger didSelectItemAt is executed correctly.
I tried to do the same on another project and that's work great but not on this VC and i really don't find the problem. The VC Bugged is of addTest clas in Main.storyboard

答:
Probably there is a UIGesture or another interactable thing underneath the collection view. You should DISABLE its ability to cancel touches in view in interface builder:

or in code:

```<code>myTapGestureRecognizer.cancelsTouchesInView = false
</code>```

Title: collectionView didSlectRow bug

Body:
Hello on a specific viewController of my project i have a UICollectionView with a custom class cell. But i have a big problem this that func :

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("tapped on a cell")
    }

when is click on a cell and instant realease (normal click) it does nothing, just nothing.

if i press and hold about 1s without release the finger it become grey, highlighted

And if i press and hold at least 3 seconds release the finger didSelectItemAt is executed correctly.
I tried to do the same on another project and that's work great but not on this VC and i really don't find the problem. The VC Bugged is of addTest clas in Main.storyboard

Body:
Probably there is a UIGesture or another interactable thing underneath the collection view. You should DISABLE its ability to cancel touches in view in interface builder:

or in code:

myTapGestureRecognizer.cancelsTouchesInView = false


问:
Drawing will be cleared after minimizing window vc++ mfc
I have written this program, but when I minimize the window, all the drawing will be cleared. what should I do?

```<code>        CClientDC dc(this);
        dc.Ellipse(point.x-20,point.y-20,point.x+20,point.y+20);
        c[n][1] = point.x; c[n][2] = point.y;
</code>```

who can help me solving this problem?

thanks alot

答: Make a function of your above code and call it from OnDraw function. It will work fine.

Body:
I have written this program, but when I minimize the window, all the drawing will be cleared. what should I do?

        CClientDC dc(this);
        dc.Ellipse(point.x-20,point.y-20,point.x+20,point.y+20);
        c[n][1] = point.x; c[n][2] = point.y;

who can help me solving this problem?

thanks alot


问:
How to allow users to type address when using vue spa on google cloud storage
We are hosting a vue spa on google storage buckets and it works find for the main index page and for the links on the page but you are unable to type a url in and go the the page because google cloud tries to find the file instead of using vue router

If i switch off history mode it works because its a # instead of a path but we need history mode on for this to work

```<code><Code>NoSuchKey</Code>
<Message>The specified key does not exist.</Message>
</Error>
</code>```

Here is the XML data for not found pages

I want to have users able to type in the url and goes to that page. I would like to keep it on GCloud Storage buckets if possible if not a vm is fine.

答: Fixed it by setting the 404 page to index.html</p>

Body:
We are hosting a vue spa on google storage buckets and it works find for the main index page and for the links on the page but you are unable to type a url in and go the the page because google cloud tries to find the file instead of using vue router

If i switch off history mode it works because its a # instead of a path but we need history mode on for this to work

NoSuchKey
<Message>The specified key does not exist.</Message>
</Error>

Here is the XML data for not found pages

I want to have users able to type in the url and goes to that page. I would like to keep it on GCloud Storage buckets if possible if not a vm is fine.


问:
Extracting data from grib file based on latitude and longitude
If i have a grib2 file that contains information for whole world (for some parameters) and I want to extract data from it using wgrib2 based on latitude and longitude given by user (client software to server). I tried following command but I am getting complete grib2 file only:

wgrib2.exe input.grb -undefine out-box 10:90 -10:10 -grib output.grb

Please tell me where am I going wrong? Thanks.

答:
This is still the top hit on Google, so even though it is a bit old, here is a more detailed explanation.

First, you need wgrib2 from the National Weather Service Climate Prediction Centre. (The installation of that is straightforward, but not too well explained. See this page, or this gist for help.)

Next, you need to use the lola function (for LOngitude-LAtitude grid).

You need to give wgrib2 several arguments:

the grib file that has the data

the longitude information:

the longitude of the southwest corner of your bounding box

the length of the bounding box in degrees

the spacing of the points in this direction

the latitude information, the same as above

the latitude of the southwest corner of your bounding box

the length of the bounding box in degrees

the spacing of the points in this direction

the file name to write to

the format of the file to write (either bin for binary, text for simple text, spread for spreadsheet format, or grib for grib2).

For example:

```<code>wgrib2 input.grb 220:100:1 20:50:1 output.grb2 grib
</code>```

will create an output file that covers north america (220 E - 320 E; 20 N - 70 N) at 1 degree intervals in both directions.

Rob

Body:
This is still the top hit on Google, so even though it is a bit old, here is a more detailed explanation.

First, you need wgrib2 from the National Weather Service Climate Prediction Centre. (The installation of that is straightforward, but not too well explained. See this page, or this gist for help.)

Next, you need to use the lola function (for LOngitude-LAtitude grid).

You need to give wgrib2 several arguments:

the grib file that has the data

the longitude information:

the longitude of the southwest corner of your bounding box

the length of the bounding box in degrees

the spacing of the points in this direction

the latitude information, the same as above

the latitude of the southwest corner of your bounding box

the length of the bounding box in degrees

the spacing of the points in this direction

the file name to write to

the format of the file to write (either bin for binary, text for simple text, spread for spreadsheet format, or grib for grib2).

For example:

wgrib2 input.grb 220:100:1 20:50:1 output.grb2 grib

will create an output file that covers north america (220 E - 320 E; 20 N - 70 N) at 1 degree intervals in both directions.

Rob


问:
ngClass not working when calling a css class diferently?
Im having a problem, more like trouble understanding why a code does/doesn't work while using ngClass directive.
I have this css class inside the component.css

```<code>.yellow-text {
    color: yellow;
}
</code>```

In the component.html I have this simple paragraph, nameTest is a property from the component which has the value 'Testing'.

```<code><p [ngClass]="{ yellow-text: nameTest === 'Testing' }">ASDASD</p>
</code>```

This doesn't compile unless I add ' ' in yellow-text.

```<code><p [ngClass]="{ 'yellow-text': nameTest === 'Testing' }">ASDASD</p>
</code>```

On the other hand, if I make the css class look like this

```<code>.yellowtext {
    color: yellow;
}
</code>```

I can use this code.

```<code><p [ngClass]="{ yellowtext: nameTest === 'Testing' }">ASDASD</p>
</code>```

Why? What am I missing? Sorry for asking this, im probably missing something fundamental.

答:
The reason it does not compile with no quotes, be they single or double, is because ngClass expects an object, and in Javascript, object keys don't need quotes if they only contain characters, numbers and underscores, if the keys have special characters like - in your case, you have to put quotes around them. For example

{this is not valid: 'Not OK'} is not a valid object syntax, to make it valid, you put quotes around the key {'this is now valid': 'OK now'}

Body:
Im having a problem, more like trouble understanding why a code does/doesn't work while using ngClass directive.
I have this css class inside the component.css

.yellow-text {
    color: yellow;
}

In the component.html I have this simple paragraph, nameTest is a property from the component which has the value 'Testing'.

ASDASD

This doesn't compile unless I add ' ' in yellow-text.

ASDASD

On the other hand, if I make the css class look like this

.yellowtext {
    color: yellow;
}

I can use this code.

ASDASD

Why? What am I missing? Sorry for asking this, im probably missing something fundamental.


问:
Access ApplicationResource.properties file from Action Class in Struts 2
can i access ApplicationResource.properties file keys from Action Class in Struts 2
and update the values of the key ?</p>

答:
Yes its possible.
Lets say if you have a property error.login in applicationResources.properties file.
eg : error.login= Invalid Username/Password. Please try again.

then in  the Action class you can access it like this : getText("error.login")

Complete example:

applicationResources.properties

```<code>error.login= Invalid Username/Password
</code>```

LoginAction.java

```<code>package net.sumitknath.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

    private String username;

    private String password;

    public String execute() {
        if (this.username.equals("admin") && this.password.equals("admin123")) {
            return "success";
        } else {
            addActionError(getText("error.login"));
            return "error";
        }
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Yes its possible.
Lets say if you have a property error.login in applicationResources.properties file.
eg : error.login= Invalid Username/Password. Please try again.

then in  the Action class you can access it like this : getText("error.login")

Complete example:

applicationResources.properties

error.login= Invalid Username/Password

LoginAction.java

package net.sumitknath.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

    private String username;

    private String password;

    public String execute() {
        if (this.username.equals("admin") && this.password.equals("admin123")) {
            return "success";
        } else {
            addActionError(getText("error.login"));
            return "error";
        }
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}


问:
How to fix a geolocation API URL to work with specific parameters
I'm trying to use the geolocation api to get the latitude and longitude from an address given by the user but it isn't working.

I'm doing the following(in which I'm thinking how to modify the URL to put the key):

```<code>response = requests.get("https://maps.googleapis.com/maps/api/geocode/json?address="+request.form.get("address"))

resp_json_payload = response.json()
</code>```

But I'm getting the following error:

"error_message" : "You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please refer to http://g.co/dev/maps-no-account"

This is all the code:

```<code>import requests

requests.get("https://maps.googleapis.com/maps/api/geocode/json?address="+request.form.get("address"))

resp_json_payload = response.json()
</code>```

答:
Anywhere after the ? you can insert your API key key=yourAPIKey

```<code>requests.get("https://maps.googleapis.com/maps/api/geocode/json?key=yourAPIKey&address=" + request.form.get("address"))
</code>```

Or

```<code>requests.get("https://maps.googleapis.com/maps/api/geocode/json?address=" + request.form.get("address") + "&key=yourAPIKey")
</code>```

Body:
I'm trying to use the geolocation api to get the latitude and longitude from an address given by the user but it isn't working.

I'm doing the following(in which I'm thinking how to modify the URL to put the key):

response = requests.get("https://maps.googleapis.com/maps/api/geocode/json?address="+request.form.get("address"))

resp_json_payload = response.json()

But I'm getting the following error:

"error_message" : "You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please refer to http://g.co/dev/maps-no-account"

This is all the code:

import requests

requests.get("https://maps.googleapis.com/maps/api/geocode/json?address="+request.form.get("address"))

resp_json_payload = response.json()

Body:
Anywhere after the ? you can insert your API key key=yourAPIKey

requests.get("https://maps.googleapis.com/maps/api/geocode/json?key=yourAPIKey&address=" + request.form.get("address"))

Or

requests.get("https://maps.googleapis.com/maps/api/geocode/json?address=" + request.form.get("address") + "&key=yourAPIKey")


问:
Cannot center javascript created button using css
I created a button in javascript seen in the code below, but I cannot style it. Neither text-align:center nor margin: 0 auto works. Does any one have a solution? Thanks!

button = document.createElement("button");
button.innerHTML = "Reset High Score"
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
button.addEventListener("click", function() {
  alert("High Score Reset!");
  localStorage.clear();
  location.reload();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button {
  margin: 0 auto;
  text-align: center;
}</code>```

答:
The reason is that you don't center inline elements directly, you apply centering to their parent element and the contents of the container get centered. Also, inline elements don't have margins or padding, only block-level elements do.

text-align is an inherited property. That means that it affects its descendant elements rather than itself.

It's incredibly important to know if an element is a block or inline element because, as you've found out the hard way, certain CSS properties only work on one vs. the other.

It's actually pretty easy to spot an inline vs. a block-level element. Block-level elements place their content on a new line, while inline elements do not. So, a div is a block, but a button is an inline. Knowing that, when you look at CSS documentation, you can see if the property works with the type of element you have. In the link I mentioned earlier about text-align, if you scroll down to just above the browser compatibility chart you' see that for text-align, it says that it is an inherited property and applied to blocks.

button = document.createElement("button");
button.innerHTML = "Reset High Score"
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
button.addEventListener("click", function(){
    alert("High Score Reset!");
    localStorage.clear();
    location.reload();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
margin: 0 auto;
text-align: center;

}</code>```

FYI:

Never, never, never do this: document.getElementsByTagName("body")[0]. Please read this other post of mine that explains how bad this is. Instead, use .querySelector() or, in this case, because you want the one and only body element, which is a child of the document, you can just write document.body.

button = document.createElement("button");
button.innerHTML = "Reset High Score"
var body = document.querySelector("body"); // Instead of getElementsByTagName()
var body = document.body; // The easiest way to get a reference to the body element
body.appendChild(button);
button.addEventListener("click", function(){
    alert("High Score Reset!");
    localStorage.clear();
    location.reload();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
margin: 0 auto;
text-align: center;

}</code>```

Body:
I created a button in javascript seen in the code below, but I cannot style it. Neither text-align:center nor margin: 0 auto works. Does any one have a solution? Thanks!

button = document.createElement("button");
button.innerHTML = "Reset High Score"
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
button.addEventListener("click", function() {
  alert("High Score Reset!");
  localStorage.clear();
  location.reload();
})

button {
  margin: 0 auto;
  text-align: center;
}

Body:
The reason is that you don't center inline elements directly, you apply centering to their parent element and the contents of the container get centered. Also, inline elements don't have margins or padding, only block-level elements do.

text-align is an inherited property. That means that it affects its descendant elements rather than itself.

It's incredibly important to know if an element is a block or inline element because, as you've found out the hard way, certain CSS properties only work on one vs. the other.

It's actually pretty easy to spot an inline vs. a block-level element. Block-level elements place their content on a new line, while inline elements do not. So, a div is a block, but a button is an inline. Knowing that, when you look at CSS documentation, you can see if the property works with the type of element you have. In the link I mentioned earlier about text-align, if you scroll down to just above the browser compatibility chart you' see that for text-align, it says that it is an inherited property and applied to blocks.

button = document.createElement("button");
button.innerHTML = "Reset High Score"
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
button.addEventListener("click", function(){
    alert("High Score Reset!");
    localStorage.clear();
    location.reload();
})

body {
margin: 0 auto;
text-align: center;

}

FYI:

Never, never, never do this: document.getElementsByTagName("body")[0]. Please read this other post of mine that explains how bad this is. Instead, use .querySelector() or, in this case, because you want the one and only body element, which is a child of the document, you can just write document.body.

button = document.createElement("button");
button.innerHTML = "Reset High Score"
var body = document.querySelector("body"); // Instead of getElementsByTagName()
var body = document.body; // The easiest way to get a reference to the body element
body.appendChild(button);
button.addEventListener("click", function(){
    alert("High Score Reset!");
    localStorage.clear();
    location.reload();
})

body {
margin: 0 auto;
text-align: center;

}


问:
How do shared parameters in actor-critic models work?
Hello StackOverflow Community!

I have a question about Actor-Critic Models in Reinforcement Learning.

While listening policy gradient methods classes of Berkeley University, it is said in the lecture that in the actor-critic algorithms where we both optimize our policy with some policy parameters and our value functions with some value function parameters, we use same parameters in both optimization problems(i.e. policy parameters = value function parameters) in some algorithms (e.g. A2C/A3C)

I could not understand how this works. I was thinking that we should optimize them separately. How does this shared parameter solution helps us?

Thanks in advance :)

答:
You can do it by sharing some (or all) layers of their network. If you do, however, you are assuming that there is a common state representation (the intermediate layer output) that is optimal w.r.t. both. This is a very strong assumption and it usually doesn't hold. It has been shown to work for learning from image, where you put (for instance) an autoencoder on the top both the actor and the critic network and train it using the sum of their loss function.

This is mentioned in PPO paper (just before Eq. (9)). However, they just say that they share layers only for learning Atari games, not for continuous control problems. They don't say why, but this can be explained as I said above: Atari games have a low-dimensional state representation that is optimal for both the actor and the critic (e.g., the encoded image learned by an autoencoder), while for continuous control you usually pass directly a low-dimensional state (coordinates, velocities, ...).

A3C, which you mentioned, was also used mostly for games (Doom, I think).

From my experience, in control sharing layers never worked if the state is already compact.


问:
MKMapView not Clustering Annotation on zooming out map in Swift
before duplicating my questing please read the whole thing.
i am using MkMapKit in my app and now I have to show people in cluster when zoom out the map, I have achieved numbering them out so far using from this answer using Apple's default clustering class. now I have no idea how to add and show them all one circle with there count, i know something that it should relate with radius but i don't know how can i do that, sharing my code below, i hope any help would be appreciated. thanks
also showing picture of what i have done :

This is my UserAnnotationClass

```<code>class UserAnnotation: NSObject, MKAnnotation {

    let title: String?
    let locationName: String
    let discipline: String
    let coordinate: CLLocationCoordinate2D

    let userProfile: UserProfile!
    let index: Int!
    let memberAnnotations: [UserProfile]!
    init(userProfile: UserProfile, at index: Int) {

        self.title = userProfile.fullName
        self.locationName = (userProfile.locationAddress != nil) ? userProfile.locationAddress : ""
        let userProfilePicture: String = (userProfile.profilePicture == nil || userProfile.profilePicture == "") ? "" : userProfile.profilePicture

        self.discipline = userProfilePicture

       // print("\(userProfile.fullName) \(userProfile.location.dist)")

        if (userProfile.isMapVisibility == true) {
            self.coordinate = CLLocationCoordinate2D(latitude: userProfile.location.lat, longitude: userProfile.location.lon)
        } else {
            self.coordinate = CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)
        }
        memberAnnotations = [UserProfile]()
        memberAnnotations.append(userProfile)
        self.userProfile = userProfile
        self.index = index

        super.init()
    }

    var subtitle: String? {
        return locationName
    }

    // pinTintColor for disciplines: Sculpture, Plaque, Mural, Monument, other
    var markerTintColor: UIColor  {
        switch discipline {
        case "Monument":
            return .red
        case "Mural":
            return .cyan
        case "Plaque":
            return .blue
        case "Sculpture":
            return .purple
        default:
            return .clear
        }
    }

    // Annotation right callout accessory opens this mapItem in Maps app
    func mapItem() -> MKMapItem {
        let addressDict = [CNPostalAddressStreetKey: subtitle!]
        let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDict)
        let mapItem = MKMapItem(placemark: placemark)
        mapItem.name = title

        return mapItem
    }
}
</code>```

And This is the CLusterViewClass i am using to make them clustered .

```<code>class ClusterView: MKAnnotationView {

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let hitView = super.hitTest(point, with: event)
        if (hitView != nil)
        {

            if (hitView?.isKind(of: UIButton.self))! {

                let sender: UIButton = hitView as! UIButton

                sender.sendActions(for: .touchUpInside)

            }
            else {

                self.superview?.bringSubviewToFront(self)
            }
        }
        return hitView
    }
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let rect = self.bounds
        var isInside: Bool = rect.contains(point)
        if(!isInside)
        {
            for view in self.subviews
            {
                isInside = view.frame.contains(point)
                if isInside
                {
                    break
                }
            }
        }
        return isInside
    }
    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        displayPriority = .defaultHigh
        collisionMode = .circle
        centerOffset = CGPoint(x: 0, y: -10) // Offset center point to animate better with marker annotations
    }

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

    override var annotation: MKAnnotation? {
        willSet {

            canShowCallout = false

            if let cluster = newValue as? UserAnnotation {
                let renderer = UIGraphicsImageRenderer(size: CGSize(width: 40, height: 40))
                let count = cluster.memberAnnotations.count
                let uniCount = cluster.memberAnnotations.filter { member -> Bool in
                    //Log("Bool  \(member) , \(member.isMapVisibility == false) ")

                    return member.isMapVisibility == true
                }.count
                //Log("COUNTS \(count) , \(uniCount) ❤")
                image = renderer.image { _ in
                    // Fill full circle with tricycle color
                    if uniCount > 0 {

                        AppTheme.blueColor.setFill()
                        UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 40, height: 40)).fill()

                        // Fill inner circle with white color
                        UIColor.white.setFill()
                        UIBezierPath(ovalIn: CGRect(x: 8, y: 8, width: 24, height: 24)).fill()

                        // Finally draw count text vertically and horizontally centered
                        let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.black,
                                           NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20)]
                        //let text = "\(count)"
                        let text = "4"
                        let size = text.size(withAttributes: attributes)
                        let rect = CGRect(x: 20 - size.width / 2, y: 20 - size.height / 2, width: size.width, height: size.height)
                        text.draw(in: rect, withAttributes: attributes)
                    }
                }
            }
        }
    }

}
</code>```

And these are some of my MapKit Functions

```<code>extension FeedsViewController: MKMapViewDelegate {

    //   1
      func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        guard let annotation = annotation as? UserAnnotation else { return nil }
        // 2
        let identifier = "marker"
        if #available(iOS 11.0, *) {
            var view: ClusterView

            if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
                as? ClusterView { // 3
                dequeuedView.annotation = annotation
                view = dequeuedView
            } else {
                // 4
                view = ClusterView(annotation: annotation, reuseIdentifier: identifier)
            }
            return view
        } else {
            // Fallback on earlier versions

            return nil
        }

      }
    func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
//        let zoomWidth = mapView.visibleMapRect.size.width
//        let zoomFactor = Int(log2(zoomWidth))
//        print("...REGION DID CHANGE: ZOOM FACTOR \(zoomFactor)")
        let centralLocation = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude:  mapView.centerCoordinate.longitude)

        Log(" Radius - \(self.getRadius(centralLocation: centralLocation))")

    }
    func getRadius(centralLocation: CLLocation) -> Double{
        let topCentralLat:Double = centralLocation.coordinate.latitude -  mapView.region.span.latitudeDelta/2
        let topCentralLocation = CLLocation(latitude: topCentralLat, longitude: centralLocation.coordinate.longitude)
        let radius = centralLocation.distance(from: topCentralLocation)
        return radius / 1000.0 // to convert radius to meters
    }
    func mapView(_ mapView: MKMapView,
                 didSelect view: MKAnnotationView)
    {
        // 1
        if view.annotation is MKUserLocation
        {
            // Don't proceed with custom callout
            return
        }
        // 2
        let annotation = view.annotation as! UserAnnotation

        let detailAnnotationView: UserDetailAnnotationView = UserDetailAnnotationView(frame: CGRect(x: 0, y: 0, width: 320, height: 74))

        let url = (annotation.discipline == "") ? nil : URL(string: annotation.discipline)!
        let range = 0.0..<0.9
        if annotation.userProfile.location.dist != nil {
            if range.contains(annotation.userProfile.location.dist) {
                let kMeters = Measurement(value: annotation.userProfile.location.dist, unit: UnitLength.kilometers)
                let meters = kMeters.converted(to: UnitLength.meters)
                detailAnnotationView.distancelbl.text = "\(String(describing: round(Double(meters.value)))) m Away"

            } else {
                detailAnnotationView.distancelbl.text = "\(String(describing: round(annotation.userProfile.location.dist))) Km Away"
            }
        }

        detailAnnotationView.set(Title: annotation.title!, imageUrl: url) { [weak self] (sender) in
            guard let self = self else { return }
            if self.isOpenChat {

                self.isOpenChat = false

                if annotation.userProfile.channel != "" {

                    self.appDelegate.pubNubAddPushNotifications([annotation.userProfile.channel]) { (status) in

                        print(status.description)
                    }

                    let chatViewController: ChatViewController = self.storyboard?.instantiateViewController(withIdentifier: "ChatViewController") as! ChatViewController

                    chatViewController.userProfile = annotation.userProfile
                    chatViewController.loginUserProfile = self.loginUserProfile
                    self.navigationController?.pushViewController(chatViewController, animated: true)
                }
            }

        }

        detailAnnotationView.center = CGPoint(x: view.bounds.size.width / 2, y: -detailAnnotationView.bounds.size.height*0.52)

        view.addSubview(detailAnnotationView)

        mapView.setCenter((view.annotation?.coordinate)!, animated: true)

//        let calloutView = views?[0] as! CustomCalloutView
//        calloutView.starbucksName.text = starbucksAnnotation.name
//        calloutView.starbucksAddress.text = starbucksAnnotation.address
//        calloutView.starbucksPhone.text = starbucksAnnotation.phone
//        calloutView.starbucksImage.image = starbucksAnnotation.image
//        let button = UIButton(frame: calloutView.starbucksPhone.frame)
//        button.addTarget(self, action: #selector(ViewController.callPhoneNumber(sender:)), for: .touchUpInside)
//        calloutView.addSubview(button)
//        // 3
//        calloutView.center = CGPoint(x: view.bounds.size.width / 2, y: -calloutView.bounds.size.height*0.52)
//        view.addSubview(calloutView)
//        mapView.setCenter((view.annotation?.coordinate)!, animated: true)
    }

    func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
        if #available(iOS 11.0, *) {
            if view.isKind(of: ClusterView.self)
            {
                for subview in view.subviews
                {
                    subview.removeFromSuperview()
                }
            }
        } else {
            // Fallback on earlier versions
        }
    }

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView,
                 calloutAccessoryControlTapped control: UIControl) {
//        let location = view.annotation as! UserAnnotation
//        let launchOptions = [MKLaunchOptionsDirectionsModeKey:
//            MKLaunchOptionsDirectionsModeDriving]
//        location.mapItem().openInMaps(launchOptions: launchOptions)
    }
}
</code>```

This is how I am setting up mapView....

```<code>fileprivate func setupMapsLayout() {

    if self.userAnnotationList.count > 0 {
    // HereMap
        self.mapView.removeAnnotations(self.userAnnotationList)
    }

    self.mapView.delegate = self
    //    mapView.register(ArtworkMarkerView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
    if #available(iOS 11.0, *) {
        // HereMap
        //self.mapView.register(UserAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
        mapView.register(ClusterView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier)
    } else {
        // Fallback on earlier versions
    }

    self.loadInitialData()

    self.mapView.addAnnotations(self.userAnnotationList)
    //self.mapView.topCenterCoordinate()
}
</code>```

答:
OK, the iOS 11 and later solution is fairly simple. You have two annotation views, one for your own annotations, and one for clusters of annotations. Your main annotation view simply has to specify the clusteringIdentifier when it’s initialized and when the annotation property changes:

```<code>class UserAnnotationView: MKMarkerAnnotationView {
    static let preferredClusteringIdentifier = Bundle.main.bundleIdentifier! + ".UserAnnotationView"

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        clusteringIdentifier = UserAnnotationView.preferredClusteringIdentifier
        collisionMode = .circle
    }

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

    override var annotation: MKAnnotation? {
        willSet {
            clusteringIdentifier = UserAnnotationView.preferredClusteringIdentifier
        }
    }
}
</code>```

And your cluster annotation view should just update its image when its annotation property is updated:

```<code>class UserClusterAnnotationView: MKAnnotationView {
    static let preferredClusteringIdentifier = Bundle.main.bundleIdentifier! + ".UserClusterAnnotationView"

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        collisionMode = .circle
        updateImage()
    }

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

    override var annotation: MKAnnotation? { didSet { updateImage() } }

    private func updateImage() {
        if let clusterAnnotation = annotation as? MKClusterAnnotation {
            self.image = image(count: clusterAnnotation.memberAnnotations.count)
        } else {
            self.image = image(count: 1)
        }
    }

    func image(count: Int) -> UIImage {
        let bounds = CGRect(origin: .zero, size: CGSize(width: 40, height: 40))

        let renderer = UIGraphicsImageRenderer(bounds: bounds)
        return renderer.image { _ in
            // Fill full circle with tricycle color
            AppTheme.blueColor.setFill()
            UIBezierPath(ovalIn: bounds).fill()

            // Fill inner circle with white color
            UIColor.white.setFill()
            UIBezierPath(ovalIn: bounds.insetBy(dx: 8, dy: 8)).fill()

            // Finally draw count text vertically and horizontally centered
            let attributes: [NSAttributedString.Key: Any] = [
                .foregroundColor: UIColor.black,
                .font: UIFont.boldSystemFont(ofSize: 20)
            ]

            let text = "\(count)"
            let size = text.size(withAttributes: attributes)
            let origin = CGPoint(x: bounds.midX - size.width / 2, y: bounds.midY - size.height / 2)
            let rect = CGRect(origin: origin, size: size)
            text.draw(in: rect, withAttributes: attributes)
        }
    }
}
</code>```

Then, all you have to do is register your classes:

```<code>mapView.register(UserAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
mapView.register(UserClusterAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier)
</code>```

No mapView(_:viewFor:) implementation is needed (nor desired). But the above yields (showing the default animation as you zoom out and back in):

Now, clearly, you can modify your UserAnnotationView however you want. (Your question didn’t indicate what the standard, single user annotation view would look like). But by setting its clusteringIdentifier and registering a MKMapViewDefaultClusterAnnotationViewReuseIdentifier you get clustering fairly easily in iOS 11 and later.

If you really want to make the cluster annotation views look like the standard annotation views, you can register the same annotation view class for both:

```<code>mapView.register(UserClusterAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
mapView.register(UserClusterAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier)
</code>```

But you then have to give the cluster annotation view the same clusteringIdentifier that we previously gave to the standard annotation view:

```<code>class UserClusterAnnotationView: MKAnnotationView {
    static let preferredClusteringIdentifier = Bundle.main.bundleIdentifier! + ".UserClusterAnnotationView"

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        clusteringIdentifier = UserClusterAnnotationView.preferredClusteringIdentifier
        collisionMode = .circle
        updateImage()
    }

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

    override var annotation: MKAnnotation? {
        didSet {
            clusteringIdentifier = UserClusterAnnotationView.preferredClusteringIdentifier
            updateImage()
        }
    }

    private func updateImage() {
        if let clusterAnnotation = annotation as? MKClusterAnnotation {
            self.image = image(count: clusterAnnotation.memberAnnotations.count)
        } else {
            self.image = image(count: 1)
        }
    }

    func image(count: Int) -> UIImage {
        let bounds = CGRect(origin: .zero, size: CGSize(width: 40, height: 40))

        let renderer = UIGraphicsImageRenderer(bounds: bounds)
        return renderer.image { _ in
            // Fill full circle with tricycle color
            AppTheme.blueColor.setFill()
            UIBezierPath(ovalIn: bounds).fill()

            // Fill inner circle with white color
            UIColor.white.setFill()
            UIBezierPath(ovalIn: bounds.insetBy(dx: 8, dy: 8)).fill()

            // Finally draw count text vertically and horizontally centered
            let attributes: [NSAttributedString.Key: Any] = [
                .foregroundColor: UIColor.black,
                .font: UIFont.boldSystemFont(ofSize: 20)
            ]

            let text = "\(count)"
            let size = text.size(withAttributes: attributes)
            let origin = CGPoint(x: bounds.midX - size.width / 2, y: bounds.midY - size.height / 2)
            let rect = CGRect(origin: origin, size: size)
            text.draw(in: rect, withAttributes: attributes)
        }
    }
}
</code>```

That yields:

Personally, I think that’s a little confusing, but if that’s what you’re going for, that’s one way to achieve it.

Now, if you really need to support iOS versions prior to 11 and you want clustering, then you’ll have to do all this clustering logic yourself (or find third party library to do it). Apple shows how to do this in WWDC 2011 Visualizing Information Geographically with MapKit. The concept they employ is the notion of dividing the visible map into a grid, and if there are multiple annotations within a particular grid, they remove them and add a single “cluster”  annotation. And they illustrate how you might even visually animate the moving of the annotations in and out of the cluster, so the user can understand what's going on as they zoom in and out. It's a nice starting point as you dive into this.

This is non-trivial, so I’d think long and hard about whether I wanted to implement this myself. I’d either abandon iOS versions prior to 11 or find a third-party implementation (and that question you reference has plenty of examples).

Body:
before duplicating my questing please read the whole thing.
i am using MkMapKit in my app and now I have to show people in cluster when zoom out the map, I have achieved numbering them out so far using from this answer using Apple's default clustering class. now I have no idea how to add and show them all one circle with there count, i know something that it should relate with radius but i don't know how can i do that, sharing my code below, i hope any help would be appreciated. thanks
also showing picture of what i have done :

This is my UserAnnotationClass

class UserAnnotation: NSObject, MKAnnotation {

    let title: String?
    let locationName: String
    let discipline: String
    let coordinate: CLLocationCoordinate2D

    let userProfile: UserProfile!
    let index: Int!
    let memberAnnotations: [UserProfile]!
    init(userProfile: UserProfile, at index: Int) {

        self.title = userProfile.fullName
        self.locationName = (userProfile.locationAddress != nil) ? userProfile.locationAddress : ""
        let userProfilePicture: String = (userProfile.profilePicture == nil || userProfile.profilePicture == "") ? "" : userProfile.profilePicture

        self.discipline = userProfilePicture

       // print("\(userProfile.fullName) \(userProfile.location.dist)")

        if (userProfile.isMapVisibility == true) {
            self.coordinate = CLLocationCoordinate2D(latitude: userProfile.location.lat, longitude: userProfile.location.lon)
        } else {
            self.coordinate = CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)
        }
        memberAnnotations = [UserProfile]()
        memberAnnotations.append(userProfile)
        self.userProfile = userProfile
        self.index = index

        super.init()
    }

    var subtitle: String? {
        return locationName
    }

    // pinTintColor for disciplines: Sculpture, Plaque, Mural, Monument, other
    var markerTintColor: UIColor  {
        switch discipline {
        case "Monument":
            return .red
        case "Mural":
            return .cyan
        case "Plaque":
            return .blue
        case "Sculpture":
            return .purple
        default:
            return .clear
        }
    }

    // Annotation right callout accessory opens this mapItem in Maps app
    func mapItem() -> MKMapItem {
        let addressDict = [CNPostalAddressStreetKey: subtitle!]
        let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDict)
        let mapItem = MKMapItem(placemark: placemark)
        mapItem.name = title

        return mapItem
    }
}

And This is the CLusterViewClass i am using to make them clustered .

class ClusterView: MKAnnotationView {

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let hitView = super.hitTest(point, with: event)
        if (hitView != nil)
        {

            if (hitView?.isKind(of: UIButton.self))! {

                let sender: UIButton = hitView as! UIButton

                sender.sendActions(for: .touchUpInside)

            }
            else {

                self.superview?.bringSubviewToFront(self)
            }
        }
        return hitView
    }
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let rect = self.bounds
        var isInside: Bool = rect.contains(point)
        if(!isInside)
        {
            for view in self.subviews
            {
                isInside = view.frame.contains(point)
                if isInside
                {
                    break
                }
            }
        }
        return isInside
    }
    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        displayPriority = .defaultHigh
        collisionMode = .circle
        centerOffset = CGPoint(x: 0, y: -10) // Offset center point to animate better with marker annotations
    }

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

    override var annotation: MKAnnotation? {
        willSet {

            canShowCallout = false

            if let cluster = newValue as? UserAnnotation {
                let renderer = UIGraphicsImageRenderer(size: CGSize(width: 40, height: 40))
                let count = cluster.memberAnnotations.count
                let uniCount = cluster.memberAnnotations.filter { member -> Bool in
                    //Log("Bool  \(member) , \(member.isMapVisibility == false) ")

                    return member.isMapVisibility == true
                }.count
                //Log("COUNTS \(count) , \(uniCount) ❤")
                image = renderer.image { _ in
                    // Fill full circle with tricycle color
                    if uniCount > 0 {

                        AppTheme.blueColor.setFill()
                        UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 40, height: 40)).fill()

                        // Fill inner circle with white color
                        UIColor.white.setFill()
                        UIBezierPath(ovalIn: CGRect(x: 8, y: 8, width: 24, height: 24)).fill()

                        // Finally draw count text vertically and horizontally centered
                        let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.black,
                                           NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20)]
                        //let text = "\(count)"
                        let text = "4"
                        let size = text.size(withAttributes: attributes)
                        let rect = CGRect(x: 20 - size.width / 2, y: 20 - size.height / 2, width: size.width, height: size.height)
                        text.draw(in: rect, withAttributes: attributes)
                    }
                }
            }
        }
    }

}

And these are some of my MapKit Functions

extension FeedsViewController: MKMapViewDelegate {

    //   1
      func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        guard let annotation = annotation as? UserAnnotation else { return nil }
        // 2
        let identifier = "marker"
        if #available(iOS 11.0, *) {
            var view: ClusterView

            if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
                as? ClusterView { // 3
                dequeuedView.annotation = annotation
                view = dequeuedView
            } else {
                // 4
                view = ClusterView(annotation: annotation, reuseIdentifier: identifier)
            }
            return view
        } else {
            // Fallback on earlier versions

            return nil
        }

      }
    func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
//        let zoomWidth = mapView.visibleMapRect.size.width
//        let zoomFactor = Int(log2(zoomWidth))
//        print("...REGION DID CHANGE: ZOOM FACTOR \(zoomFactor)")
        let centralLocation = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude:  mapView.centerCoordinate.longitude)

        Log(" Radius - \(self.getRadius(centralLocation: centralLocation))")

    }
    func getRadius(centralLocation: CLLocation) -> Double{
        let topCentralLat:Double = centralLocation.coordinate.latitude -  mapView.region.span.latitudeDelta/2
        let topCentralLocation = CLLocation(latitude: topCentralLat, longitude: centralLocation.coordinate.longitude)
        let radius = centralLocation.distance(from: topCentralLocation)
        return radius / 1000.0 // to convert radius to meters
    }
    func mapView(_ mapView: MKMapView,
                 didSelect view: MKAnnotationView)
    {
        // 1
        if view.annotation is MKUserLocation
        {
            // Don't proceed with custom callout
            return
        }
        // 2
        let annotation = view.annotation as! UserAnnotation

        let detailAnnotationView: UserDetailAnnotationView = UserDetailAnnotationView(frame: CGRect(x: 0, y: 0, width: 320, height: 74))

        let url = (annotation.discipline == "") ? nil : URL(string: annotation.discipline)!
        let range = 0.0..<0.9
        if annotation.userProfile.location.dist != nil {
            if range.contains(annotation.userProfile.location.dist) {
                let kMeters = Measurement(value: annotation.userProfile.location.dist, unit: UnitLength.kilometers)
                let meters = kMeters.converted(to: UnitLength.meters)
                detailAnnotationView.distancelbl.text = "\(String(describing: round(Double(meters.value)))) m Away"

            } else {
                detailAnnotationView.distancelbl.text = "\(String(describing: round(annotation.userProfile.location.dist))) Km Away"
            }
        }

        detailAnnotationView.set(Title: annotation.title!, imageUrl: url) { [weak self] (sender) in
            guard let self = self else { return }
            if self.isOpenChat {

                self.isOpenChat = false

                if annotation.userProfile.channel != "" {

                    self.appDelegate.pubNubAddPushNotifications([annotation.userProfile.channel]) { (status) in

                        print(status.description)
                    }

                    let chatViewController: ChatViewController = self.storyboard?.instantiateViewController(withIdentifier: "ChatViewController") as! ChatViewController

                    chatViewController.userProfile = annotation.userProfile
                    chatViewController.loginUserProfile = self.loginUserProfile
                    self.navigationController?.pushViewController(chatViewController, animated: true)
                }
            }

        }

        detailAnnotationView.center = CGPoint(x: view.bounds.size.width / 2, y: -detailAnnotationView.bounds.size.height*0.52)

        view.addSubview(detailAnnotationView)

        mapView.setCenter((view.annotation?.coordinate)!, animated: true)

//        let calloutView = views?[0] as! CustomCalloutView
//        calloutView.starbucksName.text = starbucksAnnotation.name
//        calloutView.starbucksAddress.text = starbucksAnnotation.address
//        calloutView.starbucksPhone.text = starbucksAnnotation.phone
//        calloutView.starbucksImage.image = starbucksAnnotation.image
//        let button = UIButton(frame: calloutView.starbucksPhone.frame)
//        button.addTarget(self, action: #selector(ViewController.callPhoneNumber(sender:)), for: .touchUpInside)
//        calloutView.addSubview(button)
//        // 3
//        calloutView.center = CGPoint(x: view.bounds.size.width / 2, y: -calloutView.bounds.size.height*0.52)
//        view.addSubview(calloutView)
//        mapView.setCenter((view.annotation?.coordinate)!, animated: true)
    }

    func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
        if #available(iOS 11.0, *) {
            if view.isKind(of: ClusterView.self)
            {
                for subview in view.subviews
                {
                    subview.removeFromSuperview()
                }
            }
        } else {
            // Fallback on earlier versions
        }
    }

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView,
                 calloutAccessoryControlTapped control: UIControl) {
//        let location = view.annotation as! UserAnnotation
//        let launchOptions = [MKLaunchOptionsDirectionsModeKey:
//            MKLaunchOptionsDirectionsModeDriving]
//        location.mapItem().openInMaps(launchOptions: launchOptions)
    }
}

This is how I am setting up mapView....

fileprivate func setupMapsLayout() {

    if self.userAnnotationList.count > 0 {
    // HereMap
        self.mapView.removeAnnotations(self.userAnnotationList)
    }

    self.mapView.delegate = self
    //    mapView.register(ArtworkMarkerView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
    if #available(iOS 11.0, *) {
        // HereMap
        //self.mapView.register(UserAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
        mapView.register(ClusterView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier)
    } else {
        // Fallback on earlier versions
    }

    self.loadInitialData()

    self.mapView.addAnnotations(self.userAnnotationList)
    //self.mapView.topCenterCoordinate()
}

Body:
OK, the iOS 11 and later solution is fairly simple. You have two annotation views, one for your own annotations, and one for clusters of annotations. Your main annotation view simply has to specify the clusteringIdentifier when it’s initialized and when the annotation property changes:

class UserAnnotationView: MKMarkerAnnotationView {
    static let preferredClusteringIdentifier = Bundle.main.bundleIdentifier! + ".UserAnnotationView"

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        clusteringIdentifier = UserAnnotationView.preferredClusteringIdentifier
        collisionMode = .circle
    }

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

    override var annotation: MKAnnotation? {
        willSet {
            clusteringIdentifier = UserAnnotationView.preferredClusteringIdentifier
        }
    }
}

And your cluster annotation view should just update its image when its annotation property is updated:

class UserClusterAnnotationView: MKAnnotationView {
    static let preferredClusteringIdentifier = Bundle.main.bundleIdentifier! + ".UserClusterAnnotationView"

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        collisionMode = .circle
        updateImage()
    }

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

    override var annotation: MKAnnotation? { didSet { updateImage() } }

    private func updateImage() {
        if let clusterAnnotation = annotation as? MKClusterAnnotation {
            self.image = image(count: clusterAnnotation.memberAnnotations.count)
        } else {
            self.image = image(count: 1)
        }
    }

    func image(count: Int) -> UIImage {
        let bounds = CGRect(origin: .zero, size: CGSize(width: 40, height: 40))

        let renderer = UIGraphicsImageRenderer(bounds: bounds)
        return renderer.image { _ in
            // Fill full circle with tricycle color
            AppTheme.blueColor.setFill()
            UIBezierPath(ovalIn: bounds).fill()

            // Fill inner circle with white color
            UIColor.white.setFill()
            UIBezierPath(ovalIn: bounds.insetBy(dx: 8, dy: 8)).fill()

            // Finally draw count text vertically and horizontally centered
            let attributes: [NSAttributedString.Key: Any] = [
                .foregroundColor: UIColor.black,
                .font: UIFont.boldSystemFont(ofSize: 20)
            ]

            let text = "\(count)"
            let size = text.size(withAttributes: attributes)
            let origin = CGPoint(x: bounds.midX - size.width / 2, y: bounds.midY - size.height / 2)
            let rect = CGRect(origin: origin, size: size)
            text.draw(in: rect, withAttributes: attributes)
        }
    }
}

Then, all you have to do is register your classes:

mapView.register(UserAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
mapView.register(UserClusterAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier)

No mapView(_:viewFor:) implementation is needed (nor desired). But the above yields (showing the default animation as you zoom out and back in):

Now, clearly, you can modify your UserAnnotationView however you want. (Your question didn’t indicate what the standard, single user annotation view would look like). But by setting its clusteringIdentifier and registering a MKMapViewDefaultClusterAnnotationViewReuseIdentifier you get clustering fairly easily in iOS 11 and later.

If you really want to make the cluster annotation views look like the standard annotation views, you can register the same annotation view class for both:

mapView.register(UserClusterAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
mapView.register(UserClusterAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier)

But you then have to give the cluster annotation view the same clusteringIdentifier that we previously gave to the standard annotation view:

class UserClusterAnnotationView: MKAnnotationView {
    static let preferredClusteringIdentifier = Bundle.main.bundleIdentifier! + ".UserClusterAnnotationView"

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        clusteringIdentifier = UserClusterAnnotationView.preferredClusteringIdentifier
        collisionMode = .circle
        updateImage()
    }

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

    override var annotation: MKAnnotation? {
        didSet {
            clusteringIdentifier = UserClusterAnnotationView.preferredClusteringIdentifier
            updateImage()
        }
    }

    private func updateImage() {
        if let clusterAnnotation = annotation as? MKClusterAnnotation {
            self.image = image(count: clusterAnnotation.memberAnnotations.count)
        } else {
            self.image = image(count: 1)
        }
    }

    func image(count: Int) -> UIImage {
        let bounds = CGRect(origin: .zero, size: CGSize(width: 40, height: 40))

        let renderer = UIGraphicsImageRenderer(bounds: bounds)
        return renderer.image { _ in
            // Fill full circle with tricycle color
            AppTheme.blueColor.setFill()
            UIBezierPath(ovalIn: bounds).fill()

            // Fill inner circle with white color
            UIColor.white.setFill()
            UIBezierPath(ovalIn: bounds.insetBy(dx: 8, dy: 8)).fill()

            // Finally draw count text vertically and horizontally centered
            let attributes: [NSAttributedString.Key: Any] = [
                .foregroundColor: UIColor.black,
                .font: UIFont.boldSystemFont(ofSize: 20)
            ]

            let text = "\(count)"
            let size = text.size(withAttributes: attributes)
            let origin = CGPoint(x: bounds.midX - size.width / 2, y: bounds.midY - size.height / 2)
            let rect = CGRect(origin: origin, size: size)
            text.draw(in: rect, withAttributes: attributes)
        }
    }
}

That yields:

Personally, I think that’s a little confusing, but if that’s what you’re going for, that’s one way to achieve it.

Now, if you really need to support iOS versions prior to 11 and you want clustering, then you’ll have to do all this clustering logic yourself (or find third party library to do it). Apple shows how to do this in WWDC 2011 Visualizing Information Geographically with MapKit. The concept they employ is the notion of dividing the visible map into a grid, and if there are multiple annotations within a particular grid, they remove them and add a single “cluster”  annotation. And they illustrate how you might even visually animate the moving of the annotations in and out of the cluster, so the user can understand what's going on as they zoom in and out. It's a nice starting point as you dive into this.

This is non-trivial, so I’d think long and hard about whether I wanted to implement this myself. I’d either abandon iOS versions prior to 11 or find a third-party implementation (and that question you reference has plenty of examples).


问:
How do I Check if an email address is real or fake in flutter
I use createUserWithEmailAndPassword(string, string) in flutter, but I noticed if the user used a fake email address, like making us some random Gmail or yahoo account that doesn't exist, the user would still be registered, is there a solution to this

Or some logic that checks if the email account is real, then I can use the result in an if else statement to create the account

答:
If you are looking for a solution that doesn't involve blocking the user experience, you'll be disappointed. We could come up with a new solution for checking whether an email exists or not, but this doesn't guarantee you anything. The user may use an existing email that doesn't belong to him/her.

The best you can do is send a verification email to your user, which is supported by Firebase. However, the user experience is going to be blocked until the user verifies the email.

Update

Check here how to send the user the verification email and here how to see if the email has been verified.


问:
Aggregation and Grouping with Pandas
I am trying to add a column of values based on account numbers and have the result show in a new column. Also, I'm identifying the first instance of the contract account as a Unique value and the others as duplicates.
For example:

```<code>Index   CA#   Duplicate?    $     $$
1      1101   True        440.4  880.80
2      1101   False       440.4  -
3      1102   True        440.8  440.80
4      1103   True        441.2  441.20
5      1106   True        442.4  1,327.20
6      1106   False       442.4  -
7      1106   False       442.4  -
</code>```

My first column 'CA#' are identifiers that I want to flag as True(or 1) if they're the first and only CA#, otherwise, I want them flagged as False(or 0).
For instance, CA# 1101 on Index 1 would receive a True and CA# 1101 on Index 2 would receive a False.

Then I'm trying to use that True flag to sum the total that each CA# is linked to on the $ column. In the CA#1101 case, the total $$ is 880.80.
So far I have only got as far as trying to generate a new column that has the boolean identifier for the unique values on the CA# column, but I get only True values on the new series that my code creates and I know that is wrong.

```<code>import pandas as pd
from pandas import DataFrame, Series
import numpy as np

file_name= ('A:\LEO\Documents\Mock data.xlsx')
sheet_name= ('Sheet1')
data = pd.read_excel(io= file_name, sheet= sheet_name)
data.sort_values('CA#', inplace= True)
data_ltd = DataFrame(data, columns=['CA#','$'])
bool_series = data_ltd['CA'].duplicated()
data_ltd ['bool_series'] = bool_series
print(data_ltd[bool_series].head(10))
</code>```

答:
This should do the trick for the Duplicated column:

df = pd.DataFrame({'CA#': [1101, 1101, 1102,1103, 1106, 1106, 1106]})
seen = set()
def already(x):
    global seen
    if x in seen:
        return False
    else:
        seen.add(x)
        return True

df['Duplicate'] = df['CA#'].apply(already)
df
#     CA#  Duplicate
# 0  1101       True
# 1  1101      False
# 2  1102       True
# 3  1103       True
# 4  1106       True
# 5  1106      False
# 6  1106      False
```

Title: Aggregation and Grouping with Pandas

Body:
I am trying to add a column of values based on account numbers and have the result show in a new column. Also, I'm identifying the first instance of the contract account as a Unique value and the others as duplicates.
For example:

Index   CA#   Duplicate?    $     $$
1      1101   True        440.4  880.80
2      1101   False       440.4  -
3      1102   True        440.8  440.80
4      1103   True        441.2  441.20
5      1106   True        442.4  1,327.20
6      1106   False       442.4  -
7      1106   False       442.4  -

My first column 'CA#' are identifiers that I want to flag as True(or 1) if they're the first and only CA#, otherwise, I want them flagged as False(or 0).
For instance, CA# 1101 on Index 1 would receive a True and CA# 1101 on Index 2 would receive a False.

Then I'm trying to use that True flag to sum the total that each CA# is linked to on the $ column. In the CA#1101 case, the total $$ is 880.80.
So far I have only got as far as trying to generate a new column that has the boolean identifier for the unique values on the CA# column, but I get only True values on the new series that my code creates and I know that is wrong.

import pandas as pd
from pandas import DataFrame, Series
import numpy as np

file_name= ('A:\LEO\Documents\Mock data.xlsx')
sheet_name= ('Sheet1')
data = pd.read_excel(io= file_name, sheet= sheet_name)
data.sort_values('CA#', inplace= True)
data_ltd = DataFrame(data, columns=['CA#','$'])
bool_series = data_ltd['CA'].duplicated()
data_ltd ['bool_series'] = bool_series
print(data_ltd[bool_series].head(10))


问:
My program is not working. Main is not returning a value
Why is it saying main must return a value?
I have tried almost nothing because i dont know much about c++ and I dont understand the meaning behind the error msg</p>

```<code>#include<iostream>
using namespace std;

int main()
{
    // one acre equals 43560 square feet

    double oneacre = 43560;

    // one square meter equals 10.7639 square feet
    double squaremeter = 10.7639;

    double halfacre = 0.5;

    double sfiha = oneacre * halfacre;

    double smiha = sfiha * squaremeter;

    cout << "in half acre there is" << sfiha << "square feet" << endl;

    cout << "in half acre there is" << smiha << "square meters" << endl;
}
</code>```

答:
Add "return 0" at last line of the main's body.Since main is also a function and it's return type is "int". You've written int main()..So main will only end successfully by returning any integer value at last within the main's body. Generally 0 is returned as it signifies that program executed correctly and without errors. But you can try returning any integer value. Even -10 in place of 0 will work..
With return it also returns the control from the program's console to the OS or the IDE you're using .
You can return at any point,not necessarily at the last statement.Any statement after return will not be executed. Because control will no longer with program it'll be with OS again.You can try printing anything with printf in the next statements i.e., after return 0 and that won't be printed,you'll see. Give it a try!

You'll learn more about this return statement and return type i.e., int before main,when you'll study about functions. For now you think of it as it signifies the last statement to be executed,or ending of the program.

Body:
Why is it saying main must return a value?
I have tried almost nothing because i dont know much about c++ and I dont understand the meaning behind the error msg

#include<iostream>
using namespace std;

int main()
{
    // one acre equals 43560 square feet

    double oneacre = 43560;

    // one square meter equals 10.7639 square feet
    double squaremeter = 10.7639;

    double halfacre = 0.5;

    double sfiha = oneacre * halfacre;

    double smiha = sfiha * squaremeter;

    cout << "in half acre there is" << sfiha << "square feet" << endl;

    cout << "in half acre there is" << smiha << "square meters" << endl;
}