问:
Repeating Macro gets error after several run throughs
Sample WorkbookI have repeating macros that freeze with an error after running 500 to 600 times through. The number of times I need it to run will change every time but mostly be around 2000 times.Error Notice

Line of code it stops onMaE.png

The entire code is below, multiple macros running after each other and calling others until report completes. It runs fine if it runs less than 500 times.

```<code>    Sub Start_New_Report()
'
' Start_New_Report Macro
' Clear Old data and prepare for new lines.
'
    Application.ScreenUpdating = False
    Sheets("Filtered Report").Select
    Range("A2:I1048576").Select
    Selection.ClearContents
    Range("A2").Select
    ActiveCell.FormulaR1C1 = "1"

    Call Filter_Data

End Sub

Sub Filter_Data()
' Filter raw Syteline data to usable lines

    Worksheets("Filtered Report").Range("B2").Value = _
        Worksheets("PurchaseOrderStatus").Range("A5:E5").Value
    Worksheets("Filtered Report").Range("C2").Value = _
        Worksheets("PurchaseOrderStatus").Range("A6:C6").Value
    Worksheets("Filtered Report").Range("D2").Value = _
        Worksheets("PurchaseOrderStatus").Range("A7:F7").Value
    Worksheets("Filtered Report").Range("E2").Value = _
        Worksheets("PurchaseOrderStatus").Range("J5").Value
    Worksheets("Filtered Report").Range("F2").Value = _
        Worksheets("PurchaseOrderStatus").Range("O7").Value
    Worksheets("Filtered Report").Range("G2").Value = _
        Worksheets("PurchaseOrderStatus").Range("P6:R6").Value
    Worksheets("Filtered Report").Range("H2").Value = _
        Worksheets("PurchaseOrderStatus").Range("P7:T7").Value
    Worksheets("Filtered Report").Range("I2").Value = _
        Worksheets("PurchaseOrderStatus").Range("V7").Value

    Call Clear_Raw_Data

End Sub

 Sub Clear_Raw_Data()
' Clear Raw Data Lines

    Sheets("PurchaseOrderStatus").Select
    Rows("5:7").Delete

    Call Blank_Cells

End Sub

Sub Blank_Cells()
' Check if blank cells exist in current line

    Sheets("Filtered Report").Select
    Range("B2").Select
If IsEmpty(Range("B2").Value) Then
    Call Copy_Up
Else
    Call Blank_Cells_Raw_Data
End If

End Sub

Sub Copy_Up()
'
' Copy Data Up from line below if cells are empty.
'
    Range("B3:D3").Copy Range("B2:D2")

    Call Blank_Cells_Raw_Data

End Sub

Sub Blank_Cells_Raw_Data()

    Sheets("PurchaseOrderStatus").Select
    Range("V5").Select
If IsEmpty(ActiveCell.Value) Then
    Call Finalize_Report
Else
    Call Clear_for_Next_Line
End If

End Sub

Sub Clear_for_Next_Line()
'
' Clear_for_Next_Line Macro
'
' Insert_line Macro
    Sheets("Filtered Report").Select
    Range("2:2").Insert CopyOrigin:=xlFormatFromRightOrBelow

' Create next index number

    Worksheets("Filtered Report").Range("A2").Value = _
        Worksheets("Filtered Report").Range("A3").Value + 1

    Call Filter_Data

End Sub

Sub Finalize_Report()
'
' Finalize_Report Macro
' Finish report and sort the order.
'
    Sheets("Filtered Report").Select
    Range("A1") = "Index"
    Columns("A:I").Sort key1:=Range("A2"), _
      order1:=xlAscending, Header:=xlYes

End Sub
</code>```

答:
In essence, I discarded the entire model where separate subroutines were calling each other in sequence and replaced it with a single subroutine that performs all of the functions.

I opted to rewrite the sample code by removing the use of .Select (see link) and defining worksheet variables whenever possible.

One other thing I noticed was in Blank_Cells and Blank_Cells_Raw_Data, I don't think you meant to use IsEmpty there (which checks to see if a variable is initialized; see link), but rather determine if the cell itself is empty. I changed this to If Application.WorksheetFunction.CountA(Range) = 0 in both instances.

In Filter_Data, I noticed you're setting the value of one cell (e.g. B2) to the value of multiple cells (e.g. A5:E5). In testing this just set the first cell to the first value in the range defined (i.e. cell A5). Assuming you didn't mean to do something like Application.WorksheetFunction.Sum(ws2.Range("A5:E5")) (to sum the values in those cells) I just changed these to get the first cell.

I changed Filter_Data and a few other spots to use cell/column references instead of ranges when possible.

In Copy_Up I replaced the .Copy function with actually setting the cells to the values (Copy can get weird sometimes so I avoid using it whenever possible).

Additionally, since .Delete and .Insert both slow down the macro considerably, I used a method that avoids doing either by just checking one group of three rows on 'PurchaseOrderStatus' at a time then moving to the next one, and by writing to the first free row on 'Filtered Report' instead of inserting new rows at the top. This sped the macro up considerably (~35 seconds to less than a second).

```<code>Option Explicit

Sub Start_New_Report()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim rng As Range
Dim newRow As Long, lastRow As Long, x As Long

Set ws1 = ThisWorkbook.Sheets("Filtered Report")
Set ws2 = ThisWorkbook.Sheets("PurchaseOrderStatus")

' Turn screen updating / calculation off for speed
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

' Clear Old data and prepare for new lines.
ws1.Range(ws1.Cells(2, 1), ws1.Cells(10000, 9)).ClearContents
ws1.Cells(2, 1) = 1

' Define last row
lastRow = ws2.Cells(ws2.Rows.Count, 1).End(xlUp).Row - 2

' Iterate through all groups of 3 rows on PurchaseOrderStatus sheet
For x = 5 To lastRow Step 3

    ' Determine new row to write to
    newRow = ws1.Cells(ws1.Rows.Count, 1).End(xlUp).Row

    ' Filter raw Syteline data to usable lines
    ws1.Cells(newRow, 2) = ws2.Cells(x, 1)
    ws1.Cells(newRow, 3) = ws2.Cells(x + 1, 1)
    ws1.Cells(newRow, 4) = ws2.Cells(x + 2, 1)
    ws1.Cells(newRow, 5) = ws2.Cells(x, 10)
    ws1.Cells(newRow, 6) = ws2.Cells(x + 2, 15)
    ws1.Cells(newRow, 7) = ws2.Cells(x + 1, 16)
    ws1.Cells(newRow, 8) = ws2.Cells(x + 2, 16)
    ws1.Cells(newRow, 9) = ws2.Cells(x + 2, 22)

    ' Copy Data Up from line below if cells are empty.
    If Application.WorksheetFunction.CountA(ws1.Cells(newRow, 2)) = 0 Then
        ws1.Cells(newRow, 2) = ws1.Cells(newRow - 1, 2)
        ws1.Cells(newRow, 3) = ws1.Cells(newRow - 1, 3)
        ws1.Cells(newRow, 4) = ws1.Cells(newRow - 1, 4)
    End If

    ' Create next index number if not the last row
    If x <> lastRow Then
        ws1.Cells(newRow + 1, 1) = ws1.Cells(newRow, 1).Value + 1
    End If

Next x

' Finish report and sort the order.
ws1.Range(ws1.Columns(1), ws1.Columns(9)).Sort _
    Key1:=ws1.Cells(2, 1), _
    Order1:=xlAscending, _
    Header:=xlYes

' Turn screen updating / calculation back on
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub
</code>```

Body:
Sample WorkbookI have repeating macros that freeze with an error after running 500 to 600 times through. The number of times I need it to run will change every time but mostly be around 2000 times.Error Notice

Line of code it stops onMaE.png

The entire code is below, multiple macros running after each other and calling others until report completes. It runs fine if it runs less than 500 times.

    Sub Start_New_Report()
'
' Start_New_Report Macro
' Clear Old data and prepare for new lines.
'
    Application.ScreenUpdating = False
    Sheets("Filtered Report").Select
    Range("A2:I1048576").Select
    Selection.ClearContents
    Range("A2").Select
    ActiveCell.FormulaR1C1 = "1"

    Call Filter_Data

End Sub

Sub Filter_Data()
' Filter raw Syteline data to usable lines

    Worksheets("Filtered Report").Range("B2").Value = _
        Worksheets("PurchaseOrderStatus").Range("A5:E5").Value
    Worksheets("Filtered Report").Range("C2").Value = _
        Worksheets("PurchaseOrderStatus").Range("A6:C6").Value
    Worksheets("Filtered Report").Range("D2").Value = _
        Worksheets("PurchaseOrderStatus").Range("A7:F7").Value
    Worksheets("Filtered Report").Range("E2").Value = _
        Worksheets("PurchaseOrderStatus").Range("J5").Value
    Worksheets("Filtered Report").Range("F2").Value = _
        Worksheets("PurchaseOrderStatus").Range("O7").Value
    Worksheets("Filtered Report").Range("G2").Value = _
        Worksheets("PurchaseOrderStatus").Range("P6:R6").Value
    Worksheets("Filtered Report").Range("H2").Value = _
        Worksheets("PurchaseOrderStatus").Range("P7:T7").Value
    Worksheets("Filtered Report").Range("I2").Value = _
        Worksheets("PurchaseOrderStatus").Range("V7").Value

    Call Clear_Raw_Data

End Sub

 Sub Clear_Raw_Data()
' Clear Raw Data Lines

    Sheets("PurchaseOrderStatus").Select
    Rows("5:7").Delete

    Call Blank_Cells

End Sub

Sub Blank_Cells()
' Check if blank cells exist in current line

    Sheets("Filtered Report").Select
    Range("B2").Select
If IsEmpty(Range("B2").Value) Then
    Call Copy_Up
Else
    Call Blank_Cells_Raw_Data
End If

End Sub

Sub Copy_Up()
'
' Copy Data Up from line below if cells are empty.
'
    Range("B3:D3").Copy Range("B2:D2")

    Call Blank_Cells_Raw_Data

End Sub

Sub Blank_Cells_Raw_Data()

    Sheets("PurchaseOrderStatus").Select
    Range("V5").Select
If IsEmpty(ActiveCell.Value) Then
    Call Finalize_Report
Else
    Call Clear_for_Next_Line
End If

End Sub

Sub Clear_for_Next_Line()
'
' Clear_for_Next_Line Macro
'
' Insert_line Macro
    Sheets("Filtered Report").Select
    Range("2:2").Insert CopyOrigin:=xlFormatFromRightOrBelow

' Create next index number

    Worksheets("Filtered Report").Range("A2").Value = _
        Worksheets("Filtered Report").Range("A3").Value + 1

    Call Filter_Data

End Sub

Sub Finalize_Report()
'
' Finalize_Report Macro
' Finish report and sort the order.
'
    Sheets("Filtered Report").Select
    Range("A1") = "Index"
    Columns("A:I").Sort key1:=Range("A2"), _
      order1:=xlAscending, Header:=xlYes

End Sub

Body:
In essence, I discarded the entire model where separate subroutines were calling each other in sequence and replaced it with a single subroutine that performs all of the functions.

I opted to rewrite the sample code by removing the use of .Select (see link) and defining worksheet variables whenever possible.

One other thing I noticed was in Blank_Cells and Blank_Cells_Raw_Data, I don't think you meant to use IsEmpty there (which checks to see if a variable is initialized; see link), but rather determine if the cell itself is empty. I changed this to If Application.WorksheetFunction.CountA(Range) = 0 in both instances.

In Filter_Data, I noticed you're setting the value of one cell (e.g. B2) to the value of multiple cells (e.g. A5:E5). In testing this just set the first cell to the first value in the range defined (i.e. cell A5). Assuming you didn't mean to do something like Application.WorksheetFunction.Sum(ws2.Range("A5:E5")) (to sum the values in those cells) I just changed these to get the first cell.

I changed Filter_Data and a few other spots to use cell/column references instead of ranges when possible.

In Copy_Up I replaced the .Copy function with actually setting the cells to the values (Copy can get weird sometimes so I avoid using it whenever possible).

Additionally, since .Delete and .Insert both slow down the macro considerably, I used a method that avoids doing either by just checking one group of three rows on 'PurchaseOrderStatus' at a time then moving to the next one, and by writing to the first free row on 'Filtered Report' instead of inserting new rows at the top. This sped the macro up considerably (~35 seconds to less than a second).

Option Explicit

Sub Start_New_Report()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim rng As Range
Dim newRow As Long, lastRow As Long, x As Long

Set ws1 = ThisWorkbook.Sheets("Filtered Report")
Set ws2 = ThisWorkbook.Sheets("PurchaseOrderStatus")

' Turn screen updating / calculation off for speed
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

' Clear Old data and prepare for new lines.
ws1.Range(ws1.Cells(2, 1), ws1.Cells(10000, 9)).ClearContents
ws1.Cells(2, 1) = 1

' Define last row
lastRow = ws2.Cells(ws2.Rows.Count, 1).End(xlUp).Row - 2

' Iterate through all groups of 3 rows on PurchaseOrderStatus sheet
For x = 5 To lastRow Step 3

    ' Determine new row to write to
    newRow = ws1.Cells(ws1.Rows.Count, 1).End(xlUp).Row

    ' Filter raw Syteline data to usable lines
    ws1.Cells(newRow, 2) = ws2.Cells(x, 1)
    ws1.Cells(newRow, 3) = ws2.Cells(x + 1, 1)
    ws1.Cells(newRow, 4) = ws2.Cells(x + 2, 1)
    ws1.Cells(newRow, 5) = ws2.Cells(x, 10)
    ws1.Cells(newRow, 6) = ws2.Cells(x + 2, 15)
    ws1.Cells(newRow, 7) = ws2.Cells(x + 1, 16)
    ws1.Cells(newRow, 8) = ws2.Cells(x + 2, 16)
    ws1.Cells(newRow, 9) = ws2.Cells(x + 2, 22)

    ' Copy Data Up from line below if cells are empty.
    If Application.WorksheetFunction.CountA(ws1.Cells(newRow, 2)) = 0 Then
        ws1.Cells(newRow, 2) = ws1.Cells(newRow - 1, 2)
        ws1.Cells(newRow, 3) = ws1.Cells(newRow - 1, 3)
        ws1.Cells(newRow, 4) = ws1.Cells(newRow - 1, 4)
    End If

    ' Create next index number if not the last row
    If x <> lastRow Then
        ws1.Cells(newRow + 1, 1) = ws1.Cells(newRow, 1).Value + 1
    End If

Next x

' Finish report and sort the order.
ws1.Range(ws1.Columns(1), ws1.Columns(9)).Sort _
    Key1:=ws1.Cells(2, 1), _
    Order1:=xlAscending, _
    Header:=xlYes

' Turn screen updating / calculation back on
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub


来源: stackexchange

问:
Comparing dates in Javascript for fullcalendar
I'm trying to check dates in Javascript for a calendar (fullcalendar), essentially I just want it to not be able to choose past dates:

```<code>        dateClick: function(info) {
            var today = Date.now();
            var check = new Date(info.dateStr)

            if(check < today)
            {
                alert('You cannot request dates in the past');
                return;
            }
            else
            {
                alert('this is the future');
            }
        },
</code>```

I'm getting some odd results in that, it seems to calculate the past fine, but also calculates the current day as the past AS well as tomorrow.  The day after tomorrow it calculates as the future.  No sure what's going on.

info.dateStr gives the format YYYY-mm-dd.

答:
You should coerce to number using +Date or use .getTime() to make sure you are comparing the numeric timestamp values.  You're probably fine since you're using Date.now(), which returns a timestamp.

Parsing using the string parsing for Date is strongly discouraged, due to issues like the one in OP:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date

Use Date(yyyy, mm, dd, ...) constructor (which uses local time zone) by parsing string manually instead of built-in Date string parsing (which uses UTC if timezone isn't provided).

Using end of the day by adding 24*60*60*1000 to the getTime() value, as that's most likely what you're expecting (same date as today being past is not what most people usually want).

eg:  with date to check 05-29-2020, you actually want anything before 05-29-2020 23:59:999

ie: check=05-29-2020 23:59:999 < today=05-29-2020 22:00:000 === false (not past)

or to put it another way the actual intention when:

05-29-2020 => anything from 05-29-2020 00:00 to 05-29-2020 23:59 => actually same as checking 05-30-2020 00:00 - 1 millisecond

dateClick = function(info) {

        var today = Date.now()
        var check = (([y,m,d])=>new Date(+y,+m-1,+d))(info.dateStr.split(/\D/)).getTime()
           + 24*60*60*1000-1  // add full day so same date as today is not past
        console.log(today,check)

        if(check < today)
        {
            alert('You cannot request dates in the past');
            return;
        }
        else
        {
            alert('this is the future');
        }
    }
    dateClick({dateStr:'2020-05-28'})
    dateClick({dateStr:'2020-05-29'})
    dateClick({dateStr:'2020-05-30'})
    dateClick({dateStr:'2020-05-31'})```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to check dates in Javascript for a calendar (fullcalendar), essentially I just want it to not be able to choose past dates:

        dateClick: function(info) {
            var today = Date.now();
            var check = new Date(info.dateStr)

            if(check < today)
            {
                alert('You cannot request dates in the past');
                return;
            }
            else
            {
                alert('this is the future');
            }
        },

I'm getting some odd results in that, it seems to calculate the past fine, but also calculates the current day as the past AS well as tomorrow.  The day after tomorrow it calculates as the future.  No sure what's going on.

info.dateStr gives the format YYYY-mm-dd.


问:
Reliably detect PDF support on Android device
I am using a method to detect pdf support on an Android device that goes like this

```<code>public boolean canDisplayPdf() {
    PackageManager packageManager = application.getPackageManager();
    Intent testIntent = new Intent(Intent.ACTION_VIEW);
    testIntent.setType("application/pdf");
    if (packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0) {
        return true;
    } else {
        return false;
    }
}
</code>```

And that has been working great so far. I know that at least the HTC default viewer, droidreader and adobe acrobat get reported that way and the right result is returned. However I now got a comment on the market console by a user that says that he has pdf support on the device, but from the described behaviour of the app I conclude that this method returns false.

Is there any better way to detect pdf support?

PS: I would love to be able to ask the user for details on the market.

答: You're doing it correctly. You could consider updating the description of your app to say that you invoke a PDF app using the Android-approved method with the application/pdf MIME type. And also mention that if users have any trouble with the app, you'd appreciate an email to blahblah@myappsupport.com (or whatever your app support email address is setup to be). Maybe then they'd send an email instead of just leaving an anonymous comment.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am using a method to detect pdf support on an Android device that goes like this

public boolean canDisplayPdf() {
    PackageManager packageManager = application.getPackageManager();
    Intent testIntent = new Intent(Intent.ACTION_VIEW);
    testIntent.setType("application/pdf");
    if (packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0) {
        return true;
    } else {
        return false;
    }
}

And that has been working great so far. I know that at least the HTC default viewer, droidreader and adobe acrobat get reported that way and the right result is returned. However I now got a comment on the market console by a user that says that he has pdf support on the device, but from the described behaviour of the app I conclude that this method returns false.

Is there any better way to detect pdf support?

PS: I would love to be able to ask the user for details on the market.

ContentLicense: CC BY-SA 3.0


问:
How do I filter data in data frame and change column's cell values based on it using a loop?
Currently working with a larger data frame with various participant IDs that looks like this:

```<code>#ASC_new Data Frame

           Pcp Choice Target ASC       Product choice_consis
2393 zwyn27soc      B      A   1     USB drive             0
2394 zwyn27soc      B      A   1           job             0
2395 zwyn27soc      B      B   1     USB drive             0
2397 zwyn27soc      B      A   1       printer             0
2399 zwyn27soc      B      B   1 walking shoes             0
2400 zwyn27soc      B      A   1       printer             0
</code>```

I would like to try to loop through each participant (Pcp), and look at their choices in column "Choice." For example, under both of the products "USB drive," the participant chose "B" (Choice). Therefore, under "choice_consis," I want there to be a 1 to replace the 0 because the choices are consistent or equal. Although, my for loop for going through the participants and product names isn't working:

```<code>#Examples/snippets of my values

pcp_list <- list("ybg606k3l", "yk83d2asc", "yl55v0zhm", "zwyn27soc")
product_list <- list("USB drive", "printer", "walking shoes", "job")

#for loop that isn't working
for (i in pcp_list){ #iterating through participant codes
  for (j in product_list){ #iterating through product names
    comparison <- filter(ASC_new, Pcp == i & Product == j) #filtering participant data and products into new dataframe

    choice_1 <- ASC_new$Choice[1] #creating labels for choice 1 and 2
    choice_2 <- ASC_new$Choice[2]

    if (isTRUE(choice_1 == choice_2)){ #comparing choice 1 and choice 2 and adding value of 1 to Choice_consis column if they are equal

      ASC_new$choice_consis[1] <- 1
      ASC_new$choice_consis[2] <- 1

    }
  }

}
</code>```

In the end I would like a data frame where each participant's choice_consis is labeled with a 1 or 0 expressing if they chose the same item (A,B,D) both times that each product appeared.

答:
You can count the unique value of Choice for each Pcp and Product and assign 1 if it is 1 or 0 otherwise.

This can be done in base R :

```<code>df$choice_consis <- +(with(df, ave(Choice, Pcp, Product, FUN = function(x)
                           length(unique(x)))) == 1)
</code>```

dplyr :

```<code>library(dplyr)
df %>%
  group_by(Pcp, Product) %>%
  mutate(choice_consis = +(n_distinct(Choice) == 1))
</code>```

and data.table

```<code>library(data.table)
setDT(df)[, choice_consis := as.integer(uniqueN(Choice) == 1), .(Pcp, Product)]
</code>```

Body:
Currently working with a larger data frame with various participant IDs that looks like this:

#ASC_new Data Frame

           Pcp Choice Target ASC       Product choice_consis
2393 zwyn27soc      B      A   1     USB drive             0
2394 zwyn27soc      B      A   1           job             0
2395 zwyn27soc      B      B   1     USB drive             0
2397 zwyn27soc      B      A   1       printer             0
2399 zwyn27soc      B      B   1 walking shoes             0
2400 zwyn27soc      B      A   1       printer             0

I would like to try to loop through each participant (Pcp), and look at their choices in column "Choice." For example, under both of the products "USB drive," the participant chose "B" (Choice). Therefore, under "choice_consis," I want there to be a 1 to replace the 0 because the choices are consistent or equal. Although, my for loop for going through the participants and product names isn't working:

#Examples/snippets of my values

pcp_list <- list("ybg606k3l", "yk83d2asc", "yl55v0zhm", "zwyn27soc")
product_list <- list("USB drive", "printer", "walking shoes", "job")

#for loop that isn't working
for (i in pcp_list){ #iterating through participant codes
  for (j in product_list){ #iterating through product names
    comparison <- filter(ASC_new, Pcp == i & Product == j) #filtering participant data and products into new dataframe

    choice_1 <- ASC_new$Choice[1] #creating labels for choice 1 and 2
    choice_2 <- ASC_new$Choice[2]

    if (isTRUE(choice_1 == choice_2)){ #comparing choice 1 and choice 2 and adding value of 1 to Choice_consis column if they are equal

      ASC_new$choice_consis[1] <- 1
      ASC_new$choice_consis[2] <- 1

    }
  }

}

In the end I would like a data frame where each participant's choice_consis is labeled with a 1 or 0 expressing if they chose the same item (A,B,D) both times that each product appeared.

Body:
You can count the unique value of Choice for each Pcp and Product and assign 1 if it is 1 or 0 otherwise.

This can be done in base R :

df$choice_consis <- +(with(df, ave(Choice, Pcp, Product, FUN = function(x)
                           length(unique(x)))) == 1)

dplyr :

library(dplyr)
df %>%
  group_by(Pcp, Product) %>%
  mutate(choice_consis = +(n_distinct(Choice) == 1))

and data.table

library(data.table)
setDT(df)[, choice_consis := as.integer(uniqueN(Choice) == 1), .(Pcp, Product)]


问:
Flutter stuck at 'waiting for observatory port to be available' if Android background services is used
I been trying to get write platform code for Flutter to get a background service started. In here, I used a minimal example with no actual work done to show that the application simply won't run. The actual flutter code is not modified at all.

MainActivity.java

```<code>public class MainActivity extends FlutterActivity {

  Intent i = new Intent(this, MainService.class);

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);
  }
}
</code>```

MainService.java

```<code>public class MainService extends IntentService {
  public MainService() {
    super("MainService");
  }

  @Override
  protected void onHandleIntent(Intent Intent) {
  }
}
</code>```

AndroidManifest.xml

```<code> <service android:enabled="true"
android:name=".MainService"></service>
</code>```

The buildVersion is >27 and Manifest file has the service tag added accordingly.

Compiling and running with flutter run -v will show the following message:

```<code>..
[ +121 ms] Starting: Intent { act=android.intent.action.RUN flg=0x20000000 cmp=com.example.hello/.MainActivity (has extras)}
[   +1 ms] Waiting for observatory port to be available...
</code>```

And the installation is stuck.

Is there a workaround about this? If this is an actual bug in Flutter's implementation, does it also mean there is no way to run a Flutter application in the background?

答:
Following @david-conlisk 's answer, it's also possible that you:

renamed the Kotlin package without updating the package line;

copy-pasted the MainActivity code from another class/project, but
forgot to update the package line

All these cases could lead to the same hang and crash.

IMHO, Android Studio should shift away from the current text-file editing hell, and provide an all-in-one project configuration UI similar to Xcode or VisualStudio. The need for editing multiple Gradle config files, and Android's own property pages leaves too much room for mistakes.

Body:
I been trying to get write platform code for Flutter to get a background service started. In here, I used a minimal example with no actual work done to show that the application simply won't run. The actual flutter code is not modified at all.

MainActivity.java

public class MainActivity extends FlutterActivity {

  Intent i = new Intent(this, MainService.class);

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);
  }
}

MainService.java

public class MainService extends IntentService {
  public MainService() {
    super("MainService");
  }

  @Override
  protected void onHandleIntent(Intent Intent) {
  }
}

AndroidManifest.xml

 <service android:enabled="true"
android:name=".MainService"></service>

The buildVersion is >27 and Manifest file has the service tag added accordingly.

Compiling and running with flutter run -v will show the following message:

..
[ +121 ms] Starting: Intent { act=android.intent.action.RUN flg=0x20000000 cmp=com.example.hello/.MainActivity (has extras)}
[   +1 ms] Waiting for observatory port to be available...

And the installation is stuck.

Is there a workaround about this? If this is an actual bug in Flutter's implementation, does it also mean there is no way to run a Flutter application in the background?


问:
Javascript push object as clone
I use d3 for a interactive network application. The data I need to bind changes during the interaction and consists of some selected objects from my JSON variable.

For that I used map on the JSON variable and made some queries to select the appropriate objects. The objects are pushed onto a list and this list is bound as new data.

My problem is, that Javascript pushes objects just as reference. While d3 makes some fancy data modifications my JSON variable gets messy and my queries won't work anymore.

Do I need to copy each object with something like JSON.stringify() or jQuery.extend() or is there a different solution to decouple my JSON variable from the array of objects I pass as data?

答:
If you only need a shallow copy you can do it like this:

```<code>arr.push({...o})
</code>```

Assuming o is the object that you want to push and clone at the same time.

Title: Javascript push object as clone

Body:
If you only need a shallow copy you can do it like this:

arr.push({...o})

Assuming o is the object that you want to push and clone at the same time.


问:
Iterate matrix of vectors using c++ with auto range and structured binding?
I want to do something like this:

```<code>vector<vector<int>>& matrix; -> [[1, 1], [2, 2]]

for (auto [a, b] : matrix) {
    ...
}
</code>```

This won't compile for me. Is this the correct way to do this? If not why?

答:
You can use structured binding only for storage, location of which can be determined at compile time, i.e. bind it to array or class-like storage. Vector's data storage is dynamic, you can't bind to its content , comprising of adjacent elements.
You can bind that list to members of existing type, e.g. if vector contains a pair, a tuple or any similar structure.</p>
```<code>#include <string>
#include <vector>
#include <tuple>
#include <iostream>

int main()
{
   std::vector<std::tuple<int,int, std::string>>
                            v  = {{1,3,"aa"},{3,5,"bb"}};

   for(auto& [a,b,s] : v)
   {
       std::cout << a << b << s << std::endl;
   }
   return 0;
}
</code>```

Body:
I want to do something like this:

vector<vector<int>>& matrix; -> [[1, 1], [2, 2]]

for (auto [a, b] : matrix) {
    ...
}

This won't compile for me. Is this the correct way to do this? If not why?

Body:
You can use structured binding only for storage, location of which can be determined at compile time, i.e. bind it to array or class-like storage. Vector's data storage is dynamic, you can't bind to its content , comprising of adjacent elements.
You can bind that list to members of existing type, e.g. if vector contains a pair, a tuple or any similar structure.

#include <string>
#include <vector>
#include <tuple>
#include <iostream>

int main()
{
   std::vector<std::tuple<int,int, std::string>>
                            v  = {{1,3,"aa"},{3,5,"bb"}};

   for(auto& [a,b,s] : v)
   {
       std::cout << a << b << s << std::endl;
   }
   return 0;
}


问:
I can not connect to Postgres DB with Strapi on Heroku
Trying to deploy Strapi on Heroku with Postgres as described here

https://strapi.io/documentation/v3.x/deployment/heroku.html

But I get this error

```<code>error: no pg_hba.conf entry for host "84.212.51.43", user "ssqqeaz***", database "d6gtu***", SSL off
</code>```

I use Heroku Postgres add-on.

My database config:

```<code>module.exports = ({ env }) => ({
  defaultConnection: 'default',
  connections: {
    default: {
      connector: 'bookshelf',
      settings: {
        client: 'postgres',
        host: env('DATABASE_HOST', '127.0.0.1'),
        port: env.int('DATABASE_PORT', 27017),
        database: env('DATABASE_NAME', 'strapi'),
        username: env('DATABASE_USERNAME', ''),
        password: env('DATABASE_PASSWORD', ''),
      },
      options: {
        ssl: true
      },
    },
  },
});

</code>```

Why? Please help!

答:
The current configuration you've posted will not work with a Heroku Postgres database. The primary concern here is that you're reading components of your postgres database url out of manually set config vars. This is very much recommended against by Heroku because they may need to move the database to a new host in the case of disasters. DATABASE_URL is set by Heroku when you create a database on an app and it's the one config var you can rely on to stay up-to-date. Moving on...

You will need to parse the username, password, host, port and database name out of the DATABASE_URL config var and supply those to the attributes of the settings block. Based on the error you provided, I can tell you're not presently doing this because Heroku databse usernames all start with a 'u', so something is very wrong if you get the error user "ssqqeaz***". As a first step you might try hard coding these values in the settings block to make sure it works (make sure to rotate the credentials after you do it, or otherwise clean up your git history to prevent leaked creds). The pattern for a postgres connection url is something like this: postgres:// $USERNAME : $PASSWORD @ $HOSTNAME : $PORT / $DATABASE_NAME.

Body:
Trying to deploy Strapi on Heroku with Postgres as described here

https://strapi.io/documentation/v3.x/deployment/heroku.html

But I get this error

error: no pg_hba.conf entry for host "84.212.51.43", user "ssqqeaz***", database "d6gtu***", SSL off

I use Heroku Postgres add-on.

My database config:

module.exports = ({ env }) => ({
  defaultConnection: 'default',
  connections: {
    default: {
      connector: 'bookshelf',
      settings: {
        client: 'postgres',
        host: env('DATABASE_HOST', '127.0.0.1'),
        port: env.int('DATABASE_PORT', 27017),
        database: env('DATABASE_NAME', 'strapi'),
        username: env('DATABASE_USERNAME', ''),
        password: env('DATABASE_PASSWORD', ''),
      },
      options: {
        ssl: true
      },
    },
  },
});

Why? Please help!


问:
How to fetch the last item in a JSON in C#
I'm trying to get a single value out of a JSON response from Azure Rest API.

Below is my code where I was able to get to final array but unable to fetch the last item from this array.

```<code>            string token = await GetAccessToken(GMETenantID, GMEClientID, GMEAppKey);

            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://management.azure.com/subscriptions/")
            };
            string URI = $"/subscriptions/{SubscriptionGUID}/providers/Microsoft.Storage/storageAccounts?api-version=2019-06-01";

            httpClient.DefaultRequestHeaders.Remove("Authorization");
            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            HttpResponseMessage response = await httpClient.GetAsync(URI).ConfigureAwait(false);

            var HttpsResponse = await response.Content.ReadAsStringAsync();
            dynamic Result = JsonConvert.DeserializeObject<object>(HttpsResponse);

            foreach (dynamic item in Result["value"])
            {
                string StorageID = item.id;
                string StorageAccountName = item.name;
                string ResourceType = item.type;

                int CharsToRemove = 12 + ResourceType.Length + StorageAccountName.Length;

                string ResourceGroupName = StorageID.Remove(0,67);
                ResourceGroupName = ResourceGroupName.Remove(ResourceGroupName.Length - CharsToRemove);

                string StartTime = DateTime.Now.AddDays(-7).ToString("yyyy-MM-ddTHH:mm:ss") + "Z"; ;
                string EndTime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + "Z";

                var BlobhttpClient = new HttpClient
                {
                    BaseAddress = new Uri("https://management.azure.com/subscriptions/")
                };

                string BlobURI = $"/subscriptions/{SubscriptionGUID}/resourceGroups/{ResourceGroupName}/providers/{ResourceType}/{StorageAccountName}/blobServices/default/providers/microsoft.insights/metrics?timespan={StartTime}/{EndTime}&aggregation=average&metricnames=BlobCapacity&api-version=2018-01-01";
                BlobhttpClient.DefaultRequestHeaders.Remove("Authorization");
                BlobhttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                HttpResponseMessage Blobresponse = await httpClient.GetAsync(BlobURI).ConfigureAwait(false);
                var BlobHttpsResponse = await Blobresponse.Content.ReadAsStringAsync();

                dynamic value = JObject.Parse(BlobHttpsResponse);

                foreach (dynamic List1 in value["value"])
                {
                    foreach (dynamic List2 in List1["timeseries"])
                    {
                        foreach (dynamic List3 in List2["data"])
                        {
                            Console.WriteLine((long?)List3["average"]);
                        }
                    }
                }
            }
            Console.ReadLine();
</code>```

I also feel there must be an easier way to get this one value out instead of using 3 Foreach loops.

HttpsResponse: (There are a 168 timestamp and average values in the actual response but i've put only 3 values)

```<code>{
  "cost": 0,
  "timespan": "2020-05-22T03:04:46Z/2020-05-29T03:04:46Z",
  "interval": "PT1H",
  "value": [
    {
      "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/MyResourceGroupName/providers/Microsoft.Storage/storageAccounts/MyAstorageAccountName/blobServices/default/providers/Microsoft.Insights/metrics/BlobCapacity",
      "type": "Microsoft.Insights/metrics",
      "name": {
        "value": "BlobCapacity",
        "localizedValue": "Blob Capacity"
      },
      "displayDescription": "The amount of storage used by the storage account's Blob service in bytes.",
      "unit": "Bytes",
      ".timeseries": [
        {
          "metadatavalues": [],
          "data": [
            {
              "timeStamp": "2020-05-22T03:04:00Z",
              "average": 586904516140.0
            },
            {
              "timeStamp": "2020-05-22T04:04:00Z",
              "average": 587058965680.0
            },
            {
              "timeStamp": "2020-05-22T05:04:00Z",
              "average": 587058965680.0
            }
          ]
        }
      ],
      "errorCode": "Success"
    }
  ],
  "namespace": "Microsoft.Storage/storageAccounts/blobServices",
  "resourceregion": "eastus2"
}
</code>```

All I want is the number 587058965680 which is the last value of the JSON and the most recent timestamp.

Pretty much I want to get exact result the way I'm getting in below powershell code
PowerShell works like a charm in 4 lines but I had to write so many lines in C#

```<code>$StorageAccounts = Get-AzStorageAccount -ResourceGroupName "My ResourceGroupName"

$StorageAccountID = $StorageAccounts.ID + "/blobServices/default"
$Start = (get-date).AddDays(-7)
$End = get-date

$Metric = Get-AzMetric -ResourceId $StorageAccountID -MetricName "BlobCapacity" -StartTime $Start -EndTime $End  -WarningAction Ignore

$ContainerSize = ($Metric.Data | sort-object -Descending Average | Select-Object -First 1).Average/1024/1024/1024
</code>```

答:
Create a simple model for it :

```<code>public class Data
{
    [JsonProperty("timeStamp")]
    public DateTime TimeStamp { get; set; }

    [JsonProperty("average")]
    public decimal Average { get; set; }
}
</code>```

Now, just use JObject to navigate to the data key in the json, and deserilize it.

```<code>var jObj = JObject.Parse(json);
var data = jObj["value"][0][".timeseries"][0]["data"].ToString();
var dataList = JsonConvert.DeserializeObject<IEnumerable<Data>>(data);
</code>```

Then, you can use Linq to get the last element in the array :

```<code>var last = dataList.Last();
</code>```

If you don't want to use Models, you can have a direct access to the values using JObject

So, you can do this directly :

```<code>var jObj = JObject.Parse(json);
var data = jObj["value"][0][".timeseries"][0]["data"].Last();
var avg = data["average"];
</code>```

Body:
I'm trying to get a single value out of a JSON response from Azure Rest API.

Below is my code where I was able to get to final array but unable to fetch the last item from this array.

            string token = await GetAccessToken(GMETenantID, GMEClientID, GMEAppKey);

            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://management.azure.com/subscriptions/")
            };
            string URI = $"/subscriptions/{SubscriptionGUID}/providers/Microsoft.Storage/storageAccounts?api-version=2019-06-01";

            httpClient.DefaultRequestHeaders.Remove("Authorization");
            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            HttpResponseMessage response = await httpClient.GetAsync(URI).ConfigureAwait(false);

            var HttpsResponse = await response.Content.ReadAsStringAsync();
            dynamic Result = JsonConvert.DeserializeObject<object>(HttpsResponse);

            foreach (dynamic item in Result["value"])
            {
                string StorageID = item.id;
                string StorageAccountName = item.name;
                string ResourceType = item.type;

                int CharsToRemove = 12 + ResourceType.Length + StorageAccountName.Length;

                string ResourceGroupName = StorageID.Remove(0,67);
                ResourceGroupName = ResourceGroupName.Remove(ResourceGroupName.Length - CharsToRemove);

                string StartTime = DateTime.Now.AddDays(-7).ToString("yyyy-MM-ddTHH:mm:ss") + "Z"; ;
                string EndTime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + "Z";

                var BlobhttpClient = new HttpClient
                {
                    BaseAddress = new Uri("https://management.azure.com/subscriptions/")
                };

                string BlobURI = $"/subscriptions/{SubscriptionGUID}/resourceGroups/{ResourceGroupName}/providers/{ResourceType}/{StorageAccountName}/blobServices/default/providers/microsoft.insights/metrics?timespan={StartTime}/{EndTime}&aggregation=average&metricnames=BlobCapacity&api-version=2018-01-01";
                BlobhttpClient.DefaultRequestHeaders.Remove("Authorization");
                BlobhttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                HttpResponseMessage Blobresponse = await httpClient.GetAsync(BlobURI).ConfigureAwait(false);
                var BlobHttpsResponse = await Blobresponse.Content.ReadAsStringAsync();

                dynamic value = JObject.Parse(BlobHttpsResponse);

                foreach (dynamic List1 in value["value"])
                {
                    foreach (dynamic List2 in List1["timeseries"])
                    {
                        foreach (dynamic List3 in List2["data"])
                        {
                            Console.WriteLine((long?)List3["average"]);
                        }
                    }
                }
            }
            Console.ReadLine();

I also feel there must be an easier way to get this one value out instead of using 3 Foreach loops.

HttpsResponse: (There are a 168 timestamp and average values in the actual response but i've put only 3 values)

{
  "cost": 0,
  "timespan": "2020-05-22T03:04:46Z/2020-05-29T03:04:46Z",
  "interval": "PT1H",
  "value": [
    {
      "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/MyResourceGroupName/providers/Microsoft.Storage/storageAccounts/MyAstorageAccountName/blobServices/default/providers/Microsoft.Insights/metrics/BlobCapacity",
      "type": "Microsoft.Insights/metrics",
      "name": {
        "value": "BlobCapacity",
        "localizedValue": "Blob Capacity"
      },
      "displayDescription": "The amount of storage used by the storage account's Blob service in bytes.",
      "unit": "Bytes",
      ".timeseries": [
        {
          "metadatavalues": [],
          "data": [
            {
              "timeStamp": "2020-05-22T03:04:00Z",
              "average": 586904516140.0
            },
            {
              "timeStamp": "2020-05-22T04:04:00Z",
              "average": 587058965680.0
            },
            {
              "timeStamp": "2020-05-22T05:04:00Z",
              "average": 587058965680.0
            }
          ]
        }
      ],
      "errorCode": "Success"
    }
  ],
  "namespace": "Microsoft.Storage/storageAccounts/blobServices",
  "resourceregion": "eastus2"
}

All I want is the number 587058965680 which is the last value of the JSON and the most recent timestamp.

Pretty much I want to get exact result the way I'm getting in below powershell code
PowerShell works like a charm in 4 lines but I had to write so many lines in C#

$StorageAccounts = Get-AzStorageAccount -ResourceGroupName "My ResourceGroupName"

$StorageAccountID = $StorageAccounts.ID + "/blobServices/default"
$Start = (get-date).AddDays(-7)
$End = get-date

$Metric = Get-AzMetric -ResourceId $StorageAccountID -MetricName "BlobCapacity" -StartTime $Start -EndTime $End  -WarningAction Ignore

$ContainerSize = ($Metric.Data | sort-object -Descending Average | Select-Object -First 1).Average/1024/1024/1024

Body:
Create a simple model for it :

public class Data
{
    [JsonProperty("timeStamp")]
    public DateTime TimeStamp { get; set; }

    [JsonProperty("average")]
    public decimal Average { get; set; }
}

Now, just use JObject to navigate to the data key in the json, and deserilize it.

var jObj = JObject.Parse(json);
var data = jObj["value"][0][".timeseries"][0]["data"].ToString();
var dataList = JsonConvert.DeserializeObject<IEnumerable<Data>>(data);

Then, you can use Linq to get the last element in the array :

var last = dataList.Last();

If you don't want to use Models, you can have a direct access to the values using JObject

So, you can do this directly :

var jObj = JObject.Parse(json);
var data = jObj["value"][0][".timeseries"][0]["data"].Last();
var avg = data["average"];


问:
C#, WPF: Do work on each element in a list View
I have a WPF app with a listview control.  The application basically loads a file into a list view.  I then want to iterate through each listview element, highlighting the current row, and performing a certain task.

When the task is done I update another file and a panel with the results and move on to the next listview element.

I've done stuff like this in WinForms before, but I'm quite green when it comes to WPF.  I guess my main concern is how to handle the second thread, other than the UI thread.  Is the threading model any different in WPF?

Secondly, the program is essentially a loop through an ObservableCollection:

```<code>for (int i = 0 ; i < Collection.Count; i++)
{
   HighlightCurrentRowInListView();
   Collection[i].DoWork();
   PostWorkToPanel();

   // Bad loop around code
   if (i == (Collection.Count - 1))
   { i = -1; }
}
</code>```

If I make a change to the collection (which is an ObservableCollection), how will the loop update?  Whats the best iteration method, foreach, .ForEach(x=>x) for this context?  The program should keep running until a "STOP" button or something is pressed.

答:
If you need info on the threading model see the respective MSDN page.

Since you have an observable collection you can handle the CollectionChanged event, you can see if items have been added or removed so you can add or remove those from a workqueue that you could just take items from until it's empty (while-loop).

To change UI-Elements from the background thread you need to use the Dispatcher, see the threading model link i gave for help on that topic.

Body:
I have a WPF app with a listview control.  The application basically loads a file into a list view.  I then want to iterate through each listview element, highlighting the current row, and performing a certain task.

When the task is done I update another file and a panel with the results and move on to the next listview element.

I've done stuff like this in WinForms before, but I'm quite green when it comes to WPF.  I guess my main concern is how to handle the second thread, other than the UI thread.  Is the threading model any different in WPF?

Secondly, the program is essentially a loop through an ObservableCollection:

for (int i = 0 ; i < Collection.Count; i++)
{
   HighlightCurrentRowInListView();
   Collection[i].DoWork();
   PostWorkToPanel();

   // Bad loop around code
   if (i == (Collection.Count - 1))
   { i = -1; }
}

If I make a change to the collection (which is an ObservableCollection), how will the loop update?  Whats the best iteration method, foreach, .ForEach(x=>x) for this context?  The program should keep running until a "STOP" button or something is pressed.


问:
Why are these loop & hashing operations take O(N) time complexity?
Given the array :

```<code>int arr[]= {1, 2, 3, 2, 3, 1, 3}
</code>```

You are asked to find a number within the array that occurs odd number of times. It's 3 (occurring 3 times). The time complexity should be at least O(n).
The solution is to use an HashMap. Elements become keys and their counts become values of the hashmap.

```<code>// Code belongs to geeksforgeeks.org
// function to find the element occurring odd
    // number of times

    static int getOddOccurrence(int arr[], int n)
    {
        HashMap<Integer,Integer> hmap = new HashMap<>();
        // Putting all elements into the HashMap
        for(int i = 0; i < n; i++)
        {
            if(hmap.containsKey(arr[i]))
            {
                int val = hmap.get(arr[i]);
                // If array element is already present then
                // increase the count of that element.
                hmap.put(arr[i], val + 1);
            }
            else
                // if array element is not present then put
                // element into the HashMap and initialize
                // the count to one.
                hmap.put(arr[i], 1);
        }

        // Checking for odd occurrence of each element present
          // in the HashMap
        for(Integer a:hmap.keySet())
        {
            if(hmap.get(a) % 2 != 0)
                return a;
        }
        return -1;
    }
</code>```

I don't get why this overall operation takes O(N) time complexity. If I think about it, the loop alone takes O(N) time complexity. Those hmap.put (an insert operation) and hmap.get(a find operations) take O(N) and they are nested within the loop. So normally I would think this function takes O(N^2) times. Why it instead takes O(N)?.

答: The algorithm first iterates the array of numbers, of size n, to generate the map with counts of occurrences.  It should be clear why this is an O(n) operation.  Then, after the hashmap has been built, it iterates that map and finds all entries whose counts are odd numbers.  The size of this map would in practice be somewhere between 1 (in the case of all input numbers being the same), and n (in the case where all inputs are different).  So, this second operation is also bounded by O(n), leaving the entire algorithm O(n).

Body:
Given the array :

int arr[]= {1, 2, 3, 2, 3, 1, 3}

You are asked to find a number within the array that occurs odd number of times. It's 3 (occurring 3 times). The time complexity should be at least O(n).
The solution is to use an HashMap. Elements become keys and their counts become values of the hashmap.

// Code belongs to geeksforgeeks.org
// function to find the element occurring odd
    // number of times

    static int getOddOccurrence(int arr[], int n)
    {
        HashMap<Integer,Integer> hmap = new HashMap<>();
        // Putting all elements into the HashMap
        for(int i = 0; i < n; i++)
        {
            if(hmap.containsKey(arr[i]))
            {
                int val = hmap.get(arr[i]);
                // If array element is already present then
                // increase the count of that element.
                hmap.put(arr[i], val + 1);
            }
            else
                // if array element is not present then put
                // element into the HashMap and initialize
                // the count to one.
                hmap.put(arr[i], 1);
        }

        // Checking for odd occurrence of each element present
          // in the HashMap
        for(Integer a:hmap.keySet())
        {
            if(hmap.get(a) % 2 != 0)
                return a;
        }
        return -1;
    }

I don't get why this overall operation takes O(N) time complexity. If I think about it, the loop alone takes O(N) time complexity. Those hmap.put (an insert operation) and hmap.get(a find operations) take O(N) and they are nested within the loop. So normally I would think this function takes O(N^2) times. Why it instead takes O(N)?.


问:
How to get mod_wsgi to pick up my virtualenv
I'm very new to working with Flask-

according to http://flask.pocoo.org/docs/0.12/deploying/mod_wsgi/

under the heading "Working with Virtual Environments"
I read:

For Python 3 add the following lines to the top of your .wsgi file:

```<code>activate_this = '/path/to/env/bin/activate_this.py'
with open(activate_this) as file_:
    exec(file_.read(), dict(__file__=activate_this)) This sets up the load paths according to the settings of the virtual environment.
</code>```

Keep in mind that the path has to be absolute.

to activate my venv I use the command from linux:

```<code> my_env/bin/activate
</code>```

I looked in my my_env/bin/ directory and do not see any .py files.
Am I suppose to create a .py file that in my_env/bin/ that will be called by the .wsgi file?

答:
I was having the same issue, the solution is actually quite simple. You need to install libapache2-mod-wsgi-py3 instead of libapache2-mod-wsgi. The latter is for python 2.

You can then activate your environment by adding the environment's site-packages to the system path. For example, for me (using venv) I can do this by adding the following line to my *.wgsi file.

sys.path.insert(0,"/path/to/venv/lib/python3.8/site-packages")
```

Body:
I'm very new to working with Flask-

according to http://flask.pocoo.org/docs/0.12/deploying/mod_wsgi/

under the heading "Working with Virtual Environments"
I read:

For Python 3 add the following lines to the top of your .wsgi file:

activate_this = '/path/to/env/bin/activate_this.py'
with open(activate_this) as file_:
    exec(file_.read(), dict(__file__=activate_this)) This sets up the load paths according to the settings of the virtual environment.

Keep in mind that the path has to be absolute.

to activate my venv I use the command from linux:

 my_env/bin/activate

I looked in my my_env/bin/ directory and do not see any .py files.
Am I suppose to create a .py file that in my_env/bin/ that will be called by the .wsgi file?


问:
Create a custom legend for multiple subplots
I want to make scatter subplots, but I need to differentiate each marker according to column "Wall_construction".
My data includes:
content of data

Here is what I have so far:

```<code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.read_csv("forpythonultimo.csv")
grouped = df.groupby(["panel_coverage", "wwr"])
ncols= 5
nrows = int(np.ceil(grouped.ngroups/ncols))
cols = ['WWR {}'.format(col) for col in ['10%', '20%', '30%', '40%', '50%']]
rows = ['Panel {}'.format(row) for row in ['42%', '47%', '52%', '57%', '63%', '68%', '75%', '78%']]

fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12, 4), sharex=True, sharey=True)
pad = 5

for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
    grouped.get_group(key).plot(x='disc_hours', y='Total_heat_gain', kind='scatter', subplots=True, ax=ax)
    ax.set_xlabel('')
    ax.set_ylabel('')
    ax.set_title('')

for ax, col in zip(axes[0], cols):
    ax.annotate(col, xy=(0.5, 1), xytext=(0, pad),
            xycoords='axes fraction', textcoords='offset points',
            size='large', ha='center', va='baseline')

for ax, row in zip(axes[:,0], rows):
    ax.annotate(row, xy=(0, 0.5), xytext=(-ax.yaxis.labelpad - pad, 0),
            xycoords=ax.yaxis.label, textcoords='offset points',
            size='large', ha='right', va='center')
plt.show()
</code>```

Subplots

Thanks in advance for your help.

答:
I haven't actually tried it in the code, but I think the usual legend is displayed as a list of df['Wall_constraction'] and given to the label. The rest is up to you and your custom.

```<code>lbls = list(df['Wall_constraction'])
for (key, ax, l) in zip(grouped.groups.keys(), axes.flatten(), lbls):
    grouped.get_group(key).plot(x='disc_hours', y='Total_heat_gain', kind='scatter', subplots=True, ax=ax, lable=l)
    ax.set_xlabel('')
    ax.set_ylabel('')
    ax.set_title('')
    ax.legend(loc="upper right", bbox_to_anchor=(0.5, 0, 0.5, 1), borderaxespad=0)
</code>```

Body:
I want to make scatter subplots, but I need to differentiate each marker according to column "Wall_construction".
My data includes:
content of data

Here is what I have so far:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.read_csv("forpythonultimo.csv")
grouped = df.groupby(["panel_coverage", "wwr"])
ncols= 5
nrows = int(np.ceil(grouped.ngroups/ncols))
cols = ['WWR {}'.format(col) for col in ['10%', '20%', '30%', '40%', '50%']]
rows = ['Panel {}'.format(row) for row in ['42%', '47%', '52%', '57%', '63%', '68%', '75%', '78%']]

fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12, 4), sharex=True, sharey=True)
pad = 5

for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
    grouped.get_group(key).plot(x='disc_hours', y='Total_heat_gain', kind='scatter', subplots=True, ax=ax)
    ax.set_xlabel('')
    ax.set_ylabel('')
    ax.set_title('')

for ax, col in zip(axes[0], cols):
    ax.annotate(col, xy=(0.5, 1), xytext=(0, pad),
            xycoords='axes fraction', textcoords='offset points',
            size='large', ha='center', va='baseline')

for ax, row in zip(axes[:,0], rows):
    ax.annotate(row, xy=(0, 0.5), xytext=(-ax.yaxis.labelpad - pad, 0),
            xycoords=ax.yaxis.label, textcoords='offset points',
            size='large', ha='right', va='center')
plt.show()

Subplots

Thanks in advance for your help.

Body:
I haven't actually tried it in the code, but I think the usual legend is displayed as a list of df['Wall_constraction'] and given to the label. The rest is up to you and your custom.

lbls = list(df['Wall_constraction'])
for (key, ax, l) in zip(grouped.groups.keys(), axes.flatten(), lbls):
    grouped.get_group(key).plot(x='disc_hours', y='Total_heat_gain', kind='scatter', subplots=True, ax=ax, lable=l)
    ax.set_xlabel('')
    ax.set_ylabel('')
    ax.set_title('')
    ax.legend(loc="upper right", bbox_to_anchor=(0.5, 0, 0.5, 1), borderaxespad=0)


问:
C++ concept check vs inheritance
What is the relationship between using virtual functions and C++ inheritance mechanisms versus using templates and something like boost concepts?

It seems like there is quite an overlap of what is possible. Namely, it appears to be possible to achieve polymorphic behavior with either approach. So, when does it make sense to favor one over the other?

The reason why I bring this up is because I have a templated container, where the containers themselves have a hierarchical relationship. I would like to write algorithms that use these containers without caring about which specific container it is. Also, some algorithms would benefit from knowing that the template type satisfied certain concepts (Comparable, for example).

So, on one hand, I want containers to behave polymorphicly. On the other, I still have to use concepts if I want to correctly implement some algorithms. What is a junior developer to do?

答:
In this specific case you can do something like

```<code>template<typename T>
class ContainerBase{};

template<typename T>
class ContainerDerived : public ContainerBase<T> {};
</code>```

Since each 'Container' type is unique for each template type, there's no reason member functions of each container type couldn't be specialized on the templated type's traits.

OwnerDisplayName: Voltaire

Title: C++ concept check vs inheritance

Body:
In this specific case you can do something like

template<typename T>
class ContainerBase{};

template<typename T>
class ContainerDerived : public ContainerBase<T> {};

Since each 'Container' type is unique for each template type, there's no reason member functions of each container type couldn't be specialized on the templated type's traits.


问:
reverse serialize() -jquery
I sent my data (json) for an ajax request with this code;

```<code>var formdata = $("#customForm").serialize();

            type: "post",
            dataType: "json",
            data: formdata,
</code>```

In the php file, there is possible reverse the serialize?

or i need to make  something like that: $pass = $_POST['pass']; for all fields?

thanks

答:
Try PHP's extract function:

```<code>extract($_POST);
</code>```

Example:

```<code>$_POST = array('var_1' => 1234, 'var_2' => 'another variable');

extract($_POST);

echo $var_1.' '.$var_2;
</code>```

Outputs:

1234 another variable

Applied to Your Situation:

extract($_POST);

Would result in whatever key => value pairs present in the $_POST array being extracted into variables.

Like doing $pass = $_POST['pass'] on all variables in the $_POST array.

Explanation:

extract will import variables from an array into the current symbol table.

It checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table.

From PHP Docs (extract)

Title: reverse serialize() -jquery

Body:
I sent my data (json) for an ajax request with this code;

var formdata = $("#customForm").serialize();

            type: "post",
            dataType: "json",
            data: formdata,

In the php file, there is possible reverse the serialize?

or i need to make  something like that: $pass = $_POST['pass']; for all fields?

thanks

Body:
Try PHP's extract function:

extract($_POST);

Example:

$_POST = array('var_1' => 1234, 'var_2' => 'another variable');

extract($_POST);

echo $var_1.' '.$var_2;

Outputs:

1234 another variable

Applied to Your Situation:

extract($_POST);

Would result in whatever key => value pairs present in the $_POST array being extracted into variables.

Like doing $pass = $_POST['pass'] on all variables in the $_POST array.

Explanation:

extract will import variables from an array into the current symbol table.

It checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table.

From PHP Docs (extract)


问:
ThinkingSphinx::SphinxError (Unknown MySQL error):
ThinkingSphinx was working fine in my app on Ubuntu and MacOS Mojave. Then I upgrade my macOS to Catalina 10.15.4 . Now thinking sphinx giving error Unknown MySQL.

Altough commands like rake ts:rebuild , rake ts:index are working fine but when I search on model  it gives an error ThinkingSphinx::SphinxError: Unknown MySQL error.

Mysql Version is 8. As per Unknown Mysql Error Sphinx v2.2 (and 3.0) is not compatible with MySQL v8. So I download sphinx 3.2.1 and place its bin folder inside /usr/local/bin but its still not working

答:
Just to confirm: you will need to place the binaries from the downloaded bin folder inside /usr/local/bin - but not the downloaded bin folder itself.

So, make sure that /usr/local/bin/searchd is the right version - just use the full path, no arguments. And confirm that you've not put the files at /user/local/bin/bin/searchd, etc.


问:
I tried to access the name property of a radio input in the DOM, but apparently all the name fields have a value of false?
```<code><div class="tab">Question 1 of 12
      <p><input type="radio" name="gender" value="male">Male</p>
      <p><input type="radio" name="gender" value="female">Female</p>
</div>
</code>```

I have a couple of elements with the same html format as above, and i'm trying to perform some operation in which i'll need the value of the name property,

```<code>var x = document.getElementsByClassName("tab")
var y = x[0].getElementsByTagName("input")
</code>```

in this case, y[0].name should evaluate to "gender", instead it evaluates to false as does all other input name properties. Is there a reason for this?

答:
This fragment seems to be ok.

y[0].name returns 'gender' as expected.

It's probably something else in your code.

Body:
Question 1 of 12

<input type="radio" name="gender" value="male">Male

<input type="radio" name="gender" value="female">Female

I have a couple of elements with the same html format as above, and i'm trying to perform some operation in which i'll need the value of the name property,

var x = document.getElementsByClassName("tab")
var y = x[0].getElementsByTagName("input")

in this case, y[0].name should evaluate to "gender", instead it evaluates to false as does all other input name properties. Is there a reason for this?


问:
Why starting a service from command line in Android needs root access (su)?
I am trying to start a service of an another app (not mine) from command line in my Android app. But I've noticed that it works only if I run "su". My phone of course is "rooted".
Maybe there is another way to start a service of an app without needing to execute a shell command?

This code works:

```<code>   try {
                            Process process = Runtime.getRuntime().exec("su", null,null);
                            OutputStream outputStream = process.getOutputStream();

                            outputStream.write(("am startservice -a com.companyname.notmyapp.TEST --option a 1").getBytes("ASCII"));

                            outputStream.flush();
                            outputStream.close();
                            process.waitFor();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
</code>```

This one it doesn't:

```<code>   try {
                            Process process = Runtime.getRuntime().exec("am startservice -a com.companyname.notmyapp.TEST --option a 1", null,null);
                            //OutputStream outputStream = process.getOutputStream();
                            //outputStream.flush();
                            //outputStream.close();
                            process.waitFor();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
</code>```

答:
Intent intent = new Intent(Intent.ACTION_VIEW);
String packageName = "com.ang.chapter_2_service"; //the package name what you want to start

String className = "com.ang.chapter_2.poolBinder.BinderPoolService"; //service full name what you want to start
intent.setClassName(packageName, className);
startService(intent);//or bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

the activity is same to this.

Of course the service or activity what you want to start  need a tag in manifest.xml:

```<code>android:exported="true"
</code>```

Body:
I am trying to start a service of an another app (not mine) from command line in my Android app. But I've noticed that it works only if I run "su". My phone of course is "rooted".
Maybe there is another way to start a service of an app without needing to execute a shell command?

This code works:

   try {
                            Process process = Runtime.getRuntime().exec("su", null,null);
                            OutputStream outputStream = process.getOutputStream();

                            outputStream.write(("am startservice -a com.companyname.notmyapp.TEST --option a 1").getBytes("ASCII"));

                            outputStream.flush();
                            outputStream.close();
                            process.waitFor();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

This one it doesn't:

   try {
                            Process process = Runtime.getRuntime().exec("am startservice -a com.companyname.notmyapp.TEST --option a 1", null,null);
                            //OutputStream outputStream = process.getOutputStream();
                            //outputStream.flush();
                            //outputStream.close();
                            process.waitFor();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

Body:
Intent intent = new Intent(Intent.ACTION_VIEW);
String packageName = "com.ang.chapter_2_service"; //the package name what you want to start

String className = "com.ang.chapter_2.poolBinder.BinderPoolService"; //service full name what you want to start
intent.setClassName(packageName, className);
startService(intent);//or bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

the activity is same to this.

Of course the service or activity what you want to start  need a tag in manifest.xml:

android:exported="true"


问:
Spring Boot Application using Oracle - ORA-01000: maximum open cursors exceeded - error happening during load testing
Am working on spring-boot application. While performing load testing we get error

"ORA-01000:maximum open cursors exceeded"

We have following entries for spring boot and jdbc in the pom.xml file

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
</parent>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.3</version>
</dependency>
</code>```

To fix the issue I tried changing the "ojdbc" from 6 to 8.

```<code><dependency>
    <groupId>com.oracle.jdbc</groupId>
    <artifactId>ojdbc8</artifactId>
    <version>12.2.0.1</version>
</dependency>
</code>```

but I still got the same issue.

All our backend calls using either "jdbcTemplate" or "namedParameterJdbcTemplate".

The error is happening during load testing.
Our Oracle DB cursor limit is 1000.
Load test run game the error after 1hr 55mins and failure rate our our service was 0.5%
the number of users/threads is set to 25.

Looking for some suggestions to fix this issue.

答:
Okay, I finally got an answer. My project was EXACTLY same as yours(Spring boot 2.1.6.RELEASE and ojdbc8 12.2.0.1), (additionally Spring data jpa,) and upgrading version to 2.2.5.RELEASE didn't work for me.

I had the same exception occurs when every time I call the same function using certain amount of data(or above) - I tried to get rid of this error by upgrading ojdbc version to 19.6.0.0, adding spring config spring.jdbc.getParameterType.ignore, and so on. None of them works for me.

Finally what I found was the return type of jpa repository method. Originally my method was like this :

```<code>Stream<MyEntity> findByMyColumn(MyColumnType myColumnValue);
</code>```

note that the return type of this repository method is java.util.Stream. The reason why I get this return type as stream is that this method is used only when the streaming is required.
And everytime I execute same procedure, the stack trace contains this method and I feel weird.
So I changed the type to List, and the error is GONE!!!

```<code>List<MyEntity> findByMyColumn(MyColumnType myColumnValue);
</code>```

I think that the Stream is holding cursors even if the stream ended. Obviously it's a bug on Spring boot or ojdbc, but none of them seems to recognize or have willing to fix this problem.

Hope that helps to your situation, too.

Body:
Am working on spring-boot application. While performing load testing we get error

"ORA-01000:maximum open cursors exceeded"

We have following entries for spring boot and jdbc in the pom.xml file

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
</parent>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.3</version>
</dependency>

To fix the issue I tried changing the "ojdbc" from 6 to 8.

<dependency>
    <groupId>com.oracle.jdbc</groupId>
    <artifactId>ojdbc8</artifactId>
    <version>12.2.0.1</version>
</dependency>

but I still got the same issue.

All our backend calls using either "jdbcTemplate" or "namedParameterJdbcTemplate".

The error is happening during load testing.
Our Oracle DB cursor limit is 1000.
Load test run game the error after 1hr 55mins and failure rate our our service was 0.5%
the number of users/threads is set to 25.

Looking for some suggestions to fix this issue.

Body:
Okay, I finally got an answer. My project was EXACTLY same as yours(Spring boot 2.1.6.RELEASE and ojdbc8 12.2.0.1), (additionally Spring data jpa,) and upgrading version to 2.2.5.RELEASE didn't work for me.

I had the same exception occurs when every time I call the same function using certain amount of data(or above) - I tried to get rid of this error by upgrading ojdbc version to 19.6.0.0, adding spring config spring.jdbc.getParameterType.ignore, and so on. None of them works for me.

Finally what I found was the return type of jpa repository method. Originally my method was like this :

Stream<MyEntity> findByMyColumn(MyColumnType myColumnValue);

note that the return type of this repository method is java.util.Stream. The reason why I get this return type as stream is that this method is used only when the streaming is required.
And everytime I execute same procedure, the stack trace contains this method and I feel weird.
So I changed the type to List, and the error is GONE!!!

List<MyEntity> findByMyColumn(MyColumnType myColumnValue);

I think that the Stream is holding cursors even if the stream ended. Obviously it's a bug on Spring boot or ojdbc, but none of them seems to recognize or have willing to fix this problem.

Hope that helps to your situation, too.


问:
How to prevent relativeLayout from rising with linearLayout
I need the icon to remain in the bottom corner of the screen

When clicking on the icon, a RelativeLayout is displayed, but the icon goes up along with it

Prints

OK

Problem:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/icon"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:src="@mipmap/ic_launcher"
            tools:ignore="ContentDescription" />

        <ImageView
            android:id="@+id/close"
            android:layout_width="18dp"
            android:layout_height="18dp"
            android:layout_marginStart="35dp"
            android:src="@drawable/ic_close"
            tools:ignore="ContentDescription" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/content"
        android:layout_width="400dp"
        android:layout_height="250dp"
        android:layout_marginStart="50dp"
        android:background="#000000"
        android:orientation="vertical"
        android:visibility="gone">

        <!-- TODO -->

    </LinearLayout>
</FrameLayout>
</code>```

答:
You have a parent FrameLayout containing a RelativeLayout and LinearLayout. A FrameLayout simply places layouts inside on top of each other, although child layouts can be positioned with layout_gravity. In general, it can get a bit crazy when you mix RelativeLayout and LinearLayout, although you can do it as long as you understand how they will work together.

There's a few ways you can make your child layouts behave the way you want in your question, but to make it quick and simple, use a parent RelativeLayout rather than FrameLayout, and have the child views position themselves inside the parent layout with the one of the many layout_alignXYZ attributes. (see: https://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams) I hope this helps out.

Body:
I need the icon to remain in the bottom corner of the screen

When clicking on the icon, a RelativeLayout is displayed, but the icon goes up along with it

Prints

OK

Problem:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/icon"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:src="@mipmap/ic_launcher"
            tools:ignore="ContentDescription" />

        <ImageView
            android:id="@+id/close"
            android:layout_width="18dp"
            android:layout_height="18dp"
            android:layout_marginStart="35dp"
            android:src="@drawable/ic_close"
            tools:ignore="ContentDescription" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/content"
        android:layout_width="400dp"
        android:layout_height="250dp"
        android:layout_marginStart="50dp"
        android:background="#000000"
        android:orientation="vertical"
        android:visibility="gone">

    </LinearLayout>
</FrameLayout>


问:
Send and read data through socket from fiber
Trying to figure out how to send/read data through socket. On remote server I create new netcat -l 4444 and from local send text data echo "test" | netcat remote.host 4444. This is always works fine.

Trying to reproduce:

```<code>require "socket"

HOST = "remote.host"
PORT = 4444

ch_request = Channel(String).new
ch_response = Channel(String).new

spawn do
  socket = TCPSocket.new(HOST, PORT)
  loop do
    select
    when request = ch_request.receive
      socket << request
      socket.flush
    end

    if response = socket.gets
      ch_response.send response
    end
  end
end

sleep 0.1

ch_request.send "hello"

loop do
  select
  when response = ch_response.receive
    pp response
  end
end

</code>```

In my dream I send data to channel, read it from first loop then send to socket. The same way but reverse order need for read it from second loop.

On practice this is not happens. On local after connect I got "test" and can't send back anything. On remote I can send to local but on local got only empty string once and nothing more after.

What mean this behavior and how to achieve planned?

答:
Who is looking for an answer to similar questions. The final result what I wanted looks like this:

```<code># Open socket for simulate remote server: `netcat -v -4 -l 4444`

require "socket"

HOST = "remote.host"
PORT = 4444

# JFYI: In real life this packed into class and I use class variable instead consts.
TUBE_REQUEST  = Channel(String).new
TUBE_RESPONSE = Channel(String).new

SOCKET = TCPSocket.new(HOST, PORT)

spawn do
  until SOCKET.closed?
    if request = TUBE_REQUEST.receive
      SOCKET << request
      SOCKET.flush
    end
  end
end

spawn do
  until SOCKET.closed?
    if response = SOCKET.gets
      TUBE_RESPONSE.send response
    end
  end
end

sleep 0.1

def receive_response
  TUBE_RESPONSE.receive
end

def send(message, wait_for_response = true)
  TUBE_REQUEST.send message
  receive_response if wait_for_response
end

send("command with response")
send("command with new line and response\n")
send("command without new line and response", false)

</code>```

It will send each command and wait for answer (except the last) from remote and then call the next command.

Body:
Trying to figure out how to send/read data through socket. On remote server I create new netcat -l 4444 and from local send text data echo "test" | netcat remote.host 4444. This is always works fine.

Trying to reproduce:

require "socket"

HOST = "remote.host"
PORT = 4444

ch_request = Channel(String).new
ch_response = Channel(String).new

spawn do
  socket = TCPSocket.new(HOST, PORT)
  loop do
    select
    when request = ch_request.receive
      socket << request
      socket.flush
    end

    if response = socket.gets
      ch_response.send response
    end
  end
end

sleep 0.1

ch_request.send "hello"

loop do
  select
  when response = ch_response.receive
    pp response
  end
end

In my dream I send data to channel, read it from first loop then send to socket. The same way but reverse order need for read it from second loop.

On practice this is not happens. On local after connect I got "test" and can't send back anything. On remote I can send to local but on local got only empty string once and nothing more after.

What mean this behavior and how to achieve planned?

Body:
Who is looking for an answer to similar questions. The final result what I wanted looks like this:

# Open socket for simulate remote server: `netcat -v -4 -l 4444`

require "socket"

HOST = "remote.host"
PORT = 4444

# JFYI: In real life this packed into class and I use class variable instead consts.
TUBE_REQUEST  = Channel(String).new
TUBE_RESPONSE = Channel(String).new

SOCKET = TCPSocket.new(HOST, PORT)

spawn do
  until SOCKET.closed?
    if request = TUBE_REQUEST.receive
      SOCKET << request
      SOCKET.flush
    end
  end
end

spawn do
  until SOCKET.closed?
    if response = SOCKET.gets
      TUBE_RESPONSE.send response
    end
  end
end

sleep 0.1

def receive_response
  TUBE_RESPONSE.receive
end

def send(message, wait_for_response = true)
  TUBE_REQUEST.send message
  receive_response if wait_for_response
end

send("command with response")
send("command with new line and response\n")
send("command without new line and response", false)

It will send each command and wait for answer (except the last) from remote and then call the next command.


问:
Huge Errorlog with SQL Server 2005 Express (15GB)
With SQL Server 2005 Express (obeserved on XP and Server 2003), I get sometimes huge Error logs files in production:
The file C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\LOG\ERRORLOG grows to fill the disk (file size becomes more than 15 GB).

This file is not the transaction log, just the error log : a text log for SQL Server.

The error log starts like this: (seems to be normal)

```<code>2009-01-11 09:16:57.04 spid51      Starting up database 'SDomain'.
2009-01-11 10:04:34.21 spid21s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'Object Plans' cachestore (part of plan cache) due
to some database maintenance or reconfigure operations.
2009-01-11 10:04:34.23 spid21s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'SQL Plans' cachestore (part of plan cache) due to
some database maintenance or reconfigure operations.
2009-01-11 10:04:34.23 spid21s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'Bound Trees' cachestore (part of plan cache) due t
o some database maintenance or reconfigure operations.
2009-01-11 10:08:37.32 spid51      Starting up database 'SDomain'.
2009-01-11 10:56:55.48 spid22s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'Object Plans' cachestore (part of plan cache) due
to some database maintenance or reconfigure operations.
2009-01-11 10:56:55.49 spid22s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'SQL Plans' cachestore (part of plan cache) due to
some database maintenance or reconfigure operations.
2009-01-11 10:56:55.49 spid22s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'Bound Trees' cachestore (part of plan cache) due t
o some database maintenance or reconfigure operations.
2009-01-11 11:00:07.51 spid51      Starting up database 'SDomain'.
2009-01-11 11:47:44.73 spid15s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'Object Plans' cachestore (part of plan cache) due
to some database maintenance or reconfigure operations.
2009-01-11 11:47:44.74 spid15s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'SQL Plans' cachestore (part of plan cache) due to
some database maintenance or reconfigure operations.
2009-01-11 11:47:44.74 spid15s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'Bound Trees' cachestore (part of plan cache) due t
o some database maintenance or reconfigure operations.
</code>```

Then the file seems to contain endlessly repeating lines like this:

```<code>2008-12-17 00:12:24.03 spid13s     The log for database 'SDomain' is not available. Check the event log for related error messages. Resolve any errors and restart the database**
</code>```

FYI, the windows eventlog contains exactly the same messages.

Any idea of the reason why this problem occurs? Could it be a particular issue of configuration of SQL Server? Or an issue in code causing this?

答:
The common reasons why a database would start recovering on its own are:

The SQL Service was shutdown from the Service Control Manager or due a server shutdown

A fatal error occurred on the database which forced SQL Server to shut down the database and recover it

Someone manually initiated a recovery on the database using RESTORE  WITH RECOVERY command

A database backup was restored onto the database
During this phase your database will not respond to any user requests. Only once the recovery phase is complete will the database be accessible to users.
To find out why this happened you might want to check the SQL Server ERRORLOG and find out what find right before the recovery started on the database. Any fatal errors or database restore operations would be logged in the SQL Server ERRORLOG.
Also check if Auto Close option is enabled for your database. If thats true you need to turn off that option as follows,

Right click the database.

Select Properties

Click on Options.

AutoClose is the first option and ensure that it is marked as False.

Body:
With SQL Server 2005 Express (obeserved on XP and Server 2003), I get sometimes huge Error logs files in production:
The file C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\LOG\ERRORLOG grows to fill the disk (file size becomes more than 15 GB).

This file is not the transaction log, just the error log : a text log for SQL Server.

The error log starts like this: (seems to be normal)

2009-01-11 09:16:57.04 spid51      Starting up database 'SDomain'.
2009-01-11 10:04:34.21 spid21s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'Object Plans' cachestore (part of plan cache) due
to some database maintenance or reconfigure operations.
2009-01-11 10:04:34.23 spid21s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'SQL Plans' cachestore (part of plan cache) due to
some database maintenance or reconfigure operations.
2009-01-11 10:04:34.23 spid21s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'Bound Trees' cachestore (part of plan cache) due t
o some database maintenance or reconfigure operations.
2009-01-11 10:08:37.32 spid51      Starting up database 'SDomain'.
2009-01-11 10:56:55.48 spid22s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'Object Plans' cachestore (part of plan cache) due
to some database maintenance or reconfigure operations.
2009-01-11 10:56:55.49 spid22s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'SQL Plans' cachestore (part of plan cache) due to
some database maintenance or reconfigure operations.
2009-01-11 10:56:55.49 spid22s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'Bound Trees' cachestore (part of plan cache) due t
o some database maintenance or reconfigure operations.
2009-01-11 11:00:07.51 spid51      Starting up database 'SDomain'.
2009-01-11 11:47:44.73 spid15s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'Object Plans' cachestore (part of plan cache) due
to some database maintenance or reconfigure operations.
2009-01-11 11:47:44.74 spid15s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'SQL Plans' cachestore (part of plan cache) due to
some database maintenance or reconfigure operations.
2009-01-11 11:47:44.74 spid15s     SQL Server has encountered 1 occurrence(s) of cachestore flush for the 'Bound Trees' cachestore (part of plan cache) due t
o some database maintenance or reconfigure operations.

Then the file seems to contain endlessly repeating lines like this:

2008-12-17 00:12:24.03 spid13s     The log for database 'SDomain' is not available. Check the event log for related error messages. Resolve any errors and restart the database**

FYI, the windows eventlog contains exactly the same messages.

Any idea of the reason why this problem occurs? Could it be a particular issue of configuration of SQL Server? Or an issue in code causing this?


问:
When brew does not have latest package version
How do I force brew to install latest version of neovim (ver 0.5.0) when brew's formula only has 0.4.3?
I have tried:

```<code>brew update
brew upgrade neovim
</code>```

And it says: Warning: neovim 0.4.3 already installed

I went brew's git repo and checked on neovim formula. Brew has neovim's 0.4.3, not 0.5.0. So brew update/upgrade is not going to help. https://github.com/Homebrew/homebrew-core/blob/master/Formula/neovim.rb

I'm thinking of just downloading neovim from neovim repo and installing it manually, but I'm afraid I'll have to manage updates and dependencies if I do this manual install.

```<code>curl -LO https://github.com/neovim/neovim/releases/download/nightly/nvim-macos.tar.gz
tar xzf nvim-macos.tar.gz
./nvim-osx64/bin/nvim
</code>```

What should I do?

答:
According to the brew doc, brew install --HEAD will install the master branch of the package. For neovim, it means that the latest version of neovim will be built for you, which may not be stable enough or even compile.

I suggest you install the nightly binary version of neovim. The best way to get the nightly version is to download from the binary release. No dependency is required to install if you download the binary release.

If you don't want to do this manually, you can write a bash script to automate this.

Body:
How do I force brew to install latest version of neovim (ver 0.5.0) when brew's formula only has 0.4.3?
I have tried:

brew update
brew upgrade neovim

And it says: Warning: neovim 0.4.3 already installed

I went brew's git repo and checked on neovim formula. Brew has neovim's 0.4.3, not 0.5.0. So brew update/upgrade is not going to help. https://github.com/Homebrew/homebrew-core/blob/master/Formula/neovim.rb

I'm thinking of just downloading neovim from neovim repo and installing it manually, but I'm afraid I'll have to manage updates and dependencies if I do this manual install.

curl -LO https://github.com/neovim/neovim/releases/download/nightly/nvim-macos.tar.gz
tar xzf nvim-macos.tar.gz
./nvim-osx64/bin/nvim

What should I do?


答:
Using Newtonsoft.Json.Linq might be helpful for this particular case.

For example:

IList<long> averages =
    value["value"].SelectMany(val => val[".timeseries"]
                  .SelectMany(tm => tm["data"]
                  .Select(ave => (long) ave["average"]))).ToList();

```

<p>Outputs:</p>

<pre class="lang-cs prettyprint-override"><code>[0] 586904516140
[1] 587058965680
[2] 587058965680
</code>```

Title: How to fetch the last item in a JSON in C#

Body:
I'm trying to get a single value out of a JSON response from Azure Rest API.

Below is my code where I was able to get to final array but unable to fetch the last item from this array.

            string token = await GetAccessToken(GMETenantID, GMEClientID, GMEAppKey);

            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://management.azure.com/subscriptions/")
            };
            string URI = $"/subscriptions/{SubscriptionGUID}/providers/Microsoft.Storage/storageAccounts?api-version=2019-06-01";

            httpClient.DefaultRequestHeaders.Remove("Authorization");
            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            HttpResponseMessage response = await httpClient.GetAsync(URI).ConfigureAwait(false);

            var HttpsResponse = await response.Content.ReadAsStringAsync();
            dynamic Result = JsonConvert.DeserializeObject<object>(HttpsResponse);

            foreach (dynamic item in Result["value"])
            {
                string StorageID = item.id;
                string StorageAccountName = item.name;
                string ResourceType = item.type;

                int CharsToRemove = 12 + ResourceType.Length + StorageAccountName.Length;

                string ResourceGroupName = StorageID.Remove(0,67);
                ResourceGroupName = ResourceGroupName.Remove(ResourceGroupName.Length - CharsToRemove);

                string StartTime = DateTime.Now.AddDays(-7).ToString("yyyy-MM-ddTHH:mm:ss") + "Z"; ;
                string EndTime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + "Z";

                var BlobhttpClient = new HttpClient
                {
                    BaseAddress = new Uri("https://management.azure.com/subscriptions/")
                };

                string BlobURI = $"/subscriptions/{SubscriptionGUID}/resourceGroups/{ResourceGroupName}/providers/{ResourceType}/{StorageAccountName}/blobServices/default/providers/microsoft.insights/metrics?timespan={StartTime}/{EndTime}&aggregation=average&metricnames=BlobCapacity&api-version=2018-01-01";
                BlobhttpClient.DefaultRequestHeaders.Remove("Authorization");
                BlobhttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                HttpResponseMessage Blobresponse = await httpClient.GetAsync(BlobURI).ConfigureAwait(false);
                var BlobHttpsResponse = await Blobresponse.Content.ReadAsStringAsync();

                dynamic value = JObject.Parse(BlobHttpsResponse);

                foreach (dynamic List1 in value["value"])
                {
                    foreach (dynamic List2 in List1["timeseries"])
                    {
                        foreach (dynamic List3 in List2["data"])
                        {
                            Console.WriteLine((long?)List3["average"]);
                        }
                    }
                }
            }
            Console.ReadLine();

I also feel there must be an easier way to get this one value out instead of using 3 Foreach loops.

HttpsResponse: (There are a 168 timestamp and average values in the actual response but i've put only 3 values)

{
  "cost": 0,
  "timespan": "2020-05-22T03:04:46Z/2020-05-29T03:04:46Z",
  "interval": "PT1H",
  "value": [
    {
      "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/MyResourceGroupName/providers/Microsoft.Storage/storageAccounts/MyAstorageAccountName/blobServices/default/providers/Microsoft.Insights/metrics/BlobCapacity",
      "type": "Microsoft.Insights/metrics",
      "name": {
        "value": "BlobCapacity",
        "localizedValue": "Blob Capacity"
      },
      "displayDescription": "The amount of storage used by the storage account's Blob service in bytes.",
      "unit": "Bytes",
      ".timeseries": [
        {
          "metadatavalues": [],
          "data": [
            {
              "timeStamp": "2020-05-22T03:04:00Z",
              "average": 586904516140.0
            },
            {
              "timeStamp": "2020-05-22T04:04:00Z",
              "average": 587058965680.0
            },
            {
              "timeStamp": "2020-05-22T05:04:00Z",
              "average": 587058965680.0
            }
          ]
        }
      ],
      "errorCode": "Success"
    }
  ],
  "namespace": "Microsoft.Storage/storageAccounts/blobServices",
  "resourceregion": "eastus2"
}

All I want is the number 587058965680 which is the last value of the JSON and the most recent timestamp.

Pretty much I want to get exact result the way I'm getting in below powershell code
PowerShell works like a charm in 4 lines but I had to write so many lines in C#

$StorageAccounts = Get-AzStorageAccount -ResourceGroupName "My ResourceGroupName"

$StorageAccountID = $StorageAccounts.ID + "/blobServices/default"
$Start = (get-date).AddDays(-7)
$End = get-date

$Metric = Get-AzMetric -ResourceId $StorageAccountID -MetricName "BlobCapacity" -StartTime $Start -EndTime $End  -WarningAction Ignore

$ContainerSize = ($Metric.Data | sort-object -Descending Average | Select-Object -First 1).Average/1024/1024/1024

Body:
Using Newtonsoft.Json.Linq might be helpful for this particular case.

For example:

IList<long> averages =
    value["value"].SelectMany(val => val[".timeseries"]
                  .SelectMany(tm => tm["data"]
                  .Select(ave => (long) ave["average"]))).ToList();

Outputs:

[0] 586904516140
[1] 587058965680
[2] 587058965680