问:
WPF TextBlock dynamic bold and italic parts
I'm using MVVM pattern and I have string type property in my ModelView.

The string may contain following HTML tags:

```<code><b>, </b>, <i>, </i>
</code>```

I need to make certain parts of text in TextBlock to be in normal, bold or italic.

At moment I have created workaround, a helper method that works like this:

Breaks HTML string into parts

Creates instance of Run class

Depending on tag, sets FontWeight or FontStyle properties

Adds instance of Run class to TextBlock's Inlines collection

This solution works, but it is not compatible with MVVM pattern.

I was thinking of using Convertors, but I'm not sure what property of TextBlock should I do binding to.

What do You think, how can this problem be solved?

答:
The easiest solution that I've found for this problem.

Is to use BindableRichTextBox, that can be found at http://www.shawnduggan.com/?p=54

Using Convertors convert HTML string to XAML and then make it into FlowDocument object

Bind Document to BindableRichTextBox

Make RichTextBox look like TextBlock (Focusable="False", BorderThinkness="0", BorderBrush="White"....etc)

OwnerDisplayName: Daniil Harik

Body:
I'm using MVVM pattern and I have string type property in my ModelView.

The string may contain following HTML tags:

, , ,

I need to make certain parts of text in TextBlock to be in normal, bold or italic.

At moment I have created workaround, a helper method that works like this:

Breaks HTML string into parts

Creates instance of Run class

Depending on tag, sets FontWeight or FontStyle properties

Adds instance of Run class to TextBlock's Inlines collection

This solution works, but it is not compatible with MVVM pattern.

I was thinking of using Convertors, but I'm not sure what property of TextBlock should I do binding to.

What do You think, how can this problem be solved?


来源: stackexchange

问:
Getting an error as "decoding to str: need a bytes-like object, int found" while tried to return id and field value in django models
model #1

```<code>class Add_Job(models.Model):

    job_name=models.CharField(max_length=254)
    client=models.ForeignKey(Client,on_delete=CASCADE,related_name='client')
    #client=models.ManyToManyField(Client)
    project=models.ForeignKey(Project,on_delete=CASCADE,related_name='project')
    #project=models.ManyToManyField(Project)
    user=models.ForeignKey(Users,on_delete=CASCADE)
    Hours=models.TimeField(null=True)
    start_Date = models.DateTimeField(max_length=10)
    end_Date=models.DateTimeField(max_length=10)

    def __str__(self):
        return str(self.id, self.job_name)
</code>```

model #2

```<code>class Add_Timelog(models.Model):

    project=models.ManyToManyField(Project)
    client=models.ManyToManyField(Client)
    Job=models.ManyToManyField(Add_Job)
    #Date = models.DateField(max_length=100 ,auto_now_add=True,editable=True)
    Date= models.DateField(default = datetime.date.today)
    Hours=models.TimeField(null=True)

    def __str__(self):
        return str(self.Date)
</code>```

while I tried to return the 'id' and 'job_name' from the 'Add_Job' model it is getting reflected in the database table. But the 'Add_timelog' model is getting an error

TypeError at /api/Add_Timelog/ decoding to str: need a bytes-like
object, int found

Don't know why it is getting an error.

After update1:

```<code>class Add_Timelog(models.Model):

    project=models.ManyToManyField(Project)
    client=models.ManyToManyField(Client)
    Job=models.ManyToManyField(Add_Job)
    #Date = models.DateField(max_length=100 ,auto_now_add=True,editable=True)
    Date= models.DateField(default = datetime.date.today)
    Hours=models.TimeField(null=True)

    def __str__(self):
        return str( '{} {}'.format(self.Date, self.Hours))
</code>```

model 2

```<code>class Consolidated(models.Model):

   emp_name=models.ManyToManyField(Users,related_name="employee_name+")
    proj_name=models.ManyToManyField(Project)
    custom_name=models.ManyToManyField(Client)
    Cons_date=models.ManyToManyField(Add_Timelog)
    bill_no_bill=models.ManyToManyField(Users,related_name="billable_and_non_billable+")
    hour_spent = models.ManyToManyField(Add_Timelog,related_name="hour_spent")

    def __str__(self):
       return str(self.emp_name)
</code>```

So as per property method code it is returning the value as object and not as value. But I defined a str function and removed the property method and I am getting the value but both date and hours in the same field. But as per my model "consolidated", I need to get that date seperately and hours seperately. Is that possible to do that in django model ?

答:
It looks like problem with Add_Job model, not Add_Timelog. In str method you are trying to convert id and job_name to str, but this raises TypeError. Try to change return str(self.id, self.job_name) to return '{} {}'.format(str(self.id), self.job_name) it's going to convert id of object to string and put it in first {} and job_name, which is already string in second {}

If you want to access both Date and Hours you can do it using @property method decorator. In your case you would need to write in your Add_Timelog model.

```<code>@property
def date_and_hours(self):
    return '{} {}'.format(self.Date, self.Hours)
</code>```

If you want to get their values not string representation just return two values from property, but you need to unpack them.

```<code>@property
def date_and_hours(self):
    return self.Date, self.Hours
</code>```

ContentLicense: CC BY-SA 4.0

Body:
model #1

class Add_Job(models.Model):

    job_name=models.CharField(max_length=254)
    client=models.ForeignKey(Client,on_delete=CASCADE,related_name='client')
    #client=models.ManyToManyField(Client)
    project=models.ForeignKey(Project,on_delete=CASCADE,related_name='project')
    #project=models.ManyToManyField(Project)
    user=models.ForeignKey(Users,on_delete=CASCADE)
    Hours=models.TimeField(null=True)
    start_Date = models.DateTimeField(max_length=10)
    end_Date=models.DateTimeField(max_length=10)

    def __str__(self):
        return str(self.id, self.job_name)

model #2

class Add_Timelog(models.Model):

    project=models.ManyToManyField(Project)
    client=models.ManyToManyField(Client)
    Job=models.ManyToManyField(Add_Job)
    #Date = models.DateField(max_length=100 ,auto_now_add=True,editable=True)
    Date= models.DateField(default = datetime.date.today)
    Hours=models.TimeField(null=True)

    def __str__(self):
        return str(self.Date)

while I tried to return the 'id' and 'job_name' from the 'Add_Job' model it is getting reflected in the database table. But the 'Add_timelog' model is getting an error

TypeError at /api/Add_Timelog/ decoding to str: need a bytes-like
object, int found

Don't know why it is getting an error.

After update1:

class Add_Timelog(models.Model):

    project=models.ManyToManyField(Project)
    client=models.ManyToManyField(Client)
    Job=models.ManyToManyField(Add_Job)
    #Date = models.DateField(max_length=100 ,auto_now_add=True,editable=True)
    Date= models.DateField(default = datetime.date.today)
    Hours=models.TimeField(null=True)

    def __str__(self):
        return str( '{} {}'.format(self.Date, self.Hours))

model 2

class Consolidated(models.Model):

   emp_name=models.ManyToManyField(Users,related_name="employee_name+")
    proj_name=models.ManyToManyField(Project)
    custom_name=models.ManyToManyField(Client)
    Cons_date=models.ManyToManyField(Add_Timelog)
    bill_no_bill=models.ManyToManyField(Users,related_name="billable_and_non_billable+")
    hour_spent = models.ManyToManyField(Add_Timelog,related_name="hour_spent")

    def __str__(self):
       return str(self.emp_name)

So as per property method code it is returning the value as object and not as value. But I defined a str function and removed the property method and I am getting the value but both date and hours in the same field. But as per my model "consolidated", I need to get that date seperately and hours seperately. Is that possible to do that in django model ?

Body:
It looks like problem with Add_Job model, not Add_Timelog. In str method you are trying to convert id and job_name to str, but this raises TypeError. Try to change return str(self.id, self.job_name) to return '{} {}'.format(str(self.id), self.job_name) it's going to convert id of object to string and put it in first {} and job_name, which is already string in second {}

If you want to access both Date and Hours you can do it using @property method decorator. In your case you would need to write in your Add_Timelog model.

@property
def date_and_hours(self):
    return '{} {}'.format(self.Date, self.Hours)

If you want to get their values not string representation just return two values from property, but you need to unpack them.

@property
def date_and_hours(self):
    return self.Date, self.Hours


问:
how to pass one function context variable to another function in django , or what is the good method instead of session for that?
views.py

```<code>    def contest(request):
        context = {}
        all_contest = Contest.objects.all()
        context["contest"] = all_contest
        return render(request,"contest.html",context)

    def contest_candidates(request,id):
        context = {}
        all_candidates_ = Contest_Candidates.objects.filter(contest_id = id)
        high_like = 0
        winner_ = ""
        for i in all_candidates_:

            if i.likes_count > high_like:
                high_like = high_like + i.likes_count
                winner_ = i.owner.name

        context["cadidates"] = all_candidates_

        return render(request,"view_contest_candidates.html",context)
</code>```

urls.py

```<code>path("contest",views.contest, name="contest"),
path("candidates/<id>",views.view_contest_candidates, name="candidates"),
</code>```

models.py

```<code>class Contest(models.Model):
    title = models.CharField(max_length=50)

class Contest_Candidates(models.Model):
    image = models.FileField( upload_to="contest_candidates/",)
    owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    contest = models.ForeignKey(Contest, on_delete=models.CASCADE,related_name='candidates')

    @property
    def likes_count(self):
       return self.likes.all().count()

class CandidateLikes(models.Model):
    like = models.CharField(max_length=10)
    user = models.ForeignKey(CustomUser,on_delete=models.CASCADE,related_name='candidate_likes')
    contest_candidates = models.ForeignKey(Contest_Candidates, on_delete=models.CASCADE, related_name='likes')
</code>```

how to pass the winner variable in to contest function ? i need to show that in contest.html

if it's not possible,  which is the best method . want to show every contest winner in contest.html

答:
As far as I understand - winner variable is calculated in your second function.

Nothing prevents calculating it in contest as well:

models.py

```<code>class Contest(models.Model):
    title = models.CharField(max_length=50)

    @property
    def winner(self):
     high_like = 0
     all_candidates_ = Contest_Candidates.objects.filter(contest=self)
     winner = None
     for c in all_candidates_:
         if c.likes_count > high_like:
             winner = c.owner
     return winner
</code>```

views.py

```<code>def contest(request):
    context = {"contests": Contest.objects.all()}

    return render(request,"contest.html",context)

def contest_candidates(request,id):
    contest = Contest.objects.get(id=id)
    context = {
        "contest": contest,
        "candidates": Contest_Candidates.objects.filter(contest=contest)
    }

    return render(request,"view_contest_candidates.html",context)
</code>```

contest.html

```<code>{% for c in contests %}
    {{ c.title }}
    {{ c.winner.name }}
{% endfor %}
</code>```

Body:
views.py

    def contest(request):
        context = {}
        all_contest = Contest.objects.all()
        context["contest"] = all_contest
        return render(request,"contest.html",context)

    def contest_candidates(request,id):
        context = {}
        all_candidates_ = Contest_Candidates.objects.filter(contest_id = id)
        high_like = 0
        winner_ = ""
        for i in all_candidates_:

            if i.likes_count > high_like:
                high_like = high_like + i.likes_count
                winner_ = i.owner.name

        context["cadidates"] = all_candidates_

        return render(request,"view_contest_candidates.html",context)

urls.py

path("contest",views.contest, name="contest"),
path("candidates/<id>",views.view_contest_candidates, name="candidates"),

models.py

class Contest(models.Model):
    title = models.CharField(max_length=50)

class Contest_Candidates(models.Model):
    image = models.FileField( upload_to="contest_candidates/",)
    owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    contest = models.ForeignKey(Contest, on_delete=models.CASCADE,related_name='candidates')

    @property
    def likes_count(self):
       return self.likes.all().count()

class CandidateLikes(models.Model):
    like = models.CharField(max_length=10)
    user = models.ForeignKey(CustomUser,on_delete=models.CASCADE,related_name='candidate_likes')
    contest_candidates = models.ForeignKey(Contest_Candidates, on_delete=models.CASCADE, related_name='likes')

how to pass the winner variable in to contest function ? i need to show that in contest.html

if it's not possible,  which is the best method . want to show every contest winner in contest.html

Body:
As far as I understand - winner variable is calculated in your second function.

Nothing prevents calculating it in contest as well:

models.py

class Contest(models.Model):
    title = models.CharField(max_length=50)

    @property
    def winner(self):
     high_like = 0
     all_candidates_ = Contest_Candidates.objects.filter(contest=self)
     winner = None
     for c in all_candidates_:
         if c.likes_count > high_like:
             winner = c.owner
     return winner

views.py

def contest(request):
    context = {"contests": Contest.objects.all()}

    return render(request,"contest.html",context)

def contest_candidates(request,id):
    contest = Contest.objects.get(id=id)
    context = {
        "contest": contest,
        "candidates": Contest_Candidates.objects.filter(contest=contest)
    }

    return render(request,"view_contest_candidates.html",context)

contest.html

{% for c in contests %}
    {{ c.title }}
    {{ c.winner.name }}
{% endfor %}


问:
Make container scroll when dragging in Safari HTML5
Building a draggable component using HTML5 Drag and drop API source. I am rendering the elements inside a scrollable container. When I drag an item - the container scrolls fine in Chrome and Firefox. But in Safari the container does not scroll at all when I drag an item. Any thoughts/pointers?

jsbin

```<code>// relevant css.
.container {
  display: grid;
  grid-template-rows: repeat(5, 1fr);
  gap: 10px;
  overflow-y: scroll;
  height: 200px;
}
</code>```

答:
Its a limitation as of now. Safari supports scrolling when something is being dragged (multiple gestures support I guess) but doesn't auto-scroll when you try to drag and move the draggable content. This may be the reason it doesn't scroll unless the user drags with mouse and scrolls at the same time using the keypad as discussed in the below thread:
https://discussions.apple.com/thread/252081922</p>

Body:
Building a draggable component using HTML5 Drag and drop API source. I am rendering the elements inside a scrollable container. When I drag an item - the container scrolls fine in Chrome and Firefox. But in Safari the container does not scroll at all when I drag an item. Any thoughts/pointers?

jsbin

// relevant css.
.container {
  display: grid;
  grid-template-rows: repeat(5, 1fr);
  gap: 10px;
  overflow-y: scroll;
  height: 200px;
}


问:
STAN - Real parameter given a categorical vector
I am a beginner using stan (and stackoverflow by the way, I have absolutely no idea how you pretty print a dataframe on it, could not find how, sorry).

Let's say I want to make the following model :

```<code>y ~ normal(I*S + P*J,sigma)
P ~ normal(dP,1)
</code>```

(to simplify this example I fix the deviation around P at 1)

where on one hand, I is a n,p matrix predictor and S are the corresponding regression coefficients (size p)

and on the other hand dP and J can only have 3 different values but my dataframe is constructed such as they looks like this (R-project):

```<code>dp <- c(0,0,0,0,0,0,0,2,2,2,2,2,2,2,1,1,1,1,1,1)
J <- c(5.2,5.2,....,2.3,2.3,....,7.5,7.5,...)
</code>```

parameters are S, P and sigma.

I do no want stan to change every components of P, dp represents 3 types of data and I only want three different values of P corresponding to the 3 differents values of dp.
However each row of my dataframe contains different values of I.

edit: said in another way: for each row k, I want :

```<code>y[k] ~ I[k,1]*S[1]+I[k,2]*S[2]...+ real_value_P * J[k]
</code>```

How can I achieve that ?

Here is my code:

```<code>data {
 int < lower = 1 > NR; // Number of rows
 int < lower = 1 > NC; // Number of columns

 matrix [NR,NC] I ;// Predictor I
 vector [NR] dP;
 vector [NR] J ;

 vector [NR] y; // Outcome
}

parameters {
 real < lower = 0 > sigma; // Error SD
 vector [NC] S ;
 vector [NC] P ;
 }

model {
P ~ normal(dP,1)
y ~ normal(I*S+P*J,sigma) ;
}
</code>```

I am not sure I have been really clear, stats are still a tough subject to me either and my model is a bit more complicated than presented.

Thanks

答:
The "trick" seems to indicate in a vector ("indices" here) which value of P to take (1,1,1,1,1,...2,2,2,2,2,...,3,3,3,3,3) and then to loop over it in the parameters to assign the correct value :

```<code>transformed parameters {
 vector [NR] JP ; //J*P
 for (k in 1:NR){
        JP[k]=True_P[indices[k]]*J[k] ;
 }
</code>```

Hence the complete code :

```<code>data {
 int < lower = 1 > NR; // Number of rows
 int < lower = 1 > NC; // Number of columns

 matrix [NR,NC] I ;// Predictor I

 int indices[NR]; // indices
 vector [3] P ;
 vector [NR] dP ;
 vector [NR] J ;

 vector [NR] y; // Outcome
}

parameters {
 real < lower = 0 > sigma; // Error SD
 vector < lower = 0 > [NC] S ;     // regression coefficients for predictors I
 vector [2] True_P ;
}

transformed parameters {
 vector [NR] JP ; //J*P
 for (k in 1:NR){
        JP[k]=True_P[indices[k]]*J[k] ;
 }

}

model {

for (k in 1:3){
P[k] ~ normal(True_P[k],1) ;
}

y ~ normal(I*S+JP,sigma) ;
}

generated quantities {
} // The posterior predictive distributiondistribution
</code>```

Body:
I am a beginner using stan (and stackoverflow by the way, I have absolutely no idea how you pretty print a dataframe on it, could not find how, sorry).

Let's say I want to make the following model :

y ~ normal(I*S + P*J,sigma)
P ~ normal(dP,1)

(to simplify this example I fix the deviation around P at 1)

where on one hand, I is a n,p matrix predictor and S are the corresponding regression coefficients (size p)

and on the other hand dP and J can only have 3 different values but my dataframe is constructed such as they looks like this (R-project):

dp <- c(0,0,0,0,0,0,0,2,2,2,2,2,2,2,1,1,1,1,1,1)
J <- c(5.2,5.2,....,2.3,2.3,....,7.5,7.5,...)

parameters are S, P and sigma.

I do no want stan to change every components of P, dp represents 3 types of data and I only want three different values of P corresponding to the 3 differents values of dp.
However each row of my dataframe contains different values of I.

edit: said in another way: for each row k, I want :

y[k] ~ I[k,1]*S[1]+I[k,2]*S[2]...+ real_value_P * J[k]

How can I achieve that ?

Here is my code:

data {
 int < lower = 1 > NR; // Number of rows
 int < lower = 1 > NC; // Number of columns

 matrix [NR,NC] I ;// Predictor I
 vector [NR] dP;
 vector [NR] J ;

 vector [NR] y; // Outcome
}

parameters {
 real < lower = 0 > sigma; // Error SD
 vector [NC] S ;
 vector [NC] P ;
 }

model {
P ~ normal(dP,1)
y ~ normal(I*S+P*J,sigma) ;
}

I am not sure I have been really clear, stats are still a tough subject to me either and my model is a bit more complicated than presented.

Thanks

Body:
The "trick" seems to indicate in a vector ("indices" here) which value of P to take (1,1,1,1,1,...2,2,2,2,2,...,3,3,3,3,3) and then to loop over it in the parameters to assign the correct value :

transformed parameters {
 vector [NR] JP ; //J*P
 for (k in 1:NR){
        JP[k]=True_P[indices[k]]*J[k] ;
 }

Hence the complete code :

data {
 int < lower = 1 > NR; // Number of rows
 int < lower = 1 > NC; // Number of columns

 matrix [NR,NC] I ;// Predictor I

 int indices[NR]; // indices
 vector [3] P ;
 vector [NR] dP ;
 vector [NR] J ;

 vector [NR] y; // Outcome
}

parameters {
 real < lower = 0 > sigma; // Error SD
 vector < lower = 0 > [NC] S ;     // regression coefficients for predictors I
 vector [2] True_P ;
}

transformed parameters {
 vector [NR] JP ; //J*P
 for (k in 1:NR){
        JP[k]=True_P[indices[k]]*J[k] ;
 }

}

model {

for (k in 1:3){
P[k] ~ normal(True_P[k],1) ;
}

y ~ normal(I*S+JP,sigma) ;
}

generated quantities {
} // The posterior predictive distributiondistribution


问:
Spring Security OAuth Client for WebClient With Password Grant Type Doesn't Ask For New Token
I have a Spring Web application that has a oauth2 resource server configured for it's API endpoints and a completely different oauth2 client for REST calls it makes. The oauth2 client needs to be of a password grant type. Username and password is fixed (not coming from HTTP request). My problem is that after 30 minutes both access token and refresh token expire, so there is no way to do a refresh. I would expect that Spring Security would just ask for new access token, but no. It calls the REST endpoint with the expired one and it returns 403.
Here's what I have:

application.yml:

```<code>spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://our.idp.keycloak.host/auth/realms/firstrealm
      client:
        registration:
          my-client-authorization:
            client-id: my_client
            client-secret: ${CLIENT_SECRET}
            authorization-grant-type: password
            scope: openid, profile
        provider:
          my-client-authorization:
            token-uri: https://our.idp.keycloak.host/auth/realms/secondrealm/protocol/openid-connect/token
</code>```

MyClientConfig.java:

```<code>import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.oauth2.client.OAuth2AuthorizationContext;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.Map;

@Configuration
@RequiredArgsConstructor
public class MyClientConfig {
    @Bean
    WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
        ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
        oauth2Client.setDefaultClientRegistrationId("my-client-authorization");
        return WebClient.builder()
                .apply(oauth2Client.oauth2Configuration())
                .baseUrl("https://the.api.host.to.call")
                .build();
    }

    @Bean
    public OAuth2AuthorizedClientManager authorizedClientManager(
            ClientRegistrationRepository clientRegistrationRepository,
            OAuth2AuthorizedClientRepository authorizedClientRepository
    ) {
        OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
                .password()
                .build();

        DefaultOAuth2AuthorizedClientManager result = new DefaultOAuth2AuthorizedClientManager(
                clientRegistrationRepository,
                authorizedClientRepository
        );

        result.setAuthorizedClientProvider(authorizedClientProvider);
        result.setContextAttributesMapper(oAuth2AuthorizeRequest -> Map.of(
                OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "user",
                OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password"
        ));

        return result;
    }
}
</code>```

The API call itself:

```<code>private <T> T callApi(Function<UriBuilder, URI> uriFunction, Class<T> resultType) {
    return this.webClient
            .get()
            .uri(uriFunction)
            .retrieve()
            .bodyToMono(resultType)
            .block();
}
</code>```

It works the first time I call it. But after 30 minutes the token is dead and I have no idea how to get a new one.
If I switch this to client_credentials grant type, it works, it automatically gets a new token when it is needed. But for some reason I cannot do the same for password grant type.

Edit:
So I managed to fix this thanks to this: https://github.com/spring-projects/spring-security/issues/8831 .
When I configure the WebClient also for refreshToken, then it crashes when the refresh token expires. But when you do the request again after that, it obtains a new token. So I had to wrap the API call in try catch and if the error is the one that I care about, I call the API again. It's not a very elegant solution, but it works.

答:
Additions to Abhinaba Chakraborty post:

There is no defined "ReactiveOAuth2AuthorizedClientService" and no "clientRegistrationRepository". Based on your Post I have these working settings

```<code>@Bean
ReactiveClientRegistrationRepository getRegistrationRepository() {
    ClientRegistration registration = ClientRegistration
            .withRegistrationId(REGISTRATION_ID)
            .tokenUri(TOKEN_URI)
            .clientId(CLIENT_ID)
            .clientSecret(CLIENT_SECRET)
            .authorizationGrantType(new AuthorizationGrantType(GRANT_TYPE))
            .build();
    return new InMemoryReactiveClientRegistrationRepository(registration);
}

@Bean
WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) {
    ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
    oauth2Client.setDefaultClientRegistrationId(REGISTRATION_ID);
    return WebClient.builder()
            .filter(oauth2Client)
            .build();
}

@Bean
public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
        ReactiveClientRegistrationRepository clientRegistrationRepository
) {
    ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
            .password()
            .build();

    AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager clientManager = new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
            clientRegistrationRepository,
            new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository)
    );

    clientManager.setAuthorizedClientProvider(authorizedClientProvider);
    clientManager.setContextAttributesMapper(oAuth2AuthorizeRequest -> Mono.just(Map.of(
            OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, USERNAME,
            OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, PASSWORD
    )));

    return clientManager;
}
</code>```

All constants should be clear. The REGISTRATION_ID is just any value but needs to be equal when creating/using the repository

Body:
I have a Spring Web application that has a oauth2 resource server configured for it's API endpoints and a completely different oauth2 client for REST calls it makes. The oauth2 client needs to be of a password grant type. Username and password is fixed (not coming from HTTP request). My problem is that after 30 minutes both access token and refresh token expire, so there is no way to do a refresh. I would expect that Spring Security would just ask for new access token, but no. It calls the REST endpoint with the expired one and it returns 403.
Here's what I have:

application.yml:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://our.idp.keycloak.host/auth/realms/firstrealm
      client:
        registration:
          my-client-authorization:
            client-id: my_client
            client-secret: ${CLIENT_SECRET}
            authorization-grant-type: password
            scope: openid, profile
        provider:
          my-client-authorization:
            token-uri: https://our.idp.keycloak.host/auth/realms/secondrealm/protocol/openid-connect/token

MyClientConfig.java:

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.oauth2.client.OAuth2AuthorizationContext;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.Map;

@Configuration
@RequiredArgsConstructor
public class MyClientConfig {
    @Bean
    WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
        ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
        oauth2Client.setDefaultClientRegistrationId("my-client-authorization");
        return WebClient.builder()
                .apply(oauth2Client.oauth2Configuration())
                .baseUrl("https://the.api.host.to.call")
                .build();
    }

    @Bean
    public OAuth2AuthorizedClientManager authorizedClientManager(
            ClientRegistrationRepository clientRegistrationRepository,
            OAuth2AuthorizedClientRepository authorizedClientRepository
    ) {
        OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
                .password()
                .build();

        DefaultOAuth2AuthorizedClientManager result = new DefaultOAuth2AuthorizedClientManager(
                clientRegistrationRepository,
                authorizedClientRepository
        );

        result.setAuthorizedClientProvider(authorizedClientProvider);
        result.setContextAttributesMapper(oAuth2AuthorizeRequest -> Map.of(
                OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "user",
                OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password"
        ));

        return result;
    }
}

The API call itself:

private <T> T callApi(Function<UriBuilder, URI> uriFunction, Class<T> resultType) {
    return this.webClient
            .get()
            .uri(uriFunction)
            .retrieve()
            .bodyToMono(resultType)
            .block();
}

It works the first time I call it. But after 30 minutes the token is dead and I have no idea how to get a new one.
If I switch this to client_credentials grant type, it works, it automatically gets a new token when it is needed. But for some reason I cannot do the same for password grant type.

Edit:
So I managed to fix this thanks to this: https://github.com/spring-projects/spring-security/issues/8831 .
When I configure the WebClient also for refreshToken, then it crashes when the refresh token expires. But when you do the request again after that, it obtains a new token. So I had to wrap the API call in try catch and if the error is the one that I care about, I call the API again. It's not a very elegant solution, but it works.

Body:
Additions to Abhinaba Chakraborty post:

There is no defined "ReactiveOAuth2AuthorizedClientService" and no "clientRegistrationRepository". Based on your Post I have these working settings

@Bean
ReactiveClientRegistrationRepository getRegistrationRepository() {
    ClientRegistration registration = ClientRegistration
            .withRegistrationId(REGISTRATION_ID)
            .tokenUri(TOKEN_URI)
            .clientId(CLIENT_ID)
            .clientSecret(CLIENT_SECRET)
            .authorizationGrantType(new AuthorizationGrantType(GRANT_TYPE))
            .build();
    return new InMemoryReactiveClientRegistrationRepository(registration);
}

@Bean
WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) {
    ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
    oauth2Client.setDefaultClientRegistrationId(REGISTRATION_ID);
    return WebClient.builder()
            .filter(oauth2Client)
            .build();
}

@Bean
public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
        ReactiveClientRegistrationRepository clientRegistrationRepository
) {
    ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
            .password()
            .build();

    AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager clientManager = new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
            clientRegistrationRepository,
            new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository)
    );

    clientManager.setAuthorizedClientProvider(authorizedClientProvider);
    clientManager.setContextAttributesMapper(oAuth2AuthorizeRequest -> Mono.just(Map.of(
            OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, USERNAME,
            OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, PASSWORD
    )));

    return clientManager;
}

All constants should be clear. The REGISTRATION_ID is just any value but needs to be equal when creating/using the repository


问:
Null Pointer Exception for read properties file in Idea
after define a property file in idea 10.5 when i try to use it,compiler show me Null Pointer Exception!I try anything that i think fix it among change property file path,...
here is the code that i write:
thanks.
beginner programmer!!!</p>

```<code>public class MainDlg{
    Properties properties=new Properties();
    public MainDlg() {
        try {
            InputStream reader=MainDlg.class.getResourceAsStream("propFile");
            properties.load(reader);
</code>```

答: getResourceAsStream returns null if the resource cannot be found.  Are you positive that, relative to the location of the MainDlg.class file, there is a folder called presentation, in which is a file called propFile?</p>

ContentLicense: CC BY-SA 3.0

Body:
after define a property file in idea 10.5 when i try to use it,compiler show me Null Pointer Exception!I try anything that i think fix it among change property file path,...
here is the code that i write:
thanks.
beginner programmer!!!

public class MainDlg{
    Properties properties=new Properties();
    public MainDlg() {
        try {
            InputStream reader=MainDlg.class.getResourceAsStream("propFile");
            properties.load(reader);


问:
Python Dataframe - Use column names as index, and sum of columns as values
I have a dataframe where the column names are dates, and values are number of cases. However, there are 300+ daily columns. How do I create a series where the index is the column names (dates), and values are the sum of number of days for each column?

Input:

```<code>      Country     1/1/2020   1/2/2020  ...  12/31/2020
  0   Afganistan  50         100       ...  500
  1   Albania     20         50        ...  50
  ...
  99  Zimbabwe   6          10         ...  5
</code>```

Desired output (pd.Series):

```<code>1/1/2020    76
1/2/2020    160
...
12/31/2020  555
</code>```

答:
Transposing and summing should do the trick:

```<code>df.T.sum()
</code>```

Where df is your DataFrame

Body:
I have a dataframe where the column names are dates, and values are number of cases. However, there are 300+ daily columns. How do I create a series where the index is the column names (dates), and values are the sum of number of days for each column?

Input:

      Country     1/1/2020   1/2/2020  ...  12/31/2020
  0   Afganistan  50         100       ...  500
  1   Albania     20         50        ...  50
  ...
  99  Zimbabwe   6          10         ...  5

Desired output (pd.Series):

1/1/2020    76
1/2/2020    160
...
12/31/2020  555

Body:
Transposing and summing should do the trick:

df.T.sum()

Where df is your DataFrame


问:
Keyboard not appearing in UITextField and UITextView IOS 15
i am not using storyboard for this application so here's my SceneDelegate willConnectTo function

```<code>func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    let windowScene = UIWindowScene(session: session, connectionOptions: connectionOptions)
    self.window = UIWindow(frame: UIScreen.main.bounds)

    self.window?.backgroundColor = .white
    let rootViewController = PersonsViewController()
    let navigationController = UINavigationController(rootViewController: rootViewController)
    navigationController.navigationBar.tintColor = .black

    self.window?.rootViewController = navigationController
    self.window?.makeKeyAndVisible()
    self.window?.windowScene = windowScene
}
</code>```

and here is the UITextView configuration function

```<code>private func configureTextView() {
    textView = UITextView(frame: CGRect(x: 75, y: 120, width: view.frame.width, height: 120))
    textView.font = UIFont.systemFont(ofSize: 16)
    textView.textColor = .black
    textView.backgroundColor = .blue
    textView.delegate = self
    textView.becomeFirstResponder()
    textView.isUserInteractionEnabled = true

    textView.keyboardType = .default
    view.addSubview(textView)
}
</code>```

and this is what gets printed in the console

```<code>Could not find keyboard scene delegate for interaction view <_UITextLayoutCanvasView: 0x105904be0; frame = (0 0; 375 120); userInteractionEnabled = NO; layer = <CALayer: 0x282ed8ee0>>.

2022-02-07 08:33:15.481898+0200 Project[40078:7478637] [Assert] Could not find window to attach loupe view.
</code>```

I made sure that the delegate methods get called

答:
The following code works:

  func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    guard let scene = (scene as? UIWindowScene) else { return }
    self.window = UIWindow(windowScene: scene)
    self.window?.backgroundColor = .white
    let rootViewController = ViewController()
    let navigationController = UINavigationController(rootViewController: rootViewController)
    navigationController.navigationBar.tintColor = .black
    self.window?.rootViewController = navigationController
    self.window?.makeKeyAndVisible()
  }
```

Body:
i am not using storyboard for this application so here's my SceneDelegate willConnectTo function

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    let windowScene = UIWindowScene(session: session, connectionOptions: connectionOptions)
    self.window = UIWindow(frame: UIScreen.main.bounds)

    self.window?.backgroundColor = .white
    let rootViewController = PersonsViewController()
    let navigationController = UINavigationController(rootViewController: rootViewController)
    navigationController.navigationBar.tintColor = .black

    self.window?.rootViewController = navigationController
    self.window?.makeKeyAndVisible()
    self.window?.windowScene = windowScene
}

and here is the UITextView configuration function

private func configureTextView() {
    textView = UITextView(frame: CGRect(x: 75, y: 120, width: view.frame.width, height: 120))
    textView.font = UIFont.systemFont(ofSize: 16)
    textView.textColor = .black
    textView.backgroundColor = .blue
    textView.delegate = self
    textView.becomeFirstResponder()
    textView.isUserInteractionEnabled = true

    textView.keyboardType = .default
    view.addSubview(textView)
}

and this is what gets printed in the console

Could not find keyboard scene delegate for interaction view <_UITextLayoutCanvasView: 0x105904be0; frame = (0 0; 375 120); userInteractionEnabled = NO; layer = <CALayer: 0x282ed8ee0>>.

2022-02-07 08:33:15.481898+0200 Project[40078:7478637] [Assert] Could not find window to attach loupe view.

I made sure that the delegate methods get called


问:
Zip array of structs with array of ints into array of structs column
I have a dataframe that looks like this:

```<code>val sourceData = Seq(
  Row(List(Row("a"), Row("b"), Row("c")), List(1, 2, 3)),
  Row(List(Row("d"), Row("e")), List(4, 5))
)

val sourceSchema = StructType(List(
  StructField("structs", ArrayType(StructType(List(StructField("structField", StringType))))),
  StructField("ints", ArrayType(IntegerType))
))

val sourceDF = sparkSession.createDataFrame(sourceData, sourceSchema)
</code>```

I want to transform it into a dataframe that looks like this:

```<code>val targetData = Seq(
  Row(List(Row("a", 1), Row("b", 2), Row("c", 3))),
  Row(List(Row("d", 4), Row("e", 5)))
)

val targetSchema = StructType(List(
  StructField("structs", ArrayType(StructType(List(
    StructField("structField", StringType),
    StructField("value", IntegerType)))))
))

val targetDF = sparkSession.createDataFrame(targetData, targetSchema)
</code>```

My best idea so far is to zip the two columns then run a UDF that puts the int value into the struct.

Is there an elegant way to do this, namely without UDFs?

答:
You can use array_zip function to zip structs and ints column then you can use transform function on zipped column to get required output.</p>
```<code>sourceDF.withColumn("structs", arrays_zip('structs, 'ints))
    .withColumn("structs",
      expr("transform(structs, s-> struct(s.structs.structField as structField, s.ints as value))"))
    .select("structs")
    .show(false)

+------------------------+
|structs                 |
+------------------------+
|[{a, 1}, {b, 2}, {c, 3}]|
|[{d, 4}, {e, 5}]        |
+------------------------+
</code>```

Body:
I have a dataframe that looks like this:

val sourceData = Seq(
  Row(List(Row("a"), Row("b"), Row("c")), List(1, 2, 3)),
  Row(List(Row("d"), Row("e")), List(4, 5))
)

val sourceSchema = StructType(List(
  StructField("structs", ArrayType(StructType(List(StructField("structField", StringType))))),
  StructField("ints", ArrayType(IntegerType))
))

val sourceDF = sparkSession.createDataFrame(sourceData, sourceSchema)

I want to transform it into a dataframe that looks like this:

val targetData = Seq(
  Row(List(Row("a", 1), Row("b", 2), Row("c", 3))),
  Row(List(Row("d", 4), Row("e", 5)))
)

val targetSchema = StructType(List(
  StructField("structs", ArrayType(StructType(List(
    StructField("structField", StringType),
    StructField("value", IntegerType)))))
))

val targetDF = sparkSession.createDataFrame(targetData, targetSchema)

My best idea so far is to zip the two columns then run a UDF that puts the int value into the struct.

Is there an elegant way to do this, namely without UDFs?

Body:
You can use array_zip function to zip structs and ints column then you can use transform function on zipped column to get required output.

sourceDF.withColumn("structs", arrays_zip('structs, 'ints))
    .withColumn("structs",
      expr("transform(structs, s-> struct(s.structs.structField as structField, s.ints as value))"))
    .select("structs")
    .show(false)

+------------------------+
|structs                 |
+------------------------+
|[{a, 1}, {b, 2}, {c, 3}]|
|[{d, 4}, {e, 5}]        |
+------------------------+


答:
You can set_index to "Country" and sum:

```<code>out = df.set_index('Country').sum()
</code>```

or drop "Country" and sum:

```<code>out = df.drop(columns='Country').sum()
</code>```

Output:

```<code>1/1/2020       76
1/2/2020      160
12/31/2020    555
dtype: int64
</code>```

Title: Python Dataframe - Use column names as index, and sum of columns as values

Body:
You can set_index to "Country" and sum:

out = df.set_index('Country').sum()

or drop "Country" and sum:

out = df.drop(columns='Country').sum()

Output:

1/1/2020       76
1/2/2020      160
12/31/2020    555
dtype: int64


问:
How to remove this warning from VScode python code?
In my python code, I see the following warning all over the place;

```<code>Missing function or method docstringpylint(missing-function-docstring)
</code>```

How do I remove this warning?

I am using VS code v1.64.0, Microsoft Python Extension for Visual Studio Code v2022.0.1786462952.

答:
From the hints provided in the comments, I managed to find an answer to my question.

Edit settings.json found in .vscode folder.

Add in the following;

```<code>{
    "python.linting.pylintArgs": [
        "--disable=C0116",
    ],
}
</code>```

My answer was found thanks to another answer here
How do you fix "Missing module docstringpylint(missing-module-docstring)"

Body:
In my python code, I see the following warning all over the place;

Missing function or method docstringpylint(missing-function-docstring)

How do I remove this warning?

I am using VS code v1.64.0, Microsoft Python Extension for Visual Studio Code v2022.0.1786462952.

Body:
From the hints provided in the comments, I managed to find an answer to my question.

Edit settings.json found in .vscode folder.

Add in the following;

{
    "python.linting.pylintArgs": [
        "--disable=C0116",
    ],
}

My answer was found thanks to another answer here
How do you fix "Missing module docstringpylint(missing-module-docstring)"


问:
Material UI v5 Align Inline Typography Component to the right
I just upgraded to MUI Version 5.4 and now my Inline Typography does not align right anymore.

This is my Code that worked for MUI Version 4:

```<code><Grid container xs={12}>
  <Grid container xs={12} justify="space-between" style={{borderBottom: "3px solid black"}}>
    <Typography inline>Value</Typography>
    <Typography inline align="right">{prodVol}MWh</Typography>
  </Grid>
</Grid>
</code>```

My Guess is, that there is a Problem with the new Grid, because when I changed that Import the Code stopped working.

答:
As Explained in this answer, I just replaced "justify" with "justifyContent".

My Working Code for MUI V5:

```<code><Grid container xs={12}>
  <Grid container xs={12} justifyContent="space-between" style={{borderBottom: "3px solid black"}}>
    <Typography inline>Value</Typography>
    <Typography inline align="right">{prodVol}MWh</Typography>
  </Grid>
</Grid>
</code>```

Thanks Medi :)

Body:
I just upgraded to MUI Version 5.4 and now my Inline Typography does not align right anymore.

This is my Code that worked for MUI Version 4:

<Grid container xs={12}>
  <Grid container xs={12} justify="space-between" style={{borderBottom: "3px solid black"}}>
    <Typography inline>Value</Typography>
    <Typography inline align="right">{prodVol}MWh</Typography>
  </Grid>
</Grid>

My Guess is, that there is a Problem with the new Grid, because when I changed that Import the Code stopped working.

Body:
As Explained in this answer, I just replaced "justify" with "justifyContent".

My Working Code for MUI V5:

<Grid container xs={12}>
  <Grid container xs={12} justifyContent="space-between" style={{borderBottom: "3px solid black"}}>
    <Typography inline>Value</Typography>
    <Typography inline align="right">{prodVol}MWh</Typography>
  </Grid>
</Grid>

Thanks Medi :)


问:
Screen glitch when validation errors are shown xamarin forms
I am learning a new way to show validation errors and I am having very weird issue with forms, when I click on Add button the controls that are pushed below the screen disappears or becomes transparent.

here is my form https://i.stack.imgur.com/LIrD6.jpg

when I click on add button this happens https://i.stack.imgur.com/PWZLZ.jpg (Note: this is an extended screenshot and my screen ends on phone number control. when I scroll remaining blank space is for Add button)

when I click/focus on any control the screen is fixes by itself https://i.stack.imgur.com/Exw4z.jpg

I am using shell app and have no idea whats going wrong here. Any help is appreciated.

here is my code

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="PROOF.Views.Patient.NewPatientPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
    xmlns:vm="clr-namespace:PROOF.ViewModels"
    xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
    Title="{Binding PageTitle}"
    ios:Page.UseSafeArea="true"
    x:DataType="vm:NewPatientViewModel"
    Shell.TabBarIsVisible="False"
    Visual="Material">
    <ContentPage.Resources>
        <ResourceDictionary>
            <xct:InvertedBoolConverter x:Key="InvertedBoolConverter" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <ScrollView>
            <Grid Margin="10">
                <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                    <Label Style="{DynamicResource HeadingLabel}" Text="Patient Info" />
                    <Entry
                        Placeholder="First Name"
                        Style="{DynamicResource DefaultEntry}"
                        Text="{Binding PatientFirstName}">
                        <Entry.Behaviors>
                            <xct:TextValidationBehavior
                                Flags="ValidateOnValueChanging"
                                IsValid="{Binding PatientFirstNameValid}"
                                RegexPattern="^(?!\s*$).+" />
                        </Entry.Behaviors>
                        <Entry.Triggers>
                            <DataTrigger
                                Binding="{Binding PatientFirstNameValid}"
                                TargetType="Entry"
                                Value="False">
                                <Setter Property="PlaceholderColor" Value="{StaticResource Error}" />
                            </DataTrigger>
                        </Entry.Triggers>
                    </Entry>
                    <Label
                        IsVisible="{Binding PatientFirstNameValid, Converter={StaticResource InvertedBoolConverter}}"
                        Style="{DynamicResource ValidationLabel}"
                        Text="First Name is required." />
                    <Entry
                        Placeholder="Last Name"
                        Style="{DynamicResource DefaultEntry}"
                        Text="{Binding PatientLastName}">
                        <Entry.Behaviors>
                            <xct:TextValidationBehavior
                                Flags="ValidateOnValueChanging"
                                IsValid="{Binding PatientLastNameValid}"
                                RegexPattern="^(?!\s*$).+" />
                        </Entry.Behaviors>
                        <Entry.Triggers>
                            <DataTrigger
                                Binding="{Binding PatientLastNameValid}"
                                TargetType="Entry"
                                Value="False">
                                <Setter Property="PlaceholderColor" Value="{StaticResource Error}" />
                            </DataTrigger>
                        </Entry.Triggers>
                    </Entry>
                    <Label
                        IsVisible="{Binding PatientLastNameValid, Converter={StaticResource InvertedBoolConverter}}"
                        Style="{DynamicResource ValidationLabel}"
                        Text="Last Name is required." />
                    <Entry
                        Keyboard="Email"
                        Placeholder="Email"
                        Style="{DynamicResource DefaultEntry}"
                        Text="{Binding PatientEmail}">
                        <Entry.Behaviors>
                            <xct:EmailValidationBehavior
                                DecorationFlags="Trim"
                                Flags="ValidateOnValueChanging"
                                IsValid="{Binding PatientEmailValid}" />
                        </Entry.Behaviors>
                        <Entry.Triggers>
                            <DataTrigger
                                Binding="{Binding PatientEmailValid}"
                                TargetType="Entry"
                                Value="False">
                                <Setter Property="PlaceholderColor" Value="{StaticResource Error}" />
                            </DataTrigger>
                        </Entry.Triggers>
                    </Entry>
                    <Label
                        IsVisible="{Binding PatientEmailValid, Converter={StaticResource InvertedBoolConverter}}"
                        Style="{DynamicResource ValidationLabel}"
                        Text="Email is required." />
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>
                        <StackLayout Grid.Column="0">
                            <Picker
                                Title="Year"
                                ItemsSource="{Binding DobYears}"
                                SelectedItem="{Binding SelectedDobYear}"
                                Style="{DynamicResource DefaultPicker}">
                                <Picker.Behaviors>
                                    <xct:TextValidationBehavior
                                        Flags="ValidateOnValueChanging"
                                        IsValid="{Binding SelectedDobYearValid}"
                                        RegexPattern="^(?!\s*$).+" />
                                </Picker.Behaviors>
                                <Picker.Triggers>
                                    <DataTrigger
                                        Binding="{Binding SelectedDobYearValid}"
                                        TargetType="Picker"
                                        Value="False">
                                        <Setter Property="TitleColor" Value="{StaticResource Error}" />
                                    </DataTrigger>
                                </Picker.Triggers>
                            </Picker>
                            <Label
                                IsVisible="{Binding SelectedDobYearValid, Converter={StaticResource InvertedBoolConverter}}"
                                Style="{DynamicResource ValidationLabel}"
                                Text="Year is required." />
                        </StackLayout>
                        <StackLayout Grid.Column="1">
                            <Picker
                                Title="Month"
                                ItemsSource="{Binding DobMonths}"
                                SelectedItem="{Binding SelectedDobMonth}"
                                Style="{DynamicResource DefaultPicker}">
                                <Picker.Behaviors>
                                    <xct:TextValidationBehavior
                                        Flags="ValidateOnValueChanging"
                                        IsValid="{Binding SelectedDobMonthValid}"
                                        RegexPattern="^(?!\s*$).+" />
                                </Picker.Behaviors>
                                <Picker.Triggers>
                                    <DataTrigger
                                        Binding="{Binding SelectedDobMonthValid}"
                                        TargetType="Picker"
                                        Value="False">
                                        <Setter Property="TitleColor" Value="{StaticResource Error}" />
                                    </DataTrigger>
                                </Picker.Triggers>
                            </Picker>
                            <Label
                                IsVisible="{Binding SelectedDobMonthValid, Converter={StaticResource InvertedBoolConverter}}"
                                Style="{DynamicResource ValidationLabel}"
                                Text="Year is required." />
                        </StackLayout>
                        <StackLayout Grid.Column="2">
                            <Picker
                                Title="Day"
                                ItemsSource="{Binding DobDays}"
                                SelectedItem="{Binding SelectedDobDay}"
                                Style="{DynamicResource DefaultPicker}">
                                <Picker.Behaviors>
                                    <xct:TextValidationBehavior
                                        Flags="ValidateOnValueChanging"
                                        IsValid="{Binding SelectedDobDayValid}"
                                        RegexPattern="^(?!\s*$).+" />
                                </Picker.Behaviors>
                                <Picker.Triggers>
                                    <DataTrigger
                                        Binding="{Binding SelectedDobDayValid}"
                                        TargetType="Picker"
                                        Value="False">
                                        <Setter Property="TitleColor" Value="{StaticResource Error}" />
                                    </DataTrigger>
                                </Picker.Triggers>
                            </Picker>
                            <Label
                                IsVisible="{Binding SelectedDobDayValid, Converter={StaticResource InvertedBoolConverter}}"
                                Style="{DynamicResource ValidationLabel}"
                                Text="Year is required." />
                        </StackLayout>
                    </Grid>
                    <Label Style="{DynamicResource HeadingLabel}" Text="Guardian Info" />
                    <Entry
                        Placeholder="First Name"
                        Style="{DynamicResource DefaultEntry}"
                        Text="{Binding GuardianFirstName}">
                        <Entry.Behaviors>
                            <xct:TextValidationBehavior
                                Flags="ValidateOnValueChanging"
                                IsValid="{Binding GuardianFirstNameValid}"
                                RegexPattern="^(?!\s*$).+" />
                        </Entry.Behaviors>
                        <Entry.Triggers>
                            <DataTrigger
                                Binding="{Binding GuardianFirstNameValid}"
                                TargetType="Entry"
                                Value="False">
                                <Setter Property="PlaceholderColor" Value="{StaticResource Error}" />
                            </DataTrigger>
                        </Entry.Triggers>
                    </Entry>
                    <Label
                        IsVisible="{Binding GuardianFirstNameValid, Converter={StaticResource InvertedBoolConverter}}"
                        Style="{DynamicResource ValidationLabel}"
                        Text="First Name is required." />
                    <Entry
                        Placeholder="Last Name"
                        Style="{DynamicResource DefaultEntry}"
                        Text="{Binding GuardianLastName}">
                        <Entry.Behaviors>
                            <xct:TextValidationBehavior
                                Flags="ValidateOnValueChanging"
                                IsValid="{Binding GuardianLastNameValid}"
                                RegexPattern="^(?!\s*$).+" />
                        </Entry.Behaviors>
                        <Entry.Triggers>
                            <DataTrigger
                                Binding="{Binding GuardianLastNameValid}"
                                TargetType="Entry"
                                Value="False">
                                <Setter Property="PlaceholderColor" Value="{StaticResource Error}" />
                            </DataTrigger>
                        </Entry.Triggers>
                    </Entry>
                    <Label
                        IsVisible="{Binding GuardianLastNameValid, Converter={StaticResource InvertedBoolConverter}}"
                        Style="{DynamicResource ValidationLabel}"
                        Text="Last Name is required." />
                    <Entry
                        Keyboard="Email"
                        Placeholder="Email"
                        Style="{DynamicResource DefaultEntry}"
                        Text="{Binding GuardianEmail}">
                        <Entry.Behaviors>
                            <xct:EmailValidationBehavior
                                DecorationFlags="Trim"
                                Flags="ValidateOnValueChanging"
                                IsValid="{Binding GuardianEmailValid}" />
                        </Entry.Behaviors>
                        <Entry.Triggers>
                            <DataTrigger
                                Binding="{Binding GuardianEmailValid}"
                                TargetType="Entry"
                                Value="False">
                                <Setter Property="PlaceholderColor" Value="{StaticResource Error}" />
                            </DataTrigger>
                        </Entry.Triggers>
                    </Entry>
                    <Label
                        IsVisible="{Binding GuardianEmailValid, Converter={StaticResource InvertedBoolConverter}}"
                        Style="{DynamicResource ValidationLabel}"
                        Text="Email is required." />
                    <Entry
                        Keyboard="Numeric"
                        Placeholder="Phone Number"
                        Style="{DynamicResource DefaultEntry}"
                        Text="{Binding PhoneNumber}">
                        <Entry.Behaviors>
                            <xct:CharactersValidationBehavior
                                Flags="ValidateOnValueChanging"
                                IsValid="{Binding PhoneNumberValid}"
                                MinimumCharacterCount="10" />
                        </Entry.Behaviors>
                        <Entry.Triggers>
                            <DataTrigger
                                Binding="{Binding PhoneNumberValid}"
                                TargetType="Entry"
                                Value="False">
                                <Setter Property="PlaceholderColor" Value="{StaticResource Error}" />
                            </DataTrigger>
                        </Entry.Triggers>
                    </Entry>
                    <Label
                        IsVisible="{Binding PhoneNumberValid, Converter={StaticResource InvertedBoolConverter}}"
                        Style="{DynamicResource ValidationLabel}"
                        Text="Phone Number is required." />
                    <StackLayout IsVisible="{Binding IsAddViewVisible}">
                        <Button
                            Padding="5"
                            Command="{Binding AddCommand}"
                            Style="{x:StaticResource DefaultButton}"
                            Text="Add"
                            TextColor="White" />
                    </StackLayout>
                    <StackLayout Padding="0,10">
                        <StackLayout IsVisible="{Binding IsEditViewVisible}" Orientation="Horizontal">
                            <Button
                                Padding="5"
                                BackgroundColor="{x:StaticResource Error}"
                                Command="{Binding DeleteCommand}"
                                HorizontalOptions="FillAndExpand"
                                Text="Delete" />
                            <Button
                                Padding="5"
                                Command="{Binding EditCommand}"
                                HorizontalOptions="FillAndExpand"
                                Style="{x:StaticResource DefaultButton}"
                                Text="Edit"
                                TextColor="White" />
                        </StackLayout>
                    </StackLayout>
                </StackLayout>
            </Grid>
        </ScrollView>
    </ContentPage.Content>
</ContentPage>
</code>```

答:
You can add a StackLayout out of the ScrollView.

Please refer to the following code:

```<code> <!--add a StackLayout out of the ScrollView-->

 <StackLayout>

    <ScrollView VerticalOptions="EndAndExpand">

       <!--other code-->

    </ScrollView>

 </StackLayout>
</code>```

Body:
I am learning a new way to show validation errors and I am having very weird issue with forms, when I click on Add button the controls that are pushed below the screen disappears or becomes transparent.

here is my form https://i.stack.imgur.com/LIrD6.jpg

when I click on add button this happens https://i.stack.imgur.com/PWZLZ.jpg (Note: this is an extended screenshot and my screen ends on phone number control. when I scroll remaining blank space is for Add button)

when I click/focus on any control the screen is fixes by itself https://i.stack.imgur.com/Exw4z.jpg

I am using shell app and have no idea whats going wrong here. Any help is appreciated.

here is my code

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="PROOF.Views.Patient.NewPatientPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
    xmlns:vm="clr-namespace:PROOF.ViewModels"
    xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
    Title="{Binding PageTitle}"
    ios:Page.UseSafeArea="true"
    x:DataType="vm:NewPatientViewModel"
    Shell.TabBarIsVisible="False"
    Visual="Material">
    <ContentPage.Resources>
        <ResourceDictionary>
            <xct:InvertedBoolConverter x:Key="InvertedBoolConverter" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <ScrollView>
            <Grid Margin="10">
                <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

                    <Entry
                        Placeholder="First Name"
                        Style="{DynamicResource DefaultEntry}"
                        Text="{Binding PatientFirstName}">
                        <Entry.Behaviors>
                            <xct:TextValidationBehavior
                                Flags="ValidateOnValueChanging"
                                IsValid="{Binding PatientFirstNameValid}"
                                RegexPattern="^(?!\s*$).+" />
                        </Entry.Behaviors>
                        <Entry.Triggers>
                            <DataTrigger
                                Binding="{Binding PatientFirstNameValid}"
                                TargetType="Entry"
                                Value="False">
                                <Setter Property="PlaceholderColor" Value="{StaticResource Error}" />
                            </DataTrigger>
                        </Entry.Triggers>
                    </Entry>

                    <Entry
                        Placeholder="Last Name"
                        Style="{DynamicResource DefaultEntry}"
                        Text="{Binding PatientLastName}">
                        <Entry.Behaviors>
                            <xct:TextValidationBehavior
                                Flags="ValidateOnValueChanging"
                                IsValid="{Binding PatientLastNameValid}"
                                RegexPattern="^(?!\s*$).+" />
                        </Entry.Behaviors>
                        <Entry.Triggers>
                            <DataTrigger
                                Binding="{Binding PatientLastNameValid}"
                                TargetType="Entry"
                                Value="False">
                                <Setter Property="PlaceholderColor" Value="{StaticResource Error}" />
                            </DataTrigger>
                        </Entry.Triggers>
                    </Entry>

                    <Entry
                        Keyboard="Email"
                        Placeholder="Email"
                        Style="{DynamicResource DefaultEntry}"
                        Text="{Binding PatientEmail}">
                        <Entry.Behaviors>
                            <xct:EmailValidationBehavior
                                DecorationFlags="Trim"
                                Flags="ValidateOnValueChanging"
                                IsValid="{Binding PatientEmailValid}" />
                        </Entry.Behaviors>
                        <Entry.Triggers>
                            <DataTrigger
                                Binding="{Binding PatientEmailValid}"
                                TargetType="Entry"
                                Value="False">
                                <Setter Property="PlaceholderColor" Value="{StaticResource Error}" />
                            </DataTrigger>
                        </Entry.Triggers>
                    </Entry>

                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>
                        <StackLayout Grid.Column="0">
                            <Picker
                                Title="Year"
                                ItemsSource="{Binding DobYears}"
                                SelectedItem="{Binding SelectedDobYear}"
                                Style="{DynamicResource DefaultPicker}">
                                <Picker.Behaviors>
                                    <xct:TextValidationBehavior
                                        Flags="ValidateOnValueChanging"
                                        IsValid="{Binding SelectedDobYearValid}"
                                        RegexPattern="^(?!\s*$).+" />
                                </Picker.Behaviors>
                                <Picker.Triggers>
                                    <DataTrigger
                                        Binding="{Binding SelectedDobYearValid}"
                                        TargetType="Picker"
                                        Value="False">
                                        <Setter Property="TitleColor" Value="{StaticResource Error}" />
                                    </DataTrigger>
                                </Picker.Triggers>
                            </Picker>

                        </StackLayout>
                        <StackLayout Grid.Column="1">
                            <Picker
                                Title="Month"
                                ItemsSource="{Binding DobMonths}"
                                SelectedItem="{Binding SelectedDobMonth}"
                                Style="{DynamicResource DefaultPicker}">
                                <Picker.Behaviors>
                                    <xct:TextValidationBehavior
                                        Flags="ValidateOnValueChanging"
                                        IsValid="{Binding SelectedDobMonthValid}"
                                        RegexPattern="^(?!\s*$).+" />
                                </Picker.Behaviors>
                                <Picker.Triggers>
                                    <DataTrigger
                                        Binding="{Binding SelectedDobMonthValid}"
                                        TargetType="Picker"
                                        Value="False">
                                        <Setter Property="TitleColor" Value="{StaticResource Error}" />
                                    </DataTrigger>
                                </Picker.Triggers>
                            </Picker>

                        </StackLayout>
                        <StackLayout Grid.Column="2">
                            <Picker
                                Title="Day"
                                ItemsSource="{Binding DobDays}"
                                SelectedItem="{Binding SelectedDobDay}"
                                Style="{DynamicResource DefaultPicker}">
                                <Picker.Behaviors>
                                    <xct:TextValidationBehavior
                                        Flags="ValidateOnValueChanging"
                                        IsValid="{Binding SelectedDobDayValid}"
                                        RegexPattern="^(?!\s*$).+" />
                                </Picker.Behaviors>
                                <Picker.Triggers>
                                    <DataTrigger
                                        Binding="{Binding SelectedDobDayValid}"
                                        TargetType="Picker"
                                        Value="False">
                                        <Setter Property="TitleColor" Value="{StaticResource Error}" />
                                    </DataTrigger>
                                </Picker.Triggers>
                            </Picker>

                        </StackLayout>
                    </Grid>

                    <Entry
                        Placeholder="First Name"
                        Style="{DynamicResource DefaultEntry}"
                        Text="{Binding GuardianFirstName}">
                        <Entry.Behaviors>
                            <xct:TextValidationBehavior
                                Flags="ValidateOnValueChanging"
                                IsValid="{Binding GuardianFirstNameValid}"
                                RegexPattern="^(?!\s*$).+" />
                        </Entry.Behaviors>
                        <Entry.Triggers>
                            <DataTrigger
                                Binding="{Binding GuardianFirstNameValid}"
                                TargetType="Entry"
                                Value="False">
                                <Setter Property="PlaceholderColor" Value="{StaticResource Error}" />
                            </DataTrigger>
                        </Entry.Triggers>
                    </Entry>

                    <Entry
                        Placeholder="Last Name"
                        Style="{DynamicResource DefaultEntry}"
                        Text="{Binding GuardianLastName}">
                        <Entry.Behaviors>
                            <xct:TextValidationBehavior
                                Flags="ValidateOnValueChanging"
                                IsValid="{Binding GuardianLastNameValid}"
                                RegexPattern="^(?!\s*$).+" />
                        </Entry.Behaviors>
                        <Entry.Triggers>
                            <DataTrigger
                                Binding="{Binding GuardianLastNameValid}"
                                TargetType="Entry"
                                Value="False">
                                <Setter Property="PlaceholderColor" Value="{StaticResource Error}" />
                            </DataTrigger>
                        </Entry.Triggers>
                    </Entry>

                    <Entry
                        Keyboard="Email"
                        Placeholder="Email"
                        Style="{DynamicResource DefaultEntry}"
                        Text="{Binding GuardianEmail}">
                        <Entry.Behaviors>
                            <xct:EmailValidationBehavior
                                DecorationFlags="Trim"
                                Flags="ValidateOnValueChanging"
                                IsValid="{Binding GuardianEmailValid}" />
                        </Entry.Behaviors>
                        <Entry.Triggers>
                            <DataTrigger
                                Binding="{Binding GuardianEmailValid}"
                                TargetType="Entry"
                                Value="False">
                                <Setter Property="PlaceholderColor" Value="{StaticResource Error}" />
                            </DataTrigger>
                        </Entry.Triggers>
                    </Entry>

                    <Entry
                        Keyboard="Numeric"
                        Placeholder="Phone Number"
                        Style="{DynamicResource DefaultEntry}"
                        Text="{Binding PhoneNumber}">
                        <Entry.Behaviors>
                            <xct:CharactersValidationBehavior
                                Flags="ValidateOnValueChanging"
                                IsValid="{Binding PhoneNumberValid}"
                                MinimumCharacterCount="10" />
                        </Entry.Behaviors>
                        <Entry.Triggers>
                            <DataTrigger
                                Binding="{Binding PhoneNumberValid}"
                                TargetType="Entry"
                                Value="False">
                                <Setter Property="PlaceholderColor" Value="{StaticResource Error}" />
                            </DataTrigger>
                        </Entry.Triggers>
                    </Entry>

                    <StackLayout IsVisible="{Binding IsAddViewVisible}">
                        <Button
                            Padding="5"
                            Command="{Binding AddCommand}"
                            Style="{x:StaticResource DefaultButton}"
                            Text="Add"
                            TextColor="White" />
                    </StackLayout>
                    <StackLayout Padding="0,10">
                        <StackLayout IsVisible="{Binding IsEditViewVisible}" Orientation="Horizontal">
                            <Button
                                Padding="5"
                                BackgroundColor="{x:StaticResource Error}"
                                Command="{Binding DeleteCommand}"
                                HorizontalOptions="FillAndExpand"
                                Text="Delete" />
                            <Button
                                Padding="5"
                                Command="{Binding EditCommand}"
                                HorizontalOptions="FillAndExpand"
                                Style="{x:StaticResource DefaultButton}"
                                Text="Edit"
                                TextColor="White" />
                        </StackLayout>
                    </StackLayout>
                </StackLayout>
            </Grid>
        </ScrollView>
    </ContentPage.Content>
</ContentPage>

Body:
You can add a StackLayout out of the ScrollView.

Please refer to the following code:

 <!--add a StackLayout out of the ScrollView-->

 <StackLayout>

    <ScrollView VerticalOptions="EndAndExpand">

       <!--other code-->

    </ScrollView>

 </StackLayout>


问:
Firebug - spotting error before page post
OK this is starting to drive me crazy!

I am trying to do some debugging with firebug, except I keep missing the error.

I have set break on all errors. Except that I think some jQuery code causes the page to post really quickly after the error-so I can't see it.

So my question is - how do I stop firefox/firebug from posting before I can read this error?

答:
Your firebug's console menu has a button called persist. This button keeps console messages even after your page has changed.

This is precisely the kind of scenario it was created for.


问:
How to use only one Connection to execute multiple commands and queries?
Here is Complete code link

I wanted to use only npgsql connection to execute multiple queries, instead of using multiple connections as shown below:

```<code>class TransactionAccess
{
    private const string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
        public static void GetExpense(DateTime startDate, DateTime endDate)
    {
        using (var connection = new NpgsqlConnection(connString))
        {
            var Expense = connection.Query<TransactionView>(@"SELECT SUM(t.amount) as Expense
                                                        FROM transaction AS t
                                                        INNER JOIN account AS a ON t.account_id = a.account_id
                                                        WHERE t.date BETWEEN @startDate AND @endDate AND a.type = 'expense'", new { startDate, endDate });
            Expense.Dump();
        }
    }

    public static void GetFilteredTransactionsList(DateTime startDate, DateTime endDate)
    {
        using (var connection = new NpgsqlConnection(connString))
        {
            var filteredTransactions = connection.Query<TransactionView>(@"SELECT a.account_name, a.account_id, a.type, DATE(t.date), t.transaction_id, t.amount, t.note
                                                                       FROM transaction AS t
                                                                       INNER JOIN account AS a ON t.account_id = a.account_id
                                                                       WHERE t.date BETWEEN @startDate AND @endDate
                                                                       ORDER BY t.date", new { startDate, endDate });
            filteredTransactions.Dump();
        }
    }
}
</code>```

Instead, I want to do something like this:

```<code>    class TransactionAccess
{
    private const string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
    using (var connection = new NpgsqlConnection(connString))
{
public static void GetExpense(DateTime startDate, DateTime endDate)
    {
            var Expense = connection.Query<TransactionView>(@"SELECT SUM(t.amount) as Expense
                                                        FROM transaction AS t
                                                        INNER JOIN account AS a ON t.account_id = a.account_id
                                                        WHERE t.date BETWEEN @startDate AND @endDate AND a.type = 'expense'", new { startDate, endDate });
            Expense.Dump();

    }

    public static void GetFilteredTransactionsList(DateTime startDate, DateTime endDate)
    {
            var filteredTransactions = connection.Query<TransactionView>(@"SELECT a.account_name, a.account_id, a.type, DATE(t.date), t.transaction_id, t.amount, t.note
                                                                       FROM transaction AS t
                                                                       INNER JOIN account AS a ON t.account_id = a.account_id
                                                                       WHERE t.date BETWEEN @startDate AND @endDate
                                                                       ORDER BY t.date", new { startDate, endDate });
            filteredTransactions.Dump();

    }
}
</code>```

like this, using a single connection to execute multiple queries and methods/ How can I do that?

If anyone can help a bit more please edit the code accordingly in here

答: You can only run a single statement on one database connection at the same time (unless you are using cursors, but then the same holds for the FETCH statements). So if you want several threads to issue database statements independently, you either have to serialize access to the database connection or you have to use multiple connections.

Body:
Here is Complete code link

I wanted to use only npgsql connection to execute multiple queries, instead of using multiple connections as shown below:

class TransactionAccess
{
    private const string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
        public static void GetExpense(DateTime startDate, DateTime endDate)
    {
        using (var connection = new NpgsqlConnection(connString))
        {
            var Expense = connection.Query<TransactionView>(@"SELECT SUM(t.amount) as Expense
                                                        FROM transaction AS t
                                                        INNER JOIN account AS a ON t.account_id = a.account_id
                                                        WHERE t.date BETWEEN @startDate AND @endDate AND a.type = 'expense'", new { startDate, endDate });
            Expense.Dump();
        }
    }

    public static void GetFilteredTransactionsList(DateTime startDate, DateTime endDate)
    {
        using (var connection = new NpgsqlConnection(connString))
        {
            var filteredTransactions = connection.Query<TransactionView>(@"SELECT a.account_name, a.account_id, a.type, DATE(t.date), t.transaction_id, t.amount, t.note
                                                                       FROM transaction AS t
                                                                       INNER JOIN account AS a ON t.account_id = a.account_id
                                                                       WHERE t.date BETWEEN @startDate AND @endDate
                                                                       ORDER BY t.date", new { startDate, endDate });
            filteredTransactions.Dump();
        }
    }
}

Instead, I want to do something like this:

    class TransactionAccess
{
    private const string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
    using (var connection = new NpgsqlConnection(connString))
{
public static void GetExpense(DateTime startDate, DateTime endDate)
    {
            var Expense = connection.Query<TransactionView>(@"SELECT SUM(t.amount) as Expense
                                                        FROM transaction AS t
                                                        INNER JOIN account AS a ON t.account_id = a.account_id
                                                        WHERE t.date BETWEEN @startDate AND @endDate AND a.type = 'expense'", new { startDate, endDate });
            Expense.Dump();

    }

    public static void GetFilteredTransactionsList(DateTime startDate, DateTime endDate)
    {
            var filteredTransactions = connection.Query<TransactionView>(@"SELECT a.account_name, a.account_id, a.type, DATE(t.date), t.transaction_id, t.amount, t.note
                                                                       FROM transaction AS t
                                                                       INNER JOIN account AS a ON t.account_id = a.account_id
                                                                       WHERE t.date BETWEEN @startDate AND @endDate
                                                                       ORDER BY t.date", new { startDate, endDate });
            filteredTransactions.Dump();

    }
}

like this, using a single connection to execute multiple queries and methods/ How can I do that?

If anyone can help a bit more please edit the code accordingly in here


问:
Mathematica Lists - Search Level Two and Return Level One?
I need to string match in the second level of a list but have true cases returned at the first level (there's information in the first level that I need to categorize the returns).

```<code> First /@ GatherBy[#, #[[3]] &] &@
  Cases[#, x_List /;
   MemberQ[x, s_String /;
    StringMatchQ[s, ("*PHYSICAL EXAMINATION*"),
     IgnoreCase -> True]], {2}] &@
  Cases[MemoizeTable["Diagnostic_table.txt"], {_,
   11111, __}]
</code>```

The GatherBy command at the top is just organizing all the entries by date so I don't get any duplicates. Then I ask for cases within the diagnostic table that have terms matching the string "PHYSICAL EXAMINATION".

I have to search only the second level of the lists. If I search just the first I don't return all the true cases. If I search the first and second, I get duplicates (some cases include the desired string at both the first and second levels, so the first and second levels of the list are both returned, separately).

I need to search for the string at the second level and then return ONLY the first level of the lists that contain that matched second level. I don't need to exclude the second level, I just don't want it returned separately like it is if I search levels one and two.

Any help would be much appreciated!

答:
If I understand your requirements, you may consider:</p>

```<code>dat = {{1111113, 21119, SQLDateTime[{2011, 1, 11, 11, 11, 0.`}],
    31111, "EB/JW", 1, 47000,
    "T-510 CHEEK", {"T-510 CHEEK", "No Examination, NOS"},
    "Text bla bla bla physical examination bla bla"}, {1111114, 21119,
     SQLDateTime[{2011, 2, 11, 11, 11, 0.`}], 31112, "EB/JW", 1,
    47000, "T-510 CHEEK", {"T-510 CHEEK",
     "P-023 PHYSICAL EXAMINATION, TECHNICIAN, NOS"},
    "Text bla bla bla"}, {1111115, 21000,
    SQLDateTime[{2011, 1, 11, 11, 11, 0.`}], 31111, "EB/JW", 1, 47000,
     "T-510 CHEEK", {"T-510 CHEEK",
     "P-023 physical examination, TECHNICIAN, NOS"},
    "Text bla bla bla physical examination bla bla"}};

p =
 Position[ dat,
   _String?(StringMatchQ[#, "*PHYSICAL EXAMINATION*", IgnoreCase -> True] &),
   {2, 3}
 ];

dat[[ Union[First /@ p] ]]
</code>```

Body:
I need to string match in the second level of a list but have true cases returned at the first level (there's information in the first level that I need to categorize the returns).

 First /@ GatherBy[#, #[[3]] &] &@
  Cases[#, x_List /;
   MemberQ[x, s_String /;
    StringMatchQ[s, ("*PHYSICAL EXAMINATION*"),
     IgnoreCase -> True]], {2}] &@
  Cases[MemoizeTable["Diagnostic_table.txt"], {_,
   11111, __}]

The GatherBy command at the top is just organizing all the entries by date so I don't get any duplicates. Then I ask for cases within the diagnostic table that have terms matching the string "PHYSICAL EXAMINATION".

I have to search only the second level of the lists. If I search just the first I don't return all the true cases. If I search the first and second, I get duplicates (some cases include the desired string at both the first and second levels, so the first and second levels of the list are both returned, separately).

I need to search for the string at the second level and then return ONLY the first level of the lists that contain that matched second level. I don't need to exclude the second level, I just don't want it returned separately like it is if I search levels one and two.

Any help would be much appreciated!

Body:
If I understand your requirements, you may consider:

dat = {{1111113, 21119, SQLDateTime[{2011, 1, 11, 11, 11, 0.`}],
    31111, "EB/JW", 1, 47000,
    "T-510 CHEEK", {"T-510 CHEEK", "No Examination, NOS"},
    "Text bla bla bla physical examination bla bla"}, {1111114, 21119,
     SQLDateTime[{2011, 2, 11, 11, 11, 0.`}], 31112, "EB/JW", 1,
    47000, "T-510 CHEEK", {"T-510 CHEEK",
     "P-023 PHYSICAL EXAMINATION, TECHNICIAN, NOS"},
    "Text bla bla bla"}, {1111115, 21000,
    SQLDateTime[{2011, 1, 11, 11, 11, 0.`}], 31111, "EB/JW", 1, 47000,
     "T-510 CHEEK", {"T-510 CHEEK",
     "P-023 physical examination, TECHNICIAN, NOS"},
    "Text bla bla bla physical examination bla bla"}};

p =
 Position[ dat,
   _String?(StringMatchQ[#, "*PHYSICAL EXAMINATION*", IgnoreCase -> True] &),
   {2, 3}
 ];

dat[[ Union[First /@ p] ]]


问:
Bootstrap Navbar Dropdown "Flashes" White When Clicking Off
When you click on the dropdown button on the navbar(button labeled Dropdown), and then click off(anywhere in the page), you can see the dropdown button flash white briefly.

I've seen this quite similar bug: Bootstrap navbar "flashing" when clicking outside of menu to close it. But it, unfortunately, doesn't work(actually copy and pasted the exact same code in css).

Here's a minimal reproducible version of the bug on plunk: https://embed.plnkr.co/plunk/nBIvKcLMkYbey8Oa

Code:

<!doctype html>

    <link rel="stylesheet" href="lib/style.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

                Dropdown

asdf

```
<pre class="lang-css prettyprint-override"><code>nav {
    background-color: #26445a !important;
    border-color: #26445a !important;
    margin: 0px !important;
}

.navbar a{
    color: #EEFBFB !important;
}
.navbar-header a{
    font-size: 1.45em !important;
}

.nav >li > a:hover, .nav > li > a:focus{
    background-color: #335369 !important;
}

.nav-item{
    background-color: #26445a !important;
    font-size: 1.23em !important;
}

#games-dropdown > .dropdown-menu a{
    background-color: #ffffff !important;
    color: #000000 !important;
    font-size: 1.2em !important;
}
#games-dropdown > .dropdown-menu a:hover{
    background-color: #d1d1d1 !important;
    color: #000000 !important;
}
</code>```

Thanks a lot!

答:
It's due to Bootstrap applying a background color on the focus and hover event.
So you can override this behavior</p>
```<code>.nav .open>a, .nav .open>a:focus, .nav .open>a:hover
{
  background-color: unset !important;
}
</code>```

Body:
When you click on the dropdown button on the navbar(button labeled Dropdown), and then click off(anywhere in the page), you can see the dropdown button flash white briefly.

I've seen this quite similar bug: Bootstrap navbar "flashing" when clicking outside of menu to close it. But it, unfortunately, doesn't work(actually copy and pasted the exact same code in css).

Here's a minimal reproducible version of the bug on plunk: https://embed.plnkr.co/plunk/nBIvKcLMkYbey8Oa

Code:

<!doctype html>

    <link rel="stylesheet" href="lib/style.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

                Dropdown

asdf

nav {
    background-color: #26445a !important;
    border-color: #26445a !important;
    margin: 0px !important;
}

.navbar a{
    color: #EEFBFB !important;
}
.navbar-header a{
    font-size: 1.45em !important;
}

.nav >li > a:hover, .nav > li > a:focus{
    background-color: #335369 !important;
}

.nav-item{
    background-color: #26445a !important;
    font-size: 1.23em !important;
}

#games-dropdown > .dropdown-menu a{
    background-color: #ffffff !important;
    color: #000000 !important;
    font-size: 1.2em !important;
}
#games-dropdown > .dropdown-menu a:hover{
    background-color: #d1d1d1 !important;
    color: #000000 !important;
}

Thanks a lot!

Body:
It's due to Bootstrap applying a background color on the focus and hover event.
So you can override this behavior

.nav .open>a, .nav .open>a:focus, .nav .open>a:hover
{
  background-color: unset !important;
}