问:
Configure custom OAuth2AccessToken on a client Spring Boot Application
The standard JSON format that an authorization server usually gives you, has a property named "expires_in", but now I'm working with an autorization server that gives me a property named "access_token_expires_in". Because of this, my OAuth2AccessToken always returns isExpired to false even when then access_token is expired, and that makes sens because it's trying to read the "expires_in" property that dose not exist. The getAdditionalInformation from OAuth2AccessToken returns my "access_token_expires_in" property value with 18000.

I was wondering if I can tell spring to use the "access_token_expires_in" property as an expiration value for my access_token?

My code:

```<code>@Configuration
class OAuth2RestConfiguration {
    @Bean
    protected OAuth2ProtectedResourceDetails resource() {

        final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
        resourceDetails.setAccessTokenUri("<tokenUri>");
        resourceDetails.setClientId("<clientId>");
        resourceDetails.setClientSecret("<clientSecret>");

        return resourceDetails;
    }

    @Bean
    public OAuth2RestTemplate restTemplate() throws Exception {
        final AccessTokenRequest atr = new DefaultAccessTokenRequest();
        final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resource(),
                new DefaultOAuth2ClientContext(atr));

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

Authorization server response sample:

```<code>{
    "refresh_token_expires_in": 0,
    "access_token": "<access_token>",
    "access_token_expires_in": 18000,
    "token_type": "bearer"
}
</code>```

EDIT 1:
As a workaround, I've extended the OAuth2RestTemplate class and override the getAccessToken method:

```<code>public class CustomOAuth2RestTemplate extends OAuth2RestTemplate {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomOAuth2RestTemplate.class);

    private OAuth2ClientContext context;
    private Long LAST_RESET = getCurrentTimeSeconds();
    private Long FORCE_EXPIRATION;

    public CustomOAuth2RestTemplate(OAuth2ProtectedResourceDetails resource) {
        super(resource);
        this.context = super.getOAuth2ClientContext();
        this.FORCE_EXPIRATION = 10800L;
    }

    public CustomOAuth2RestTemplate(OAuth2ProtectedResourceDetails resource,
            DefaultOAuth2ClientContext defaultOAuth2ClientContext, Long forceExpiration) {
        super(resource, defaultOAuth2ClientContext);
        this.context = defaultOAuth2ClientContext;
        this.FORCE_EXPIRATION = Objects.requireNonNull(forceExpiration, "Please set expiration!");
    }

    @Override
    public OAuth2AccessToken getAccessToken() throws UserRedirectRequiredException {

        OAuth2AccessToken accessToken = context.getAccessToken();

        final Long diff = getCurrentTimeSeconds() - LAST_RESET;

        /*
        Either use a hardcoded variable or use the value stored in
        context.getAccessToken().getAdditionalInformation().
        */
        if (diff > FORCE_EXPIRATION) {
            LOGGER.info("Access token has expired! Generating new one...");
            this.LAST_RESET = getCurrentTimeSeconds();
            context.setAccessToken(null);
            accessToken = acquireAccessToken(context);
        } else {
            accessToken = super.getAccessToken();
        }

        LOGGER.info("Access token: " + context.getAccessToken().getValue());

        return accessToken;
    }

    private Long getCurrentTimeSeconds() {
        return System.currentTimeMillis() / 1000L;
    }

}
</code>```

And now the bean:

```<code>@Bean
public OAuth2RestTemplate restTemplate() throws Exception {
    final AccessTokenRequest atr = new DefaultAccessTokenRequest();
    final OAuth2RestTemplate oAuth2RestTemplate = new CustomOAuth2RestTemplate(resource(),
            new DefaultOAuth2ClientContext(atr), 10800L); //example: 3h
    oAuth2RestTemplate.setRequestFactory(customRequestFactory());

    return oAuth2RestTemplate;
}
</code>```

EDIT 2:
After I analyzed the OAuth2RestTemplate class more thoroughly, code refactoring was required:

```<code>public class CustomOAuth2RestTemplate extends OAuth2RestTemplate {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomOAuth2RestTemplate.class);
    private Long LAST_RESET = getCurrentTimeSeconds();
    private Long FORCE_EXPIRATION;

    public CustomOAuth2RestTemplate(OAuth2ProtectedResourceDetails resource) {
        super(resource);
        this.FORCE_EXPIRATION = 10800L; //3h
    }

    public CustomOAuth2RestTemplate(OAuth2ProtectedResourceDetails resource,
            DefaultOAuth2ClientContext defaultOAuth2ClientContext, Long forceExpiration) {
        super(resource, defaultOAuth2ClientContext);
        this.FORCE_EXPIRATION = Objects.requireNonNull(forceExpiration, "Please set expiration!");
    }

    @Override
    public OAuth2AccessToken getAccessToken() throws UserRedirectRequiredException {
        final Long diff = getCurrentTimeSeconds() - LAST_RESET;

        /*
        Either use a hardcoded variable or use the value stored in
        context.getAccessToken().getAdditionalInformation().
        */
        if (diff > FORCE_EXPIRATION) {
            LOGGER.info("Access token has expired! Generating new one...");
            this.LAST_RESET = getCurrentTimeSeconds();
            final OAuth2ClientContext oAuth2ClientContext = getOAuth2ClientContext();
            oAuth2ClientContext.setAccessToken(null);
            return acquireAccessToken(oAuth2ClientContext);
        }
        return super.getAccessToken();
    }

    private Long getCurrentTimeSeconds() {
        return System.currentTimeMillis() / 1000L;
    }

}
</code>```

答:
I'll post this as an answer since it works just fine. The only thing that was added was synchronized for concurrency, so that multiple access tokens should never be requested.

Final code:

```<code>public class CustomOAuth2RestTemplate extends OAuth2RestTemplate {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomOAuth2RestTemplate.class);
    private Long LAST_RESET = getCurrentTimeSeconds();
    private Long FORCE_EXPIRATION;

    public CustomOAuth2RestTemplate(OAuth2ProtectedResourceDetails resource) {
        super(resource);
        this.FORCE_EXPIRATION = 10800L; // 3h
    }

    public CustomOAuth2RestTemplate(OAuth2ProtectedResourceDetails resource,
            DefaultOAuth2ClientContext defaultOAuth2ClientContext, Long forceExpiration) {
        super(resource, defaultOAuth2ClientContext);
        this.FORCE_EXPIRATION = Objects.requireNonNull(forceExpiration, "Please set expiration!");
    }

    @Override
    public synchronized OAuth2AccessToken getAccessToken() throws UserRedirectRequiredException {
        final Long diff = getCurrentTimeSeconds() - LAST_RESET;

        /*
         * Either use a hardcoded variable or use the value stored in
         * context.getAccessToken().getAdditionalInformation().
         */
        if (diff > FORCE_EXPIRATION) {
            LOGGER.info("Access token has expired! Generating new one...");
            this.LAST_RESET = getCurrentTimeSeconds();
            final OAuth2ClientContext oAuth2ClientContext = getOAuth2ClientContext();
            oAuth2ClientContext.setAccessToken(null);
            return acquireAccessToken(oAuth2ClientContext);
        }
        return super.getAccessToken();
    }

    private Long getCurrentTimeSeconds() {
        return System.currentTimeMillis() / 1000L;
    }

}
</code>```

Body:
The standard JSON format that an authorization server usually gives you, has a property named "expires_in", but now I'm working with an autorization server that gives me a property named "access_token_expires_in". Because of this, my OAuth2AccessToken always returns isExpired to false even when then access_token is expired, and that makes sens because it's trying to read the "expires_in" property that dose not exist. The getAdditionalInformation from OAuth2AccessToken returns my "access_token_expires_in" property value with 18000.

I was wondering if I can tell spring to use the "access_token_expires_in" property as an expiration value for my access_token?

My code:

@Configuration
class OAuth2RestConfiguration {
    @Bean
    protected OAuth2ProtectedResourceDetails resource() {

        final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
        resourceDetails.setAccessTokenUri("<tokenUri>");
        resourceDetails.setClientId("<clientId>");
        resourceDetails.setClientSecret("<clientSecret>");

        return resourceDetails;
    }

    @Bean
    public OAuth2RestTemplate restTemplate() throws Exception {
        final AccessTokenRequest atr = new DefaultAccessTokenRequest();
        final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resource(),
                new DefaultOAuth2ClientContext(atr));

        return oAuth2RestTemplate;
    }
}

Authorization server response sample:

{
    "refresh_token_expires_in": 0,
    "access_token": "<access_token>",
    "access_token_expires_in": 18000,
    "token_type": "bearer"
}

EDIT 1:
As a workaround, I've extended the OAuth2RestTemplate class and override the getAccessToken method:

public class CustomOAuth2RestTemplate extends OAuth2RestTemplate {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomOAuth2RestTemplate.class);

    private OAuth2ClientContext context;
    private Long LAST_RESET = getCurrentTimeSeconds();
    private Long FORCE_EXPIRATION;

    public CustomOAuth2RestTemplate(OAuth2ProtectedResourceDetails resource) {
        super(resource);
        this.context = super.getOAuth2ClientContext();
        this.FORCE_EXPIRATION = 10800L;
    }

    public CustomOAuth2RestTemplate(OAuth2ProtectedResourceDetails resource,
            DefaultOAuth2ClientContext defaultOAuth2ClientContext, Long forceExpiration) {
        super(resource, defaultOAuth2ClientContext);
        this.context = defaultOAuth2ClientContext;
        this.FORCE_EXPIRATION = Objects.requireNonNull(forceExpiration, "Please set expiration!");
    }

    @Override
    public OAuth2AccessToken getAccessToken() throws UserRedirectRequiredException {

        OAuth2AccessToken accessToken = context.getAccessToken();

        final Long diff = getCurrentTimeSeconds() - LAST_RESET;

        /*
        Either use a hardcoded variable or use the value stored in
        context.getAccessToken().getAdditionalInformation().
        */
        if (diff > FORCE_EXPIRATION) {
            LOGGER.info("Access token has expired! Generating new one...");
            this.LAST_RESET = getCurrentTimeSeconds();
            context.setAccessToken(null);
            accessToken = acquireAccessToken(context);
        } else {
            accessToken = super.getAccessToken();
        }

        LOGGER.info("Access token: " + context.getAccessToken().getValue());

        return accessToken;
    }

    private Long getCurrentTimeSeconds() {
        return System.currentTimeMillis() / 1000L;
    }

}

And now the bean:

@Bean
public OAuth2RestTemplate restTemplate() throws Exception {
    final AccessTokenRequest atr = new DefaultAccessTokenRequest();
    final OAuth2RestTemplate oAuth2RestTemplate = new CustomOAuth2RestTemplate(resource(),
            new DefaultOAuth2ClientContext(atr), 10800L); //example: 3h
    oAuth2RestTemplate.setRequestFactory(customRequestFactory());

    return oAuth2RestTemplate;
}

EDIT 2:
After I analyzed the OAuth2RestTemplate class more thoroughly, code refactoring was required:

public class CustomOAuth2RestTemplate extends OAuth2RestTemplate {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomOAuth2RestTemplate.class);
    private Long LAST_RESET = getCurrentTimeSeconds();
    private Long FORCE_EXPIRATION;

    public CustomOAuth2RestTemplate(OAuth2ProtectedResourceDetails resource) {
        super(resource);
        this.FORCE_EXPIRATION = 10800L; //3h
    }

    public CustomOAuth2RestTemplate(OAuth2ProtectedResourceDetails resource,
            DefaultOAuth2ClientContext defaultOAuth2ClientContext, Long forceExpiration) {
        super(resource, defaultOAuth2ClientContext);
        this.FORCE_EXPIRATION = Objects.requireNonNull(forceExpiration, "Please set expiration!");
    }

    @Override
    public OAuth2AccessToken getAccessToken() throws UserRedirectRequiredException {
        final Long diff = getCurrentTimeSeconds() - LAST_RESET;

        /*
        Either use a hardcoded variable or use the value stored in
        context.getAccessToken().getAdditionalInformation().
        */
        if (diff > FORCE_EXPIRATION) {
            LOGGER.info("Access token has expired! Generating new one...");
            this.LAST_RESET = getCurrentTimeSeconds();
            final OAuth2ClientContext oAuth2ClientContext = getOAuth2ClientContext();
            oAuth2ClientContext.setAccessToken(null);
            return acquireAccessToken(oAuth2ClientContext);
        }
        return super.getAccessToken();
    }

    private Long getCurrentTimeSeconds() {
        return System.currentTimeMillis() / 1000L;
    }

}

Body:
I'll post this as an answer since it works just fine. The only thing that was added was synchronized for concurrency, so that multiple access tokens should never be requested.

Final code:

public class CustomOAuth2RestTemplate extends OAuth2RestTemplate {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomOAuth2RestTemplate.class);
    private Long LAST_RESET = getCurrentTimeSeconds();
    private Long FORCE_EXPIRATION;

    public CustomOAuth2RestTemplate(OAuth2ProtectedResourceDetails resource) {
        super(resource);
        this.FORCE_EXPIRATION = 10800L; // 3h
    }

    public CustomOAuth2RestTemplate(OAuth2ProtectedResourceDetails resource,
            DefaultOAuth2ClientContext defaultOAuth2ClientContext, Long forceExpiration) {
        super(resource, defaultOAuth2ClientContext);
        this.FORCE_EXPIRATION = Objects.requireNonNull(forceExpiration, "Please set expiration!");
    }

    @Override
    public synchronized OAuth2AccessToken getAccessToken() throws UserRedirectRequiredException {
        final Long diff = getCurrentTimeSeconds() - LAST_RESET;

        /*
         * Either use a hardcoded variable or use the value stored in
         * context.getAccessToken().getAdditionalInformation().
         */
        if (diff > FORCE_EXPIRATION) {
            LOGGER.info("Access token has expired! Generating new one...");
            this.LAST_RESET = getCurrentTimeSeconds();
            final OAuth2ClientContext oAuth2ClientContext = getOAuth2ClientContext();
            oAuth2ClientContext.setAccessToken(null);
            return acquireAccessToken(oAuth2ClientContext);
        }
        return super.getAccessToken();
    }

    private Long getCurrentTimeSeconds() {
        return System.currentTimeMillis() / 1000L;
    }

}


来源: stackexchange

问:
Detect if default back button in navigation bar is pressed
I know that there are answers to this like make custom button and then make action but I don't want to change the default back button with arrow and I also tried like this:

```<code>override func viewWillDisappear(_ animated : Bool) {
    super.viewWillDisappear(animated)
    if self.isMovingFromParentViewController {
     print("something")
    }
}
</code>```

Here the problem is that this function gets called even if I press on save button that I also have in that view controller. I need to detect only when the back button is pressed

答:
In your viewWillDisappear method, add the isMovingFromParentViewController property:

```<code>if self.isMovingFromParentViewController {
    //do stuff, the back button was pressed
}
</code>```

EDIT: As had pointed out, if you are merely dismissing the view controller when the save button is pressed, you need a Bool value to check if the save button was pressed or the default back button.

At the top of your class, define a Boolean value:

```<code>var saveButtonPressed = false
</code>```

I'm assuming that you have an @IBAction method linked to your save button. If you don't, then I suggest you add that connection.

In that method, set saveButtonPressed equal to true.

Then, in your viewWillDisappear method, add this to the if condition:

```<code>if (self.isMovingFromParentViewController && !saveButtonPressed) {
    //do stuff, the back button was pressed
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know that there are answers to this like make custom button and then make action but I don't want to change the default back button with arrow and I also tried like this:

override func viewWillDisappear(_ animated : Bool) {
    super.viewWillDisappear(animated)
    if self.isMovingFromParentViewController {
     print("something")
    }
}

Here the problem is that this function gets called even if I press on save button that I also have in that view controller. I need to detect only when the back button is pressed

Body:
In your viewWillDisappear method, add the isMovingFromParentViewController property:

if self.isMovingFromParentViewController {
    //do stuff, the back button was pressed
}

EDIT: As had pointed out, if you are merely dismissing the view controller when the save button is pressed, you need a Bool value to check if the save button was pressed or the default back button.

At the top of your class, define a Boolean value:

var saveButtonPressed = false

I'm assuming that you have an @IBAction method linked to your save button. If you don't, then I suggest you add that connection.

In that method, set saveButtonPressed equal to true.

Then, in your viewWillDisappear method, add this to the if condition:

if (self.isMovingFromParentViewController && !saveButtonPressed) {
    //do stuff, the back button was pressed
}


问:
Pandas: display groupby aggregate statistic with data
Data Snippet

I am trying to add a new column to my data frame that displays the average purchase amount per user. The data frame is called trainDf and the below line of code produces the average by user. I'm trying to learn how to add it as a column to display similar  to the above image.

AveragePurchaseAmountUser = trainDf.groupby(by='User_ID')['Purchase_Amount'].mean()
```

Thank you in advance!

答:
This will return the DataFrame with the new column

```<code>def avg(df):
    df['Average_Purchase_Amount'] = df['Purchase_Amount'].mean()
    return df

newDf = trainDf.groupby(by='User_ID').apply(avg)
</code>```

And if you want the column as a Series you can apply this function:

```<code>def avgSeries(df):
    return pd.Series(data = df['Purchase_Amount'].mean(), index = df.index)
</code>```

Then add the column to you DataFrame later

Body:
Data Snippet

I am trying to add a new column to my data frame that displays the average purchase amount per user. The data frame is called trainDf and the below line of code produces the average by user. I'm trying to learn how to add it as a column to display similar  to the above image.

AveragePurchaseAmountUser = trainDf.groupby(by='User_ID')['Purchase_Amount'].mean()

Thank you in advance!

Body:
This will return the DataFrame with the new column

def avg(df):
    df['Average_Purchase_Amount'] = df['Purchase_Amount'].mean()
    return df

newDf = trainDf.groupby(by='User_ID').apply(avg)

And if you want the column as a Series you can apply this function:

def avgSeries(df):
    return pd.Series(data = df['Purchase_Amount'].mean(), index = df.index)

Then add the column to you DataFrame later


问:
Coq, meta programming, generate fresh variable to create a Prop
I have my own type Mytype, that defines a kind of formula. I'd like to translate this formula into a Coq proposition Prop. To do so, I feel like I would need some kind of Meta Programming, that would let me write forall <variable 15>, <variable 15> /\ <variable (15+1)>.

Here is a MWE that I'd like to translate:

```<code>Inductive Myprop : Type :=
| MTrue
| MFalse
| MVar (_ : nat)
| MAnd (_ : Myprop) (_ : Myprop)
| MOr (_ : Myprop) (_ : Myprop)
| MForall (_ : nat) (_ : Myprop)
.

(* Exemple *)
Eval simpl in MForall 42 (MForall 42 (MOr (MVar 42) (MVar 50))).

Fixpoint translate (myprop : Myprop) : Prop :=
  match myprop with
  | MTrue => True
  | MFalse => False
  | MVar n => (* ???? Variable n ??? *)
  | MAnd a b => (translate a) /\ (translate b)
  | MOr  a b => (translate a) \/ (translate b)
  | MForall n a => forall (* ???? Variable n ??? *), (translate a)
  end.
</code>```

Thank you!

答:
As gallais suggests, you can augment your translate function with a context lookup function:

```<code>Fixpoint translate (lookup : nat -> Prop) (myprop : Myprop) : Prop :=
  match myprop with
  | MTrue => True
  | MFalse => False
  | MVar n => lookup n
  | MAnd a b => (translate lookup a) /\ (translate lookup b)
  | MOr  a b => (translate lookup a) \/ (translate lookup b)
  | MForall n a => forall p : Prop,
      translate (fun n' => if Nat.eqb n' n then p else lookup n') a
  end.

Eval compute in translate _ (MForall 42 (MForall 42 (MOr (MVar 42) (MVar 50)))).
(* Prop -> forall p0 : Prop, p0 \/ ?lookup 50 *)
</code>```

Another approach is to use HOAS (Higher-Order Abstract Syntax), and let your bindings be Gallina bindings:

```<code>Inductive Myprop : Type :=
| MTrue
| MFalse
| MVar (_ : Prop)
| MAnd (_ : Myprop) (_ : Myprop)
| MOr (_ : Myprop) (_ : Myprop)
| MForall (_ : Prop -> Myprop)
.

(* Exemple *)
Eval simpl in MForall (fun p42 => MForall (fun p42 => MOr (MVar p42) (MVar ?[p50]))).
(* ?[p50] denotes a fresh evar named "p50" *)

Fixpoint translate (myprop : Myprop) : Prop :=
  match myprop with
  | MTrue => True
  | MFalse => False
  | MVar P => P
  | MAnd a b => (translate a) /\ (translate b)
  | MOr  a b => (translate a) \/ (translate b)
  | MForall P => forall p : Prop, translate (P p)
  end.

Eval simpl in translate (MForall (fun p42 => MForall (fun p42 => MOr (MVar p42) (MVar ?[p50])))).
(* forall p p0 : Prop, p0 \/ ?p50@{p43:=p; p42:=p0} *)
</code>```

Body:
I have my own type Mytype, that defines a kind of formula. I'd like to translate this formula into a Coq proposition Prop. To do so, I feel like I would need some kind of Meta Programming, that would let me write forall <variable 15>, <variable 15> /\ <variable (15+1)>.

Here is a MWE that I'd like to translate:

Inductive Myprop : Type :=
| MTrue
| MFalse
| MVar (_ : nat)
| MAnd (_ : Myprop) (_ : Myprop)
| MOr (_ : Myprop) (_ : Myprop)
| MForall (_ : nat) (_ : Myprop)
.

(* Exemple *)
Eval simpl in MForall 42 (MForall 42 (MOr (MVar 42) (MVar 50))).

Fixpoint translate (myprop : Myprop) : Prop :=
  match myprop with
  | MTrue => True
  | MFalse => False
  | MVar n => (* ???? Variable n ??? *)
  | MAnd a b => (translate a) /\ (translate b)
  | MOr  a b => (translate a) \/ (translate b)
  | MForall n a => forall (* ???? Variable n ??? *), (translate a)
  end.

Thank you!

Body:
As gallais suggests, you can augment your translate function with a context lookup function:

Fixpoint translate (lookup : nat -> Prop) (myprop : Myprop) : Prop :=
  match myprop with
  | MTrue => True
  | MFalse => False
  | MVar n => lookup n
  | MAnd a b => (translate lookup a) /\ (translate lookup b)
  | MOr  a b => (translate lookup a) \/ (translate lookup b)
  | MForall n a => forall p : Prop,
      translate (fun n' => if Nat.eqb n' n then p else lookup n') a
  end.

Eval compute in translate _ (MForall 42 (MForall 42 (MOr (MVar 42) (MVar 50)))).
(* Prop -> forall p0 : Prop, p0 \/ ?lookup 50 *)

Another approach is to use HOAS (Higher-Order Abstract Syntax), and let your bindings be Gallina bindings:

Inductive Myprop : Type :=
| MTrue
| MFalse
| MVar (_ : Prop)
| MAnd (_ : Myprop) (_ : Myprop)
| MOr (_ : Myprop) (_ : Myprop)
| MForall (_ : Prop -> Myprop)
.

(* Exemple *)
Eval simpl in MForall (fun p42 => MForall (fun p42 => MOr (MVar p42) (MVar ?[p50]))).
(* ?[p50] denotes a fresh evar named "p50" *)

Fixpoint translate (myprop : Myprop) : Prop :=
  match myprop with
  | MTrue => True
  | MFalse => False
  | MVar P => P
  | MAnd a b => (translate a) /\ (translate b)
  | MOr  a b => (translate a) \/ (translate b)
  | MForall P => forall p : Prop, translate (P p)
  end.

Eval simpl in translate (MForall (fun p42 => MForall (fun p42 => MOr (MVar p42) (MVar ?[p50])))).
(* forall p p0 : Prop, p0 \/ ?p50@{p43:=p; p42:=p0} *)


问:
Asynchronous DataClass running post Exit Sub
I have a custom class in VBA that pulls historical data from Bloomberg. The class, and the Bloomberg objects it uses, are asynchronous and based on the RTD platform.

The issue I'm having is that I run Subs that call this custom class, but the event handling code in the custom class only runs once my Sub is finished.

```<code>Dim bbHist As New HistDataControl

Sub PullDataAndDoStuff()
     bbHist.MakeHistRequest StockTicker, "MOV_AVG_50D", startDate, Date
     Call DoStuffWithTheData
End Sub

Private Sub DoStuffWithTheData()
 ..... 'None of this works, because MakeHistRequest / bbHist class hasn't run
End Sub
</code>```

Is there a way to force Excel to wait until the bbHist has run?

答: If it has a property to check to see if it's done, then you can just put a DoEvents in a Do Until loop, checking that property for its completion.

Body:
I have a custom class in VBA that pulls historical data from Bloomberg. The class, and the Bloomberg objects it uses, are asynchronous and based on the RTD platform.

The issue I'm having is that I run Subs that call this custom class, but the event handling code in the custom class only runs once my Sub is finished.

Dim bbHist As New HistDataControl

Sub PullDataAndDoStuff()
     bbHist.MakeHistRequest StockTicker, "MOV_AVG_50D", startDate, Date
     Call DoStuffWithTheData
End Sub

Private Sub DoStuffWithTheData()
 ..... 'None of this works, because MakeHistRequest / bbHist class hasn't run
End Sub

Is there a way to force Excel to wait until the bbHist has run?


问:
ERROR: Unknown Punctuation String @ 7
I'm trying to move my old phpBB forum database to my new server. So when I donwloaded the .sql file I tried uploading it to a new database via a phpMyAdmin panel. Here is the error I recieved:

```<code>```Error

There seems to be an error in your SQL query. The MySQL server error output below, if there is any, may also help you in diagnosing the problem

ERROR: Unknown Punctuation String @ 7
STR: />
SQL:

Warning:  Cannot modify header information - headers already sent by (output started at webiste/includes/acp/acp_database.php:593) in website/includes/functions.php on line 3582

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>General Error</title>

答:
On line 7 you have

* { margin: 0;

The ; symbol delineates the end of a SQL query. Obviously, in this case if that's the end of the query the server does not know what to do, hence the error.

You need to specify a new delimiter (I often use |) so that phpMyAdmin knows when the script is complete.

ContentLicense: CC BY-SA 2.5

Title: ERROR: Unknown Punctuation String @ 7

Body:
I'm trying to move my old phpBB forum database to my new server. So when I donwloaded the .sql file I tried uploading it to a new database via a phpMyAdmin panel. Here is the error I recieved:

Error

There seems to be an error in your SQL query. The MySQL server error output below, if there is any, may also help you in diagnosing the problem

ERROR: Unknown Punctuation String @ 7
STR: />
SQL:

Warning:  Cannot modify header information - headers already sent by (output started at webiste/includes/acp/acp_database.php:593) in website/includes/functions.php on line 3582

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>General Error</title>


问:
How can I baseline-align two blocks with different font-height?
I've got a table with 2 cells. One cell contains a number, the other contains text in a larger font. I want to align the baselines of the two texts. I've tried lots of combinations of display-align, vertical-align, alignment-baseline etc. Nothing seems to work: the blocks are always aligned as if alignment-baseline="center".

```<code><fo:table>
    <fo:table-column column-width="20mm" column-number="1"/>
    <fo:table-column column-width="100mm" column-number="2"/>
    <fo:table-body>
       <fo:table-row>
           <fo:table-cell column-number="1">
               <fo:block font-size="9pt" line-height="22pt">1.</fo:block>
           </fo:table-cell>
           <fo:table-cell column-number="2">
               <fo:block font-size="20pt"line-height="22pt">Title</fo:block>
           </fo:table-cell>
       </fo:table-row>
    <fo:table-body>
</fo:table>
</code>```

I can fake the correct alignment by putting a padding on the block in column 1, but I'd rather use a non-hack solution.

答:
Use relative-align="baseline".  See https://www.w3.org/TR/xsl11/#relative-align

relative-align exists because of this problem.  It applies only to fo:table-cell and fo:list-item since they are (or were expected to be) the only places where it's needed.

Body:
I've got a table with 2 cells. One cell contains a number, the other contains text in a larger font. I want to align the baselines of the two texts. I've tried lots of combinations of display-align, vertical-align, alignment-baseline etc. Nothing seems to work: the blocks are always aligned as if alignment-baseline="center".

<fo:table>
    <fo:table-column column-width="20mm" column-number="1"/>
    <fo:table-column column-width="100mm" column-number="2"/>
    <fo:table-body>
       <fo:table-row>
           <fo:table-cell column-number="1">
               <fo:block font-size="9pt" line-height="22pt">1.</fo:block>
           </fo:table-cell>
           <fo:table-cell column-number="2">
               <fo:block font-size="20pt"line-height="22pt">Title</fo:block>
           </fo:table-cell>
       </fo:table-row>
    <fo:table-body>
</fo:table>

I can fake the correct alignment by putting a padding on the block in column 1, but I'd rather use a non-hack solution.


问:
Weblogic 12c REP-501: The specified database cannot be connected
I have a problem when executing it outside the form builder,

from the call

http: // localhost: 9001 / forms / frmservlet? Config = webutil_webstart

the report works well from the formbuilder and runs smoothly

but when executing it from the direct url, I do not run the report,

I do the validation on the server with showjobs the error that I have is

The report ended in error:
REP-501: The specified database can not be connected ..

Maybe you can give me a hand where I would be missing some configuration.

thanks a lot.

答: If you're on Linux. The issues is due to special character in your password that could not be interpreted. If you change the password in the database without special character or replace the spacial character with an underscore (_). It should work.  </p>


问:
Difference in XSD Validation Errors between .net and other technologies
I have the following schema that I use to validate XMLs in my c# application.
The following code is the example of what I am doing. But what I found out is there is a difference in validations as opposed to validations in other technologies. I am not sure if its related to regex.

```<code><xsd:schema targetNamespace="http://tempuri.org/XMLSchema.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/XMLSchema.xsd"
    xmlns:mstns="http://tempuri.org/XMLSchema.xsd"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
>
  <xsd:simpleType name="DateCCYYType">
    <xsd:annotation>
      <xsd:documentation>A type that is used for any century/year combination field.</xsd:documentation>
    </xsd:annotation>
    <xsd:restriction base="xsd:string">
      <xsd:maxLength value="4"/>
      <xsd:pattern value="(^$|[1-2][0-9][0-9][0-9])"/>
    </xsd:restriction>
  </xsd:simpleType>
  <xsd:complexType name="PersonalDetails">
    <xsd:sequence>
      <xsd:element name="yearJoined" type="mstns:DateCCYYType"></xsd:element>
      <xsd:element name="yearReleased" type="mstns:DateCCYYType"></xsd:element>
    </xsd:sequence>
  </xsd:complexType>
  <xsd:element name="PersonalDetails" type="mstns:PersonalDetails"></xsd:element>
</xsd:schema>
</code>```

The class file is as follows

```<code>public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            /*textBox1 Contains the xml text
            <urn:PersonalDetails xmlns:urn="http://tempuri.org/XMLSchema.xsd">
                <urn:yearJoined></urn:yearJoined>
                <urn:yearReleased>5000</urn:yearReleased>
            </urn:PersonalDetails>
             */
            StringReader reader = new StringReader(textBox1.Text);
            XmlTextReader xmlReader = new XmlTextReader(@"C:\visual studio 2015\Projects\WindowsFormsApplication1\SampleSchema.xsd");
            Exception xsdException = new Exception();
            try
            {
                bool isValid = IsXmlValidForSchema(reader, xmlReader, ref xsdException);
                if (isValid)
                {
                    MessageBox.Show("Success");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        public static void ValidateXml(
            StringReader srXML,
            XmlTextReader xtrSchema)
        {

            XmlSchemaSet xssValidate = null;
            try
            {
                xssValidate = new XmlSchemaSet();
                xssValidate.Add(null, xtrSchema);
                xssValidate.Compile();
                XPathDocument xpdValidate = new XPathDocument(srXML);
                XPathNavigator editor = xpdValidate.CreateNavigator();
                if (!editor.CheckValidity(xssValidate, ValidateEventHandler))
                {
                    throw new System.Xml.Schema.XmlSchemaValidationException();
                }
            }
            finally
            {
                if (xssValidate != null) xssValidate = null;
            }
        }

        public static bool IsXmlValidForSchema(
            StringReader xmlReader,
            XmlTextReader schemaReader, ref Exception xsdException)
        {
            bool result = true;
            try
            {
                ValidateXml(xmlReader, schemaReader);
            }
            catch (XmlSchemaValidationException ex)
            {

                xsdException = ex;
                result = false;
            }
            return result;
        }

        private static void ValidateEventHandler(object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
            {
                XmlSchemaException schemaException = new XmlSchemaException(e.Message, e.Exception);
                throw schemaException;
            }
        }

    }
</code>```

If you use the xml in the commented block, it validates fine and does not throw error for the emptiness of yearJoined. However if I validate this using other validators like XMLSPY or any online validators, these are shown as errors.
I can fix this in .Net by using minLength. But why is this conflict? Is there a way to correct it.

答:
Here is the code I used to test :</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.XPath;
using System.IO;

namespace ConsoleApplication16
{
    class Program
    {
        const string SCHEMA_FILENAME = @"c:\temp\test1.xml";
        static void Main(string[] args)
        {
            //textBox1 Contains the xml text
            string xml = "<urn:PersonalDetails xmlns:urn=\"http://tempuri.org/XMLSchema.xsd\">" +
                     "<urn:yearJoined></urn:yearJoined>" +
                     "<urn:yearReleased>2017</urn:yearReleased>" +
                 "</urn:PersonalDetails>";

            StringReader reader = new StringReader(xml);
            XmlTextReader xmlReader = new XmlTextReader(SCHEMA_FILENAME);
            Exception xsdException = new Exception();
            try
            {
                bool isValid = IsXmlValidForSchema(reader, xmlReader, ref xsdException);
                if (isValid)
                {
                    Console.WriteLine("Success");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

        }
        public static void ValidateXml(
    StringReader srXML,
    XmlTextReader xtrSchema)
        {

            XmlSchemaSet xssValidate = null;
            try
            {
                xssValidate = new XmlSchemaSet();
                xssValidate.Add(null, xtrSchema);
                xssValidate.Compile();
                XPathDocument xpdValidate = new XPathDocument(srXML);
                XPathNavigator editor = xpdValidate.CreateNavigator();
                if (!editor.CheckValidity(xssValidate, ValidateEventHandler))
                {
                    throw new System.Xml.Schema.XmlSchemaValidationException();
                }
            }
            finally
            {
                if (xssValidate != null) xssValidate = null;
            }
        }

        public static bool IsXmlValidForSchema(
            StringReader xmlReader,
            XmlTextReader schemaReader, ref Exception xsdException)
        {
            bool result = true;
            try
            {
                ValidateXml(xmlReader, schemaReader);
            }
            catch (XmlSchemaValidationException ex)
            {

                xsdException = ex;
                result = false;
            }
            return result;
        }

        private static void ValidateEventHandler(object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
            {
                XmlSchemaException schemaException = new XmlSchemaException(e.Message, e.Exception);
                throw schemaException;
            }
        }
    }

}
</code>```

Body:
I have the following schema that I use to validate XMLs in my c# application.
The following code is the example of what I am doing. But what I found out is there is a difference in validations as opposed to validations in other technologies. I am not sure if its related to regex.

<xsd:schema targetNamespace="http://tempuri.org/XMLSchema.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/XMLSchema.xsd"
    xmlns:mstns="http://tempuri.org/XMLSchema.xsd"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
>
  <xsd:simpleType name="DateCCYYType">
    <xsd:annotation>
      <xsd:documentation>A type that is used for any century/year combination field.</xsd:documentation>
    </xsd:annotation>
    <xsd:restriction base="xsd:string">
      <xsd:maxLength value="4"/>
      <xsd:pattern value="(^$|[1-2][0-9][0-9][0-9])"/>
    </xsd:restriction>
  </xsd:simpleType>
  <xsd:complexType name="PersonalDetails">
    <xsd:sequence>
      <xsd:element name="yearJoined" type="mstns:DateCCYYType"></xsd:element>
      <xsd:element name="yearReleased" type="mstns:DateCCYYType"></xsd:element>
    </xsd:sequence>
  </xsd:complexType>
  <xsd:element name="PersonalDetails" type="mstns:PersonalDetails"></xsd:element>
</xsd:schema>

The class file is as follows

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            /*textBox1 Contains the xml text
            <urn:PersonalDetails xmlns:urn="http://tempuri.org/XMLSchema.xsd">
                <urn:yearJoined></urn:yearJoined>
                <urn:yearReleased>5000</urn:yearReleased>
            </urn:PersonalDetails>
             */
            StringReader reader = new StringReader(textBox1.Text);
            XmlTextReader xmlReader = new XmlTextReader(@"C:\visual studio 2015\Projects\WindowsFormsApplication1\SampleSchema.xsd");
            Exception xsdException = new Exception();
            try
            {
                bool isValid = IsXmlValidForSchema(reader, xmlReader, ref xsdException);
                if (isValid)
                {
                    MessageBox.Show("Success");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        public static void ValidateXml(
            StringReader srXML,
            XmlTextReader xtrSchema)
        {

            XmlSchemaSet xssValidate = null;
            try
            {
                xssValidate = new XmlSchemaSet();
                xssValidate.Add(null, xtrSchema);
                xssValidate.Compile();
                XPathDocument xpdValidate = new XPathDocument(srXML);
                XPathNavigator editor = xpdValidate.CreateNavigator();
                if (!editor.CheckValidity(xssValidate, ValidateEventHandler))
                {
                    throw new System.Xml.Schema.XmlSchemaValidationException();
                }
            }
            finally
            {
                if (xssValidate != null) xssValidate = null;
            }
        }

        public static bool IsXmlValidForSchema(
            StringReader xmlReader,
            XmlTextReader schemaReader, ref Exception xsdException)
        {
            bool result = true;
            try
            {
                ValidateXml(xmlReader, schemaReader);
            }
            catch (XmlSchemaValidationException ex)
            {

                xsdException = ex;
                result = false;
            }
            return result;
        }

        private static void ValidateEventHandler(object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
            {
                XmlSchemaException schemaException = new XmlSchemaException(e.Message, e.Exception);
                throw schemaException;
            }
        }

    }

If you use the xml in the commented block, it validates fine and does not throw error for the emptiness of yearJoined. However if I validate this using other validators like XMLSPY or any online validators, these are shown as errors.
I can fix this in .Net by using minLength. But why is this conflict? Is there a way to correct it.

Body:
Here is the code I used to test :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.XPath;
using System.IO;

namespace ConsoleApplication16
{
    class Program
    {
        const string SCHEMA_FILENAME = @"c:\temp\test1.xml";
        static void Main(string[] args)
        {
            //textBox1 Contains the xml text
            string xml = "<urn:PersonalDetails xmlns:urn=\"http://tempuri.org/XMLSchema.xsd\">" +
                     "<urn:yearJoined></urn:yearJoined>" +
                     "<urn:yearReleased>2017</urn:yearReleased>" +
                 "</urn:PersonalDetails>";

            StringReader reader = new StringReader(xml);
            XmlTextReader xmlReader = new XmlTextReader(SCHEMA_FILENAME);
            Exception xsdException = new Exception();
            try
            {
                bool isValid = IsXmlValidForSchema(reader, xmlReader, ref xsdException);
                if (isValid)
                {
                    Console.WriteLine("Success");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

        }
        public static void ValidateXml(
    StringReader srXML,
    XmlTextReader xtrSchema)
        {

            XmlSchemaSet xssValidate = null;
            try
            {
                xssValidate = new XmlSchemaSet();
                xssValidate.Add(null, xtrSchema);
                xssValidate.Compile();
                XPathDocument xpdValidate = new XPathDocument(srXML);
                XPathNavigator editor = xpdValidate.CreateNavigator();
                if (!editor.CheckValidity(xssValidate, ValidateEventHandler))
                {
                    throw new System.Xml.Schema.XmlSchemaValidationException();
                }
            }
            finally
            {
                if (xssValidate != null) xssValidate = null;
            }
        }

        public static bool IsXmlValidForSchema(
            StringReader xmlReader,
            XmlTextReader schemaReader, ref Exception xsdException)
        {
            bool result = true;
            try
            {
                ValidateXml(xmlReader, schemaReader);
            }
            catch (XmlSchemaValidationException ex)
            {

                xsdException = ex;
                result = false;
            }
            return result;
        }

        private static void ValidateEventHandler(object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
            {
                XmlSchemaException schemaException = new XmlSchemaException(e.Message, e.Exception);
                throw schemaException;
            }
        }
    }

}


问:
How can I determine the number of segments of a DASH MPD if duration and mediaPresentationDuration field is missing
How can I determine the number of segments of a DASH MPD, if neither duration field is available under period tag nor mediaPresentationDuration tag is present under MPD Header tag.

I have following dash mpd. how can I calculate total duration of all media segments available here.

Please find below the link for MPD, I am referring to.

http://wowzaec2demo.streamlock.net/live/definst/bigbuckbunny/manifest_mvnumber_w1608158161.mpd

答: MPD@type="dynamic" means that this is a live stream, so there is no duration (but the live stream could end at some time of course).


问:
Created a mvc5 app with Identity2, how do i set it up to use session cookies, so they expire when the browser closes
Created a mvc5 app with Identity2,using google login (pretty much the empty app, with google stuff turned on)

How do I set it up to use session cookies, so they expire when the browser closes.
The app will be used by students who may hot swap seats, so i need the login to expire when the browser closes.

I read an SO article that implies this is the default, but when i close the browser, and go back to the site, it remembers the google login.

Edit

Sorry to burst everyone bubble, but this isn't a duplicate.

It reproduced in Chrome after the settings in the supposed "answer" are changed, and it also reproduces in IE... This is an Asp.net Identity 2 +Google login issue, not a Chrome issue.

Edit

Adding Startup Auth file for Setup Help

```<code>using System;
using System.Configuration;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using StudentPortalGSuite.Models;

namespace StudentPortalGSuite
{
    public partial class Startup
    {
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(
            new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                               Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes( 30 ),
                        regenerateIdentity: ( manager, user ) => user.GenerateUserIdentityAsync( manager )
                        )
                },
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // per https://learn.microsoft.com/en-us/aspnet/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on - EWB
            //dev-jcsn email
            app.UseGoogleAuthentication( new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "...",
                ClientSecret = "..."

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

EDIT
The use case I'm trying to fix is, since our app is used in a classroom, that student A Closes his/her browser instead of logging out, and then next user tries to login. As it stands they are autologged into user A's account.

I'd also be up for a way to 100% log out the user when redirected to the login page, but all the ways I've tried that aren't working.

答:
Maybe you can catch the window close event on page and call logout method</p>

```<code>$(window).on("beforeunload", function() {
    //ajax call to a post controller that logs the user out

})
</code>```

Body:
Created a mvc5 app with Identity2,using google login (pretty much the empty app, with google stuff turned on)

How do I set it up to use session cookies, so they expire when the browser closes.
The app will be used by students who may hot swap seats, so i need the login to expire when the browser closes.

I read an SO article that implies this is the default, but when i close the browser, and go back to the site, it remembers the google login.

Edit

Sorry to burst everyone bubble, but this isn't a duplicate.

It reproduced in Chrome after the settings in the supposed "answer" are changed, and it also reproduces in IE... This is an Asp.net Identity 2 +Google login issue, not a Chrome issue.

Edit

Adding Startup Auth file for Setup Help

using System;
using System.Configuration;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using StudentPortalGSuite.Models;

namespace StudentPortalGSuite
{
    public partial class Startup
    {
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(
            new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                               Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes( 30 ),
                        regenerateIdentity: ( manager, user ) => user.GenerateUserIdentityAsync( manager )
                        )
                },
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // per https://learn.microsoft.com/en-us/aspnet/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on - EWB
            //dev-jcsn email
            app.UseGoogleAuthentication( new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "...",
                ClientSecret = "..."

            } );
            //});
        }
    }
}

EDIT
The use case I'm trying to fix is, since our app is used in a classroom, that student A Closes his/her browser instead of logging out, and then next user tries to login. As it stands they are autologged into user A's account.

I'd also be up for a way to 100% log out the user when redirected to the login page, but all the ways I've tried that aren't working.

Body:
Maybe you can catch the window close event on page and call logout method

$(window).on("beforeunload", function() {
    //ajax call to a post controller that logs the user out

})


问:
Access parameters from an object listed in a listbox c#
I have several classes in my program and I'm using Windows Form to create the objects from the different classes and list them in different listboxes.

Right now I have a form with all the listboxes (Form 1) and another form (CreerVoiture) where i put all the info to create my selected object.

An example is when i click on the button "Voiture!" my second form opens, when I add all the info and push on "Ajouter" it adds the object to the listbox selected.

Code from Form1:

```<code>private void button1_Click(object sender, EventArgs e)
    {
        CreerVoiture creervoiture = new CreerVoiture();
        if (creervoiture.ShowDialog(this) == DialogResult.OK)
        {
            // Read the contents of form2's TextBox.
            Voiture voiture = new Voiture(creervoiture.GetMarque(), creervoiture.GetPrix(), creervoiture.GetConsommation(), creervoiture.GetReservoir());
            this.list_voiture.Items.Add(voiture);

            this.list_voiture.DataSource = null;
        }
        creervoiture.Dispose();
    }
</code>```

What I would like to know is how I can access a parameter I added in my second form once I added it to the listbox.

I was thinking to use something like:

```<code>list_voiture.SelectedItem.Prix
</code>```

Prix is a getter from my class Voiture

```<code>public double Prix
    {
        get { return this.prix; }
        set { this.prix = value; }
    }
</code>```

But that doesn't seem to be possible. Is this possible and if so, how?

Thanks in advance,

Jeremy

答:
If the type of object is Voiture then you can cast the object to that type:

```<code>Voiture voiture = (Voiture)list_voiture.SelectedItem;
double prix = voiture.Prix;
</code>```

Or in one line:

```<code>double prix = ((Voiture)list_voiture.SelectedItem).Prix;
</code>```

Body:
I have several classes in my program and I'm using Windows Form to create the objects from the different classes and list them in different listboxes.

Right now I have a form with all the listboxes (Form 1) and another form (CreerVoiture) where i put all the info to create my selected object.

An example is when i click on the button "Voiture!" my second form opens, when I add all the info and push on "Ajouter" it adds the object to the listbox selected.

Code from Form1:

private void button1_Click(object sender, EventArgs e)
    {
        CreerVoiture creervoiture = new CreerVoiture();
        if (creervoiture.ShowDialog(this) == DialogResult.OK)
        {
            // Read the contents of form2's TextBox.
            Voiture voiture = new Voiture(creervoiture.GetMarque(), creervoiture.GetPrix(), creervoiture.GetConsommation(), creervoiture.GetReservoir());
            this.list_voiture.Items.Add(voiture);

            this.list_voiture.DataSource = null;
        }
        creervoiture.Dispose();
    }

What I would like to know is how I can access a parameter I added in my second form once I added it to the listbox.

I was thinking to use something like:

list_voiture.SelectedItem.Prix

Prix is a getter from my class Voiture

public double Prix
    {
        get { return this.prix; }
        set { this.prix = value; }
    }

But that doesn't seem to be possible. Is this possible and if so, how?

Thanks in advance,

Jeremy

Body:
If the type of object is Voiture then you can cast the object to that type:

Voiture voiture = (Voiture)list_voiture.SelectedItem;
double prix = voiture.Prix;

Or in one line:

double prix = ((Voiture)list_voiture.SelectedItem).Prix;


问:
PHP arrays within an array - nested arrays PHP
I'm using ACF Pro plugin for Wordpress and use repeater fields.
With this code I get all the field values and additional info in an array:

```<code>$fields = get_field_object('slideshow');
</code>```

With this code I can narrow it down to what I want to achieve:

```<code>print_r($fields[value];
</code>```

By now I get this array below:

```<code>Array
(
    [0] => Array
        (
            [videoWebm] => /wc/data/uploads/sea.webm
            [videoMp4] => /wc/data/uploads/sea1.mp4
            [text] => Test1
            [kund] => Kund1
            [link1] =>
            [link2] =>
        )
    [1] => Array
        (
            [videoWebm] => /wc/data/uploads/turntable.webm
            [videoMp4] => /wc/data/uploads/turntable.mp4
            [text] => Test2
            [kund] => Kund2
            [link1] =>
            [link2] =>
        )
)
</code>```

it can grow more - like [2] => Array, [3] => Array etc.

I want to access all videoWebm & videoMp4 values.
As of now I know how to access a specific value - for example:

```<code>print_r($fields[value][0][videoWebm]);
</code>```

But I can't figure out how to access all of them and put them in two new arrays. One for videoWebm values and one for videoMp4 values. The problem for me is the index value when I try to loop thru the array. I don't know if this really is the way to go...

Anyone suggestions?

Best, Niklas

答:
You can use foreach:

```<code>foreach ($fields[value] as $field) {
    $videoWebms[] = $field['videoWebm']
    $videoMp4s[] = $field['videoMp4'];
}
</code>```

Or as splash58 said, use array_column:

```<code>$vieoWebms = array_column($fields[value], 'videoWebm');
$vieoMp4s = array_column($fields[value], 'videoMp4');
</code>```

I would highly recommend you learn about php's foreach, it is very powerful and widely used (maybe a little too widely).

https://www.google.com/search?q=php%20foreach

Body:
I'm using ACF Pro plugin for Wordpress and use repeater fields.
With this code I get all the field values and additional info in an array:

$fields = get_field_object('slideshow');

With this code I can narrow it down to what I want to achieve:

print_r($fields[value];

By now I get this array below:

Array
(
    [0] => Array
        (
            [videoWebm] => /wc/data/uploads/sea.webm
            [videoMp4] => /wc/data/uploads/sea1.mp4
            [text] => Test1
            [kund] => Kund1
            [link1] =>
            [link2] =>
        )
    [1] => Array
        (
            [videoWebm] => /wc/data/uploads/turntable.webm
            [videoMp4] => /wc/data/uploads/turntable.mp4
            [text] => Test2
            [kund] => Kund2
            [link1] =>
            [link2] =>
        )
)

it can grow more - like [2] => Array, [3] => Array etc.

I want to access all videoWebm & videoMp4 values.
As of now I know how to access a specific value - for example:

print_r($fields[value][0][videoWebm]);

But I can't figure out how to access all of them and put them in two new arrays. One for videoWebm values and one for videoMp4 values. The problem for me is the index value when I try to loop thru the array. I don't know if this really is the way to go...

Anyone suggestions?

Best, Niklas

Body:
You can use foreach:

foreach ($fields[value] as $field) {
    $videoWebms[] = $field['videoWebm']
    $videoMp4s[] = $field['videoMp4'];
}

Or as splash58 said, use array_column:

$vieoWebms = array_column($fields[value], 'videoWebm');
$vieoMp4s = array_column($fields[value], 'videoMp4');

I would highly recommend you learn about php's foreach, it is very powerful and widely used (maybe a little too widely).

https://www.google.com/search?q=php%20foreach


问:
Only in Firefox got error "SyntaxError: missing ; before statement"
I have got error in Firefox "SyntaxError: missing ; before statement".In Chrome and Explorer all is fine. Maybe somebody can help.
Here is the code:

```<code>function filterArray (data, elem, checkingData)
{
    let array = data.filter(function (item) { //FIREFOX points to this string
        return (item[elem] !== checkingData);
    });
    return array;
}
</code>```

答: Change let to var and the error message will disappear.

Body:
I have got error in Firefox "SyntaxError: missing ; before statement".In Chrome and Explorer all is fine. Maybe somebody can help.
Here is the code:

function filterArray (data, elem, checkingData)
{
    let array = data.filter(function (item) { //FIREFOX points to this string
        return (item[elem] !== checkingData);
    });
    return array;
}


问:
Applying styles to a dynamically-injected div via AJAX call (xhrGet)
Hey guys, I'm using the code below to retrieve updated content after receiving a "push" event from a server. The updated content is then used to replace the div/content that is already there.

The problem I'm having is that none of my styles from my external stylesheet are applied to this new content.

It makes sense to me why this would occur... but is there no way around this? I can apply styles dynamically, as I've done to an extent below, but it seems like there should be an easier way.

Is there no way to have styles from an external stylesheet applied automatically to dynamically-loaded content?

See code below:

```<code>loadContent = function(page, count) {
    var xhrArgs = {
        url: '/content/'+page+'/'+count+'/',
        handleAs: 'text',
        load: function(response) {
            dojo.byId('content').innerHTML = response;

            dojo.query('.dropdown').forEach(function(node, index, arr) {
                dojo.style(node, 'display', 'none'); // **This defaults to "display: none" in the stylesheet, but it's not applied until I do this**
            });
        },
        error: function(error) {
            console.debug('error loading content');
        }
    };

    var deferred = dojo.xhrGet(xhrArgs);
};
</code>```

答: Style sheets are applied dynamically already. If this doesn't happen then there is an error and possibly the new content doesn't have the tag names and attributes that your CSS applies on. So double check the returned data, and use Firebug to help you with that new content.</p>

Body:
Hey guys, I'm using the code below to retrieve updated content after receiving a "push" event from a server. The updated content is then used to replace the div/content that is already there.

The problem I'm having is that none of my styles from my external stylesheet are applied to this new content.

It makes sense to me why this would occur... but is there no way around this? I can apply styles dynamically, as I've done to an extent below, but it seems like there should be an easier way.

Is there no way to have styles from an external stylesheet applied automatically to dynamically-loaded content?

See code below:

loadContent = function(page, count) {
    var xhrArgs = {
        url: '/content/'+page+'/'+count+'/',
        handleAs: 'text',
        load: function(response) {
            dojo.byId('content').innerHTML = response;

            dojo.query('.dropdown').forEach(function(node, index, arr) {
                dojo.style(node, 'display', 'none'); // **This defaults to "display: none" in the stylesheet, but it's not applied until I do this**
            });
        },
        error: function(error) {
            console.debug('error loading content');
        }
    };

    var deferred = dojo.xhrGet(xhrArgs);
};


答:
To get the value from repeater use this :               </p>

```<code>$slides = get_field('slideshow');
if($slides){
    foreach($slides as $slide){
        echo $slide['videoWebm'];
        echo $slide['text'];
        echo $slide['kund]'];
        echo $slide['link1'];
        echo $slide['link2'];
    }
}
</code>```

Title: PHP arrays within an array - nested arrays PHP

Body:
To get the value from repeater use this :

$slides = get_field('slideshow');
if($slides){
    foreach($slides as $slide){
        echo $slide['videoWebm'];
        echo $slide['text'];
        echo $slide['kund]'];
        echo $slide['link1'];
        echo $slide['link2'];
    }
}


问:
MVC ASP.NET MVC3 AllowHtml Attribute Not Working?
The question is very simple:

Say you have a model called Person

```<code>public class Person
{

       public int PersonID {get; set;}

       public string Name {get; set;}

       [AllowHtml] // Allow html in Intro property
       public string Intro {get; set;}

       [ScaffoldColumn(false)]
       public string ComplicatedValue {get; set;}

}
</code>```

In controller's Create action

```<code>[HttpPost]
public ActionResult Create(Person o, FormCollection collection)
{

// whatever code here;

}
</code>```

If you run it,

input plain text for Intro, no
problem happens.

input html content for Intro, no matter how you set
your configuration file, it will
tells "A potential dangerous ..."

I DO find the reason of this problem.

If you change the function to

```<code>public ActionResult Create(Person o) // Get rid of the *FormCollection collection*
{

// whatever code here;

}
</code>```

This will eliminate the "potential dangerous" error.

But my problem is that for my application, I have to use the secondary parameter FormCollection collection in the Create Action method, because I need to use some other control values and server variable to assign a calculated value to the ComplicatedValue property.

If any expert of ASP.NET MVC3 have met the same problem as me, and found a solution, please kindly let me know.

答: Might I suggest using a custom model binder instead of pulling the complex data from a FormCollection.  Scott Hanselman has a blog post on creating a custom model binder that would serve as a good template.  In his post he puts together a DateTimeModelBinder that allows a DateTime property to be set either by a single input containing the date or a pair of inputs containing a date and a time.</p>

Body:
The question is very simple:

Say you have a model called Person

public class Person
{

       public int PersonID {get; set;}

       public string Name {get; set;}

       [AllowHtml] // Allow html in Intro property
       public string Intro {get; set;}

       [ScaffoldColumn(false)]
       public string ComplicatedValue {get; set;}

}

In controller's Create action

[HttpPost]
public ActionResult Create(Person o, FormCollection collection)
{

// whatever code here;

}

If you run it,

input plain text for Intro, no
problem happens.

input html content for Intro, no matter how you set
your configuration file, it will
tells "A potential dangerous ..."

I DO find the reason of this problem.

If you change the function to

public ActionResult Create(Person o) // Get rid of the *FormCollection collection*
{

// whatever code here;

}

This will eliminate the "potential dangerous" error.

But my problem is that for my application, I have to use the secondary parameter FormCollection collection in the Create Action method, because I need to use some other control values and server variable to assign a calculated value to the ComplicatedValue property.

If any expert of ASP.NET MVC3 have met the same problem as me, and found a solution, please kindly let me know.


问:
JMS + ActiveMQ: exclusive access to data
Good day everyone.

1) I have a simple app which creates JMSProducer, ActiveMQ Query and send some messages to query.

2) I also have the application which is a subscriber
of ActiveMQ Query (it receives messages from application above).

This is the situation:

I create another server config to my subscriber-App, and launch it twice at a time on different ports.
(for example: subscriber-App1 started at jetty-http-port-9998/jetty-ssl-port-9994; subscriber-App2 started at jetty-http-port-9999/jetty-ssl-port-9995).

I open subscriber-App1 console and subscriber-App2 console at Intellij IDEa and begin to send messages by producer-App. And I see that subscribers takes messages by rotation: when I send it the first time - subscriber1 takes it; 2nd time - subscriber2; 3rd time - subscriber1 etc.

The question is: how can I configure subscriber-Application to give it exclusive access to data? The main condition is: if there is the one Subscriber of my Queue - another applications can't receive messages from Queue. And if I launch two subscriberApps on different ports - all messages will be received by only one of them.

Thank you in advance!

答: I believe you should be able to use the exclusive consumer feature to achieve your goal.</p>


问:
Extract keywords from strings and assign them to properties in C#
I need to transfer data from MATLAB to a C# software. The data from MATLAB should also be editable offline (i.e. outside MATLAB and the C# software). To achieve this, my MATLAB code prints the data with readable patterns to a text file. For example:

```<code><L> pt: [0.001,2,3], spd: 100, cfg: fut, daq: on, id: [1,1] </L>
<L> pt: [0.002,3,4], cfg: nut, spd: 100, id: [1,1], daq: on</L>
<C> pt: [0.02,5,3], spd: 100, daq: on, id: [1,1] </C>
<L> pt: [1.002,3,4], spd: 100, daq: off</L>
</code>```

In C#, I want to parse each line, extract these keywords and assign them to properties:

```<code>enum PathType { L, C}
class Path
{
    public PathType Type { get; set; }
    public float[] Pt { get; set; }
    public int Spd { get; set; }
    public string Cfg { get; set; }
    public bool Daq { get; set; }
    public int[] Id { get; set; }
}
</code>```

So for Line 1, I intend to have something look like this:

```<code>var path = new Path {
    PathType = PathType.L,
    Pt = new []{ 0.001, 2, 3 },
    Spd = 100,
    Cfg = "fut",
    Daq = true,
    Id = new []{ 1, 1 }};
</code>```

for Line 4:

```<code>var path = new Path {
    PathType = PathType.L,
    Pt = new []{ 1.002, 3, 4 },
    Spd = 100,
    Cfg = null,
    Daq = false,
    Id = null;
</code>```

Since the keywords are arranged in different order and may not appear in all lines, I can't use a single regular expression to extract these information. I have to use multiple regular expressions to test each line:

```<code>    var typeReg = new Regex(@"<(\w+)>");
    var ptReg = new Regex(@"pt:\s+(?<open>\[)[^\[]*(?<close-open>\])(?(open))");
    var spdReg = new Regex(@"spd:\s+(\d+)");
    var cfgReg = new Regex(@"cfg:\s+(fut|nut)");
    var daqReg = new Regex(@"daq:\s+(on|off)");
    var idReg = new Regex(@"id:\s+(?<open>\[)[^\[]*(?<close-open>\])(?(open))");
</code>```

This works but I'm wondering if there is any better way of doing this?

Shall I print the data in a different pattern such as:

```<code>L; pt: [0.001,2,3]; spd: 100; cfg: fut; daq: on; id: [1,1]
</code>```

Then I can split the string with delimiter ; and then check each substring with x.StartWith('...'). But this way, I feel it is not as readable as the current pattern.

I do not want to use xml since it will make the text file bigger than the desired size.

答:
I compared JSON and XML and found XML is better. I had a poor understanding of XML format and thought it would significantly increase file size, which is wrong.

The JSON implementation

This method requires a NuGet package, Newtonsoft.Json. There are also other solutions that do not require it.

MATLAB output:

```<code>{"type":"L", "pt": "[0.001,2,3]", "spd": "100", "cfg": "fut", "daq": "on", "id": "[1,1]"}
</code>```

C# code for decoding JSON is as simple as:

```<code>using Newtonsoft.Json;
public void Dictionary<string,string> DecodeJson(script)
{
    return JsonConvert.DeserializeObject(script);
}
</code>```

The returned object is a dictionary consists of attribute names, i.e. type, pt, spd etc., as keys and attribute values as values.

Decoding 100k of the example output requires roughly 330 ms.

The XML implementation

MATLAB output:

```<code><L pt='[0.001,2,3]' spd='100' cfg='fut' daq='on' id='[1,1]'  />
</code>```

C# code:

```<code>public void Dictionary<string,string> DecodeXml(script)
{
    var xmlObj = new Dictionary<string, string>();
    using (var reader = XmlReader.Create(new StringReader(script)))
    {
        reader.Read();
        // add node name, i.e. xmlObj["type"] -> L
        xmlObj.Add("type",reader.Name);
        // add all attributes
        while (reader.MoveToNextAttribute())
        {
            xmlObj.Add(reader.Name, reader.Value);
        }
    }
    return xmlObj;
}
</code>```

This method returns the same object as the JSON method.

Decoding 100k of the example output requires roughly 180 ms.

Conclusion

The input string for the xml implementation is shorter than that for the JSON implementation, hence smaller file size. The execution time of the XML code is almost 2x faster than that of the JSON code. Therefore, XML is a better choice.

Body:
I need to transfer data from MATLAB to a C# software. The data from MATLAB should also be editable offline (i.e. outside MATLAB and the C# software). To achieve this, my MATLAB code prints the data with readable patterns to a text file. For example:

<L> pt: [0.001,2,3], spd: 100, cfg: fut, daq: on, id: [1,1] </L>
<L> pt: [0.002,3,4], cfg: nut, spd: 100, id: [1,1], daq: on</L>
<C> pt: [0.02,5,3], spd: 100, daq: on, id: [1,1] </C>
<L> pt: [1.002,3,4], spd: 100, daq: off</L>

In C#, I want to parse each line, extract these keywords and assign them to properties:

enum PathType { L, C}
class Path
{
    public PathType Type { get; set; }
    public float[] Pt { get; set; }
    public int Spd { get; set; }
    public string Cfg { get; set; }
    public bool Daq { get; set; }
    public int[] Id { get; set; }
}

So for Line 1, I intend to have something look like this:

var path = new Path {
    PathType = PathType.L,
    Pt = new []{ 0.001, 2, 3 },
    Spd = 100,
    Cfg = "fut",
    Daq = true,
    Id = new []{ 1, 1 }};

for Line 4:

var path = new Path {
    PathType = PathType.L,
    Pt = new []{ 1.002, 3, 4 },
    Spd = 100,
    Cfg = null,
    Daq = false,
    Id = null;

Since the keywords are arranged in different order and may not appear in all lines, I can't use a single regular expression to extract these information. I have to use multiple regular expressions to test each line:

    var typeReg = new Regex(@"<(\w+)>");
    var ptReg = new Regex(@"pt:\s+(?<open>\[)[^\[]*(?<close-open>\])(?(open))");
    var spdReg = new Regex(@"spd:\s+(\d+)");
    var cfgReg = new Regex(@"cfg:\s+(fut|nut)");
    var daqReg = new Regex(@"daq:\s+(on|off)");
    var idReg = new Regex(@"id:\s+(?<open>\[)[^\[]*(?<close-open>\])(?(open))");

This works but I'm wondering if there is any better way of doing this?

Shall I print the data in a different pattern such as:

L; pt: [0.001,2,3]; spd: 100; cfg: fut; daq: on; id: [1,1]

Then I can split the string with delimiter ; and then check each substring with x.StartWith('...'). But this way, I feel it is not as readable as the current pattern.

I do not want to use xml since it will make the text file bigger than the desired size.

Body:
I compared JSON and XML and found XML is better. I had a poor understanding of XML format and thought it would significantly increase file size, which is wrong.

The JSON implementation

This method requires a NuGet package, Newtonsoft.Json. There are also other solutions that do not require it.

MATLAB output:

{"type":"L", "pt": "[0.001,2,3]", "spd": "100", "cfg": "fut", "daq": "on", "id": "[1,1]"}

C# code for decoding JSON is as simple as:

using Newtonsoft.Json;
public void Dictionary<string,string> DecodeJson(script)
{
    return JsonConvert.DeserializeObject(script);
}

The returned object is a dictionary consists of attribute names, i.e. type, pt, spd etc., as keys and attribute values as values.

Decoding 100k of the example output requires roughly 330 ms.

The XML implementation

MATLAB output:

<L pt='[0.001,2,3]' spd='100' cfg='fut' daq='on' id='[1,1]'  />

C# code:

public void Dictionary<string,string> DecodeXml(script)
{
    var xmlObj = new Dictionary<string, string>();
    using (var reader = XmlReader.Create(new StringReader(script)))
    {
        reader.Read();
        // add node name, i.e. xmlObj["type"] -> L
        xmlObj.Add("type",reader.Name);
        // add all attributes
        while (reader.MoveToNextAttribute())
        {
            xmlObj.Add(reader.Name, reader.Value);
        }
    }
    return xmlObj;
}

This method returns the same object as the JSON method.

Decoding 100k of the example output requires roughly 180 ms.

Conclusion

The input string for the xml implementation is shorter than that for the JSON implementation, hence smaller file size. The execution time of the XML code is almost 2x faster than that of the JSON code. Therefore, XML is a better choice.


问:
Size Limit of camel header variable and property
I have to store the request xml in to database. I was using header variable to do that.

```<code>exchange.getIn().setHeader("inputRequestXml", body);
</code>```

it was working for some files And I was getting below exception for some files, it seems like because of the file size.

```<code> 413 Request entity too large
</code>```

So I have changed the implementation by using camel property, like below

```<code>exchange.setProperty("inputRequestXml", body);
</code>```

Now I am not getting the exception. But I am afraid that will it handle the bigger files in actual PROD environment. So i want to know, What would be the size
limit of header variable and property?

答:
Exchange properties have no limit, its just a HashMap that stores key/values in the memory of the JVM.

Message headers is also just a HashMap, but headers are part of the message contract, and depending on which Camel components (transports) you use then these headers may be in use, eg HTTP headers, SOAP headers, JMS headers etc. And when so you may have header limitations that are caused by these transports.

You can find more details and it can be a good idea to read the free chapter 1 of the Camel in Action 2nd edition book which explains the important Camel concepts.

Body:
I have to store the request xml in to database. I was using header variable to do that.

exchange.getIn().setHeader("inputRequestXml", body);

it was working for some files And I was getting below exception for some files, it seems like because of the file size.

 413 Request entity too large

So I have changed the implementation by using camel property, like below

exchange.setProperty("inputRequestXml", body);

Now I am not getting the exception. But I am afraid that will it handle the bigger files in actual PROD environment. So i want to know, What would be the size
limit of header variable and property?


问:
SQL Many-To-Many multiple items per column
Sorry about the title, as I'm new to SQL and I don't know how to explain the problem appropriately...

I have 5 tables.

Delivery

```<code>ID | Time      |
---------------|
1  | 1999-01-01|
2  | 1999-01-01|
3  | 1999-01-01|
</code>```

Delivery_Items

```<code>Delivery_ID | Order_ID|
----------------------|
1           | 1       |
2           | 2       |
3           | 3       |
</code>```

Food

```<code>ID | Name | Price  |
-------------------|
1  |Eggs  | 3.00   |
2  |Bacon | 1.50   |
3  |Ham   | 4.00   |
</code>```

Ordered_Items

```<code>Order_ID | Item_ID  |
--------------------|
1        |  1       |
1        |  1       |
1        |  2       |
1        |  3       |
2        |  2       |
2        |  1       |
3        |  3       |
</code>```

Orders

```<code>ID | Total_Price  |
------------------|
1  | 11.50        |
</code>```

I would like to Join them together for an expected result of something like this

```<code>Delivery_ID    | Food.Name            | Total Price |
----------------------------------------------------|
1              |Eggs, Eggs, Bacon, Ham| 11.50       |
2              |Bacon, Eggs           | 4.50        |
3              |Ham                   | 4.00        |
</code>```

So far I've tried:

```<code>SELECT
    O.Id,
    GROUP_CONCAT(F.Name
        SEPARATOR ','),
    O.Total
FROM
    Food F
        LEFT OUTER JOIN
    Ordered_Items OI ON OI.Item_ID = F.Id
        LEFT OUTER JOIN
    Orders O ON O.Id = OI.order_Id
GROUP BY O.Id;
</code>```

Which results in

```<code>Delivery_ID    | Food.Name                     | Total Price |
-------------------------------------------------------------|
NULL           |Eggs, Bacon, Ham(trash values) | NULL        |
1              |Eggs, Eggs, Bacon, Ham         | 11.50       |
2              |Bacon, Eggs                    | 4.50        |
3              |Ham                            | 4.00        |
</code>```

How do I get rid of that first NULL line?
And by trash values I mean their IDs don't appear in any Ordered_Items row.

答:
To join two or more tables you need to use Join and the query for this will look like-

'SELECT Delivery_Items.Delivery_ID,Food.Name,Orders.Total_Price FROM
Delivery_Items  JOIN Ordered_items ON Delivery_Items.Delivery_ID=Ordered_Items.Order_ID
JOIN Food ON ordered_items.Order_ID=Food.ID
JOIN Orders ON Delivery_Items.Delivery_ID=Orders.ID

So, As we need to look the tables we start joining tables.Thus , first we join Delivery_Items and Ordered_Items which created a temporary result making another table and then this is joined by another table and the process goes on.

1.First choose which columns you want to show in the end result

2.Select all those columns

3.Look up the tables that you need to join to get the result

4.Then in the sql query  join those according to table1.primarykeytable2.foreignkey

Body:
Sorry about the title, as I'm new to SQL and I don't know how to explain the problem appropriately...

I have 5 tables.

Delivery

ID | Time      |
---------------|
1  | 1999-01-01|
2  | 1999-01-01|
3  | 1999-01-01|

Delivery_Items

Delivery_ID | Order_ID|
----------------------|
1           | 1       |
2           | 2       |
3           | 3       |

Food

ID | Name | Price  |
-------------------|
1  |Eggs  | 3.00   |
2  |Bacon | 1.50   |
3  |Ham   | 4.00   |

Ordered_Items

Order_ID | Item_ID  |
--------------------|
1        |  1       |
1        |  1       |
1        |  2       |
1        |  3       |
2        |  2       |
2        |  1       |
3        |  3       |

Orders

ID | Total_Price  |
------------------|
1  | 11.50        |

I would like to Join them together for an expected result of something like this

Delivery_ID    | Food.Name            | Total Price |
----------------------------------------------------|
1              |Eggs, Eggs, Bacon, Ham| 11.50       |
2              |Bacon, Eggs           | 4.50        |
3              |Ham                   | 4.00        |

So far I've tried:

SELECT
    O.Id,
    GROUP_CONCAT(F.Name
        SEPARATOR ','),
    O.Total
FROM
    Food F
        LEFT OUTER JOIN
    Ordered_Items OI ON OI.Item_ID = F.Id
        LEFT OUTER JOIN
    Orders O ON O.Id = OI.order_Id
GROUP BY O.Id;

Which results in

Delivery_ID    | Food.Name                     | Total Price |
-------------------------------------------------------------|
NULL           |Eggs, Bacon, Ham(trash values) | NULL        |
1              |Eggs, Eggs, Bacon, Ham         | 11.50       |
2              |Bacon, Eggs                    | 4.50        |
3              |Ham                            | 4.00        |

How do I get rid of that first NULL line?
And by trash values I mean their IDs don't appear in any Ordered_Items row.


问:
Android Push Notifications: Icon not displaying in notification, white square shown instead
My app generates a notification, but the icon I set for that notification is not being displayed. Instead, I get a white square.

I have tried resizing the png of the icon (dimensions 720x720, 66x66, 44x44, 22x22). Curiously, when using smaller dimensions the white square is smaller.

I have googled this problem, as well as the correct way of generating notifications, and from what I've read my code should be correct. Sadly things are not as they should be.

My phone is a Nexus 5 with Android 5.1.1. The problem is also present on emulators, a Samsung Galaxy s4 with Android 5.0.1 and a Motorola Moto G with Android 5.0.1 (both of which I borrowed, and don't have right now)

The code for notifications follows, and two screenshots. If you require more information, please feel free to ask for it.

Thank you all.

```<code>@SuppressLint("NewApi") private void sendNotification(String msg, String title, String link, Bundle bundle) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
    resultIntent.putExtras(bundle);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            resultIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
    Notification notification;
    Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notificationsound);
    notification = new Notification.Builder(this)
                .setSmallIcon(R.drawable.lg_logo)
                .setContentTitle(title)
                .setStyle(new Notification.BigTextStyle().bigText(msg))
                .setAutoCancel(true)
                .setContentText(msg)
                .setContentIntent(contentIntent)
                .setSound(sound)
                .build();
    notificationManager.notify(0, notification);
}
</code>```

答:
When you want keep colorful icon - Workaround

Add pixel with slightly different color into icon.
 In my case a have black icon with shades and light. When added dark blue pixel it works.

ContentLicense: CC BY-SA 4.0

Body:
My app generates a notification, but the icon I set for that notification is not being displayed. Instead, I get a white square.

I have tried resizing the png of the icon (dimensions 720x720, 66x66, 44x44, 22x22). Curiously, when using smaller dimensions the white square is smaller.

I have googled this problem, as well as the correct way of generating notifications, and from what I've read my code should be correct. Sadly things are not as they should be.

My phone is a Nexus 5 with Android 5.1.1. The problem is also present on emulators, a Samsung Galaxy s4 with Android 5.0.1 and a Motorola Moto G with Android 5.0.1 (both of which I borrowed, and don't have right now)

The code for notifications follows, and two screenshots. If you require more information, please feel free to ask for it.

Thank you all.

@SuppressLint("NewApi") private void sendNotification(String msg, String title, String link, Bundle bundle) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
    resultIntent.putExtras(bundle);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            resultIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
    Notification notification;
    Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notificationsound);
    notification = new Notification.Builder(this)
                .setSmallIcon(R.drawable.lg_logo)
                .setContentTitle(title)
                .setStyle(new Notification.BigTextStyle().bigText(msg))
                .setAutoCancel(true)
                .setContentText(msg)
                .setContentIntent(contentIntent)
                .setSound(sound)
                .build();
    notificationManager.notify(0, notification);
}


问:
Gradle Replace text in jsp using filter
I have a jsp that contains a css link that looks like

```<code><link type="text/css" href="/css/login-min.css" rel="stylesheet" />
</code>```

In order to keep browsers from caching the css file we replace login-min.css with the name of the css and a timestamp or version number

```<code>login-min.css?t=432432423423...
</code>```

In ant I would do something like

```<code><tstamp>
  <format property="current.time" pattern="MMddyyyyhhmmssaa" offset="-5" unit="hour" />
</tstamp>

<replace dir="${deploy.path}/${name}/WEB-INF/jsp" value="login-min.css?t=${current.time}">
  <include name="includes/login_css_include.jsp" />
  <replacetoken>login-min.css</replacetoken>
</replace>
</code>```

For gradle I've updated the jsp page to look like

```<code><link type="text/css" href="/css/@loginCSS@" rel="stylesheet" />
</code>```

and in the build.gradle am doing

```<code>import org.apache.tools.ant.filters.ReplaceTokens
war {
  webInf {
    from ("${webAppDir}/WEB-INF/jsp") {
      include: "/includes/login_css_include.jsp"
      filter(ReplaceTokens, tokens: [loginCSS: 'login-min.css?v=1'])
    }
  }
}
</code>```

but this isn't working.

This one works but it changes the source... I just want the files in the war to be modified.

```<code>import org.apache.tools.ant.filters.ReplaceTokens
war {
  webInf {
    from ("${webAppDir}/WEB-INF/jsp/includes/login_css_include.jsp") {
      it.eachFile {
        ant.replace(file: it.file, token: "@loginCSS@", value: "login-min.css?v=1")
      }
    }
  }
}
</code>```

I'm brand new to gradle am I going about this totally incorrectly?  Anyone needed to do something like this before?  Using gradle 1.0-milestone-1.

Thanks

答:
You can also set encoding by(because by default it will change the file encoding):</p>

```<code>war {
    filteringCharset = 'UTF-8'
    filesMatching( '**/*.jsp' ) {
        filter ReplaceTokens, tokens: [
                'versionDate': "${new Date().format('yyyyMMdd')}".toString(),
                'copyright'  : "${new Date().format('yyyy')}".toString()
        ]
    }
}
</code>```

Title: Gradle Replace text in jsp using filter

Body:
I have a jsp that contains a css link that looks like

<link type="text/css" href="/css/login-min.css" rel="stylesheet" />

In order to keep browsers from caching the css file we replace login-min.css with the name of the css and a timestamp or version number

login-min.css?t=432432423423...

In ant I would do something like

<tstamp>
  <format property="current.time" pattern="MMddyyyyhhmmssaa" offset="-5" unit="hour" />
</tstamp>

<replace dir="${deploy.path}/${name}/WEB-INF/jsp" value="login-min.css?t=${current.time}">
  <include name="includes/login_css_include.jsp" />
  <replacetoken>login-min.css</replacetoken>
</replace>

For gradle I've updated the jsp page to look like

<link type="text/css" href="/css/@loginCSS@" rel="stylesheet" />

and in the build.gradle am doing

import org.apache.tools.ant.filters.ReplaceTokens
war {
  webInf {
    from ("${webAppDir}/WEB-INF/jsp") {
      include: "/includes/login_css_include.jsp"
      filter(ReplaceTokens, tokens: [loginCSS: 'login-min.css?v=1'])
    }
  }
}

but this isn't working.

This one works but it changes the source... I just want the files in the war to be modified.

import org.apache.tools.ant.filters.ReplaceTokens
war {
  webInf {
    from ("${webAppDir}/WEB-INF/jsp/includes/login_css_include.jsp") {
      it.eachFile {
        ant.replace(file: it.file, token: "@loginCSS@", value: "login-min.css?v=1")
      }
    }
  }
}

I'm brand new to gradle am I going about this totally incorrectly?  Anyone needed to do something like this before?  Using gradle 1.0-milestone-1.

Thanks

Body:
You can also set encoding by(because by default it will change the file encoding):

war {
    filteringCharset = 'UTF-8'
    filesMatching( '**/*.jsp' ) {
        filter ReplaceTokens, tokens: [
                'versionDate': "${new Date().format('yyyyMMdd')}".toString(),
                'copyright'  : "${new Date().format('yyyy')}".toString()
        ]
    }
}


问:
opendialog.onhint crash
I have checked 100% I am closing all handles on a file I recently created. But when I call "opendialog.execute;" the dialog pop up as usual but on the mouse over hint of a recently created file the entire thing crashes with a out of bounds error.

I know this is not any of my out of bounds as if I open the file without causing a (onhint) event there is no problem and hardcoding a list of filenames for testing showed that there was nothing wrong with opening or saving a file. Its purely on the onhint event of the open dialog. Like I said if I am quick or I use arrow keys there is nothing wrong with my program.

Whats more interesting is that it doesnt even happen 100% of the time about 70% which has led to me thinking I have fixed it several time if not only for a short amount of time. Does anyone know what could be happening? And if not how can I disable the onhint event?

as aked for the code not that helps at all

```<code>OpenDialog.execute;    // crashes here
if fileexists(form1.OpenDialog.FileName) then
  form1.Address.Text:=form1.OpenDialog.FileName;
</code>```

and the error
link text

EDIT: ok i have some new information a new instance of opendialog still has the same issues. and more interestingly i seem to have solved the 30% issue its on hint of a file with a double tag for example "test.jpg.enc" the thing is its fine with it the first time it runs, and it only crashes on hint of these encoded files, but only if i have encoded that file white the applicatuion has benn open. for example if i encode it,, then try to decode and it crashes.. i can run it again and decode it fine,, but there is no problem with decoding and then encoding in one instance of the aplication.

答:
Are you sure an instance of form1 is created?

if yes:

Why dont you use like this:

```<code>OpenDialog.Options:=  OpenDialog.Options + [ofFileMustExist];

if OpenDialog.Execute then
  Address.Text:= OpenDialog.FileName
</code>```

And use FastMM4, and define FullDebugMode in FastMM4.inc.
This may help you to find the real problem

OwnerDisplayName: Arthur

Title: opendialog.onhint crash

Body:
I have checked 100% I am closing all handles on a file I recently created. But when I call "opendialog.execute;" the dialog pop up as usual but on the mouse over hint of a recently created file the entire thing crashes with a out of bounds error.

I know this is not any of my out of bounds as if I open the file without causing a (onhint) event there is no problem and hardcoding a list of filenames for testing showed that there was nothing wrong with opening or saving a file. Its purely on the onhint event of the open dialog. Like I said if I am quick or I use arrow keys there is nothing wrong with my program.

Whats more interesting is that it doesnt even happen 100% of the time about 70% which has led to me thinking I have fixed it several time if not only for a short amount of time. Does anyone know what could be happening? And if not how can I disable the onhint event?

as aked for the code not that helps at all

OpenDialog.execute;    // crashes here
if fileexists(form1.OpenDialog.FileName) then
  form1.Address.Text:=form1.OpenDialog.FileName;

and the error
link text

EDIT: ok i have some new information a new instance of opendialog still has the same issues. and more interestingly i seem to have solved the 30% issue its on hint of a file with a double tag for example "test.jpg.enc" the thing is its fine with it the first time it runs, and it only crashes on hint of these encoded files, but only if i have encoded that file white the applicatuion has benn open. for example if i encode it,, then try to decode and it crashes.. i can run it again and decode it fine,, but there is no problem with decoding and then encoding in one instance of the aplication.

LastEditorDisplayName: Arthur

Body:
Are you sure an instance of form1 is created?

if yes:

Why dont you use like this:

OpenDialog.Options:=  OpenDialog.Options + [ofFileMustExist];

if OpenDialog.Execute then
  Address.Text:= OpenDialog.FileName

And use FastMM4, and define FullDebugMode in FastMM4.inc.
This may help you to find the real problem

OwnerDisplayName: Cesar Romero