问:
Jquery (this) help
Just wanted some quick help I'm 90% sure i need to use the (this) call/function because i need it to work on multiple objects on the page. but im not sure where or how to place it into my jquery code, im trying to create a hover state for a object once the user rolls over another , here is my jquery code, I hope this makes sense, thanks!

```<code>    $("li.projectpost").hover(function () {
    $("div.portfolio-title a").toggleClass("highlighter");
    });
</code>```

Basically all i really want to know is, I have more than one element on the page that I would like to apply a hover effect to, as is right now, when i hover over one item they all change, but I want to know is how to change the css in a child element when rolled over a parent I guess,  I have a Div wrapper, that when hovered  over an inside div changes, does that make better sense, Still trying to wrap my head around jquery thanks for the help! :)

Thanks for the help everyone! I just figured this out, I needed to use -
    jQuery(this).find(); thanks!

答:
http://jsfiddle.net/tbq3x/13/

Just try the above fiddle. Your code works fine.

Title: Jquery (this) help

Body:
Just wanted some quick help I'm 90% sure i need to use the (this) call/function because i need it to work on multiple objects on the page. but im not sure where or how to place it into my jquery code, im trying to create a hover state for a object once the user rolls over another , here is my jquery code, I hope this makes sense, thanks!

    $("li.projectpost").hover(function () {
    $("div.portfolio-title a").toggleClass("highlighter");
    });

Basically all i really want to know is, I have more than one element on the page that I would like to apply a hover effect to, as is right now, when i hover over one item they all change, but I want to know is how to change the css in a child element when rolled over a parent I guess,  I have a Div wrapper, that when hovered  over an inside div changes, does that make better sense, Still trying to wrap my head around jquery thanks for the help! :)

Thanks for the help everyone! I just figured this out, I needed to use -
    jQuery(this).find(); thanks!


来源: stackexchange

问:
Create new dummy variable columns from categorical variable
I have a several data sets with 75,000 observations and a type variable that can take on a value 0-4.  I want to add five new dummy variables to each data set for all types.  The best way I could come up with to do this is as follows:

```<code># For the 'binom' data set create dummy variables for all types in all data sets
binom.dummy.list<-list()
for(i in 0:4){
    binom.dummy.list[[i+1]]<-sapply(binom$type,function(t) ifelse(t==i,1,0))
}

# Add and merge data
binom.dummy.df<-as.data.frame(do.call("cbind",binom.dummy.list))
binom.dummy.df<-transform(binom.dummy.df,id=1:nrow(binom))
binom<-merge(binom,binom.dummy.df,by="id")
</code>```

While this works, it is incredibly slow (the merge function has even crashed a few times). Is there a more efficient way to do this?  Perhaps this functionality is part of a package that I am not familiar with?

答:
I did not have good luck with model.matrix() function as it was omitting some factor levels for whatever reason. However, i have had good luck with this simple function from library(fastDummies):

Columns that are converted into binary dummy variables have to be categorical.

 fastDummies::dummy_cols(fastDummies_example, select_columns = "numbers", remove_selected_columns = "numbers")

ContentLicense: CC BY-SA 3.0

Body:
I have a several data sets with 75,000 observations and a type variable that can take on a value 0-4.  I want to add five new dummy variables to each data set for all types.  The best way I could come up with to do this is as follows:

# For the 'binom' data set create dummy variables for all types in all data sets
binom.dummy.list<-list()
for(i in 0:4){
    binom.dummy.list[[i+1]]<-sapply(binom$type,function(t) ifelse(t==i,1,0))
}

# Add and merge data
binom.dummy.df<-as.data.frame(do.call("cbind",binom.dummy.list))
binom.dummy.df<-transform(binom.dummy.df,id=1:nrow(binom))
binom<-merge(binom,binom.dummy.df,by="id")

While this works, it is incredibly slow (the merge function has even crashed a few times). Is there a more efficient way to do this?  Perhaps this functionality is part of a package that I am not familiar with?

ContentLicense: CC BY-SA 4.0


问:
returning a string with decremented versions of itself
i am trying to write a code that takes a string and adds itself to the begginning of it missing the final letter until the string runs out. I originally had it as a print, but need to change to return, but it causes an error with the "end=''" syntax

sample output: "hey" ---> "hhehey"

```<code>def explode(str):
    for i in range(0, len(str)):
        return(str[0:i + 1], end='')
</code>```

答:
If you want the method to return a string, you need to concatenate then return

```<code>def explode(value):
    result = ""
    for i in range(len(value)):
        result += value[:i + 1]
    return result
</code>```

You can inline it

```<code>def explode(value):
    return "".join(value[:i + 1] for i in range(len(value)))

print(explode("hey"))  # hhehey
</code>```

Body:
i am trying to write a code that takes a string and adds itself to the begginning of it missing the final letter until the string runs out. I originally had it as a print, but need to change to return, but it causes an error with the "end=''" syntax

sample output: "hey" ---> "hhehey"

def explode(str):
    for i in range(0, len(str)):
        return(str[0:i + 1], end='')

Body:
If you want the method to return a string, you need to concatenate then return

def explode(value):
    result = ""
    for i in range(len(value)):
        result += value[:i + 1]
    return result

You can inline it

def explode(value):
    return "".join(value[:i + 1] for i in range(len(value)))

print(explode("hey"))  # hhehey


问:
How can I simplify the following R code into a FOR LOOP？
I would like to convert this code into FOR LOOP but I met mistakes and I could not finish it. Thank you for your help!</p>
```<code>
PM2.52018 <- data_df[which(data_df$type=='PM2.5'),]
PM102018<- data_df[which(data_df$type=='PM10'),]
SO2 <- data_df[which(data_df$type=='SO2'),]
CO <- data_df[which(data_df$type=='CO'),]
NO2 <- data_df[which(data_df$type=='NO2'),]
O3 <-  data_df[which(data_df$type=='O3'),]
</code>```

答:
We do not need a for loop here.
Just use split. After that, we can rename the individual data.frames as desired.
This will get us a list of dataframes, which is usually much better than keeping all this likely related dataframes in the global environment

```<code>my_list <- split(data_df, data_df$type)
</code>```

Body:
I would like to convert this code into FOR LOOP but I met mistakes and I could not finish it. Thank you for your help!

PM2.52018 <- data_df[which(data_df$type=='PM2.5'),]
PM102018<- data_df[which(data_df$type=='PM10'),]
SO2 <- data_df[which(data_df$type=='SO2'),]
CO <- data_df[which(data_df$type=='CO'),]
NO2 <- data_df[which(data_df$type=='NO2'),]
O3 <-  data_df[which(data_df$type=='O3'),]

Body:
We do not need a for loop here.
Just use split. After that, we can rename the individual data.frames as desired.
This will get us a list of dataframes, which is usually much better than keeping all this likely related dataframes in the global environment

my_list <- split(data_df, data_df$type)


问:
HTTP Status 405 - Request method 'POST' not supported (Spring MVC)
Im getting this error: HTTP Status 405 - Request method 'POST' not supported

What I am trying to do is make a form with a drop down box that get populated based on the other value selected in another drop down box. For example when I select a name in the customerName box the onChange function in the .jsp page should be run and the page submitted then loaded again with the corresponding values in the customerCountry box.

however I'm getting this HTTP Status 405 error. I have searched the internet for a solution but haven't been able to find anything that helped. Here is the relevant parts of my code:

part of jsp page

```<code><html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
            <style>
            .error { color: red; }
            </style>

        <script>
            function repopulate(){
                document.deliveryForm.submit();
            }

            function setFalse(){
                document.getElementById("hasId").value ="false";
                document.deliveryForm.submit();
                // document.submitForm.submit(); (This was causing the error)

            }
        </script>

    </head>
    <body>

        <h1>Create New Delivery</h1>

        <c:url var="saveUrl" value="/test/delivery/add" />
        <form:form modelAttribute="deliveryDtoAttribute" method="POST" action="${saveUrl}" name="deliveryForm">
            <table>

                <tr>
                    <td><form:hidden id="hasId" path="hasCustomerName" value="true"/></td>
                </tr>

                <tr>
                    <td>Customer Name</td>
                    <td><form:select path="customerName" onChange="repopulate()">
                        <form:option value="" label="--- Select ---" />
                        <form:options items="${customerNameList}" />
                        </form:select>
                    </td>
                    <td><form:errors path="customerName" cssClass="error" /></td>
                </tr>

                <tr>
                    <td>Customer Country</td>
                    <td><form:select path="customerCountry">
                        <form:option value="" label="--- Select ---" />
                        <form:options items="${customerCountryList}" />
                        </form:select>
                    </td>
                    <td><form:errors path="customerCountry" cssClass="error" /></td>
                </tr>

        </form:form>

        <form:form name="submitForm">
        <input type="button" value="Save" onClick="setFalse()"/>
        </form:form>

    </body>
</html>
</code>```

part of controller:

```<code>@RequestMapping(value = "/add", method = RequestMethod.GET)
    public String getDelivery(ModelMap model) {
        DeliveryDto deliveryDto = new DeliveryDto();

        model.addAttribute("deliveryDtoAttribute", deliveryDto);
        model.addAttribute("customerNameList",
                customerService.listAllCustomerNames());
        model.addAttribute("customerCountryList", customerService
                    .listAllCustomerCountries(deliveryDto.getCustomerName()));
        return "new-delivery";
    }

    // I want to enter this method if hasId=true which means that a value in the CustomerName
    // drop down list was selected. This should set the CountryList to the corresponding values
    // from the database. I want this post method to be triggered by the onChange in the jsp page

    @RequestMapping(value = "/add", method = RequestMethod.POST, params="hasCustomerName=true")
    public String postDelivery(
            @ModelAttribute("deliveryDtoAttribute") DeliveryDto deliveryDto,
            BindingResult result, ModelMap model) {

            model.addAttribute("deliveryDtoAttribute", deliveryDto);

            model.addAttribute("customerNameList",
                    customerService.listAllCustomerNames());
            model.addAttribute("customerCountryList", customerService
                    .listAllCustomerCountries(deliveryDto.getCustomerName()));

            return "new-delivery";
    }

    // This next post method should only be entered if the save button is hit in the jsp page

    @RequestMapping(value = "/add", method = RequestMethod.POST, params="hasCustomerName=false")
    public String postDelivery2(
            @ModelAttribute("deliveryDtoAttribute") @Valid DeliveryDto deliveryDto,
            BindingResult result, ModelMap model) {

        if (result.hasErrors()) {

            model.addAttribute("deliveryDtoAttribute", deliveryDto);

            model.addAttribute("customerNameList",
                    customerService.listAllCustomerNames());
            model.addAttribute("customerCountryList", customerService
                    .listAllCustomerCountries(deliveryDto.getCustomerName()));

            return "new-delivery";
        } else {

            Delivery delivery = new Delivery();

            //Setters to set delivery values

            return "redirect:/mis/home";
        }

    }
</code>```

How come I get this error? Any help would be much appreciated! Thanks

EDIT: Changed hasId to hasCustomerName. I still get the HTTP Status 405 - Request method 'POST' not supported error though.

EDIT2: Commented out the line in the setFalse function that was causing the error

// D

答:
In my case the url was ending with /

paymentUrl(old)= /get-details/

i just removed the trailing /

paymentUrl(new)= /get-details

and it worked

Body:
Im getting this error: HTTP Status 405 - Request method 'POST' not supported

What I am trying to do is make a form with a drop down box that get populated based on the other value selected in another drop down box. For example when I select a name in the customerName box the onChange function in the .jsp page should be run and the page submitted then loaded again with the corresponding values in the customerCountry box.

however I'm getting this HTTP Status 405 error. I have searched the internet for a solution but haven't been able to find anything that helped. Here is the relevant parts of my code:

part of jsp page

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>

Create New Delivery

        <c:url var="saveUrl" value="/test/delivery/add" />
        <form:form modelAttribute="deliveryDtoAttribute" method="POST" action="${saveUrl}" name="deliveryForm">

                    <form:hidden id="hasId" path="hasCustomerName" value="true"/>

                    Customer Name
                    <form:select path="customerName" onChange="repopulate()">
                        <form:option value="" label="--- Select ---" />
                        <form:options items="${customerNameList}" />
                        </form:select>

                    <form:errors path="customerName" cssClass="error" />

                    Customer Country
                    <form:select path="customerCountry">
                        <form:option value="" label="--- Select ---" />
                        <form:options items="${customerCountryList}" />
                        </form:select>

                    <form:errors path="customerCountry" cssClass="error" />

        </form:form>

        <form:form name="submitForm">
        <input type="button" value="Save" onClick="setFalse()"/>
        </form:form>

part of controller:

@RequestMapping(value = "/add", method = RequestMethod.GET)
    public String getDelivery(ModelMap model) {
        DeliveryDto deliveryDto = new DeliveryDto();

        model.addAttribute("deliveryDtoAttribute", deliveryDto);
        model.addAttribute("customerNameList",
                customerService.listAllCustomerNames());
        model.addAttribute("customerCountryList", customerService
                    .listAllCustomerCountries(deliveryDto.getCustomerName()));
        return "new-delivery";
    }

    // I want to enter this method if hasId=true which means that a value in the CustomerName
    // drop down list was selected. This should set the CountryList to the corresponding values
    // from the database. I want this post method to be triggered by the onChange in the jsp page

    @RequestMapping(value = "/add", method = RequestMethod.POST, params="hasCustomerName=true")
    public String postDelivery(
            @ModelAttribute("deliveryDtoAttribute") DeliveryDto deliveryDto,
            BindingResult result, ModelMap model) {

            model.addAttribute("deliveryDtoAttribute", deliveryDto);

            model.addAttribute("customerNameList",
                    customerService.listAllCustomerNames());
            model.addAttribute("customerCountryList", customerService
                    .listAllCustomerCountries(deliveryDto.getCustomerName()));

            return "new-delivery";
    }

    // This next post method should only be entered if the save button is hit in the jsp page

    @RequestMapping(value = "/add", method = RequestMethod.POST, params="hasCustomerName=false")
    public String postDelivery2(
            @ModelAttribute("deliveryDtoAttribute") @Valid DeliveryDto deliveryDto,
            BindingResult result, ModelMap model) {

        if (result.hasErrors()) {

            model.addAttribute("deliveryDtoAttribute", deliveryDto);

            model.addAttribute("customerNameList",
                    customerService.listAllCustomerNames());
            model.addAttribute("customerCountryList", customerService
                    .listAllCustomerCountries(deliveryDto.getCustomerName()));

            return "new-delivery";
        } else {

            Delivery delivery = new Delivery();

            //Setters to set delivery values

            return "redirect:/mis/home";
        }

    }

How come I get this error? Any help would be much appreciated! Thanks

EDIT: Changed hasId to hasCustomerName. I still get the HTTP Status 405 - Request method 'POST' not supported error though.

EDIT2: Commented out the line in the setFalse function that was causing the error

// D


问:
flutter navigator do when action after call pushReplacement in child page
I have a flutter app look like this

PAGE 1 > PAGE 2 > PAGE 3

When I change value on PAGE 2, I need to refresh data on PAGE 1 so I using Navigator.push from PAGE 1 to PAGE 2 with then action in PAGE 1. When I navigator from PAGE 2 to PAGE 3 by Navigator.pushReplacement (to escape from PAGE 3 to PAGE 1 when press back button) but when I navigator from PAGE 2 to PAGE 3 then when action are calling in PAGE 1 and when I press back button on PAGE 3 then action when are not calling

How can I still refresh data on PAGE 1 and when press back button on PAGE 3? and not call when action when navigator from PAGE 2 to PAGE 3

答: You can use any state management pattern like provider, you can easily update your data in PAGE 1 from anywhere under provider widget, have a look LINK_HERE</p>


问:
redirect_uri using http instead of https
I'm using spring stack (Spring Boot 2.0.1.RELEASE) for creating a site that delegues user authentication/registration to Facebook via OAuth2. When I click the "login with facebook" button I get redirected to Facebook, but Spring Security OAuth2 is creating the redirect_uri parameter using http instead of https. The application uses https and I can't figure out where this "http" is coming from.

So, how can I make Spring create the redirect_uri parameter correctly?

UPDATE

Sorry for the original post. It was late and I wanted to have the question posted before going sleep :-)

Well, my application uses Spring Boot 2.0.1.RELEASE, which comes with Spring Security 2.0.1.RELEASE and Spring Security OAuth2 5.0.4.RELEASE. My application uses Facebook for registering and authenticating users. Currently I have a test environment running in AWS (Beanstalk) and using Amazon's SSL certificate.

When I first wrote the post my issue was that the redirect_uri parameter sent by my application (by SS actually) to Facebook had a http prefix, instead of https. This was causing an error in Facebook, which only accepts https redirect urls.

Reading the docs I found the spring.security.oauth2.client.registration.facebook.redirect-uri-template property, which I set to https://[my domain]/login/oauth2/code/{registrationId}. Now Facebook processes my authentication requests and posts back to my application.

However, with the previous parameter set, now the problem has changed. Now when the Facebook's callback hits my application at AWS I get the following exception (from the logs):

```<code>2018-04-11 10:51:23 [http-nio-5000-exec-5] DEBUG o.s.s.o.c.w.OAuth2LoginAuthenticationFilter - Request is to process authentication
2018-04-11 10:51:23 [http-nio-5000-exec-5] DEBUG o.s.s.authentication.ProviderManager - Authentication attempt using org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationProvider
2018-04-11 10:51:23 [http-nio-5000-exec-5] DEBUG o.s.s.authentication.ProviderManager - Authentication attempt using org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeAuthenticationProvider
2018-04-11 10:51:23 [http-nio-5000-exec-5] DEBUG o.s.s.o.c.w.OAuth2LoginAuthenticationFilter - Authentication request failed: org.springframework.security.oauth2.core.OAuth2AuthenticationException: [invalid_redirect_uri_parameter]
org.springframework.security.oauth2.core.OAuth2AuthenticationException: [invalid_redirect_uri_parameter]
    at org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationProvider.authenticate(OAuth2LoginAuthenticationProvider.java:117)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
    at org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter.attemptAuthentication(OAuth2LoginAuthenticationFilter.java:159)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter.doFilterInternal(OAuth2AuthorizationRequestRedirectFilter.java:128)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Taking a look at the sources I found that the issue seems to be in the following test in the org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationProvider class:

```<code>if (!authorizationResponse.getRedirectUri().equals(authorizationRequest.getRedirectUri())) {
    OAuth2Error oauth2Error = new OAuth2Error(INVALID_REDIRECT_URI_PARAMETER_ERROR_CODE);
    throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
</code>```

To check why this comparison is failing I checked the requests and responses using Chrome's developer tools. So, this is the call to Facebook:

```<code>https://www.facebook.com/v2.8/dialog/oauth?response_type=code&client_id=[REMOVED]&scope=public_profile%20email&state=[REMOVED]&redirect_uri=https://[REMOVED]/login/oauth2/code/facebook
</code>```

Everything seems to be ok, the redirect_uri parameter is using https as expected and the complete redirect_uri seems correct.

And this is Facebook's callback:

```<code>https://[REMOVED]/login/oauth2/code/facebook?code=[REMOVED]
</code>```

Once again, everything seems ok. However, SS is rejecting the user authentication because request and response redirect_uris are not matching.

And this is the issue. Any idea of what is going wrong here? Am I missing something?

答: If you're using container apps or web apps contained over Linux, refer this answer. It could be caused by authentication redirecting to provider handle that's not served over HTTPS.</p>

Body:
I'm using spring stack (Spring Boot 2.0.1.RELEASE) for creating a site that delegues user authentication/registration to Facebook via OAuth2. When I click the "login with facebook" button I get redirected to Facebook, but Spring Security OAuth2 is creating the redirect_uri parameter using http instead of https. The application uses https and I can't figure out where this "http" is coming from.

So, how can I make Spring create the redirect_uri parameter correctly?

UPDATE

Sorry for the original post. It was late and I wanted to have the question posted before going sleep :-)

Well, my application uses Spring Boot 2.0.1.RELEASE, which comes with Spring Security 2.0.1.RELEASE and Spring Security OAuth2 5.0.4.RELEASE. My application uses Facebook for registering and authenticating users. Currently I have a test environment running in AWS (Beanstalk) and using Amazon's SSL certificate.

When I first wrote the post my issue was that the redirect_uri parameter sent by my application (by SS actually) to Facebook had a http prefix, instead of https. This was causing an error in Facebook, which only accepts https redirect urls.

Reading the docs I found the spring.security.oauth2.client.registration.facebook.redirect-uri-template property, which I set to https://[my domain]/login/oauth2/code/{registrationId}. Now Facebook processes my authentication requests and posts back to my application.

However, with the previous parameter set, now the problem has changed. Now when the Facebook's callback hits my application at AWS I get the following exception (from the logs):

2018-04-11 10:51:23 [http-nio-5000-exec-5] DEBUG o.s.s.o.c.w.OAuth2LoginAuthenticationFilter - Request is to process authentication
2018-04-11 10:51:23 [http-nio-5000-exec-5] DEBUG o.s.s.authentication.ProviderManager - Authentication attempt using org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationProvider
2018-04-11 10:51:23 [http-nio-5000-exec-5] DEBUG o.s.s.authentication.ProviderManager - Authentication attempt using org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeAuthenticationProvider
2018-04-11 10:51:23 [http-nio-5000-exec-5] DEBUG o.s.s.o.c.w.OAuth2LoginAuthenticationFilter - Authentication request failed: org.springframework.security.oauth2.core.OAuth2AuthenticationException: [invalid_redirect_uri_parameter]
org.springframework.security.oauth2.core.OAuth2AuthenticationException: [invalid_redirect_uri_parameter]
    at org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationProvider.authenticate(OAuth2LoginAuthenticationProvider.java:117)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
    at org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter.attemptAuthentication(OAuth2LoginAuthenticationFilter.java:159)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter.doFilterInternal(OAuth2AuthorizationRequestRedirectFilter.java:128)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

Taking a look at the sources I found that the issue seems to be in the following test in the org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationProvider class:

if (!authorizationResponse.getRedirectUri().equals(authorizationRequest.getRedirectUri())) {
    OAuth2Error oauth2Error = new OAuth2Error(INVALID_REDIRECT_URI_PARAMETER_ERROR_CODE);
    throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}

To check why this comparison is failing I checked the requests and responses using Chrome's developer tools. So, this is the call to Facebook:

https://www.facebook.com/v2.8/dialog/oauth?response_type=code&client_id=[REMOVED]&scope=public_profile%20email&state=[REMOVED]&redirect_uri=https://[REMOVED]/login/oauth2/code/facebook

Everything seems to be ok, the redirect_uri parameter is using https as expected and the complete redirect_uri seems correct.

And this is Facebook's callback:

https://[REMOVED]/login/oauth2/code/facebook?code=[REMOVED]

Once again, everything seems ok. However, SS is rejecting the user authentication because request and response redirect_uris are not matching.

And this is the issue. Any idea of what is going wrong here? Am I missing something?


问:
Coq: How are the equality tacticts symmetry and transitivity defined?
I'm interested in how the Coq tactics symmetry and transitivity actually work. I've read the Coq manual but this only describes what they do, not how they operate on a proof and change the proof states. As an example of what I'm looking for, in Interactive Theorem Proving and Program Development, the authors state that
"The reflexivity tactic actually is synonymous with apply refl_equal" (p. 124).
But, the author refers the reader to the reference manual for symmetry and transitivity. I haven't found a good description of things that these two tactics are synonymous with in the same way.

For clarification, the reason why I ask is that I have defined a path space paths {A : UU} : A -> A -> UU notated a = b (like in UniMath) which acts like an equivalence relation except for that a = b is not a proposition but a type. For this reason I was unable to add this relation as an equivalence relation using Add Parametric Relation. I'm trying to cook up a version of symmetry and transitivity with Ltac for this path space relation but I don't know how to change the proof state; knowing how symmetry and transitivity actually work might help.

答:
These tactics only apply the lemmas corresponding to symmetry and transitivity of the relation it finds in the goal.
These are found using the type classes mechanism.

For instance you could declare

```<code>From Coq Require Import RelationClasses.

Instance trans : Transitive R.
</code>```

which would ask you to prove R is transitive and then you would be able to use the tactic transitivity to prove R x y.

Body:
These tactics only apply the lemmas corresponding to symmetry and transitivity of the relation it finds in the goal.
These are found using the type classes mechanism.

For instance you could declare

From Coq Require Import RelationClasses.

Instance trans : Transitive R.

which would ask you to prove R is transitive and then you would be able to use the tactic transitivity to prove R x y.


问:
What if I only want one class to access my form's controls?
I implemented an Undo/Redo system in my application but because it is a separate class from my main form it cannot access any of its controls. Currently I'm passing every control that needs undoing or redoing in to the class's constructor but it is quickly becoming one of the largest constructors in my project.

It'd be nice if only this class were allowed to access to my form's controls. If I pass in the form to the constructor I still cannot access the control's because they are all private. I suppose the simple solution would be to make all the controls I need to use public but what is the ideal or elegant solution?

P.S. I have already read about the technique of having a public property for everything required and passing in the form to the constructor but that will end up being quite a bit of properties and the solution does not seem very applicable in this situation.

Thanks!

答:
accessing the controls for tracking state is aint the best way, but if thats wat you want then i would suggest you access the controls which are private through reflection
http://social.msdn.microsoft.com/forums/en-US/clr/thread/ef7cc349-cf35-4b01-95b3-b71675f9b9d5/</p>


问:
VS Code - size of description popup
I am creating a snippet for VS Code with long descriptions.
I have noticed that the description popup window in VS Code has a scrollbar, but it would be greater if I can enlarge the window? Is it possible?</p>

答:
That's definitely possible with Customize UI + Monkey Patch extensions.

Install them and then add the following to your settings.json:

"customizeUI.stylesheet": {".monaco-hover-content, .hover-contents span, .parameter-hints-widget div.code, .parameter-hints-widget div.docs": "font-size: 12px !important"}

Don't forget to reload the window to apply the changes!

Works like a charm for me with VS Code 1.63.2

Title: VS Code - size of description popup


问:
Replace link with empty string based on a wildcard
So I have the following method that I'm calling $text = $this->get('text') that returns the following items:

Uploading a photo to test the Twitter API endpoint.
pic.twitter.com/i4bV2UWkBM

Is there a way that I can take that return and find all pic.twitter.com instances and replace it with an empty string or remove the URL?

I tried to use:

```<code>$text = str_replace(
    'pic.twitter.com',
    '',
    $text
);
</code>```

But it's not working, I guess the wildcard isn't properly detecting the pic.twitter.com.

答:
You can create a regex pattern and use preg_replace() to remove the whole URL from the string:

<?php

$replaced = preg_replace(
    '/pic\.twitter\.com\/[a-zA-z0-9]{10}/',
    '',
    <<<TESTS
    Uploading a photo to test the Twitter API endpoint.
    pic.twitter.com/i4bV2UWkBM …
    pic.twitter.com/i1bx2U55BM …
    pic.twitter.com/i22x2U55BM …
    TESTS
);

echo $replaced;
```
<p>That code will print the following:</p>
```Uploading a photo to test the Twitter API endpoint.
 …
 …
 …
```

Body:
So I have the following method that I'm calling $text = $this->get('text') that returns the following items:

Uploading a photo to test the Twitter API endpoint.
pic.twitter.com/i4bV2UWkBM

Is there a way that I can take that return and find all pic.twitter.com instances and replace it with an empty string or remove the URL?

I tried to use:

$text = str_replace(
    'pic.twitter.com',
    '',
    $text
);

But it's not working, I guess the wildcard isn't properly detecting the pic.twitter.com.

Body:
You can create a regex pattern and use preg_replace() to remove the whole URL from the string:

<?php

$replaced = preg_replace(
    '/pic\.twitter\.com\/[a-zA-z0-9]{10}/',
    '',
    <<<TESTS
    Uploading a photo to test the Twitter API endpoint.
    pic.twitter.com/i4bV2UWkBM …
    pic.twitter.com/i1bx2U55BM …
    pic.twitter.com/i22x2U55BM …
    TESTS
);

echo $replaced;

That code will print the following:

Uploading a photo to test the Twitter API endpoint.
 …
 …
 …


问:
How to write my_strchr() in C
Right now I hope to write my own my_strchr() in the C language.

I checked that the answer should be like this:

```<code>char *my_strchr(const char *src1, int c) {

    while (*src1 != '\0') { //when the string goes to the last, jump out
        if (c == *src1) {
            return src1;
        }
        src1++;
    }
    return NULL;
}
</code>```

I'm quite confused by:

why we use *src1  in the while loop condition (*src1 != '\0'), is *src1 a pointer to the const char*? Can we just use src1 instead?

When we return value and src1++, we do not have that *src1, why?

For this function, it in fact prints the whole string after the required characters, but why is that? Why does it not print only the character that we need to find?

答:
In C, a string is basically an array of char, an array is a pointer pointing to the first element in the array, and a pointer is the memory address of the value. Therefore:

You can use *src1 to get the value that it is pointing to.

src1++ means to +1 on the address, so you are basically moving where the pointer is pointing at.

Since you are returning a pointer, it is essentially equal to a string (char array).

Title: How to write my_strchr() in C

Body:
Right now I hope to write my own my_strchr() in the C language.

I checked that the answer should be like this:

char *my_strchr(const char *src1, int c) {

    while (*src1 != '\0') { //when the string goes to the last, jump out
        if (c == *src1) {
            return src1;
        }
        src1++;
    }
    return NULL;
}

I'm quite confused by:

why we use *src1  in the while loop condition (*src1 != '\0'), is *src1 a pointer to the const char*? Can we just use src1 instead?

When we return value and src1++, we do not have that *src1, why?

For this function, it in fact prints the whole string after the required characters, but why is that? Why does it not print only the character that we need to find?


问:
Vuex store state not being updated
Why is this not updating the store d3 state?

```
<p>Here is the mutations for the "addHorizontalData"</p>
```mutations: {
        addHorizontalData(state, d3){
            state.d3Horizontal(d3)
        }
    },
```
<p>And here is the state. It's just a simple variable as the d1, d2 and d3 on the component.</p>
```state: {
        d3Horizontal:[],
    },
```
<p>Full Store:</p>
```import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        d3Horizontal:[],
    },
    mutations: {
        addHorizontalData(state, d3){
            state.d3Horizontal(d3)
        }
    },
})
```

答:
You're probably having a console error due to the fact that d3Horizontal is an array and not a function, therefore your code should be:

mutations: { addHorizontalData(state, d3){ state.d3Horizontal = d3; } }

Title: Vuex store state not being updated

Body:
Why is this not updating the store d3 state?

Here is the mutations for the "addHorizontalData"

mutations: {
        addHorizontalData(state, d3){
            state.d3Horizontal(d3)
        }
    },

And here is the state. It's just a simple variable as the d1, d2 and d3 on the component.

state: {
        d3Horizontal:[],
    },

Full Store:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        d3Horizontal:[],
    },
    mutations: {
        addHorizontalData(state, d3){
            state.d3Horizontal(d3)
        }
    },
})


问:
MySQL slow request on partitionned table
I am facing a complet mystery.

I have create a table to store meteorolocal data. I have one value per hour, since 1979, for every 0.25 latitude and longitude.
This brings me to have billions of lines in the database.
Following multiples advices, I partionnated the table.
I choosed to partitionnate by years. This is how it looks like :

```<code> CREATE TABLE `MyTable` (
  `latitude_100` SMALLINT NOT NULL, -- Smallint is 2 bytes, where float is 4. So we take latitude * 100
  `longitude_100` SMALLINT NOT NULL, -- Same logic here
  `time` DATETIME NOT NULL,
  `final` TINYINT UNSIGNED NOT NULL,
  `value` DOUBLE NOT NULL,
  PRIMARY KEY (`latitude_100` ASC, `longitude_100` ASC, `time` ASC)
)
PARTITION BY HASH(YEAR(time)) PARTITIONS 45 ; -- This will work until 2023 included
</code>```

In order to test, I injected in the table data only from 2015 to 2021.

The problem :
All SELECT from this table are extremly long.

Even worst, they are sometime stupidly long.
For example :

```<code>SELECT time, latitude_100, longitude_100, value
FROM MyTable
WHERE  latitude_100 BETWEEN 500 AND 2000
AND longitude_100 BETWEEN 11600 AND 12800 AND
YEAR(time) = 1990 ;
</code>```

Remember that there is NO data for 1990. By looking into the right partition, MySQL should see it immeditaly isn't it ?

MySQL explain me that it will look in all partition, which I do not understand why :

```<code>EXPLAIN SELECT time, latitude_100, longitude_100, value
FROM MyTable
WHERE  latitude_100 BETWEEN 500 AND 2000
AND longitude_100 BETWEEN 11600 AND 12800 AND
YEAR(time) = 1990 ;
# id, select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, Extra
1, SIMPLE, MyTable, p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14,p15,p16,p17,p18,p19,p20,p21,p22,p23,p24,p25,p26,p27,p28,p29,p30,p31,p32,p33,p34,p35,p36,p37,p38,p39,p40,p41,p42,p43,p44, range, PRIMARY, PRIMARY, 4, , 118295536, 11.11, Using where
</code>```

When I do

```<code>SELECT * FROM information_schema.partitions WHERE TABLE_SCHEMA='MySchema' AND TABLE_NAME = 'MyTable' AND PARTITION_NAME IS NOT NULL
</code>```

I can see that only 6 partitions have data, all other are empty.

Last think I tried was to formulate the WHERE differently, to maybe take advantage of the index :

```<code>SELECT time, latitude_100, longitude_100, value
FROM MyTable
WHERE  latitude_100 BETWEEN 500 AND 2000
AND longitude_100 BETWEEN 11600 AND 12800 AND
time BETWEEN "1990-01-01 00:00:00" AND "1990-12-31 23:00:00" AND
YEAR(time) = 1990 ;
</code>```

But this does not accelerate the execution. Only the EXPLAIN is a bit different (but not in termes of partition reading) :

```<code># id, select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, Extra
1, SIMPLE, MyTable, p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14,p15,p16,p17,p18,p19,p20,p21,p22,p23,p24,p25,p26,p27,p28,p29,p30,p31,p32,p33,p34,p35,p36,p37,p38,p39,p40,p41,p42,p43,p44, range, PRIMARY, PRIMARY, 9, , 118295536, 1.23, Using where
</code>```

What do I do wrong ?
Why MySQL does not want to cooperate with partitionning ?

Thank you very much !

[Edit]
On technical side, the database is hosted on AWS RDS. It is powered by a "db.t4g.large" instance and user MySQL 8.0.27

答:
Do not use PARTITION BY HASH!  HASH will fail to do any pruning when using a date range (as you have!).  Simply put, the Optimizer is not smart enough to see that your range fits in a single partition.  Furthermore, HASH may unnecessarily be lumping two different years into the same partition.  Instead, use PARTITION BY RANGE.

I know that RANGE(TO_DAYS(time)) works; perhaps RANGE(YEAR(time)) may work, depending on what version of MySQL you are using; check the specifics.

Hour: With some date arithmetic, you can shrink a 5-byte DATETIME down to a 3-byte MEDIUMINT.  (A suitable change to PARTITION BY RANGE would be needed.)

Not enough: Since you are testing with only 7 years of data, my Partitioning suggestion will help only by a factor of 7.

DOUBLE?  What are you measuring? DOUBLE takes 8 bytes and gives you about 16 significant digits.  Even FLOAT (4 bytes, 7 digits) is likely to be overkill.  For temperature (°C), consider DECIMAL(2) or TINYINT (-128..+127) or DECIMAL(4,2); they are 1,1,2 bytes, respectively.  Extremes recorded: -89..+57.  Note: °F would need one more byte in any INT or DECIMAL encoding.  (I would guess that an instrument too close to a volcano or wildfire would fail to transmit data if the temp exceeded 99°C.)

Shrinking the DOUBLE would shrink the dataset size by about 1/3 -- worth the effort.

If you will end up with about 400GB rows, datatype size is very important.

So, let's dig deeper...  Please provide

Amount of RAM

SHOW VARIABLES LIKE 'innodb_buffer_pool_size';

Any other SELECTs that you are likely to run, including WHERE clauses other than exactly one year.

How much disk space did your 7 years take?  If using MyISAM, I would expect about 1.2TB; if using InnoDB, 3TB.

The lat/lng ranges in the sample Select were relatively small.  Is this typical?  If so, we may be able to take advantage of it.

ENGINE -- Since this is, I assume, mostly a readonly dataset, it may be a rare case where MyISAM is better.  See estimates above; multiple by 6 to get estimates for the 43 years.

Usage -- What will you do with the results of a SELECT like the one you have?  If that is the 'only' query, then there are more compact ways to store the data.  But they will be more complex to Insert and Select.  However, the speed improvement may be worth it.  I need to see the various Selects before advising further.

Body:
I am facing a complet mystery.

I have create a table to store meteorolocal data. I have one value per hour, since 1979, for every 0.25 latitude and longitude.
This brings me to have billions of lines in the database.
Following multiples advices, I partionnated the table.
I choosed to partitionnate by years. This is how it looks like :

 CREATE TABLE `MyTable` (
  `latitude_100` SMALLINT NOT NULL, -- Smallint is 2 bytes, where float is 4. So we take latitude * 100
  `longitude_100` SMALLINT NOT NULL, -- Same logic here
  `time` DATETIME NOT NULL,
  `final` TINYINT UNSIGNED NOT NULL,
  `value` DOUBLE NOT NULL,
  PRIMARY KEY (`latitude_100` ASC, `longitude_100` ASC, `time` ASC)
)
PARTITION BY HASH(YEAR(time)) PARTITIONS 45 ; -- This will work until 2023 included

In order to test, I injected in the table data only from 2015 to 2021.

The problem :
All SELECT from this table are extremly long.

Even worst, they are sometime stupidly long.
For example :

SELECT time, latitude_100, longitude_100, value
FROM MyTable
WHERE  latitude_100 BETWEEN 500 AND 2000
AND longitude_100 BETWEEN 11600 AND 12800 AND
YEAR(time) = 1990 ;

Remember that there is NO data for 1990. By looking into the right partition, MySQL should see it immeditaly isn't it ?

MySQL explain me that it will look in all partition, which I do not understand why :

EXPLAIN SELECT time, latitude_100, longitude_100, value
FROM MyTable
WHERE  latitude_100 BETWEEN 500 AND 2000
AND longitude_100 BETWEEN 11600 AND 12800 AND
YEAR(time) = 1990 ;
# id, select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, Extra
1, SIMPLE, MyTable, p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14,p15,p16,p17,p18,p19,p20,p21,p22,p23,p24,p25,p26,p27,p28,p29,p30,p31,p32,p33,p34,p35,p36,p37,p38,p39,p40,p41,p42,p43,p44, range, PRIMARY, PRIMARY, 4, , 118295536, 11.11, Using where

When I do

SELECT * FROM information_schema.partitions WHERE TABLE_SCHEMA='MySchema' AND TABLE_NAME = 'MyTable' AND PARTITION_NAME IS NOT NULL

I can see that only 6 partitions have data, all other are empty.

Last think I tried was to formulate the WHERE differently, to maybe take advantage of the index :

SELECT time, latitude_100, longitude_100, value
FROM MyTable
WHERE  latitude_100 BETWEEN 500 AND 2000
AND longitude_100 BETWEEN 11600 AND 12800 AND
time BETWEEN "1990-01-01 00:00:00" AND "1990-12-31 23:00:00" AND
YEAR(time) = 1990 ;

But this does not accelerate the execution. Only the EXPLAIN is a bit different (but not in termes of partition reading) :

# id, select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, Extra
1, SIMPLE, MyTable, p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14,p15,p16,p17,p18,p19,p20,p21,p22,p23,p24,p25,p26,p27,p28,p29,p30,p31,p32,p33,p34,p35,p36,p37,p38,p39,p40,p41,p42,p43,p44, range, PRIMARY, PRIMARY, 9, , 118295536, 1.23, Using where

What do I do wrong ?
Why MySQL does not want to cooperate with partitionning ?

Thank you very much !

[Edit]
On technical side, the database is hosted on AWS RDS. It is powered by a "db.t4g.large" instance and user MySQL 8.0.27


问:
Separate cell value and take part of it
I'm looking for a solution for my problem. I have a table, and there is column, which contains words separate with dots. I want to take only one part of that word. I know about Substring_Index but my problem is, that word i want to take is on random position. e.g
Project1.Test1
Project1.Subproject1.Test2
Test21.Project4
I want to take only part with Test word and number. How can i take it from whole cell value

答:
Assuming that you have a table Projects with column Project:

```<code>WITH Projects AS (
    SELECT CONCAT( Project , '.' ) AS project, LOCATE('Test', Project) AS Position
    FROM Projects)
SELECT Project, substring(Project,Position,LOCATE('.',Project,Position)- Position)
from Projects;
</code>```

Here's the same query without the CTE:

```<code>SELECT Project, substring(Project,Position,LOCATE('.',Project,Position)-
   Position)
FROM (SELECT CONCAT(Project,'.') AS Project, LOCATE('Test',Project) AS
  Position
FROM Projects) AS Projects;
</code>```

In the CTE, add a dot and find the position of the word Test. In the outer query return the string starting at the Position and find the dot after that position. Subtract the two positions.

Title: Separate cell value and take part of it

Body:
Assuming that you have a table Projects with column Project:

WITH Projects AS (
    SELECT CONCAT( Project , '.' ) AS project, LOCATE('Test', Project) AS Position
    FROM Projects)
SELECT Project, substring(Project,Position,LOCATE('.',Project,Position)- Position)
from Projects;

Here's the same query without the CTE:

SELECT Project, substring(Project,Position,LOCATE('.',Project,Position)-
   Position)
FROM (SELECT CONCAT(Project,'.') AS Project, LOCATE('Test',Project) AS
  Position
FROM Projects) AS Projects;

In the CTE, add a dot and find the position of the word Test. In the outer query return the string starting at the Position and find the dot after that position. Subtract the two positions.


问:
drupal and status.net sso
I would like to implement/use (if it already exists) an SSO solution for drupal and status.net. Something like AuthDrupal for Mediawiki. A google search did not bring up anything.

When a user signs in on status.net it also does in drupal and vice-versa. It also has to change the status.net register and login links to the corresponding drupal pages

Any ideas?

答: CAS is a good choice. Drupal and StatusNet have their own CAS Authentication plugin. And you should setup Tomcat for CAS server.</p>

ContentLicense: CC BY-SA 2.5

Title: drupal and status.net sso


问:
How to add custom CSS to existing styled component?
I have an issue related to styled component.
I have a prewritten Select component and I want to write my own select component by using that.
Here are some codes that I wrote.

in the Comopnent.tsx

```<code>...
import Select from './Select'

const StyledSelect = styled(Select)`
  // CUSTOMIZED STYLES
  height: 25px;
  border-radius: 10px;
  cursor: default;
`

...

const Component1:React.FC = () => {
  ...

  return (
    <StyledSelect
        options={[
          {
            label: t('Hot'),
            value: 'hot',
          },
          {
            label: t('APR'),
            value: 'apr',
          },
          {
            label: t('Multiplier'),
            value: 'multiplier',
          },
          {
            label: t('Earned'),
            value: 'earned',
          },
          {
            label: t('Liquidity'),
            value: 'liquidity',
          },
        ]}
        onChange={handleSortOptionChange}
      />
  )
}
...
</code>```

in the Select.tsx

```<code>...
const DropDownContainer = styled.div<{ isOpen: boolean; width: number; height: number }>`
  cursor: pointer;
  width: ${({ width }) => width}px;
  position: relative;
  ...
`

const Select:React.FunctionComponent<SelectProps> = ({options, onChange}) => {
  ...

  return (
    <DropDownContainer isOpen={isOpen} ref={containerRef} {...containerSize}>
      {containerSize.width !== 0 && (
        <DropDownHeader onClick={toggling}>
          <Text>{options[selectedOptionIndex].label}</Text>
        </DropDownHeader>
      )}
      <ArrowDropDownIcon color="text" onClick={toggling} />
      <DropDownListContainer>
        <DropDownList ref={dropdownRef}>
          {options.map((option, index) =>
            index !== selectedOptionIndex ? (
              <ListItem onClick={onOptionClicked(index)} key={option.label}>
                <Text>{option.label}</Text>
              </ListItem>
            ) : null,
          )}
        </DropDownList>
      </DropDownListContainer>
    </DropDownContainer>
  )
}
...
</code>```

But CUSTOMIZED STYLES don't work.
I have some similar experience with adding custom CSS to the existing styled component like the above but I don't know why that doesn't work.
What is my fault?

答:
You forgot to accept a property className and set it on needed element.
Below is an example. Pay attention to the className in the props and set it to the container.

To style the component, you need to pass the className props. And in the component where you get that className prop, you need to assign it to the element that needs to be styled, like so:

Notice how Link takes a className and assigns it to Element "a".

```<code>const Link = ({ className, children }) => (
  <a className={className}>
    {children}
  </a>
);

const StyledLink = styled(Link)`
  color: palevioletred;
  font-weight: bold;
`;
</code>```

For more detail, check official docs.
https://styled-components.com/docs/basics#styling-any-component

```<code>const Select:React.FunctionComponent<SelectProps> = ({options, onChange, className}) => {
  ...

  return (
    <DropDownContainer className={className} isOpen={isOpen} ref={containerRef} {...containerSize}>
      {containerSize.width !== 0 && (
        <DropDownHeader onClick={toggling}>
          <Text>{options[selectedOptionIndex].label}</Text>
        </DropDownHeader>
      )}
      <ArrowDropDownIcon color="text" onClick={toggling} />
      <DropDownListContainer>
        <DropDownList ref={dropdownRef}>
          {options.map((option, index) =>
            index !== selectedOptionIndex ? (
              <ListItem onClick={onOptionClicked(index)} key={option.label}>
                <Text>{option.label}</Text>
              </ListItem>
            ) : null,
          )}
        </DropDownList>
      </DropDownListContainer>
    </DropDownContainer>
  )
}
...
</code>```

Body:
I have an issue related to styled component.
I have a prewritten Select component and I want to write my own select component by using that.
Here are some codes that I wrote.

in the Comopnent.tsx

...
import Select from './Select'

const StyledSelect = styled(Select)`
  // CUSTOMIZED STYLES
  height: 25px;
  border-radius: 10px;
  cursor: default;
`

...

const Component1:React.FC = () => {
  ...

  return (

Body:
You forgot to accept a property className and set it on needed element.
Below is an example. Pay attention to the className in the props and set it to the container.

To style the component, you need to pass the className props. And in the component where you get that className prop, you need to assign it to the element that needs to be styled, like so:

Notice how Link takes a className and assigns it to Element "a".

const Link = ({ className, children }) => (
  <a className={className}>
    {children}
  </a>
);

const StyledLink = styled(Link)`
  color: palevioletred;
  font-weight: bold;
`;

For more detail, check official docs.
https://styled-components.com/docs/basics#styling-any-component

const Select:React.FunctionComponent<SelectProps> = ({options, onChange, className}) => {
  ...

  return (
    <DropDownContainer className={className} isOpen={isOpen} ref={containerRef} {...containerSize}>
      {containerSize.width !== 0 && (
        <DropDownHeader onClick={toggling}>
          <Text>{options[selectedOptionIndex].label}</Text>
        </DropDownHeader>
      )}
      <ArrowDropDownIcon color="text" onClick={toggling} />
      <DropDownListContainer>
        <DropDownList ref={dropdownRef}>
          {options.map((option, index) =>
            index !== selectedOptionIndex ? (
              <ListItem onClick={onOptionClicked(index)} key={option.label}>
                <Text>{option.label}</Text>
              </ListItem>
            ) : null,
          )}
        </DropDownList>
      </DropDownListContainer>
    </DropDownContainer>
  )
}
...


问:
Metadata in neo4j graph database
I know that neo4j stores data structured in graphs rather than in tables. In RDBMS we will be having schemas of the tables but in neo4j we  will not be having the tables. Only nodes, relations and properties are defined. So is there any concept of metadata in neo4j. Like is there any information stored about nodes, relationships in the database? If yes, how and what it stores in the metadata? Also where can we find the metadata related information in the graph database (location)

Thanks,

答:
Meanwhile there is the official APOC Library.

This includes functions like apoc.meta.graph, apoc.meta.schema and others.

The link above describes the installation, if you run into sandbox errors, check the answers in this question

Title: Metadata in neo4j graph database


问:
Use Column Name Rather than Column Number (even after using .Offset) VBA
Here is a walkthrough of the situation:

My excel has 2 tabs, one called AssetName Sheet and the other called AMP Sheet

After clicking a vba button, the user is able to generate names in column B of the AssetName Sheet

I have another button that generates an AMP ID for the user. The easiest way for me to explain how this works is through an Index - Match function

```<code>=IFERROR(INDEX('AMP Sheet'!$L:$L,MATCH("*"&B2&"*", 'AMP Sheet'!$B:$B,0)), "Not Found")
</code>```

Column B in the AssetName Sheet is named GeneratedAssetName and column L in the AMP Sheet is named ID.

So, in this example, My_Sandwich_6S_HeroRegular_Mobile exists in the AMP Sheet. Since this is a match, it will grab the associated ID from the AMP Sheet and copy it over to column E of the AssetName Sheet:

My logic (which does the exact same thing as the function I listed in step 3) is housed within a VBA macro button. The code is shown below:

```<code>Sub AMPTabid()

Dim wsAN As Worksheet
Set wsAN = Sheets("AssetName Sheet")

Dim wsAMP As Worksheet
Set wsAMP = Sheets("AMP Sheet")

Dim LastRow As Long
LastRow = wsAN.Cells(wsAN.Rows.Count, 2).End(xlUp).Row

Dim i As Long
For i = 2 To LastRow

 Dim rFind As range
 Set rFind = wsAMP.Columns(2).Find(what:=wsAN.Cells(i, 2), LookIn:=xlValues, LookAt:=xlPart, MatchCase:=True)

 If Not rFind Is Nothing Then
     wsAN.Cells(i, 5).Value = rFind.Offset(0, 10).Value
 End If

Next i

End Sub
</code>```

Basically, I would like to use my existing code shown in step 4, but with column Names (rather than column numbers). The names I would like to use are Name and ID from the AMP Sheet.

The .Offset logic in my code is the tricky part, since it's going from column B to Column L in the AMP Sheet, so it count column L as 10, rather than 12.

Thanks!

答:
Find Headers and Lookup Values Using Application.Match

Option Explicit

Sub AMPTabid()

    ' Source
    Const sName As String = "AMP Sheet"
    Const slTitle As String = "Name"
    Const svTitle As String = "ID"
    ' Destination
    Const dName As String = "AssetName Sheet"
    Const dlTitle As String = "Generated Asset Name"
    Const dvTitle As String = "AMP ID"
    ' Workbook
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    ' Source

    Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
    Dim srg As Range: Set srg = sws.Range("A1").CurrentRegion ' Table Range
    Dim shrg As Range: Set shrg = srg.Rows(1) ' Header Range

    ' Get the column numbers.
    Dim slCol As Variant: slCol = Application.Match(slTitle, shrg, 0) ' Lookup
    Dim svCol As Variant: svCol = Application.Match(svTitle, shrg, 0) ' Value

    ' Reference the data ranges.
    Dim srCount As Long: srCount = srg.Rows.Count - 1
    Dim sdrg As Range: Set sdrg = srg.Resize(srCount).Offset(1) ' Data Range

    ' Lookup Column Range ('Application.Match' works faster with ranges)
    Dim slrg As Range: Set slrg = sdrg.Columns(slCol) ' lookup stays in range

    Dim svrg As Range: Set svrg = sdrg.Columns(svCol) ' Value Range
    Dim svData As Variant: svData = svrg.Value ' value data to array

    ' Destination

    Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
    Dim drg As Range: Set drg = dws.Range("A1").CurrentRegion ' Table Range
    Dim dhrg As Range: Set dhrg = drg.Rows(1) ' Header Range

    ' Get the column numbers.
    Dim dlCol As Variant: dlCol = Application.Match(dlTitle, dhrg, 0) ' Lookup
    Dim dvCol As Variant: dvCol = Application.Match(dvTitle, dhrg, 0) ' Value

    ' Reference the data ranges.
    Dim drCount As Long: drCount = drg.Rows.Count - 1
    Dim ddrg As Range: Set ddrg = drg.Resize(drCount).Offset(1) ' Data Range

    Dim dlrg As Range: Set dlrg = ddrg.Columns(dlCol) ' Lookup Range
    ' The same array will be used for lookup and values (results).
    Dim dData As Variant: dData = dlrg.Value ' lookup data to array

    Dim dvrg As Range: Set dvrg = ddrg.Columns(dvCol) ' to be written to

    Dim sIndex As Variant ' Source Lookup (and Value) Index
    Dim dlValue As Variant ' Destination Lookup Value
    Dim dr As Long

    For dr = 1 To drCount
        dlValue = dData(dr, 1)
        If Not IsError(dlValue) Then ' exclude error values
            If Len(dlValue) > 0 Then ' exclude blanks
                sIndex = Application.Match(dlValue, slrg, 0)
                If IsNumeric(sIndex) Then ' match found
                    dData(dr, 1) = svData(sIndex, 1)
                Else ' no match found
                    dData(dr, 1) = Empty
                End If
            End If
        End If
    Next dr

    dvrg.Value = dData

    MsgBox "Ids updated.", vbInformation

End Sub
```

Body:
Here is a walkthrough of the situation:

My excel has 2 tabs, one called AssetName Sheet and the other called AMP Sheet

After clicking a vba button, the user is able to generate names in column B of the AssetName Sheet

I have another button that generates an AMP ID for the user. The easiest way for me to explain how this works is through an Index - Match function

=IFERROR(INDEX('AMP Sheet'!$L:$L,MATCH("*"&B2&"*", 'AMP Sheet'!$B:$B,0)), "Not Found")

Column B in the AssetName Sheet is named GeneratedAssetName and column L in the AMP Sheet is named ID.

So, in this example, My_Sandwich_6S_HeroRegular_Mobile exists in the AMP Sheet. Since this is a match, it will grab the associated ID from the AMP Sheet and copy it over to column E of the AssetName Sheet:

My logic (which does the exact same thing as the function I listed in step 3) is housed within a VBA macro button. The code is shown below:

Sub AMPTabid()

Dim wsAN As Worksheet
Set wsAN = Sheets("AssetName Sheet")

Dim wsAMP As Worksheet
Set wsAMP = Sheets("AMP Sheet")

Dim LastRow As Long
LastRow = wsAN.Cells(wsAN.Rows.Count, 2).End(xlUp).Row

Dim i As Long
For i = 2 To LastRow

 Dim rFind As range
 Set rFind = wsAMP.Columns(2).Find(what:=wsAN.Cells(i, 2), LookIn:=xlValues, LookAt:=xlPart, MatchCase:=True)

 If Not rFind Is Nothing Then
     wsAN.Cells(i, 5).Value = rFind.Offset(0, 10).Value
 End If

Next i

End Sub

Basically, I would like to use my existing code shown in step 4, but with column Names (rather than column numbers). The names I would like to use are Name and ID from the AMP Sheet.

The .Offset logic in my code is the tricky part, since it's going from column B to Column L in the AMP Sheet, so it count column L as 10, rather than 12.

Thanks!


问:
Visual Basic Loops Even When Condition Isn't Met
I'm trying to program a motorized stage in an xy array configuration in visual basic. I take the n x n array size as input from the user and I move the stages accordingly. Here I am testing a value of 3 so a 3x3 array, The problem occurs with the outer y loop. When County reaches a value of 4, larger than the 3, the loop iterates again, adding another row to my array. Why is it iterating again even though the loop condition isn't satisfied?

Countx and County are my counters and increment every time the stage is moved. Switch is to alternate between the x stage moving back and forth (in a snake pattern)

```<code>    Dim countx As Integer = 1
    Dim county As Integer = 1

    Dim switch As Integer = 1

    While county <= arraysize

        If switch = 1 Then
            While countx < arraysize
                AxMG17Motor1.MoveJog(0, 1)
                countx = countx + 1
                Await Task.Delay(5000)
            End While
            switch = -1
            county += 1
            AxMG17Motor2.MoveJog(0, 1)
            Await Task.Delay(5000)

        End If

        If switch = -1 Then
            While countx > 1
                AxMG17Motor1.MoveJog(0, 2)
                countx = countx - 1
                Await Task.Delay(5000)
            End While
            switch = 1
            county += 1
            AxMG17Motor2.MoveJog(0, 1)
            Await Task.Delay(5000)

        End If

    End While
</code>```

答:
Personally, I prefer absolute moves if possible. You can iterate over the indices and create locations.

I believe you can also be more accurate in allowing the motors to both complete their moves, rather than a "blind" 5 second wait. I am not sure about the thread safety of AxMG17MotorLib moving multiple stages asynchronously, but it's worth a try.

Dim rows = 3
Dim cols = 3
Dim jogSizeX = 5
Dim jogSizeY = 10
Dim originX As Single
Dim originY As Single
AxMG17Motor1.GetPosition(0, originX)
AxMG17Motor2.GetPosition(0, originY)
Dim locations = Enumerable.Range(0, rows - 1).
    Select(Function(r) If(r Mod 2 = 0, Enumerable.Range(0, cols - 1).Select(Function(c) New PointF(r, c)),
                                       Enumerable.Range(cols - 1, 0).Select(Function(c) New PointF(r, c)))).
    SelectMany(Function(p) p)
For Each location In locations
    Dim absoluteX = location.X * jogSizeX + originX
    Dim absoluteY = location.Y * jogSizeY + originY
    AxMG17Motor1.SetAbsMovePos(0, absoluteX)
    AxMG17Motor2.SetAbsMovePos(0, absoluteY)
    Await Task.WhenAll({Task.Run(Sub() AxMG17Motor1.MoveAbsolute(0, True)),
                        Task.Run(Sub() AxMG17Motor2.MoveAbsolute(0, True))})
    Console.WriteLine($"Moved to absolute location: ({absoluteX}, {absoluteY}), relative index: ({location.X}, {location.Y})")
Next
```

Body:
I'm trying to program a motorized stage in an xy array configuration in visual basic. I take the n x n array size as input from the user and I move the stages accordingly. Here I am testing a value of 3 so a 3x3 array, The problem occurs with the outer y loop. When County reaches a value of 4, larger than the 3, the loop iterates again, adding another row to my array. Why is it iterating again even though the loop condition isn't satisfied?

Countx and County are my counters and increment every time the stage is moved. Switch is to alternate between the x stage moving back and forth (in a snake pattern)

    Dim countx As Integer = 1
    Dim county As Integer = 1

    Dim switch As Integer = 1

    While county <= arraysize

        If switch = 1 Then
            While countx < arraysize
                AxMG17Motor1.MoveJog(0, 1)
                countx = countx + 1
                Await Task.Delay(5000)
            End While
            switch = -1
            county += 1
            AxMG17Motor2.MoveJog(0, 1)
            Await Task.Delay(5000)

        End If

        If switch = -1 Then
            While countx > 1
                AxMG17Motor1.MoveJog(0, 2)
                countx = countx - 1
                Await Task.Delay(5000)
            End While
            switch = 1
            county += 1
            AxMG17Motor2.MoveJog(0, 1)
            Await Task.Delay(5000)

        End If

    End While


问:
How to have an inherited callback in ruby that is triggered after the child class is defined instead of before

Possible Duplicate:

  ruby: can I have something like Class#inherited that's triggered only after the class definition?

```<code>class A
  def self.inherited(child)
    puts "XXX"
  end
end

class B < A
  puts "YYY"
end
</code>```

prints out

```<code>XXX
YYY
</code>```

I'd prefer

```<code>YYY
XXX
</code>```

if I could get it somehow.

答:
You can trace until you find the end of the class definition. I did it in a method which I called after_inherited:

```<code>class Class
  def after_inherited child = nil, &blk
    line_class = nil
    set_trace_func(lambda do |event, file, line, id, binding, classname|
      unless line_class
        # save the line of the inherited class entry
        line_class = line if event == 'class'
      else
        # check the end of inherited class
        if line == line_class && event == 'end'
          # if so, turn off the trace and call the block
          set_trace_func nil
          blk.call child
        end
      end
    end)
  end
end

# testing...

class A
  def self.inherited(child)
    after_inherited do
      puts "XXX"
    end
  end
end

class B < A
  puts "YYY"
  # .... code here can include class << self, etc.
end
</code>```

Output:

```<code>YYY
XXX
</code>```

Body:
Possible Duplicate:

  ruby: can I have something like Class#inherited that's triggered only after the class definition?

class A
  def self.inherited(child)
    puts "XXX"
  end
end

class B < A
  puts "YYY"
end

prints out

XXX
YYY

I'd prefer

YYY
XXX

if I could get it somehow.

Body:
You can trace until you find the end of the class definition. I did it in a method which I called after_inherited:

class Class
  def after_inherited child = nil, &blk
    line_class = nil
    set_trace_func(lambda do |event, file, line, id, binding, classname|
      unless line_class
        # save the line of the inherited class entry
        line_class = line if event == 'class'
      else
        # check the end of inherited class
        if line == line_class && event == 'end'
          # if so, turn off the trace and call the block
          set_trace_func nil
          blk.call child
        end
      end
    end)
  end
end

# testing...

class A
  def self.inherited(child)
    after_inherited do
      puts "XXX"
    end
  end
end

class B < A
  puts "YYY"
  # .... code here can include class << self, etc.
end

Output:

YYY
XXX


问:
Laravel storage link won't work on production
I'm using storage_path to save my images and I symbolic my storage folder to public_html

```<code>php artisan storage:link
</code>```

On the local everything works fine, when I upload an image it will upload in storage folder and link of it will appear in public folder but since I moved to live host and production mode my images will upload in storage folder but nothing in my public_html/storage and I'm not able to get them in my front-end.

Codes

/config/filesystems.php

```<code>'public' => [
  'driver' => 'local',
  'root' => storage_path('app/public/'),
  'url' => env('APP_URL').'/storage',
  'visibility' => 'public',
],
</code>```

.env

```<code>FILESYSTEM_DRIVER=public
</code>```

controller sample

```<code>if ($request->hasFile('image')) {
  $image = $request->file('image');
  $filename = 'page' . '-' . time() . '.' . $image->getClientOriginalExtension();
  $location = storage_path('app/public/images/' . $filename);
  Image::make($image)->resize(1200, 600)->save($location);
  if(!empty($page->image)){
    Storage::delete('images/' . $page->image);
  }
  $page->image = $filename;
}
</code>```

any idea?

答:
I had this issue on shared web hosting and also i had no access to terminal.
this was the Error

symlink(): No such file or directory

So,
Just create a folder named 'public' in my root (same address with app,vendor,config,... folders)

then i did :

```<code>    Artisan::call('storage:link');
</code>```

Because you changed "public" folder's name on production to "public_html" and there is no "public" folder depend on default configs on Laravel 8
remember set all configs on config/filesystem and ... to default.

after all, if the symbolic was created, you can remove 'public_html' and rename "public" folder to "public_html"!
That's it

Body:
I'm using storage_path to save my images and I symbolic my storage folder to public_html

php artisan storage:link

On the local everything works fine, when I upload an image it will upload in storage folder and link of it will appear in public folder but since I moved to live host and production mode my images will upload in storage folder but nothing in my public_html/storage and I'm not able to get them in my front-end.

Codes

/config/filesystems.php

'public' => [
  'driver' => 'local',
  'root' => storage_path('app/public/'),
  'url' => env('APP_URL').'/storage',
  'visibility' => 'public',
],

.env

FILESYSTEM_DRIVER=public

controller sample

if ($request->hasFile('image')) {
  $image = $request->file('image');
  $filename = 'page' . '-' . time() . '.' . $image->getClientOriginalExtension();
  $location = storage_path('app/public/images/' . $filename);
  Image::make($image)->resize(1200, 600)->save($location);
  if(!empty($page->image)){
    Storage::delete('images/' . $page->image);
  }
  $page->image = $filename;
}

any idea?

Body:
I had this issue on shared web hosting and also i had no access to terminal.
this was the Error

symlink(): No such file or directory

So,
Just create a folder named 'public' in my root (same address with app,vendor,config,... folders)

then i did :

    Artisan::call('storage:link');

Because you changed "public" folder's name on production to "public_html" and there is no "public" folder depend on default configs on Laravel 8
remember set all configs on config/filesystem and ... to default.

after all, if the symbolic was created, you can remove 'public_html' and rename "public" folder to "public_html"!
That's it


问:
I have a problem with elif statement and else statement and dictionary in python
The Code

```<code>men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}

def mo():
    r1 = input('Please Enter The Number: ')
    r = int(r1)
    if r in men:
        print(men[r])
    elif len(str(r)) > 10:
        print('This is invalid number')
    elif len(str(r)) < 10:
        print('This is invalid number')
    elif r not in men:
        print('Sorry, the number is not found')
    else:
        print('This is invalid number')
</code>```

what I want is that the console print 'This is invalid number' if i have entered any data type in the console except integer but error show up in the console page

OutPut

```<code>Please Enter The Number: d
Traceback (most recent call last):
  File "C:\Users\walee\PycharmProjects\pythonProject\main.py", line 19, in <module>
    mo()
  File "C:\Users\walee\PycharmProjects\pythonProject\main.py", line 7, in mo
    r = int(r1)
ValueError: invalid literal for int() with base 10: 'd'

Process finished with exit code 1
</code>```

first screenshot
second screenshot

答:
Wrap the input statement in a while True loop.  Break out of the loop if they enter a number.

```<code>while True:
    r1 = input("Enter the number: ")
    if r1.isdigit():
        break
    else:
        print("Invalid number, please try again")

r1 = int(r1)
# ... continue with rest of the code
</code>```

Body:
The Code

men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}

def mo():
    r1 = input('Please Enter The Number: ')
    r = int(r1)
    if r in men:
        print(men[r])
    elif len(str(r)) > 10:
        print('This is invalid number')
    elif len(str(r)) < 10:
        print('This is invalid number')
    elif r not in men:
        print('Sorry, the number is not found')
    else:
        print('This is invalid number')

what I want is that the console print 'This is invalid number' if i have entered any data type in the console except integer but error show up in the console page

OutPut

Please Enter The Number: d
Traceback (most recent call last):
  File "C:\Users\walee\PycharmProjects\pythonProject\main.py", line 19, in <module>
    mo()
  File "C:\Users\walee\PycharmProjects\pythonProject\main.py", line 7, in mo
    r = int(r1)
ValueError: invalid literal for int() with base 10: 'd'

Process finished with exit code 1

first screenshot
second screenshot

Body:
Wrap the input statement in a while True loop.  Break out of the loop if they enter a number.

while True:
    r1 = input("Enter the number: ")
    if r1.isdigit():
        break
    else:
        print("Invalid number, please try again")

r1 = int(r1)
# ... continue with rest of the code


问:
How do I log off all currently logged on users?
I would like to create a GPO that includes a scheduled task, that should be run once every day. The scheduled task should get a list of all users currently logged on a specific workstation and log them off (just lock Windows would be prefered, but a regular log off seems easier to make)

First I tried to execute the following with the scheduled task:
"shutdown.exe /f /l" to log off users. But the command was being executed by the SYSTEM user, so all regular users was not being logged off.

2nd idea was then to create a Powershell Script and place on each workstation. The script should be able to extract all currently logged on users on the workstation and log off / lock screen for all users.

```<code>$Sessions = quser

# Parse the session IDs from the output
$SessionIds = ($Sessions -split ' +')[3]
$SessionIds

# Loop through each session ID and pass each to the logoff command
ForEach-Object ($SessionId in $SessionIds){
    logoff $SessionId
    }
</code>```

答:
Neither of the above solutions worked for me for all cases because of the variation in blank fields and time formatting.  The following worked better.</p>
```<code>$first = 1
quser | ForEach-Object {
    if ($first -eq 1) {
        $userPos = $_.IndexOf("USERNAME")
        $sessionPos = $_.IndexOf("SESSIONNAME")
        $idPos = $_.IndexOf("ID")
        $statePos = $_.IndexOf("STATE")
        $first = 0
    }
    else {
        $user = $_.substring($userPos,$sessionPos-$userPos).Trim()
        $session = $_.substring($sessionPos,$idPos-$sessionPos).Trim()
        $id = $_.substring($idPos,$statePos-$idPos).Trim()
        Write-Output "Logging off user:$user session:$session id:$id"
        logoff $id
    }
}
</code>```

Body:
I would like to create a GPO that includes a scheduled task, that should be run once every day. The scheduled task should get a list of all users currently logged on a specific workstation and log them off (just lock Windows would be prefered, but a regular log off seems easier to make)

First I tried to execute the following with the scheduled task:
"shutdown.exe /f /l" to log off users. But the command was being executed by the SYSTEM user, so all regular users was not being logged off.

2nd idea was then to create a Powershell Script and place on each workstation. The script should be able to extract all currently logged on users on the workstation and log off / lock screen for all users.

$Sessions = quser

# Parse the session IDs from the output
$SessionIds = ($Sessions -split ' +')[3]
$SessionIds

# Loop through each session ID and pass each to the logoff command
ForEach-Object ($SessionId in $SessionIds){
    logoff $SessionId
    }

Body:
Neither of the above solutions worked for me for all cases because of the variation in blank fields and time formatting.  The following worked better.

$first = 1
quser | ForEach-Object {
    if ($first -eq 1) {
        $userPos = $_.IndexOf("USERNAME")
        $sessionPos = $_.IndexOf("SESSIONNAME")
        $idPos = $_.IndexOf("ID")
        $statePos = $_.IndexOf("STATE")
        $first = 0
    }
    else {
        $user = $_.substring($userPos,$sessionPos-$userPos).Trim()
        $session = $_.substring($sessionPos,$idPos-$sessionPos).Trim()
        $id = $_.substring($idPos,$statePos-$idPos).Trim()
        Write-Output "Logging off user:$user session:$session id:$id"
        logoff $id
    }
}


问:
Unable to start kafka with zookeeper (kafka.common.InconsistentClusterIdException)
Below the steps I did to get this issue :

Launch ZooKeeper

Launch Kafka : .\bin\windows\kafka-server-start.bat .\config\server.properties

And at the second step the error happens :

ERROR Fatal error during KafkaServer startup. Prepare to shutdown
  (kafka.server.KafkaServer)
  kafka.common.InconsistentClusterIdException: The Cluster ID
  Reu8ClK3TTywPiNLIQIm1w doesn't match stored clusterId
  Some(BaPSk1bCSsKFxQQ4717R6Q) in meta.properties. The broker is trying
  to join the wrong cluster. Configured zookeeper.connect may be wrong.
          at kafka.server.KafkaServer.startup(KafkaServer.scala:220)
          at kafka.server.KafkaServerStartable.startup(KafkaServerStartable.scala:44)
          at kafka.Kafka$.main(Kafka.scala:84)
          at kafka.Kafka.main(Kafka.scala)

When I trigger .\bin\windows\kafka-server-start.bat .\config\server.properties zookeeper console returns :

INFO  [SyncThread:0:FileTxnLog@216] - Creating new log file: log.1

How to fix this issue to get kafka running ?

Edit You can access to the proper issue on the right site (serverfault) here

Edit Here is the Answer

答:
I also deleted all the content of the folder containing all data generated by Kafka. I could find the folder in my .yml file:

```<code> kafka:
    image: confluentinc/cp-kafka:7.0.0
    ports:
      - '9092:9092'
    environment:
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181"
      KAFKA_BROKER_ID: 1
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_CFG_AUTO_CREATE_TOPICS_ENABLE: "true"
    volumes:
      - ./kafka-data/data:/var/lib/kafka/data
    depends_on:
      - zookeeper
    networks:
      - default
</code>```

Under volumes: stays the location. So, in my case I deleted all files of the data folder located under kafka-data.

Body:
I also deleted all the content of the folder containing all data generated by Kafka. I could find the folder in my .yml file:

 kafka:
    image: confluentinc/cp-kafka:7.0.0
    ports:
      - '9092:9092'
    environment:
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181"
      KAFKA_BROKER_ID: 1
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_CFG_AUTO_CREATE_TOPICS_ENABLE: "true"
    volumes:
      - ./kafka-data/data:/var/lib/kafka/data
    depends_on:
      - zookeeper
    networks:
      - default

Under volumes: stays the location. So, in my case I deleted all files of the data folder located under kafka-data.


问:
How to navigate on path by button click in react router v4?
I have this paths in react-router-dom:

```<code> <BrowserRouter>
  <div>
  <Route exact path='/(index.html)?' component={Home}/> {/* app = home */}
  <Route  path='/register' component={Registration}/>
  </div>
</BrowserRouter>
</code>```

everything is working fine, now anywhere in my components I want to change path by onClick, a code like this:

```<code><button onClick={() => history.push('/the/path') }> change path </button>
</code>```

how can I do that?

答:
in react-router-dom version 6 use useNavigate

```<code>import { useNavigate } from "react-router-dom";
import { Button } from "@mui/material";
...
const navigate = useNavigate();
<Button
   onClick={() => navigate("/your-path-here")}>
click me
</Button>
</code>```

do not forget to install from mui.com to use the <Button></Button> component

Body:
I have this paths in react-router-dom:

 <BrowserRouter>

  <Route exact path='/(index.html)?' component={Home}/> {/* app = home */}
  <Route  path='/register' component={Registration}/>

</BrowserRouter>

everything is working fine, now anywhere in my components I want to change path by onClick, a code like this:

<button onClick={() => history.push('/the/path') }> change path </button>

how can I do that?

Body:
in react-router-dom version 6 use useNavigate

import { useNavigate } from "react-router-dom";
import { Button } from "@mui/material";
...
const navigate = useNavigate();
<Button
   onClick={() => navigate("/your-path-here")}>
click me
</Button>

do not forget to install from mui.com to use the <Button></Button> component


问:
How do I clear specific columns in DataGrid?
i am using WPF, connected to SQL DataBase via LinqToSql.
I have filled DataGrid using ItemsSource.

I would like to clear everything in my DataGrid, except first two rows(ID,first and second name), and Headers ofcourse, by pressing a button. All items i would like to(either set to null or 0) remove, are floats, but I can't find the right logic to do that.

Here is the picture of my DataGrid-->

```<code>public partial class Spisak : Microsoft.Office.Interop.Excel.Window
{
    DiplomskiDataContext diplomski = new DiplomskiDataContext();
    public Spisak()
    {
        InitializeComponent();

        dataGridRadnici.ItemsSource = diplomski.Radniks.ToList();
    }
}
</code>```

This is my code behind, and here is Xaml code:

```<code><DataGrid HorizontalAlignment="Left" Name="dataGridRadnici" AutoGenerateColumns="False" Height="260" Margin="10,120,0,0" VerticalAlignment="Top" Width="550">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Ime" Binding="{Binding Ime}"></DataGridTextColumn>
            <DataGridTextColumn Header="Prezime" Binding="{Binding Prezime}"></DataGridTextColumn>
            <DataGridTextColumn Header="BrSati" Binding="{Binding BrojSati, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
            <DataGridTextColumn Header="Prekovremeni" Binding="{Binding BrojPrekovremenih, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
            <DataGridTextColumn Header="Gorivo" Binding="{Binding BrojDana, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
            <DataGridTextColumn Header="Bonus" Binding="{Binding Bonus}"></DataGridTextColumn>
            <DataGridTextColumn Header="VracanjeDuga" Binding="{Binding VracanjeDuga}"></DataGridTextColumn>
            <DataGridTextColumn Header="UkZarada" Binding="{Binding UkupnaPlata, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
            <DataGridTextColumn Header="UkSaGorivom" Binding="{Binding UkupnoSaGorivom, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
        </DataGrid.Columns>
        <DataGrid.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Izmeni" Click="MenuItem_Click"></MenuItem>
                <MenuItem Header="Obrisi" Click="MenuItem_Click_1"></MenuItem>
            </ContextMenu>
        </DataGrid.ContextMenu>
    </DataGrid>
</code>```

答:
Change the type of the columns that you want to be able to blank out from float to Nullable<float> (float?) and simply set the properties to null:

```<code>var sourceList = dataGridRadnici.ItemsSource as List<Radnik>; //or whatever your data is called
foreach (var item in sourceList)
{
    item.BrojPrekovremenih = null; // or 0
    //set the other properties the same way...
}
</code>```

You also need to implement the INotifyPropertyChanged interface and raise property change notifications in your data class.

Body:
i am using WPF, connected to SQL DataBase via LinqToSql.
I have filled DataGrid using ItemsSource.

I would like to clear everything in my DataGrid, except first two rows(ID,first and second name), and Headers ofcourse, by pressing a button. All items i would like to(either set to null or 0) remove, are floats, but I can't find the right logic to do that.

Here is the picture of my DataGrid-->

public partial class Spisak : Microsoft.Office.Interop.Excel.Window
{
    DiplomskiDataContext diplomski = new DiplomskiDataContext();
    public Spisak()
    {
        InitializeComponent();

        dataGridRadnici.ItemsSource = diplomski.Radniks.ToList();
    }
}

This is my code behind, and here is Xaml code:

<DataGrid HorizontalAlignment="Left" Name="dataGridRadnici" AutoGenerateColumns="False" Height="260" Margin="10,120,0,0" VerticalAlignment="Top" Width="550">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Ime" Binding="{Binding Ime}"></DataGridTextColumn>
            <DataGridTextColumn Header="Prezime" Binding="{Binding Prezime}"></DataGridTextColumn>
            <DataGridTextColumn Header="BrSati" Binding="{Binding BrojSati, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
            <DataGridTextColumn Header="Prekovremeni" Binding="{Binding BrojPrekovremenih, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
            <DataGridTextColumn Header="Gorivo" Binding="{Binding BrojDana, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
            <DataGridTextColumn Header="Bonus" Binding="{Binding Bonus}"></DataGridTextColumn>
            <DataGridTextColumn Header="VracanjeDuga" Binding="{Binding VracanjeDuga}"></DataGridTextColumn>
            <DataGridTextColumn Header="UkZarada" Binding="{Binding UkupnaPlata, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
            <DataGridTextColumn Header="UkSaGorivom" Binding="{Binding UkupnoSaGorivom, Converter={StaticResource ThreePlaceConverter}}"></DataGridTextColumn>
        </DataGrid.Columns>
        <DataGrid.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Izmeni" Click="MenuItem_Click"></MenuItem>
                <MenuItem Header="Obrisi" Click="MenuItem_Click_1"></MenuItem>
            </ContextMenu>
        </DataGrid.ContextMenu>
    </DataGrid>

Body:
Change the type of the columns that you want to be able to blank out from float to Nullable<float> (float?) and simply set the properties to null:

var sourceList = dataGridRadnici.ItemsSource as List<Radnik>; //or whatever your data is called
foreach (var item in sourceList)
{
    item.BrojPrekovremenih = null; // or 0
    //set the other properties the same way...
}

You also need to implement the INotifyPropertyChanged interface and raise property change notifications in your data class.