问:
Numeric .csl styles causing misalignment of pdf bibliography in RMarkdown
My goal is to generate a numeric bibliography in pdf using Rmarkdown and a .csl. However, no matter which .csl file I use, the first word of the references are all slightly misaligned from each other. I suspect it has something to do with how latex justifies but I don't know it or pandoc well enough to figure it out or fix it. Ideally I'm looking for a way to fix it in Rmarkdown. As far as I can tell this doesn't happen with non-numeric styles.

MRE:

First get some numeric .csl files, as far as I can tell it happens with any of them. https://www.zotero.org/styles is a good source, good examples are Nature (nature.csl), Science (science.csl), or Biomed Central (biomed-central.csl).

Then run this to generate a sample bib:

```<code>knitr::write_bib(c("knitr", "stringr", "ggplot2"), "test.bib")
</code>```

Then knit this Rmd file:

```<code>---
title: "test"
output: pdf_document
bibliography: test.bib
csl: biomed-central.csl # whatever numeric .csl
---

# Citations

@R-ggplot2 @R-knitr @R-stringr @ggplot22016 @knitr2015 @knitr2014

# References

</code>```

Results:

With biomed-central.csl:

With nature.csl (slight but still there):

With science.csl:

I have also tried different latex engines to no avail.

sessioninfo:

```<code>R version 3.6.2 (2019-12-12)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18362)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] forcats_0.4.0   stringr_1.4.0   dplyr_0.8.3     purrr_0.3.3     readr_1.3.1     tidyr_1.0.0     tibble_2.1.3    ggplot2_3.2.1   tidyverse_1.3.0 rmarkdown_2.1.1
[11] knitr_1.27      here_0.1

loaded via a namespace (and not attached):
 [1] tinytex_0.19     tidyselect_0.2.5 xfun_0.12        haven_2.2.0      lattice_0.20-38  colorspace_1.4-1 generics_0.0.2   vctrs_0.2.1      htmltools_0.4.0  yaml_2.2.0
[11] rlang_0.4.2      pillar_1.4.3     withr_2.1.2      glue_1.3.1       DBI_1.1.0        dbplyr_1.4.2     modelr_0.1.5     readxl_1.3.1     lifecycle_0.1.0  cellranger_1.1.0
[21] munsell_0.5.0    gtable_0.3.0     rvest_0.3.5      evaluate_0.14    labeling_0.3     fansi_0.4.1      highr_0.8        broom_0.5.3      Rcpp_1.0.3       scales_1.1.0
[31] backports_1.1.5  jsonlite_1.6     farver_2.0.3     fs_1.3.1         hms_0.5.3        digest_0.6.23    stringi_1.4.4    grid_3.6.2       rprojroot_1.3-2  cli_2.0.1
[41] tools_3.6.2      magrittr_1.5     lazyeval_0.2.2   crayon_1.3.4     pkgconfig_2.0.3  zeallot_0.1.0    ellipsis_0.3.0   xml2_1.2.2       reprex_0.3.0     lubridate_1.7.4
[51] assertthat_0.2.1 httr_1.4.1       rstudioapi_0.10  R6_2.4.1         nlme_3.1-142     compiler_3.6.2
</code>```

答:
\raggedright fixes the problem:

```<code>---
title: "test"
output: pdf_document
bibliography: test.bib
csl: biomed-central.csl # whatever numeric .csl
---

# Citations

@R-ggplot2 @R-knitr @R-stringr @ggplot22016 @knitr2015 @knitr2014

\raggedright
# References
</code>```

Body:
My goal is to generate a numeric bibliography in pdf using Rmarkdown and a .csl. However, no matter which .csl file I use, the first word of the references are all slightly misaligned from each other. I suspect it has something to do with how latex justifies but I don't know it or pandoc well enough to figure it out or fix it. Ideally I'm looking for a way to fix it in Rmarkdown. As far as I can tell this doesn't happen with non-numeric styles.

MRE:

First get some numeric .csl files, as far as I can tell it happens with any of them. https://www.zotero.org/styles is a good source, good examples are Nature (nature.csl), Science (science.csl), or Biomed Central (biomed-central.csl).

Then run this to generate a sample bib:

knitr::write_bib(c("knitr", "stringr", "ggplot2"), "test.bib")

Then knit this Rmd file:

---
title: "test"
output: pdf_document
bibliography: test.bib
csl: biomed-central.csl # whatever numeric .csl
---

# Citations

@R-ggplot2 @R-knitr @R-stringr @ggplot22016 @knitr2015 @knitr2014

# References

Results:

With biomed-central.csl:

With nature.csl (slight but still there):

With science.csl:

I have also tried different latex engines to no avail.

sessioninfo:

R version 3.6.2 (2019-12-12)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18362)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] forcats_0.4.0   stringr_1.4.0   dplyr_0.8.3     purrr_0.3.3     readr_1.3.1     tidyr_1.0.0     tibble_2.1.3    ggplot2_3.2.1   tidyverse_1.3.0 rmarkdown_2.1.1
[11] knitr_1.27      here_0.1

loaded via a namespace (and not attached):
 [1] tinytex_0.19     tidyselect_0.2.5 xfun_0.12        haven_2.2.0      lattice_0.20-38  colorspace_1.4-1 generics_0.0.2   vctrs_0.2.1      htmltools_0.4.0  yaml_2.2.0
[11] rlang_0.4.2      pillar_1.4.3     withr_2.1.2      glue_1.3.1       DBI_1.1.0        dbplyr_1.4.2     modelr_0.1.5     readxl_1.3.1     lifecycle_0.1.0  cellranger_1.1.0
[21] munsell_0.5.0    gtable_0.3.0     rvest_0.3.5      evaluate_0.14    labeling_0.3     fansi_0.4.1      highr_0.8        broom_0.5.3      Rcpp_1.0.3       scales_1.1.0
[31] backports_1.1.5  jsonlite_1.6     farver_2.0.3     fs_1.3.1         hms_0.5.3        digest_0.6.23    stringi_1.4.4    grid_3.6.2       rprojroot_1.3-2  cli_2.0.1
[41] tools_3.6.2      magrittr_1.5     lazyeval_0.2.2   crayon_1.3.4     pkgconfig_2.0.3  zeallot_0.1.0    ellipsis_0.3.0   xml2_1.2.2       reprex_0.3.0     lubridate_1.7.4
[51] assertthat_0.2.1 httr_1.4.1       rstudioapi_0.10  R6_2.4.1         nlme_3.1-142     compiler_3.6.2

Body:
\raggedright fixes the problem:

---
title: "test"
output: pdf_document
bibliography: test.bib
csl: biomed-central.csl # whatever numeric .csl
---

# Citations

@R-ggplot2 @R-knitr @R-stringr @ggplot22016 @knitr2015 @knitr2014

\raggedright
# References


来源: stackexchange

问:
Regex to match Bearer token
I'm having a bad moment trying to make a regex that can find line similar to this in files :

Bearer 89abddfb-2cff-4fda-83e6-13221f0c3d4f

It should have Bearer at the begining followed by space, and the token after is the same format :
[hexadecimal, 8 char]-[hexadecimal, 4 char]-[hexadecimal, 4 char]-[hexadecimal, 4 char]-[hexadecimal, 12 char]

Any help would be very appreciated

PS: Maybe just the regex of the token format will be enough to find the token without the Bearer not sure

答: you can also use this regex ^(?i)Bearer (.*)(?-i) as it will match for lower and upper cases too.

ContentLicense: CC BY-SA 4.0

Title: Regex to match Bearer token


问:
How to convert list into json format in python
```<code>x=json.dumps(result)
print(x)
</code>```

Output:

```<code>['Client Name:'Sriram',
 'Trade Date :'03-09-2019',
 'Security :CERAMICIST-ICICLE,NAT CO - PHARMA',
 'Quantity:14,2',
 'Net Rate: 145.7500,552.3725',
 'Buy/Sell :'Buy ', 'Buy',
 'Net Total:2040.5000,1104.7450']
</code>```

and I want to convert this list into a json format like this:

```<code>{'Client Name': Sriram',
 'Trade Date' :03-09-2019',
 'Security' :['CERAMICIST-ICICLE','NAT CO - PHARMA',
 'Quantity':'14,2',
 'Net Rate':['145.7500','552.3725'],
 'Buy/Sell':['Buy','Sell',
 'Net Total':['2040.5000','1104.7450']
</code>```

答:
One Liner in Python using dict comprehension. We need to first convert it in dict using dict comprehension and then use json.dumps() to convert it to json format.

```<code>li = ['TradeDate :03-09-2019',
 'Security :ICICIPRAMCICICI500',
 'Quantity :14',
 'NetSale: 145.7500',
 'Buy/Sell :2040.5000BuyINF109KC1CZ3']

di = {i.split(':')[0]:i.split(':')[1] for i in li}
print(di)
js = json.dumps(di)
print(js)
</code>```

Outputs:

```<code>{'TradeDate ': '03-09-2019', 'Security ': 'ICICIPRAMCICICI500', 'Quantity ': '14', 'NetSale': ' 145.7500', 'Buy/Sell ': '2040.5000BuyINF109KC1CZ3'}

{"TradeDate ": "03-09-2019", "Security ": "ICICIPRAMCICICI500", "Quantity ": "14", "NetSale": " 145.7500", "Buy/Sell ": "2040.5000BuyINF109KC1CZ3"}
</code>```

Body:
x=json.dumps(result)
print(x)

Output:

['Client Name:'Sriram',
 'Trade Date :'03-09-2019',
 'Security :CERAMICIST-ICICLE,NAT CO - PHARMA',
 'Quantity:14,2',
 'Net Rate: 145.7500,552.3725',
 'Buy/Sell :'Buy ', 'Buy',
 'Net Total:2040.5000,1104.7450']

and I want to convert this list into a json format like this:

{'Client Name': Sriram',
 'Trade Date' :03-09-2019',
 'Security' :['CERAMICIST-ICICLE','NAT CO - PHARMA',
 'Quantity':'14,2',
 'Net Rate':['145.7500','552.3725'],
 'Buy/Sell':['Buy','Sell',
 'Net Total':['2040.5000','1104.7450']

Body:
One Liner in Python using dict comprehension. We need to first convert it in dict using dict comprehension and then use json.dumps() to convert it to json format.

li = ['TradeDate :03-09-2019',
 'Security :ICICIPRAMCICICI500',
 'Quantity :14',
 'NetSale: 145.7500',
 'Buy/Sell :2040.5000BuyINF109KC1CZ3']

di = {i.split(':')[0]:i.split(':')[1] for i in li}
print(di)
js = json.dumps(di)
print(js)

Outputs:

{'TradeDate ': '03-09-2019', 'Security ': 'ICICIPRAMCICICI500', 'Quantity ': '14', 'NetSale': ' 145.7500', 'Buy/Sell ': '2040.5000BuyINF109KC1CZ3'}

{"TradeDate ": "03-09-2019", "Security ": "ICICIPRAMCICICI500", "Quantity ": "14", "NetSale": " 145.7500", "Buy/Sell ": "2040.5000BuyINF109KC1CZ3"}


问:
spring: customizing the authorizationEndpoint (OAuth2)
I am trying to customize the code of the spring oauth authorization server.
for now I have just copied the framework authorizationEndpoint code and placed it in another class. I just changed the address mapping to /custom/oauth/authorize. I have also added @Controller before the class declaration otherwise this code will not be used at all:

```<code>@Controller
//@Order(Ordered.HIGHEST_PRECEDENCE)
@SessionAttributes("authorizationRequest")

public class AuthorizationEndpointCustom extends AuthorizationEndpoint {

    @Autowired
    private AuthenticationManager authenticationManager;

    private AuthorizationCodeServices authorizationCodeServices = new InMemoryAuthorizationCodeServices();

    private RedirectResolver redirectResolver = new DefaultRedirectResolver();

    private UserApprovalHandler userApprovalHandler = new DefaultUserApprovalHandler();

    private SessionAttributeStore sessionAttributeStore = new DefaultSessionAttributeStore();

    private OAuth2RequestValidator oauth2RequestValidator = new DefaultOAuth2RequestValidator();

    private String userApprovalPage = "forward:/oauth/confirm_access";

    private String errorPage = "forward:/oauth/error";

    private Object implicitLock = new Object();

    public void setSessionAttributeStore(SessionAttributeStore sessionAttributeStore) {
        this.sessionAttributeStore = sessionAttributeStore;
    }

    public void setErrorPage(String errorPage) {
        this.errorPage = errorPage;
    }

    @RequestMapping(value = "/oauth/authorize")
    public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters,
            SessionStatus sessionStatus, Principal principal) {

        System.out.println("\n\ninside custom authorization endpoint");

        // Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should
        // query off of the authorization request instead of referring back to the parameters map. The contents of the
        // parameters map will be stored without change in the AuthorizationRequest object once it is created.
        AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters);

        Set<String> responseTypes = authorizationRequest.getResponseTypes();

        if (!responseTypes.contains("token") && !responseTypes.contains("code")) {
            throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
        }

        if (authorizationRequest.getClientId() == null) {
            throw new InvalidClientException("A client id must be provided");
        }

        try {

            if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) {
                throw new InsufficientAuthenticationException(
                        "User must be authenticated with Spring Security before authorization can be completed.");
            }

            ClientDetails client = getClientDetailsService().loadClientByClientId(authorizationRequest.getClientId());

            // The resolved redirect URI is either the redirect_uri from the parameters or the one from
            // clientDetails. Either way we need to store it on the AuthorizationRequest.
            String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
            String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);
            if (!StringUtils.hasText(resolvedRedirect)) {
                throw new RedirectMismatchException(
                        "A redirectUri must be either supplied or preconfigured in the ClientDetails");
            }
            authorizationRequest.setRedirectUri(resolvedRedirect);

            // We intentionally only validate the parameters requested by the client (ignoring any data that may have
            // been added to the request by the manager).
            oauth2RequestValidator.validateScope(authorizationRequest, client);

            // Some systems may allow for approval decisions to be remembered or approved by default. Check for
            // such logic here, and set the approved flag on the authorization request accordingly.
            authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest,
                    (Authentication) principal);
            // TODO: is this call necessary?
            boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
            authorizationRequest.setApproved(approved);

            // Validation is all done, so we can check for auto approval...
            if (authorizationRequest.isApproved()) {
                if (responseTypes.contains("token")) {
                    return getImplicitGrantResponse(authorizationRequest);
                }
                if (responseTypes.contains("code")) {
                    return new ModelAndView(getAuthorizationCodeResponse(authorizationRequest,
                            (Authentication) principal));
                }
            }

            // Place auth request into the model so that it is stored in the session
            // for approveOrDeny to use. That way we make sure that auth request comes from the session,
            // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session.
            model.put("authorizationRequest", authorizationRequest);

            return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal);

        }
        catch (RuntimeException e) {
            sessionStatus.setComplete();
            throw e;
        }

    }

    private OAuth2AccessToken getAccessTokenForImplicitGrant(TokenRequest tokenRequest,
            OAuth2Request storedOAuth2Request) {
        OAuth2AccessToken accessToken = null;
        // These 1 method calls have to be atomic, otherwise the ImplicitGrantService can have a race condition where
        // one thread removes the token request before another has a chance to redeem it.
        synchronized (this.implicitLock) {
            accessToken = getTokenGranter().grant("implicit",
                    new ImplicitTokenRequest(tokenRequest, storedOAuth2Request));
        }
        return accessToken;
    }

.
.
.
</code>```

I have also instructed the framework to change the mappring from /oauth/authorize to /custom/oauth/authorize:

```<code>@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

    endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore())
            .accessTokenConverter(tokenEnhancer()).pathMapping("/oauth/authorize", "/custom/authorize/");
}
</code>```

but when I run the code I encounter the following error:

```<code>Description:

Field tokenGranter in com.example.demo.controller.AuthorizationEndpointCustom required a bean of type 'org.springframework.security.oauth2.provider.TokenGranter' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'org.springframework.security.oauth2.provider.TokenGranter' in your configuration.
</code>```

the parent class of AuthorizationEndpoint (AbstractEndpoint) declares tokenGranter but it is not instantiated. there is no @autowired for this and other attributes of this class. who does genereate and inject these variable into this class?
how can I get hold of tokenGranter obj and inject it?

```<code>/*
 * Copyright 2002-2011 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.security.oauth2.provider.endpoint;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.util.Assert;

/**
 * @author Dave Syer
 *
 */
public class AbstractEndpoint implements InitializingBean {

    protected final Log logger = LogFactory.getLog(getClass());

    private WebResponseExceptionTranslator providerExceptionHandler = new DefaultWebResponseExceptionTranslator();

    private TokenGranter tokenGranter;

    private ClientDetailsService clientDetailsService;

    private OAuth2RequestFactory oAuth2RequestFactory;

    private OAuth2RequestFactory defaultOAuth2RequestFactory;

    public void afterPropertiesSet() throws Exception {
        Assert.state(tokenGranter != null, "TokenGranter must be provided");
        Assert.state(clientDetailsService != null, "ClientDetailsService must be provided");
        defaultOAuth2RequestFactory = new DefaultOAuth2RequestFactory(getClientDetailsService());
        if (oAuth2RequestFactory == null) {
            oAuth2RequestFactory = defaultOAuth2RequestFactory;
        }
    }

    public void setProviderExceptionHandler(WebResponseExceptionTranslator providerExceptionHandler) {
        this.providerExceptionHandler = providerExceptionHandler;
    }

    public void setTokenGranter(TokenGranter tokenGranter) {
        this.tokenGranter = tokenGranter;
    }

    protected TokenGranter getTokenGranter() {
        return tokenGranter;
    }

    protected WebResponseExceptionTranslator getExceptionTranslator() {
        return providerExceptionHandler;
    }

    protected OAuth2RequestFactory getOAuth2RequestFactory() {
        return oAuth2RequestFactory;
    }

    protected OAuth2RequestFactory getDefaultOAuth2RequestFactory() {
        return defaultOAuth2RequestFactory;
    }

    public void setOAuth2RequestFactory(OAuth2RequestFactory oAuth2RequestFactory) {
        this.oAuth2RequestFactory = oAuth2RequestFactory;
    }

    protected ClientDetailsService getClientDetailsService() {
        return clientDetailsService;
    }

    public void setClientDetailsService(ClientDetailsService clientDetailsService) {
        this.clientDetailsService = clientDetailsService;
    }

}
</code>```

答:
I am answering my own question.
I took a good look at the framework code and I found out that AuthorizationServerEndpointsConfiguration class creates an object of type AuthorizationEndpoint and populates it's attributes and then return this object as a bean.
I managed to solve above mentioned problem with TokenGranter by creating a bean of my new AuthorizationEndpointCustom the same way AuthorizationServerEndpointsConfiguration does. this is the code to do so:

```<code>@Autowired
private ClientDetailsService clientDetailsService;

@Autowired
AuthorizationServerEndpointsConfiguration asec;

@Bean
@Order(value = Ordered.HIGHEST_PRECEDENCE)
@Primary
public AuthorizationEndpoint authorizationEndpoint () throws Exception{

    AuthorizationEndpointCustom authorizationEndpoint = new AuthorizationEndpointCustom();
    FrameworkEndpointHandlerMapping mapping = asec.getEndpointsConfigurer().getFrameworkEndpointHandlerMapping();
    authorizationEndpoint.setUserApprovalPage(extractPath(mapping, "/oauth/confirm_access"));
    authorizationEndpoint.setProviderExceptionHandler(asec.getEndpointsConfigurer().getExceptionTranslator());
    authorizationEndpoint.setErrorPage(extractPath(mapping, "/oauth/error"));
    authorizationEndpoint.setTokenGranter(asec.getEndpointsConfigurer().getTokenGranter());
    authorizationEndpoint.setClientDetailsService(clientDetailsService);
    authorizationEndpoint.setAuthorizationCodeServices(asec.getEndpointsConfigurer().getAuthorizationCodeServices());
    authorizationEndpoint.setOAuth2RequestFactory(asec.getEndpointsConfigurer().getOAuth2RequestFactory());
    authorizationEndpoint.setOAuth2RequestValidator(asec.getEndpointsConfigurer().getOAuth2RequestValidator());
    authorizationEndpoint.setUserApprovalHandler(asec.getEndpointsConfigurer().getUserApprovalHandler());

    return authorizationEndpoint;
}

private String extractPath(FrameworkEndpointHandlerMapping mapping, String page) {
    String path = mapping.getPath(page);
    if (path.contains(":")) {
        return path;
    }
    return "forward:" + path;
}
</code>```

but this did not result in what I hoped to. the new bean does not replace the bean from framework code. this situation with overriding beans led to another question:
how replace framework beans

buttom line, this is not the way to override the framework endpoints. you can simply create a controller with mappings for these endpoints (e.g /oauth/authorize or /oauth/token). automatically these mappings will get precedence over framework endpoints. for more info refer to spring doc

Body:
I am trying to customize the code of the spring oauth authorization server.
for now I have just copied the framework authorizationEndpoint code and placed it in another class. I just changed the address mapping to /custom/oauth/authorize. I have also added @Controller before the class declaration otherwise this code will not be used at all:

@Controller
//@Order(Ordered.HIGHEST_PRECEDENCE)
@SessionAttributes("authorizationRequest")

public class AuthorizationEndpointCustom extends AuthorizationEndpoint {

    @Autowired
    private AuthenticationManager authenticationManager;

    private AuthorizationCodeServices authorizationCodeServices = new InMemoryAuthorizationCodeServices();

    private RedirectResolver redirectResolver = new DefaultRedirectResolver();

    private UserApprovalHandler userApprovalHandler = new DefaultUserApprovalHandler();

    private SessionAttributeStore sessionAttributeStore = new DefaultSessionAttributeStore();

    private OAuth2RequestValidator oauth2RequestValidator = new DefaultOAuth2RequestValidator();

    private String userApprovalPage = "forward:/oauth/confirm_access";

    private String errorPage = "forward:/oauth/error";

    private Object implicitLock = new Object();

    public void setSessionAttributeStore(SessionAttributeStore sessionAttributeStore) {
        this.sessionAttributeStore = sessionAttributeStore;
    }

    public void setErrorPage(String errorPage) {
        this.errorPage = errorPage;
    }

    @RequestMapping(value = "/oauth/authorize")
    public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters,
            SessionStatus sessionStatus, Principal principal) {

        System.out.println("\n\ninside custom authorization endpoint");

        // Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should
        // query off of the authorization request instead of referring back to the parameters map. The contents of the
        // parameters map will be stored without change in the AuthorizationRequest object once it is created.
        AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters);

        Set<String> responseTypes = authorizationRequest.getResponseTypes();

        if (!responseTypes.contains("token") && !responseTypes.contains("code")) {
            throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
        }

        if (authorizationRequest.getClientId() == null) {
            throw new InvalidClientException("A client id must be provided");
        }

        try {

            if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) {
                throw new InsufficientAuthenticationException(
                        "User must be authenticated with Spring Security before authorization can be completed.");
            }

            ClientDetails client = getClientDetailsService().loadClientByClientId(authorizationRequest.getClientId());

            // The resolved redirect URI is either the redirect_uri from the parameters or the one from
            // clientDetails. Either way we need to store it on the AuthorizationRequest.
            String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
            String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);
            if (!StringUtils.hasText(resolvedRedirect)) {
                throw new RedirectMismatchException(
                        "A redirectUri must be either supplied or preconfigured in the ClientDetails");
            }
            authorizationRequest.setRedirectUri(resolvedRedirect);

            // We intentionally only validate the parameters requested by the client (ignoring any data that may have
            // been added to the request by the manager).
            oauth2RequestValidator.validateScope(authorizationRequest, client);

            // Some systems may allow for approval decisions to be remembered or approved by default. Check for
            // such logic here, and set the approved flag on the authorization request accordingly.
            authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest,
                    (Authentication) principal);
            // TODO: is this call necessary?
            boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
            authorizationRequest.setApproved(approved);

            // Validation is all done, so we can check for auto approval...
            if (authorizationRequest.isApproved()) {
                if (responseTypes.contains("token")) {
                    return getImplicitGrantResponse(authorizationRequest);
                }
                if (responseTypes.contains("code")) {
                    return new ModelAndView(getAuthorizationCodeResponse(authorizationRequest,
                            (Authentication) principal));
                }
            }

            // Place auth request into the model so that it is stored in the session
            // for approveOrDeny to use. That way we make sure that auth request comes from the session,
            // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session.
            model.put("authorizationRequest", authorizationRequest);

            return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal);

        }
        catch (RuntimeException e) {
            sessionStatus.setComplete();
            throw e;
        }

    }

    private OAuth2AccessToken getAccessTokenForImplicitGrant(TokenRequest tokenRequest,
            OAuth2Request storedOAuth2Request) {
        OAuth2AccessToken accessToken = null;
        // These 1 method calls have to be atomic, otherwise the ImplicitGrantService can have a race condition where
        // one thread removes the token request before another has a chance to redeem it.
        synchronized (this.implicitLock) {
            accessToken = getTokenGranter().grant("implicit",
                    new ImplicitTokenRequest(tokenRequest, storedOAuth2Request));
        }
        return accessToken;
    }

.
.
.

I have also instructed the framework to change the mappring from /oauth/authorize to /custom/oauth/authorize:

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

    endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore())
            .accessTokenConverter(tokenEnhancer()).pathMapping("/oauth/authorize", "/custom/authorize/");
}

but when I run the code I encounter the following error:

Description:

Field tokenGranter in com.example.demo.controller.AuthorizationEndpointCustom required a bean of type 'org.springframework.security.oauth2.provider.TokenGranter' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'org.springframework.security.oauth2.provider.TokenGranter' in your configuration.

the parent class of AuthorizationEndpoint (AbstractEndpoint) declares tokenGranter but it is not instantiated. there is no @autowired for this and other attributes of this class. who does genereate and inject these variable into this class?
how can I get hold of tokenGranter obj and inject it?

/*
 * Copyright 2002-2011 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.security.oauth2.provider.endpoint;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.util.Assert;

/**
 * @author Dave Syer
 *
 */
public class AbstractEndpoint implements InitializingBean {

    protected final Log logger = LogFactory.getLog(getClass());

    private WebResponseExceptionTranslator providerExceptionHandler = new DefaultWebResponseExceptionTranslator();

    private TokenGranter tokenGranter;

    private ClientDetailsService clientDetailsService;

    private OAuth2RequestFactory oAuth2RequestFactory;

    private OAuth2RequestFactory defaultOAuth2RequestFactory;

    public void afterPropertiesSet() throws Exception {
        Assert.state(tokenGranter != null, "TokenGranter must be provided");
        Assert.state(clientDetailsService != null, "ClientDetailsService must be provided");
        defaultOAuth2RequestFactory = new DefaultOAuth2RequestFactory(getClientDetailsService());
        if (oAuth2RequestFactory == null) {
            oAuth2RequestFactory = defaultOAuth2RequestFactory;
        }
    }

    public void setProviderExceptionHandler(WebResponseExceptionTranslator providerExceptionHandler) {
        this.providerExceptionHandler = providerExceptionHandler;
    }

    public void setTokenGranter(TokenGranter tokenGranter) {
        this.tokenGranter = tokenGranter;
    }

    protected TokenGranter getTokenGranter() {
        return tokenGranter;
    }

    protected WebResponseExceptionTranslator getExceptionTranslator() {
        return providerExceptionHandler;
    }

    protected OAuth2RequestFactory getOAuth2RequestFactory() {
        return oAuth2RequestFactory;
    }

    protected OAuth2RequestFactory getDefaultOAuth2RequestFactory() {
        return defaultOAuth2RequestFactory;
    }

    public void setOAuth2RequestFactory(OAuth2RequestFactory oAuth2RequestFactory) {
        this.oAuth2RequestFactory = oAuth2RequestFactory;
    }

    protected ClientDetailsService getClientDetailsService() {
        return clientDetailsService;
    }

    public void setClientDetailsService(ClientDetailsService clientDetailsService) {
        this.clientDetailsService = clientDetailsService;
    }

}

Body:
I am answering my own question.
I took a good look at the framework code and I found out that AuthorizationServerEndpointsConfiguration class creates an object of type AuthorizationEndpoint and populates it's attributes and then return this object as a bean.
I managed to solve above mentioned problem with TokenGranter by creating a bean of my new AuthorizationEndpointCustom the same way AuthorizationServerEndpointsConfiguration does. this is the code to do so:

@Autowired
private ClientDetailsService clientDetailsService;

@Autowired
AuthorizationServerEndpointsConfiguration asec;

@Bean
@Order(value = Ordered.HIGHEST_PRECEDENCE)
@Primary
public AuthorizationEndpoint authorizationEndpoint () throws Exception{

    AuthorizationEndpointCustom authorizationEndpoint = new AuthorizationEndpointCustom();
    FrameworkEndpointHandlerMapping mapping = asec.getEndpointsConfigurer().getFrameworkEndpointHandlerMapping();
    authorizationEndpoint.setUserApprovalPage(extractPath(mapping, "/oauth/confirm_access"));
    authorizationEndpoint.setProviderExceptionHandler(asec.getEndpointsConfigurer().getExceptionTranslator());
    authorizationEndpoint.setErrorPage(extractPath(mapping, "/oauth/error"));
    authorizationEndpoint.setTokenGranter(asec.getEndpointsConfigurer().getTokenGranter());
    authorizationEndpoint.setClientDetailsService(clientDetailsService);
    authorizationEndpoint.setAuthorizationCodeServices(asec.getEndpointsConfigurer().getAuthorizationCodeServices());
    authorizationEndpoint.setOAuth2RequestFactory(asec.getEndpointsConfigurer().getOAuth2RequestFactory());
    authorizationEndpoint.setOAuth2RequestValidator(asec.getEndpointsConfigurer().getOAuth2RequestValidator());
    authorizationEndpoint.setUserApprovalHandler(asec.getEndpointsConfigurer().getUserApprovalHandler());

    return authorizationEndpoint;
}

private String extractPath(FrameworkEndpointHandlerMapping mapping, String page) {
    String path = mapping.getPath(page);
    if (path.contains(":")) {
        return path;
    }
    return "forward:" + path;
}

but this did not result in what I hoped to. the new bean does not replace the bean from framework code. this situation with overriding beans led to another question:
how replace framework beans

buttom line, this is not the way to override the framework endpoints. you can simply create a controller with mappings for these endpoints (e.g /oauth/authorize or /oauth/token). automatically these mappings will get precedence over framework endpoints. for more info refer to spring doc


问:
What is the right way to get an NSString object from an NSArray, keeping Memory Managment in mind?
What is the right way to get an NSString object from an NSArray,  keeping Memory Managment in mind.

Suppose I have an array

```<code>NSArray *myNewArray = [[NSArray alloc] initWithObjects:.......];
</code>```

Now I want to get an object from this NSArray at index 2.

```<code>NSString *nameString = [myNewArray objectAtIndex:2]; // is it the right way? how to deal with "nameString"
                                                     // now regarding memory managment, should I release it ?
</code>```

OR I should first alloc nameString and then assign value to it ?

答:
There is no need to allocate or initialize NSString object and after all if you are not allocating any memory then there is no need to release....Only release NSArray objects nothing else....

You are going through right way...

ContentLicense: CC BY-SA 3.0

Body:
What is the right way to get an NSString object from an NSArray,  keeping Memory Managment in mind.

Suppose I have an array

NSArray *myNewArray = [[NSArray alloc] initWithObjects:.......];

Now I want to get an object from this NSArray at index 2.

NSString *nameString = [myNewArray objectAtIndex:2]; // is it the right way? how to deal with "nameString"
                                                     // now regarding memory managment, should I release it ?

OR I should first alloc nameString and then assign value to it ?


问:
Warning on Kubeadm init - No validator is available
I'm trying to setup a minimum viable kubernetes cluster using kubeadm.
On invoking kubeadm init command i'm getting following warning.

W0218 23:13:59.411414   25332 validation.go:28] Cannot validate
  kube-proxy config - no validator is available

W0218 23:13:59.411496   25332 validation.go:28] Cannot validate
  kubelet config - no validator is available

What this exactly this warning means? Where can i find these validators?

I've gone through couple of links and everyone suggesting to ignore it. But i would really like to know why this warning coming up

答:
It's a known issue

Define policy around klog.Warning usage in kubeadm #1913

And there is a workaround:

Try kubeadm reset

Manual: kubeadm reset - Kubernetes

kubeadm reset

pls note:

The reset process does not clean CNI configuration. To do so, you must remove /etc/cni/net.d

The reset process does not reset or clean up iptables rules or IPVS tables.
  If you wish to reset iptables, you must do so manually by using the "iptables" command.

If your cluster was setup to utilize IPVS, run ipvsadm --clear (or similar)
  to reset your system's IPVS tables.

If it doesn't help, you may hide warnings from console out

polarapfel recommends to hide warnings :)

Here's a quick fix to folks being thrown off by this behaviour in their automation scripts: redirect stderr to /dev/null (or elsewhere).

For example, if you wanted the join command, you'd do this

kubeadm token create --print-join-command 2>/dev/null


答:
As I have mentioned in comment, your result is not a valid JSON.

Let me have these assumption:

You have a list of string, and for each string it is in form of key : value

You want a JSON string like

```<code>{ "key1" : "value1",
  "key2" : "value2",...}
</code>```

(i.e. all key and values are string)

You could just construct a dict, with each line in the list become an entry of dict, and then use json.dumps.

If you need to preserve the type of the value (e.g. 123 should be a number instead of string:  "key1" : 123), then it is more complicated: you may need to check the format of the value and convert it to correct type

Another choice is, as key: value is a valid entry in YAML (note the missing double quote and the space after colon), you can do simple massaging in your message and construct a yaml string, use yaml parser to parse it to a dict, and then use json parser to construct a json string.  Something like:

```<code>import yaml
import json
l = [ "a:b", "c: 123", "d: true"]
result = json.dumps(
            yaml.load("\n".join(
                      [ t[0] + ": " + t[1] for t in
                          [ s.split(":", 1) for s in l]
                      ])))
# result string is '{"a": "b", "c": 123, "d": true}'
</code>```

Title: How to convert list into json format in python

Body:
As I have mentioned in comment, your result is not a valid JSON.

Let me have these assumption:

You have a list of string, and for each string it is in form of key : value

You want a JSON string like

{ "key1" : "value1",
  "key2" : "value2",...}

(i.e. all key and values are string)

You could just construct a dict, with each line in the list become an entry of dict, and then use json.dumps.

If you need to preserve the type of the value (e.g. 123 should be a number instead of string:  "key1" : 123), then it is more complicated: you may need to check the format of the value and convert it to correct type

Another choice is, as key: value is a valid entry in YAML (note the missing double quote and the space after colon), you can do simple massaging in your message and construct a yaml string, use yaml parser to parse it to a dict, and then use json parser to construct a json string.  Something like:

import yaml
import json
l = [ "a:b", "c: 123", "d: true"]
result = json.dumps(
            yaml.load("\n".join(
                      [ t[0] + ": " + t[1] for t in
                          [ s.split(":", 1) for s in l]
                      ])))
# result string is '{"a": "b", "c": 123, "d": true}'


问:
Upload images to Azure blob from front end (React)
The front end enables people to upload their photos, so i was sending the base64 to the server and working with it initially, but there are problems with firewall which blocks the request which contains base64. As an alternative solution I was trying to upload the image to azure blob get the file name and then send that to the server for processing where I generate a sas token for the blob validation and processing.

This works perfectly fine when I work locally and the front end connection works with @azure/storage-blob
and uploadBrowserData() when I send the arrayBuffer as the param

```<code>export const uploadSelfieToBlob = async arrayBuffer => {
    try {
        const blobURL = `https://${accountName}.blob.core.windows.net${sasString}`;
        const blobServiceClient = new BlobServiceClient(blobURL, anonymousCredential);
        const containerClient = blobServiceClient.getContainerClient(containerName);
        let randomString = Math.random().toString(36).substring(7);
        const blobName = `${randomString}_${new Date().getTime()}.jpg`;
        const blockBlobClient = containerClient.getBlockBlobClient(blobName);
        const uploadBlobResponse = await blockBlobClient.uploadBrowserData(arrayBuffer);
        return { blobName, blobId: uploadBlobResponse.requestId };
    } catch (error) {
        console.log('error when uploading to blob', error);
        throw new Error('Error Uploading the selfie to blob');
    }
};
</code>```

When I deploy this is not working, the front is deployed in the EastUs2 location and the local development location is different.

I thought the sasString generated for anonymous access had the timezone option so I generated 2 different one's one for local and one for hosted server with the same location selected.

```<code> Failed to send request to https://xxxx.blob.core.windows.net/contanainer-name/26pcie_1582087489288.jpg?sv=2019-02-02&ss=b&srt=c&sp=rwdlac&se=2023-09-11T07:57:29Z&st=2020-02-18T00:57:29Z&spr=https&sig=9IWhXo5i%2B951%2F8%2BTDqIY5MRXbumQasOnY4%2Bju%2BqF3gw%3D
</code>```

What am I missing any lead would be helpful thanks

答:
I couldn't notice anything wrong with the code you mentioned about, but I have been using a different method to upload files to Azure Blog Storage using React, the method is exactly the same as in this blog article which works perfectly for me.
https://medium.com/@stuarttottle/upload-to-azure-blob-storage-with-react-34f37805fdfc </p>

Body:
The front end enables people to upload their photos, so i was sending the base64 to the server and working with it initially, but there are problems with firewall which blocks the request which contains base64. As an alternative solution I was trying to upload the image to azure blob get the file name and then send that to the server for processing where I generate a sas token for the blob validation and processing.

This works perfectly fine when I work locally and the front end connection works with @azure/storage-blob
and uploadBrowserData() when I send the arrayBuffer as the param

export const uploadSelfieToBlob = async arrayBuffer => {
    try {
        const blobURL = `https://${accountName}.blob.core.windows.net${sasString}`;
        const blobServiceClient = new BlobServiceClient(blobURL, anonymousCredential);
        const containerClient = blobServiceClient.getContainerClient(containerName);
        let randomString = Math.random().toString(36).substring(7);
        const blobName = `${randomString}_${new Date().getTime()}.jpg`;
        const blockBlobClient = containerClient.getBlockBlobClient(blobName);
        const uploadBlobResponse = await blockBlobClient.uploadBrowserData(arrayBuffer);
        return { blobName, blobId: uploadBlobResponse.requestId };
    } catch (error) {
        console.log('error when uploading to blob', error);
        throw new Error('Error Uploading the selfie to blob');
    }
};

When I deploy this is not working, the front is deployed in the EastUs2 location and the local development location is different.

I thought the sasString generated for anonymous access had the timezone option so I generated 2 different one's one for local and one for hosted server with the same location selected.

 Failed to send request to https://xxxx.blob.core.windows.net/contanainer-name/26pcie_1582087489288.jpg?sv=2019-02-02&ss=b&srt=c&sp=rwdlac&se=2023-09-11T07:57:29Z&st=2020-02-18T00:57:29Z&spr=https&sig=9IWhXo5i%2B951%2F8%2BTDqIY5MRXbumQasOnY4%2Bju%2BqF3gw%3D

What am I missing any lead would be helpful thanks


问:
Run git log from different directory
I want to start git-bash.exe, and run git log from different directory.

I tried something like this:

```<code>"C:/Program Files/Git/git-bash.exe" log -- C:\repos\foo
</code>```

and this

```<code>"C:\Program Files\Git\git-bash.exe" --cd=C:\repos\foo log
</code>```

But none of theese works. Any ideas?

答:
I just tested, in a regular CMD session (no bash):

```<code>git -C C:\path\to\repo log
</code>```

It does work just fine, using the -C option I presented here, introduced in Git 1.8.5 (Q4 2013).

Title: Run git log from different directory

Body:
I want to start git-bash.exe, and run git log from different directory.

I tried something like this:

"C:/Program Files/Git/git-bash.exe" log -- C:\repos\foo

and this

"C:\Program Files\Git\git-bash.exe" --cd=C:\repos\foo log

But none of theese works. Any ideas?

Body:
I just tested, in a regular CMD session (no bash):

git -C C:\path\to\repo log

It does work just fine, using the -C option I presented here, introduced in Git 1.8.5 (Q4 2013).


问:
What is the difference between std::set and std::vector?
I am learning STL now. I read about set container. I have question when you want to use set? After reading description of set it looks like it is useless because we can substitute it by vector. Could you say pros and cos for vector vs set containers. Thanks

答:
The simple difference is that set can contain only unique values, and it is sorted. So you can use it for the cases where you need to continuously sort the values after every insert / delete.

```<code>set<int> a;
vector<int> b;
for (int i = 0; i < 10; ++i)
{
    int val = rand() % 10;
    a.insert(val);
    b.push_back(val);
}
cout << "--SET---\n"; for (auto i : a) cout << i << ","; cout << endl;
cout << "--VEC---\n"; for (auto j : b) cout << j << ","; cout << endl;
</code>```

The output is

```<code>--SET---
0,1,2,4,7,8,9,
--VEC---
1,7,4,0,9,4,8,8,2,4,
</code>```

Body:
The simple difference is that set can contain only unique values, and it is sorted. So you can use it for the cases where you need to continuously sort the values after every insert / delete.

set<int> a;
vector<int> b;
for (int i = 0; i < 10; ++i)
{
    int val = rand() % 10;
    a.insert(val);
    b.push_back(val);
}
cout << "--SET---\n"; for (auto i : a) cout << i << ","; cout << endl;
cout << "--VEC---\n"; for (auto j : b) cout << j << ","; cout << endl;

The output is

--SET---
0,1,2,4,7,8,9,
--VEC---
1,7,4,0,9,4,8,8,2,4,


问:
HTML keeping images inside row without overflowing it

```<code><div class="fluid-container">
  <div class="row" style="height: 100%;">
    <div repeat.for="pw of lstPainelWidgets" class="col ${getPanelCol($index)} p-0">
        <img class="my-img" src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1"
        width="100%" height="100%">
    </div>
</div>
</code>```

I'm trying to keep 4 images (which must be in a single row) inside a fluid-container div but my images keep overflowing it. The goal is for the images to adapt to the container (like object-fit: contain) and fill it, instead of ignoring its max-height limits.

I already tried img-fluid, img-responsive, max-height: 100%, but the images ignore all these options and keep overflowing both the row div and the fluid container!

答:
Try to use max-width and max-height instead of height and width.

```<code><div class="fluid-container">
  <div class="row" style="height: 100%;">
    <div repeat.for="pw of lstPainelWidgets" class="col ${getPanelCol($index)} p-0">
        <img class="my-img" src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" max-width="100%" max-height="100%">
      <img class="my-img " src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" max-width="100%" max-height="100%">
      <img class="my-img" src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" max-width="100%" max-height="100%">
    </div>
</div>
</code>```

by using flex you can also...

```<code><div cass="container">
    <div class="d-flex ">
      <div class="p-2 flex-fill bd-highlight">
        <img class="my-img img-fluid" src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" max-width="100%" max-height="100%">
       </div>
      <div class="p-2 flex-fill bd-highlight">
        <img class="my-img img-fluid" src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" max-width="100%" max-height="100%">
       </div>
      <div class="p-2 flex-fill bd-highlight">
        <img class="my-img img-fluid" src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" max-width="100%" max-height="100%">
       </div>
      <div class="p-2 flex-fill bd-highlight">
        <img class="my-img img-fluid" src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" max-width="100%" max-height="100%">
       </div>
    </div>
  </div>
</code>```

Body:
Try to use max-width and max-height instead of height and width.

<div class="fluid-container">
  <div class="row" style="height: 100%;">
    <div repeat.for="pw of lstPainelWidgets" class="col ${getPanelCol($index)} p-0">
        <img class="my-img" src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" max-width="100%" max-height="100%">
      <img class="my-img " src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" max-width="100%" max-height="100%">
      <img class="my-img" src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" max-width="100%" max-height="100%">
    </div>
</div>

by using flex you can also...

<div cass="container">
    <div class="d-flex ">
      <div class="p-2 flex-fill bd-highlight">
        <img class="my-img img-fluid" src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" max-width="100%" max-height="100%">
       </div>
      <div class="p-2 flex-fill bd-highlight">
        <img class="my-img img-fluid" src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" max-width="100%" max-height="100%">
       </div>
      <div class="p-2 flex-fill bd-highlight">
        <img class="my-img img-fluid" src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" max-width="100%" max-height="100%">
       </div>
      <div class="p-2 flex-fill bd-highlight">
        <img class="my-img img-fluid" src="https://techcrunch.com/wp-content/uploads/2017/11/graphdown.jpg?w=730&crop=1" max-width="100%" max-height="100%">
       </div>
    </div>
  </div>


问:
ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[FormBuilder]
in my angular app when I add routes in gifts-routing.module.ts this error appears
and when i remove the routes it works
but i still need to route
so how can i solve this error

```<code>ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[FormBuilder]:
  StaticInjectorError(Platform: core)[FormBuilder]:
    NullInjectorError: No provider for FormBuilder!
NullInjectorError: StaticInjectorError(AppModule)[FormBuilder]:
  StaticInjectorError(Platform: core)[FormBuilder]:
    NullInjectorError: No provider for FormBuilder!
</code>```

gifts.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { GiftsRoutingModule } from './gifts-routing.module';
import { GiftListComponent } from './components/gift-list/gift-list.component';
import { GiftFormComponent } from './components/gift-form/gift-form.component';
import { SharedModule } from '../shared/shared.module';

@NgModule({
  declarations: [GiftListComponent, GiftFormComponent],
  imports: [
    CommonModule,
    GiftsRoutingModule,
    SharedModule
  ]
})
export class GiftsModule { }
</code>```

gifts-routing.module.ts

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LayoutComponent } from '../shared/components/layout/layout.component';
import { GiftListComponent } from './components/gift-list/gift-list.component';

const routes: Routes = [
  {
    path: '',
    component: LayoutComponent,
    children: [
      {
        path:'',
        component: GiftListComponent
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class GiftsRoutingModule { }
</code>```

and I also import the ReactiveFormsModule and FormsModule inside my shared module

shared.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { SharedRoutingModule } from './shared-routing.module';
import { LayoutComponent } from './components/layout/layout.component';
import { NavbarComponent } from './components/layout/navbar/navbar.component';

import { ReactiveFormsModule, FormsModule } from '@angular/forms'
import {
  MatButtonModule,
  MatCardModule,
  MatInputModule,
  MatIconModule,
  MatTabsModule,
  MatTableModule,
  MatPaginatorModule,
  MatSortModule,
  MatProgressSpinnerModule,
  MatSlideToggleModule,
  MatDialogModule,
  MatSelectModule,
  MatDatepickerModule,
  MatToolbarModule,
  MatListModule,
  MatMenuModule,
  MatSidenavModule,
  MatTooltipModule,
  MatRadioModule,
  MatStepperModule,
  MatCheckboxModule,
  MatExpansionModule,
  MatProgressBarModule,
  MatNativeDateModule,
} from '@angular/material';
import { RouterModule } from '@angular/router';
import { FloatingButtonComponent } from './components/floating-button/floating-button.component';
import { ConfirmComponent } from './components/confirm/confirm.component';
@NgModule({
  declarations: [LayoutComponent, NavbarComponent, FloatingButtonComponent, ConfirmComponent],
  imports: [
    CommonModule,
    SharedRoutingModule,
    ReactiveFormsModule,
    RouterModule,
    FormsModule,
    CommonModule,
    MatButtonModule,
    MatMenuModule,
    MatSidenavModule,
    MatListModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule,
    MatTabsModule,
    MatInputModule,
    MatTableModule,
    MatPaginatorModule,
    MatSortModule,
    MatProgressSpinnerModule,
    MatSlideToggleModule,
    MatDialogModule,
    MatSelectModule,
    MatDatepickerModule,
    MatProgressBarModule,
    MatTooltipModule,
    MatRadioModule,
    MatStepperModule,
    MatCheckboxModule,
    MatExpansionModule,
    MatNativeDateModule,

  ],
  exports: [
    CommonModule,
    ReactiveFormsModule,
    RouterModule,
    FormsModule,
    CommonModule,
    MatButtonModule,
    MatMenuModule,
    MatSidenavModule,
    MatListModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule,
    MatTabsModule,
    MatInputModule,
    MatTableModule,
    MatPaginatorModule,
    MatSortModule,
    MatProgressSpinnerModule,
    MatSlideToggleModule,
    MatDialogModule,
    MatSelectModule,
    MatDatepickerModule,
    MatProgressBarModule,
    MatTooltipModule,
    MatRadioModule,
    MatStepperModule,
    MatCheckboxModule,
    MatExpansionModule,
  ],
  entryComponents: [ConfirmComponent]
})
export class SharedModule {

}
</code>```

what I should do to solve this error, please?

答:
You need to move the imports shared module to main module
FormsModule and ReactiveFormsModule do not work as shared module.

Body:
in my angular app when I add routes in gifts-routing.module.ts this error appears
and when i remove the routes it works
but i still need to route
so how can i solve this error

ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[FormBuilder]:
  StaticInjectorError(Platform: core)[FormBuilder]:
    NullInjectorError: No provider for FormBuilder!
NullInjectorError: StaticInjectorError(AppModule)[FormBuilder]:
  StaticInjectorError(Platform: core)[FormBuilder]:
    NullInjectorError: No provider for FormBuilder!

gifts.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { GiftsRoutingModule } from './gifts-routing.module';
import { GiftListComponent } from './components/gift-list/gift-list.component';
import { GiftFormComponent } from './components/gift-form/gift-form.component';
import { SharedModule } from '../shared/shared.module';

@NgModule({
  declarations: [GiftListComponent, GiftFormComponent],
  imports: [
    CommonModule,
    GiftsRoutingModule,
    SharedModule
  ]
})
export class GiftsModule { }

gifts-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LayoutComponent } from '../shared/components/layout/layout.component';
import { GiftListComponent } from './components/gift-list/gift-list.component';

const routes: Routes = [
  {
    path: '',
    component: LayoutComponent,
    children: [
      {
        path:'',
        component: GiftListComponent
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class GiftsRoutingModule { }

and I also import the ReactiveFormsModule and FormsModule inside my shared module

shared.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { SharedRoutingModule } from './shared-routing.module';
import { LayoutComponent } from './components/layout/layout.component';
import { NavbarComponent } from './components/layout/navbar/navbar.component';

import { ReactiveFormsModule, FormsModule } from '@angular/forms'
import {
  MatButtonModule,
  MatCardModule,
  MatInputModule,
  MatIconModule,
  MatTabsModule,
  MatTableModule,
  MatPaginatorModule,
  MatSortModule,
  MatProgressSpinnerModule,
  MatSlideToggleModule,
  MatDialogModule,
  MatSelectModule,
  MatDatepickerModule,
  MatToolbarModule,
  MatListModule,
  MatMenuModule,
  MatSidenavModule,
  MatTooltipModule,
  MatRadioModule,
  MatStepperModule,
  MatCheckboxModule,
  MatExpansionModule,
  MatProgressBarModule,
  MatNativeDateModule,
} from '@angular/material';
import { RouterModule } from '@angular/router';
import { FloatingButtonComponent } from './components/floating-button/floating-button.component';
import { ConfirmComponent } from './components/confirm/confirm.component';
@NgModule({
  declarations: [LayoutComponent, NavbarComponent, FloatingButtonComponent, ConfirmComponent],
  imports: [
    CommonModule,
    SharedRoutingModule,
    ReactiveFormsModule,
    RouterModule,
    FormsModule,
    CommonModule,
    MatButtonModule,
    MatMenuModule,
    MatSidenavModule,
    MatListModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule,
    MatTabsModule,
    MatInputModule,
    MatTableModule,
    MatPaginatorModule,
    MatSortModule,
    MatProgressSpinnerModule,
    MatSlideToggleModule,
    MatDialogModule,
    MatSelectModule,
    MatDatepickerModule,
    MatProgressBarModule,
    MatTooltipModule,
    MatRadioModule,
    MatStepperModule,
    MatCheckboxModule,
    MatExpansionModule,
    MatNativeDateModule,

  ],
  exports: [
    CommonModule,
    ReactiveFormsModule,
    RouterModule,
    FormsModule,
    CommonModule,
    MatButtonModule,
    MatMenuModule,
    MatSidenavModule,
    MatListModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule,
    MatTabsModule,
    MatInputModule,
    MatTableModule,
    MatPaginatorModule,
    MatSortModule,
    MatProgressSpinnerModule,
    MatSlideToggleModule,
    MatDialogModule,
    MatSelectModule,
    MatDatepickerModule,
    MatProgressBarModule,
    MatTooltipModule,
    MatRadioModule,
    MatStepperModule,
    MatCheckboxModule,
    MatExpansionModule,
  ],
  entryComponents: [ConfirmComponent]
})
export class SharedModule {

}

what I should do to solve this error, please?


问:
z3 Solver and solve give different results
I have been experimenting with z3 (version '4.8.7' obtained through pip3) and found this (apparent) discrepancy.

```<code>
t, s0, s, u, a, v = Reals('t s0 s u a v')
equations = [v == u + a*t, s == s0 + u*t + a*t**2/2,
             v**2 - u**2 == 2*a*s]
problem = [t == 10, s0 == 0, u == 0, a == 9.81]
solve(equations+problem)
</code>```

This gives the correct output for s:

[a = 981/100, u = 0, s0 = 0, t = 10, s = 981/2, v = 981/10]

But when I use the Solver, the result is different:

```<code>solver = Solver()
solver.check(equations+problem)
solver.model()
</code>```

This gives a wrong output for s, though it gets v right.

[t = 10, u = 0, s0 = 0, s = 0, a = 981/100, v = 981/10]

s should be (1/2) * (981/100) * 100 which is the result in solve.

Am I missing something obvious in z3's Solver or is this a bug? Thank you.

答:
The issue here is that the argument to solver.check are extra assumptions the solver can make as it solves the constraints, not the actual constraints to check. See the documentation here: https://z3prover.github.io/api/html/z3py_8py_source.html#l06628

The correct call would be:

solver = Solver()
solver.add(equations+problem)
print solver.check()
print solver.model()
```

that is, you add the constraints, and then call check with no arguments. This would match what solve does. The argument to check are used if you want to check validity under some extra assumptions only.

Body:
I have been experimenting with z3 (version '4.8.7' obtained through pip3) and found this (apparent) discrepancy.

t, s0, s, u, a, v = Reals('t s0 s u a v')
equations = [v == u + a*t, s == s0 + u*t + a*t**2/2,
             v**2 - u**2 == 2*a*s]
problem = [t == 10, s0 == 0, u == 0, a == 9.81]
solve(equations+problem)

This gives the correct output for s:

[a = 981/100, u = 0, s0 = 0, t = 10, s = 981/2, v = 981/10]

But when I use the Solver, the result is different:

solver = Solver()
solver.check(equations+problem)
solver.model()

This gives a wrong output for s, though it gets v right.

[t = 10, u = 0, s0 = 0, s = 0, a = 981/100, v = 981/10]

s should be (1/2) * (981/100) * 100 which is the result in solve.

Am I missing something obvious in z3's Solver or is this a bug? Thank you.

Body:
The issue here is that the argument to solver.check are extra assumptions the solver can make as it solves the constraints, not the actual constraints to check. See the documentation here: https://z3prover.github.io/api/html/z3py_8py_source.html#l06628

The correct call would be:

solver = Solver()
solver.add(equations+problem)
print solver.check()
print solver.model()

that is, you add the constraints, and then call check with no arguments. This would match what solve does. The argument to check are used if you want to check validity under some extra assumptions only.


问:
Get the Max and Min value and if values are same then print only one value, Laravel Blade
Fetch the Max and Min Value from the array and if the values are same then print only one value.
Error: I am getting all Price Value in foreach
Eg, Rs 120 120 120 120 120 120</p>

```<code><?php
$maxprice = $product_attributes->max('price');
$minprice = $product_attributes->min('price'); ?>
  @foreach($product_attributes->sortBy('price') as $attribute)
    @if($maxprice === $minprice )
        {{ $attribute->price }}
    @endif
  @endforeach
</code>```

答:
If you need to find max and min value from the collection.

```<code>$max = $product_attributes->max('price');
$min = $product_attributes->min('price');

@foreach($product_attributes->sortBy('price') as $attribute)
    @if($max === $min )
        {{ $attribute->price }}
    @endif
@endforeach
</code>```

Body:
Fetch the Max and Min Value from the array and if the values are same then print only one value.
Error: I am getting all Price Value in foreach
Eg, Rs 120 120 120 120 120 120

<?php
$maxprice = $product_attributes->max('price');
$minprice = $product_attributes->min('price'); ?>
  @foreach($product_attributes->sortBy('price') as $attribute)
    @if($maxprice === $minprice )
        {{ $attribute->price }}
    @endif
  @endforeach

Body:
If you need to find max and min value from the collection.

$max = $product_attributes->max('price');
$min = $product_attributes->min('price');

@foreach($product_attributes->sortBy('price') as $attribute)
    @if($max === $min )
        {{ $attribute->price }}
    @endif
@endforeach


问:
How to store file paths from a tab separated text file in a bash array
I have a tab separated text file with one column of file paths, e.g. table.txt

```<code>> SampleID  Factor  Condition   Replicate   Treatment   Type    Dataset isPE    ReadLength  isREF   PathFASTQ
> DG13  fd3 c1  1   cc  0   0102    0   50  1   "/path/to/fastq"
> DG14  fd3 c1 1    cc  1   0102    0   50  1   "/path/to/fastq"
</code>```

I would like to store the paths in a bash array so I can use these in a downstream parallel computation (SGE Task Arrays). For simplicity, the leading and trailing " can easily be not included in table.txt.

Excluding the header line, I tried the following:

```<code>files=($(awk '{ if(($8 == 0)) { print $1} }' table.txt ))
paths=($(awk '{ if(($8 == 0)) { print $11} }' table.txt ))
infile="${paths[$SGE_TASK_ID]}"/"${files[$SGE_TASK_ID]}".fastq.gz
</code>```

$SGE_TASK_ID takes a user-defined integer value between (1-N) in case someone does not know.

Unfortunately $infile does not show the expected value for $SGE_TASK_ID=1:

```<code>/path/to/fastq/DG13.fastq.gz
</code>```

Thanks for your help.

答:
Would you please try the following:

```<code>while read -r -a ary; do
    ((nr++)) || continue                # skip header line
    if (( ${ary[7]} == 0 )); then       # if "isPE" == 0 ..
        path=${ary[10]#\"}              # remove leading double-quote
        path=${path%\"}                 # remove trailing double-quote
        file=${ary[0]}
        infile[$((++SGE_TASK_ID))]="${path}/${file}.fastq.gz"
    fi
done < table.txt

echo "${infile[1]}"
echo "${infile[2]}"
</code>```

Output:

```<code>/path/to/fastq/DG13.fastq.gz
/path/to/fastq/DG14.fastq.gz
</code>```

Body:
I have a tab separated text file with one column of file paths, e.g. table.txt

> SampleID  Factor  Condition   Replicate   Treatment   Type    Dataset isPE    ReadLength  isREF   PathFASTQ
> DG13  fd3 c1  1   cc  0   0102    0   50  1   "/path/to/fastq"
> DG14  fd3 c1 1    cc  1   0102    0   50  1   "/path/to/fastq"

I would like to store the paths in a bash array so I can use these in a downstream parallel computation (SGE Task Arrays). For simplicity, the leading and trailing " can easily be not included in table.txt.

Excluding the header line, I tried the following:

files=($(awk '{ if(($8 == 0)) { print $1} }' table.txt ))
paths=($(awk '{ if(($8 == 0)) { print $11} }' table.txt ))
infile="${paths[$SGE_TASK_ID]}"/"${files[$SGE_TASK_ID]}".fastq.gz

$SGE_TASK_ID takes a user-defined integer value between (1-N) in case someone does not know.

Unfortunately $infile does not show the expected value for $SGE_TASK_ID=1:

/path/to/fastq/DG13.fastq.gz

Thanks for your help.

Body:
Would you please try the following:

while read -r -a ary; do
    ((nr++)) || continue                # skip header line
    if (( ${ary[7]} == 0 )); then       # if "isPE" == 0 ..
        path=${ary[10]#\"}              # remove leading double-quote
        path=${path%\"}                 # remove trailing double-quote
        file=${ary[0]}
        infile[$((++SGE_TASK_ID))]="${path}/${file}.fastq.gz"
    fi
done < table.txt

echo "${infile[1]}"
echo "${infile[2]}"

Output:

/path/to/fastq/DG13.fastq.gz
/path/to/fastq/DG14.fastq.gz


问:
How to access nested array and objects in http response In angular
I have a nested data structure containing objects and arrays. How can I extract the information, i.e. access specific or multiple values (or keys)?

```<code>{
  "data": [
    {
      "id": 2,
      "addEmployee": {
        "firstName": "Devansh"
      },
      "attendances": [
        {
          "id": 3,
          "checkIn": "2020-02-18T04:36:45.000Z",
          "checkOut": "2020-02-18T11:46:16.000Z",
          "totalHours": "7:9",
          "date": "2020-02-18",
          "status": "present",
          "createdAt": "2020-02-18T04:36:45.000Z",
          "updatedAt": "2020-02-18T11:46:16.000Z",
          "userId": 2
        }
      ]
    }
  ]
}
</code>```

how could i access the firstName and attendances array value

答:
You can access the data array of the object, then, the item of the array by index and so on, like this:</p>

```<code>let employee = myObject.data[0].addEmployee.firstName; // i suggest renaming the addEmployee attribute
let attendances = myObject.data[0].attendances[0]
</code>```

Body:
I have a nested data structure containing objects and arrays. How can I extract the information, i.e. access specific or multiple values (or keys)?

{
  "data": [
    {
      "id": 2,
      "addEmployee": {
        "firstName": "Devansh"
      },
      "attendances": [
        {
          "id": 3,
          "checkIn": "2020-02-18T04:36:45.000Z",
          "checkOut": "2020-02-18T11:46:16.000Z",
          "totalHours": "7:9",
          "date": "2020-02-18",
          "status": "present",
          "createdAt": "2020-02-18T04:36:45.000Z",
          "updatedAt": "2020-02-18T11:46:16.000Z",
          "userId": 2
        }
      ]
    }
  ]
}

how could i access the firstName and attendances array value

Body:
You can access the data array of the object, then, the item of the array by index and so on, like this:

let employee = myObject.data[0].addEmployee.firstName; // i suggest renaming the addEmployee attribute
let attendances = myObject.data[0].attendances[0]


问:
How to implement usage of multiple strategies at runtime
I need to process a list of records returned from a service.

However the processing algorithm for a record changes completely based on a certain field on the record.

To implement this , I have defined an IProcessor interface which has just one method :

```<code>public interface IProcessor
{
    ICollection<OutputEntity> Process(ICollection<InputEntity>> entities);
}
</code>```

And I have two concrete implementations of IProcessor for the different types of processing.

The issue is that I need to use all implementations of IProcessor at the same time .. so how do I inject the IProcessor into my Engine class which drives the whole thing:

```<code>public class Engine
{
    public void ProcessRecords(IService service)
    {
        var records = service.GetRecords();
        var type1Records = records.Where(x => x.SomeField== "Type1").ToList();
        var type2Records = records.Where(x => x.SomeField== "Type2").ToList();

        IProcessor processor1 = new Type1Processor();
        processor.Process(type1Records);

        IProcessor processor2 = new Type2Processor();
        processor.Process(type2Records);
    }
}
</code>```

This is what I'm doing at present .. and it doesn't look nice and clean.

Any ideas as to how I could improve this design .. using IoC perhaps ?

答:
You could put the SomeField specification in the IProcessor implementations (you'd have to add an extra field to the IProcessor interface), and find the corresponding records based on the processor you're using at the moment.

A bit of code to clear that up:

```<code>public interface IProcessor
{
    ICollection<OutputEntity> Process(ICollection<InputEntity>> entities);
    string SomeField{get;set;}
}

public class Engine
{
    public Engine(IEnumerable<IProcessor> processors)
    {
        //asign the processors to local variable
    }

    public void ProcessRecords(IService service)
    {
        // getRecords code etc.
        foreach(var processor in processors)
        {
            processor.Process(typeRecords.Where(typeRecord => typeRecord.SomeField == processor.SomeField));
        }
    }
}
</code>```

Alternatively, you could provide the IProcessors in the ProcessRecords method, or set them as Properties in the Engine class ( though I prefer the constructor injection ).

Edit

You might also want to look into the CanProcess approach in the other answers. Though the principle is the same, it provides an even more extensible/robust solution if you need to change the criteria to decide if the processor should process the types.

Body:
I need to process a list of records returned from a service.

However the processing algorithm for a record changes completely based on a certain field on the record.

To implement this , I have defined an IProcessor interface which has just one method :

public interface IProcessor
{
    ICollection<OutputEntity> Process(ICollection<InputEntity>> entities);
}

And I have two concrete implementations of IProcessor for the different types of processing.

The issue is that I need to use all implementations of IProcessor at the same time .. so how do I inject the IProcessor into my Engine class which drives the whole thing:

public class Engine
{
    public void ProcessRecords(IService service)
    {
        var records = service.GetRecords();
        var type1Records = records.Where(x => x.SomeField== "Type1").ToList();
        var type2Records = records.Where(x => x.SomeField== "Type2").ToList();

        IProcessor processor1 = new Type1Processor();
        processor.Process(type1Records);

        IProcessor processor2 = new Type2Processor();
        processor.Process(type2Records);
    }
}

This is what I'm doing at present .. and it doesn't look nice and clean.

Any ideas as to how I could improve this design .. using IoC perhaps ?

Body:
You could put the SomeField specification in the IProcessor implementations (you'd have to add an extra field to the IProcessor interface), and find the corresponding records based on the processor you're using at the moment.

A bit of code to clear that up:

public interface IProcessor
{
    ICollection<OutputEntity> Process(ICollection<InputEntity>> entities);
    string SomeField{get;set;}
}

public class Engine
{
    public Engine(IEnumerable<IProcessor> processors)
    {
        //asign the processors to local variable
    }

    public void ProcessRecords(IService service)
    {
        // getRecords code etc.
        foreach(var processor in processors)
        {
            processor.Process(typeRecords.Where(typeRecord => typeRecord.SomeField == processor.SomeField));
        }
    }
}

Alternatively, you could provide the IProcessors in the ProcessRecords method, or set them as Properties in the Engine class ( though I prefer the constructor injection ).

Edit

You might also want to look into the CanProcess approach in the other answers. Though the principle is the same, it provides an even more extensible/robust solution if you need to change the criteria to decide if the processor should process the types.


问:
Finding index of recurring objects in an ArrayList in Java
```<code>public class NewMain {
    public static void main(String[] args) {
        ArrayList<String> array = new ArrayList<>();
        array.add("Ace of Hearts");
        array.add("King of Clubs");
        array.add("Three of Spade");
        array.add("Ace of Hearts");
        array.add("Ten of Clubs");
        for(String s: array)
            System.out.println(s+"at postion: "+array.indexOf(s));
    }
}
</code>```

IndexOf() returns the first occurence of the object in an ArrayList.
Assuming my code is the hand of a poker player, and I want to know the indices of the cards he is holding. Ace of Hearts is at positon 1 and 4. But IndexOf() returns as position 1 and 1 for both occurences of Ace of Hearts.

Question:

1)Is there any other way of getting the value?

2)Should I use someother Data Structure like HashMap or something else?

答:
This should solve your problem : </p>

```<code> public class NewMain {
        public static void main(String[] args) {
            String abc="Ace of Hearts";
            List<String> array = new ArrayList<String>();
            array.add("Ace of Hearts");
            array.add("King of Clubs");
            array.add("Three of Spade");
            array.add("Ace of Hearts");
            array.add("Ten of Clubs");
            List<Integer> indexList= indexOfAll(abc,array);
            System.out.println(indexList);

        }

        static <T> List<Integer> indexOfAll(T obj, List<T> list) {
            final List<Integer> indexList = new ArrayList<Integer>();
            for (int i = 0; i < list.size(); i++) {
                if (obj.equals(list.get(i))) {
                    indexList.add(i);
                }
            }
            return indexList;
        }
</code>```

Body:
public class NewMain {
    public static void main(String[] args) {
        ArrayList<String> array = new ArrayList<>();
        array.add("Ace of Hearts");
        array.add("King of Clubs");
        array.add("Three of Spade");
        array.add("Ace of Hearts");
        array.add("Ten of Clubs");
        for(String s: array)
            System.out.println(s+"at postion: "+array.indexOf(s));
    }
}

IndexOf() returns the first occurence of the object in an ArrayList.
Assuming my code is the hand of a poker player, and I want to know the indices of the cards he is holding. Ace of Hearts is at positon 1 and 4. But IndexOf() returns as position 1 and 1 for both occurences of Ace of Hearts.

Question:

1)Is there any other way of getting the value?

2)Should I use someother Data Structure like HashMap or something else?

Body:
This should solve your problem :

 public class NewMain {
        public static void main(String[] args) {
            String abc="Ace of Hearts";
            List<String> array = new ArrayList<String>();
            array.add("Ace of Hearts");
            array.add("King of Clubs");
            array.add("Three of Spade");
            array.add("Ace of Hearts");
            array.add("Ten of Clubs");
            List<Integer> indexList= indexOfAll(abc,array);
            System.out.println(indexList);

        }

        static <T> List<Integer> indexOfAll(T obj, List<T> list) {
            final List<Integer> indexList = new ArrayList<Integer>();
            for (int i = 0; i < list.size(); i++) {
                if (obj.equals(list.get(i))) {
                    indexList.add(i);
                }
            }
            return indexList;
        }


问:
Material UI Table with Drop Down inside a column
I want to insert a select drop down inside material ui table as part of row. Can you please share a reference as to how to perform this using React.</p>

答:
In material able you have a special feature "lookup".

Please refer to the following code:

```<code> const columns = [
 {
  title: "Name",
  field: "Name",
  value:Name,
  lookup:
   {
     1:"John"
     2:"Jessica"
   }
  },
 ]
</code>```

Body:
In material able you have a special feature "lookup".

Please refer to the following code:

 const columns = [
 {
  title: "Name",
  field: "Name",
  value:Name,
  lookup:
   {
     1:"John"
     2:"Jessica"
   }
  },
 ]


问:
How to pipe Howler.masterGain output to mediaRecorder
I'm trying to record composed Web-Audio-API output from Howler (a bunch of sounds and audio sprites combined programmatically).

So far I've tried connecting the Howler.masterGain context to a createMediaStreamDestination Node but the MediaRecorder.ondataavailable event only fires once and without data.

Here's an example with a wired up version here: https://jsfiddle.net/chadananda/kvzrsx5t/86/

const audioURL = 'https://cdn.glitch.com/02dcea11-9bd2-4462-ac38-eeb6a5ad9530%2F331_full_beautiful-minds_0171_preview.mp3?1522829295082'

// connect MediaStreamDestination to Howler.masterGain
Howler.mute(false) // to initialize Howler internals
let mediaDest = Howler.ctx.createMediaStreamDestination()
// first disconnect
Howler.masterGain.disconnect()
// then reconnect to our new destination?
Howler.masterGain.connect(mediaDest)

// set up media recorder to record output
let audioChunks = []
let mediaRecorder = new MediaRecorder(mediaDest.stream, {mimeType: 'audio/webm'})
mediaRecorder.onstart = (event) => { console.log('Started recording Howl output...') }
mediaRecorder.ondataavailable = (e) => { if (e.data.size) audioChunks.push(e.data) }
mediaRecorder.onstop = (event) => {
  console.log('Completed Recording', audioChunks) // why is this returning empty?
    // let buffer = new Blob(chunks)
    // let audioPlayer = document.createElement("AUDIO")
    // audioPlayer.src = window.URL.createObjectURL(buffer)
    // audioPlayer.play()
}

// example of recording one sound looping for 3 seconds
let sound = new Howl({ html5: false, src: audioURL })
// start sound and recording
sound.play(); mediaRecorder.start()
// stop in a few seconds
setTimeout( ()=>{ mediaRecorder.stop(); sound.stop() }, 5000)

```

答:
The problem is that Howler.masterGain changes after you create your Howl instance:

const audioURL = 'https://cdn.glitch.com/02dcea11-9bd2-4462-ac38-eeb6a5ad9530%2F331_full_beautiful-minds_0171_preview.mp3?1522829295082';
const masterGain = Howler.masterGain;
const sound = new Howl({ html5: false, src: audioURL });
sound.play();

console.log( masterGain === Howler.masterGain ); // false```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.1.3/howler.min.js"></script></code>```

So the one you connect to your MediaStreamDestination node is not the one where the audio data will be passed, and hence it records only silence.

I don't realy know this library, so I can't tell why it behaves like that, or if there is a way to make it behave differently, but a simple workaround is to initialize your stream and create your recorder only after you initialized your Howl instance:

onclick = e => { onclick = null; msg.remove();

const audioURL = 'https://cdn.glitch.com/02dcea11-9bd2-4462-ac38-eeb6a5ad9530%2F331_full_beautiful-minds_0171_preview.mp3?1522829295082'

Howler.mute(false) // to initialize Howler internals

// first initiate your Howl instance
const sound = new Howl( { html5: false, src: audioURL } );
sound.play();
// now intitiate your MediaStreamDestination

const mediaDest = Howler.ctx.createMediaStreamDestination();
Howler.masterGain.connect( mediaDest );

// set up media recorder to record output
const audioChunks = []
const mediaRecorder = new MediaRecorder( mediaDest.stream, { mimeType: 'audio/webm' } );

mediaRecorder.onstart = (event) =>
  { console.log('Started recording Howl output...') };
mediaRecorder.ondataavailable = (event) =>
  { audioChunks.push( event.data ) };
mediaRecorder.onstop = (event) =>
  { console.log('Completed Recording', new Blob( audioChunks ) ) };

mediaRecorder.start();

setTimeout( ()=>{ mediaRecorder.stop(); sound.stop() }, 5000);

};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.1.3/howler.min.js"></script>
<pre id="msg">click anywhere to start``````

Body:
The problem is that Howler.masterGain changes after you create your Howl instance:

const audioURL = 'https://cdn.glitch.com/02dcea11-9bd2-4462-ac38-eeb6a5ad9530%2F331_full_beautiful-minds_0171_preview.mp3?1522829295082';
const masterGain = Howler.masterGain;
const sound = new Howl({ html5: false, src: audioURL });
sound.play();

console.log( masterGain === Howler.masterGain ); // false

<script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.1.3/howler.min.js"></script>

So the one you connect to your MediaStreamDestination node is not the one where the audio data will be passed, and hence it records only silence.

I don't realy know this library, so I can't tell why it behaves like that, or if there is a way to make it behave differently, but a simple workaround is to initialize your stream and create your recorder only after you initialized your Howl instance:

onclick = e => { onclick = null; msg.remove();

const audioURL = 'https://cdn.glitch.com/02dcea11-9bd2-4462-ac38-eeb6a5ad9530%2F331_full_beautiful-minds_0171_preview.mp3?1522829295082'

Howler.mute(false) // to initialize Howler internals

// first initiate your Howl instance
const sound = new Howl( { html5: false, src: audioURL } );
sound.play();
// now intitiate your MediaStreamDestination

const mediaDest = Howler.ctx.createMediaStreamDestination();
Howler.masterGain.connect( mediaDest );

// set up media recorder to record output
const audioChunks = []
const mediaRecorder = new MediaRecorder( mediaDest.stream, { mimeType: 'audio/webm' } );

mediaRecorder.onstart = (event) =>
  { console.log('Started recording Howl output...') };
mediaRecorder.ondataavailable = (event) =>
  { audioChunks.push( event.data ) };
mediaRecorder.onstop = (event) =>
  { console.log('Completed Recording', new Blob( audioChunks ) ) };

mediaRecorder.start();

setTimeout( ()=>{ mediaRecorder.stop(); sound.stop() }, 5000);

};

<script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.1.3/howler.min.js"></script>
<pre id="msg">click anywhere to start</pre>


问:
Bypass all cacheing on jQuery.autocomplete(1.02)
I am using jQuery.autocomplete(1.02) on my search box and I want exact string and substring matching. I don't care (yet!) about the database load, I'm happy for it to fire off a query every keystroke and bypass the caching entirely - I just don't want anything missed.

To this end I have tried setting cacheLength=1, the minimum permitted, but the autocomplete function refuses to fire off a GET request for each key up.

```<code>searchbox          GET_request

   'a'       ->    http://localhost/service_search_request?q=a
   'ar'      ->    http://localhost/service_search_request?q=ar
   'ars'     ->    http://localhost/service_search_request?q=ars
</code>```

Instead, it sends the first and the third and misses the second, giving me the wrong results for 'ar' :-/  I've cleared my cache and sessions but it looks like some sort of caching is still going on. AFAIK I have no proxying going on and I'm shift-refreshing each time. It looks likely then that this behavior is from jQuery.autocomplete itself.

So my questions are...

A) Does this seem likely?  i.e. is it a feature, or maybe a bug?

B) If so is there a clean way around it?...

C) If not, what autocomplete would you use instead?

Naturally D) No you're just using it incorrectly you douche! is always a possibility, and indeed the one I'd prefer having spent time going down this road - assuming it comes with a link to the docs I've failed to find / read!

Cheers,

Roger :)

答:
This worked for me.</p>

```<code>function requestData(q) {
   if (!options.matchCase) q = q.toLowerCase();

   //-- I turned off this line
   // var data = options.cacheLength ? loadFromCache(q) : null;

   //-- And added this line of code
   var data = null;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am using jQuery.autocomplete(1.02) on my search box and I want exact string and substring matching. I don't care (yet!) about the database load, I'm happy for it to fire off a query every keystroke and bypass the caching entirely - I just don't want anything missed.

To this end I have tried setting cacheLength=1, the minimum permitted, but the autocomplete function refuses to fire off a GET request for each key up.

searchbox          GET_request

   'a'       ->    http://localhost/service_search_request?q=a
   'ar'      ->    http://localhost/service_search_request?q=ar
   'ars'     ->    http://localhost/service_search_request?q=ars

Instead, it sends the first and the third and misses the second, giving me the wrong results for 'ar' :-/  I've cleared my cache and sessions but it looks like some sort of caching is still going on. AFAIK I have no proxying going on and I'm shift-refreshing each time. It looks likely then that this behavior is from jQuery.autocomplete itself.

So my questions are...

A) Does this seem likely?  i.e. is it a feature, or maybe a bug?

B) If so is there a clean way around it?...

C) If not, what autocomplete would you use instead?

Naturally D) No you're just using it incorrectly you douche! is always a possibility, and indeed the one I'd prefer having spent time going down this road - assuming it comes with a link to the docs I've failed to find / read!

Cheers,

Roger :)

Body:
This worked for me.

function requestData(q) {
   if (!options.matchCase) q = q.toLowerCase();

   //-- I turned off this line
   // var data = options.cacheLength ? loadFromCache(q) : null;

   //-- And added this line of code
   var data = null;


问:
How do I get my nav links in the nav bar?
I'm not sure why this is happening. The  tag that is the title "Don't Be Square" is in the nav bar, but not the links. What am I missing here in the CSS or the HTML that will bump it up inside there? enter image description here</p>

答:
I think, you have header "Don't Be Square" after that you are righting code for Nav bar. And you wanted to bring your nav bar top right. To do so, you can right css for your title.
use float: left; there other way also you can acheive, for that you have to share the code.

Hope it will help you.


问:
Android: Viewing SharedPreferences file?
For debugging purposes I need to access the shared preferences file of my application. As far as I know I should find this file in /data/... but I can't access the /data folder through to missing permissions. Is this normal? Any way to still access the file? (except maybe raeding it from inside the application?) The phone is not rooted and I also don't want to root it.
Thanks for any hint!</p>

答:
You can access and modify SharedPreferences data easily by using stetho. Follow the
 link provided below to add it to your android project and view data.

http://facebook.github.io/stetho/


问:
SQL Query Minimizer : CREATE + ALTER => CREATE
Are there any tools available which can give me
a single CREATE query
when I give a
CREATE & number of ALTER queries as input

For Example,
INPUT:

```<code>CREATE TABLE student(
    student_id INT,
    name VARCHAR(100),
    age INT);

ALTER TABLE student ADD(
    address VARCHAR(200)
);
</code>```

Expected OUTPUT:

```<code>CREATE TABLE student(
    student_id INT,
    name VARCHAR(100),
    age INT,
    address VARCHAR(200));
</code>```

This is just a simple example, I need a tool which can work for more complex queries as well.

Real Problem:

I have set of files having multiple SQL queries.
Therefore, I need this task to be done in bulk.

Example

Input File:

```<code>CREATE query (table 1)
CREATE query (table 2)
CREATE query (table 3)
ALTER  query (table 1)
ALTER  query (table 3)
ALTER  query (table 2)
ALTER  query (table 2)
ALTER  query (table 1)
......
</code>```

Expected Output File:

```<code>CREATE query (table 1)
CREATE query (table 2)
CREATE query (table 3)
......
</code>```

There are a lot of tables in a file, may be around 30.

答:
You can use XAMPP server to do it.....
It has basic GUI window in which you could just click and get your query, without actually typing it...
It can save time

REGARD

Body:
Are there any tools available which can give me
a single CREATE query
when I give a
CREATE & number of ALTER queries as input

For Example,
INPUT:

CREATE TABLE student(
    student_id INT,
    name VARCHAR(100),
    age INT);

ALTER TABLE student ADD(
    address VARCHAR(200)
);

Expected OUTPUT:

CREATE TABLE student(
    student_id INT,
    name VARCHAR(100),
    age INT,
    address VARCHAR(200));

This is just a simple example, I need a tool which can work for more complex queries as well.

Real Problem:

I have set of files having multiple SQL queries.
Therefore, I need this task to be done in bulk.

Example

Input File:

CREATE query (table 1)
CREATE query (table 2)
CREATE query (table 3)
ALTER  query (table 1)
ALTER  query (table 3)
ALTER  query (table 2)
ALTER  query (table 2)
ALTER  query (table 1)
......

Expected Output File:

CREATE query (table 1)
CREATE query (table 2)
CREATE query (table 3)
......

There are a lot of tables in a file, may be around 30.


答:
It would help if you posted some of the source code along with it. The only thing that I can potentially think of by just the image is that you are using some sort of header (h1, h2, etc) followed by some other tag that isn't inline (div, p, etc). Since both are block that could be why it displays on the line after. If this is the problem, a tags are inline so simply putting the  tags within the body of the h1 could suffice such as

```<code><h1>Don't Be Square <a some link here/> <a another link/> <a third link></h1>
</code>```

and then styling the links differently from the h1 by giving them an id or using the css identifier

```<code>h1 a{ your styling here}
</code>```

Again I can't help much because there is no source but hopefully this helps.

Title: How do I get my nav links in the nav bar?

Body: I'm not sure why this is happening. The  tag that is the title "Don't Be Square" is in the nav bar, but not the links. What am I missing here in the CSS or the HTML that will bump it up inside there? enter image description here

Body:
It would help if you posted some of the source code along with it. The only thing that I can potentially think of by just the image is that you are using some sort of header (h1, h2, etc) followed by some other tag that isn't inline (div, p, etc). Since both are block that could be why it displays on the line after. If this is the problem, a tags are inline so simply putting the  tags within the body of the h1 could suffice such as

<h1>Don't Be Square <a some link here/> <a another link/> <a third link></h1>

and then styling the links differently from the h1 by giving them an id or using the css identifier

h1 a{ your styling here}

Again I can't help much because there is no source but hopefully this helps.


问:
How to apply-artifact "Run PowerShell" for azure devtest lab VM by Azure CLI?
I have a PowerShell script and would like to use az lab vm -apply-artifacts to add the artifacts to VM. Could anyone please give me an example artifact Json file and how to call it from Azure CLI?
Thanks a lot!</p>

答:
give me an example artifact Json file and how to call it from Azure CLI?

The following example shows the sections that make up the basic structure of a definition file:

```<code>{
  "$schema": "https://raw.githubusercontent.com/Azure/azure-devtestlab/master/schemas/2016-11-28/dtlArtifacts.json",
  "title": "",
  "description": "",
  "iconUri": "",
  "targetOsType": "",
  "parameters": {
    "<parameterName>": {
      "type": "",
      "displayName": "",
      "description": ""
    }
  },
  "runCommand": {
    "commandToExecute": ""
  }
}
</code>```

And you cuold get a sample artifacts.json definition file. Check out the artifacts created by the DevTest Labs team in GitHub repository.

Apply artifacts to a virtual machine in Azure DevTest Lab.

```<code>az lab vm apply-artifacts --artifacts '@artifacts.json' --lab-name MyLab --name MyVirtualMachine --resource-group MyResourceGroup
</code>```

Body:
give me an example artifact Json file and how to call it from Azure CLI?

The following example shows the sections that make up the basic structure of a definition file:

{
  "$schema": "https://raw.githubusercontent.com/Azure/azure-devtestlab/master/schemas/2016-11-28/dtlArtifacts.json",
  "title": "",
  "description": "",
  "iconUri": "",
  "targetOsType": "",
  "parameters": {
    "<parameterName>": {
      "type": "",
      "displayName": "",
      "description": ""
    }
  },
  "runCommand": {
    "commandToExecute": ""
  }
}

And you cuold get a sample artifacts.json definition file. Check out the artifacts created by the DevTest Labs team in GitHub repository.

Apply artifacts to a virtual machine in Azure DevTest Lab.

az lab vm apply-artifacts --artifacts '@artifacts.json' --lab-name MyLab --name MyVirtualMachine --resource-group MyResourceGroup