问:
Aggregate features by distance in sf objects
I have two sf objects: polygon county (note: this is a multiple polygon, i.e. many counties) and points monitor2.

The county looks like below. Chinese characters cannot be displayed properly, but it's not a big deal.

```<code>Simple feature collection with 6 features and 4 fields
geometry type:  MULTIPOLYGON
dimension:      XY
bbox:           xmin: 113.15 ymin: 20.58265 xmax: 124.5656 ymax: 40.10793
epsg (SRID):    4326
proj4string:    +proj=longlat +datum=WGS84 +no_defs
                      City                 District                 Province   Code                       geometry
1 <U+53F0><U+6E7E><U+7701> <U+53F0><U+6E7E><U+7701> <U+53F0><U+6E7E><U+7701> 710000 MULTIPOLYGON (((116.7346 20...
2 <U+5317><U+4EAC><U+5E02> <U+671D><U+9633><U+533A> <U+5317><U+4EAC><U+5E02> 110105 MULTIPOLYGON (((116.4834 40...
3 <U+4E0A><U+6D77><U+5E02> <U+666E><U+9640><U+533A> <U+4E0A><U+6D77><U+5E02> 310107 MULTIPOLYGON (((121.3562 31...
4 <U+4E0A><U+6D77><U+5E02> <U+5B9D><U+5C71><U+533A> <U+4E0A><U+6D77><U+5E02> 230506 MULTIPOLYGON (((121.4855 31...
5 <U+5E7F><U+5DDE><U+5E02> <U+767D><U+4E91><U+533A> <U+5E7F><U+4E1C><U+7701> 440111 MULTIPOLYGON (((113.4965 23...
6 <U+798F><U+5DDE><U+5E02> <U+9F13><U+697C><U+533A> <U+798F><U+5EFA><U+7701> 320106 MULTIPOLYGON (((119.2611 26...
</code>```

The monitor2 looks like below.

```<code>Simple feature collection with 6 features and 5 fields
geometry type:  POINT
dimension:      XY
bbox:           xmin: 116.17 ymin: 39.8673 xmax: 116.473 ymax: 40.2865
epsg (SRID):    4326
proj4string:    +proj=longlat +datum=WGS84 +no_defs
# A tibble: 6 x 6
  code  name     city  ref   value          geometry
  <chr> <chr>    <chr> <chr> <dbl>       <POINT [°]>
1 1001A 万寿西宫 北京  N      47.8 (116.366 39.8673)
2 1002A 定陵     北京  Y      45.9  (116.17 40.2865)
3 1003A 东四     北京  N      42.2 (116.434 39.9522)
4 1004A 天坛     北京  N      51.2 (116.434 39.8745)
5 1005A 农展馆   北京  N      46.9 (116.473 39.9716)
6 1006A 官园     北京  N      49.5 (116.361 39.9425)

</code>```

The first task is to join the value feature in monitor2 to county. I did this with st_is_within_distance and st_join. See the code below. I set distance to be 50 km. Some counties in the new polygon may have values from multiple points within the 50 km buffer.

```<code>new = st_join(county, monitor2,
            join = st_is_within_distance, dist = 50)
</code>```

Here comes the second task. I need to aggregate values from different points within that 50 km buffer by their distances to the centroid of the county. How do I achieve this task?

Any comments are welcome.

答:
It's difficult to know exactly what you want without reproducible data, but here's an attempt to show how you can do this.

Get sample data. We reproject here from lat/long to something with metres so we can do distance based spatial operations. We'll use 3 counties from the sample data and use the middle county as the main polygon we want to measure distances from and add a random sample of points scattered across the three counties.

```<code>library(sf)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
nc <- st_transform(nc, 32119) # NC state plane projection in metres
county = st_cast(nc[2,],"POLYGON")
p1 = st_as_sf(st_sample(nc[1:3, ], 200)) # random points

# Visualize
plot(st_geometry(nc)[1:3])
plot(county, col = "grey80", add = TRUE)
</code>```

We want to focus only on points within some distance from our target county. Let's see what that looks like by adding a buffer using st_buffer.

```<code>plot(st_buffer(county, dist = 10000), col = NA, border = "red", lty = 3, add = TRUE)
</code>```

We can subset the points within 10000m of the central county by using st_is_within_distance which would accomplish the same as doing an intersect with the st_buffer object.

```<code>p1_10 <- p1[st_is_within_distance(county,p1,dist = 10000, sparse = FALSE),]
</code>```

Measuring distance between the centroid and each element of this subset is straight forward. We can then assign the distance measurement as a variable in the subset spatial object.

```<code>p1_10$distance_to_centroid <- as.vector(st_distance(st_centroid(county), p1_10))
</code>```

Here's what that looks like plotted altogether

```<code>plot(st_geometry(nc)[1:3])
plot(county, col = "grey80", add = TRUE)
plot(p1, add = TRUE, pch = 19)
plot(st_buffer(county, dist = 10000), col = NA, border = "red", lty = 3, add = TRUE)
plot(st_centroid(county), col = "red", pch = 15, cex = 1, axes = TRUE, add = TRUE)
plot(p1_10["distance_to_centroid"], add = TRUE, pch = 19)
</code>```

This is what the p1_10 obj looks like here:

```<code>> p1_10
Simple feature collection with 78 features and 1 field
geometry type:  POINT
dimension:      XY
bbox:           xmin: 389967.6 ymin: 293489.4 xmax: 448197.1 ymax: 315140.7
CRS:            EPSG:32119
First 10 features:
                           x distance_to_centroid
1  POINT (437228.1 294079.7)           21703.5425
2  POINT (425029.8 305656.7)            5868.4917
3  POINT (425131.4 309137.8)            6665.0253
4  POINT (409851.2 294971.7)           14549.0585
5  POINT (393070.6 303879.7)           26207.5651
6  POINT (436666.3 296282.2)           20070.5879
7  POINT (442623.8 295976.3)           25549.5662
8  POINT (400517.2 307897.4)           18746.6918
9    POINT (418763.7 306728)             724.6165
10 POINT (405001.4 294845.7)           18125.0738
</code>```

So from here you can aggregate your features by distance using whatever method you want. In dplyr, it's pretty straightforward. Suppose for example here I wanted to aggregate in 5km intervals.

```<code>library(dplyr)
p1_10 %>%
  mutate(dist_group = ceiling(distance_to_centroid/5000)) %>%
  group_by(dist_group) %>%
  tally() %>% # stop here if you want the result to retain geography
  as_tibble() %>%
  select(dist_group, n)
</code>```

```<code># A tibble: 7 x 2
  dist_group     n
       <dbl> <int>
1          1     7
2          2    15
3          3    22
4          4    13
5          5    11
6          6     9
7          7     1
</code>```

Body:
I have two sf objects: polygon county (note: this is a multiple polygon, i.e. many counties) and points monitor2.

The county looks like below. Chinese characters cannot be displayed properly, but it's not a big deal.

Simple feature collection with 6 features and 4 fields
geometry type:  MULTIPOLYGON
dimension:      XY
bbox:           xmin: 113.15 ymin: 20.58265 xmax: 124.5656 ymax: 40.10793
epsg (SRID):    4326
proj4string:    +proj=longlat +datum=WGS84 +no_defs
                      City                 District                 Province   Code                       geometry
1    710000 MULTIPOLYGON (((116.7346 20...
2    110105 MULTIPOLYGON (((116.4834 40...
3    310107 MULTIPOLYGON (((121.3562 31...
4    230506 MULTIPOLYGON (((121.4855 31...
5    440111 MULTIPOLYGON (((113.4965 23...
6    320106 MULTIPOLYGON (((119.2611 26...

The monitor2 looks like below.

Simple feature collection with 6 features and 5 fields
geometry type:  POINT
dimension:      XY
bbox:           xmin: 116.17 ymin: 39.8673 xmax: 116.473 ymax: 40.2865
epsg (SRID):    4326
proj4string:    +proj=longlat +datum=WGS84 +no_defs
# A tibble: 6 x 6
  code  name     city  ref   value          geometry
  <chr> <chr>    <chr> <chr> <dbl>       <POINT [°]>
1 1001A 万寿西宫 北京  N      47.8 (116.366 39.8673)
2 1002A 定陵     北京  Y      45.9  (116.17 40.2865)
3 1003A 东四     北京  N      42.2 (116.434 39.9522)
4 1004A 天坛     北京  N      51.2 (116.434 39.8745)
5 1005A 农展馆   北京  N      46.9 (116.473 39.9716)
6 1006A 官园     北京  N      49.5 (116.361 39.9425)

The first task is to join the value feature in monitor2 to county. I did this with st_is_within_distance and st_join. See the code below. I set distance to be 50 km. Some counties in the new polygon may have values from multiple points within the 50 km buffer.

new = st_join(county, monitor2,
            join = st_is_within_distance, dist = 50)

Here comes the second task. I need to aggregate values from different points within that 50 km buffer by their distances to the centroid of the county. How do I achieve this task?

Any comments are welcome.

Body:
It's difficult to know exactly what you want without reproducible data, but here's an attempt to show how you can do this.

Get sample data. We reproject here from lat/long to something with metres so we can do distance based spatial operations. We'll use 3 counties from the sample data and use the middle county as the main polygon we want to measure distances from and add a random sample of points scattered across the three counties.

library(sf)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
nc <- st_transform(nc, 32119) # NC state plane projection in metres
county = st_cast(nc[2,],"POLYGON")
p1 = st_as_sf(st_sample(nc[1:3, ], 200)) # random points

# Visualize
plot(st_geometry(nc)[1:3])
plot(county, col = "grey80", add = TRUE)

We want to focus only on points within some distance from our target county. Let's see what that looks like by adding a buffer using st_buffer.

plot(st_buffer(county, dist = 10000), col = NA, border = "red", lty = 3, add = TRUE)

We can subset the points within 10000m of the central county by using st_is_within_distance which would accomplish the same as doing an intersect with the st_buffer object.

p1_10 <- p1[st_is_within_distance(county,p1,dist = 10000, sparse = FALSE),]

Measuring distance between the centroid and each element of this subset is straight forward. We can then assign the distance measurement as a variable in the subset spatial object.

p1_10$distance_to_centroid <- as.vector(st_distance(st_centroid(county), p1_10))

Here's what that looks like plotted altogether

plot(st_geometry(nc)[1:3])
plot(county, col = "grey80", add = TRUE)
plot(p1, add = TRUE, pch = 19)
plot(st_buffer(county, dist = 10000), col = NA, border = "red", lty = 3, add = TRUE)
plot(st_centroid(county), col = "red", pch = 15, cex = 1, axes = TRUE, add = TRUE)
plot(p1_10["distance_to_centroid"], add = TRUE, pch = 19)

This is what the p1_10 obj looks like here:

> p1_10
Simple feature collection with 78 features and 1 field
geometry type:  POINT
dimension:      XY
bbox:           xmin: 389967.6 ymin: 293489.4 xmax: 448197.1 ymax: 315140.7
CRS:            EPSG:32119
First 10 features:
                           x distance_to_centroid
1  POINT (437228.1 294079.7)           21703.5425
2  POINT (425029.8 305656.7)            5868.4917
3  POINT (425131.4 309137.8)            6665.0253
4  POINT (409851.2 294971.7)           14549.0585
5  POINT (393070.6 303879.7)           26207.5651
6  POINT (436666.3 296282.2)           20070.5879
7  POINT (442623.8 295976.3)           25549.5662
8  POINT (400517.2 307897.4)           18746.6918
9    POINT (418763.7 306728)             724.6165
10 POINT (405001.4 294845.7)           18125.0738

So from here you can aggregate your features by distance using whatever method you want. In dplyr, it's pretty straightforward. Suppose for example here I wanted to aggregate in 5km intervals.

library(dplyr)
p1_10 %>%
  mutate(dist_group = ceiling(distance_to_centroid/5000)) %>%
  group_by(dist_group) %>%
  tally() %>% # stop here if you want the result to retain geography
  as_tibble() %>%
  select(dist_group, n)

# A tibble: 7 x 2
  dist_group     n
       <dbl> <int>
1          1     7
2          2    15
3          3    22
4          4    13
5          5    11
6          6     9
7          7     1


来源: stackexchange

问:
Scrolling multiple Tkinter listboxes together
I have multiple Tkinter listboxes that I have scrolling together using a single scrollbar, but I'd ALSO like them to scroll together for mousewheel activity over any of the listboxes.

How to do this?

My current code is based on the last pattern discussed here: http://effbot.org/tkinterbook/listbox.htm  It works fine when using only the scrollbar, but the listboxes scroll independently when the mousewheel is used.

答:
I've made a very simple procedural solution. After looking on the tutorials point site for information on how to use the scrollbar for one widget (https://www.tutorialspoint.com/python/tk_scrollbar.htm), I adapted it to scroll through multiple text boxes at the same time (you can change the code so it uses list boxes). This solution will update all three textboxes when you use the scroll bar.</p>

```<code>import tkinter as tk

HEIGHT = 200
WIDTH = 300

def scroll(x, y):
    l_textbox.yview(x,y)
    m_textbox.yview(x,y)
    r_textbox.yview(x,y)

root = tk.Tk()

canvas = tk.Canvas(root,height = HEIGHT, width = WIDTH, bg = "white")
canvas.pack()

frame = tk.Frame(root, bg ='white')
frame.place(relx=0,rely=0,relwidth=1,relheight=1)

scrollbar = tk.Scrollbar(frame)

l_label = tk.Label (frame, text = "Left")
l_label.place(relx=0, rely=0)

m_label = tk.Label (frame, text= "Middle")
m_label.place(relx=0.3, rely=0)

r_label = tk.Label (frame, text= "Right")
r_label.place(relx=0.6, rely=0)

l_textbox = tk.Text(frame, yscrollcommand = scrollbar.set)
l_textbox.config(font = ('Arial',9))
l_textbox.place(relx=0, rely=0.2,relwidth=0.3,relheight=0.8)

m_textbox = tk.Text(frame, yscrollcommand = scrollbar.set)
m_textbox.config(font = ('Arial',9))
m_textbox.place(relx=0.3, rely=0.2,relwidth=0.3,relheight=0.8)

r_textbox = tk.Text(frame, yscrollcommand = scrollbar.set)
r_textbox.config(font = ('Arial',9))
r_textbox.place(relx=0.6, rely=0.2,relwidth=0.3,relheight=0.8)

scrollbar.config( command = scroll)
scrollbar.place(relx = 0.9, relwidth = 0.1,relheight = 1)

for i in range(0, 100):
    l_textbox.insert(tk.INSERT, str(i)+"\n")
    m_textbox.insert(tk.INSERT, str(i)+"\n")
    r_textbox.insert(tk.INSERT, str(i)+"\n")
    l_textbox.place()
    m_textbox.place()
    r_textbox.place()

root.mainloop()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've made a very simple procedural solution. After looking on the tutorials point site for information on how to use the scrollbar for one widget (https://www.tutorialspoint.com/python/tk_scrollbar.htm), I adapted it to scroll through multiple text boxes at the same time (you can change the code so it uses list boxes). This solution will update all three textboxes when you use the scroll bar.

import tkinter as tk

HEIGHT = 200
WIDTH = 300

def scroll(x, y):
    l_textbox.yview(x,y)
    m_textbox.yview(x,y)
    r_textbox.yview(x,y)

root = tk.Tk()

canvas = tk.Canvas(root,height = HEIGHT, width = WIDTH, bg = "white")
canvas.pack()

frame = tk.Frame(root, bg ='white')
frame.place(relx=0,rely=0,relwidth=1,relheight=1)

scrollbar = tk.Scrollbar(frame)

l_label = tk.Label (frame, text = "Left")
l_label.place(relx=0, rely=0)

m_label = tk.Label (frame, text= "Middle")
m_label.place(relx=0.3, rely=0)

r_label = tk.Label (frame, text= "Right")
r_label.place(relx=0.6, rely=0)

l_textbox = tk.Text(frame, yscrollcommand = scrollbar.set)
l_textbox.config(font = ('Arial',9))
l_textbox.place(relx=0, rely=0.2,relwidth=0.3,relheight=0.8)

m_textbox = tk.Text(frame, yscrollcommand = scrollbar.set)
m_textbox.config(font = ('Arial',9))
m_textbox.place(relx=0.3, rely=0.2,relwidth=0.3,relheight=0.8)

r_textbox = tk.Text(frame, yscrollcommand = scrollbar.set)
r_textbox.config(font = ('Arial',9))
r_textbox.place(relx=0.6, rely=0.2,relwidth=0.3,relheight=0.8)

scrollbar.config( command = scroll)
scrollbar.place(relx = 0.9, relwidth = 0.1,relheight = 1)

for i in range(0, 100):
    l_textbox.insert(tk.INSERT, str(i)+"\n")
    m_textbox.insert(tk.INSERT, str(i)+"\n")
    r_textbox.insert(tk.INSERT, str(i)+"\n")
    l_textbox.place()
    m_textbox.place()
    r_textbox.place()

root.mainloop()

ContentLicense: CC BY-SA 4.0


问:
How do i run code given/taken by the user in python
I am pretty new to Kotlin, i am trying to make a project in Kotlin that executes code taken by the user.
I have used exec() in python to execute code but I don't know how to use that either, please help me if you know python and Kotlin please help
Any help will be very much appreciated!!
Thanks

EDIT:here is some more info.. i am a newbie in Kotlin
i need help with some commands which are like exec in python
i am making a program to run python commands in a Kotlin program
this is experimental..
forgive me as i am a newbie to Stackoverflow..
thanks..

答:
I have an idea
You can get user inputs and save them on a file.
Then execute the saved file on the shell by importing 'os' library

```<code>import os

print("Enter any python commands!")
print("Enter 'run' to execute.")

user_inputs = ''

# Get user input until user enter 'run' phrase
while True:
    user_input = input('> ')
    if user_input == 'run': break
    user_inputs = user_inputs + "\r\n" + user_input

# save user input on a file
file = open("run.py", 'w')
file.writelines(user_inputs)
file.close()

# execute the code on terminal and get output, then display to the user
stream = os.popen('python run.py')
output = stream.read()

print("---------------------------------")
print(output)
</code>```

Happy coding

Body:
I have an idea
You can get user inputs and save them on a file.
Then execute the saved file on the shell by importing 'os' library

import os

print("Enter any python commands!")
print("Enter 'run' to execute.")

user_inputs = ''

# Get user input until user enter 'run' phrase
while True:
    user_input = input('> ')
    if user_input == 'run': break
    user_inputs = user_inputs + "\r\n" + user_input

# save user input on a file
file = open("run.py", 'w')
file.writelines(user_inputs)
file.close()

# execute the code on terminal and get output, then display to the user
stream = os.popen('python run.py')
output = stream.read()

print("---------------------------------")
print(output)

Happy coding


问:
Should a many-to-many relationship define anything other than the relationship
Taking the typical products / categories many-to-many relationship you'd typically have a relationship like follows:

```<code>table -- ProductsCategories
column - ProductId
column - CategoryId
</code>```

Is it ill advised to add other properties to that relationship, things that only exist on that specific relationship. Such as (please forgive my terrible examples, I'm not good at examples):

```<code>table -- ProductsCategories
column - ProductId
column - CategoryId
column - DiscountForProductsInThisCategory
column - CategoryImageForProductsInThisCategory
</code>```

答:
Yes.

A relationship can have attributes, IMO.  Although some design masters don't think so.

Consider the "enrolled" relationship between Students and Courses.  If a student could be enrolled either for credit or as an auditor,  it would make sense for this attribute to be stored in a table whose key is (StudentID, CourseID).  This table is the relationship table that catalogues which students are enrolle d in which courses.

OwnerDisplayName: Kyle West

ContentLicense: CC BY-SA 2.5

Body:
Taking the typical products / categories many-to-many relationship you'd typically have a relationship like follows:

table -- ProductsCategories
column - ProductId
column - CategoryId

Is it ill advised to add other properties to that relationship, things that only exist on that specific relationship. Such as (please forgive my terrible examples, I'm not good at examples):

table -- ProductsCategories
column - ProductId
column - CategoryId
column - DiscountForProductsInThisCategory
column - CategoryImageForProductsInThisCategory

OwnerDisplayName: Walter Mitty


问:
Clearing the memory or files after opening using a macro
I have a VBA macro that open files in a folder, download data from an add-in, save and close.
This runs fine, but after 10 or 15 files, it gets quite slow. I think it is because Excel still keep previously opened files in the memory. I knew this because I saw the already-opened-and-closed files on the left panel as in the photo below. (the photo is to show where the panel is, I know there is only one file opened with the sheets, but you know what I mean).

My question is: is there a line of code that refresh or clear this temporary memory?

Here is my code:

```<code>'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim filename As String
Dim path_to_save As String
Dim FldrPicker As FileDialog
Dim w As Long
Dim StartTime As Double
Dim SecondsElapsed As Double
Dim oFile       As Object
Dim oFSO        As Object
Dim oFolder     As Object
Dim oFiles      As Object

Application.ScreenUpdating = False
StartTime = Timer

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Assign the folder to oFSO
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(myPath)
    Set oFiles = oFolder.Files
    If oFiles.Count = 0 Then GoTo ResetSettings

For Each oFile In oFolder.Files
    'Set variable equal to opened workbook
    myFile = oFile.Name
    Set wb = Workbooks.Open(filename:=myPath & myFile)
    Set cmd = Application.CommandBars("Cell").Controls("Refresh All")
    cmd.Execute
    DoEvents

    'Ensure Workbook has opened before moving on to next line of code

    wb.Close savechanges:=True

    'Ensure Workbook has closed before moving on to next line of code
    DoEvents
Next 'oFile

SecondsElapsed = Timer - StartTime
MsgBox "This code ran successfully in " & SecondsElapsed
    Set oFile = Nothing
    Set oFolder = Nothing
    Set oFSO = Nothing

ResetSettings:
  'Reset Macro Optimization Settings
    Application.ScreenUpdating = True
End Sub
</code>```

答:
There is a known issue in Excel with closed Workbooks leaving data in Memory, which can only be cleared by closing and reopening Excel.

The below code uses a late-bound second instance of the Excel application, in an attempt to alleviate this issue; the second instance will be closed and reopened periodically (currently set to every 5 files).

```<code>Sub SomeName()
    'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them

    Dim wb As Workbook
    Dim myPath As String
    Dim myFile As String
    Dim myExtension As String
    Dim filename As String
    Dim path_to_save As String
    Dim FldrPicker As FileDialog
    Dim w As Long
    Dim StartTime As Double
    Dim SecondsElapsed As Double
    Dim oFile       As Object
    Dim oFSO        As Object
    Dim oFolder     As Object
    Dim oFiles      As Object

    'NEW CODE
    Dim appXL AS Object, counterFiles AS Long
    counterFiles = 0

    Application.ScreenUpdating = False
    StartTime = Timer

    'Retrieve Target Folder Path From User
    Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
    With FldrPicker
    .Title = "Select A Target Folder"
        .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

    'In Case of Cancel
    NextCode:
    myPath = myPath
    If myPath = "" Then GoTo ResetSettings

    'Assign the folder to oFSO
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(myPath)
    Set oFiles = oFolder.Files
    If oFiles.Count = 0 Then GoTo ResetSettings

    For Each oFile In oFolder.Files
        'NEW CODE
        If appXL Is Nothing Then Set appNewExcel = CreateObject("Excel.Application")
        DoEvents

        'Set variable equal to opened workbook
        myFile = oFile.Name
        Set wb = appNewExcel.Workbooks.Open(filename:=myPath & myFile)

        'Update / Refresh workbook
        wb.RefreshAll
        appNewExcel.CalculateFullRebuild
        DoEvents

        'Ensure Workbook has opened before moving on to next line of code
        wb.Save
        DoEvents
        wb.Close savechanges:=True

        'Ensure Workbook has closed before moving on to next line of code
        'NEW CODE
        Set wb = Nothing
        counterFiles = counterFiles+1
        If counterFiles mod 5 = 0 Then
            appNewExcel.Quit
            Set appNewExcel = Nothing
        End If

        DoEvents
    Next 'oFile

    SecondsElapsed = Timer - StartTime
    MsgBox "This code ran successfully in " & SecondsElapsed

    Set oFile = Nothing
    Set oFolder = Nothing
    Set oFSO = Nothing

ResetSettings:
    'Reset Macro Optimization Settings
    Application.ScreenUpdating = True
End Sub
</code>```

Body:
I have a VBA macro that open files in a folder, download data from an add-in, save and close.
This runs fine, but after 10 or 15 files, it gets quite slow. I think it is because Excel still keep previously opened files in the memory. I knew this because I saw the already-opened-and-closed files on the left panel as in the photo below. (the photo is to show where the panel is, I know there is only one file opened with the sheets, but you know what I mean).

My question is: is there a line of code that refresh or clear this temporary memory?

Here is my code:

'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim filename As String
Dim path_to_save As String
Dim FldrPicker As FileDialog
Dim w As Long
Dim StartTime As Double
Dim SecondsElapsed As Double
Dim oFile       As Object
Dim oFSO        As Object
Dim oFolder     As Object
Dim oFiles      As Object

Application.ScreenUpdating = False
StartTime = Timer

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Assign the folder to oFSO
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(myPath)
    Set oFiles = oFolder.Files
    If oFiles.Count = 0 Then GoTo ResetSettings

For Each oFile In oFolder.Files
    'Set variable equal to opened workbook
    myFile = oFile.Name
    Set wb = Workbooks.Open(filename:=myPath & myFile)
    Set cmd = Application.CommandBars("Cell").Controls("Refresh All")
    cmd.Execute
    DoEvents

    'Ensure Workbook has opened before moving on to next line of code

    wb.Close savechanges:=True

    'Ensure Workbook has closed before moving on to next line of code
    DoEvents
Next 'oFile

SecondsElapsed = Timer - StartTime
MsgBox "This code ran successfully in " & SecondsElapsed
    Set oFile = Nothing
    Set oFolder = Nothing
    Set oFSO = Nothing

ResetSettings:
  'Reset Macro Optimization Settings
    Application.ScreenUpdating = True
End Sub

Body:
There is a known issue in Excel with closed Workbooks leaving data in Memory, which can only be cleared by closing and reopening Excel.

The below code uses a late-bound second instance of the Excel application, in an attempt to alleviate this issue; the second instance will be closed and reopened periodically (currently set to every 5 files).

Sub SomeName()
    'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them

    Dim wb As Workbook
    Dim myPath As String
    Dim myFile As String
    Dim myExtension As String
    Dim filename As String
    Dim path_to_save As String
    Dim FldrPicker As FileDialog
    Dim w As Long
    Dim StartTime As Double
    Dim SecondsElapsed As Double
    Dim oFile       As Object
    Dim oFSO        As Object
    Dim oFolder     As Object
    Dim oFiles      As Object

    'NEW CODE
    Dim appXL AS Object, counterFiles AS Long
    counterFiles = 0

    Application.ScreenUpdating = False
    StartTime = Timer

    'Retrieve Target Folder Path From User
    Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
    With FldrPicker
    .Title = "Select A Target Folder"
        .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

    'In Case of Cancel
    NextCode:
    myPath = myPath
    If myPath = "" Then GoTo ResetSettings

    'Assign the folder to oFSO
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(myPath)
    Set oFiles = oFolder.Files
    If oFiles.Count = 0 Then GoTo ResetSettings

    For Each oFile In oFolder.Files
        'NEW CODE
        If appXL Is Nothing Then Set appNewExcel = CreateObject("Excel.Application")
        DoEvents

        'Set variable equal to opened workbook
        myFile = oFile.Name
        Set wb = appNewExcel.Workbooks.Open(filename:=myPath & myFile)

        'Update / Refresh workbook
        wb.RefreshAll
        appNewExcel.CalculateFullRebuild
        DoEvents

        'Ensure Workbook has opened before moving on to next line of code
        wb.Save
        DoEvents
        wb.Close savechanges:=True

        'Ensure Workbook has closed before moving on to next line of code
        'NEW CODE
        Set wb = Nothing
        counterFiles = counterFiles+1
        If counterFiles mod 5 = 0 Then
            appNewExcel.Quit
            Set appNewExcel = Nothing
        End If

        DoEvents
    Next 'oFile

    SecondsElapsed = Timer - StartTime
    MsgBox "This code ran successfully in " & SecondsElapsed

    Set oFile = Nothing
    Set oFolder = Nothing
    Set oFSO = Nothing

ResetSettings:
    'Reset Macro Optimization Settings
    Application.ScreenUpdating = True
End Sub


问:
How to create two different value in the same row
Below is the Data Set I am working on.

I am trying to create new column based on certain condition. Below is the code:-

```<code>SELECT
  *
,
CASE
WHEN [Partner Number] Like ('SAL%') THEN [Partner Name]
ELSE ''
END AS [SAL Name],
    CASE
WHEN [Partner Number] Like ('SAL%') THEN [Partner Email Address]
ELSE ''
END AS [SAL Email],
CASE
WHEN [Partner Number] Like ('CEO%') THEN [Partner Name]
ELSE ''
END AS [CEO Name],
    CASE
WHEN [Partner Number] Like ('CEO%') THEN [Partner Email Address]
ELSE ''
END AS [CEO Email],
    CASE
WHEN [Partner Number] Like ('VPS%') THEN [Partner Name]
ELSE ''
END AS [VPS Name],
    CASE
WHEN [Partner Number] Like ('VPS%') THEN [Partner Email Address]
ELSE ''
END AS [VPS Email]

     Into #Partner
  from (
         Select distinct  [Vendor Number],
[Purchasing Org],

[Partner Number],

[Partner Name]
,
[Partner Email Address] from #Temp)k
</code>```

But It is generating two different rows, if the set has both SAL and CAL.

It is possible to generate both of them in same row because when i am doing join , the data is getting explode .

Ideally both Sal Name and cal Name  in the same row.

Result

答:
I think this is more something you should do in the presentation layer.

But something like this should do it:

```<code>WITH cte_cat
as
(
    SELECT *,   CASE    WHEN partnerNumber like 'CEO%' THEN 'CEO'
                        WHEN partnerNumber like 'SAL%' THEN 'SAL'
                        ELSE 'OTHER' END as Category

    FROM #yourtable
),
cte_rn
as
(
    SELECT *,ROW_NUMBER () OVER (PARTITION BY vendorNbr,purchasingOrg,Category ORDER BY Commodity) as RN
    FROM cte_cat
)

SELECT oth.vendorNbr,oth.purchasingOrg,oth.commodity,oth.partnerNumber,oth.PartnerName,oth.ParterEmail,CEO.partnerNumber,CEO.PartnerName,CEO.ParterEmail,SAL.partnerNumber,SAL.PartnerName,SAL.ParterEmail
FROM cte_rn oth
LEFT JOIN cte_rn CEO
    ON CEO.Category = 'CEO'
    AND oth.RN = CEO.rn
    AND oth.vendorNbr=CEO.vendorNbr
    AND oth.purchasingOrg = CEO.purchasingOrg
LEFT JOIN cte_rn SAL
    ON SAL.Category = 'SAL'
    AND oth.RN = SAL.rn
    AND oth.vendorNbr=SAL.vendorNbr
    AND oth.purchasingOrg = SAL.purchasingOrg

WHERE oth.Category ='OTHER';
</code>```

Body:
Below is the Data Set I am working on.

I am trying to create new column based on certain condition. Below is the code:-

SELECT
  *
,
CASE
WHEN [Partner Number] Like ('SAL%') THEN [Partner Name]
ELSE ''
END AS [SAL Name],
    CASE
WHEN [Partner Number] Like ('SAL%') THEN [Partner Email Address]
ELSE ''
END AS [SAL Email],
CASE
WHEN [Partner Number] Like ('CEO%') THEN [Partner Name]
ELSE ''
END AS [CEO Name],
    CASE
WHEN [Partner Number] Like ('CEO%') THEN [Partner Email Address]
ELSE ''
END AS [CEO Email],
    CASE
WHEN [Partner Number] Like ('VPS%') THEN [Partner Name]
ELSE ''
END AS [VPS Name],
    CASE
WHEN [Partner Number] Like ('VPS%') THEN [Partner Email Address]
ELSE ''
END AS [VPS Email]

     Into #Partner
  from (
         Select distinct  [Vendor Number],
[Purchasing Org],

[Partner Number],

[Partner Name]
,
[Partner Email Address] from #Temp)k

But It is generating two different rows, if the set has both SAL and CAL.

It is possible to generate both of them in same row because when i am doing join , the data is getting explode .

Ideally both Sal Name and cal Name  in the same row.

Result

Body:
I think this is more something you should do in the presentation layer.

But something like this should do it:

WITH cte_cat
as
(
    SELECT *,   CASE    WHEN partnerNumber like 'CEO%' THEN 'CEO'
                        WHEN partnerNumber like 'SAL%' THEN 'SAL'
                        ELSE 'OTHER' END as Category

    FROM #yourtable
),
cte_rn
as
(
    SELECT *,ROW_NUMBER () OVER (PARTITION BY vendorNbr,purchasingOrg,Category ORDER BY Commodity) as RN
    FROM cte_cat
)

SELECT oth.vendorNbr,oth.purchasingOrg,oth.commodity,oth.partnerNumber,oth.PartnerName,oth.ParterEmail,CEO.partnerNumber,CEO.PartnerName,CEO.ParterEmail,SAL.partnerNumber,SAL.PartnerName,SAL.ParterEmail
FROM cte_rn oth
LEFT JOIN cte_rn CEO
    ON CEO.Category = 'CEO'
    AND oth.RN = CEO.rn
    AND oth.vendorNbr=CEO.vendorNbr
    AND oth.purchasingOrg = CEO.purchasingOrg
LEFT JOIN cte_rn SAL
    ON SAL.Category = 'SAL'
    AND oth.RN = SAL.rn
    AND oth.vendorNbr=SAL.vendorNbr
    AND oth.purchasingOrg = SAL.purchasingOrg

WHERE oth.Category ='OTHER';


问:
problem in deleting a node in linked list (Python)
So below is a linked that removes an item from the list

class Node(object):
    def __init__(self, data=None):
        self.data = data
        self.next_node = None
class LinkedList(object):
    def __init__(self):
        self.head = None

    def remove(self,item_to_remove):
        n = self.head
        while n is not item_to_remove :
            n = n.next_node
        if n == item_to_remove:
            n = None
```

<p>In the process of looping through the nodes it returns me this ERROR</p>

```AttributeError: 'NoneType' object has no attribute 'next_node'
```

It would be great if you can help
Thanks in advance!!

答:
Before accessing the remove method, try to insert data first.
Try the below method for inserting.</p>

```<code>  def insert(self, data):
    newNode = Node(data)
    if(self.head):
      current = self.head
      while(current.next):
        current = current.next
      current.next = newNode
    else:
      self.head = newNode

</code>```

Body:
So below is a linked that removes an item from the list

class Node(object):
    def __init__(self, data=None):
        self.data = data
        self.next_node = None
class LinkedList(object):
    def __init__(self):
        self.head = None

    def remove(self,item_to_remove):
        n = self.head
        while n is not item_to_remove :
            n = n.next_node
        if n == item_to_remove:
            n = None

In the process of looping through the nodes it returns me this ERROR

AttributeError: 'NoneType' object has no attribute 'next_node'

It would be great if you can help
Thanks in advance!!

Body:
Before accessing the remove method, try to insert data first.
Try the below method for inserting.

  def insert(self, data):
    newNode = Node(data)
    if(self.head):
      current = self.head
      while(current.next):
        current = current.next
      current.next = newNode
    else:
      self.head = newNode


问:
Exception not getting handled in recover method
This method throws exception

```<code>  @throws(classOf[QuestionNotFoundException])
  def getQuestionFromQuestionID(questionKey: PracticeQuestionKeys) = {
    logger.trace(s"getting question with keys ${questionKey}")
    val practiceQuestionFuture: Future[Option[PracticeQuestion]] = findOne(questionKey)
    for (questionOption <- practiceQuestionFuture) yield {
      questionOption.fold(throw QuestionNotFoundException())(question => {
        logger.trace("got question " + question)
        question
      })
    }
  }
</code>```

I use it like follows

```<code>def function1 = {
...
val res = for{existingQuestion <- questionsRepository.getQuestionFromQuestionID(questionKey){..}
res.recover {
                     case exception => {
                       logger.trace(s"exception ${exception}")
                       Ok(Json.toJson(JsonResultError(messagesApi("error.answerAdditionFail")(langs.availables(0))+". "+exception.getMessage())))
                     }
...
}
</code>```

I want to test that function1 handles the thrown exception. I have written the following test case

```<code>"function" should {
    "should return error if the question id is not correct" in {
      ...

      when(answerTestEnv.mockPracticeQuestionsRepository.getQuestionFromQuestionID(ArgumentMatchers.any[PracticeQuestionKeys])).thenThrow(
        QuestionNotFoundException()
      )

      val response:Accumulator[ByteString,Result] = controller.function1(request)
      //note that run is how accumulator gets the data and starts processing it. no parameter means no data
      val resultOfAccumulatorRun:Future[Result] = response.run(ByteString(body))
      val responseBody = contentAsJson(resultOfAccumulatorRun)(Timeout(Duration(5000,"millis")),TestEnvImplicits.mat)

      println(s"received response ${responseBody}")
      val result = (responseBody \ "result").get.as[String]

      val additionalInfo = (responseBody \ "additional-info").get.as[String]

      result mustBe "error"
      additionalInfo mustBe components.messagesApi("error.answerAdditionFail")(components.langs.availables(0))+". "+QuestionNotFoundException().msg

    }

}
</code>```

But when I run my test case, the Exception gets thrown but it seems that res.recover doesn't handle it. I see this in the console.

```<code>Question not found
utilities.QuestionNotFoundException: Question not found
    at controllers.AnswerController.$anonfun$newAnswer$1(AnswerController.scala:428)
</code>```

Why doestres.recover` doesn't handle it.

答:
the partial function passed to recover() gets invoked on a failed Future, but your Future isn't a failed Future, it is a Future that contains an exception as its 'successful' result type (actually it will be forced to be something more like Future[AnyRef], as it could be either an Exception or a PracticeQuestion).

You probably don't want to be using Option.fold() like that. Instead try:

```<code>practiceQuestionFuture.flatMap { qOpt =>
          qOpt.map(q => Future(q))
              .getOrElse(Future.failed(QuestionNotFoundException()))
}
</code>```

(NB: I'm not near a compiler to try this out right now, so I may have made a syntactical mistake or two, but there should be enough there to get you going).

Body:
This method throws exception

  @throws(classOf[QuestionNotFoundException])
  def getQuestionFromQuestionID(questionKey: PracticeQuestionKeys) = {
    logger.trace(s"getting question with keys ${questionKey}")
    val practiceQuestionFuture: Future[Option[PracticeQuestion]] = findOne(questionKey)
    for (questionOption <- practiceQuestionFuture) yield {
      questionOption.fold(throw QuestionNotFoundException())(question => {
        logger.trace("got question " + question)
        question
      })
    }
  }

I use it like follows

def function1 = {
...
val res = for{existingQuestion <- questionsRepository.getQuestionFromQuestionID(questionKey){..}
res.recover {
                     case exception => {
                       logger.trace(s"exception ${exception}")
                       Ok(Json.toJson(JsonResultError(messagesApi("error.answerAdditionFail")(langs.availables(0))+". "+exception.getMessage())))
                     }
...
}

I want to test that function1 handles the thrown exception. I have written the following test case

"function" should {
    "should return error if the question id is not correct" in {
      ...

      when(answerTestEnv.mockPracticeQuestionsRepository.getQuestionFromQuestionID(ArgumentMatchers.any[PracticeQuestionKeys])).thenThrow(
        QuestionNotFoundException()
      )

      val response:Accumulator[ByteString,Result] = controller.function1(request)
      //note that run is how accumulator gets the data and starts processing it. no parameter means no data
      val resultOfAccumulatorRun:Future[Result] = response.run(ByteString(body))
      val responseBody = contentAsJson(resultOfAccumulatorRun)(Timeout(Duration(5000,"millis")),TestEnvImplicits.mat)

      println(s"received response ${responseBody}")
      val result = (responseBody \ "result").get.as[String]

      val additionalInfo = (responseBody \ "additional-info").get.as[String]

      result mustBe "error"
      additionalInfo mustBe components.messagesApi("error.answerAdditionFail")(components.langs.availables(0))+". "+QuestionNotFoundException().msg

    }

}

But when I run my test case, the Exception gets thrown but it seems that res.recover doesn't handle it. I see this in the console.

Question not found
utilities.QuestionNotFoundException: Question not found
    at controllers.AnswerController.$anonfun$newAnswer$1(AnswerController.scala:428)

Why doestres.recover` doesn't handle it.

Body:
the partial function passed to recover() gets invoked on a failed Future, but your Future isn't a failed Future, it is a Future that contains an exception as its 'successful' result type (actually it will be forced to be something more like Future[AnyRef], as it could be either an Exception or a PracticeQuestion).

You probably don't want to be using Option.fold() like that. Instead try:

practiceQuestionFuture.flatMap { qOpt =>
          qOpt.map(q => Future(q))
              .getOrElse(Future.failed(QuestionNotFoundException()))
}

(NB: I'm not near a compiler to try this out right now, so I may have made a syntactical mistake or two, but there should be enough there to get you going).


问:
My docker container has no internet
I had it working allright but now it stopped. I tried the following commands with no avail:

docker run -dns 8.8.8.8 base ping google.com

docker run base ping google.com

sysctl -w net.ipv4.ip_forward=1 - both on the host and on the container

All I get is unknown host google.com.  Docker version 0.7.0

Any ideas?

P.S. ufw disabled as well

答: for me, using centos 7.4, it was not issue of /etc/resolve.conf, iptables, iptables nat rules nor docker itself. The issue is the host missing the package bridge-utils which docker require to build the bridge using command brctl. yum install -y bridge-utils and restart docker, solve the problem.</p>

Title: My docker container has no internet


问:
In Selenium maven project not able to lunch the chrome browser
java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html
    at com.google.common.base.Preconditions.checkState(Preconditions.java:847)
    at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:134)
    at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:35)
    at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:159)
    at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:355)
    at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:94)
    at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:123)
    at iotdatanormalization.Datanormalization.beforeClass(Datanormalization.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)</p>

答:
Pls check your chrome driver path ,error is saying there is no chrome driver at your path </p>

```<code> @Test
public void testLogin() throws InterruptedException {
    System.setProperty("webdriver.chrome.driver","chromepath);
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get(url);
</code>```

Body:
Pls check your chrome driver path ,error is saying there is no chrome driver at your path

 @Test
public void testLogin() throws InterruptedException {
    System.setProperty("webdriver.chrome.driver","chromepath);
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get(url);


问:
Allow others to view repo w/o being added as collaborators
Is there a way to allow others to view a private repo on GitHub without adding them as collaborators? </p>

答:
You can do this through Organisations, this way it's in read only.

Resources:

Github - Read-only access to private repo


问:
can I mutate a selector value?
I have an app using NGRX.

I have a question, I know the store is a readonly place where you can't mutate object directly.
But when I use a selector

Like if I have the following ngrx selector

```<code>export const getSelectedMission = (state: State): Readonly<IMission> => state.selectedMission;
export const selectedMission: MemoizedSelector<object, Readonly<string>> = createSelector(
  selectMissionState,
  getSelectedMissionId
);
</code>```

If in my app I do this

```<code>this.store$.pipe(select(MissionsStoreSelectors.selectedMission)).subscribe((mission) => mission.name = "123")
</code>```

Is this a valid operation ? or it should be avoided ?

If I want to select portion in the store, and be able to edit those value (to dispatch action again in the store), what would be the best way ? Should I make all my selector return a copy of the object/array ?

EDIT :

It's fine to do so, but only if you do a copy of the object.

What if I do like this in the component :

```<code>this.selectedMission$ = this.store$.pipe(select(MissionsStoreSelectors.selectedMission))
</code>```

Then in the template I pass this value to a child

```<code><app-child [mission]="selectedMission$ | async"></app-child>
</code>```

And in the child I so at some point

```<code>mission.name = "123"
</code>```

This would edit the direct reference of the value in the store right? but the child component shouldn't care about making copy of the object before mutating it.

答:
if you want to mutate a value from the store you need to spread it, but you need to be very careful here because if the value is a deep object you need to take care about its nested values too.

this.selectedMission$ = this.store$.pipe(
  select(MissionsStoreSelectors.selectedMission),

  // now we do a deep clone and can pass it anywhere.
  map(value => JSON.stringify(JSON.encode(value))),
);
```

<hr>

<p>The right way would be to use <code>outputs</code> and <code>actions</code> like that.</p>

<pre class="lang-html prettyprint-override"><code><app-child [mission]="selectedMission$ | async" (update)="update($event)"></app-child>
</code>```

the app-child should emit at some point

this.update.emit({
  ...this.mission,
  name: '123',
});
```

<p>and in the parent component you can dispatch the action.</p>

<pre class="lang-js prettyprint-override"><code>update(mission): void {
  this.store.dispatch(new UpdateMission(mission));
}
</code>```

In this case you don't need map with JSON magic.

Title: can I mutate a selector value?

Body:
I have an app using NGRX.

I have a question, I know the store is a readonly place where you can't mutate object directly.
But when I use a selector

Like if I have the following ngrx selector

export const getSelectedMission = (state: State): Readonly<IMission> => state.selectedMission;
export const selectedMission: MemoizedSelector<object, Readonly<string>> = createSelector(
  selectMissionState,
  getSelectedMissionId
);

If in my app I do this

this.store$.pipe(select(MissionsStoreSelectors.selectedMission)).subscribe((mission) => mission.name = "123")

Is this a valid operation ? or it should be avoided ?

If I want to select portion in the store, and be able to edit those value (to dispatch action again in the store), what would be the best way ? Should I make all my selector return a copy of the object/array ?

EDIT :

It's fine to do so, but only if you do a copy of the object.

What if I do like this in the component :

this.selectedMission$ = this.store$.pipe(select(MissionsStoreSelectors.selectedMission))

Then in the template I pass this value to a child

<app-child [mission]="selectedMission$ | async"></app-child>

And in the child I so at some point

mission.name = "123"

This would edit the direct reference of the value in the store right? but the child component shouldn't care about making copy of the object before mutating it.

Body:
if you want to mutate a value from the store you need to spread it, but you need to be very careful here because if the value is a deep object you need to take care about its nested values too.

this.selectedMission$ = this.store$.pipe(
  select(MissionsStoreSelectors.selectedMission),

  // now we do a deep clone and can pass it anywhere.
  map(value => JSON.stringify(JSON.encode(value))),
);

The right way would be to use outputs and actions like that.

<app-child [mission]="selectedMission$ | async" (update)="update($event)"></app-child>

the app-child should emit at some point

this.update.emit({
  ...this.mission,
  name: '123',
});

and in the parent component you can dispatch the action.

update(mission): void {
  this.store.dispatch(new UpdateMission(mission));
}

In this case you don't need map with JSON magic.


问:
X is only available in IOS 9.0 o newer
During the development of the app with the plotter, it suddenly becomes impossible to build ios at all of a sudden. I will upload the related image below.

Other team members who do the same work have no problems.
Reinstallation of project ,xcode has already been attempted, and flutter clear , pod install has been attempted countless times. What can I do to fix this error?

Android builds normally.

I'm Korean and I'm not good at English, so I sent a question through a translator.

答:
You should set

```<code>platform:ios, '9.0'
</code>```

in your Podfile which you can find in iOS directory.

What Xcode basically saying is that you need to point to iOS version 9.0 min.

Title: X is only available in IOS 9.0 o newer

Body:
You should set

platform:ios, '9.0'

in your Podfile which you can find in iOS directory.

What Xcode basically saying is that you need to point to iOS version 9.0 min.


问:
How to write inner class test method in Python with Unittest
In Java when doing unit testing it is common to have a test class that contains multiple inner classes for each method of the class to test. Each inner class can have multiple testing methods to test a specific functionality of the related method.

I am trying to do the same thing in Python with unittest, but it seems that the inner classes' methods are not executed. For example:

```<code>import unittest

class OuterTestClass(unittest.TestCase):

    print("start outer class")

    def test_should_do_something(self):

            self.assertTrue( True )

            print("outer method test completed")

    class InnerTestClass(unittest.TestCase):

        print("start inner class")

        def test_should_do_something(self):

            self.assertTrue( True )

            print("inner method test completed")

</code>```

Expected behavior:

```<code>> start outer class
> start inner class
> inner method test completed
> outer method test completed
</code>```

Actual behavior:

```<code>> start outer class
> start inner class
> outer method test completed
</code>```

Is it possible to execute the inner class methods as well with unittest ?

答:
You can create a new test method in OuterTestClass that builds a suite of all test cases contained in InnerTestClass.</p>

```<code>class OuterTestClass(TestCase):

    print("start outer class")

    def test_should_do_something(self):

        self.assertTrue( True )

        print("outer method test completed")

    class InnerTestClass(TestCase):

        print("start inner class")

        def test_should_do_something(self):

            self.assertTrue( True )

            print("inner method test completed")

    def test_inner_test_class(self):
        suite = unittest.defaultTestLoader.loadTestsFromTestCase(self.InnerTestClass)
        unittest.TextTestRunner().run(suite)
</code>```

Body:
In Java when doing unit testing it is common to have a test class that contains multiple inner classes for each method of the class to test. Each inner class can have multiple testing methods to test a specific functionality of the related method.

I am trying to do the same thing in Python with unittest, but it seems that the inner classes' methods are not executed. For example:

import unittest

class OuterTestClass(unittest.TestCase):

    print("start outer class")

    def test_should_do_something(self):

            self.assertTrue( True )

            print("outer method test completed")

    class InnerTestClass(unittest.TestCase):

        print("start inner class")

        def test_should_do_something(self):

            self.assertTrue( True )

            print("inner method test completed")

Expected behavior:

> start outer class
> start inner class
> inner method test completed
> outer method test completed

Actual behavior:

> start outer class
> start inner class
> outer method test completed

Is it possible to execute the inner class methods as well with unittest ?

Body:
You can create a new test method in OuterTestClass that builds a suite of all test cases contained in InnerTestClass.

class OuterTestClass(TestCase):

    print("start outer class")

    def test_should_do_something(self):

        self.assertTrue( True )

        print("outer method test completed")

    class InnerTestClass(TestCase):

        print("start inner class")

        def test_should_do_something(self):

            self.assertTrue( True )

            print("inner method test completed")

    def test_inner_test_class(self):
        suite = unittest.defaultTestLoader.loadTestsFromTestCase(self.InnerTestClass)
        unittest.TextTestRunner().run(suite)


问:
query specific range prometheus
I want to query the number of the increased "connections_per_ms" every 1 hour at a specific range at a specific date ex:

from "1.5.20, 12:00" to "2.5.20 12:00",
query the increased connections every 1hour

so if at 12:00 I had 4000 connections and at 13:00 I have 4300 connections

should return 300

and do that in a range

答:
I am not sure what is the relation of the time dimension and range in your question, but maybe this would work (part with label is optional and can be removed):</p>

```<code>sum(increase(your_metric{your_label='your_label_value'}[1h])
</code>```

Title: query specific range prometheus

Body:
I am not sure what is the relation of the time dimension and range in your question, but maybe this would work (part with label is optional and can be removed):

sum(increase(your_metric{your_label='your_label_value'}[1h])


问:
R time series from day to month
I'm new to R and i need help with an R time series. I have daily data that I want to sum up to one month.
How can I sum up the days to a month?
In the end I want to use the TS as monthly frequency.

```<code>library(data.table)

#read csv "ProductList-B1-134564"
coffeedata = fread("https://raw.githubusercontent.com/Skruff80/FFHS/master/KantineWII/ProductList-B1-134564_w3_original.csv")

#Formating date
coffeedata$Date = as.Date(coffeedata$Date, "%d.%m.%Y")

#dailycounter
countcoffee = function(timeStamps) {
Dates = as.Date(strftime(coffeedata$Date, "%Y-%m-%d"))
allDates = seq(from = min(Dates), to = max(Dates), by = "day")
coffee.count = sapply(allDates, FUN = function(X) sum(Dates == X))
data.frame(day = allDates, coffee.count = coffee.count)}
dailycounter = countcoffee(df$coffee.date)

#time series
demand <- ts(dailycounter$coffee.count, start = c(2018, 1), frequency = 365)
plot(demand, type="l", xlab = "Year", col = "orange", lwd = "1", ylab = "Products a day")
</code>```

I appreciate your help.

答:
You can use some other packages to simplify your work. I recommend you to install tidyverse for this, which comes with a number of useful packages. Then it's much easier and straightforward to manipulate, group and visualize data.

```<code>library(readr)     # for reading data
library(dplyr)     # for manipulating data
library(lubridate) # for date and time manipulation
library(ggplot2)   # for graphics

# load data
coffee <- read_csv2("https://raw.githubusercontent.com/Skruff80/FFHS/master/KantineWII/ProductList-B1-134564_w3_original.csv")

# make a date
coffee$Date <- parse_date_time(coffee$Date, "d.m.Y H:M")

# make a plot from month data:
# 1. group data by month
# 2. count # of coffees (in that month)
# 3. create a plot
coffee %>%
  group_by(Month = floor_date(Date, "month")) %>%
  count() %>%
  ggplot(aes(Month, n)) + geom_col()
</code>```

And if you want e.g. color data by a product category, you just adjust this code like that:

```<code>coffee %>%
  group_by(Month = floor_date(Date, "month"), Product_Category) %>%
  count() %>%
  ggplot(aes(Month, n, fill = Product_Category)) + geom_col()
</code>```

Note that for simplicity I haven't named axes etc. but hope this pieces of code help you.

Title: R time series from day to month

Body:
I'm new to R and i need help with an R time series. I have daily data that I want to sum up to one month.
How can I sum up the days to a month?
In the end I want to use the TS as monthly frequency.

library(data.table)

#read csv "ProductList-B1-134564"
coffeedata = fread("https://raw.githubusercontent.com/Skruff80/FFHS/master/KantineWII/ProductList-B1-134564_w3_original.csv")

#Formating date
coffeedata$Date = as.Date(coffeedata$Date, "%d.%m.%Y")

#dailycounter
countcoffee = function(timeStamps) {
Dates = as.Date(strftime(coffeedata$Date, "%Y-%m-%d"))
allDates = seq(from = min(Dates), to = max(Dates), by = "day")
coffee.count = sapply(allDates, FUN = function(X) sum(Dates == X))
data.frame(day = allDates, coffee.count = coffee.count)}
dailycounter = countcoffee(df$coffee.date)

#time series
demand <- ts(dailycounter$coffee.count, start = c(2018, 1), frequency = 365)
plot(demand, type="l", xlab = "Year", col = "orange", lwd = "1", ylab = "Products a day")

I appreciate your help.

Body:
You can use some other packages to simplify your work. I recommend you to install tidyverse for this, which comes with a number of useful packages. Then it's much easier and straightforward to manipulate, group and visualize data.

library(readr)     # for reading data
library(dplyr)     # for manipulating data
library(lubridate) # for date and time manipulation
library(ggplot2)   # for graphics

# load data
coffee <- read_csv2("https://raw.githubusercontent.com/Skruff80/FFHS/master/KantineWII/ProductList-B1-134564_w3_original.csv")

# make a date
coffee$Date <- parse_date_time(coffee$Date, "d.m.Y H:M")

# make a plot from month data:
# 1. group data by month
# 2. count # of coffees (in that month)
# 3. create a plot
coffee %>%
  group_by(Month = floor_date(Date, "month")) %>%
  count() %>%
  ggplot(aes(Month, n)) + geom_col()

And if you want e.g. color data by a product category, you just adjust this code like that:

coffee %>%
  group_by(Month = floor_date(Date, "month"), Product_Category) %>%
  count() %>%
  ggplot(aes(Month, n, fill = Product_Category)) + geom_col()

Note that for simplicity I haven't named axes etc. but hope this pieces of code help you.


问:
Custom buttons in silverlight
How can I create buttons like this in silverlight. Do I need expression blend for this.

Since I need to use the modified buttons at many places in my application, should I do it as a user control?

答:
I'd definitely recommend Blend as it saves so much time when styling controls and creating templates.

However, if you're not set on having the buttons exactly the same as the image, there are several themes that you could use (such as JetPack) from which you could borrow the templates and amend the colours relatively easily in XAML.

Title: Custom buttons in silverlight


问:
How to delete one blank row and the following row only if it is not empty
I have a two column file with a structure

```<code>1 2
10 1

10 1
10 3
102 40

102 40
25 5
53 4

53 4
35 6
64 5
456 4

456 4
243 535
435 6
</code>```

So number above and below the blank row are same. But the blank row are not uniform (they are single, double or triple). I want to delete the number just after the each blank row and the blank row just above this number.

My expected output should be like this

```<code>1 2
10 1
10 3
102 40

25 5
53 4
35 6
64 5
456 4

243 535
435 6
</code>```

I have tried to do this:

```<code>sed -e '/pattern/,+1d' input_file
</code>```

You see my pattern is varying and I failed to solve the issue.

答:
With GNU sed and input file small enough to fit memory:

```<code>$ # or: perl -0777 -pe 's/\n\n\N+//g' ip.txt
$ sed -zE 's/\n\n[^\n]+//g' ip.txt
1 2
10 1
10 3
102 40

25 5
53 4
35 6
64 5
456 4

243 535
435 6
</code>```

This will match empty line and delete another line only if it contains any character. The sed solution assumes input doesn't contain ASCII NUL characters, because -z uses NUL as line separator.

With GNU awk

```<code>awk -v RS='\n\n[^\n]+' -v ORS= '1' ip.txt
</code>```

Body:
I have a two column file with a structure

1 2
10 1

10 1
10 3
102 40

102 40
25 5
53 4

53 4
35 6
64 5
456 4

456 4
243 535
435 6

So number above and below the blank row are same. But the blank row are not uniform (they are single, double or triple). I want to delete the number just after the each blank row and the blank row just above this number.

My expected output should be like this

1 2
10 1
10 3
102 40

25 5
53 4
35 6
64 5
456 4

243 535
435 6

I have tried to do this:

sed -e '/pattern/,+1d' input_file

You see my pattern is varying and I failed to solve the issue.

Body:
With GNU sed and input file small enough to fit memory:

$ # or: perl -0777 -pe 's/\n\n\N+//g' ip.txt
$ sed -zE 's/\n\n[^\n]+//g' ip.txt
1 2
10 1
10 3
102 40

25 5
53 4
35 6
64 5
456 4

243 535
435 6

This will match empty line and delete another line only if it contains any character. The sed solution assumes input doesn't contain ASCII NUL characters, because -z uses NUL as line separator.

With GNU awk

awk -v RS='\n\n[^\n]+' -v ORS= '1' ip.txt


问:
How to undersample/oversample more than two classes' dataset using "imblearn" library in Python?
I am working with "imblearn" library for undersampling. I have four classes in my dataset each having 20, 30, 40 and 50 number of data(as it is an imbalanced class).

But when I try to undersample the dataset using "fit_resample(X, y)", it only undersamples the first and last classes.

Is there any way I can undersample all the four classes using "imblearn"?

Necessary code:

```<code>undersample = RandomUnderSampler(sampling_strategy='majority')
X_over, y_over = undersample.fit_resample(X, y)
</code>```

答: The problem was solved setting smapling_strategy='all'.

Body:
I am working with "imblearn" library for undersampling. I have four classes in my dataset each having 20, 30, 40 and 50 number of data(as it is an imbalanced class).

But when I try to undersample the dataset using "fit_resample(X, y)", it only undersamples the first and last classes.

Is there any way I can undersample all the four classes using "imblearn"?

Necessary code:

undersample = RandomUnderSampler(sampling_strategy='majority')
X_over, y_over = undersample.fit_resample(X, y)


问:
Is there a way to programmatically set up security rules for a custom storage bucket in Firebase?
For multiple business and technical reasons, we want to give a specific bucket to each company that use our solution. This bucket is created by a Cloud function triggered by the company registration.

To be used with Firebase, this bucket must be "imported" in the web console in order to define a default security policy that needs to be adjusted.

As we won't be able to do that manually in the long range, is there any possibility to programmatically realize this bucket import and policy enforcement in the Admin SDK ?

答:
After multiple tests, Im sad to say that even if one is able to create a new bucket with the Admin SDK, there is no way to use it on the client side without manually importing it via the Firebase console.

The security rules can't be added just after creation with the following code. The bucket can't be found by the Admin SDK (Error: Requested entity was not found.)

[...]
const bucketName = getCompanyBucketName(key)
const storage = new Storage()
const bucket = storage.bucket(bucketName)
const result = await bucket.create({ location: 'EU' })
if (result[0]) {
   const ruleset = `
      service firebase.storage {
         match /b/{bucket}/o {
            match /{allPaths=**} {
            allow read, write: if request.auth != null;
            }
         }
      }
   `
   await admin
      .securityRules()
      .releaseStorageRulesetFromSource(ruleset, bucketName)
   }
```


问:
python3: how to convert "\u3000" (ideographic space) to "　"?
japanese.txt

```<code>あかさ
あいうえ　お
いい
</code>```

mycode.py

```<code>with open('japanese.txt', 'r', encoding='utf-8') as f:
    old = [line.strip() for line in f.readlines()]

send_mail(from, to, title, message=f"hello {old}!")
</code>```

Then I receive mail like this

```<code>hello ['あかさ', 'あいうえ\u3000お', 'いい']!
</code>```

What I want to mail is this

```<code>hello ['あかさ', 'あいうえ　お', 'いい']!
</code>```

How can I achieve this?

答:
If you want to replace the \u3000 character with a standard space and do the same type of thing for other less common unicode characters, you can use the unicodedata module:

```<code>import unicodedata

jText = """あかさ
あいうえ　お
いい"""

jList = [line.strip() for line in jText.split("\n")]
    # ['あかさ', 'あいうえ\u3000お', 'いい']

normalizedList = [unicodedata.normalize('NFKC', line) for line in jList]
    # ['あかさ', 'あいうえ お', 'いい']
</code>```

Body:
japanese.txt

あかさ
あいうえ　お
いい

mycode.py

with open('japanese.txt', 'r', encoding='utf-8') as f:
    old = [line.strip() for line in f.readlines()]

send_mail(from, to, title, message=f"hello {old}!")

Then I receive mail like this

hello ['あかさ', 'あいうえ\u3000お', 'いい']!

What I want to mail is this

hello ['あかさ', 'あいうえ　お', 'いい']!

How can I achieve this?

Body:
If you want to replace the \u3000 character with a standard space and do the same type of thing for other less common unicode characters, you can use the unicodedata module:

import unicodedata

jText = """あかさ
あいうえ　お
いい"""

jList = [line.strip() for line in jText.split("\n")]
    # ['あかさ', 'あいうえ\u3000お', 'いい']

normalizedList = [unicodedata.normalize('NFKC', line) for line in jList]
    # ['あかさ', 'あいうえ お', 'いい']


问:
Angular app deployment to IIS - Images not displaying (Static URLs)
I am deploying an angular 6 app to IIS. I installed IIS Rewrite module and also updated the web.config file and index.html file with Base URLs and rewrite rules.

Issue is Login page shows up without the logo/images. I tried to see what is wrong.
http://localhost/ATSTV2/#/login (This shows up the login page with controls and without images)

I looked at the image urls referred and it shows up an the source as http://localhost/assets/Logo_White.png which is incorrect.
The correct image link is http://localhost/ATSTV2/assets/Logo_White.png

Apart from changing my web.config and index.html for base URL, should I make some global changes and ensure the static urls are referred correctly?

This whole application works locally just fine with angular CLI ng serve. But when deploying to server I am deploying it to IIS and hence following some suggested approaches in the internet.

答:
You an use the deploy-url option to specify the url from which to load js/css files.

```<code>ng build ... --deploy-url /ATSTV2/
</code>```

Edit

Try modifying angular.json file and set deployUrl : "/ATSTV2/ to projects->YourProjectName->architect->build->options

```<code> "projects": {
    "YourProjectName": {
      ...
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            ...
            "deployUrl" : "/ATSTV2/",
</code>```

Body:
You an use the deploy-url option to specify the url from which to load js/css files.

ng build ... --deploy-url /ATSTV2/

Edit

Try modifying angular.json file and set deployUrl : "/ATSTV2/ to projects->YourProjectName->architect->build->options

 "projects": {
    "YourProjectName": {
      ...
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            ...
            "deployUrl" : "/ATSTV2/",


问:
How to create a cross-platform smartphone application?
I am new to smartphone application Development, I have worked with .NET web and Windows Forms applications and only used the C# language.

I am planning to make a simple application which can run on all mobile OSes, like BlackBerry, Windows Mobile, Android phones, iPhone, etc. On searching I found that all have different OSes and uses different languages. I can use the C# language and .NET since I am aware about it. After some thinking, is it possible to make a web-based application using normal website coding but make it work like an application?

Please suggest some method to make a application which is possible to run on all smartphones. What technology or tools can be used for developing it?

答:
The best approach to create truly cross platform app is to use HTML5 and JavaScript. All the other options will be painful. However, of course you can't access all the features with these web applications.

One interesting framework for creating HTML5/JavaScript based apps is PhoneGap (http://www.phonegap.com/). It has quite many API's available and wide support for different platforms. (Note that browser performance varies between devices so make sure not to add too much effects and glitter)

For native apps, there's no that many frameworks but one interesting is MoSync (http://www.mosync.com/)


问:
Error with google libraries play-services-location and play-services-analytics
I have this services in the gradle:

```<code>implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.google.android.libraries.places:places:1.1.0'
implementation 'com.google.android.gms:play-services-analytics:11.0.2'
</code>```

My app connect to a device wristband through Bluetooth. When the connect is finished, I have the next error:

2020-04-30 19:36:21.562 3113-3283/com.example.healthcarehighbloodpressure D/BluetoothGatt: close()
2020-04-30 19:36:21.563 3113-3283/com.example.healthcarehighbloodpressure D/BluetoothGatt: unregisterApp() - mClientIf=10
2020-04-30 19:36:21.566 3113-3283/com.example.healthcarehighbloodpressure I/[BLE] [BLE:D4:01:07:A4:44:00(3)] BLEGattClient(D4:01:07:A4:44:00)#close: android.bluetooth.BluetoothGatt@ee1d2e5
2020-04-30 19:36:21.581 3113-3283/com.example.healthcarehighbloodpressure I/[BLE] [BLE:D4:01:07:A4:44:00(3)] BLEDevice(D4:01:07:A4:44:00)#notifyState: 16 <- 64
2020-04-30 19:36:21.583 3113-3248/com.example.healthcarehighbloodpressure D/BluetoothAdapter: isLeEnabled(): ON
2020-04-30 19:36:21.591 3113-3248/com.example.healthcarehighbloodpressure I/[BLE] [BLEManager(1)] BLEScanObject#outputScanReport: D4:01:07:A4:44:00/38, <<Adv:38/Device:1>>
2020-04-30 19:36:21.593 3113-3248/com.example.healthcarehighbloodpressure I/[BLE] [BLEManager(1)] BLEManager#eventCallback: change : state=[BLUETOOTH_ON[WAIT_SCAN][SERVER_RUNNING]] / CMD_STOP_SCAN
2020-04-30 19:36:21.599 3113-3248/com.example.healthcarehighbloodpressure D/BluetoothGattServer: clearServices()
2020-04-30 19:36:21.600 3113-3283/com.example.healthcarehighbloodpressure I/[BLE] [BLE:D4:01:07:A4:44:00(3)] BLEDevice#issueEventSyncWithLog: change : state=[DISCONNECTED] / TIMEOUT_DELAY_CLOSE_GATT2
2020-04-30 19:36:21.600 3113-3248/com.example.healthcarehighbloodpressure D/BluetoothGattServer: close()
2020-04-30 19:36:21.600 3113-3248/com.example.healthcarehighbloodpressure D/BluetoothGattServer: unregisterCallback() - mServerIf=9
2020-04-30 19:36:21.601 3113-3248/com.example.healthcarehighbloodpressure I/[BLE] [BLEManager(1)] BLEManager#eventCallback: change : state=[BLUETOOTH_ON[WAIT_SCAN][SERVER_BREAKING]] / EVT_DEVICE_DISCONNECTED
2020-04-30 19:36:21.604 3113-3278/com.example.healthcarehighbloodpressure I/[OHQ] [OHQBLE:D4:01:07:A4:44:00(2)] OHQBleDevice(D4:01:07:A4:44:00)#finalize: broadcast detected : (actionUuid:0, aclConnected:0
2020-04-30 19:36:21.607 3113-3278/com.example.healthcarehighbloodpressure I/[OHQ] [OHQBLE:D4:01:07:A4:44:00(2)] OHQBleDevice(D4:01:07:A4:44:00)#notifyState: 1 <- 4
2020-04-30 19:36:21.608 3113-3278/com.example.healthcarehighbloodpressure I/[OHQ] [OHQBLE:D4:01:07:A4:44:00(2)] OHQBleDevice#eventCallback: change : state=[DISCONNECTED] / EVT_BLE_DISCONNECTED
2020-04-30 19:36:21.609 3113-3277/com.example.healthcarehighbloodpressure I/[OGSC] [OHQ_DEVICE_CALLBACK] OGSCWlpDevice#onDeviceStateChange: (4, 1, 1, 0x0)
2020-04-30 19:36:21.610 3113-3277/com.example.healthcarehighbloodpressure I/[OGSC] [OHQ_DEVICE_CALLBACK] OGSCWlpDevice#onDeviceStateChange: accessEnd completed. change errorCode to BLELIB_ERROR_SUCCESS
2020-04-30 19:36:21.632 3113-3277/com.example.healthcarehighbloodpressure E/AndroidRuntime: FATAL EXCEPTION: OHQ_DEVICE_CALLBACK
    Process: com.example.healthcarehighbloodpressure, PID: 3113
    java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/internal/zzbo;
        at com.google.android.gms.internal.zzamj.zzaf(Unknown Source:0)
        at com.google.android.gms.analytics.GoogleAnalytics.getInstance(Unknown Source:0)
        at jp.co.omron.healthcare.communicationlibrary.utility.ErrorInfo.getTracker(Unknown Source:6)
        at jp.co.omron.healthcare.communicationlibrary.ble.BLEErrorInfo.sendGoogleAnalytics(Unknown Source:80)
        at jp.co.omron.healthcare.communicationlibrary.ogsc.b.a(Unknown Source:121)
        at jp.co.omron.healthcare.communicationlibrary.ogsc.j.onDeviceStateChange(Unknown Source:275)
        at jp.co.omron.healthcare.communicationlibrary.ohq.OHQBleDevice$23$1.run(Unknown Source:31)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:224)
        at android.os.HandlerThread.run(HandlerThread.java:67)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.internal.zzbo" on path: DexPathList[[zip file "/data/app/com.example.healthcarehighbloodpressure-5seYA8AMyM_dgXjk44W48g==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.healthcarehighbloodpressure-5seYA8AMyM_dgXjk44W48g==/lib/arm64, /system/lib64, /system/product/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:230)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at com.google.android.gms.internal.zzamj.zzaf(Unknown Source:0)
        at com.google.android.gms.analytics.GoogleAnalytics.getInstance(Unknown Source:0)
        at jp.co.omron.healthcare.communicationlibrary.utility.ErrorInfo.getTracker(Unknown Source:6)
        at jp.co.omron.healthcare.communicationlibrary.ble.BLEErrorInfo.sendGoogleAnalytics(Unknown Source:80)
        at jp.co.omron.healthcare.communicationlibrary.ogsc.b.a(Unknown Source:121)
        at jp.co.omron.healthcare.communicationlibrary.ogsc.j.onDeviceStateChange(Unknown Source:275)
        at jp.co.omron.healthcare.communicationlibrary.ohq.OHQBleDevice$23$1.run(Unknown Source:31)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:224)
        at android.os.HandlerThread.run(HandlerThread.java:67)
2020-04-30 19:36:21.638 3113-3277/com.example.healthcarehighbloodpressure E/MQSEventManagerDelegate: failed to get MQSService.
2020-04-30 19:36:21.655 3113-3277/com.example.healthcarehighbloodpressure I/Process: Sending signal. PID: 3113 SIG: 9```

If I delete the places and location libraries, it works fine. The analytics is a mandatory library for de SDK of the wristband. In the case of places is not necessary for me, I was thinking of deleting it. The problen is location, my app needs to locate the position of the user.

Do you have a way to solve it? Thanks in advance.

答:
By removing places and setting the remaining ones to version 16, it already works.</p>

```<code>implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.google.android.gms:play-services-analytics:16.0.0'
</code>```

Body:
I have this services in the gradle:

implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.google.android.libraries.places:places:1.1.0'
implementation 'com.google.android.gms:play-services-analytics:11.0.2'

My app connect to a device wristband through Bluetooth. When the connect is finished, I have the next error:

2020-04-30 19:36:21.562 3113-3283/com.example.healthcarehighbloodpressure D/BluetoothGatt: close()
2020-04-30 19:36:21.563 3113-3283/com.example.healthcarehighbloodpressure D/BluetoothGatt: unregisterApp() - mClientIf=10
2020-04-30 19:36:21.566 3113-3283/com.example.healthcarehighbloodpressure I/[BLE] [BLE:D4:01:07:A4:44:00(3)] BLEGattClient(D4:01:07:A4:44:00)#close: android.bluetooth.BluetoothGatt@ee1d2e5
2020-04-30 19:36:21.581 3113-3283/com.example.healthcarehighbloodpressure I/[BLE] [BLE:D4:01:07:A4:44:00(3)] BLEDevice(D4:01:07:A4:44:00)#notifyState: 16 <- 64
2020-04-30 19:36:21.583 3113-3248/com.example.healthcarehighbloodpressure D/BluetoothAdapter: isLeEnabled(): ON
2020-04-30 19:36:21.591 3113-3248/com.example.healthcarehighbloodpressure I/[BLE] [BLEManager(1)] BLEScanObject#outputScanReport: D4:01:07:A4:44:00/38, <<Adv:38/Device:1>>
2020-04-30 19:36:21.593 3113-3248/com.example.healthcarehighbloodpressure I/[BLE] [BLEManager(1)] BLEManager#eventCallback: change : state=[BLUETOOTH_ON[WAIT_SCAN][SERVER_RUNNING]] / CMD_STOP_SCAN
2020-04-30 19:36:21.599 3113-3248/com.example.healthcarehighbloodpressure D/BluetoothGattServer: clearServices()
2020-04-30 19:36:21.600 3113-3283/com.example.healthcarehighbloodpressure I/[BLE] [BLE:D4:01:07:A4:44:00(3)] BLEDevice#issueEventSyncWithLog: change : state=[DISCONNECTED] / TIMEOUT_DELAY_CLOSE_GATT2
2020-04-30 19:36:21.600 3113-3248/com.example.healthcarehighbloodpressure D/BluetoothGattServer: close()
2020-04-30 19:36:21.600 3113-3248/com.example.healthcarehighbloodpressure D/BluetoothGattServer: unregisterCallback() - mServerIf=9
2020-04-30 19:36:21.601 3113-3248/com.example.healthcarehighbloodpressure I/[BLE] [BLEManager(1)] BLEManager#eventCallback: change : state=[BLUETOOTH_ON[WAIT_SCAN][SERVER_BREAKING]] / EVT_DEVICE_DISCONNECTED
2020-04-30 19:36:21.604 3113-3278/com.example.healthcarehighbloodpressure I/[OHQ] [OHQBLE:D4:01:07:A4:44:00(2)] OHQBleDevice(D4:01:07:A4:44:00)#finalize: broadcast detected : (actionUuid:0, aclConnected:0
2020-04-30 19:36:21.607 3113-3278/com.example.healthcarehighbloodpressure I/[OHQ] [OHQBLE:D4:01:07:A4:44:00(2)] OHQBleDevice(D4:01:07:A4:44:00)#notifyState: 1 <- 4
2020-04-30 19:36:21.608 3113-3278/com.example.healthcarehighbloodpressure I/[OHQ] [OHQBLE:D4:01:07:A4:44:00(2)] OHQBleDevice#eventCallback: change : state=[DISCONNECTED] / EVT_BLE_DISCONNECTED
2020-04-30 19:36:21.609 3113-3277/com.example.healthcarehighbloodpressure I/[OGSC] [OHQ_DEVICE_CALLBACK] OGSCWlpDevice#onDeviceStateChange: (4, 1, 1, 0x0)
2020-04-30 19:36:21.610 3113-3277/com.example.healthcarehighbloodpressure I/[OGSC] [OHQ_DEVICE_CALLBACK] OGSCWlpDevice#onDeviceStateChange: accessEnd completed. change errorCode to BLELIB_ERROR_SUCCESS
2020-04-30 19:36:21.632 3113-3277/com.example.healthcarehighbloodpressure E/AndroidRuntime: FATAL EXCEPTION: OHQ_DEVICE_CALLBACK
    Process: com.example.healthcarehighbloodpressure, PID: 3113
    java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/internal/zzbo;
        at com.google.android.gms.internal.zzamj.zzaf(Unknown Source:0)
        at com.google.android.gms.analytics.GoogleAnalytics.getInstance(Unknown Source:0)
        at jp.co.omron.healthcare.communicationlibrary.utility.ErrorInfo.getTracker(Unknown Source:6)
        at jp.co.omron.healthcare.communicationlibrary.ble.BLEErrorInfo.sendGoogleAnalytics(Unknown Source:80)
        at jp.co.omron.healthcare.communicationlibrary.ogsc.b.a(Unknown Source:121)
        at jp.co.omron.healthcare.communicationlibrary.ogsc.j.onDeviceStateChange(Unknown Source:275)
        at jp.co.omron.healthcare.communicationlibrary.ohq.OHQBleDevice$23$1.run(Unknown Source:31)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:224)
        at android.os.HandlerThread.run(HandlerThread.java:67)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.internal.zzbo" on path: DexPathList[[zip file "/data/app/com.example.healthcarehighbloodpressure-5seYA8AMyM_dgXjk44W48g==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.healthcarehighbloodpressure-5seYA8AMyM_dgXjk44W48g==/lib/arm64, /system/lib64, /system/product/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:230)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at com.google.android.gms.internal.zzamj.zzaf(Unknown Source:0)
        at com.google.android.gms.analytics.GoogleAnalytics.getInstance(Unknown Source:0)
        at jp.co.omron.healthcare.communicationlibrary.utility.ErrorInfo.getTracker(Unknown Source:6)
        at jp.co.omron.healthcare.communicationlibrary.ble.BLEErrorInfo.sendGoogleAnalytics(Unknown Source:80)
        at jp.co.omron.healthcare.communicationlibrary.ogsc.b.a(Unknown Source:121)
        at jp.co.omron.healthcare.communicationlibrary.ogsc.j.onDeviceStateChange(Unknown Source:275)
        at jp.co.omron.healthcare.communicationlibrary.ohq.OHQBleDevice$23$1.run(Unknown Source:31)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:224)
        at android.os.HandlerThread.run(HandlerThread.java:67)
2020-04-30 19:36:21.638 3113-3277/com.example.healthcarehighbloodpressure E/MQSEventManagerDelegate: failed to get MQSService.
2020-04-30 19:36:21.655 3113-3277/com.example.healthcarehighbloodpressure I/Process: Sending signal. PID: 3113 SIG: 9

If I delete the places and location libraries, it works fine. The analytics is a mandatory library for de SDK of the wristband. In the case of places is not necessary for me, I was thinking of deleting it. The problen is location, my app needs to locate the position of the user.

Do you have a way to solve it? Thanks in advance.

Body:
By removing places and setting the remaining ones to version 16, it already works.

implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.google.android.gms:play-services-analytics:16.0.0'


问:
Trigger update for Dynamo DB items
I'm looking for a solution to trigger update event for Dynamo DB records without actual updates to the records, but I can't find if there is a built-in solution for this.

I can of course retrieve items one-by-one and update something on them (like updated_at field), but I don't think this is an effective solution.

The purpose of all of this is to trigger update stream for all these records for data migration purposes via lambda.

答: This was resolved by scanning of the table item and passing item directly into lambda.

Title: Trigger update for Dynamo DB items


问:
jqGrid multiselect "check all" in header: how to hide it?
I use jqGrid with the multiselect option set to true.

I'm looking for a way to hide or disable the first checkbox (the one in the row of the column names) so that users can't use the "check all/uncheck all" feature.

How to do it?

答: Find the div of checkbox and hide/overwrite its inner HTML.</p>


问:
Indentation error in VS Code for Python script
I'm trying to run the following script in VS Code, however I keep getting an indentation error, which is kinda self-explanatory, but I haven't been able to find the error? Is there a way auto-formatting in VS Code?

```<code>import logging
import uuid
import json

import azure.functions as func

def main(msg: func.QueueMessage, message: func.Out[func.Document]) -> None:

    logging.info('Python queue trigger function processed a queue item: %s', msg_body)
    data = json.dumps({
        'id': msg.id,
        'body': msg.get_body().decode('utf-8'),
        'expiration_time': (msg.expiration_time.isoformat()
                            if msg.expiration_time else None),
        'insertion_time': (msg.insertion_time.isoformat()
                           if msg.insertion_time else None),
        'time_next_visible': (msg.time_next_visible.isoformat()
                             if msg.time_next_visible else None),
        'pop_receipt': msg.pop_receipt,
        'dequeue_count': msg.dequeue_count
    })
    message.set(func.Document.from_json(json.dumps(data)))
</code>```

My error message when I run the script:

```<code>[Running] python -u "c:\Users\artem\Desktop\function\inspariqueuestore\__init__.py"
  File "c:\Users\artem\Desktop\function\inspariqueuestore\__init__.py", line 12
    data = json.dumps({
    ^
IndentationError: unexpected indent

[Done] exited with code=1 in 0.093 seconds
</code>```

UPDATE

I mixed tabs and spaces apparently. Issue resolved.

答:
I don't see any indentation errors in your file.

Yes, you can try to format your file using VS Code.
There is a shortcut named editor.action.formatDocument.
You can find the exact keys for your setup in settings.

In my case it is shift + option (alt) + F

Body:
I'm trying to run the following script in VS Code, however I keep getting an indentation error, which is kinda self-explanatory, but I haven't been able to find the error? Is there a way auto-formatting in VS Code?

import logging
import uuid
import json

import azure.functions as func

def main(msg: func.QueueMessage, message: func.Out[func.Document]) -> None:

    logging.info('Python queue trigger function processed a queue item: %s', msg_body)
    data = json.dumps({
        'id': msg.id,
        'body': msg.get_body().decode('utf-8'),
        'expiration_time': (msg.expiration_time.isoformat()
                            if msg.expiration_time else None),
        'insertion_time': (msg.insertion_time.isoformat()
                           if msg.insertion_time else None),
        'time_next_visible': (msg.time_next_visible.isoformat()
                             if msg.time_next_visible else None),
        'pop_receipt': msg.pop_receipt,
        'dequeue_count': msg.dequeue_count
    })
    message.set(func.Document.from_json(json.dumps(data)))

My error message when I run the script:

[Running] python -u "c:\Users\artem\Desktop\function\inspariqueuestore\__init__.py"
  File "c:\Users\artem\Desktop\function\inspariqueuestore\__init__.py", line 12
    data = json.dumps({
    ^
IndentationError: unexpected indent

[Done] exited with code=1 in 0.093 seconds

UPDATE

I mixed tabs and spaces apparently. Issue resolved.


问:
Android, If a user delete the SAF tree uri(folder) on SD Card. Couldn't able to create the same folder
I have fetched the folder uri using SAF Document tree and saved it in Shared Preferences for future files saving purpose. Suppose, If a user delete's the folder. I could create the same folder on sd card.

Alternative:

1) Again ask the user to choose a directory using
   ACTION_OPEN_DOCUMENT_TREE

2) Create a same directory with the deleted folder name - It is not
   working.

Hint:
This is for Android Sdk built version less than 29. Impelemented scoped storage

Pls guide me with apt solution

答:
Suppose, If a user delete's the folder. I could create the same folder on sd card.

No you -your app- cant as for that you need saf write permission in parent folder.


问:
Not Adding Element to Dictionary - RPG Item System
I am implementing an inventory system into my RPG, I am trying to make it so that it gives me the item name, weight, the number of items, etc. I am having trouble with getting the number of items. So here is my code;

```<code>class Item():
    def __init__(self, name, damage, armor, weight, value, itype, rarity):
        self.name = name
        self.damage = damage
        self.armor = armor
        self.weight = weight
        self.value = value
        self.itype = itype
        self.rarity = rarity

class Inventory():

    def __init__(self):
        self.items = {}

    def add_item(self, item):

        self.items[item.name] = item

    def print_items(self):
        print('\t'.join(['Name', 'Atk', 'Arm', 'Kg', 'Val', 'Type', 'Rarity']))

        for item in self.items.values():
            print('\t'.join([str(x) for x in [item.name, item.damage, item.armor, item.weight, item.value, item.itype, item.rarity]]))

Items = {
    'dragonbane': Item('Dragon bane', 60, 0, 5, 1000, 'Weapon', '.oOo. LEGENDARY .oOo.'), # Name, Damage, Armour, Weight, Type, Rarity
    'trainingsword': Item('Training Sword', 2, 0, 5, 10, 'Weapon', '[ Common ]')}

inventory = Inventory()

inventory.add_item(Items['dragonbane']

inventory.print_items()
</code>```

Output:

```<code>Name    Atk Arm Kg  Val Type    Rarity
Dragon bane 60  0   5   1000    Weapon  .oOo. LEGENDARY .oOo.
</code>```

But if I were to add two Dragon Banes, it would only print Dragon Banes once. I simply cannot figure out how to add a system that counts how many of one item the player has.

Thanks in advance :D

答:
In Item construction, simply add:
self.uid= randint(1, 99999999)

*PS: Don't forget to import on top the random module (from random import randint).

Body:
I am implementing an inventory system into my RPG, I am trying to make it so that it gives me the item name, weight, the number of items, etc. I am having trouble with getting the number of items. So here is my code;

class Item():
    def __init__(self, name, damage, armor, weight, value, itype, rarity):
        self.name = name
        self.damage = damage
        self.armor = armor
        self.weight = weight
        self.value = value
        self.itype = itype
        self.rarity = rarity

class Inventory():

    def __init__(self):
        self.items = {}

    def add_item(self, item):

        self.items[item.name] = item

    def print_items(self):
        print('\t'.join(['Name', 'Atk', 'Arm', 'Kg', 'Val', 'Type', 'Rarity']))

        for item in self.items.values():
            print('\t'.join([str(x) for x in [item.name, item.damage, item.armor, item.weight, item.value, item.itype, item.rarity]]))

Items = {
    'dragonbane': Item('Dragon bane', 60, 0, 5, 1000, 'Weapon', '.oOo. LEGENDARY .oOo.'), # Name, Damage, Armour, Weight, Type, Rarity
    'trainingsword': Item('Training Sword', 2, 0, 5, 10, 'Weapon', '[ Common ]')}

inventory = Inventory()

inventory.add_item(Items['dragonbane']

inventory.print_items()

Output:

Name    Atk Arm Kg  Val Type    Rarity
Dragon bane 60  0   5   1000    Weapon  .oOo. LEGENDARY .oOo.

But if I were to add two Dragon Banes, it would only print Dragon Banes once. I simply cannot figure out how to add a system that counts how many of one item the player has.

Thanks in advance :D


问:
Resolve generic type of method passed via delegate
In my code, I am trying to dynamically resolve which type parameter should be used for a generic method call.

```<code>    private int FooResolver<T1, T2>(bool condition, Func<int> fooMethod)
    {
        if (condition)
        {
            return fooMethod<T1>();
        }

        return fooMethod<T2>();
    }
</code>```

I have created a wrapper method that takes in both type parameters and decides which one to use based on a condition... However, it seems C# does not allow this behavior. Are there any particular reasons for that? And is there a viable workaround for my code?

EDIT

After seeing the responses, I have decided to defer the type definition to the caller of the handler method:

```<code>private int FooResolver(bool condition, Func<int> foo1, Func<int> foo2)
{
    if (condition)
    {
        return foo1();
    }

    return foo2();
}

...

private int Bar()
{
    return FooResolver(myCondition, MyMethod<FirstType>, MyMethod<SecondType>);
}
</code>```

答:
Delegates aren't abstractions to open generic methods or method-groups; they are an indirection to a specific closed method - i.e. everything is already resolved. You can invoke it, and you can use reflection to find out what it is pointing at, but that's all (caveat: for simplicity I'm talking about delegates in the unicast sense; they are technically multicast, but that detail probably doesn't matter here).

If you want to get hold of a different method in the method-group (things that share the same name), or a different generic parameter usage of the same generic method: you'll need to use reflection to get hold of that. You can't do it directly from the delegate instance.

If you demonstrate the intended usage here, we may be able to offer more guidance on ways to achieve what you are after, but: it probably won't be as simple or direct as you are hoping.

Body:
In my code, I am trying to dynamically resolve which type parameter should be used for a generic method call.

    private int FooResolver<T1, T2>(bool condition, Func<int> fooMethod)
    {
        if (condition)
        {
            return fooMethod<T1>();
        }

        return fooMethod<T2>();
    }

I have created a wrapper method that takes in both type parameters and decides which one to use based on a condition... However, it seems C# does not allow this behavior. Are there any particular reasons for that? And is there a viable workaround for my code?

EDIT

After seeing the responses, I have decided to defer the type definition to the caller of the handler method:

private int FooResolver(bool condition, Func<int> foo1, Func<int> foo2)
{
    if (condition)
    {
        return foo1();
    }

    return foo2();
}

...

private int Bar()
{
    return FooResolver(myCondition, MyMethod<FirstType>, MyMethod<SecondType>);
}