问:
receive "Uncaught ReferenceError: require is not defined" when use "require" keyword in google v8
I am new google to google v8.

I modified v8 hello world app.

```<code>const char* testJS = R"(
   var assert = require("assert");
   1 + 2;
)";
v8::Local<v8::Script> script = v8::Script::Compile(context, testJS).ToLocalChecked();
</code>```

https://chromium.googlesource.com/v8/v8/+/branch-heads/5.8/samples/hello-world.cc

but got exception when running

```<code>Uncaught ReferenceError: require is not defined
</code>```

So my question is, how could I
1) use 'require' in google v8
2) Make a custom common javascript class could be used as 'require(xyz)'

is they are related to v8::StartupData, but I don't know how to setup them correctly. Any advice would be appreciated.

thanks

答: The function require() is not a part of ECMAScript. If you need it, you have to implement it by yourself.

Body:
I am new google to google v8.

I modified v8 hello world app.

const char* testJS = R"(
   var assert = require("assert");
   1 + 2;
)";
v8::Local<v8::Script> script = v8::Script::Compile(context, testJS).ToLocalChecked();

https://chromium.googlesource.com/v8/v8/+/branch-heads/5.8/samples/hello-world.cc

but got exception when running

Uncaught ReferenceError: require is not defined

So my question is, how could I
1) use 'require' in google v8
2) Make a custom common javascript class could be used as 'require(xyz)'

is they are related to v8::StartupData, but I don't know how to setup them correctly. Any advice would be appreciated.

thanks


来源: stackexchange

问:
Finding an existing file with access vba
I am trying to find an existing file in a folder location

Current Code:

```<code>Dim FileExistsbol As Boolean
Dim stFileName As String
stFileName = "H:\Test File.txt"
stFileName = Trim(stFileName)
FileExistsbol = dir(stFileName) <> vbNullString
If FileExistsbol Then Kill stFileName
</code>```

Error:

The error message is: Type Mismatch
VBA debugs on this line:

```<code>FileExistsbol = dir(stFileName) <> vbNullString
</code>```

The file does exist so unsure how to resolve this - Any ideas?

答:
I would get rid of the FileExistsbol variable and then just do something like:</p>

```<code>If Dir(stFileName) <> "" Then
    Kill stFileName
End If
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to find an existing file in a folder location

Current Code:

Dim FileExistsbol As Boolean
Dim stFileName As String
stFileName = "H:\Test File.txt"
stFileName = Trim(stFileName)
FileExistsbol = dir(stFileName) <> vbNullString
If FileExistsbol Then Kill stFileName

Error:

The error message is: Type Mismatch
VBA debugs on this line:

FileExistsbol = dir(stFileName) <> vbNullString

The file does exist so unsure how to resolve this - Any ideas?

Body:
I would get rid of the FileExistsbol variable and then just do something like:

If Dir(stFileName) <> "" Then
    Kill stFileName
End If


问:
Spring Oauth2 : Authentication Object was not found in the SecurityContext
I have a project where i implement Spring security and Spring OAuth2 Security.When i request for access token it works well but when i request for resource using access token i got 'An authentication object was not found in the SecurityContext'.

SecurityContext of my project is :

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:oauth2="http://www.springframework.org/schema/security/oauth2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2
       http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security.xsd">

<global-method-security jsr250-annotations="enabled" />
<http pattern="/**/*.css" security="none" />
<http pattern="/**/*.css.map" security="none" />

<http pattern="/**/*.gif" security="none" />
<http pattern="/**/*.html" security="none" />
<http pattern="/**/*.ttf" security="none" />
<http pattern="/**/*.eot" security="none" />
<http pattern="/**/*.svg" security="none" />
<http pattern="/**/*.woff" security="none" />
<http pattern="/**/*.woff2" security="none" />
<http pattern="/**/*.xls" security="none" />
<http pattern="/**/*.ico" security="none" />
<http pattern="/**/*.jpg" security="none" />
<http pattern="/**/*.js" security="none" />
<http pattern="/**/*.png" security="none" />
<http pattern="/**/*.xml" security="none" />
<http pattern="/**/*.mp4" security="none" />
<http pattern="editCustomerTrnx" security="none"/>
<!--<http pattern="/embed/*" security="none"/> -->

<!-- Default URL provided by spring to get the token(access and refresh) from oauth -->
<http pattern="/oauth/token" create-session="never"
      authentication-manager-ref="clientAuthenticationManager"
      xmlns="http://www.springframework.org/schema/security">
    <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY"/>
    <http-basic entry-point-ref="clientAuthenticationEntryPoint"/>
    <!-- Using this to authenticate client using request parameter -->
    <custom-filter ref="clientCredentialsTokenEndPointFilter" after="BASIC_AUTH_FILTER"/>
    <access-denied-handler ref="oauthAccessDeniedHandler"/>
</http>

<!-- The OAuth2 protected resources are separated out into their own block so we can deal with authorization and error handling
      separately. This isn't mandatory, but it makes it easier to control the behaviour -->
<http pattern="/Api/**" create-session="stateless" entry-point-ref="oauthAuthenticationEntryPoint"
      access-decision-manager-ref="accessDecisionManager"
      xmlns="http://www.springframework.org/schema/security">
   <anonymous enabled="false"/>
   <intercept-url pattern="/Api/**" access="ROLE_ADMIN"/>
   <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
   <access-denied-handler ref="oauthAccessDeniedHandler"/>
</http>

<!-- 2 -->
<http auto-config="true">
    <intercept-url pattern="/Admin/**"
        access="ROLE_ADMINISTRATOR,ROLE_AUTHENTICATED" requires-channel="any" />
    <intercept-url pattern="/Seller/**" access="ROLE_AUTHENTICATED,ROLE_SELLER"
        requires-channel="any" />
    <intercept-url pattern="/login/**" access="IS_AUTHENTICATED_ANONYMOUSLY"
        requires-channel="any" />
    <intercept-url  pattern="/" access="IS_AUTHENTICATED_ANONYMOUSLY"
        requires-channel="any" />
    <!-- <remember-me key="remittancerm" /> -->
    <custom-filter position="CONCURRENT_SESSION_FILTER" ref="customSessionFilter" />
    <form-login login-page="/main"

        authentication-failure-handler-ref="failureHandler"
        always-use-default-target="false" default-target-url="/"
        authentication-success-handler-ref="ash" />
    <logout logout-url="/logout" logout-success-url="/" />
    <access-denied-handler ref="" error-page="/" />
    <!-- authentication-failure-url="/main?errormessage=authentication.login.failed" -->
    <session-management
        session-authentication-strategy-ref="sls" />
    <port-mappings>
        <port-mapping http="8080" https="8443" />
    </port-mappings>
</http>

<authentication-manager alias="authenticationManager" xmlns="http://www.springframework.org/schema/security">
    <authentication-provider> <!-- user-service-ref="userDetailService" -->
        <user-service>
           <user name="subash" authorities="ROLE_ADMIN" password="123456"/>
        </user-service>
        <!-- <password-encoder ref="passwordEncoder">
        </password-encoder> -->
    </authentication-provider>
</authentication-manager>

<beans:bean id="ash"
    class="com.remittance.session.CustomSavedRequestAwareAuthenticationSuccessHandler">
</beans:bean>

<beans:bean id="failureHandler" class="com.remittance.session.CustomAuthenticationFailureHandler">
</beans:bean>
<beans:bean id="forbiddenEntryPoint"
    class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />

<beans:bean id="customSessionFilter" class="com.remittance.session.CustomSessionFilter">
    <beans:constructor-arg ref="sessionRegistry" />
</beans:bean>

<beans:bean id="sls"
    class="com.remittance.session.SessionLoggingStrategy">
    <beans:constructor-arg ref="sas" />
    <beans:constructor-arg ref="sessionLogApi" />
</beans:bean>

<beans:bean id="sas"
    class="com.remittance.session.PersistingConcurrentSessionControlStrategy">
    <beans:constructor-arg name="sessionRegistry"
        ref="sessionRegistry" />
    <beans:constructor-arg name="sessionApi" ref="sessionApi" />
    <beans:property name="maximumSessions" value="-1" />
</beans:bean>

<beans:bean id="sessionRegistry"
    class="com.remittance.session.PersistingSessionRegistry">
    <beans:constructor-arg ref="sessionApi" />
</beans:bean>

<beans:bean id="userDetailService"
    class="com.remittance.session.UserDetailsServiceImpl">
    <beans:constructor-arg ref="userRepository" />
</beans:bean>

<beans:bean id="passwordEncoder"
    class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />

<beans:bean id="userTest" class="com.remittance.session.UserTest">
    <beans:constructor-arg ref="userRepository" />
</beans:bean>

<!-- OAuth2 Security  -->

<!-- Resource protected by oauth2 security -->

<!-- OAuth Client Details -->
<oauth2:client-details-service id="clientDetails">
   <oauth2:client client-id="android5.5" secret="1234567890" authorized-grant-types="password,authorization_code,refresh_token,implicit,client_credentials"
                 authorities="ROLE_CLIENT,ROLE_TRUSTED_CLIENT" scope="read,write,trust"/>
   <oauth2:client client-id="nokia3320" secret="0987654321" authorized-grant-types="password,authorization_code,refresh_token,implicit,client_credentials"
                 authorities="ROLE_CLIENT,ROLE_TRUSTED_CLIENT" scope="read,write,trust"/>
</oauth2:client-details-service>

 <!-- This defined token store, we have used in memory token store for now but this can be changed to a user defined one -->
 <beans:bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore"/>

 <!-- Load User By User name -->
 <beans:bean id="clientDetailsUserDetailsService" class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
    <beans:constructor-arg ref="clientDetails"/>
 </beans:bean>

 <!-- This is where we defined token based configurations, token validity and other things -->
 <beans:bean id="tokenService" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
   <beans:property name="tokenStore" ref="tokenStore"/>
   <beans:property name="accessTokenValiditySeconds" value="500"/>
   <beans:property name="clientDetailsService" ref="clientDetails"/>
   <beans:property name="supportRefreshToken" value="true"/>
 </beans:bean>

 <!-- It Determine whether a given client authentication request has been approved by user or not -->
 <!-- ToeknStoreUserApprovalHandler : A user approval handler that remembers approval decisions by consulting existing tokens -->
 <beans:bean id="userApprovalHandler" class="org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler">
    <beans:property name="tokenStore" ref="tokenStore"/>
    <beans:property name="requestFactory" ref="oauth2RequestFactory"/>
 </beans:bean>

 <!-- Server issuing access token to the client after successfully authenticating the resource owner and obtaining authorization -->
 <oauth2:authorization-server client-details-service-ref="clientDetails" token-services-ref="tokenService"
                             user-approval-handler-ref="userApprovalHandler">
     <!-- <oauth2:authorization-code/> -->
     <!-- <oauth2:client-credentials/> -->
     <!-- <oauth2:implicit/> -->
     <oauth2:password/>
     <!-- <oauth2:refresh-token/> -->
 </oauth2:authorization-server>

 <authentication-manager id="clientAuthenticationManager">
     <authentication-provider user-service-ref="clientDetailsUserDetailsService"/>
 </authentication-manager>

 <!-- Include this if you need to authenticate client via request parameter -->
 <beans:bean id="clientCredentialsTokenEndPointFilter"
    class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
    <beans:property name="authenticationManager" ref="clientAuthenticationManager" />
</beans:bean>

 <!-- Server hosting the protected resource ,capable of accepting and responding to protected resource request using access tokens -->
 <oauth2:resource-server id="resourceServerFilter" resource-id="test" token-services-ref="tokenService"/>

 <!-- Authentication Entry Point -->
 <beans:bean id="oauthAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
   <beans:property name="realmName" value="test" />
 </beans:bean>

 <beans:bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
    <beans:property name="realmName" value="test/client" />
    <beans:property name="typeName" value="Basic" />
 </beans:bean>

<!-- Access Denied Handler -->
<beans:bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler"/>

<!-- This beans prepares oauth2Request using incoming request parameter -->
<beans:bean id="oauth2RequestFactory" class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
  <beans:constructor-arg ref="clientDetails"/>
</beans:bean>

<!-- Access Decision Manager -->
<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased" xmlns="http://www.springframework.org/schema/beans">
  <beans:constructor-arg>
    <beans:list>
        <beans:bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
        <beans:bean class="org.springframework.security.access.vote.RoleVoter" />
        <beans:bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
    </beans:list>
</beans:constructor-arg>
</beans:bean>
</code>```

I request for token using http://localhost:8060/oauth/token?grant_type=password&client_id=nokia3320&client_secret=0987654321&username=subash&password=123456 and i got following response

```<code>{
 "access_token": "9f5a89ce-a0d9-4d65-8e83-5d3b16d8c025",
 "token_type": "bearer",
 "refresh_token": "c2ac82ec-9f41-46dd-b7c2-4772c018505c",
 "expires_in": 499,
 "scope": "read trust write"
}
</code>```

When i try to access resource using http://localhost:8060/Api/currencyList with access token in authorizatioin error i got following response

```<code>{
 "error": "unauthorized",
 "error_description": "An Authentication object was not found in the
                      SecurityContext"
}
</code>```

I want to protect the resource below using spring oauth2

```<code>@RequestMapping(value="/currencyList",method=RequestMethod.GET,produces={MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public List<CurrencyDTO> getCurrencyList(){

    List<CurrencyDTO> currencyList=new ArrayList<CurrencyDTO>();

    CurrencyDTO currency1 = new CurrencyDTO();
    currency1.setCurrencyCode("NEP");
    currency1.setCurrencyName("Rupees");
    currency1.setId((long)1);
    currency1.setSymbol("Rs");

    CurrencyDTO currency2 = new CurrencyDTO();
    currency2.setCurrencyCode("AM");
    currency2.setCurrencyName("Dollar");
    currency2.setId((long)2);
    currency2.setSymbol("$");

    currencyList.add(currency1);
    currencyList.add(currency2);

    return currencyList;

}
</code>```

I got stuck in this problem for about 2 days.How could i resolve this problem?

答:
In my case, I added my api urls as public urls. My oauth protected REST-Service urls start with /resource/api/**, but I added in my security configuration class as

```<code>@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/css/**","/js/**","/resource/**");
}
</code>```

So, OAuth2AuthenticationProcessingFilter did not invoke and I got exception as Authentication Object was not found in the SecurityContext at my api server.

Body:
I have a project where i implement Spring security and Spring OAuth2 Security.When i request for access token it works well but when i request for resource using access token i got 'An authentication object was not found in the SecurityContext'.

SecurityContext of my project is :

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:oauth2="http://www.springframework.org/schema/security/oauth2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2
       http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security.xsd">

<global-method-security jsr250-annotations="enabled" />
<http pattern="/**/*.css" security="none" />
<http pattern="/**/*.css.map" security="none" />

<http pattern="/**/*.gif" security="none" />
<http pattern="/**/*.html" security="none" />
<http pattern="/**/*.ttf" security="none" />
<http pattern="/**/*.eot" security="none" />
<http pattern="/**/*.svg" security="none" />
<http pattern="/**/*.woff" security="none" />
<http pattern="/**/*.woff2" security="none" />
<http pattern="/**/*.xls" security="none" />
<http pattern="/**/*.ico" security="none" />
<http pattern="/**/*.jpg" security="none" />
<http pattern="/**/*.js" security="none" />
<http pattern="/**/*.png" security="none" />
<http pattern="/**/*.xml" security="none" />
<http pattern="/**/*.mp4" security="none" />
<http pattern="editCustomerTrnx" security="none"/>

<http pattern="/oauth/token" create-session="never"
      authentication-manager-ref="clientAuthenticationManager"
      xmlns="http://www.springframework.org/schema/security">
    <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY"/>
    <http-basic entry-point-ref="clientAuthenticationEntryPoint"/>

    <custom-filter ref="clientCredentialsTokenEndPointFilter" after="BASIC_AUTH_FILTER"/>
    <access-denied-handler ref="oauthAccessDeniedHandler"/>
</http>

<http pattern="/Api/**" create-session="stateless" entry-point-ref="oauthAuthenticationEntryPoint"
      access-decision-manager-ref="accessDecisionManager"
      xmlns="http://www.springframework.org/schema/security">
   <anonymous enabled="false"/>
   <intercept-url pattern="/Api/**" access="ROLE_ADMIN"/>
   <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
   <access-denied-handler ref="oauthAccessDeniedHandler"/>
</http>

<http auto-config="true">
    <intercept-url pattern="/Admin/**"
        access="ROLE_ADMINISTRATOR,ROLE_AUTHENTICATED" requires-channel="any" />
    <intercept-url pattern="/Seller/**" access="ROLE_AUTHENTICATED,ROLE_SELLER"
        requires-channel="any" />
    <intercept-url pattern="/login/**" access="IS_AUTHENTICATED_ANONYMOUSLY"
        requires-channel="any" />
    <intercept-url  pattern="/" access="IS_AUTHENTICATED_ANONYMOUSLY"
        requires-channel="any" />

    <custom-filter position="CONCURRENT_SESSION_FILTER" ref="customSessionFilter" />
    <form-login login-page="/main"

        authentication-failure-handler-ref="failureHandler"
        always-use-default-target="false" default-target-url="/"
        authentication-success-handler-ref="ash" />
    <logout logout-url="/logout" logout-success-url="/" />
    <access-denied-handler ref="" error-page="/" />

    <session-management
        session-authentication-strategy-ref="sls" />
    <port-mappings>
        <port-mapping http="8080" https="8443" />
    </port-mappings>
</http>

<authentication-manager alias="authenticationManager" xmlns="http://www.springframework.org/schema/security">
    <authentication-provider>
        <user-service>
           <user name="subash" authorities="ROLE_ADMIN" password="123456"/>
        </user-service>

    </authentication-provider>
</authentication-manager>

<beans:bean id="ash"
    class="com.remittance.session.CustomSavedRequestAwareAuthenticationSuccessHandler">
</beans:bean>

<beans:bean id="failureHandler" class="com.remittance.session.CustomAuthenticationFailureHandler">
</beans:bean>
<beans:bean id="forbiddenEntryPoint"
    class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />

<beans:bean id="customSessionFilter" class="com.remittance.session.CustomSessionFilter">
    <beans:constructor-arg ref="sessionRegistry" />
</beans:bean>

<beans:bean id="sls"
    class="com.remittance.session.SessionLoggingStrategy">
    <beans:constructor-arg ref="sas" />
    <beans:constructor-arg ref="sessionLogApi" />
</beans:bean>

<beans:bean id="sas"
    class="com.remittance.session.PersistingConcurrentSessionControlStrategy">
    <beans:constructor-arg name="sessionRegistry"
        ref="sessionRegistry" />
    <beans:constructor-arg name="sessionApi" ref="sessionApi" />
    <beans:property name="maximumSessions" value="-1" />
</beans:bean>

<beans:bean id="sessionRegistry"
    class="com.remittance.session.PersistingSessionRegistry">
    <beans:constructor-arg ref="sessionApi" />
</beans:bean>

<beans:bean id="userDetailService"
    class="com.remittance.session.UserDetailsServiceImpl">
    <beans:constructor-arg ref="userRepository" />
</beans:bean>

<beans:bean id="passwordEncoder"
    class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />

<beans:bean id="userTest" class="com.remittance.session.UserTest">
    <beans:constructor-arg ref="userRepository" />
</beans:bean>

<oauth2:client-details-service id="clientDetails">
   <oauth2:client client-id="android5.5" secret="1234567890" authorized-grant-types="password,authorization_code,refresh_token,implicit,client_credentials"
                 authorities="ROLE_CLIENT,ROLE_TRUSTED_CLIENT" scope="read,write,trust"/>
   <oauth2:client client-id="nokia3320" secret="0987654321" authorized-grant-types="password,authorization_code,refresh_token,implicit,client_credentials"
                 authorities="ROLE_CLIENT,ROLE_TRUSTED_CLIENT" scope="read,write,trust"/>
</oauth2:client-details-service>

 <beans:bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore"/>

 <beans:bean id="clientDetailsUserDetailsService" class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
    <beans:constructor-arg ref="clientDetails"/>
 </beans:bean>

 <beans:bean id="tokenService" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
   <beans:property name="tokenStore" ref="tokenStore"/>
   <beans:property name="accessTokenValiditySeconds" value="500"/>
   <beans:property name="clientDetailsService" ref="clientDetails"/>
   <beans:property name="supportRefreshToken" value="true"/>
 </beans:bean>

 <beans:bean id="userApprovalHandler" class="org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler">
    <beans:property name="tokenStore" ref="tokenStore"/>
    <beans:property name="requestFactory" ref="oauth2RequestFactory"/>
 </beans:bean>

 <oauth2:authorization-server client-details-service-ref="clientDetails" token-services-ref="tokenService"
                             user-approval-handler-ref="userApprovalHandler">

     <oauth2:password/>

 </oauth2:authorization-server>

 <authentication-manager id="clientAuthenticationManager">
     <authentication-provider user-service-ref="clientDetailsUserDetailsService"/>
 </authentication-manager>

 <beans:bean id="clientCredentialsTokenEndPointFilter"
    class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
    <beans:property name="authenticationManager" ref="clientAuthenticationManager" />
</beans:bean>

 <oauth2:resource-server id="resourceServerFilter" resource-id="test" token-services-ref="tokenService"/>

 <beans:bean id="oauthAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
   <beans:property name="realmName" value="test" />
 </beans:bean>

 <beans:bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
    <beans:property name="realmName" value="test/client" />
    <beans:property name="typeName" value="Basic" />
 </beans:bean>

<beans:bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler"/>

<beans:bean id="oauth2RequestFactory" class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
  <beans:constructor-arg ref="clientDetails"/>
</beans:bean>

<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased" xmlns="http://www.springframework.org/schema/beans">
  <beans:constructor-arg>
    <beans:list>
        <beans:bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
        <beans:bean class="org.springframework.security.access.vote.RoleVoter" />
        <beans:bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
    </beans:list>
</beans:constructor-arg>
</beans:bean>

I request for token using http://localhost:8060/oauth/token?grant_type=password&client_id=nokia3320&client_secret=0987654321&username=subash&password=123456 and i got following response

{
 "access_token": "9f5a89ce-a0d9-4d65-8e83-5d3b16d8c025",
 "token_type": "bearer",
 "refresh_token": "c2ac82ec-9f41-46dd-b7c2-4772c018505c",
 "expires_in": 499,
 "scope": "read trust write"
}

When i try to access resource using http://localhost:8060/Api/currencyList with access token in authorizatioin error i got following response

{
 "error": "unauthorized",
 "error_description": "An Authentication object was not found in the
                      SecurityContext"
}

I want to protect the resource below using spring oauth2

@RequestMapping(value="/currencyList",method=RequestMethod.GET,produces={MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public List<CurrencyDTO> getCurrencyList(){

    List<CurrencyDTO> currencyList=new ArrayList<CurrencyDTO>();

    CurrencyDTO currency1 = new CurrencyDTO();
    currency1.setCurrencyCode("NEP");
    currency1.setCurrencyName("Rupees");
    currency1.setId((long)1);
    currency1.setSymbol("Rs");

    CurrencyDTO currency2 = new CurrencyDTO();
    currency2.setCurrencyCode("AM");
    currency2.setCurrencyName("Dollar");
    currency2.setId((long)2);
    currency2.setSymbol("$");

    currencyList.add(currency1);
    currencyList.add(currency2);

    return currencyList;

}

I got stuck in this problem for about 2 days.How could i resolve this problem?

Body:
In my case, I added my api urls as public urls. My oauth protected REST-Service urls start with /resource/api/**, but I added in my security configuration class as

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/css/**","/js/**","/resource/**");
}

So, OAuth2AuthenticationProcessingFilter did not invoke and I got exception as Authentication Object was not found in the SecurityContext at my api server.


问:
How do I get the Ubuntu source code?
Where can I find the source code for the latest Ubuntu release?

Also, how would I view the code? Would it just be lots of .cpp and .h files I could view in Visual Studio?

答:
The source code for ubuntu is divided up by package - from a running ubuntu system you can easily retreive the source for any package by doing:

```<code>apt-get source (package name)
</code>```

Otherwise, go to launchpad, and search up the package in question. For example, here's the download page for the source code for a specific version of curl: https://launchpad.net/ubuntu/+source/curl/7.21.2-4ubuntu1

That said, it's a lot easier if you're on a Linux system already - the package sources are divided into an original source tarball plus ubuntu patches, so if you don't use apt-get source, you'll need to manually apply the patch to the source code. And new-style packages are even divided into multiple packages.

What's more, the packages are generally not designed to be cross-compiled from a non-Linux system. Even if you download them and open them in VS, you won't be able to build them from a Windows system.

Finally, note that not everything is in C and C++ - there are packages in just about any language you can imagine. But I suppose most of them could be opened in VS as text files :)

Note: If you really, really want all of it, and I can't stress enough how silly it would be to download everything just to start learning about the system, you can use the debmirror tool, available in ubuntu, to do this:

```<code>debmirror -a none \
          --source \
          -s main \
          -d lucid,lucid-security,lucid-updates \
          -r /ubuntu \
          --progress \
          -e http \
          -h archive.ubuntu.com \ ## or other ubuntu archive mirror
          destpath
</code>```

This will be an absolutely huge download. Have several tens of GBs of space available. Note that this downloads only core packages - replace -s main with -s main,universe,multiverse,restricted to get everything.

Once you have the package files, you can extract the source by running dpkg-source -x on a .dsc file of interest.

Title: How do I get the Ubuntu source code?

Body:
The source code for ubuntu is divided up by package - from a running ubuntu system you can easily retreive the source for any package by doing:

apt-get source (package name)

Otherwise, go to launchpad, and search up the package in question. For example, here's the download page for the source code for a specific version of curl: https://launchpad.net/ubuntu/+source/curl/7.21.2-4ubuntu1

That said, it's a lot easier if you're on a Linux system already - the package sources are divided into an original source tarball plus ubuntu patches, so if you don't use apt-get source, you'll need to manually apply the patch to the source code. And new-style packages are even divided into multiple packages.

What's more, the packages are generally not designed to be cross-compiled from a non-Linux system. Even if you download them and open them in VS, you won't be able to build them from a Windows system.

Finally, note that not everything is in C and C++ - there are packages in just about any language you can imagine. But I suppose most of them could be opened in VS as text files :)

Note: If you really, really want all of it, and I can't stress enough how silly it would be to download everything just to start learning about the system, you can use the debmirror tool, available in ubuntu, to do this:

debmirror -a none \
          --source \
          -s main \
          -d lucid,lucid-security,lucid-updates \
          -r /ubuntu \
          --progress \
          -e http \
          -h archive.ubuntu.com \ ## or other ubuntu archive mirror
          destpath

This will be an absolutely huge download. Have several tens of GBs of space available. Note that this downloads only core packages - replace -s main with -s main,universe,multiverse,restricted to get everything.

Once you have the package files, you can extract the source by running dpkg-source -x on a .dsc file of interest.

ContentLicense: CC BY-SA 2.5


问:
Create iterator from total difference
I want to iterate through the integers from x up to n values further. I can do this for example with:

```<code>x.upto(x + n - 1)
</code>```

or many other ways, but all of them require me to calculate the end myself, which seems not very elegant. Is there any way to create an iterator directly from the total difference to be iterated?

I imagine something like this:

```<code>5.up(10).to_a
# returns [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
</code>```

I know I could easily write it myself, but I want to know if what I want already exists in the core.

Title: Create iterator from total difference

Body:
I want to iterate through the integers from x up to n values further. I can do this for example with:

x.upto(x + n - 1)

or many other ways, but all of them require me to calculate the end myself, which seems not very elegant. Is there any way to create an iterator directly from the total difference to be iterated?

I imagine something like this:

5.up(10).to_a
# returns [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

I know I could easily write it myself, but I want to know if what I want already exists in the core.

Body: 5.step.take(10) # => [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]


问:
Converting a time into 12 hour format in SQL
How can i convert 24 hour formatted time into 12 hour formatted time in SQL server 2008?

答:
SQL can perform inline conversion for time

mytime in database is 4:15:00

```<code>SELECT CONVERT(varchar(15),  CAST(mytime AS TIME), 100) as my_time from mytable
</code>```

Body:
SQL can perform inline conversion for time

mytime in database is 4:15:00

SELECT CONVERT(varchar(15),  CAST(mytime AS TIME), 100) as my_time from mytable


问:
Async function not returning value, but console.log() does: how to do?
I have an es6 class, with an init() method responsible for fetching data, transforming it, then update the class's property this.data with newly transformed data.
So far so good.
The class itself has another getPostById() method, to just do what it sounds like. Here is the code for the class:

```<code>class Posts {
  constructor(url) {
    this.ready = false
    this.data = {}
    this.url = url
  }
  async init() {
      try {
        let res = await fetch( this.url )
        if (res.ok) {
            let data = await res.json()

          // Do bunch of transformation stuff here

          this.data = data
          this.ready = true
            return data
        }
      }
      catch (e) {
         console.log(e)
      }
  }
  getPostById(id){
     return this.data.find( p => p.id === id )
  }
}
</code>```

Straightforward, except I have an async/await mechanism in the init() method.
Now, this code will work correctly:

```<code>let allPosts = new Posts('https://jsonplaceholder.typicode.com/posts')

allPosts.init()
        .then( d => console.log(allPosts.getPostById(4)) )
// resulting Object correctly logged in console
</code>```

but it only gets printed into the console:
How could I use allPosts.getPostById(4) as a return of a function ?

Like:

```<code>let myFunc = async () => {
   const postId = 4
   await allPosts.init()  // I need to wait for this to finish before returning

   // This is logging correct value
   console.log( 'logging: ' + JSON.stringify(allPosts.getPostById( postId ), null, 4) )

   // How can I return the RESULT of allPosts.getPostById( postId ) ???
   return allPosts.getPostById( postId )
}
</code>```

myFunc() returns a Promise but not the final value. I have read several related posts on the subject but they all give example of logging, never returning.

Here is a fiddle that includes two ways of handling init(): using Promise and using async/await. No matter what I try, I can't manage to USE the FINAL VALUE of getPostById(id).

The question of this post is: how can I create a function that will RETURN the VALUE of getPostById(id) ?

EDIT:

A lot of good answers trying to explain what Promises are in regards to the main execution loop.
After a lot of videos and other good reads, here is what I understand now:

my function init() correctly returns. However, within the main event loop: it returns a Promise, then it is my job to catch the result of this Promise from within a kinda parallel loop (not a new real thread). In order to catch the result from the parallel loop there are two ways:

use .then( value => doSomethingWithMy(value) )

use let value = await myAsyncFn(). Now here is the foolish hiccup:

await can only be used within an async function :p

thus itself returning a Promise, usable with await which should be embed in an async function, which will be usable with await etc...

This means we cannot really WAIT for a Promise: instead we should catch parallel loop indefinitely: using .then() or async/await.

Thanks for the help !

答:
As for your comment; I'll add it as answer.

The code you write in JavaScript is run on one thread, that means that if your code could actually wait for something it will block any of your other code from getting executed. The event loop of JavaScript is explained very well in this video and if you like to read in this page.

A good example of blocking code in the browser is alert("cannot do anything until you click ok");. Alert blocks everything, the user can't even scroll or click on anything in the page and your code also blocks from executing.

```<code>Promise.resolve(22)
.then(x=>alert("blocking")||"Hello World")
.then(
  x=>console.log(
    "does not resolve untill you click ok on the alert:",
    x
  )
);
</code>```

Run that in a console and you see what I mean by blocking.

This creates a problem when you want to do something that takes time. In other frameworks you'd use a thread or processes but there is no such thing in JavaScript (technically there is with web worker and fork in node but that's another story and usually far more complicated than using async api's).

So when you want to make a http request you can use fetch but fetch takes some time to finish and your function should not block (has to return something as fast as possible). This is why fetch returns a promise.

Note that fetch is implemented by browser/node and does run in another thread, only code you write runs in one thread so starting a lot of promises that only run code you write will not speed up anything but calling native async api's in parallel will.

Before promises async code used callbacks or would return an observable object (like XmlHttpRequest) but let's cover promises since you can convert the more traditional code to a promise anyway.

A promise is an object that has a then function (and a bunch of stuff that is sugar for then but does the same), this function takes 2 parameters.

Resolve handler: A function that will be called by the promise when the promise resolves (has no errors and is finished). The function will be passed one argument with the resolve value (for http requests this usually is the response).

Reject handler: A function that will be called by the promise when the promise rejects (has an error). This function will be passed one argument, this is usually the error or reason for rejection (can be a string, number or anything).

Converting callback to promise.

The traditional api's (especially nodejs api's) use callbacks:

```<code>traditionalApi(
  arg
  ,function callback(err,value){
    err ? handleFail(err) : processValue(value);
  }
);
</code>```

This makes it difficult for the programmer to catch errors or handle the return value in a linear way (from top to bottom). It gets even more impossible to try and do things parallel or throttled parallel with error handling (impossible to read).

You can convert traditional api's to promises with new Promise

```<code>const apiAsPromise = arg =>
  new Promise(
    (resolve,reject)=>
      traditionalApi(
        arg,
        (err,val) => (err) ? reject(err) : resolve(val)
      )
  )
</code>```

async await

This is what's called syntax sugar for promises. It makes promise consuming functions look more traditional and easier to read. That is if you like to write traditional code, I would argue that composing small functions is much easier to read. For example, can you guess what this does?:

```<code>const handleSearch = search =>
  compose([
    showLoading,
    makeSearchRequest,
    processRespose,
    hideLoading
  ])(search)
  .then(
    undefined,//don't care about the resolve
    compose([
      showError,
      hideLoading
    ])
  );
</code>```

Anayway; enough ranting. The important part is to understand that async await doesn't actually start another thread, async functions always return a promise and await doesn't actually block or wait. It's syntax sugar for someFn().then(result=>...,error=>...) and looks like:

```<code>async someMethod = () =>
  //syntax sugar for:
  //return someFn().then(result=>...,error=>...)
  try{
    const result = await someFn();
    ...
   }catch(error){
     ...
   }
}
</code>```

The examples allways show try catch but you don't need to do that, for example:

```<code>var alwaysReject = async () => { throw "Always returns rejected promise"; };
alwaysReject()
.then(
  x=>console.log("never happens, doesn't resolve")
  ,err=>console.warn("got rejected:",err)
);
</code>```

Any error thrown or await returning a rejected promise will cause the async function to return a rejected promise (unless you try and catch it). Many times it is desirable to just let it fail and have the caller handle errors.

Catching errors could be needed when you want the promise to succeed with a special value for rejected promises so you can handle it later but the promise does not technically reject so will always resolve.

An example is Promise.all, this takes an array of promises and returns a new promise that resolves to an array of resolved values or reject when any one of them rejects. You may just want to get the results of all promises back and filter out the rejected ones:

```<code>const Fail = function(details){this.details=details;},
isFail = item => (item && item.constructor)===Fail;
Promise.all(
  urls.map(//map array of urls to array of promises that don't reject
    url =>
      fetch(url)
      .then(
        undefined,//do not handle resolve yet
        //when you handle the reject this ".then" will return
        //  a promise that RESOLVES to the value returned below (new Fail([url,err]))
        err=>new Fail([url,err])
      )
  )
)
.then(
  responses => {
    console.log("failed requests:");
    console.log(
      responses.filter(//only Fail type
        isFail
      )
    );
    console.log("resolved requests:");
    console.log(
      responses.filter(//anything not Fail type
        response=>!isFail(response)
      )
    );
  }
);
</code>```

Body:
I have an es6 class, with an init() method responsible for fetching data, transforming it, then update the class's property this.data with newly transformed data.
So far so good.
The class itself has another getPostById() method, to just do what it sounds like. Here is the code for the class:

class Posts {
  constructor(url) {
    this.ready = false
    this.data = {}
    this.url = url
  }
  async init() {
      try {
        let res = await fetch( this.url )
        if (res.ok) {
            let data = await res.json()

          // Do bunch of transformation stuff here

          this.data = data
          this.ready = true
            return data
        }
      }
      catch (e) {
         console.log(e)
      }
  }
  getPostById(id){
     return this.data.find( p => p.id === id )
  }
}

Straightforward, except I have an async/await mechanism in the init() method.
Now, this code will work correctly:

let allPosts = new Posts('https://jsonplaceholder.typicode.com/posts')

allPosts.init()
        .then( d => console.log(allPosts.getPostById(4)) )
// resulting Object correctly logged in console

but it only gets printed into the console:
How could I use allPosts.getPostById(4) as a return of a function ?

Like:

let myFunc = async () => {
   const postId = 4
   await allPosts.init()  // I need to wait for this to finish before returning

   // This is logging correct value
   console.log( 'logging: ' + JSON.stringify(allPosts.getPostById( postId ), null, 4) )

   // How can I return the RESULT of allPosts.getPostById( postId ) ???
   return allPosts.getPostById( postId )
}

myFunc() returns a Promise but not the final value. I have read several related posts on the subject but they all give example of logging, never returning.

Here is a fiddle that includes two ways of handling init(): using Promise and using async/await. No matter what I try, I can't manage to USE the FINAL VALUE of getPostById(id).

The question of this post is: how can I create a function that will RETURN the VALUE of getPostById(id) ?

EDIT:

A lot of good answers trying to explain what Promises are in regards to the main execution loop.
After a lot of videos and other good reads, here is what I understand now:

my function init() correctly returns. However, within the main event loop: it returns a Promise, then it is my job to catch the result of this Promise from within a kinda parallel loop (not a new real thread). In order to catch the result from the parallel loop there are two ways:

use .then( value => doSomethingWithMy(value) )

use let value = await myAsyncFn(). Now here is the foolish hiccup:

await can only be used within an async function :p

thus itself returning a Promise, usable with await which should be embed in an async function, which will be usable with await etc...

This means we cannot really WAIT for a Promise: instead we should catch parallel loop indefinitely: using .then() or async/await.

Thanks for the help !

Body:
As for your comment; I'll add it as answer.

The code you write in JavaScript is run on one thread, that means that if your code could actually wait for something it will block any of your other code from getting executed. The event loop of JavaScript is explained very well in this video and if you like to read in this page.

A good example of blocking code in the browser is alert("cannot do anything until you click ok");. Alert blocks everything, the user can't even scroll or click on anything in the page and your code also blocks from executing.

Promise.resolve(22)
.then(x=>alert("blocking")||"Hello World")
.then(
  x=>console.log(
    "does not resolve untill you click ok on the alert:",
    x
  )
);

Run that in a console and you see what I mean by blocking.

This creates a problem when you want to do something that takes time. In other frameworks you'd use a thread or processes but there is no such thing in JavaScript (technically there is with web worker and fork in node but that's another story and usually far more complicated than using async api's).

So when you want to make a http request you can use fetch but fetch takes some time to finish and your function should not block (has to return something as fast as possible). This is why fetch returns a promise.

Note that fetch is implemented by browser/node and does run in another thread, only code you write runs in one thread so starting a lot of promises that only run code you write will not speed up anything but calling native async api's in parallel will.

Before promises async code used callbacks or would return an observable object (like XmlHttpRequest) but let's cover promises since you can convert the more traditional code to a promise anyway.

A promise is an object that has a then function (and a bunch of stuff that is sugar for then but does the same), this function takes 2 parameters.

Resolve handler: A function that will be called by the promise when the promise resolves (has no errors and is finished). The function will be passed one argument with the resolve value (for http requests this usually is the response).

Reject handler: A function that will be called by the promise when the promise rejects (has an error). This function will be passed one argument, this is usually the error or reason for rejection (can be a string, number or anything).

Converting callback to promise.

The traditional api's (especially nodejs api's) use callbacks:

traditionalApi(
  arg
  ,function callback(err,value){
    err ? handleFail(err) : processValue(value);
  }
);

This makes it difficult for the programmer to catch errors or handle the return value in a linear way (from top to bottom). It gets even more impossible to try and do things parallel or throttled parallel with error handling (impossible to read).

You can convert traditional api's to promises with new Promise

const apiAsPromise = arg =>
  new Promise(
    (resolve,reject)=>
      traditionalApi(
        arg,
        (err,val) => (err) ? reject(err) : resolve(val)
      )
  )

async await

This is what's called syntax sugar for promises. It makes promise consuming functions look more traditional and easier to read. That is if you like to write traditional code, I would argue that composing small functions is much easier to read. For example, can you guess what this does?:

const handleSearch = search =>
  compose([
    showLoading,
    makeSearchRequest,
    processRespose,
    hideLoading
  ])(search)
  .then(
    undefined,//don't care about the resolve
    compose([
      showError,
      hideLoading
    ])
  );

Anayway; enough ranting. The important part is to understand that async await doesn't actually start another thread, async functions always return a promise and await doesn't actually block or wait. It's syntax sugar for someFn().then(result=>...,error=>...) and looks like:

async someMethod = () =>
  //syntax sugar for:
  //return someFn().then(result=>...,error=>...)
  try{
    const result = await someFn();
    ...
   }catch(error){
     ...
   }
}

The examples allways show try catch but you don't need to do that, for example:

var alwaysReject = async () => { throw "Always returns rejected promise"; };
alwaysReject()
.then(
  x=>console.log("never happens, doesn't resolve")
  ,err=>console.warn("got rejected:",err)
);

Any error thrown or await returning a rejected promise will cause the async function to return a rejected promise (unless you try and catch it). Many times it is desirable to just let it fail and have the caller handle errors.

Catching errors could be needed when you want the promise to succeed with a special value for rejected promises so you can handle it later but the promise does not technically reject so will always resolve.

An example is Promise.all, this takes an array of promises and returns a new promise that resolves to an array of resolved values or reject when any one of them rejects. You may just want to get the results of all promises back and filter out the rejected ones:

const Fail = function(details){this.details=details;},
isFail = item => (item && item.constructor)===Fail;
Promise.all(
  urls.map(//map array of urls to array of promises that don't reject
    url =>
      fetch(url)
      .then(
        undefined,//do not handle resolve yet
        //when you handle the reject this ".then" will return
        //  a promise that RESOLVES to the value returned below (new Fail([url,err]))
        err=>new Fail([url,err])
      )
  )
)
.then(
  responses => {
    console.log("failed requests:");
    console.log(
      responses.filter(//only Fail type
        isFail
      )
    );
    console.log("resolved requests:");
    console.log(
      responses.filter(//anything not Fail type
        response=>!isFail(response)
      )
    );
  }
);


问:
React Router - "A <Router> may have only one child element" error
In my React app, I'd like to connect my main router to Redux so I can access some values stored there, but I'm getting the error "A <Router> may have only one child element". I've seen others with this problem, but the solutions always involve wrapping the routes in a
 or a <Switch>, which I have done... I'm not quite sure how to fix it in this circumstance.

Ideally, this is what I would like to achieve - this is routes/index.jsx:

```<code>import React from "react"
import { connect } from "react-redux"
import { Route, Switch } from "react-router"
import AppContainer from "containers/App"
import SignInRouter from "./signin-router"
import SignUpRouter from "./signup-router"
import DashboardRouter from "./dashboard-router"
import NotFound from "../components/NotFound"

const mapStateToProps = (state) => {
        return { state }
    }

const routes = (props) => (
    <AppContainer>
        <Switch>
            <Route exact path="/" component={SignInRouter} />
            <Route path={`/${props.state.state.signupPath}`} component={SignUpRouter} />
            <Route path={`/${props.state.state.dashboardPath}`} component={DashboardRouter} />
            <Route path="/*" component={NotFound} />
        </Switch>
    </AppContainer>
)

export default connect(mapStateToProps, null)(routes)
</code>```

originally, this was set up like so:

```<code>const routes = (
    <AppContainer>
        // etc...
    </AppContainer>
)
</code>```

but once I changed it to a function - const routes = (props) => (...) - it broke.

I'm a little miffed, because I was able to successfully accomplish this with some of my other routers in the app - for example, here is routes/dashboard-router.jsx:

```<code>import React from "react"
import { connect } from "react-redux"
import { Switch, Route } from "react-router"
import DashboardContainer from "../containers/App/dashboard-container"
import DashboardIndex from "../components/Dashboard"
import Agendas from "../components/Dashboard/agendas"
import Meetings from "../components/Dashboard/meetings"
import Groups from "../components/Dashboard/groups"
import Account from "../components/Dashboard/account"
import NotFound from "../components/NotFound"

const mapStateToProps = (state) => {
        return { state }
    }

const DashboardRouter = (props) => (
    <DashboardContainer>
        <Switch>
            <Route exact path={`/${props.state.state.dashboardPath}`} component={DashboardIndex} />
            <Route exact path={`/${props.state.state.dashboardPath}/agendas`} component={Agendas} />
            <Route exact path={`/${props.state.state.dashboardPath}/meetings`} component={Meetings} />
            <Route exact path={`/${props.state.state.dashboardPath}/groups`} component={Groups} />
            <Route exact path={`/${props.state.state.dashboardPath}/account`} component={Account} />
            <Route path={`/${props.state.state.dashboardPath}/*`} component={NotFound} />
        </Switch>
    </DashboardContainer>
)

export default connect(mapStateToProps, null)(DashboardRouter)
</code>```

and that works perfectly.

Why is this a problem in my top-level router, but not in the lower-level routers? And what can I do to resolve this?

For additional reference, here's the AppContainer, which wraps the <Switch> in the router in question:

```<code>import React from "react"
import { connect } from "react-redux"
import { withRouter } from "react-router-dom"
import Header from "components/Header"

const mapStateToProps = (state) => {
        return { state }
    }

const AppContainer = (props) => {
    return (
        <div className="container">
            <Header
                isAuthenticated={props.state.session.isAuthenticated} />
            <main>
                {props.children}
            </main>
        </div>
    )
}

export default withRouter(connect(mapStateToProps, null)(AppContainer))
</code>```

To Robert Farley's comment, this is a React/Phoenix app, scaffolded by using https://github.com/reph-stack/reph.  Here is the way <StaticRouter> is referenced in this app's structure:

containers/index.jsx:

```<code>import React from "react"
import { Provider } from "react-redux"
import createStoreAndRouter from "store"

const Index = (props) => {
    const { store, router } = createStoreAndRouter(props)

    return (
        <Provider store={store}>
            {router}
        </Provider>
    )
}

export default Index
</code>```

store/index.js:

```<code>import React from "react"
import { createStore, combineReducers, applyMiddleware, compose } from "redux"
import { ConnectedRouter, routerReducer, routerMiddleware, push } from "react-router-redux"
import { Route, StaticRouter } from "react-router"
import createBrowserHistory from "history/createBrowserHistory"
import createMemoryHistory from "history/createMemoryHistory"
import thunkMW from "redux-thunk"
import routes from "routes"
import reducers from "reducers"
import WSActions from "actions/ws"

export default function createStoreAndRouter(props) {
    return (typeof window !== "undefined" && typeof window === "object")
        ? createForBrowser()
        : createForServer(props)
}

const createForBrowser = () => {
    const devToolsExt = typeof window.devToolsExtension !== "undefined"
        ? window.devToolsExtension()
        : f => f
    const history = createBrowserHistory()
    const store = createStore(
        reducers,
        window.__INITIAL_STATE__,
        compose(
            applyMiddleware(thunkMW),
            applyMiddleware(routerMiddleware(history)),
            devToolsExt
        )
    )
    store.dispatch(WSActions.init())
    const router = <ConnectedRouter
    history={history}
    >
    {routes}
    </ConnectedRouter>
    return { store, router }
}

const createForServer = (props) => {
    const history = createMemoryHistory()
    const store = createStore(
        reducers,
        props.initial_state,
        compose(
            applyMiddleware(thunkMW),
            applyMiddleware(routerMiddleware(history))
        )
    )
    const router = <StaticRouter
    context={{}}
    location={props.location}
    history={history}
    >
    {routes}
    </StaticRouter>
    return { store, router }
}
</code>```

答:
I think you need to wrap your routes in a router if you want to render them in a function :</p>

```<code>import { BrowserRouter } from 'react-router-dom'

const routes = (props) => (
    <AppContainer>
      <BrowserRouter>
        <Switch>
          <Route exact path="/" component={SignInRouter} />
          <Route path={`/${props.state.state.signupPath}`} component={SignUpRouter} />
          <Route path={`/${props.state.state.dashboardPath}`} component={DashboardRouter} />
          <Route path="/*" component={NotFound} />
        </Switch>
      </BrowserRouter>
    </AppContainer>
)
</code>```

Body:
In my React app, I'd like to connect my main router to Redux so I can access some values stored there, but I'm getting the error "A <Router> may have only one child element". I've seen others with this problem, but the solutions always involve wrapping the routes in a
 or a <Switch>, which I have done... I'm not quite sure how to fix it in this circumstance.

Ideally, this is what I would like to achieve - this is routes/index.jsx:

import React from "react"
import { connect } from "react-redux"
import { Route, Switch } from "react-router"
import AppContainer from "containers/App"
import SignInRouter from "./signin-router"
import SignUpRouter from "./signup-router"
import DashboardRouter from "./dashboard-router"
import NotFound from "../components/NotFound"

const mapStateToProps = (state) => {
        return { state }
    }

const routes = (props) => (
    <AppContainer>
        <Switch>
            <Route exact path="/" component={SignInRouter} />
            <Route path={`/${props.state.state.signupPath}`} component={SignUpRouter} />
            <Route path={`/${props.state.state.dashboardPath}`} component={DashboardRouter} />
            <Route path="/*" component={NotFound} />
        </Switch>
    </AppContainer>
)

export default connect(mapStateToProps, null)(routes)

originally, this was set up like so:

const routes = (
    <AppContainer>
        // etc...
    </AppContainer>
)

but once I changed it to a function - const routes = (props) => (...) - it broke.

I'm a little miffed, because I was able to successfully accomplish this with some of my other routers in the app - for example, here is routes/dashboard-router.jsx:

import React from "react"
import { connect } from "react-redux"
import { Switch, Route } from "react-router"
import DashboardContainer from "../containers/App/dashboard-container"
import DashboardIndex from "../components/Dashboard"
import Agendas from "../components/Dashboard/agendas"
import Meetings from "../components/Dashboard/meetings"
import Groups from "../components/Dashboard/groups"
import Account from "../components/Dashboard/account"
import NotFound from "../components/NotFound"

const mapStateToProps = (state) => {
        return { state }
    }

const DashboardRouter = (props) => (
    <DashboardContainer>
        <Switch>
            <Route exact path={`/${props.state.state.dashboardPath}`} component={DashboardIndex} />
            <Route exact path={`/${props.state.state.dashboardPath}/agendas`} component={Agendas} />
            <Route exact path={`/${props.state.state.dashboardPath}/meetings`} component={Meetings} />
            <Route exact path={`/${props.state.state.dashboardPath}/groups`} component={Groups} />
            <Route exact path={`/${props.state.state.dashboardPath}/account`} component={Account} />
            <Route path={`/${props.state.state.dashboardPath}/*`} component={NotFound} />
        </Switch>
    </DashboardContainer>
)

export default connect(mapStateToProps, null)(DashboardRouter)

and that works perfectly.

Why is this a problem in my top-level router, but not in the lower-level routers? And what can I do to resolve this?

For additional reference, here's the AppContainer, which wraps the <Switch> in the router in question:

import React from "react"
import { connect } from "react-redux"
import { withRouter } from "react-router-dom"
import Header from "components/Header"

const mapStateToProps = (state) => {
        return { state }
    }

const AppContainer = (props) => {
    return (

                {props.children}

    )
}

export default withRouter(connect(mapStateToProps, null)(AppContainer))

To Robert Farley's comment, this is a React/Phoenix app, scaffolded by using https://github.com/reph-stack/reph.  Here is the way <StaticRouter> is referenced in this app's structure:

containers/index.jsx:

import React from "react"
import { Provider } from "react-redux"
import createStoreAndRouter from "store"

const Index = (props) => {
    const { store, router } = createStoreAndRouter(props)

    return (
        <Provider store={store}>
            {router}
        </Provider>
    )
}

export default Index

store/index.js:

import React from "react"
import { createStore, combineReducers, applyMiddleware, compose } from "redux"
import { ConnectedRouter, routerReducer, routerMiddleware, push } from "react-router-redux"
import { Route, StaticRouter } from "react-router"
import createBrowserHistory from "history/createBrowserHistory"
import createMemoryHistory from "history/createMemoryHistory"
import thunkMW from "redux-thunk"
import routes from "routes"
import reducers from "reducers"
import WSActions from "actions/ws"

export default function createStoreAndRouter(props) {
    return (typeof window !== "undefined" && typeof window === "object")
        ? createForBrowser()
        : createForServer(props)
}

const createForBrowser = () => {
    const devToolsExt = typeof window.devToolsExtension !== "undefined"
        ? window.devToolsExtension()
        : f => f
    const history = createBrowserHistory()
    const store = createStore(
        reducers,
        window.__INITIAL_STATE__,
        compose(
            applyMiddleware(thunkMW),
            applyMiddleware(routerMiddleware(history)),
            devToolsExt
        )
    )
    store.dispatch(WSActions.init())
    const router = <ConnectedRouter
    history={history}
    >
    {routes}
    </ConnectedRouter>
    return { store, router }
}

const createForServer = (props) => {
    const history = createMemoryHistory()
    const store = createStore(
        reducers,
        props.initial_state,
        compose(
            applyMiddleware(thunkMW),
            applyMiddleware(routerMiddleware(history))
        )
    )
    const router = <StaticRouter
    context={{}}
    location={props.location}
    history={history}
    >
    {routes}
    </StaticRouter>
    return { store, router }
}

Body:
I think you need to wrap your routes in a router if you want to render them in a function :

import { BrowserRouter } from 'react-router-dom'

const routes = (props) => (
    <AppContainer>
      <BrowserRouter>
        <Switch>
          <Route exact path="/" component={SignInRouter} />
          <Route path={`/${props.state.state.signupPath}`} component={SignUpRouter} />
          <Route path={`/${props.state.state.dashboardPath}`} component={DashboardRouter} />
          <Route path="/*" component={NotFound} />
        </Switch>
      </BrowserRouter>
    </AppContainer>
)


问:
NSTextField Clear Button
On the iPhone a UITextField can have a clearButtonMode set to show a small clear button (X) at the end of a text input. Similarly, on the Mac the NSSearchField has a nice clear button on it at the end. My question is - is there a way to enable this on a normal NSTextField?

答:
I was looking for the same thing for a  multi-lined NSTextField the other day, with no luck so ended up using  a button set with no border and to toggle with a small image. set very close to the NSTextField (not on it)

and:

```<code>- (IBAction)clearTextViewTex:(id)sender{

 [textField performSelector:@selector(selectAll:)];
[textField performSelector:@selector(delete:)];

}
</code>```

Doing it this way also retained the undo functions, without me having to write any NSUndoManager stuff.

Title: NSTextField Clear Button

Body:
I was looking for the same thing for a  multi-lined NSTextField the other day, with no luck so ended up using  a button set with no border and to toggle with a small image. set very close to the NSTextField (not on it)

and:

- (IBAction)clearTextViewTex:(id)sender{

 [textField performSelector:@selector(selectAll:)];
[textField performSelector:@selector(delete:)];

}

Doing it this way also retained the undo functions, without me having to write any NSUndoManager stuff.


问:
How to force IAR to use desired Cortex-M0+ instructions (optimization will be disabled for this func.)
I need to force IAR tp use certain Cortex-M0+ instruction in some part of my code while codding with C.

Please do not offer pure asm functions or inline asm etc.

I have managed to do this for 51 instruction but could not for ;
ADR, BLX, RSBS, SBCS, SXTH instructions.

Optimization is disabled for this function (#pragma optimization=none)

I have tried many things by considering instruction behaviour.
But IAR preferred to same function with different instructions.

Did anyone else struggle with such a unnecessary thing before or has anyone an idea?

答:
Apart from BLX which isn't available on cortex-m this code may get you there.
Maybe you have to turn on some optimizations.</p>

```<code>char const * getstr(void)
{
    return "ADR";
}

long long llfunc(long long v1, long long v2)
{
    return v1 - v2;
}

int neg(int i)
{
    return -i;
}

void efunc(short);

void func(short s)
{
    efunc(s + 5);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Apart from BLX which isn't available on cortex-m this code may get you there.
Maybe you have to turn on some optimizations.

char const * getstr(void)
{
    return "ADR";
}

long long llfunc(long long v1, long long v2)
{
    return v1 - v2;
}

int neg(int i)
{
    return -i;
}

void efunc(short);

void func(short s)
{
    efunc(s + 5);
}


问:
Why is my scanner not reading from my file?
I'm trying to get my program to read data from a text file and store it in an array. The text file contains data about a planet.
Here is an example:

```<code>Mercury
4.151002e10
2.642029e10
-1.714167e9
-3.518882e4
4.355473e4
6.785804e3
3.302e23
</code>```

My file is named test.txt. It lives in the same directory as my class.java file. I've used System.out.println(new File("test.txt").getAbsolutePath()); to check if the directory path is correct, which it was, and I used System.out.println(new File(".")); to check if it was in the same directory that the code was trying to compile in, which again it was (outputted just a dot which I was led to believe meant it was in the correct directory). I've tried different ways of finding the file, such as renaming it to something else to check it wasn't a keyword, changing the encoding of the file to Unicode, or UTF-8, or ANSI, none of which worked, using .\test in the file to look in the same directory, none of which worked.

Here is my code:

```<code>public static void defaultPlanetArray(){
  Planet[] solarSystem;
  solarSystem = new Planet[9];
  PhysicsVector dummyAcceleration = new PhysicsVector();

  System.out.println(new File("test.txt").getAbsolutePath());
  System.out.println(new File("."));

  try{
    File file = new File("C:\\Users\\Lizi\\Documents\\Uni Work\\Year 2\\PHYS281\\Project\\test.txt");
    Scanner scnr = new Scanner(file);
  }
  catch(FileNotFoundException e){
    System.out.println("File not found!");
  }
  int i = 0;

  while(i<9 && scnr.hasNextLine()){
    //read values from file and set as Planet object, then set to array.
    i++
  }
</code>```

PhysicsVector and Planet are both classes I have created. PhysicsVector and the rest of Planet apart from this excerpt compile with no problems. When I try to compile this specific bit of code, I get:

.\Planet.java:65: error: cannot find symbol
      while(i<9 && scnr.hasNextLine()){
                   ^

I'm guessing this means that the variable scnr is not being created in the try section because it cannot find the file. I think this because when I don't include the try and catch blocks, I get:

.\Planet.java:59: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
        Scanner scnr = new Scanner(file);
                       ^

I've also tried the catches FileNotFoundException when I'm first creating the method but that gives me the same error as immediately above.

I could just set the values in the program, but that would give a lot of unnecessary code and be rather inefficient I think.

So my question is, how do I get the scanner to read my values from the file?

答:
As @Lalit Verma pointed the scnr variable you defined lives inside the try - catch block.

Change the code to:

```<code>try{
    File file = new File("C:\\Users\\Lizi\\Documents\\Uni Work\\Year 2\\PHYS281\\Project\\test.txt");
    Scanner scnr = new Scanner(file);
    int i = 0;

    while(i<9 && scnr.hasNextLine()){
      //read values from file and set as Planet object, then set to array.
      i++
    }
  }catch(FileNotFoundException e){
    System.out.println("File not found!");
  }
</code>```

Body:
I'm trying to get my program to read data from a text file and store it in an array. The text file contains data about a planet.
Here is an example:

Mercury
4.151002e10
2.642029e10
-1.714167e9
-3.518882e4
4.355473e4
6.785804e3
3.302e23

My file is named test.txt. It lives in the same directory as my class.java file. I've used System.out.println(new File("test.txt").getAbsolutePath()); to check if the directory path is correct, which it was, and I used System.out.println(new File(".")); to check if it was in the same directory that the code was trying to compile in, which again it was (outputted just a dot which I was led to believe meant it was in the correct directory). I've tried different ways of finding the file, such as renaming it to something else to check it wasn't a keyword, changing the encoding of the file to Unicode, or UTF-8, or ANSI, none of which worked, using .\test in the file to look in the same directory, none of which worked.

Here is my code:

public static void defaultPlanetArray(){
  Planet[] solarSystem;
  solarSystem = new Planet[9];
  PhysicsVector dummyAcceleration = new PhysicsVector();

  System.out.println(new File("test.txt").getAbsolutePath());
  System.out.println(new File("."));

  try{
    File file = new File("C:\\Users\\Lizi\\Documents\\Uni Work\\Year 2\\PHYS281\\Project\\test.txt");
    Scanner scnr = new Scanner(file);
  }
  catch(FileNotFoundException e){
    System.out.println("File not found!");
  }
  int i = 0;

  while(i<9 && scnr.hasNextLine()){
    //read values from file and set as Planet object, then set to array.
    i++
  }

PhysicsVector and Planet are both classes I have created. PhysicsVector and the rest of Planet apart from this excerpt compile with no problems. When I try to compile this specific bit of code, I get:

.\Planet.java:65: error: cannot find symbol
      while(i<9 && scnr.hasNextLine()){
                   ^

I'm guessing this means that the variable scnr is not being created in the try section because it cannot find the file. I think this because when I don't include the try and catch blocks, I get:

.\Planet.java:59: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
        Scanner scnr = new Scanner(file);
                       ^

I've also tried the catches FileNotFoundException when I'm first creating the method but that gives me the same error as immediately above.

I could just set the values in the program, but that would give a lot of unnecessary code and be rather inefficient I think.

So my question is, how do I get the scanner to read my values from the file?

Body:
As @Lalit Verma pointed the scnr variable you defined lives inside the try - catch block.

Change the code to:

try{
    File file = new File("C:\\Users\\Lizi\\Documents\\Uni Work\\Year 2\\PHYS281\\Project\\test.txt");
    Scanner scnr = new Scanner(file);
    int i = 0;

    while(i<9 && scnr.hasNextLine()){
      //read values from file and set as Planet object, then set to array.
      i++
    }
  }catch(FileNotFoundException e){
    System.out.println("File not found!");
  }


问:
SQL Query,how to write a query that queries based on filter(date) + condition(status)
i am trying to query failed  jobs from a table that contains jobs information

Lets say its a backup jobs table (backupInfoTable) (simplifies the question)

```<code>jobName  | instanceName | status | date
________________________________________
one    |first instance| failed    | 12/16/2017
one    |first instance| success   | 1/1/2017
one    |secondInstance| failed    | 1/1/2017
one    |third instance| success   | 12/14/2017
two    |first instance| success   | 1/1/2017
two    |first instance| failed    | 1/1/2016
three  |first instance| failed    | 12/14/2017
</code>```

i would like to query only the records where the most recent backup is a failed backup.
if the most recent backup is a success, its not relevant and the query should ignore it.

for example the query result should be:

```<code>one    |first instance| failed    | 12/16/2017
one    |secondInstance| failed    | 1/1/2017
three  |first instance| failed    | 12/14/2017
</code>```

thanks !

答:
i would like to query only the records where the most recent backup is a failed backup.

Something like:

```<code>with q as
(
    select jobName, instanceName, jobStatus, date,
           row_number() over (partition by jobName, instanceName order by date desc) rn
    from backupInfotable
)
select jobName, instanceName, jobStatus, date
from q
where rn = 1
  and jobStatus = 'failed'
</code>```

Body:
i am trying to query failed  jobs from a table that contains jobs information

Lets say its a backup jobs table (backupInfoTable) (simplifies the question)

jobName  | instanceName | status | date
________________________________________
one    |first instance| failed    | 12/16/2017
one    |first instance| success   | 1/1/2017
one    |secondInstance| failed    | 1/1/2017
one    |third instance| success   | 12/14/2017
two    |first instance| success   | 1/1/2017
two    |first instance| failed    | 1/1/2016
three  |first instance| failed    | 12/14/2017

i would like to query only the records where the most recent backup is a failed backup.
if the most recent backup is a success, its not relevant and the query should ignore it.

for example the query result should be:

one    |first instance| failed    | 12/16/2017
one    |secondInstance| failed    | 1/1/2017
three  |first instance| failed    | 12/14/2017

thanks !

Body:
i would like to query only the records where the most recent backup is a failed backup.

Something like:

with q as
(
    select jobName, instanceName, jobStatus, date,
           row_number() over (partition by jobName, instanceName order by date desc) rn
    from backupInfotable
)
select jobName, instanceName, jobStatus, date
from q
where rn = 1
  and jobStatus = 'failed'


问:
Problem wrapping Extjs Accordion

I am tring to start and build an accordion menu.

I want to use it as an xtype or new MyVar(). but i get few JS Errors

this is my code:

```<code>var AccordionMenu = Ext.extend(Ext.Panel, {
    layout: 'accordion',
    id:'action-panel',
        region:'west',
        split:true,
        collapsible: true,
        collapseMode: 'mini',
        width:200,
        minWidth: 150,
        border: false,
        baseCls:'x-plain',

    items: [{
        title: 'Affiliates',
        html: 'Empty',
        cls: 'empty'
    },{
        title: 'Brands',
        html: 'Empty',
        cls: 'empty'
    }]
});

Ext.reg('accordion_menu', AccordionMenu);

Ext.onReady(function() {
    Ext.QuickTips.init();

            var viewport = new Ext.Viewport({
                layout:'border',
                items:[
                    new AccordionMenu()
                   ,
                   {
                    region:'center',
                    margins:'5 5 5 0',
                    cls:'empty',
                    bodyStyle:'background:#f1f1f1',
                    html:'test'
                }]
            });

});
</code>```

this is the errors:

```<code>    this.items.add is not a function

Line 12777
</code>```

Thanks

答: Start with Ext.ns ('Application');</p>

Title: Problem wrapping Extjs Accordion

Body:
I am tring to start and build an accordion menu.

I want to use it as an xtype or new MyVar(). but i get few JS Errors

this is my code:

var AccordionMenu = Ext.extend(Ext.Panel, {
    layout: 'accordion',
    id:'action-panel',
        region:'west',
        split:true,
        collapsible: true,
        collapseMode: 'mini',
        width:200,
        minWidth: 150,
        border: false,
        baseCls:'x-plain',

    items: [{
        title: 'Affiliates',
        html: 'Empty',
        cls: 'empty'
    },{
        title: 'Brands',
        html: 'Empty',
        cls: 'empty'
    }]
});

Ext.reg('accordion_menu', AccordionMenu);

Ext.onReady(function() {
    Ext.QuickTips.init();

            var viewport = new Ext.Viewport({
                layout:'border',
                items:[
                    new AccordionMenu()
                   ,
                   {
                    region:'center',
                    margins:'5 5 5 0',
                    cls:'empty',
                    bodyStyle:'background:#f1f1f1',
                    html:'test'
                }]
            });

});

this is the errors:

    this.items.add is not a function

Line 12777

Thanks

Body: Start with Ext.ns ('Application');


问:
Godaddy URL Rewrite HTTP to HTTPS won't work Plesk
First I have looked at resolutions all around on stackoverflow as well as googling the heck out of this and even going to godaddy support(lack there of support)

I am on godaddy using windows (plesk). my site is written in C# mvc. I setup my SSL cert and I am able to access the site through https. when I try to access through http it does not redirect but instead gives me a 403.4 error.
I tried the URL rewrite like suggested on Godaddy's help section
https://www.godaddy.com/help/redirect-http-to-https-automatically-8828

I have even copied a URL rewrite we use at work on one of our production sites on our own servers.

```<code>    <rewrite>
        <rules>
            <rule name="Remove www" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTP_HOST}" pattern="^www\.(.+)$" />
                </conditions>
                <action type="Redirect" url="http://{C:1}/{R:0}" />
            </rule>
            <rule name="Redirect to HTTPS" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTPS}" pattern="^OFF$" />
                </conditions>
                <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther" />
            </rule>
        </rules>
    </rewrite>
</code>```

none of that seems to work, godaddy is blaming it on the Cert not being propagated, but if that were the case than HTTPS should not work and I shouldn't be getting a 403.4 error but instead some other related error at best.

Require SSL is enabled on the godaddy server

答: I solved this by unchecking "Require SSL" and now it redirects.</p>

Body:
First I have looked at resolutions all around on stackoverflow as well as googling the heck out of this and even going to godaddy support(lack there of support)

I am on godaddy using windows (plesk). my site is written in C# mvc. I setup my SSL cert and I am able to access the site through https. when I try to access through http it does not redirect but instead gives me a 403.4 error.
I tried the URL rewrite like suggested on Godaddy's help section
https://www.godaddy.com/help/redirect-http-to-https-automatically-8828

I have even copied a URL rewrite we use at work on one of our production sites on our own servers.

    <rewrite>
        <rules>
            <rule name="Remove www" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTP_HOST}" pattern="^www\.(.+)$" />
                </conditions>
                <action type="Redirect" url="http://{C:1}/{R:0}" />
            </rule>
            <rule name="Redirect to HTTPS" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTPS}" pattern="^OFF$" />
                </conditions>
                <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther" />
            </rule>
        </rules>
    </rewrite>

none of that seems to work, godaddy is blaming it on the Cert not being propagated, but if that were the case than HTTPS should not work and I shouldn't be getting a 403.4 error but instead some other related error at best.

Require SSL is enabled on the godaddy server


答:
Use the struct module in the standard library to unpack binary data.

The struct.unpack function accepts two parameters, a format string defining the layout of the binary data and the data itself.

Since the data is coming over the network let's assume network order (format !); the data is an array of doubles, so we'll use the double type (format d).  The struct module defines a size of 8 for a double, and the bytestring has a length of 144, so that's 18 doubles, giving the format string !18d.

Unpack the data:

```<code>>>> unpacked = struct.unpack('!18d', data)
>>> unpacked
(1.0,
 111.0,
 211.0,
 311.0,
 411.0,
 511.0,
 611.0,
 711.0,
 764.0,
 110.0,
 210.0,
 310.0,
 410.0,
 510.0,
 610.0,
 710.0,
 763.0,
 786.0)
>>>
</code>```

If this output isn't what you expect then you may have to experiment with some of the other formats defined in the struct module, or find out exactly how Matlab serialises data for transfer over the network.

Title: Convert sent TCP data to printable text in python

Body:
I have an array of type 'double' (from MATLAB) sent over TCP.

The receiving end (PYTHON), when printed as string, is shown as:

> b'?\xf0\x00\x00\x00\x00\x00\x00@[\xc0\x00\x00\x00\x00\x00@j`\x00\x00\x00\x00\x00@sp\x00\x00\x00\x00\x00@y\xb0\x00\x00\x00\x00\x00@\x7f\xf0\x00\x00\x00\x00\x00@\x83\x18\x00\x00\x00\x00\x00@\x868\x00\x00\x00\x00\x00@\x87\xe0\x00\x00\x00\x00\x00@[\x80\x00\x00\x00\x00\x00@j@\x00\x00\x00\x00\x00@s`\x00\x00\x00\x00\x00@y\xa0\x00\x00\x00\x00\x00@\x7f\xe0\x00\x00\x00\x00\x00@\x83\x10\x00\x00\x00\x00\x00@\x860\x00\x00\x00\x00\x00@\x87\xd8\x00\x00\x00\x00\x00@\x88\x90\x00\x00\x00\x00\x00'

How do I decode this to look the same as its original to be readable?

Body:
Use the struct module in the standard library to unpack binary data.

The struct.unpack function accepts two parameters, a format string defining the layout of the binary data and the data itself.

Since the data is coming over the network let's assume network order (format !); the data is an array of doubles, so we'll use the double type (format d).  The struct module defines a size of 8 for a double, and the bytestring has a length of 144, so that's 18 doubles, giving the format string !18d.

Unpack the data:

>>> unpacked = struct.unpack('!18d', data)
>>> unpacked
(1.0,
 111.0,
 211.0,
 311.0,
 411.0,
 511.0,
 611.0,
 711.0,
 764.0,
 110.0,
 210.0,
 310.0,
 410.0,
 510.0,
 610.0,
 710.0,
 763.0,
 786.0)
>>>

If this output isn't what you expect then you may have to experiment with some of the other formats defined in the struct module, or find out exactly how Matlab serialises data for transfer over the network.


问:
GZip my AFNetworking posts to my server
My application posts large amounts of data, Orders with Order Items - sometimes 1000's, and I want to send it GZipped because my users also have crappy connections most of the time.

How can I accomplish this with AFnetworking?

I am currently using AFHTTPSessionManager to perform my posts.

答:
You can use AFgzipRequestSerializer.

```<code>AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFgzipRequestSerializer serializerWithSerializer:[AFJSONRequestSerializer serializer]];

[manager POST:@"http://example.com/"
   parameters:@{@"foo": @"bar"}
      success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@", responseObject);
}
      failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"[Error] %@", error);
}];
</code>```

See details here.

Title: GZip my AFNetworking posts to my server

Body:
You can use AFgzipRequestSerializer.

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFgzipRequestSerializer serializerWithSerializer:[AFJSONRequestSerializer serializer]];

[manager POST:@"http://example.com/"
   parameters:@{@"foo": @"bar"}
      success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@", responseObject);
}
      failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"[Error] %@", error);
}];

See details here.


问:
Awk code explanation: changing order of fields
I have a file a .txt file that has 14 columns. The head of it would look like this:

```<code>name A1 A2 Freq MAF Quality Rsq n Mean Beta sBeta CHi rsid
SNP1  A  T 0.05   1       5  56 7    8    9    11  12  rs1
SNP2  T  A 0.05   1       6  55 7    8    9    11  12  rs2
</code>```

I want to put the last column in the first position. I wasn't sure what was the most efficient way of doing this, but I came across this, inspiring myself from other posts:

```<code>awk '{$0=$NF FS$0; $14=""}1' file.txt | head
</code>```

I obtained this, which I think works:

```<code>rsid    name A1 A2 Freq MAF Quality Rsq n Mean Beta sBeta CHi
rs1     SNP1  A  T 0.05   1       5  56 7    8    9    11  12
rs2     SNP2  T  A 0.05   1       6  55 7    8    9    11  12
</code>```

I am struggling though to understand what exactly the code does.

I know that NF is the field count of the line being processed

I know that FS is the field seperator

So how can my code work exactly? I just don't really understand how saying that $0 (the whole line) is equal to NF and saying FS$0 (not sure what this means) ends up with the last field now being first. I do realise that $14="" is not written, you end up with 2 rsid columns, one at the start and one at the end.

I'm quite new to using awk so if there is an easier way to achieve this, I would happily go for it.

Thanks

答:
Please go through following and let me know if this helps you on same.</p>

```<code>awk '{
$0=$NF FS$0;   ##Re-creating current line by mentioning $NF(last field value), FS(field separator, whose default value is space) then current line value.
$14=""         ##Now in current line(which is edited above by having last field value to very first) nullifying the last(14th field) here, you could use $NF here too(in case your Input_file have only 14 fields.
}
1              ##1 means we are making condition TRUE here and not mentioning any action so by default print action will happen.
' file.txt     ##Mentioning Input_file name here.
</code>```

Body:
I have a file a .txt file that has 14 columns. The head of it would look like this:

name A1 A2 Freq MAF Quality Rsq n Mean Beta sBeta CHi rsid
SNP1  A  T 0.05   1       5  56 7    8    9    11  12  rs1
SNP2  T  A 0.05   1       6  55 7    8    9    11  12  rs2

I want to put the last column in the first position. I wasn't sure what was the most efficient way of doing this, but I came across this, inspiring myself from other posts:

awk '{$0=$NF FS$0; $14=""}1' file.txt | head

I obtained this, which I think works:

rsid    name A1 A2 Freq MAF Quality Rsq n Mean Beta sBeta CHi
rs1     SNP1  A  T 0.05   1       5  56 7    8    9    11  12
rs2     SNP2  T  A 0.05   1       6  55 7    8    9    11  12

I am struggling though to understand what exactly the code does.

I know that NF is the field count of the line being processed

I know that FS is the field seperator

So how can my code work exactly? I just don't really understand how saying that $0 (the whole line) is equal to NF and saying FS$0 (not sure what this means) ends up with the last field now being first. I do realise that $14="" is not written, you end up with 2 rsid columns, one at the start and one at the end.

I'm quite new to using awk so if there is an easier way to achieve this, I would happily go for it.

Thanks

Body:
Please go through following and let me know if this helps you on same.

awk '{
$0=$NF FS$0;   ##Re-creating current line by mentioning $NF(last field value), FS(field separator, whose default value is space) then current line value.
$14=""         ##Now in current line(which is edited above by having last field value to very first) nullifying the last(14th field) here, you could use $NF here too(in case your Input_file have only 14 fields.
}
1              ##1 means we are making condition TRUE here and not mentioning any action so by default print action will happen.
' file.txt     ##Mentioning Input_file name here.


问:
Is using reinterpret_cast after typeid check valid?
If I verify first that pointer to base class is of some type (using typeid), is it valid to do reinterpret_cast on it to save some performance?

```<code>class Base {
    virtual ~Base() {}
};
class A : Base {};
class B : Base {};
...
class Z : Base {};
</code>```

and later on somewhere:

```<code>void fn(Base & msg) {
    const auto & tid = typeid(msg);
    if (tid == typeid(A)) {
        A * ptr = reinterpret_cast<A*>(&msg);
    } else if (tid == typeid(B)) {
        B * ptr = reinterpret_cast<B*>(&msg);
    } ...
    ...
    } else if (tid == typeid(Z)) {
        Z * ptr = reinterpret_cast<Z*>(&msg);
    }
}
</code>```

As far as I can tell, this code works fine as I think it should. However, I'm curious if it's just because I'm lucky or is this actually well defined usage and all? Using reinterpret_cast this way.

And before you say to just use normal polymorphism for this, I'm not able to change classes as they are so I need to build this way around it.

答:
No, the behaviour would still formally be undefined.

Using reinterpret_cast in this way still breaks strict aliasing rules.

If performance really is an issue here, then you may well want to avoid virtual classes altogether.

Body:
If I verify first that pointer to base class is of some type (using typeid), is it valid to do reinterpret_cast on it to save some performance?

class Base {
    virtual ~Base() {}
};
class A : Base {};
class B : Base {};
...
class Z : Base {};

and later on somewhere:

void fn(Base & msg) {
    const auto & tid = typeid(msg);
    if (tid == typeid(A)) {
        A * ptr = reinterpret_cast(&msg);
    } else if (tid == typeid(B)) {
        B * ptr = reinterpret_cast(&msg);
    } ...
    ...
    } else if (tid == typeid(Z)) {
        Z * ptr = reinterpret_cast<Z*>(&msg);
    }
}

As far as I can tell, this code works fine as I think it should. However, I'm curious if it's just because I'm lucky or is this actually well defined usage and all? Using reinterpret_cast this way.

And before you say to just use normal polymorphism for this, I'm not able to change classes as they are so I need to build this way around it.


问:
adding a class via python
Having a such html

```<code>somehtml = "<p>Here is my solution: </p>``` some code here  ``` ```this is not a code```"
</code>```

Via python I want to add class "foo" to those ```</code> tags which contains a child <code><code></code> thus my output will be :</p>

```somehtml = "
Here is my solution:

 some code here  ``` ```this is not a code```"
</code>```

How can I achieve this ?

答:
Using lxml, it could be done like this:

```<code>import lxml.html as lh
import io

somehtml = "<p>Here is my solution: </p>``` some code here  ``` ```this is not a code```"

doc=lh.parse(io.BytesIO(somehtml))
root=doc.getroot()
pres=root.xpath('//pre/code/..')

for pre in pres:
    pre.attrib['class']='foo'
print(lh.tostring(root))
</code>```

yields

```<code><html><body><p>Here is my solution: </p><pre class="foo"><code> some code here </code> ``` ```this is not a code```
```

Title: adding a class via python

Body:
Having a such html

somehtml = "
Here is my solution:

 some code here

this is not a code
"

Via python I want to add class "foo" to those
 tags which contains a child  thus my output will be :

somehtml = "
Here is my solution:

 some code here

this is not a code
"

How can I achieve this ?

Body:
Using lxml, it could be done like this:

import lxml.html as lh
import io

somehtml = "<p>Here is my solution: </p><pre><code> some code here </code> </pre> <pre>this is not a code</pre>"

doc=lh.parse(io.BytesIO(somehtml))
root=doc.getroot()
pres=root.xpath('//pre/code/..')

for pre in pres:
    pre.attrib['class']='foo'
print(lh.tostring(root))

yields

<html><body><p>Here is my solution: </p><pre class="foo"><code> some code here </code> </pre> <pre>this is not a code</pre></body></html>


问:
How can I extract the week number from java.util.Date in scala
I already tried to use:
getWeek
getCalendarDate
and I don't want to use Calendar package (because I am using a specific software that don't allow me to use it)
Thanks in advance,</p>

答:
I am sorry that I cannot write Scala code. I will have to trust you to adapt from my Java snippets.

If you can, abandon the long outdated Date class. Use for example ZonedDateTime from java.time, the modern Java date and time API.

```<code>    int weekNumber = myZonedDateTime.get(WeekFields.ISO.weekOfYear());
</code>```

The same will work with an OffsetDateTime, a LocalDateTime and a LocalDate. For a date or date-time today (Dec 6, 2017), you get 49.

I used ISO 8601 weeks (Monday is the first day of week, and week 1 is the first week that has at least 4 days in January). If your weeks are different, please substitute a different WeekFields object, for example WeekFields.SUNDAY_START.

If you cannot avoid getting an old-fashioned Date object, convert it to a modern Instant and do the further operations using the modern API:

```<code>    ZonedDateTime converted = oldFashionedDate.toInstant()
            .atZone(ZoneId.of("Pacific/Nauru"));
</code>```

Please substitute your desired time zone (provided that you didn’t want Pacific/Nauru). Once you’ve got a ZonedDateTime, proceed as above.

Body:
I am sorry that I cannot write Scala code. I will have to trust you to adapt from my Java snippets.

If you can, abandon the long outdated Date class. Use for example ZonedDateTime from java.time, the modern Java date and time API.

    int weekNumber = myZonedDateTime.get(WeekFields.ISO.weekOfYear());

The same will work with an OffsetDateTime, a LocalDateTime and a LocalDate. For a date or date-time today (Dec 6, 2017), you get 49.

I used ISO 8601 weeks (Monday is the first day of week, and week 1 is the first week that has at least 4 days in January). If your weeks are different, please substitute a different WeekFields object, for example WeekFields.SUNDAY_START.

If you cannot avoid getting an old-fashioned Date object, convert it to a modern Instant and do the further operations using the modern API:

    ZonedDateTime converted = oldFashionedDate.toInstant()
            .atZone(ZoneId.of("Pacific/Nauru"));

Please substitute your desired time zone (provided that you didn’t want Pacific/Nauru). Once you’ve got a ZonedDateTime, proceed as above.


问:
Show hidden divs in the new clone () div
Any suggestions on how to keep the hidden (display:none) div hidden but make it show up in the new clone div?.

The clone works When I take away the display style but i need it to be hidden. I have extensively tried to research and fix the issue with no luck. (maybe because i am a beginner coder)

Here is my code:

(div for new clones)

```<code><div class="showcontent" class="toggle"></div>
</code>```

(.poster div containing elements to be cloned)

```<code><div class=poster><img width='<?php 67*2.3 ?>' height='<?= 98*2.3 ?>' src='<?= $movie['image_url'] ?>'> <br>
<div class=title><h1text><?= $movie['title'] ?></h1text>  </div>  <br>
<span class=year>(<?= $movie['year'] ?>)</span>
<div class=title style="display:none"><h1text><?= $movie['title'] ?></h1text>  </div>  <br> </div>
</code>```

(script)

```<code>$(".poster").click(function(){
img = $(this).clone();
$(".showcontent").show().html(img.removeAttr(''));
});
</code>```

答:
```<code>$(".poster").click(function(){
  var divNewPoster = $(this).clone();

  divNewPoster.find("div").show();
  // or if you want to be more selective:
  divNewPoster.find(".title").show();

  $(".showcontent").empty().show().append(divNewPoster);
});
</code>```

Body:
Any suggestions on how to keep the hidden (display:none) div hidden but make it show up in the new clone div?.

The clone works When I take away the display style but i need it to be hidden. I have extensively tried to research and fix the issue with no luck. (maybe because i am a beginner coder)

Here is my code:

(div for new clones)

(.poster div containing elements to be cloned)

<img width='<?php 67*2.3 ?>' height='<?= 98*2.3 ?>' src='<?= $movie['image_url'] ?>'>

<h1text><?= $movie['title'] ?></h1text>

(<?= $movie['year'] ?>)

<h1text><?= $movie['title'] ?></h1text>

(script)

$(".poster").click(function(){
img = $(this).clone();
$(".showcontent").show().html(img.removeAttr(''));
});