问:
create dynamically an accordion with lapply in bs4Dash
I try to dynamically create an accordion bast on a dataframe. Despite many try-outs I did not manage to get it working. Below the code of an example dashboard with two examples:

lappy: not working (lijst1)

program each item: working (lijst2)

see example below.

Hopefully someone can help?

```<code>library(bs4Dash)
library(shiny)

dataset <- data.frame(
  title = c("title 1", "title 2")
  , tekst = c("text 1", "text 2")
)

# create using lapply (flexible)
lijst1 <- accordion(
  id = "test1"
  , lapply(seq_along(dataset$title), function(i){
    accordionItem(title = dataset$title[i], dataset$tekst[i])
  })
)

# create by specify each item
lijst2 <- accordion(
  id = "test2"
  , accordionItem(title = "title 1 simple", "text 1 simple")
  , accordionItem(title = "title 1 simple", "text 2 simple")
)

ui <- dashboardPage(
  dashboardHeader()
  , dashboardSidebar()
  , dashboardBody(
    h2("Doesn't work")
    , lijst1
    , h2("Works")
    , lijst2
  )
)

server = function(input, output) {}

shinyApp(ui = ui, server = server)
</code>```

答:
One option to achieve your desired result would be to make use of do.call which works quite well with lapply as it allows you to pass function arguments as a list:

```<code>library(bs4Dash)
library(shiny)

dataset <- data.frame(
  title = c("title 1", "title 2"),
  tekst = c("text 1", "text 2")
)

# create using lapply (flexible)
lijst1 <- do.call("accordion", c(
  list(id = "test1"),
  lapply(seq_along(dataset$title), function(i) accordionItem(title = dataset$title[i], dataset$tekst[i]))
))

# create by specify each item
lijst2 <- accordion(
  id = "test2",
  accordionItem(title = "title 1 simple", "text 1 simple"),
  accordionItem(title = "title 1 simple", "text 2 simple")
)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    h2("Doesn't work"),
    lijst1,
    h2("Works"),
    lijst2
  )
)

server <- function(input, output, session) {

}

shinyApp(ui, server)
</code>```

Body:
I try to dynamically create an accordion bast on a dataframe. Despite many try-outs I did not manage to get it working. Below the code of an example dashboard with two examples:

lappy: not working (lijst1)

program each item: working (lijst2)

see example below.

Hopefully someone can help?

library(bs4Dash)
library(shiny)

dataset <- data.frame(
  title = c("title 1", "title 2")
  , tekst = c("text 1", "text 2")
)

# create using lapply (flexible)
lijst1 <- accordion(
  id = "test1"
  , lapply(seq_along(dataset$title), function(i){
    accordionItem(title = dataset$title[i], dataset$tekst[i])
  })
)

# create by specify each item
lijst2 <- accordion(
  id = "test2"
  , accordionItem(title = "title 1 simple", "text 1 simple")
  , accordionItem(title = "title 1 simple", "text 2 simple")
)

ui <- dashboardPage(
  dashboardHeader()
  , dashboardSidebar()
  , dashboardBody(
    h2("Doesn't work")
    , lijst1
    , h2("Works")
    , lijst2
  )
)

server = function(input, output) {}

shinyApp(ui = ui, server = server)

Body:
One option to achieve your desired result would be to make use of do.call which works quite well with lapply as it allows you to pass function arguments as a list:

library(bs4Dash)
library(shiny)

dataset <- data.frame(
  title = c("title 1", "title 2"),
  tekst = c("text 1", "text 2")
)

# create using lapply (flexible)
lijst1 <- do.call("accordion", c(
  list(id = "test1"),
  lapply(seq_along(dataset$title), function(i) accordionItem(title = dataset$title[i], dataset$tekst[i]))
))

# create by specify each item
lijst2 <- accordion(
  id = "test2",
  accordionItem(title = "title 1 simple", "text 1 simple"),
  accordionItem(title = "title 1 simple", "text 2 simple")
)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    h2("Doesn't work"),
    lijst1,
    h2("Works"),
    lijst2
  )
)

server <- function(input, output, session) {

}

shinyApp(ui, server)


来源: stackexchange

问:
Split ARRAY into chunks as they appear in sequence
I got an array of objects which I need to make into three chunks in the sequence as they are in the original array. For eg.

```<code>let arr = [{1},{2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}];
</code>```

This array needs to be split like this:

```<code>let newArray = {a:[{1},{4},{7},{10},...}], b:[{2},{5},{8}], c:[{3},{6},{9}]};
</code>```

答:
reduce can distribute each value on its slot based on the index

As you need a,b,c rather than 0,1,2 , a small mapping is needed here mapNumLetter

let arr = ["{1}","{2}", "{3}", "{4}", "{5}", "{6}", "{7}", "{8}", "{9}", "{10}"];

// let newArray = {a:[{1},{4},{7},{10},...}], b:[{2},{5},{8}], c:[{3},{6},{9}]};

const mapNumLetter = {
  0:"a",
  1:"b",
  2:"c"
}

const newArray = arr.reduce((acc,cur,i) => {
  acc[mapNumLetter[i%3]].push(cur);
  return acc
},{a:[],b:[],c:[]})

console.log(newArray)```

( as {1} , {2} ... are not valid objects, i changed them to literals "{1}" , "{2}" ... )

ContentLicense: CC BY-SA 4.0

Body:
I got an array of objects which I need to make into three chunks in the sequence as they are in the original array. For eg.

let arr = [{1},{2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}];

This array needs to be split like this:

let newArray = {a:[{1},{4},{7},{10},...}], b:[{2},{5},{8}], c:[{3},{6},{9}]};

Body:
reduce can distribute each value on its slot based on the index

As you need a,b,c rather than 0,1,2 , a small mapping is needed here mapNumLetter

let arr = ["{1}","{2}", "{3}", "{4}", "{5}", "{6}", "{7}", "{8}", "{9}", "{10}"];

// let newArray = {a:[{1},{4},{7},{10},...}], b:[{2},{5},{8}], c:[{3},{6},{9}]};

const mapNumLetter = {
  0:"a",
  1:"b",
  2:"c"
}

const newArray = arr.reduce((acc,cur,i) => {
  acc[mapNumLetter[i%3]].push(cur);
  return acc
},{a:[],b:[],c:[]})

console.log(newArray)

( as {1} , {2} ... are not valid objects, i changed them to literals "{1}" , "{2}" ... )


Title: Read in CSV in mixed English and French number format

Body:
I would like to read the a CSV into R that is quoted, comma-separated (i.e. sep = "," not sep = ";" as read.csv2 defaults to) but that

uses the comma inside fields as the decimal separator

contains periods to separate each group of three digits from the right

An example of a problematic entry is "3.051,00" in the final line of the excerpt from the CSV shown.

I tried

dat <- read.csv2("path_to_csv.csv", sep = ",", stringsAsFactors = FALSE)

and a variant using read.csv (both are identical except for their defaults as noted in Difference between read.csv() and read.csv2() in R. Both return improperly-formatted data.frames (e.g. containing 3.051,00).

Can I read this comma-separated file in directly with read.table without having to perform text-preprocessing?

Excerpt of CSV

praf,pmek,plcg,PIP2,PIP3,p44/42,pakts473,PKA,PKC,P38,pjnk
"26,40","13,20","8,82","18,30","58,80","6,61","17,00","414,00","17,00","44,90","40,00"
"35,90","16,50","12,30","16,80","8,13","18,60","32,50","352,00","3,37","16,50","61,50"
"59,40","44,10","14,60","10,20","13,00","14,90","32,50","403,00","11,40","31,90","19,50"
"62,10","51,90","13,60","30,20","10,60","14,30","37,90","692,00","6,49","25,00","91,40"
"75,00","33,40","1,00","31,60","1,00","19,80","27,60","505,00","18,60","31,10","7,64"
"20,40","15,10","7,99","101,00","35,90","9,14","22,90","400,00","11,70","22,70","6,85"
"47,80","19,60","17,50","33,10","82,00","17,90","35,20","956,00","22,50","43,30","20,00"
"59,90","53,30","11,80","77,70","12,90","11,10","37,90","1.407,00","18,80","29,40","16,80"
"46,60","27,10","12,40","109,00","21,90","21,50","38,20","207,00","11,00","31,30","12,00"
"51,90","21,30","49,10","58,80","10,80","58,80","200,00","3.051,00","15,30","39,20","15,70"

Note: I am aware of the question European and American decimal format for thousands, which is not sufficient. This user preprocesses the file they want to read in whereas I would like a direct means of reading a CSV of the kind shown into R.

Body:
Like r2evans's comment says, dec = "," takes care of the cases without thousands separators. Then use lapply/gsub to process the other cases, which are still of class "character".

txt <- '
praf,pmek,plcg,PIP2,PIP3,p44/42,pakts473,PKA,PKC,P38,pjnk
"26,40","13,20","8,82","18,30","58,80","6,61","17,00","414,00","17,00","44,90","40,00"
"35,90","16,50","12,30","16,80","8,13","18,60","32,50","352,00","3,37","16,50","61,50"
"59,40","44,10","14,60","10,20","13,00","14,90","32,50","403,00","11,40","31,90","19,50"
"62,10","51,90","13,60","30,20","10,60","14,30","37,90","692,00","6,49","25,00","91,40"
"75,00","33,40","1,00","31,60","1,00","19,80","27,60","505,00","18,60","31,10","7,64"
"20,40","15,10","7,99","101,00","35,90","9,14","22,90","400,00","11,70","22,70","6,85"
"47,80","19,60","17,50","33,10","82,00","17,90","35,20","956,00","22,50","43,30","20,00"
"59,90","53,30","11,80","77,70","12,90","11,10","37,90","1.407,00","18,80","29,40","16,80"
"46,60","27,10","12,40","109,00","21,90","21,50","38,20","207,00","11,00","31,30","12,00"
"51,90","21,30","49,10","58,80","10,80","58,80","200,00","3.051,00","15,30","39,20","15,70"
'

df1 <- read.csv(textConnection(txt), dec = ",")

i <- sapply(df1, is.character)
df1[i] <- lapply(df1[i], \(x) gsub("\\.", "", x))
df1[i] <- lapply(df1[i], \(x) as.numeric(sub(",", ".", x)))
df1
#>    praf pmek  plcg  PIP2  PIP3 p44.42 pakts473  PKA   PKC  P38  pjnk
#> 1  26.4 13.2  8.82  18.3 58.80   6.61     17.0  414 17.00 44.9 40.00
#> 2  35.9 16.5 12.30  16.8  8.13  18.60     32.5  352  3.37 16.5 61.50
#> 3  59.4 44.1 14.60  10.2 13.00  14.90     32.5  403 11.40 31.9 19.50
#> 4  62.1 51.9 13.60  30.2 10.60  14.30     37.9  692  6.49 25.0 91.40
#> 5  75.0 33.4  1.00  31.6  1.00  19.80     27.6  505 18.60 31.1  7.64
#> 6  20.4 15.1  7.99 101.0 35.90   9.14     22.9  400 11.70 22.7  6.85
#> 7  47.8 19.6 17.50  33.1 82.00  17.90     35.2  956 22.50 43.3 20.00
#> 8  59.9 53.3 11.80  77.7 12.90  11.10     37.9 1407 18.80 29.4 16.80
#> 9  46.6 27.1 12.40 109.0 21.90  21.50     38.2  207 11.00 31.3 12.00
#> 10 51.9 21.3 49.10  58.8 10.80  58.80    200.0 3051 15.30 39.2 15.70

Created on 2022-02-07 by the reprex package (v2.0.1)


问:
Customize laravel fortify email verification to use a mailjet template
I've been trying to get fortify's native email verification feature to use mailjet so templates can easily be adjusted. I've hit a bit of a roadblock as all tutorials and sources I've found are all about blade templates. Does someone have some pointers in the right direction or perhaps personal experience setting this up?

Thanks in advance!

答:
You need to bind your own implementation of Laravel\Fortify\Contracts\VerifyEmailViewResponse in the FortifyServiceProvider class.

# app/Providers/FortifyServiceProvider.php

namespace App\Providers;

use App\Actions\Fortify\YourClassHere;
use Laravel\Fortify\Contracts\VerifyEmailViewResponse;

class FortifyServiceProvider extends ServiceProvider
{
    public function boot()
    {
        app()->singleton(VerifyEmailViewResponse::class, YourClassHere::class);
    }
}
```
<pre class="lang-php prettyprint-override"><code># app/Actions/Fortify/YourClassHere.php

namespace App\Actions\Fortify;

use Laravel\Fortify\Contracts\VerifyEmailViewResponse;

class YourClassHere extends VerifyEmailResponse
{
    public function toResponse($request)
    {
        // your logic here.
        // since mailjet uses an api, perhaps return the response of a curl call,
        // or a response form Http::get(...)
        // or use a third-party package like laravel-mailjet (https://mailjet.github.io/laravel-mailjet/)
    }
}
</code>```

The logic that sends the verification email is part of the Illuminate\Auth\MustVerifyEmail trait. If you want to change it, you need to override it in your User model.

```<code>class User extends Authenticatable
{
    /**
     * Send the email verification notification.
     *
     * @return void
     */
    public function sendEmailVerificationNotification()
    {
        // your logic here.
    }
}
</code>```

Body:
You need to bind your own implementation of Laravel\Fortify\Contracts\VerifyEmailViewResponse in the FortifyServiceProvider class.

# app/Providers/FortifyServiceProvider.php

namespace App\Providers;

use App\Actions\Fortify\YourClassHere;
use Laravel\Fortify\Contracts\VerifyEmailViewResponse;

class FortifyServiceProvider extends ServiceProvider
{
    public function boot()
    {
        app()->singleton(VerifyEmailViewResponse::class, YourClassHere::class);
    }
}

# app/Actions/Fortify/YourClassHere.php

namespace App\Actions\Fortify;

use Laravel\Fortify\Contracts\VerifyEmailViewResponse;

class YourClassHere extends VerifyEmailResponse
{
    public function toResponse($request)
    {
        // your logic here.
        // since mailjet uses an api, perhaps return the response of a curl call,
        // or a response form Http::get(...)
        // or use a third-party package like laravel-mailjet (https://mailjet.github.io/laravel-mailjet/)
    }
}

The logic that sends the verification email is part of the Illuminate\Auth\MustVerifyEmail trait. If you want to change it, you need to override it in your User model.

class User extends Authenticatable
{
    /**
     * Send the email verification notification.
     *
     * @return void
     */
    public function sendEmailVerificationNotification()
    {
        // your logic here.
    }
}


问:
Android Studio Bumblebee when I try to run the emulator it complains: Unknown command-line option '--version'

I'm trying to get an app to run on my Android Studio emulator, when I hit run it complains:
Unknown command-line option '--version'

I've tried a few things

Reinstalling AS

Uninstalling & reinstalling sdks

Deleting and reinstalling the emulator

File > Manage IDE settings > Default settings, and resetting the IDE from there.

Redownloading the Flutter plugin, my apps are written in Flutter.

Updating with the latest Bumblebee patch to AS, also updating Flutter.

Using the search box to search the project for --version

I have the tools SDK downloaded.

How does the run process work? Which files does it read first in the project to arrange its process?
My emulator is Android API 30, my project's targetSdkVersion is 32.

Is there a fault in some AS IDE hooks/commands being unavailable from the command line? This appears to be what it says. I also can't run Flutter commands from AS's terminal.

If this is the problem how would I fix it?

Without this working, I can't run any apps on the emulator.

答:
Go now and update to the Bumblebee February update. It solves the issue with environments.
https://androidstudio.googleblog.com/2022/02/android-studio-bumblebee-202111-patch-1.html</p>


问:
Making the y axis in HH:MM:SS instead of seconds in matplotlib
I am using matplotlib (Python), I have y values in seconds (like 1000 seconds) and I want to display the ticks of y-axis in HH:MM:SS format. What is the simple solution to do that (with example).

Y is an integer list represents time duration in seconds

Sample code

```<code>import matplotlib.pyplot as plt
import numpy as np
y= np.array([1000,2000,4000,1000])
plt.plot(y)
plt.show()
</code>```

Best regards

答:
Thanks a lot Derek, however I have to use yticks and the full code working is as follows:

```<code>import numpy as np
from datetime import timedelta
import matplotlib.pyplot as plt

y= np.array([1000,3000,2000,4000])
y_timedelta = [str(timedelta(seconds=int(s))) for s in y]
plt.plot(y)
plt.yticks(y,y_timedelta)
plt.show()
</code>```

This is output:

Body:
I am using matplotlib (Python), I have y values in seconds (like 1000 seconds) and I want to display the ticks of y-axis in HH:MM:SS format. What is the simple solution to do that (with example).

Y is an integer list represents time duration in seconds

Sample code

import matplotlib.pyplot as plt
import numpy as np
y= np.array([1000,2000,4000,1000])
plt.plot(y)
plt.show()

Best regards

Body:
Thanks a lot Derek, however I have to use yticks and the full code working is as follows:

import numpy as np
from datetime import timedelta
import matplotlib.pyplot as plt

y= np.array([1000,3000,2000,4000])
y_timedelta = [str(timedelta(seconds=int(s))) for s in y]
plt.plot(y)
plt.yticks(y,y_timedelta)
plt.show()

This is output:


问:
Trouble dealing with POSIXct timezones and truncating the time out of POSIXct objects
I have the following piece of R-code:

```<code>formatString = "%Y-%m-%d %H:%M:%OS"
x = as.POSIXct(strptime("2013-11-23 23:10:38.000000", formatString))
y = as.POSIXct(strptime("2015-07-17 01:43:38.000000", formatString))
</code>```

I have the problem that when I do as.Date(y) then I get 2015-07-16 (although its date is one day later!). Apparently the problem is the timezone. So I checked the timezones:

```<code>> x
[1] "2013-11-23 23:10:38 CET"
> y
[1] "2015-07-17 01:43:38 CEST"
>
</code>```

Ok, so they deviate in their timezone. This is weird, because why does R decide that one timestamp (given without any timezone at all) lies in a different timezone than another (given without any timezone at all)?

Ok, so lets set the timezone. Googling revealed that attr(y, "tzone") <- "CET" should do the deal. Lets try this:

```<code>> attr(y, "tzone") <- "CET"
> y
[1] "2015-07-17 01:43:38 CEST"
>
</code>```

Ok, that did not work. Let see what the timezone actually is in the beginning:

```<code>> formatString = "%Y-%m-%d %H:%M:%OS"
> x = as.POSIXct(strptime("2013-11-23 23:10:38.000000", formatString))
> y = as.POSIXct(strptime("2015-07-17 01:43:38.000000", formatString))
> unclass(x)
[1] 1385244638
attr(,"tzone")
[1] ""
> unclass(y)
[1] 1437090218
attr(,"tzone")
[1] ""
>
</code>```

So... they dont have a timezone at all but their timezones are different????

--> here are my natural questions:

1) why are they initialized with a different timezone when I dont specify a timezone at all?

2) why do both objects apparently not have a timezone and at the same time... how come they have different timezones?

3) How can I make as.Date(y) == "2015-07-17" true? I.e. how can I set both to the current timezone? Sys.timezone() results in 'NA'... (EDIT: my timezone [Germany] seems to be "CET" --> how can I set both to CET?)

I'm scratching my head here... Thanks for any thoughts on this you share with me :-)

FW

答:
I ran into the same issue and found your Question here.

While all the given answers are valid and get an upvote from me, I'd like to share another - not too elegant - but working solution:

When ever you want to transform from class 'Date' to 'POSIXct' or vice versa, use as.character() before you convert:

```<code>x = as.POSIXct("2022-01-01")
y = as.POSIXct("2022-06-01")

x_Date <- as.Date(x)
x_POSIXct_again <- as.POSIXct(x_Date)
identical(x, x_POSIXct_again)
# FALSE!

y_Date <- as.Date(y)
y_POSIXct_again <- as.POSIXct(y_Date)
identical(y, y_POSIXct_again)
# FALSE!

x_Date <- as.Date(as.character(x))
x_POSIXct_again <- as.POSIXct(as.character(x_Date))
identical(x, x_POSIXct_again)
# TRUE!

y_Date <- as.Date(as.character(y))
y_POSIXct_again <- as.POSIXct(as.character(y_Date))
identical(y, y_POSIXct_again)
# TRUE!

# little helpers
as_Date2 <- function(x, ...) {
  if("POSIXct" %in% class(x)) x <- as.character(x)
  as.Date(x, ...)
}

as_POSIXct2 <- function(x, ...) {
  if("Date" %in% class(x)) x <- as.character(x)
  as.POSIXct(x, ...)
}
</code>```

Obviously - time information gets lost when converting from POSIXct to DATE. But no more day-switching at last.

ContentLicense: CC BY-SA 3.0

Body:
I have the following piece of R-code:

formatString = "%Y-%m-%d %H:%M:%OS"
x = as.POSIXct(strptime("2013-11-23 23:10:38.000000", formatString))
y = as.POSIXct(strptime("2015-07-17 01:43:38.000000", formatString))

I have the problem that when I do as.Date(y) then I get 2015-07-16 (although its date is one day later!). Apparently the problem is the timezone. So I checked the timezones:

> x
[1] "2013-11-23 23:10:38 CET"
> y
[1] "2015-07-17 01:43:38 CEST"
>

Ok, so they deviate in their timezone. This is weird, because why does R decide that one timestamp (given without any timezone at all) lies in a different timezone than another (given without any timezone at all)?

Ok, so lets set the timezone. Googling revealed that attr(y, "tzone") <- "CET" should do the deal. Lets try this:

> attr(y, "tzone") <- "CET"
> y
[1] "2015-07-17 01:43:38 CEST"
>

Ok, that did not work. Let see what the timezone actually is in the beginning:

> formatString = "%Y-%m-%d %H:%M:%OS"
> x = as.POSIXct(strptime("2013-11-23 23:10:38.000000", formatString))
> y = as.POSIXct(strptime("2015-07-17 01:43:38.000000", formatString))
> unclass(x)
[1] 1385244638
attr(,"tzone")
[1] ""
> unclass(y)
[1] 1437090218
attr(,"tzone")
[1] ""
>

So... they dont have a timezone at all but their timezones are different????

--> here are my natural questions:

1) why are they initialized with a different timezone when I dont specify a timezone at all?

2) why do both objects apparently not have a timezone and at the same time... how come they have different timezones?

3) How can I make as.Date(y) == "2015-07-17" true? I.e. how can I set both to the current timezone? Sys.timezone() results in 'NA'... (EDIT: my timezone [Germany] seems to be "CET" --> how can I set both to CET?)

I'm scratching my head here... Thanks for any thoughts on this you share with me :-)

FW

Body:
I ran into the same issue and found your Question here.

While all the given answers are valid and get an upvote from me, I'd like to share another - not too elegant - but working solution:

When ever you want to transform from class 'Date' to 'POSIXct' or vice versa, use as.character() before you convert:

x = as.POSIXct("2022-01-01")
y = as.POSIXct("2022-06-01")

x_Date <- as.Date(x)
x_POSIXct_again <- as.POSIXct(x_Date)
identical(x, x_POSIXct_again)
# FALSE!

y_Date <- as.Date(y)
y_POSIXct_again <- as.POSIXct(y_Date)
identical(y, y_POSIXct_again)
# FALSE!

x_Date <- as.Date(as.character(x))
x_POSIXct_again <- as.POSIXct(as.character(x_Date))
identical(x, x_POSIXct_again)
# TRUE!

y_Date <- as.Date(as.character(y))
y_POSIXct_again <- as.POSIXct(as.character(y_Date))
identical(y, y_POSIXct_again)
# TRUE!

# little helpers
as_Date2 <- function(x, ...) {
  if("POSIXct" %in% class(x)) x <- as.character(x)
  as.Date(x, ...)
}

as_POSIXct2 <- function(x, ...) {
  if("Date" %in% class(x)) x <- as.character(x)
  as.POSIXct(x, ...)
}

Obviously - time information gets lost when converting from POSIXct to DATE. But no more day-switching at last.


问:
× TypeError: Cannot read properties of undefined (reading 'name') react js
i am not able to display country name,image and rating can anyone explain me why this is happening [https://api.tvmaze.com/search/shows?q=avengers] it is the API link.all other data are displaying but these 3 are not working and throwing error.</p>
```<code>import React, {useState, useEffect} from 'react'
import ReactDOM from 'react-dom'
import axios from 'axios'

const App = () => {
  const url = 'https://api.tvmaze.com/search/shows?q=avengers'

  const [data, setData] = useState([])

  useEffect(() => {
    axios.get(url).then((json) => setData(json.data))
  }, [])

  const renderTable = () => {
    return data.map((user) => {
      return (
        <tr>
          <td>{user.show.name}</td>
          <td>{user.show.language}</td>
          <td>{user.show.genres}</td>
          <td>{user.show.runtime}</td>
          <td>{user.show.premiered}</td>
          <td>{user.show.rating}</td>
          <td>{user.show.country.name}</td>
          <td>{user.image.medium}</td>

        </tr>
      )
    })
  }

  return (
    <div>
      <h1 id="title">API Table</h1>
      <table id="users">
        <thead>
          <tr>
            <th>Name</th>
            <th>language</th>
            <th>genres</th>
            <th>runtime</th>
            <th>premiered</th>
            <th>Rating</th>
            <th>country name</th>
            <th>image</th>

          </tr>
        </thead>
        <tbody>{renderTable()}</tbody>
      </table>
    </div>
  )
}
export default App
</code>```

答:
I think it is because the country name is inside of the network object. In this case i think should be: user.show.network.country.name and for the image: user.show.image.medium
json object

Body:
i am not able to display country name,image and rating can anyone explain me why this is happening [https://api.tvmaze.com/search/shows?q=avengers] it is the API link.all other data are displaying but these 3 are not working and throwing error.

import React, {useState, useEffect} from 'react'
import ReactDOM from 'react-dom'
import axios from 'axios'

const App = () => {
  const url = 'https://api.tvmaze.com/search/shows?q=avengers'

  const [data, setData] = useState([])

  useEffect(() => {
    axios.get(url).then((json) => setData(json.data))
  }, [])

  const renderTable = () => {
    return data.map((user) => {
      return (

          {user.show.name}
          {user.show.language}
          {user.show.genres}
          {user.show.runtime}
          {user.show.premiered}
          {user.show.rating}
          {user.show.country.name}
          {user.image.medium}

      )
    })
  }

  return (

API Table

            Name
            language
            genres
            runtime
            premiered
            Rating
            country name
            image

{renderTable()}

  )
}
export default App


问:
trues and length of bool list f#
Directly using recursion, write a function truesAndLength : bool list -> int * int that
returns both the length of the list (in the first component of the pair), and the number of
elements of the list that are true (in the second component). Your function must only iterate
over the elements of the list once. (Do not use any of the functions from the List module.)

this is my code so far:

```<code>let rec length bs =
    match bs with
    | [] -> 0
    | b::bs -> 1 + length bs

let rec trues bs =
    match bs with
    | [] -> 0
    | b::bs -> if b = true then 1 + trues bs else trues bs

let truesandlength bs =
    let l = length bs
    let t = trues bs
    (l, t)

truesandlength [true; true; false]
</code>```

This works by im iterating through the list 2 times, i can't figure out how to iterate only 1. Any tips?

答:
Based on your comments, here's how I suggest you think about the b::bs case:

Call truesAndLengths recursively on the tail of the list. This gives you tTail (the # of trues) and lTail (the length) of the tail.

Compute t and l for the full list based on the value of b. (E.g. l is one more than lTail.)

Return t, l.

The key is to call truesAndLengths recursively in only one place in your code, passing it the tail of the list.

Title: trues and length of bool list f#

Body:
Directly using recursion, write a function truesAndLength : bool list -> int * int that
returns both the length of the list (in the first component of the pair), and the number of
elements of the list that are true (in the second component). Your function must only iterate
over the elements of the list once. (Do not use any of the functions from the List module.)

this is my code so far:

let rec length bs =
    match bs with
    | [] -> 0
    | b::bs -> 1 + length bs

let rec trues bs =
    match bs with
    | [] -> 0
    | b::bs -> if b = true then 1 + trues bs else trues bs

let truesandlength bs =
    let l = length bs
    let t = trues bs
    (l, t)

truesandlength [true; true; false]

This works by im iterating through the list 2 times, i can't figure out how to iterate only 1. Any tips?


问:
queryselector can not find id
I am trying to query a cloned element in my dom and queryselector can not find it. Specifically #reply_form brings up nothing despite the id being used in the template. I've also tried ("#reply_form"+post_id) since I re id it at the bottom before pushing it to the dom and nothing. I'm all out of ideas.

Here is the code:

```<code><template id="reply_template">
  <div class="lk">
    <img class="profile_image" />
    <div>
      <div class="user">
        <div class="reply_author"></div>
        <div class="reply-body"></div>
      </div>
      <div class="reply">
        <div class="d-flex align-items-center">
          <i id="upvote" class="fas fa-arrow-up hover"></i>
          <span id="upvote_count_badge" class="badge bg-secondary"></span>
          <i id="downvote" class="fas fa-arrow-down hover"></i>
        </div>
        <div class="reply_comment" id="reply">Reply</div>
        <div id="post_award_modal" data-bs-toggle="modal" data-bs-target="#siteModal">
            <i class="fas fa-award hover"></i>
        </div>
      </div>
      <div id="vl" class="vl"></div>
      <form id="reply_form" class="form-hidden">
        <img class="profile_image"/>
        <input class="cmt-reply" type="text" placeholder="Write a reply2"/>
      </form>
      <div id="reply_loader"><!--Nested Replies go here--></div>
    </div>
  </div>
</template>
<script>
  function loadReplies(post_id, count) {
    var reply_loader = document.querySelector('#reply_loader'+post_id)
    var reply_template = document.querySelector('#reply_template');
    if (count==0) {
      fetch('/_load_replies?f='+post_id).then((response) => {

        // Convert the response data to JSON
        response.json().then((data) => {
          for (var i = 0; i < data.length; i++) {
            //add_post(template, counter)

            // Clone the HTML template
            let template_clone = reply_template.content.cloneNode(true);

            // Query & update the template content
            let post_id=data[i].post_id;
            let post_url=data[i].post_url;
            let author=data[i].author;
            let author_id=data[i].author_id;
            let post_saved=data[i].current_user.post_saved;
            let post_upvoted=data[i].current_user.post_upvoted;
            let post_downvoted=data[i].current_user.post_downvoted;
            let current_user=data[i].current_user.current_user;
            let is_moderator=data[i].current_user.is_moderator;
            let is_big_top_moderator=data[i].current_user.is_big_top_moderator;
            let awards=data[i].awards;
            let media_url=data[i].media_url;
            let community=data[i].community;

            profile_images=template_clone.querySelectorAll(".profile_image");
            for(var k=0; k<profile_images.length; k++) {
              profile_images[k].src=data[i].post_profile_image;
            }

            let top=data[i].author;
            top+=" "+moment(data[i].timestamp).fromNow();
            if (awards) {
              top+=' ';
              for(var key in awards) {
                top+=awards[key]+' '+key;
              }
            }

            if (post_upvoted) {
              template_clone.querySelector("#upvote").setAttribute("style", "color: white");
              template_clone.querySelector("#downvote").setAttribute("style", "color: gray");
            } else if (post_downvoted) {
              template_clone.querySelector("#upvote").setAttribute("style", "color: gray");
              template_clone.querySelector("#downvote").setAttribute("style", "color: white");
            } else {
              template_clone.querySelector("#upvote").setAttribute("style", "color: gray");
              template_clone.querySelector("#downvote").setAttribute("style", "color: gray");
            }
            template_clone.querySelector("#upvote").setAttribute("onclick", "vote("+post_id+",1)");
            template_clone.querySelector("#downvote").setAttribute("onclick", "vote("+post_id+",0)");

            template_clone.querySelector("#post_award_modal").setAttribute("onclick", "build_award_modal("+post_id+")");

            template_clone.querySelector(".reply_author").innerHTML=top
            template_clone.querySelector(".reply-body").innerHTML=data[i].body;
            template_clone.querySelector("#upvote_count_badge").innerHTML=data[i].upvotes-data[i].downvotes;

            //it finds #reply no problem
            template_clone.querySelector("#reply").addEventListener("click", (e)=>{
              e.target.classList.toggle("blue");
              //It can not find this at all no matter what. I re id it at the bottom
              console.log(template_clone.querySelector("#reply_form"+post_id))
              template_clone.querySelector("#reply_form"+post_id).setAttribute("style", "color: blue")
              template_clone.querySelector("#vl")
            });

            //re id
            template_clone.querySelector("#upvote").id="upvote"+post_id;
            template_clone.querySelector("#upvote_count_badge").id="upvote_count_badge"+post_id;
            template_clone.querySelector("#downvote").id="downvote"+post_id;
            template_clone.querySelector("#reply_loader").id="reply_loader"+post_id;
            template_clone.querySelector("#reply").id="reply"+post_id;
            template_clone.querySelector("#reply_form").id="reply_form"+post_id;
            template_clone.querySelector("#vl").id="vl"+post_id;

            reply_loader.appendChild(template_clone);
          }
        })
      })
    }
  }
</script>
</code>```

Here is a code snippet:

function open_form(post_id) {
    console.log("reply"+post_id)
    document.getElementById("#reply"+post_id).classList.toggle("blue")
    document.getElementById("#reply_form"+post_id).classList.toggle("open")
    document.getElementsByID("#vl"+post_id).classList.toggle("open");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.like-comment, .reply_comment{
    cursor: pointer;
}

.vl{
    border-left: 1px solid white;
    border-bottom: 1px solid white;
    border-bottom-left-radius: 30px;
    width: 5%;
    top: 25px;
    position: absolute;
    height: 100%;
    left: -20px;
    display: none;
}

.thumb.open, .vl.open, .form-hidden.open{
    display: flex;
}

.form-hidden{
    position: relative;
    transform: translateX(35px);
    display: none;
}

.profile_image{
    width: 30px;
    height: 30px;
    border-radius: 50%;
}

.cmt-reply{
    width: 75%;
    height: 30px;
    padding: 5px;
    border-radius: 8px;
    border: none;
    margin-left: 5px;
}</code>```

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">

      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
      <link href="/static/css/style.css" rel="stylesheet">

      <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">

Reply

      <form id="reply_form64" class="form-hidden">

        <input class="cmt-reply" type="text" placeholder="Write a reply2">
      </form>

```

答:
When using getElementById you don't need to pass # in the string. check following snippet.

function open_form(post_id) {
  console.log("reply" + post_id)
  document.getElementById("reply" + post_id).classList.toggle("blue");
  document.getElementById("reply_form" + post_id).classList.toggle("open");
  document.getElementById("vl" + post_id).classList.toggle("open");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.like-comment,
.reply_comment {
  cursor: pointer;
}

.vl {
  border-left: 1px solid white;
  border-bottom: 1px solid white;
  border-bottom-left-radius: 30px;
  width: 5%;
  top: 25px;
  position: absolute;
  height: 100%;
  left: -20px;
  display: none;
}

.thumb.open,
.vl.open,
.form-hidden.open {
  display: flex;
}

.form-hidden {
  position: relative;
  transform: translateX(35px);
  display: none;
}

.profile_image {
  width: 30px;
  height: 30px;
  border-radius: 50%;
}

.cmt-reply {
  width: 75%;
  height: 30px;
  padding: 5px;
  border-radius: 8px;
  border: none;
  margin-left: 5px;
}</code>```

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
  <link href="/static/css/style.css" rel="stylesheet">

  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">

Reply

  <form id="reply_form64" class="form-hidden">

    <input class="cmt-reply" type="text" placeholder="Write a reply2">
  </form>

```

Here is getElementById documentation on mdn.

Title: queryselector can not find id

Body:
I am trying to query a cloned element in my dom and queryselector can not find it. Specifically #reply_form brings up nothing despite the id being used in the template. I've also tried ("#reply_form"+post_id) since I re id it at the bottom before pushing it to the dom and nothing. I'm all out of ideas.

Here is the code:

<template id="reply_template">

Reply

      <form id="reply_form" class="form-hidden">

        <input class="cmt-reply" type="text" placeholder="Write a reply2"/>
      </form>

</template>

Here is a code snippet:

function open_form(post_id) {
    console.log("reply"+post_id)
    document.getElementById("#reply"+post_id).classList.toggle("blue")
    document.getElementById("#reply_form"+post_id).classList.toggle("open")
    document.getElementsByID("#vl"+post_id).classList.toggle("open");
}

.like-comment, .reply_comment{
    cursor: pointer;
}

.vl{
    border-left: 1px solid white;
    border-bottom: 1px solid white;
    border-bottom-left-radius: 30px;
    width: 5%;
    top: 25px;
    position: absolute;
    height: 100%;
    left: -20px;
    display: none;
}

.thumb.open, .vl.open, .form-hidden.open{
    display: flex;
}

.form-hidden{
    position: relative;
    transform: translateX(35px);
    display: none;
}

.profile_image{
    width: 30px;
    height: 30px;
    border-radius: 50%;
}

.cmt-reply{
    width: 75%;
    height: 30px;
    padding: 5px;
    border-radius: 8px;
    border: none;
    margin-left: 5px;
}

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">

      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
      <link href="/static/css/style.css" rel="stylesheet">

      <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">

Reply

      <form id="reply_form64" class="form-hidden">

        <input class="cmt-reply" type="text" placeholder="Write a reply2">
      </form>

Body:
When using getElementById you don't need to pass # in the string. check following snippet.

function open_form(post_id) {
  console.log("reply" + post_id)
  document.getElementById("reply" + post_id).classList.toggle("blue");
  document.getElementById("reply_form" + post_id).classList.toggle("open");
  document.getElementById("vl" + post_id).classList.toggle("open");
}

.like-comment,
.reply_comment {
  cursor: pointer;
}

.vl {
  border-left: 1px solid white;
  border-bottom: 1px solid white;
  border-bottom-left-radius: 30px;
  width: 5%;
  top: 25px;
  position: absolute;
  height: 100%;
  left: -20px;
  display: none;
}

.thumb.open,
.vl.open,
.form-hidden.open {
  display: flex;
}

.form-hidden {
  position: relative;
  transform: translateX(35px);
  display: none;
}

.profile_image {
  width: 30px;
  height: 30px;
  border-radius: 50%;
}

.cmt-reply {
  width: 75%;
  height: 30px;
  padding: 5px;
  border-radius: 8px;
  border: none;
  margin-left: 5px;
}

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- CSS only -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
  <link href="/static/css/style.css" rel="stylesheet">
  <script src="https://js.stripe.com/v3/"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
</head>

<body>

  <!--Broken Code here-->
  <div class="reply_comment" id="reply64" onclick="open_form(64)">Reply</div>
  <div id="vl64" class="vl"></div>
  <form id="reply_form64" class="form-hidden">
    <img class="profile_image" src="/avatars/1be25219994e4ef695e1c6f0d4d128ac_m.png">
    <input class="cmt-reply" type="text" placeholder="Write a reply2">
  </form>

  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js" integrity="sha512-LGXaggshOkD/at6PFNcp2V2unf9LzFq6LE+sChH7ceMTDP0g2kn6Vxwgg7wkPP7AAtX+lmPqPdxB47A0Nz0cMQ==" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>

</body>

Here is getElementById documentation on mdn.


问:
ModalViewController doesn't save to core data?
iPad app fans:

I've got a modalviewcontroller designed to popup on a button tap so users can add notes or change data inputs. A table in the main window needs to be refreshed as changes to the database are made. The database incorporates a kind of advanced bookmark. I can create and delete database entries based on where users browse - no problem: I get the console report "saveContext KQVC line 203" and entries are quickly added into the table.

The modalviewcontroller even pops (on tapping the blue (>) detail icon also in each cell) with populated data of existing records. However the save button on the modalviewcontroller just doesn't save. (the delete function works great). Here's my code for the modalviewcontroller save button:

```<code>#import "PatternViewController.h"
#import "KnittingQueenViewController.h"

 @implementation PatternViewController
 @dynamic patternName, patternNotes, patternUrl, dateAdded;
 @synthesize patternA, patternView, knittingQueenViewController;

-(IBAction)save {
    [patternA setValue:patternName.text forKey:@"patternName"];
    [patternA setValue:patternUrl.text forKey:@"patternUrl"];
    [patternA setValue:patternNotes.text forKey:@"patternNotes"];
    dateAdded = [NSDate date];
    [patternA setValue:dateAdded forKey:@"dateAdded"];
    [patternA setValue:patternLabel.text forKey:@"patternLabel"];
    [patternA setValue:pngPath forKey:@"patternPhoto"];

    [knittingQueenViewController saveContext];
    [self dismissModalViewControllerAnimated:YES];
}
</code>```

and the saveContext method in the knittingqueenviewcontroller:

```<code>- (void)saveContext {
    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    NSError *error = nil;
    if (![context save:&error]) {
         // error code goes in here
    }
    NSLog(@"saveContext KQVC line 203");
    [self refreshPatternsTable];
}
</code>```

I get no errors, but no saved data either. My question: why isn't the method saveContext being called from the modalviewcontroller? Any suggestions you can offer would be most appreciated.

答: Is your save method being called? Is knittingQueenViewController non-nil when it's called? Do the values of patternA look correct?

Body:
iPad app fans:

I've got a modalviewcontroller designed to popup on a button tap so users can add notes or change data inputs. A table in the main window needs to be refreshed as changes to the database are made. The database incorporates a kind of advanced bookmark. I can create and delete database entries based on where users browse - no problem: I get the console report "saveContext KQVC line 203" and entries are quickly added into the table.

The modalviewcontroller even pops (on tapping the blue (>) detail icon also in each cell) with populated data of existing records. However the save button on the modalviewcontroller just doesn't save. (the delete function works great). Here's my code for the modalviewcontroller save button:

#import "PatternViewController.h"
#import "KnittingQueenViewController.h"

 @implementation PatternViewController
 @dynamic patternName, patternNotes, patternUrl, dateAdded;
 @synthesize patternA, patternView, knittingQueenViewController;

-(IBAction)save {
    [patternA setValue:patternName.text forKey:@"patternName"];
    [patternA setValue:patternUrl.text forKey:@"patternUrl"];
    [patternA setValue:patternNotes.text forKey:@"patternNotes"];
    dateAdded = [NSDate date];
    [patternA setValue:dateAdded forKey:@"dateAdded"];
    [patternA setValue:patternLabel.text forKey:@"patternLabel"];
    [patternA setValue:pngPath forKey:@"patternPhoto"];

    [knittingQueenViewController saveContext];
    [self dismissModalViewControllerAnimated:YES];
}

and the saveContext method in the knittingqueenviewcontroller:

- (void)saveContext {
    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    NSError *error = nil;
    if (![context save:&error]) {
         // error code goes in here
    }
    NSLog(@"saveContext KQVC line 203");
    [self refreshPatternsTable];
}

I get no errors, but no saved data either. My question: why isn't the method saveContext being called from the modalviewcontroller? Any suggestions you can offer would be most appreciated.


问:
How to notify the android user if camera permission is denied
I am working with camera permissions. when the user clicks on take photo button, user will be shown with run time permissions menu and lets say user deny's it and then clicks on take photo button, run time permissions will be shown second time.

after this clicking the take photo button nothing happens.

What I want to do is, after the second attempt, i want to show a popup telling the user to go to settings to change the permissions.

How can I know if the user has denied the permission twice.

this is what I have coded so far

```<code>takePhotoBtn.setOnClickListener {
        takePhoto()
    }

private fun takePhoto() {
    activity?.let {
        if (isCameraPermissionsAllowed()) {
            capturePhoto()
        } else {
            permReqLauncher.launch(
                CAMERA_PERMISSION
            )
        }
    }
}

private val permReqLauncher =
    registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
        val granted = permissions.entries.all {
            it.value == true
        }
        if (granted) {
            capturePhoto()
        }
    }

private fun capturePhoto() {
    onUtilityBillTypeListener.onUtilityBillTypePhotoLink(true)
}
</code>```

where is the right place to add this dinielDialog

```<code>private fun showPermissionDeniedDialog() {
    AlertDialog.Builder(this.requireContext())
        .setTitle("Permission Denied")
        .setMessage("Permission is denied, Please allow permissions from App Settings.")
        .setPositiveButton("Settings",
            DialogInterface.OnClickListener { dialogInterface, i ->
                // send to app settings if permission is denied permanently
                val intent = Intent()
                intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                val uri = Uri.fromParts("package", getPackageName(this.requireContext()), null)
                intent.data = uri
                startActivity(intent)
            })
        .setNegativeButton("Cancel", null)
        .show()
}
</code>```

答:
You could write something like this

```<code>if (isCameraPermissionsAllowed()) {
            capturePhoto()
        } else {
            if (permissionDeniedFlag) {
                showPermissionDeniedDialog()
            } else {
            permissionDeniedFlag = True
            permReqLauncher.launch(
                CAMERA_PERMISSION
            )
        }
</code>```

With an initial declaration of var permissionDeniedFlag = False.

Body:
I am working with camera permissions. when the user clicks on take photo button, user will be shown with run time permissions menu and lets say user deny's it and then clicks on take photo button, run time permissions will be shown second time.

after this clicking the take photo button nothing happens.

What I want to do is, after the second attempt, i want to show a popup telling the user to go to settings to change the permissions.

How can I know if the user has denied the permission twice.

this is what I have coded so far

takePhotoBtn.setOnClickListener {
        takePhoto()
    }

private fun takePhoto() {
    activity?.let {
        if (isCameraPermissionsAllowed()) {
            capturePhoto()
        } else {
            permReqLauncher.launch(
                CAMERA_PERMISSION
            )
        }
    }
}

private val permReqLauncher =
    registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
        val granted = permissions.entries.all {
            it.value == true
        }
        if (granted) {
            capturePhoto()
        }
    }

private fun capturePhoto() {
    onUtilityBillTypeListener.onUtilityBillTypePhotoLink(true)
}

where is the right place to add this dinielDialog

private fun showPermissionDeniedDialog() {
    AlertDialog.Builder(this.requireContext())
        .setTitle("Permission Denied")
        .setMessage("Permission is denied, Please allow permissions from App Settings.")
        .setPositiveButton("Settings",
            DialogInterface.OnClickListener { dialogInterface, i ->
                // send to app settings if permission is denied permanently
                val intent = Intent()
                intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                val uri = Uri.fromParts("package", getPackageName(this.requireContext()), null)
                intent.data = uri
                startActivity(intent)
            })
        .setNegativeButton("Cancel", null)
        .show()
}

Body:
You could write something like this

if (isCameraPermissionsAllowed()) {
            capturePhoto()
        } else {
            if (permissionDeniedFlag) {
                showPermissionDeniedDialog()
            } else {
            permissionDeniedFlag = True
            permReqLauncher.launch(
                CAMERA_PERMISSION
            )
        }

With an initial declaration of var permissionDeniedFlag = False.


问:
Jpa Specification equivalent for cosmosDb
I'm trying to migrate spring boot application from mssql to CosmosDb.

We have the below repository implementation using org.springframework.data.jpa.domain.Specification;  which can fetch data based on any (one or more) columns requested by the user.

```<code>static Specification<User> isMatching(final Map<String, String> parameters) {
    return new Specification<User>() {
        private static final long serialVersionUID = 1L;

        public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            List<Predicate> predicates = new ArrayList<>();
            parameters.entrySet().forEach(e -> {

                predicates.add(builder.and(builder.equal(root.get(e.getKey()), e.getValue())));
            });
            return builder.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    };
}
</code>```

and then we are calling this as below:

```<code>repo.findAll(UserRepo.isMatching(parameters));
</code>```

I had to remove spring-boot-starter-data-jpa from classpath as it will not support CosmosDb. I'm using the below spring and spring data cosmos references in classpath as that is the only combination working for me.

```<code>    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
        <relativePath />
    </parent>
<dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-spring-data-cosmos</artifactId>
            <version>3.0.0</version>
        </dependency>
</code>```

I couldn't really figure out how I can implement the above Specification logic for CosmosDb. I would really appreciate any guidance regarding this. Thanks in advance!

答:
Currently azure-spring-data-cosmos doesn't provide support for Specification / QueryDSL in azure-spring-data-cosmos SDK. The closest option I can think of is using Criteria API with SqlQuerySpec. Using SqlQuerySpec you can generate CosmosQuery type, which can then be executed using CosmosTemplate or ReactiveCosmosTemplate based on your repository style (sync vs async).

Regarding versioning, I would recommend using the latest version of spring-boot-starter-parent - 2.6.2 and azure-spring-data-cosmos 3.17.0, so that you get the latest features of query annotation as well.

If the SqlQuerySpec doesn't work either, alternative would be to get CosmosClient bean through applicationContext in your spring application, and running the queries directly against azure-cosmos Java v4 SDK, which is used under the hood of our azure-spring-data-cosmos SDK.

Please follow this github issue for any updates on your question - https://github.com/Azure/azure-sdk-for-java/issues/25629

Body:
I'm trying to migrate spring boot application from mssql to CosmosDb.

We have the below repository implementation using org.springframework.data.jpa.domain.Specification;  which can fetch data based on any (one or more) columns requested by the user.

static Specification<User> isMatching(final Map<String, String> parameters) {
    return new Specification<User>() {
        private static final long serialVersionUID = 1L;

        public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            List<Predicate> predicates = new ArrayList<>();
            parameters.entrySet().forEach(e -> {

                predicates.add(builder.and(builder.equal(root.get(e.getKey()), e.getValue())));
            });
            return builder.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    };
}

and then we are calling this as below:

repo.findAll(UserRepo.isMatching(parameters));

I had to remove spring-boot-starter-data-jpa from classpath as it will not support CosmosDb. I'm using the below spring and spring data cosmos references in classpath as that is the only combination working for me.

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
        <relativePath />
    </parent>
<dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-spring-data-cosmos</artifactId>
            <version>3.0.0</version>
        </dependency>

I couldn't really figure out how I can implement the above Specification logic for CosmosDb. I would really appreciate any guidance regarding this. Thanks in advance!


问:
How to fetch previous status of an issue in JIRA using Python-Jira?
I want to fetch all the issues which are currently in 'IN PROGRESS' status and previously in 'OPEN'status.

By using the following code I would get all the issues that are currently in 'IN PROGRESS' status and the issues that are passed through 'OPEN' status once in its transition state.

eg: issues = jira.search_issues(PROJECT=XYZ AND (status in ('IN PROGRESS')) AND (status WAS in ('OPEN')))

But how can I get the issues which are currently in the 'IN PROGRESS' status and previously in 'OPEN' status in JIRA using Jira-Python?

答: You can run a search using Jira Python. Use the same search you showed us</p>


问:
Positioning a image onto another
I want to develop a program (in C#) that has following needs:

I want a webcam to take a image and display it on a picturebox (THIS I CAN DO)

Now i have a set of other images with me and i want to drag and drop these images on the clicked image and position them right with the mouse. Is it possible to put that photoshop functionality where you drag and position a picture over another and when you click save that becomes one single picture.It is more like i have a background image and i want to exactly position another image(s) onto the background image using the drag and drop functionality  Any answers are most appreciated. Thanking you guys in advance.

答: Well for 2 question, i am sure you have to first understand the image format and closely work with the image rendering libraries. And then see how you can merge the 2 images files using that library. No direct solution. But yes its possible. May be search for some jpeg c# libraries to kick start.</p>

Title: Positioning a image onto another


问:
pandas: replace values in column with the last character in the column name
I have a dataframe as follows:

```<code>import pandas as pd
df = pd.DataFrame({'sent.1':[0,1,0,1],
                'sent.2':[0,1,1,0],
                'sent.3':[0,0,0,1],
                'sent.4':[1,1,0,1]
               })
</code>```

I am trying to replace the non-zero values with the 5th character in the column names (which is the numeric part of the column names), so the output should be,

```<code>   sent.1  sent.2  sent.3  sent.4
0       0       0       0       4
1       1       2       0       4
2       0       2       0       0
3       1       0       3       4
</code>```

I have tried the following but it does not work,

```<code>print(df.replace(1, pd.Series([i[5] for i in df.columns], [i[5] for i in df.columns])))
</code>```

However when I replace it with column name, the above code works, so I am not sure which part is wrong.

```<code>print(df.replace(1, pd.Series(df.columns,  df.columns)))
</code>```

答:
And another one, working with an arbitrary condition (here s.ne(0)):

```<code>df.apply(lambda s: s.mask(s.ne(0), s.name.rpartition('.')[-1]))
</code>```

Body:
I have a dataframe as follows:

import pandas as pd
df = pd.DataFrame({'sent.1':[0,1,0,1],
                'sent.2':[0,1,1,0],
                'sent.3':[0,0,0,1],
                'sent.4':[1,1,0,1]
               })

I am trying to replace the non-zero values with the 5th character in the column names (which is the numeric part of the column names), so the output should be,

   sent.1  sent.2  sent.3  sent.4
0       0       0       0       4
1       1       2       0       4
2       0       2       0       0
3       1       0       3       4

I have tried the following but it does not work,

print(df.replace(1, pd.Series([i[5] for i in df.columns], [i[5] for i in df.columns])))

However when I replace it with column name, the above code works, so I am not sure which part is wrong.

print(df.replace(1, pd.Series(df.columns,  df.columns)))

Body:
And another one, working with an arbitrary condition (here s.ne(0)):

df.apply(lambda s: s.mask(s.ne(0), s.name.rpartition('.')[-1]))


问:
firebase_database - error after flutter migration - DataSnapshot syntax
I used this code bevor migration

```<code>  void initState() {
    DatabaseReference db;
    db = FirebaseDatabase.instance.ref().child("likes");
    db.once().then((DataSnapshot snapshot) {
      Map<dynamic, dynamic> values = snapshot.value;
      values.forEach((key, values) {
        likeList.add(values["check"]);
        print(likeList);
      });
    });
  }
</code>```

after "dart pub upgrade --null-safety" I get the Error:

```<code>The argument type 'Null Function(DataSnapshot)' can't be assigned to the parameter type 'FutureOr<dynamic> Function(DatabaseEvent)
</code>```

I can't find anything in the changelos on pub.dev how to use DataSnapshot in this case.

答:
Instead of DataSnapshot, you should put DatabaseEvent within the then

```<code>  void initState() {
    DatabaseReference db;
    db = FirebaseDatabase.instance.ref().child("likes");
    db.once().then((DatabaseEvent databaseEvent) {
      Map<dynamic, dynamic> values = databaseEvent.snapshot.value;
      values.forEach((key, values) {
        likeList.add(values["check"]);
        print(likeList);
      });
    });
  }
</code>```

Body:
I used this code bevor migration

  void initState() {
    DatabaseReference db;
    db = FirebaseDatabase.instance.ref().child("likes");
    db.once().then((DataSnapshot snapshot) {
      Map<dynamic, dynamic> values = snapshot.value;
      values.forEach((key, values) {
        likeList.add(values["check"]);
        print(likeList);
      });
    });
  }

after "dart pub upgrade --null-safety" I get the Error:

The argument type 'Null Function(DataSnapshot)' can't be assigned to the parameter type 'FutureOr<dynamic> Function(DatabaseEvent)

I can't find anything in the changelos on pub.dev how to use DataSnapshot in this case.

Body:
Instead of DataSnapshot, you should put DatabaseEvent within the then

  void initState() {
    DatabaseReference db;
    db = FirebaseDatabase.instance.ref().child("likes");
    db.once().then((DatabaseEvent databaseEvent) {
      Map<dynamic, dynamic> values = databaseEvent.snapshot.value;
      values.forEach((key, values) {
        likeList.add(values["check"]);
        print(likeList);
      });
    });
  }


答:
On your code where you're getting permission result you can do it like this :</p>
```<code>private val requestPermissionLauncher =
    registerForActivityResult(ActivityResultContracts.RequestPermission()) {
            isGranted: Boolean ->
        if (isGranted) //perform action
        else {
            val builder = AlertDialog.Builder(requireContext())
            builder.setTitle("Permission Required!")
            builder.setMessage("We need permission in order to perform this action.")
            builder.setPositiveButton("OK") { dialog, _ ->
                showPermRationale()
                dialog.cancel()
            }
            builder.setNegativeButton("CANCEL") { dialog, _ ->
                dialog.cancel()
            }
            builder.show()
        }
    }

private fun showPermRationale() {
    val intent = Intent()
    intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
    val uri = Uri.fromParts(
        "package", requireActivity().packageName, null)
    intent.data = uri
    requireActivity().startActivity(intent)
}
</code>```

Title: How to notify the android user if camera permission is denied

Body:
On your code where you're getting permission result you can do it like this :

private val requestPermissionLauncher =
    registerForActivityResult(ActivityResultContracts.RequestPermission()) {
            isGranted: Boolean ->
        if (isGranted) //perform action
        else {
            val builder = AlertDialog.Builder(requireContext())
            builder.setTitle("Permission Required!")
            builder.setMessage("We need permission in order to perform this action.")
            builder.setPositiveButton("OK") { dialog, _ ->
                showPermRationale()
                dialog.cancel()
            }
            builder.setNegativeButton("CANCEL") { dialog, _ ->
                dialog.cancel()
            }
            builder.show()
        }
    }

private fun showPermRationale() {
    val intent = Intent()
    intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
    val uri = Uri.fromParts(
        "package", requireActivity().packageName, null)
    intent.data = uri
    requireActivity().startActivity(intent)
}


问:
Filter object ListCollectionView using object's nested SerializedDictonary in C#
I would like to filter ListCollectionView using SerializableDictionary which is nested in objects.
The filter will check values for the specified (hardcoded) key.

Object (only pseudocode to avoid too much code):

```<code>MasterRecord{
   MasterName string,
   AdditionalAttributes SerializableDictionary
   }
</code>```

Below is my current simple filter using MasterName(string):

```<code>    public string Filter
    {
        get
        {
            return m_Filter;
        }
        set
        {
            if (value != m_Filter)
            {
                m_Filter = value;

                ListCollectionView masterRecords = (ListCollectionView)CollectionViewSource.GetDefaultView(MasterRecordCollection);
                if (!string.IsNullOrEmpty(m_Filter))
                {
                    masterRecords.Filter = (item) => { return (item as MasterRecord).MasterName.StartsWith(m_Filter) ? true : false; };

                }
                else
                    masterRecords.Filter = null;

                masterRecords.Refresh();
            }
        }
    }
</code>```

Sample:

How to modyfi my current method and filter by Value (using .Filter() and .StartWith(), for exmaple 'COCA-COLA') AdditionalAttributes(SerializableDictionary) when (this part should be hardcoded) Key == 'c_ProductName' ?

答:
Solution (thanks to @jdweng):</p>
```<code>masterRecords.Filter = (item) => { return (item as MasterRecord).AdditionalAttributes.Any(y => (y.Key == "c_ProductName") && (y.Value.StartsWith(m_Filter)));};
</code>```

Body:
I would like to filter ListCollectionView using SerializableDictionary which is nested in objects.
The filter will check values for the specified (hardcoded) key.

Object (only pseudocode to avoid too much code):

MasterRecord{
   MasterName string,
   AdditionalAttributes SerializableDictionary
   }

Below is my current simple filter using MasterName(string):

    public string Filter
    {
        get
        {
            return m_Filter;
        }
        set
        {
            if (value != m_Filter)
            {
                m_Filter = value;

                ListCollectionView masterRecords = (ListCollectionView)CollectionViewSource.GetDefaultView(MasterRecordCollection);
                if (!string.IsNullOrEmpty(m_Filter))
                {
                    masterRecords.Filter = (item) => { return (item as MasterRecord).MasterName.StartsWith(m_Filter) ? true : false; };

                }
                else
                    masterRecords.Filter = null;

                masterRecords.Refresh();
            }
        }
    }

Sample:

How to modyfi my current method and filter by Value (using .Filter() and .StartWith(), for exmaple 'COCA-COLA') AdditionalAttributes(SerializableDictionary) when (this part should be hardcoded) Key == 'c_ProductName' ?

Body:
Solution (thanks to @jdweng):

masterRecords.Filter = (item) => { return (item as MasterRecord).AdditionalAttributes.Any(y => (y.Key == "c_ProductName") && (y.Value.StartsWith(m_Filter)));};


问:
SelectList always null on POST causes Model State to be Invalid
I understand that the SelectListItems are meant to not return back the items on post and perhaps be null, but because of this my ModelState.IsValid condition is always false and the Studies field which contains the list is the one with the invalid attribute. I tried different methods and am stuck on resolving this

View

```<code> <label asp-for="Studies" class="form-label"></label>
 <select asp-for="SelectedStudyGuid" asp-items="@Model.Studies" class="form-control" autocomplete="off">
   <option value="">Select Study</option>
 </select>
 <span asp-validation-for="SelectedStudyGuid" class="text-danger"></span>
</code>```

ViewModel

```<code>public class AddStudyViewModel
{
    public string ParticipantGuid { get; set; }

    public IEnumerable<SelectListItem> Studies { get; set; }
    public string SelectedStudyGuid { get; set; }

    [DataType(DataType.Date)]
    public DateTime? StartDate { get; set; }

    [DataType(DataType.Date)]
    public DateTime? EndDate { get; set; }
}
</code>```

Controller

```<code>  private List<SelectListItem> GetStudyCatalog()
    {
        return _repo.GetStudyCatalog().Select(s => new SelectListItem
        {
            Text = s.Name,
            Value = s.Guid
        }).ToList();
    }

    [HttpGet]
    public IActionResult AddStudy(string participantGuid)
    {
        var model = new AddStudyViewModel
        {
            Studies = GetStudyCatalog(),
            ParticipantGuid = participantGuid
        };

        return PartialView("_AddStudyModal", model);
    }

    [HttpPost]
    public IActionResult AddStudy(AddStudyViewModel model)
    {
        if (ModelState.IsValid)
        {
           var response= _repo.AddStudy(model.SelectedStudyGuid, model.ParticipantGuid, model.StartDate, model.EndDate);

            if (response.Success)
            {
                TempData["Message"] = response.Message;
                return RedirectToAction("EditParticipant", new {id = response.NewGuid});
            }
        }

        model.Studies = GetStudyCatalog();
        return PartialView("_AddStudyModal", model);
    }
</code>```

答:
The problem is originated when you click your button to submit the form data back to the controller.

At this point the client side code sends the input fields present on the form and you don't have an input field that contains the SelectListItem. The SelectedStudyGuid select list is for that field, not for the whole Studies.

The AddStudyViewModel instance received in the post action is rebuilt on the server side using the data sent by the client side and thus you have a null for the Studies property.

Usually the SelectListItem data is not needed on the post action but only in the get action and you can simply pass it using some temporary storage like the ViewBag

So you can fix with

MODEL

```<code>public class AddStudyViewModel
{
    public string ParticipantGuid { get; set; }

    public string SelectedStudyGuid { get; set; }

    [DataType(DataType.Date)]
    public DateTime? StartDate { get; set; }

    [DataType(DataType.Date)]
    public DateTime? EndDate { get; set; }
}
</code>```

CONTROLLER

```<code>[HttpGet]
public IActionResult AddStudy(string participantGuid)
{
    var model = new AddStudyViewModel
    {
        ParticipantGuid = participantGuid
    };
    ViewBag.Studies = GetStudyCatalog(),
    return PartialView("_AddStudyModal", model);
}
</code>```

VIEW

```<code> <label asp-for="Studies" class="form-label"></label>
 <select asp-for="SelectedStudyGuid" asp-items="@ViewBag.Studies" class="form-control" autocomplete="off">
   <option value="">Select Study</option>
 </select>
 <span asp-validation-for="SelectedStudyGuid" class="text-danger"></span>
</code>```

Body:
I understand that the SelectListItems are meant to not return back the items on post and perhaps be null, but because of this my ModelState.IsValid condition is always false and the Studies field which contains the list is the one with the invalid attribute. I tried different methods and am stuck on resolving this

View

 <select asp-for="SelectedStudyGuid" asp-items="@Model.Studies" class="form-control" autocomplete="off">
   <option value="">Select Study</option>
 </select>

ViewModel

public class AddStudyViewModel
{
    public string ParticipantGuid { get; set; }

    public IEnumerable<SelectListItem> Studies { get; set; }
    public string SelectedStudyGuid { get; set; }

    [DataType(DataType.Date)]
    public DateTime? StartDate { get; set; }

    [DataType(DataType.Date)]
    public DateTime? EndDate { get; set; }
}

Controller

  private List<SelectListItem> GetStudyCatalog()
    {
        return _repo.GetStudyCatalog().Select(s => new SelectListItem
        {
            Text = s.Name,
            Value = s.Guid
        }).ToList();
    }

    [HttpGet]
    public IActionResult AddStudy(string participantGuid)
    {
        var model = new AddStudyViewModel
        {
            Studies = GetStudyCatalog(),
            ParticipantGuid = participantGuid
        };

        return PartialView("_AddStudyModal", model);
    }

    [HttpPost]
    public IActionResult AddStudy(AddStudyViewModel model)
    {
        if (ModelState.IsValid)
        {
           var response= _repo.AddStudy(model.SelectedStudyGuid, model.ParticipantGuid, model.StartDate, model.EndDate);

            if (response.Success)
            {
                TempData["Message"] = response.Message;
                return RedirectToAction("EditParticipant", new {id = response.NewGuid});
            }
        }

        model.Studies = GetStudyCatalog();
        return PartialView("_AddStudyModal", model);
    }

Body:
The problem is originated when you click your button to submit the form data back to the controller.

At this point the client side code sends the input fields present on the form and you don't have an input field that contains the SelectListItem. The SelectedStudyGuid select list is for that field, not for the whole Studies.

The AddStudyViewModel instance received in the post action is rebuilt on the server side using the data sent by the client side and thus you have a null for the Studies property.

Usually the SelectListItem data is not needed on the post action but only in the get action and you can simply pass it using some temporary storage like the ViewBag

So you can fix with

MODEL

public class AddStudyViewModel
{
    public string ParticipantGuid { get; set; }

    public string SelectedStudyGuid { get; set; }

    [DataType(DataType.Date)]
    public DateTime? StartDate { get; set; }

    [DataType(DataType.Date)]
    public DateTime? EndDate { get; set; }
}

CONTROLLER

[HttpGet]
public IActionResult AddStudy(string participantGuid)
{
    var model = new AddStudyViewModel
    {
        ParticipantGuid = participantGuid
    };
    ViewBag.Studies = GetStudyCatalog(),
    return PartialView("_AddStudyModal", model);
}

VIEW

 <label asp-for="Studies" class="form-label"></label>
 <select asp-for="SelectedStudyGuid" asp-items="@ViewBag.Studies" class="form-control" autocomplete="off">
   <option value="">Select Study</option>
 </select>
 <span asp-validation-for="SelectedStudyGuid" class="text-danger"></span>


问:
How to obtain dynamic google map url of a specific map (I have static map url)
I have the below static google map url. just want to know the equivalent for dynamic map.

Static Google Map URL

I am not sure if it is v2 or v3.

Body:
Replace center by q and just swap the base URLs:

http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn%20Bridge,New%20York,NY&zoom=14&size=512x512&maptype=roadmap%20&markers=color%3ablue|label%3aS|40.702147,-74.015794&markers=color%3agreen|label%3aG|40.711614,-74.012318%20&markers=color%3ared|color%3ared|label%3aC|40.718217,-73.998284&sensor=false

to:

http://maps.google.com/maps?q=Brooklyn%20Bridge,New%20York,NY&zoom=14&size=512x512&maptype=roadmap%20&markers=color%3ablue|label%3aS|40.702147,-74.015794&markers=color%3agreen|label%3aG|40.711614,-74.012318%20&markers=color%3ared|color%3ared|label%3aC|40.718217,-73.998284&sensor=false


问:
index fragmentation in posgresql
I can't figure out what exactly represent fragmentation for a postgres index. in the source code of pgstattuple I found this comment but it's not particularly clear for me.

/*
* If the next leaf is on an earlier block, it means a
* fragmentation.
*/

答:
Btree leaf pages form a logical chain (a doubly linked list) and if you follow that chain in the forward direction you encounter the key values in sorted order.  They also have a "physical" order, their block number within the file.  That extension considers it fragmentation if the next page following the linked list is to a "physically" earlier page in the file.

You could quibble with this for any number of reasons, but this is the definition that that extension adopted.  For example if the logically next page by the linked list is 100 pages forward, that is just as much fragmented as if it is one page backwards.  But if it does skip forward a bunch then someone else must be pointing backwards to pick them up (unless they are unused) so would get counted when that "someone else" is encountered.  Also, the "physical" order of pages in the file is really just the "logical" order of another layer of abstraction (the file system) and different file systems handle it differently.

Title: index fragmentation in posgresql


问:
CNN program has been computing for too long and not giving any output
I've implemented the following code in Jupyter notebook, and it has been over 90 mins, the programme is still running, and I've not gotten any output.

I'm working with mid-2012 MacBook Pro.
4 GB ram.
I've checked the activity monitor, memory pressure is in the yellow zone, so that means, the means, the mac is not running out of memory, and I don't know what to do now.

The program implements CNN model over CIFAR-10 dataset.

```<code>import sys
from matplotlib import pyplot
from keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Dense
from keras.layers import Flatten
from tensorflow.keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Dropout
from keras.layers import BatchNormalization
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

# load train and test dataset
def load_dataset():
    # load dataset
    (trainX, trainY), (testX, testY) = cifar10.load_data()
    # one hot encode target values
    trainY = to_categorical(trainY)
    testY = to_categorical(testY)
    return trainX, trainY, testX, testY

# scale pixels
def prep_pixels(train, test):
    # convert from integers to floats
    train_norm = train.astype('float32')
    test_norm = test.astype('float32')
    # normalize to range 0-1
    train_norm = train_norm / 255.0
    test_norm = test_norm / 255.0
    # return normalized images
    return train_norm, test_norm

# define cnn model
def define_model():
    model = Sequential()
    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(32, 32, 3)))
    model.add(BatchNormalization())
    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D((2, 2)))
    model.add(Dropout(0.2))
    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D((2, 2)))
    model.add(Dropout(0.3))
    model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D((2, 2)))
    model.add(Dropout(0.4))
    model.add(Flatten())
    model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))
    model.add(BatchNormalization())
    model.add(Dropout(0.5))
    model.add(Dense(10, activation='softmax'))
    # compile model
    opt = SGD(lr=0.001, momentum=0.9)
    model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
    return model

# plot diagnostic learning curves
def summarize_diagnostics(history):
    # plot loss
    pyplot.subplot(211)
    pyplot.title('Cross Entropy Loss')
    pyplot.plot(history.history['loss'], color='blue', label='train')
    pyplot.plot(history.history['val_loss'], color='orange', label='test')
    # plot accuracy
    pyplot.subplot(212)
    pyplot.title('Classification Accuracy')
    pyplot.plot(history.history['accuracy'], color='blue', label='train')
    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')
    # save plot to file
    filename = sys.argv[0].split('/')[-1]
    pyplot.savefig(filename + '_plot.png')
    pyplot.close()

# run the test harness for evaluating a model
def run_test_harness():
    # load dataset
    trainX, trainY, testX, testY = load_dataset()
    # prepare pixel data
    trainX, testX = prep_pixels(trainX, testX)
    # define model
    model = define_model()
    # create data generator
    datagen = ImageDataGenerator(width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True)
    # prepare iterator
    it_train = datagen.flow(trainX, trainY, batch_size=64)
    # fit model
    steps = int(trainX.shape[0] / 64)
    history = model.fit_generator(it_train, steps_per_epoch=steps, epochs=100, validation_data=(testX, testY), verbose=0)
    # evaluate model
    _, acc = model.evaluate(testX, testY, verbose=0)
    print('> %.3f' % (acc * 100.0))
    # learning curves
    summarize_diagnostics(history)

# entry point, run the test harness
run_test_harness()```

```

答: You need High GPU Operating system to run this on Jypyter Notebook. otherwise use Google Colab (https://colab.research.google.com/), Due to high value of epoch it will take a large amount of time in jupyter notebook

Body:
I've implemented the following code in Jupyter notebook, and it has been over 90 mins, the programme is still running, and I've not gotten any output.

I'm working with mid-2012 MacBook Pro.
4 GB ram.
I've checked the activity monitor, memory pressure is in the yellow zone, so that means, the means, the mac is not running out of memory, and I don't know what to do now.

The program implements CNN model over CIFAR-10 dataset.

import sys
from matplotlib import pyplot
from keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Dense
from keras.layers import Flatten
from tensorflow.keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Dropout
from keras.layers import BatchNormalization
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

# load train and test dataset
def load_dataset():
    # load dataset
    (trainX, trainY), (testX, testY) = cifar10.load_data()
    # one hot encode target values
    trainY = to_categorical(trainY)
    testY = to_categorical(testY)
    return trainX, trainY, testX, testY

# scale pixels
def prep_pixels(train, test):
    # convert from integers to floats
    train_norm = train.astype('float32')
    test_norm = test.astype('float32')
    # normalize to range 0-1
    train_norm = train_norm / 255.0
    test_norm = test_norm / 255.0
    # return normalized images
    return train_norm, test_norm

# define cnn model
def define_model():
    model = Sequential()
    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(32, 32, 3)))
    model.add(BatchNormalization())
    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D((2, 2)))
    model.add(Dropout(0.2))
    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D((2, 2)))
    model.add(Dropout(0.3))
    model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D((2, 2)))
    model.add(Dropout(0.4))
    model.add(Flatten())
    model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))
    model.add(BatchNormalization())
    model.add(Dropout(0.5))
    model.add(Dense(10, activation='softmax'))
    # compile model
    opt = SGD(lr=0.001, momentum=0.9)
    model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
    return model

# plot diagnostic learning curves
def summarize_diagnostics(history):
    # plot loss
    pyplot.subplot(211)
    pyplot.title('Cross Entropy Loss')
    pyplot.plot(history.history['loss'], color='blue', label='train')
    pyplot.plot(history.history['val_loss'], color='orange', label='test')
    # plot accuracy
    pyplot.subplot(212)
    pyplot.title('Classification Accuracy')
    pyplot.plot(history.history['accuracy'], color='blue', label='train')
    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')
    # save plot to file
    filename = sys.argv[0].split('/')[-1]
    pyplot.savefig(filename + '_plot.png')
    pyplot.close()

# run the test harness for evaluating a model
def run_test_harness():
    # load dataset
    trainX, trainY, testX, testY = load_dataset()
    # prepare pixel data
    trainX, testX = prep_pixels(trainX, testX)
    # define model
    model = define_model()
    # create data generator
    datagen = ImageDataGenerator(width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True)
    # prepare iterator
    it_train = datagen.flow(trainX, trainY, batch_size=64)
    # fit model
    steps = int(trainX.shape[0] / 64)
    history = model.fit_generator(it_train, steps_per_epoch=steps, epochs=100, validation_data=(testX, testY), verbose=0)
    # evaluate model
    _, acc = model.evaluate(testX, testY, verbose=0)
    print('> %.3f' % (acc * 100.0))
    # learning curves
    summarize_diagnostics(history)

# entry point, run the test harness
run_test_harness()```


问:
Difference between buffers in Kotlin flow
As far as I know there are three types of buffers in Kotlin flow: Buffer, Conflate and CollectLatest and I'm having trouble figuring out the differences between these three terminal operators.

```<code>flow.buffer().collect{...}
flow.collectLatest{...}
flow.conflate().collect{...}
</code>```

I apologize the brevity, but what are the differences between these buffers and when should we use each of them?

Any help is appreciated in advance.

答:
Buffers actually accept the same parameters as Channels in addition to specifying the exact capacity of a buffer.

Using the buffer method, you can pass arguments to the capacity parameter to use any type of Channel via buffer(capacity = Channel.<Type>) There is also an onBufferOverflow parameter that can be used to further customize your buffer.

The documentation at https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/buffer.html#:~:text=documentation%20for%20details.-,Parameters,-capacity describes your options for creating new buffers.

A good explanation of Channel types can be found on Kotlin's official website:

https://play.kotlinlang.org/hands-on/Introduction%20to%20Coroutines%20and%20Channels/08_Channels

buffer() allows for multiple coroutines to process emit calls concurrently, thereby saving time instead of waiting for each emit call in sequence.

conflate() is equivalent to buffer(capacity = Channel.CONFLATED) or buffer(capacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)

In the event of multiple emit calls, it will still process them all, but will only collect the final call.

collectLatest(), in the event of multiple emit calls, will not process intermediate values.

It will instead cancel each subsequent call as a new one is made available to it; returning only the final result. This gives it the fastest processing time in situations where you only need the most up-to-date call from the Flow.

Body:
As far as I know there are three types of buffers in Kotlin flow: Buffer, Conflate and CollectLatest and I'm having trouble figuring out the differences between these three terminal operators.

flow.buffer().collect{...}
flow.collectLatest{...}
flow.conflate().collect{...}

I apologize the brevity, but what are the differences between these buffers and when should we use each of them?

Any help is appreciated in advance.


问:
Object array not printing to screen - React
On page load, I am using UseEffect to take an object array files. The array is mapped through, if it is male it is added to maleArray, if it is female it is added to femaleArray. At the end, i use console.log to check if the new arrays have filled and they have. I also set hasLoaded to true after this.

```<code>const[hasLoaded, setHasLoaded] = useState();
var maleArray= [];
var femaleArray= [];

useEffect(() => {
      getPersonGender();

    }, [props.files]);

    const getPersonGender = () => {
      if(!props.files.length > 0){
        console.log("WAITING");
      }else{
        props.files.map( person => {
          if(person.gender=== "male"){
            maleArray.push(person);
          }else{
            femaleArray.push(person);
          }
        });
        console.log(maleArray)
        console.log(femaleArray)
        setHasLoaded(true);
      }
    }
</code>```

However when I get to the return statement, the new arrays I filled seem to be empty. For example, I am trying to map the maleArray to a table. I check hasLoaded and it is true but when I get to print nothing displays and I can't figure out why. When I attempted to debug, it seemed that maleArray and femaleArray never filled, but however, I am getting the console.log results saying that they are.

```<code>{!hasLoaded
    ?<div class="spinner-border" role="status"></div>
    :
    <table class="table">
    <tbody>
        {maleArray.map(male=> (
            <tr>
                <td>{male.name}</td>
                <td>{male.age}</td>
            </tr>
    ))}
    </tbody>
    </table>
}
</code>```

Any reason why the new arrays are not being filled, yet i see the output on console.log? Thanks

答:
I think you have typo in {maleArray.map(male=>

Shouldn't it be { maleArray.map((male) => { rest of code }

Body:
On page load, I am using UseEffect to take an object array files. The array is mapped through, if it is male it is added to maleArray, if it is female it is added to femaleArray. At the end, i use console.log to check if the new arrays have filled and they have. I also set hasLoaded to true after this.

const[hasLoaded, setHasLoaded] = useState();
var maleArray= [];
var femaleArray= [];

useEffect(() => {
      getPersonGender();

    }, [props.files]);

    const getPersonGender = () => {
      if(!props.files.length > 0){
        console.log("WAITING");
      }else{
        props.files.map( person => {
          if(person.gender=== "male"){
            maleArray.push(person);
          }else{
            femaleArray.push(person);
          }
        });
        console.log(maleArray)
        console.log(femaleArray)
        setHasLoaded(true);
      }
    }

However when I get to the return statement, the new arrays I filled seem to be empty. For example, I am trying to map the maleArray to a table. I check hasLoaded and it is true but when I get to print nothing displays and I can't figure out why. When I attempted to debug, it seemed that maleArray and femaleArray never filled, but however, I am getting the console.log results saying that they are.

{!hasLoaded
    ?

    :

        {maleArray.map(male=> (

                {male.name}
                {male.age}

    ))}

}

Any reason why the new arrays are not being filled, yet i see the output on console.log? Thanks


问:
How do you get text from span tag in React (onClick)?
I'm new to React, but not to programming. In the following code, desc never changes state, and I believe this is because the  tag isn't entirely compatible with the value and onChange attribute/event handler im trying to use with it.

What im trying to do is get the text information from the span tag when you press the className='submit' button. I saw some videos where people suggested the method i have in place now, where you constantly update the state onChange, however this seems janky to me and if theres a better way where you get the text only onClick once instead of constantly updating, please let me know.

Also, I'm using a span with the contentEditable attribute because of CSS styling reasons, I want a borderless box that expands itself and the container its in instead of the text going off the page to the right. I attached a screenshot of what I mean.

```<code>    const [title, setTitle] = useState('');
    const [desc, setDesc] = useState('');

        return (
            <div className='card-container'>
                <div className='card'>
                    <h1 className='card-title'>
                        <input className='titletext' value={title} onChange={e => setTitle(e.currentTarget.value)} placeholder='Who do you need?'></input>
                    </h1>
                    <p className='card-desc'>
                        <span className='textarea' value={desc} onChange={e => setDesc(e.currentTarget.value)} contentEditable></span>
                    </p>

                    <button className='submit' onClick={event => {
                        /*
                            Add job to the database (async)

                            Add new card with information submitted in the list right below
                        */
                        event.preventDefault();
                        console.log(title);
                        console.log(desc);

                    }}></button>
                </div>
            </div>
        );
}
</code>```

答:
so I figured out what the problem was. onChange doesn't work with span tags, even in vanilla JS. The solution was to change onChange to onInput, and use e.currentTarget.innerText

Thanks to Suhag Lapani88 for narrowing it down though he offered what I thought was going to be a solution with useRef, because I thought I was using useRef wrong.

Body:
I'm new to React, but not to programming. In the following code, desc never changes state, and I believe this is because the  tag isn't entirely compatible with the value and onChange attribute/event handler im trying to use with it.

What im trying to do is get the text information from the span tag when you press the className='submit' button. I saw some videos where people suggested the method i have in place now, where you constantly update the state onChange, however this seems janky to me and if theres a better way where you get the text only onClick once instead of constantly updating, please let me know.

Also, I'm using a span with the contentEditable attribute because of CSS styling reasons, I want a borderless box that expands itself and the container its in instead of the text going off the page to the right. I attached a screenshot of what I mean.

    const [title, setTitle] = useState('');
    const [desc, setDesc] = useState('');

        return (

                        <input className='titletext' value={title} onChange={e => setTitle(e.currentTarget.value)} placeholder='Who do you need?'></input>

                         setDesc(e.currentTarget.value)} contentEditable>

                    <button className='submit' onClick={event => {
                        /*
                            Add job to the database (async)

                            Add new card with information submitted in the list right below
                        */
                        event.preventDefault();
                        console.log(title);
                        console.log(desc);

                    }}></button>

        );
}


问:
Powershell start-process running windows explorer does not wait
I have a PS script to monitor a logging file for a specific list of servers in the network.  If the script logic finds the issue I'm monitoring for, I want to interrupt the script process with a launch and wait of windows explorer for the related server network folder path.

Windows explorer does show the requested folder, however PS doesn't wait for it to close.

This is the script I'm testing with:

```<code># Sample networkfolderpath
$networkfolderpath = '\\server\d$\parent\child'

Start-Process explorer.exe -ArgumentList $networkfolderpath -Wait
</code>```

FYI: I have a RDP function that is setup the same way and it does wait as expected.

```<code>Start-Process mstsc /v:$computername -Wait
</code>```

I'm presuming at this point that windows explorer just behaves differently than some other exe.

What am I missing?

答:
As mentioned in the comments, the example with mstsc only works because there's a 1-to-1 relationship between closing the main window it produces and exiting the process.

This relationship does not exist with explorer - it'll detect on launch that the desktop session already has a shell, notify it of the request, and then exit immediately.

Instead, use Read-Host to block further execution of the script until the user hits enter:

```<code># launch folder window
Invoke-Item $networkfolderpath
# block the runtime from doing anything further by prompting the user (then discard the input)
$null = Read-Host "Edit the files, then hit enter to continue..."
</code>```

Body:
I have a PS script to monitor a logging file for a specific list of servers in the network.  If the script logic finds the issue I'm monitoring for, I want to interrupt the script process with a launch and wait of windows explorer for the related server network folder path.

Windows explorer does show the requested folder, however PS doesn't wait for it to close.

This is the script I'm testing with:

# Sample networkfolderpath
$networkfolderpath = '\\server\d$\parent\child'

Start-Process explorer.exe -ArgumentList $networkfolderpath -Wait

FYI: I have a RDP function that is setup the same way and it does wait as expected.

Start-Process mstsc /v:$computername -Wait

I'm presuming at this point that windows explorer just behaves differently than some other exe.

What am I missing?

Body:
As mentioned in the comments, the example with mstsc only works because there's a 1-to-1 relationship between closing the main window it produces and exiting the process.

This relationship does not exist with explorer - it'll detect on launch that the desktop session already has a shell, notify it of the request, and then exit immediately.

Instead, use Read-Host to block further execution of the script until the user hits enter:

# launch folder window
Invoke-Item $networkfolderpath
# block the runtime from doing anything further by prompting the user (then discard the input)
$null = Read-Host "Edit the files, then hit enter to continue..."