问:
Spring Security OAuth2- POST request to oauth/token redirects to login and role displays ROLE_ANONYMOUS
I am following the link https://spring.io/blog/2015/02/03/sso-with-oauth2-angular-js-and-spring-security-part-v & the github project https://github.com/spring-guides/tut-spring-security-and-angular-js/tree/master/oauth2. I am able to login in to the OAuth provider and get the authorization code back in the client.

Now I make the following call from the client to get the token from the provider (provider is on port 9999)

```<code>        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept",MediaType.APPLICATION_JSON_VALUE);
        List<String> cookies = httpEntity.getHeaders().get("Cookie");
        headers.put("Cookie", cookies);
        String redirectURL= "http://localhost:9999/oauthprovider/oauth/token" +  "?" + "response_type=token" + "&" + "grant_type=authorization_code" + "&" + "client_id=acme"+ "&" + "client_secret=acmesecret"+  "&" + "redirect_uri=http://localhost:8081/callback"+"&" + "code=" + authCode + "&" + "state=" + stateValue;

        HttpEntity<String> redirectResponse = template.exchange(
                redirectURL,
                    HttpMethod.POST,
                    responseentity,
                    String.class);

        result=redirectResponse.toString()
</code>```

The result variable value has the following.(I have disabled csrf and sending client_secret as a query parameter (for the time being), although they are not recommended)

```<code>    <302 Found,{X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY], Location=[http://localhost:9999/oauthprovider/oauthlogin], Content-Length=[0], Date=[Thu, 09 Nov 2017 12:07:37 GMT]}>
</code>```

In the console I have these

```<code>   Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 2B669DF59BCE8047849BFBCA148BEE67; Granted Authorities: ROLE_ANONYMOUS
</code>```

Does I am redirecting back to login(I am getting it in the logs as mentioned before), since the role is ROLE_ANONYMOUS? How can I fix the issue?

Adding more details on the code (Did only minor changes from the sample code provided in the link). Providers's context path is /oauthprovider and with curl call I am getting the token.

```<code>@Configuration
@EnableAuthorizationServer
protected static class OAuth2AuthorizationConfig extends
        AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    //................................
    //................................
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("acme")
                .secret("acmesecret")
                .authorizedGrantTypes("authorization_code", "refresh_token",
                        "password").scopes("openid").autoApprove(true).redirectUris("http://localhost:8081/callback");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
        endpoints.authenticationManager(authenticationManager).accessTokenConverter(
                jwtAccessTokenConverter());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer)
            throws Exception {
        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess(
                "isAuthenticated()");
    }

}
@Configuration
@Order(-20)
protected static class LoginConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .formLogin().loginPage("/oauthlogin").loginProcessingUrl("/login").failureUrl("/login?error=true").permitAll()
        .and()
            .requestMatchers().antMatchers("/login", "/oauthlogin", "/oauth/authorize", "/oauth/token" ,"/oauth/confirm_access")
        .and()
            .authorizeRequests().anyRequest().authenticated();
        // @formatter:on

        http.csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.parentAuthenticationManager(authenticationManager);
    }
}
</code>```

答:
Something went wrong in my last day's testing. I can get access token if my handler is either in client or in provider. If my redirect handler is in provider the user is not anonymous as per the debug logs (may be due to session..?)But looks like I have to use one redirect_url consistently.(Otherwise I get redirect_uri mismatch error..)

Following is the working code that gets json response..

```<code>@ResponseBody
@RequestMapping(value = "/clientcallback", method = RequestMethod.GET)
public ResponseEntity<OauthTokenResponse> redirectCallback(@RequestParam (value= "code", defaultValue="") String authCode,@RequestParam (value= "state", defaultValue="") String stateValue,HttpEntity<String> httpEntity)
{

    HttpHeaders headers = new HttpHeaders();
    RestTemplate restTemplate = new RestTemplate();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    String plainCreds = "acme:acmesecret";
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = org.apache.commons.net.util.Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);
    headers.add("Authorization", "Basic " + base64Creds);

        List<String> cookies = httpEntity.getHeaders().get("Cookie");
        if(cookies != null)
        {
            headers.put("Cookie", cookies);
        }
        else
        {

            cookies = httpEntity.getHeaders().get("Set-Cookie");
            headers.put("Set-Cookie", cookies);
        }
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map,
                headers);

        OauthTokenResponse res = null;
        try {
            res = restTemplate.postForObject("http://localhost:9999/uaa/oauth/token?grant_type=authorization_code&client_id=acme&redirect_uri=http://localhost:8081/clientcallback&code=" + authCode, request,
                    OauthTokenResponse.class);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return  new ResponseEntity<OauthTokenResponse>(res, HttpStatus.OK);
    }
</code>```

Thanks again for the tips..

Body:
I am following the link https://spring.io/blog/2015/02/03/sso-with-oauth2-angular-js-and-spring-security-part-v & the github project https://github.com/spring-guides/tut-spring-security-and-angular-js/tree/master/oauth2. I am able to login in to the OAuth provider and get the authorization code back in the client.

Now I make the following call from the client to get the token from the provider (provider is on port 9999)

        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept",MediaType.APPLICATION_JSON_VALUE);
        List<String> cookies = httpEntity.getHeaders().get("Cookie");
        headers.put("Cookie", cookies);
        String redirectURL= "http://localhost:9999/oauthprovider/oauth/token" +  "?" + "response_type=token" + "&" + "grant_type=authorization_code" + "&" + "client_id=acme"+ "&" + "client_secret=acmesecret"+  "&" + "redirect_uri=http://localhost:8081/callback"+"&" + "code=" + authCode + "&" + "state=" + stateValue;

        HttpEntity<String> redirectResponse = template.exchange(
                redirectURL,
                    HttpMethod.POST,
                    responseentity,
                    String.class);

        result=redirectResponse.toString()

The result variable value has the following.(I have disabled csrf and sending client_secret as a query parameter (for the time being), although they are not recommended)

    <302 Found,{X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY], Location=[http://localhost:9999/oauthprovider/oauthlogin], Content-Length=[0], Date=[Thu, 09 Nov 2017 12:07:37 GMT]}>

In the console I have these

   Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 2B669DF59BCE8047849BFBCA148BEE67; Granted Authorities: ROLE_ANONYMOUS

Does I am redirecting back to login(I am getting it in the logs as mentioned before), since the role is ROLE_ANONYMOUS? How can I fix the issue?

Adding more details on the code (Did only minor changes from the sample code provided in the link). Providers's context path is /oauthprovider and with curl call I am getting the token.

@Configuration
@EnableAuthorizationServer
protected static class OAuth2AuthorizationConfig extends
        AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    //................................
    //................................
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("acme")
                .secret("acmesecret")
                .authorizedGrantTypes("authorization_code", "refresh_token",
                        "password").scopes("openid").autoApprove(true).redirectUris("http://localhost:8081/callback");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
        endpoints.authenticationManager(authenticationManager).accessTokenConverter(
                jwtAccessTokenConverter());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer)
            throws Exception {
        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess(
                "isAuthenticated()");
    }

}
@Configuration
@Order(-20)
protected static class LoginConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .formLogin().loginPage("/oauthlogin").loginProcessingUrl("/login").failureUrl("/login?error=true").permitAll()
        .and()
            .requestMatchers().antMatchers("/login", "/oauthlogin", "/oauth/authorize", "/oauth/token" ,"/oauth/confirm_access")
        .and()
            .authorizeRequests().anyRequest().authenticated();
        // @formatter:on

        http.csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.parentAuthenticationManager(authenticationManager);
    }
}

Body:
Something went wrong in my last day's testing. I can get access token if my handler is either in client or in provider. If my redirect handler is in provider the user is not anonymous as per the debug logs (may be due to session..?)But looks like I have to use one redirect_url consistently.(Otherwise I get redirect_uri mismatch error..)

Following is the working code that gets json response..

@ResponseBody
@RequestMapping(value = "/clientcallback", method = RequestMethod.GET)
public ResponseEntity<OauthTokenResponse> redirectCallback(@RequestParam (value= "code", defaultValue="") String authCode,@RequestParam (value= "state", defaultValue="") String stateValue,HttpEntity<String> httpEntity)
{

    HttpHeaders headers = new HttpHeaders();
    RestTemplate restTemplate = new RestTemplate();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    String plainCreds = "acme:acmesecret";
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = org.apache.commons.net.util.Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);
    headers.add("Authorization", "Basic " + base64Creds);

        List<String> cookies = httpEntity.getHeaders().get("Cookie");
        if(cookies != null)
        {
            headers.put("Cookie", cookies);
        }
        else
        {

            cookies = httpEntity.getHeaders().get("Set-Cookie");
            headers.put("Set-Cookie", cookies);
        }
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map,
                headers);

        OauthTokenResponse res = null;
        try {
            res = restTemplate.postForObject("http://localhost:9999/uaa/oauth/token?grant_type=authorization_code&client_id=acme&redirect_uri=http://localhost:8081/clientcallback&code=" + authCode, request,
                    OauthTokenResponse.class);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return  new ResponseEntity<OauthTokenResponse>(res, HttpStatus.OK);
    }

Thanks again for the tips..


来源: stackexchange

问:
MVVMLight-- Passing a parameter to a ViewModel constructor?
Suppose I have a ListBox which is bound to a collection of Foo objects, and the selected Foo is displayed in a contentcontrol with the content template being a FooView.

Is there a way that I can make it so that the FooView passes the selected Foo to the constructor of the FooViewModel which is it's datacontext via the ViewModelLocator?

答:
MainViewModel

```<code>/*INotifyPropertChanged property*/
public FooViewModel CurrentFooVM{
    get{/*INPC code*/}
    private set{/*INPC code*/}
}

/*INotifyPropertChanged property*/
public Foo SelectedFoo{
    get{/*INPC code*/}
    set{/*INPC code*/ CurrentFooVM = new FooViewModel(_selectedFoo)}
}

public ObservableCollection<Foo> Foos {get; private set;}
</code>```

MainView

```<code><ListBox ItemsSource={Binding Foos}
         SelectedItem={Binding SelectedFoo}>...
<FooView... bind to CurrentFooVM...
</code>```

ContentLicense: CC BY-SA 2.5

Body:
MainViewModel

/*INotifyPropertChanged property*/
public FooViewModel CurrentFooVM{
    get{/*INPC code*/}
    private set{/*INPC code*/}
}

/*INotifyPropertChanged property*/
public Foo SelectedFoo{
    get{/*INPC code*/}
    set{/*INPC code*/ CurrentFooVM = new FooViewModel(_selectedFoo)}
}

public ObservableCollection<Foo> Foos {get; private set;}

MainView

<ListBox ItemsSource={Binding Foos}
         SelectedItem={Binding SelectedFoo}>...
<FooView... bind to CurrentFooVM...


问:
Return Code on failure. Positive or negative?
a C-programm can fail to execute under special circumstances in Linux.
Example: You allocate some space and the OS denies it.

```<code>char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return ENOMEM;
</code>```

This failure is marked by the return code which is delivered to the OS.

A return code of 0 (EXIT_SUCCESS) is marked as a successful execution.

A return code which is not 0, is marked as a failure.

So my question is, what is the convention, when a program detects an error.
Should it return a positive or a negative return code ?

My professor told me in UNIX/Linux allways to return a negative error code. But the errno-Codes are all positive integers. Also the define-Statement of EXIT_FAILURE in  is 1, a positive integer.
So should my code look like this:

```<code>char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return -ENOMEM;
</code>```

or like the code above? I know from Linux-Kernel-Modules that in most cases they return a negative error code on failure.

Thanks for helping.

答:
The exit code on UNIX/Linux from a process, the return statement in main() or a call to exit(), is unsigned in the range 0 - 255.

From a function it can be any type you want it to be.  Many library functions return -1 on error.

However that is not always possible, particularly functions that normally return a pointer.  By convention those functions return NULL on error, examples are fopen() and malloc().

These return codes only indicate that an error has occurred, not what the error is, usually (on error) the global errno is also set to a positive error code giving further information.  See man errno

ContentLicense: CC BY-SA 3.0

Body:
a C-programm can fail to execute under special circumstances in Linux.
Example: You allocate some space and the OS denies it.

char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return ENOMEM;

This failure is marked by the return code which is delivered to the OS.

A return code of 0 (EXIT_SUCCESS) is marked as a successful execution.

A return code which is not 0, is marked as a failure.

So my question is, what is the convention, when a program detects an error.
Should it return a positive or a negative return code ?

My professor told me in UNIX/Linux allways to return a negative error code. But the errno-Codes are all positive integers. Also the define-Statement of EXIT_FAILURE in  is 1, a positive integer.
So should my code look like this:

char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return -ENOMEM;

or like the code above? I know from Linux-Kernel-Modules that in most cases they return a negative error code on failure.

Thanks for helping.


问:
Integrate Jama library in Netbeans platform
I would like to integrate the Jama library into Netbeans (not just a single project). However, I get the message "package Jama does not exist." I have done the following:

I downloaded Jama's jar file.

Then I went to Tools, Libraries, pressed the button new library.

Put in the name of the library and hit OK.

Then I hit the button "Add JAR / Folder" and chose the jar file.

What can this be? Unfortunately I only found descriptions of how to integrate libraries into individual projects.

答:
You use the word "platform", so I'm assuming you are building an application based on the NetBeans Platform.

Whenever you want to use an external library in such an application it is generally (although not always, but it is the cleanest method) required to create a library wrapper module for your external jar. You essentially wrap that external jar in a NetBeans module. Then you include the newly created module in application.

Creating a library wrapper module is simple, but the method depends if you are using Ant or Maven:

Ant: New project --> NetBeans Modules --> Library Wrapper Module

Maven: Create an empty NetBeans module. Add your Jama library as a dependency, something like:

<dependency>
    <groupId>gov.nist.math</groupId>
    <artifactId>jama</artifactId>
    <version>1.0.3</version>
</dependency>
```

You also need to tell which packages your newly created module exposes to the rest of the world, but in your case it is likely to be everything, i.e. all packages in the jar.

Once you have wrapped your jar in a module then that functionality can be used from any other NetBeans Module as long as you create a dependency on your newly created module.

Note: If only one module in your application will actually directly interact with Jama (i.e. use its classes), then you do not need a library wrapper module. Then you just do as follows on the module that will use the Jama classes: Right-click the top node of the project:

Then choose "Properties" --> "Libraries" --> "Wrapped JARs" tab. And add your Jama jar there.

Body:
You use the word "platform", so I'm assuming you are building an application based on the NetBeans Platform.

Whenever you want to use an external library in such an application it is generally (although not always, but it is the cleanest method) required to create a library wrapper module for your external jar. You essentially wrap that external jar in a NetBeans module. Then you include the newly created module in application.

Creating a library wrapper module is simple, but the method depends if you are using Ant or Maven:

Ant: New project --> NetBeans Modules --> Library Wrapper Module

Maven: Create an empty NetBeans module. Add your Jama library as a dependency, something like:

<dependency>
    <groupId>gov.nist.math</groupId>
    <artifactId>jama</artifactId>
    <version>1.0.3</version>
</dependency>

You also need to tell which packages your newly created module exposes to the rest of the world, but in your case it is likely to be everything, i.e. all packages in the jar.

Once you have wrapped your jar in a module then that functionality can be used from any other NetBeans Module as long as you create a dependency on your newly created module.

Note: If only one module in your application will actually directly interact with Jama (i.e. use its classes), then you do not need a library wrapper module. Then you just do as follows on the module that will use the Jama classes: Right-click the top node of the project:

Then choose "Properties" --> "Libraries" --> "Wrapped JARs" tab. And add your Jama jar there.


问:
Sun Grid Engine: submitted jobs by qsub command
I am using Sun Grid Engine queuing system.

Assume I submitted multiple jobs using a script that looks like:

```<code>#! /bin/bash
for i in 1 2 3 4 5
do
    sh qsub.sh python run.py ${i}
done
</code>```

qsub.sh looks like:

```<code>#! /bin/bash
echo cd `pwd` \; "$@" | qsub
</code>```

Assuming that 5 jobs are running, I want to find out which command each job is executing.

By using qstat -f, I can see which node is running which jobID, but not what specific command each jobID is related to.

So for example, I want to check which jobID=xxxx is running python run.py 3 and so on.

How can I do this?

答:
You could try running array jobs.  Array jobs are useful when you have multiple inputs to process in the same way.  Qstat will identify each instance of the array of jobs.  See the docs for more information.

http://docs.adaptivecomputing.com/torque/4-0-2/Content/topics/commands/qsub.htm#-t

http://wiki.gridengine.info/wiki/index.php/Simple-Job-Array-Howto

Body:
I am using Sun Grid Engine queuing system.

Assume I submitted multiple jobs using a script that looks like:

#! /bin/bash
for i in 1 2 3 4 5
do
    sh qsub.sh python run.py ${i}
done

qsub.sh looks like:

#! /bin/bash
echo cd `pwd` \; "$@" | qsub

Assuming that 5 jobs are running, I want to find out which command each job is executing.

By using qstat -f, I can see which node is running which jobID, but not what specific command each jobID is related to.

So for example, I want to check which jobID=xxxx is running python run.py 3 and so on.

How can I do this?


问:
C# Passing Dapper POCO and Dapper.Fluent EntityMap as a arguments
I am currently trying to setup work with MySQL db via dapper.

I have declared POCO for dapper:

```<code>public class DevicesOnTesterDbTable
{
    public string UUID { get; set; }
    public string DeviceType { get; set; }
    public string DeviceAddedAt { get; set; }
    public uint Address { get; set; }
}
</code>```

I also have Dapper.Fluent EntityMap for that table:

```<code>public class DevicesOnTesterDbTableMap : EntityMap<DevicesOnTesterDbTable>
{
    public DevicesOnTesterDbTableMap()
    {
        Map(p => p.UUID).ToColumn("devices_on_tester_uuid");
        Map(p => p.DeviceType).ToColumn("devices_on_tester_type");
        Map(p => p.DeviceAddedAt).ToColumn("devices_on_tester_add_at");
        Map(p => p.Address).ToColumn("devices_on_tester_address");
    }
}
</code>```

My database have about ten tables so i have ten pairs of POCO and EntityMap classes for them. So in case of reading i have to perform something like this for each table:

```<code>public static List<DevicesOnTesterDbTable> ReadDevices(string server)
{
    FluentMapper.Initialize(config =>
    {
        config.AddMap(new DevicesOnTesterDbTableMap());
    });

    try
    {
        using (var mySqlConnection = OpenConnection(server))
        {
            mySqlConnection.Open();
            return mySqlConnection.Query<DevicesOnTesterDbTable>("Select * from power_source_calibration").ToList();
         }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
}
</code>```

Now is there a way to pass this pairs into some other method that will perform common operations such as read\write\update etc? Or maybe there is some better way around?

答:
There is a better way around; actually you are doing it wrong.

You do not need to call FluentMapper.Initialize in each of your method like ReadDevices. Ideally, all your mappings (for all entities) should happen only once at the startup of your application.

Following is from here:

Initialize your mapping at the start of your application.

```<code>FluentMapper.Initialize(config =>
{
    config.AddMap(new InvoiceMap());
});
</code>```

Also, refer this question which shows how to do it at application startup. Refer Register() method which is static and caller call it once at application startup somewhere.

Body:
I am currently trying to setup work with MySQL db via dapper.

I have declared POCO for dapper:

public class DevicesOnTesterDbTable
{
    public string UUID { get; set; }
    public string DeviceType { get; set; }
    public string DeviceAddedAt { get; set; }
    public uint Address { get; set; }
}

I also have Dapper.Fluent EntityMap for that table:

public class DevicesOnTesterDbTableMap : EntityMap<DevicesOnTesterDbTable>
{
    public DevicesOnTesterDbTableMap()
    {
        Map(p => p.UUID).ToColumn("devices_on_tester_uuid");
        Map(p => p.DeviceType).ToColumn("devices_on_tester_type");
        Map(p => p.DeviceAddedAt).ToColumn("devices_on_tester_add_at");
        Map(p => p.Address).ToColumn("devices_on_tester_address");
    }
}

My database have about ten tables so i have ten pairs of POCO and EntityMap classes for them. So in case of reading i have to perform something like this for each table:

public static List<DevicesOnTesterDbTable> ReadDevices(string server)
{
    FluentMapper.Initialize(config =>
    {
        config.AddMap(new DevicesOnTesterDbTableMap());
    });

    try
    {
        using (var mySqlConnection = OpenConnection(server))
        {
            mySqlConnection.Open();
            return mySqlConnection.Query<DevicesOnTesterDbTable>("Select * from power_source_calibration").ToList();
         }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
}

Now is there a way to pass this pairs into some other method that will perform common operations such as read\write\update etc? Or maybe there is some better way around?

Body:
There is a better way around; actually you are doing it wrong.

You do not need to call FluentMapper.Initialize in each of your method like ReadDevices. Ideally, all your mappings (for all entities) should happen only once at the startup of your application.

Following is from here:

Initialize your mapping at the start of your application.

FluentMapper.Initialize(config =>
{
    config.AddMap(new InvoiceMap());
});

Also, refer this question which shows how to do it at application startup. Refer Register() method which is static and caller call it once at application startup somewhere.


问:
jQuery IF statement not working
Im performing an ajax query to check the name of a car in a mysql database, if a car is found it will return "Car name unavailable", otherwise "Car name available". This text is put into a div with an id of "checkname".

All this runs fine, but when I try to hide the add button if the car name is unavailable it fails to do so and I dont know why :/

```<code>function check_name(){

 $.ajax({
  type: "POST",
  url: "http://localhost/Framework/library/php_files/check_car_name.php",
  data:  "carName=" + document.getElementById("carName").value,
  success: function(html){
   $("#checkname").html(html);
  }
 });

 var currentHtml = $("#checkname").html();
 var compareString = "Car name unavailable";

 if (currentHtml==compareString) {
  $("#submit").hide();
 } else {
  $("#submit").show();
 }

}
</code>```

答:
You have to put the code inside of you AJAX requests success callback, otherwise it will be called before the AJAX call has completed.  Putting it inside the success callback means that the code containing the IF statement will only run after the AJAX call has completed.  Try:

function check_name(){

```<code> $.ajax({
  type: "POST",
  url: "http://localhost/Framework/library/php_files/check_car_name.php",
  data:  "carName=" + document.getElementById("carName").value,
  success: function(html){
   $("#checkname").html(html);

var currentHtml = $("#checkname").html();
 var compareString = "Car name unavailable";

 if (currentHtml==compareString) {
  $("#submit").hide();
 } else {
  $("#submit").show();
 }
  }
 });

}
</code>```

Title: jQuery IF statement not working

Body:
Im performing an ajax query to check the name of a car in a mysql database, if a car is found it will return "Car name unavailable", otherwise "Car name available". This text is put into a div with an id of "checkname".

All this runs fine, but when I try to hide the add button if the car name is unavailable it fails to do so and I dont know why :/

function check_name(){

 $.ajax({
  type: "POST",
  url: "http://localhost/Framework/library/php_files/check_car_name.php",
  data:  "carName=" + document.getElementById("carName").value,
  success: function(html){
   $("#checkname").html(html);
  }
 });

 var currentHtml = $("#checkname").html();
 var compareString = "Car name unavailable";

 if (currentHtml==compareString) {
  $("#submit").hide();
 } else {
  $("#submit").show();
 }

}

Body:
You have to put the code inside of you AJAX requests success callback, otherwise it will be called before the AJAX call has completed.  Putting it inside the success callback means that the code containing the IF statement will only run after the AJAX call has completed.  Try:

function check_name(){

 $.ajax({
  type: "POST",
  url: "http://localhost/Framework/library/php_files/check_car_name.php",
  data:  "carName=" + document.getElementById("carName").value,
  success: function(html){
   $("#checkname").html(html);

var currentHtml = $("#checkname").html();
 var compareString = "Car name unavailable";

 if (currentHtml==compareString) {
  $("#submit").hide();
 } else {
  $("#submit").show();
 }
  }
 });

}


问:
Clause group by if two lines return the maximum
My query is:

```<code>SELECT ID,B,C,D, SUM(X), SUM(Y)
FROM TABLE
GROUP BY A,B,C,D
</code>```

But if the query returns 2 lines with the same id, I want take only one line which have the max of column D.

For example if the query returns:

```<code>+----+---+---+---+--------+--------+
| ID | B | C | D | SUM(X) | SUM(Y) |
+----+---+---+---+--------+--------+
| 2  | 1 | 1 | 1 | 70     | 100    |
| 2  | 1 | 1 | 3 | 100    | 150    |
+----+---+---+---+--------+--------+
</code>```

Then drop the line with D=1, and keep only the line with D=3

答:
You want to show one row per ID/B/C combination. In case you find multiple results for one combination (ID=2, B=1, C=1 in your example), you want the one with the greatest D. So you must rank your aggregation results.

In standard SQL you rank your rows with RANK, DENSE_RANK or ROW_NUMBER depending on what you want to do with ties. We don't know your DBMS, but many DBMS feature these functions, so just try.

```<code>select id, b, c, d, sum_x, sum_y
from
(
  select
    id, b, c, d, sum(x) as sum_x, sum(y) as sum_y,
    row_number() over (partition by id, b, c order by d desc) as rnk
  from table
  group by id, b, c, d
) ranked
where rnk = 1;
</code>```

Body:
My query is:

SELECT ID,B,C,D, SUM(X), SUM(Y)
FROM TABLE
GROUP BY A,B,C,D

But if the query returns 2 lines with the same id, I want take only one line which have the max of column D.

For example if the query returns:

+----+---+---+---+--------+--------+
| ID | B | C | D | SUM(X) | SUM(Y) |
+----+---+---+---+--------+--------+
| 2  | 1 | 1 | 1 | 70     | 100    |
| 2  | 1 | 1 | 3 | 100    | 150    |
+----+---+---+---+--------+--------+

Then drop the line with D=1, and keep only the line with D=3

Body:
You want to show one row per ID/B/C combination. In case you find multiple results for one combination (ID=2, B=1, C=1 in your example), you want the one with the greatest D. So you must rank your aggregation results.

In standard SQL you rank your rows with RANK, DENSE_RANK or ROW_NUMBER depending on what you want to do with ties. We don't know your DBMS, but many DBMS feature these functions, so just try.

select id, b, c, d, sum_x, sum_y
from
(
  select
    id, b, c, d, sum(x) as sum_x, sum(y) as sum_y,
    row_number() over (partition by id, b, c order by d desc) as rnk
  from table
  group by id, b, c, d
) ranked
where rnk = 1;


问:
Gradle "manifest requires a placeholder substitution" error but manifestPlaceholders supplies a value
I'm trying to perform substitution within the AndroidManifest.xml file from the build.gradle android extension but am getting this error:

```<code>AndroidManifest.xml:89:16 Error:
    Attribute uses-library#com.company.platform.${encoding}@name at AndroidManifest.xml:89:16 requires a placeholder substitution but no value for <encoding> is provided.
/Users/Company/Desktop/Checkout/android/Project/app/src/main/AndroidManifest.xml:0:0 Error:
    Validation failed, exiting
:app:processDebugManifest FAILED
</code>```

This is a snippet of the manifest file:

```<code>...
     </receiver>
   <uses-library android:name="com.company.platform.${encoding}" />
</application>
...
</code>```

And this is a snipped of the build.gradle:

```<code>android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    defaultConfig {
        applicationId "com.company.app"
        minSdkVersion 23
        targetSdkVersion 23
        versionName cityVersion
        setProperty("archivesBaseName", "City_$versionName")
        manifestPlaceholders = [encoding: "some value"]
        manifestPlaceholders = [version: cityVersion]
    }
</code>```

I've also tried adding the manifestPlaceholders in the buildTypes i.e.

```<code>buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        manifestPlaceholders = [encoding: deviceEncoding]
        manifestPlaceholders = [version: cityIDVersion]
   }
    debug {
        manifestPlaceholders = [encoding: deviceEncoding]
        manifestPlaceholders = [version: cityIDVersion]
    }
</code>```

}

But I still get the same error.

Why is there an error about it requiring a placeholder substitution when one is provided for in the manifestPlaceholders?

答:
I had left the ${} symbols around my value:</p>

```<code><meta-data android:name="net.example" android:value="${XXXX}" />
</code>```

Body:
I'm trying to perform substitution within the AndroidManifest.xml file from the build.gradle android extension but am getting this error:

AndroidManifest.xml:89:16 Error:
    Attribute uses-library#com.company.platform.${encoding}@name at AndroidManifest.xml:89:16 requires a placeholder substitution but no value for <encoding> is provided.
/Users/Company/Desktop/Checkout/android/Project/app/src/main/AndroidManifest.xml:0:0 Error:
    Validation failed, exiting
:app:processDebugManifest FAILED

This is a snippet of the manifest file:

...
     </receiver>
   <uses-library android:name="com.company.platform.${encoding}" />
</application>
...

And this is a snipped of the build.gradle:

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    defaultConfig {
        applicationId "com.company.app"
        minSdkVersion 23
        targetSdkVersion 23
        versionName cityVersion
        setProperty("archivesBaseName", "City_$versionName")
        manifestPlaceholders = [encoding: "some value"]
        manifestPlaceholders = [version: cityVersion]
    }

I've also tried adding the manifestPlaceholders in the buildTypes i.e.

buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        manifestPlaceholders = [encoding: deviceEncoding]
        manifestPlaceholders = [version: cityIDVersion]
   }
    debug {
        manifestPlaceholders = [encoding: deviceEncoding]
        manifestPlaceholders = [version: cityIDVersion]
    }

}

But I still get the same error.

Why is there an error about it requiring a placeholder substitution when one is provided for in the manifestPlaceholders?

Body:
I had left the ${} symbols around my value:

<meta-data android:name="net.example" android:value="${XXXX}" />


问:
How is an arc described in the DXF format if it is tilted out of the X-Y plane?
I am trying to make sense of the DXF CAD file format.

I have drawn an arc in my (intellicad) CAD software, centre at (5,5,5), radius of 300, start angle 40 degrees and end angle 110. I have then rotated the arc by 5 degrees in the Y-Z plane. I am doing this because I want to see what effect the 210, 220 and 230 group codes (which define the extrusion direction) have.

I am expecting to see this:

```<code>  0
ARC
 10
5.0
 20
5.0
 30
5.0
 40
300.0
210
0.0
220
0.08715574274765817
230
0.9961946980917455
 50
220.0
 51
290.0
</code>```

Instead I see this:

```<code>  0
ARC
 10
-5.0
 20
-4.545194776720437
 30
5.416752204197018
 40
300.0
210
0.0
220
0.08715574274765817
230
0.9961946980917455
 50
220.0
 51
290.0
</code>```

Why is the centre of the arc not on (5,5,5)?

I'm trying to parse DXF files in C++ and write it as an SVG, but the values I'm getting won't give me a true depiction.

How does the value of (5.0,5.0,5.0) get changed to (-5.0,-4.545194776720437,5.416752204197018)? Does anyone know?

I'm not sure that anyone can answer this for me, but I have seen questions on the DXF format answered here, so I'm hoping!

答:
I am not a DXF expert. But..

If you rotate something at (5,5) around the origin by 5 degrees, you get:

```<code>5 * sin(5deg) - 5 * cos(5deg) = -4.54519
5 * cos(5deg) + 5 * sin(5deg) = 5.41675
</code>```

Body:
I am trying to make sense of the DXF CAD file format.

I have drawn an arc in my (intellicad) CAD software, centre at (5,5,5), radius of 300, start angle 40 degrees and end angle 110. I have then rotated the arc by 5 degrees in the Y-Z plane. I am doing this because I want to see what effect the 210, 220 and 230 group codes (which define the extrusion direction) have.

I am expecting to see this:

  0
ARC
 10
5.0
 20
5.0
 30
5.0
 40
300.0
210
0.0
220
0.08715574274765817
230
0.9961946980917455
 50
220.0
 51
290.0

Instead I see this:

  0
ARC
 10
-5.0
 20
-4.545194776720437
 30
5.416752204197018
 40
300.0
210
0.0
220
0.08715574274765817
230
0.9961946980917455
 50
220.0
 51
290.0

Why is the centre of the arc not on (5,5,5)?

I'm trying to parse DXF files in C++ and write it as an SVG, but the values I'm getting won't give me a true depiction.

How does the value of (5.0,5.0,5.0) get changed to (-5.0,-4.545194776720437,5.416752204197018)? Does anyone know?

I'm not sure that anyone can answer this for me, but I have seen questions on the DXF format answered here, so I'm hoping!

Body:
I am not a DXF expert. But..

If you rotate something at (5,5) around the origin by 5 degrees, you get:

5 * sin(5deg) - 5 * cos(5deg) = -4.54519
5 * cos(5deg) + 5 * sin(5deg) = 5.41675


问:
Astyle not working
I downloaded Astyle from here: https://sourceforge.net/projects/astyle/files/

When I execute Astyle.exe in \bin a command prompt opens which looks like this:

I can't execute any commands. Astlye.exe seems to be stuck. I've read the documentation for Quick Start and simple commands multiple times, but could not find my error, so I think, I`m overlooking something obvious.

I realize, there have been similare questions, but none of them could solve my problem.

EDIT: I also rebuild the Astyle.exe. Same problem as before.

答:
The default for most linux-based tools is to read from the standard input if no file is specified (so that one can "pipe" into it).

What you are seeing is simply astyle waiting for input. If you specify a file on the command-line or the --help flag, you'll see more useful information.

Title: Astyle not working


问:
PhoneGap/ Cordova 9-patch Image Splash Screen with center Logo?
I use PhoneGap/Cordova to create an Android app with a splash screen that contains a centered logo.

Here is what I did:

In my Android Manifest.xml I added

```<code><preference name="SplashScreen" value="splash" />
<preference name="SplashScreenDelay" value="5000" />
</code>```

Then I used the nine-path image generator here to create the 9-patch images for the splash screen. The purpose is to have a logo centered in the center all the time. When uploading the image it looks like the following. I kept the edit mode "stretch regions".

The problem is that the splash image is stretched all the time. This means that the logo (the blue box) is disproportioned.

I checked the solutions here Cordova/PhoneGap 9-patch splash screen but it did not help.

How can I use 9-patch images as a splash screen on Android such that the logo is always in the center of the screen and not stretched?

答: The problem is, that the area you have selected - the logo - is at the same time the area that will be used to stretch. You have to define different stretch areas that are outside of your logo's bounding box. While horizontal stretch area can be beneath or above your logo, vertical stretch area can be only left or right to your logo. So the image will never be in de center, as you want it. You have to use different tool to do this. Check this page out</p>

Body:
I use PhoneGap/Cordova to create an Android app with a splash screen that contains a centered logo.

Here is what I did:

In my Android Manifest.xml I added

<preference name="SplashScreen" value="splash" />
<preference name="SplashScreenDelay" value="5000" />

Then I used the nine-path image generator here to create the 9-patch images for the splash screen. The purpose is to have a logo centered in the center all the time. When uploading the image it looks like the following. I kept the edit mode "stretch regions".

The problem is that the splash image is stretched all the time. This means that the logo (the blue box) is disproportioned.

I checked the solutions here Cordova/PhoneGap 9-patch splash screen but it did not help.

How can I use 9-patch images as a splash screen on Android such that the logo is always in the center of the screen and not stretched?


问:
Biztalk Splitting a file and the use of
In Biztalk 2006 I have a custom pipeline that split a file into many files, before each file get mapped. In the send pipeline I use "Use Temporary file for writing". My question is: When splitting messages and use "Use Temporary file for writing", will every one of the splitted files be moved to the out folder from the temp folder at the same time or is each one of the splitted files moved to the out folder as soon as it's done, not waiting for the other files? The files are very smal so I haven't found out. I just want to know the standard behaviour so I don't have to use much time to create big files and watch the result. Thanks for help :)</p>

答:
From your description I'm not 100% sure I fully understand your scenario

I assume you're splitting the file through a disassembler in the receive pipeline, and that your reference to "Use Temporary file for writing" refers to the file send adapter setting and that this send port subscribes to the messages from the receive port.

Given this scenario each output message (a fragment of the original incoming message) will be processed independently and will be delivered as soon as possible, certainly after the message box (on the send side)

If you have a RecoverableInterchangeProcessing setting on your disassembler, and you have set it to True, the messages will be processed completely independently; if this setting is false they will all be committed to the message box together, but then BizTalk may pick them up in any order.

OwnerDisplayName: estranda

LastEditorDisplayName: Fabian Steeg

Title: Biztalk Splitting a file and the use of

OwnerDisplayName: Yossi Dahan


问:
How to set fake GPS location on IOS real device
Currently I have to test app and set the different fake GPS locations on real IOS 7 devices. On Android I use 'My Fake Location'. Unfortunately, I didn't find the same app for IOS 7.
Any ideas to solve my problem?</p>

答:
xCode is picky about the GPX file it accepts.

But, in xCode you can create a GPX file with the format it will accept:

And then just change the content of the file to the location you need.


问:
Set text and color for markers using JSON
I want to set a text and color for each marker with JSON data when I append them to map. This example code is fine. Text and color are static at the moment. Can I do it with some function or maybe should I change the syntax to make it work?</p>

```<code>const vectorSource = new ol.source.Vector();
const vectorLayer = new ol.layer.Vector({
  source: vectorSource,
  style: new ol.style.Style({
    image: new ol.style.Circle({
      radius: 18,
      fill: new ol.style.Fill({
        color: [0, 155, 0, 0.6]
      }),
      stroke: new ol.style.Stroke({
        color: [0, 200, 0, 0.9],
        width: 3
      })
    }),
    text: new ol.style.Text({
      text: "Test",
      scale: 1.2,
      fill: new ol.style.Fill({
        color: "#fff"
      }),
      stroke: new ol.style.Stroke({
        color: "0",
        width: 3
      })
    })
  })
})
vectorLayer.setZIndex(5);
const map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    ),
    vectorLayer
  ],
  target: "map",
  view: new ol.View({
    center: [0, 0],
     zoom: 5
  })
});
const addMarkers = (lat, long) => {
  if(lat && lat !== 0) {
    const point = new ol.geom.Point(ol.proj.transform([lat, long], "EPSG:4326", "EPSG:3857"));
    const iconFeature = new ol.Feature({
      geometry: point
    });
    vectorSource.addFeature(iconFeature);
  }
}
// Positions come from map.jade
positions.forEach(position => {
  let long = position.geolocation.longitude;
  let lat = position.geolocation.latitude;
  if (long !== 0 && long !== 999.9 && long !== "" &&  long !== undefined) {
    addMarkers(long, lat);
  }
});
</code>```

答:
In the ol.layer.Vector constructor, instead of passing an ol.style.Style instance, you can pass a function.

That function will receive feature and resolution and shall return an ol.style.Style object.

Here's an example: http://openlayersbook.github.io/ch06-styling-vector-layers/example-07.html

Otherwise, you can use the ol.Feature.setStyle function inside the addMarkers function.

Body:
I want to set a text and color for each marker with JSON data when I append them to map. This example code is fine. Text and color are static at the moment. Can I do it with some function or maybe should I change the syntax to make it work?

const vectorSource = new ol.source.Vector();
const vectorLayer = new ol.layer.Vector({
  source: vectorSource,
  style: new ol.style.Style({
    image: new ol.style.Circle({
      radius: 18,
      fill: new ol.style.Fill({
        color: [0, 155, 0, 0.6]
      }),
      stroke: new ol.style.Stroke({
        color: [0, 200, 0, 0.9],
        width: 3
      })
    }),
    text: new ol.style.Text({
      text: "Test",
      scale: 1.2,
      fill: new ol.style.Fill({
        color: "#fff"
      }),
      stroke: new ol.style.Stroke({
        color: "0",
        width: 3
      })
    })
  })
})
vectorLayer.setZIndex(5);
const map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    ),
    vectorLayer
  ],
  target: "map",
  view: new ol.View({
    center: [0, 0],
     zoom: 5
  })
});
const addMarkers = (lat, long) => {
  if(lat && lat !== 0) {
    const point = new ol.geom.Point(ol.proj.transform([lat, long], "EPSG:4326", "EPSG:3857"));
    const iconFeature = new ol.Feature({
      geometry: point
    });
    vectorSource.addFeature(iconFeature);
  }
}
// Positions come from map.jade
positions.forEach(position => {
  let long = position.geolocation.longitude;
  let lat = position.geolocation.latitude;
  if (long !== 0 && long !== 999.9 && long !== "" &&  long !== undefined) {
    addMarkers(long, lat);
  }
});


问:
Prevent submit on Enter but allow Enter for newLine in TextArea
Is it possible to prevent the enter key from submitting forms, but allowing the enter key to work inside input. (E.g. textArea newline)?

I tried so far:

e.preventDefault()

e.stopPropagation()

Both on the form tag onkeyup="if (e.keyCode == 13))"

This does prevent submission of the form on enter key, but it also prevents the enter key from working inside formfields completely.
What I want to achieve is, that when I press the enter key inside a TextArea, that it creates a newLine but when I hit enter in a input type="text"that it doesn't submit the form.

Using JSF 2.3

JQuery solution is also ok.

答:
You can test if the element focused is not your textarea like following :

var area = document.getElementById('area');

document.getElementById('doesntSubmit').addEventListener('keydown', function (e) {
  if (e.keyCode === 13 && e.target !== area) {
    e.preventDefault();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="doesntSubmit">
  <input type="text" value="whatever"/>
  <textarea id="area"></textarea>
</form></code>```

Or you could add a data- tag to the elements you don't want to be affected, or a specific class, ... to avoid checking for the tag.

You could also add a css class to the elements which shouldn't submit the form on enter and bind an event handler on it :

$('.doesntSubmit').keydown(function (e) {
  if (e.keyCode === 13) {
    e.preventDefault();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" class="doesntSubmit" value="whatever"/>
  <textarea id="area"></textarea>
</form></code>```

Body:
You can test if the element focused is not your textarea like following :

var area = document.getElementById('area');

document.getElementById('doesntSubmit').addEventListener('keydown', function (e) {
  if (e.keyCode === 13 && e.target !== area) {
    e.preventDefault();
  }
});

<form id="doesntSubmit">
  <input type="text" value="whatever"/>
  <textarea id="area"></textarea>
</form>

Or you could add a data- tag to the elements you don't want to be affected, or a specific class, ... to avoid checking for the tag.

You could also add a css class to the elements which shouldn't submit the form on enter and bind an event handler on it :

$('.doesntSubmit').keydown(function (e) {
  if (e.keyCode === 13) {
    e.preventDefault();
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" class="doesntSubmit" value="whatever"/>
  <textarea id="area"></textarea>
</form>


问:
Retrieving an element from array list in Android?
I am trying to implement voice recognition code in Android. How do I get an element at a particular position from array list in Android? I tried converting arraylist to array and retriving. Still the code is not working.

```<code>package com.espeaker;

    public class EspeakerActivity extends Activity {

                    private static final int REQUEST_CODE = 1234;
            private ListView wordsList;

            /** Called when the activity is first created. */
            @Override
            public void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.main);

                  Button speakButton = (Button) findViewById(R.id.speakButton);

                  wordsList = (ListView) findViewById(R.id.list);

                  // Disable button if no recognition service is present
                  PackageManager pm = getPackageManager();
                  List<ResolveInfo> activities = pm.queryIntentActivities(
                          new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
                  if (activities.size() == 0)
                  {
                      speakButton.setEnabled(false);
                      speakButton.setText("Recognizer not present");
                  }
            }

    /**
     * Handle the action of the button being clicked
     */
    public void speakButtonClicked(View v)
    {
        startVoiceRecognitionActivity();
    }

    /**
     * Fire an intent to start the voice recognition activity.
     */
    private void startVoiceRecognitionActivity()
    {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice recognition Demo...");
        startActivityForResult(intent, REQUEST_CODE);
    }

    /**
     * Handle the results from the voice recognition activity.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
        {
            // Populate the wordsList with the String values the recognition engine thought it heard
            ArrayList<String> matches = data.getStringArrayListExtra(
                    RecognizerIntent.EXTRA_RESULTS);
            wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                    matches));
            String[] array=matches.toArray(new String[matches.size()]);
           // ArrayList<String> places = new ArrayList<String>(
                //    Arrays.asList("black", "blue", "red"));
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item,matches);
              final AutoCompleteTextView input_text = (AutoCompleteTextView) findViewById(R.id.auto);
              Button button1 = (Button) findViewById(R.id.button1);
                     input_text.setAdapter(adapter);
            button1.setText(" "+array[0]);

           // button1.setText(""+matches);
             }
        super.onActivityResult(requestCode, resultCode, data);
    }
    }
</code>```

答:
U cant try this </p>

```<code>for (WordList i : words) {
     words.get(words.indexOf(i));
 }
</code>```

Body:
I am trying to implement voice recognition code in Android. How do I get an element at a particular position from array list in Android? I tried converting arraylist to array and retriving. Still the code is not working.

package com.espeaker;

    public class EspeakerActivity extends Activity {

                    private static final int REQUEST_CODE = 1234;
            private ListView wordsList;

            /** Called when the activity is first created. */
            @Override
            public void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.main);

                  Button speakButton = (Button) findViewById(R.id.speakButton);

                  wordsList = (ListView) findViewById(R.id.list);

                  // Disable button if no recognition service is present
                  PackageManager pm = getPackageManager();
                  List<ResolveInfo> activities = pm.queryIntentActivities(
                          new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
                  if (activities.size() == 0)
                  {
                      speakButton.setEnabled(false);
                      speakButton.setText("Recognizer not present");
                  }
            }

    /**
     * Handle the action of the button being clicked
     */
    public void speakButtonClicked(View v)
    {
        startVoiceRecognitionActivity();
    }

    /**
     * Fire an intent to start the voice recognition activity.
     */
    private void startVoiceRecognitionActivity()
    {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice recognition Demo...");
        startActivityForResult(intent, REQUEST_CODE);
    }

    /**
     * Handle the results from the voice recognition activity.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
        {
            // Populate the wordsList with the String values the recognition engine thought it heard
            ArrayList<String> matches = data.getStringArrayListExtra(
                    RecognizerIntent.EXTRA_RESULTS);
            wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                    matches));
            String[] array=matches.toArray(new String[matches.size()]);
           // ArrayList<String> places = new ArrayList<String>(
                //    Arrays.asList("black", "blue", "red"));
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item,matches);
              final AutoCompleteTextView input_text = (AutoCompleteTextView) findViewById(R.id.auto);
              Button button1 = (Button) findViewById(R.id.button1);
                     input_text.setAdapter(adapter);
            button1.setText(" "+array[0]);

           // button1.setText(""+matches);
             }
        super.onActivityResult(requestCode, resultCode, data);
    }
    }

Body:
U cant try this

for (WordList i : words) {
     words.get(words.indexOf(i));
 }


问:
Cant get scrollify.js to work?
I am trying to use scrollify.js on my single page website but cannot get it to work?

I have the following html, header.php for loading scrollify and my js in my custom.js file.

What am I doing wrong?

Thanks in advance?

HTML

```<code>        <?php get_header(); ?>
        <div id="sections_all">
        <div id="section_1">
            <section class='section'>
                <div class="section-1-container">
                    <h1 id="section_1">
                        <span style='font-size: 20vh;'>Sell your old <br>Garrard</span>
                    </h1>
                    <h2 id="section_1">
                        Looking to sell your turntable? We buy your used Garrard 301 & 401 record players.
                    </h2>
                </div>
            </section>
        </div>
        <div id="section_2">
            <section class='section'>
                <div class="section-2-container">
                    <!--<p class="contact-text">Contact Us</p>-->
                    <?php echo do_shortcode('[contact-form-7 id="66" title="Contact Us"]'); ?>
                </div>
            </section>
        </div>
        <div id="section_3">
            <section class='section'>
                <div class="section-3-container">
                    <h1 id="section_3">
                        Sell your old turntable
                    </h1>
                </div>
            </section>
        </div>
        <div id="section_4">
            <section class='section'>
                <div class="section-4-container">
                    <h1 id="section_4">
                        Sell your old turntable
                    </h1>
                </div>
            </section>
        </div>
        </div>
        </div>

        <?php get_footer(); ?>
</code>```

Header PHP

```<code> <!DOCTYPE html>
        <html lang="en" class="no-js">
            <head>

                <meta http-equiv="Content-Type" content="text/html"; charset="utf-8">
                <meta name="viewport" content="width-device-width">
                <meta name="apple-mobile-web-app-capable" content="yes">
                <meta name="apple-mobile-web-app-status-bar-style" content="black">
                <meta name="description" content="<?php bloginfo('description'); ?>">
                <title>SellGarrard301</title>
                <script src='https://www.google.com/recaptcha/api.js'></script>
                <script src="https://cdn.jsdelivr.net/npm/jquery-scrollify@1.0.17/jquery.scrollify.js"></script>
                <script src="https://cdn.jsdelivr.net/npm/jquery-scrollify@1.0.17/jquery.scrollify.min.js"></script>
                <?php wp_head(); ?>

            </head>
                <body>
                    <div class="container">
                        <header class="header-wrapper">
                            <p class="logo-text">Sell Garrard.com</p>
                            <div class="hamburger-helper">
                            <div id="menu-toggle">
                                <div id="hamburger">
                                  <span></span>
                                  <span></span>
                                  <span></span>
                                </div>
                                <div id="cross">
                                  <span></span>
                                  <span></span>
                                </div>
                            </div>
                            </div>
                            <nav class="menu-hide">
                                    <?php
                                                wp_nav_menu( array(
                                                    'theme_location' => 'header_menu',
                                                    'container'      => '',
                                                    'container_class' => 'menu-hidden',
                                                    'menu_class'     => 'menu-hide',
                                                    'menu_id'     => 'header_menu',
                                                    ) );
                                            ?>
                            </nav>

                        </header>

        <!-- end of header start of main content -->
</code>```

Custom JS function

```<code> $(document).ready(function(){

 $(function() {
      $.scrollify({
      section: ".section",

      });
 });

 });
</code>```

All files and scripts are loaded when I check but I cannot find any information on how to get it to work?

UPDATED CONSOLE ERRORS:

```<code>                jquery.scrollify.js:45 Uncaught ReferenceError: jQuery is not defined
                at jquery.scrollify.js:45
                at jquery.scrollify.js:47
            (anonymous) @ jquery.scrollify.js:45
            (anonymous) @ jquery.scrollify.js:47
            jquery.scrollify.min.js:1 Uncaught ReferenceError: jQuery is not defined
                at jquery.scrollify.min.js:1
                at jquery.scrollify.min.js:1
            (anonymous) @ jquery.scrollify.min.js:1
            (anonymous) @ jquery.scrollify.min.js:1
            jquery-migrate.min.js?ver=1.4.1:2 JQMIGRATE: Migrate is installed, version 1.4.1
            jquery-3.2.1.js?ver=4.8.3:3860 jQuery.Deferred exception: $.scrollify is not a function TypeError: $.scrollify is not a function
                at HTMLDocument.<anonymous> (http://localhost/sellgarrard/SellGarrard/wp-content/themes/SellGarrard301/JS/custom.js?ver=4.8.3:134:7)
                at j (https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js?ver=4.8.3:2:26911)
                at Object.add [as done] (https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js?ver=4.8.3:2:27220)
                at n.fn.init.n.fn.ready (https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js?ver=4.8.3:2:29326)
                at new n.fn.init (https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js?ver=4.8.3:2:24411)
                at n (https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js?ver=4.8.3:2:405)
                at HTMLDocument.<anonymous> (http://localhost/sellgarrard/SellGarrard/wp-content/themes/SellGarrard301/JS/custom.js?ver=4.8.3:133:1)
                at mightThrow (http://localhost/sellgarrard/SellGarrard/wp-content/themes/SellGarrard301/JS/jquery-3.2.1.js?ver=4.8.3:3583:29)
                at process (http://localhost/sellgarrard/SellGarrard/wp-content/themes/SellGarrard301/JS/jquery-3.2.1.js?ver=4.8.3:3651:12) undefined
            jQuery.Deferred.exceptionHook @ jquery-3.2.1.js?ver=4.8.3:3860
            process @ jquery-3.2.1.js?ver=4.8.3:3655
            setTimeout (async)
            (anonymous) @ jquery-3.2.1.js?ver=4.8.3:3689
            fire @ jquery-3.2.1.js?ver=4.8.3:3317
            fireWith @ jquery-3.2.1.js?ver=4.8.3:3447
            fire @ jquery-3.2.1.js?ver=4.8.3:3455
            fire @ jquery-3.2.1.js?ver=4.8.3:3317
            fireWith @ jquery-3.2.1.js?ver=4.8.3:3447
            ready @ jquery-3.2.1.js?ver=4.8.3:3920
            completed @ jquery-3.2.1.js?ver=4.8.3:3930
            jquery-3.2.1.js?ver=4.8.3:3869 Uncaught TypeError: $.scrollify is not a function
                at HTMLDocument.<anonymous> (custom.js?ver=4.8.3:134)
                at j (jquery.js:3094)
                at Object.add [as done] (jquery.js:3140)
                at n.fn.init.n.fn.ready (jquery.js:3373)
                at new n.fn.init (jquery.js:2816)
                at n (jquery.js:76)
                at HTMLDocument.<anonymous> (custom.js?ver=4.8.3:133)
                at mightThrow (jquery-3.2.1.js?ver=4.8.3:3583)
                at process (jquery-3.2.1.js?ver=4.8.3:3651)
            (anonymous) @ custom.js?ver=4.8.3:134
            j @ jquery.js:3094
            add @ jquery.js:3140
            n.fn.ready @ jquery.js:3373
            n.fn.init @ jquery.js:2816
            n @ jquery.js:76
            (anonymous) @ custom.js?ver=4.8.3:133
            mightThrow @ jquery-3.2.1.js?ver=4.8.3:3583
            process @ jquery-3.2.1.js?ver=4.8.3:3651
            setTimeout (async)
            jQuery.readyException @ jquery-3.2.1.js?ver=4.8.3:3868
            (anonymous) @ jquery-3.2.1.js?ver=4.8.3:3888
            mightThrow @ jquery-3.2.1.js?ver=4.8.3:3583
            process @ jquery-3.2.1.js?ver=4.8.3:3651
            setTimeout (async)
            (anonymous) @ jquery-3.2.1.js?ver=4.8.3:3689
            fire @ jquery-3.2.1.js?ver=4.8.3:3317
            fireWith @ jquery-3.2.1.js?ver=4.8.3:3447
            fire @ jquery-3.2.1.js?ver=4.8.3:3455
            fire @ jquery-3.2.1.js?ver=4.8.3:3317
            fireWith @ jquery-3.2.1.js?ver=4.8.3:3447
            process @ jquery-3.2.1.js?ver=4.8.3:3671
            setTimeout (async)
            (anonymous) @ jquery-3.2.1.js?ver=4.8.3:3689
            fire @ jquery-3.2.1.js?ver=4.8.3:3317
            fireWith @ jquery-3.2.1.js?ver=4.8.3:3447
            fire @ jquery-3.2.1.js?ver=4.8.3:3455
            fire @ jquery-3.2.1.js?ver=4.8.3:3317
            fireWith @ jquery-3.2.1.js?ver=4.8.3:3447
            ready @ jquery-3.2.1.js?ver=4.8.3:3920
            completed @ jquery-3.2.1.js?ver=4.8.3:3930
</code>```

答:
header.php

remove

```<code><script src="https://cdn.jsdelivr.net/npm/jquery-scrollify@1.0.17/jquery.scrollify.js"></script>

<script src="https://cdn.jsdelivr.net/npm/jquery-scrollify@1.0.17/jquery.scrollify.min.js"></script>
</code>```

Open footer.php

find

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

Add this directly above like so

```<code><script src="https://cdn.jsdelivr.net/npm/jquery-scrollify@1.0.17/jquery.scrollify.min.js"></script>
</body>
</code>```

Your problem is as I suggested, jQuery needs to load in on the page first, then load in scrollify. Making scrollify the very last thing to load in should resolve the issue. If not, then you need to do it the proper WP way by enqueing the script.

Title: Cant get scrollify.js to work?

Body:
I am trying to use scrollify.js on my single page website but cannot get it to work?

I have the following html, header.php for loading scrollify and my js in my custom.js file.

What am I doing wrong?

Thanks in advance?

HTML

        <?php get_header(); ?>

                        Sell your old
Garrard

                        Looking to sell your turntable? We buy your used Garrard 301 & 401 record players.

                    <?php echo do_shortcode('[contact-form-7 id="66" title="Contact Us"]'); ?>

                        Sell your old turntable

                        Sell your old turntable

        <?php get_footer(); ?>

Header PHP

 <!DOCTYPE html>

                <meta http-equiv="Content-Type" content="text/html"; charset="utf-8">
                <meta name="viewport" content="width-device-width">
                <meta name="apple-mobile-web-app-capable" content="yes">
                <meta name="apple-mobile-web-app-status-bar-style" content="black">
                <meta name="description" content="<?php bloginfo('description'); ?>">
                <title>SellGarrard301</title>

                <?php wp_head(); ?>

Sell Garrard.com

                                    <?php
                                                wp_nav_menu( array(
                                                    'theme_location' => 'header_menu',
                                                    'container'      => '',
                                                    'container_class' => 'menu-hidden',
                                                    'menu_class'     => 'menu-hide',
                                                    'menu_id'     => 'header_menu',
                                                    ) );
                                            ?>

Custom JS function

 $(document).ready(function(){

 $(function() {
      $.scrollify({
      section: ".section",

      });
 });

 });

All files and scripts are loaded when I check but I cannot find any information on how to get it to work?

UPDATED CONSOLE ERRORS:

                jquery.scrollify.js:45 Uncaught ReferenceError: jQuery is not defined
                at jquery.scrollify.js:45
                at jquery.scrollify.js:47
            (anonymous) @ jquery.scrollify.js:45
            (anonymous) @ jquery.scrollify.js:47
            jquery.scrollify.min.js:1 Uncaught ReferenceError: jQuery is not defined
                at jquery.scrollify.min.js:1
                at jquery.scrollify.min.js:1
            (anonymous) @ jquery.scrollify.min.js:1
            (anonymous) @ jquery.scrollify.min.js:1
            jquery-migrate.min.js?ver=1.4.1:2 JQMIGRATE: Migrate is installed, version 1.4.1
            jquery-3.2.1.js?ver=4.8.3:3860 jQuery.Deferred exception: $.scrollify is not a function TypeError: $.scrollify is not a function
                at HTMLDocument.<anonymous> (http://localhost/sellgarrard/SellGarrard/wp-content/themes/SellGarrard301/JS/custom.js?ver=4.8.3:134:7)
                at j (https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js?ver=4.8.3:2:26911)
                at Object.add [as done] (https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js?ver=4.8.3:2:27220)
                at n.fn.init.n.fn.ready (https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js?ver=4.8.3:2:29326)
                at new n.fn.init (https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js?ver=4.8.3:2:24411)
                at n (https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js?ver=4.8.3:2:405)
                at HTMLDocument.<anonymous> (http://localhost/sellgarrard/SellGarrard/wp-content/themes/SellGarrard301/JS/custom.js?ver=4.8.3:133:1)
                at mightThrow (http://localhost/sellgarrard/SellGarrard/wp-content/themes/SellGarrard301/JS/jquery-3.2.1.js?ver=4.8.3:3583:29)
                at process (http://localhost/sellgarrard/SellGarrard/wp-content/themes/SellGarrard301/JS/jquery-3.2.1.js?ver=4.8.3:3651:12) undefined
            jQuery.Deferred.exceptionHook @ jquery-3.2.1.js?ver=4.8.3:3860
            process @ jquery-3.2.1.js?ver=4.8.3:3655
            setTimeout (async)
            (anonymous) @ jquery-3.2.1.js?ver=4.8.3:3689
            fire @ jquery-3.2.1.js?ver=4.8.3:3317
            fireWith @ jquery-3.2.1.js?ver=4.8.3:3447
            fire @ jquery-3.2.1.js?ver=4.8.3:3455
            fire @ jquery-3.2.1.js?ver=4.8.3:3317
            fireWith @ jquery-3.2.1.js?ver=4.8.3:3447
            ready @ jquery-3.2.1.js?ver=4.8.3:3920
            completed @ jquery-3.2.1.js?ver=4.8.3:3930
            jquery-3.2.1.js?ver=4.8.3:3869 Uncaught TypeError: $.scrollify is not a function
                at HTMLDocument.<anonymous> (custom.js?ver=4.8.3:134)
                at j (jquery.js:3094)
                at Object.add [as done] (jquery.js:3140)
                at n.fn.init.n.fn.ready (jquery.js:3373)
                at new n.fn.init (jquery.js:2816)
                at n (jquery.js:76)
                at HTMLDocument.<anonymous> (custom.js?ver=4.8.3:133)
                at mightThrow (jquery-3.2.1.js?ver=4.8.3:3583)
                at process (jquery-3.2.1.js?ver=4.8.3:3651)
            (anonymous) @ custom.js?ver=4.8.3:134
            j @ jquery.js:3094
            add @ jquery.js:3140
            n.fn.ready @ jquery.js:3373
            n.fn.init @ jquery.js:2816
            n @ jquery.js:76
            (anonymous) @ custom.js?ver=4.8.3:133
            mightThrow @ jquery-3.2.1.js?ver=4.8.3:3583
            process @ jquery-3.2.1.js?ver=4.8.3:3651
            setTimeout (async)
            jQuery.readyException @ jquery-3.2.1.js?ver=4.8.3:3868
            (anonymous) @ jquery-3.2.1.js?ver=4.8.3:3888
            mightThrow @ jquery-3.2.1.js?ver=4.8.3:3583
            process @ jquery-3.2.1.js?ver=4.8.3:3651
            setTimeout (async)
            (anonymous) @ jquery-3.2.1.js?ver=4.8.3:3689
            fire @ jquery-3.2.1.js?ver=4.8.3:3317
            fireWith @ jquery-3.2.1.js?ver=4.8.3:3447
            fire @ jquery-3.2.1.js?ver=4.8.3:3455
            fire @ jquery-3.2.1.js?ver=4.8.3:3317
            fireWith @ jquery-3.2.1.js?ver=4.8.3:3447
            process @ jquery-3.2.1.js?ver=4.8.3:3671
            setTimeout (async)
            (anonymous) @ jquery-3.2.1.js?ver=4.8.3:3689
            fire @ jquery-3.2.1.js?ver=4.8.3:3317
            fireWith @ jquery-3.2.1.js?ver=4.8.3:3447
            fire @ jquery-3.2.1.js?ver=4.8.3:3455
            fire @ jquery-3.2.1.js?ver=4.8.3:3317
            fireWith @ jquery-3.2.1.js?ver=4.8.3:3447
            ready @ jquery-3.2.1.js?ver=4.8.3:3920
            completed @ jquery-3.2.1.js?ver=4.8.3:3930

Body:
header.php

remove

<script src="https://cdn.jsdelivr.net/npm/jquery-scrollify@1.0.17/jquery.scrollify.js"></script>

<script src="https://cdn.jsdelivr.net/npm/jquery-scrollify@1.0.17/jquery.scrollify.min.js"></script>

Open footer.php

find

</body>

Add this directly above like so

<script src="https://cdn.jsdelivr.net/npm/jquery-scrollify@1.0.17/jquery.scrollify.min.js"></script>
</body>

Your problem is as I suggested, jQuery needs to load in on the page first, then load in scrollify. Making scrollify the very last thing to load in should resolve the issue. If not, then you need to do it the proper WP way by enqueing the script.


问:
Difference Between setEntityMethod and SetRequestEntityMethod
I am writing a Java Application and I am sending my CSV file(2000 records) as a request Body. I came across two methods of two different Classes. setEntity(HttpPost Class) and setRequestEntity(PostMethod Class). Can anybody explain both its working? Which method is better to send the request body?

答:
The answer is very simple.

Commons HttpClient (legacy)

Commons HttpClient 3.x codeline is at the end of life(which uses postMethod.setRequestEntity(requestEntity);).

All users of Commons HttpClient 3.x are strongly encouraged to upgrade to HttpClient 4.1 (postMethod.setEntity(requestEntity);).

Reference:

Apache HTTP


问:
kivy/python : bind event when node is selected in treeview

test.py

```<code>from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.popup import Popup
from kivy.uix.treeview import TreeView, TreeViewLabel, TreeViewNode
from kivy.uix.label import Label
from kivy.properties import ObjectProperty

Window.size = (700, 530)

def populate_tree_view(tree_view, parent, node):
    if parent is None:
        tree_node = tree_view.add_node(TreeViewLabel(text=node['node_id'],
                                                     is_open=True))
    else:
        tree_node = tree_view.add_node(TreeViewLabel(text=node['node_id'],
                                                     is_open=True), parent)

    for child_node in node['children']:
        populate_tree_view(tree_view, tree_node, child_node)

tree = []
rows = [(1, 'test1', 11), (2, 'test2', 2), (3, 'test3', 3), (4, 'test4', 4), (5, 'test5', 1)]
for r in rows:
    tree.append({'node_id': r[1], 'children': []})

class TreeViewLabel(Label, TreeViewNode):
    pass

class TreeviewGroup(Popup):
    treeview = ObjectProperty(None)
    tv = ObjectProperty(None)
    #ti = ObjectProperty()

    def __init__(self, **kwargs):
        super(TreeviewGroup, self).__init__(**kwargs)
        self.tv = TreeView(root_options=dict(text=""),
                       hide_root=False,
                       indent_level=4)
        for branch in tree:
            populate_tree_view(self.tv, None, branch)
        self.remove_widgets()
        self.treeview.add_widget(self.tv)

    def remove_widgets(self):
        for child in [child for child in self.treeview.children]:
            self.treeview.remove_widget(child)

    def select_node(self, node):
        '''Select a node in the tree.
                '''
        if node.no_selection:
            return
        if self._selected_node:
            self._selected_node.is_selected = False
        node.is_selected = True
        self._selected_node = node
        print(node)

class GroupScreen(Screen):
    groupName = ObjectProperty(None)
    popup = ObjectProperty(None)

    def display_groups(self, instance):
        if len(instance.text) > 0:
            if self.popup is None:
                self.popup = TreeviewGroup()
            #self.popup.filter(instance.text)
            self.popup.open()

    def select_node(self, node):
        '''Select a node in the tree.
                '''
        if node.no_selection:
            return
        if self._selected_node:
            self._selected_node.is_selected = False
        node.is_selected = True
        self._selected_node = node
        print(node)

class Group(App):

    #rows = [(1, 'test1', 111), (2, 'test2', 112), (3, 'test3', 113), (4, 'test4', 114)]
    def build(self):
        self.root = Builder.load_file('test.kv')
        return self.root

if __name__ == '__main__':
    Group().run()
</code>```

test.kv

```<code>#:kivy 1.10.0

<TreeViewLabel>:
    on_touch_down:
        app.root.stateName.text = self.text
        app.root.popup.dismiss()

<TreeviewGroup>:
    id: treeview
    treeview: treeview
    title: "Select City"
    size_hint: None, None
    size: 400, 400
    auto_dismiss: False

    BoxLayout
        orientation: "vertical"
        #TextInput:
            #id: ti
            #size_hint_y: .1
            #on_text: root.filter(self.text)
        BoxLayout:
            id: treeview
            #on_press: root.select_node(self.text)
        Button:
            size_hint: 1, 0.1
            text: "Close"
            on_release: root.dismiss()

<CustomLabel@Label>:
    text_size: self.size
    valign: "middle"
    padding_x: 5

<SingleLineTextInput@TextInput>:
    multiline: False

<GreenButton@Button>:
    background_color: 1, 1, 1, 1
    size_hint_y: None
    height: self.parent.height * 0.150

GroupScreen:
    stateName: stateName

    GridLayout:
        cols: 2
        padding : 30,30
        spacing: 10, 10
        row_default_height: '40dp'

        CustomLabel:
            text: 'Name'

        SingleLineTextInput:
            id: stateName
            on_text: root.display_groups(self)

        CustomLabel:
            text: 'Code'

        CustomLabel:
            text: '08'

        GreenButton:
            text: 'Ok'
            #on_press: root.insert_data(stateName.text, cityName.text, shortName.text , pinCode.text)

        GreenButton:
            text: 'Cancel'
            on_press: app.stop()

        Label:

        Label:
</code>```

When i type anything in state name then a pop up open with treeview structure.

I want that when click on any node then it retrieve state code from database.And put value front of state code.at this time '08' is static value.database query is no issue for me but i dont know how to pass in a .py file after it put value in front of state code.And pop up should be close.

答:
You can do this by adding a string property attribute to the Groupscreen class which will represent the statecode, then edit the select_node method to trigger the changes

```<code>...
from kivy.properties import ObjectProperty, StringProperty

...

class GroupScreen(Screen):
    groupName = ObjectProperty(None)
    popup = ObjectProperty(None)
    statecode = StringProperty('08')

...

    def select_node(self, node):
        '''Select a node in the tree.
            '''
        for r in rows:
            if node.text == r[1]:
                self.statecode = str(r[2])
                break
</code>```

then in the kv:

```<code><TreeViewLabel>:
    on_touch_down:
        app.root.stateName.text = self.text
        app.root.select_node(self)
        app.root.popup.dismiss()

...

GroupScreen:
    stateName: stateName

    GridLayout:
        cols: 2
        padding : 30,30
        spacing: 10, 10
        row_default_height: '40dp'

        CustomLabel:
            text: 'State Name'

        SingleLineTextInput:
            id: stateName
            on_text: root.display_groups(self)

        CustomLabel:
            text: 'State Code'

        CustomLabel:
            text: root.statecode

...
</code>```

Body:
test.py

from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.popup import Popup
from kivy.uix.treeview import TreeView, TreeViewLabel, TreeViewNode
from kivy.uix.label import Label
from kivy.properties import ObjectProperty

Window.size = (700, 530)

def populate_tree_view(tree_view, parent, node):
    if parent is None:
        tree_node = tree_view.add_node(TreeViewLabel(text=node['node_id'],
                                                     is_open=True))
    else:
        tree_node = tree_view.add_node(TreeViewLabel(text=node['node_id'],
                                                     is_open=True), parent)

    for child_node in node['children']:
        populate_tree_view(tree_view, tree_node, child_node)

tree = []
rows = [(1, 'test1', 11), (2, 'test2', 2), (3, 'test3', 3), (4, 'test4', 4), (5, 'test5', 1)]
for r in rows:
    tree.append({'node_id': r[1], 'children': []})

class TreeViewLabel(Label, TreeViewNode):
    pass

class TreeviewGroup(Popup):
    treeview = ObjectProperty(None)
    tv = ObjectProperty(None)
    #ti = ObjectProperty()

    def __init__(self, **kwargs):
        super(TreeviewGroup, self).__init__(**kwargs)
        self.tv = TreeView(root_options=dict(text=""),
                       hide_root=False,
                       indent_level=4)
        for branch in tree:
            populate_tree_view(self.tv, None, branch)
        self.remove_widgets()
        self.treeview.add_widget(self.tv)

    def remove_widgets(self):
        for child in [child for child in self.treeview.children]:
            self.treeview.remove_widget(child)

    def select_node(self, node):
        '''Select a node in the tree.
                '''
        if node.no_selection:
            return
        if self._selected_node:
            self._selected_node.is_selected = False
        node.is_selected = True
        self._selected_node = node
        print(node)

class GroupScreen(Screen):
    groupName = ObjectProperty(None)
    popup = ObjectProperty(None)

    def display_groups(self, instance):
        if len(instance.text) > 0:
            if self.popup is None:
                self.popup = TreeviewGroup()
            #self.popup.filter(instance.text)
            self.popup.open()

    def select_node(self, node):
        '''Select a node in the tree.
                '''
        if node.no_selection:
            return
        if self._selected_node:
            self._selected_node.is_selected = False
        node.is_selected = True
        self._selected_node = node
        print(node)

class Group(App):

    #rows = [(1, 'test1', 111), (2, 'test2', 112), (3, 'test3', 113), (4, 'test4', 114)]
    def build(self):
        self.root = Builder.load_file('test.kv')
        return self.root

if __name__ == '__main__':
    Group().run()

test.kv

#:kivy 1.10.0

<TreeViewLabel>:
    on_touch_down:
        app.root.stateName.text = self.text
        app.root.popup.dismiss()

<TreeviewGroup>:
    id: treeview
    treeview: treeview
    title: "Select City"
    size_hint: None, None
    size: 400, 400
    auto_dismiss: False

    BoxLayout
        orientation: "vertical"
        #TextInput:
            #id: ti
            #size_hint_y: .1
            #on_text: root.filter(self.text)
        BoxLayout:
            id: treeview
            #on_press: root.select_node(self.text)
        Button:
            size_hint: 1, 0.1
            text: "Close"
            on_release: root.dismiss()

<CustomLabel@Label>:
    text_size: self.size
    valign: "middle"
    padding_x: 5

<SingleLineTextInput@TextInput>:
    multiline: False

<GreenButton@Button>:
    background_color: 1, 1, 1, 1
    size_hint_y: None
    height: self.parent.height * 0.150

GroupScreen:
    stateName: stateName

    GridLayout:
        cols: 2
        padding : 30,30
        spacing: 10, 10
        row_default_height: '40dp'

        CustomLabel:
            text: 'Name'

        SingleLineTextInput:
            id: stateName
            on_text: root.display_groups(self)

        CustomLabel:
            text: 'Code'

        CustomLabel:
            text: '08'

        GreenButton:
            text: 'Ok'
            #on_press: root.insert_data(stateName.text, cityName.text, shortName.text , pinCode.text)

        GreenButton:
            text: 'Cancel'
            on_press: app.stop()

        Label:

        Label:

When i type anything in state name then a pop up open with treeview structure.

I want that when click on any node then it retrieve state code from database.And put value front of state code.at this time '08' is static value.database query is no issue for me but i dont know how to pass in a .py file after it put value in front of state code.And pop up should be close.

Body:
You can do this by adding a string property attribute to the Groupscreen class which will represent the statecode, then edit the select_node method to trigger the changes

...
from kivy.properties import ObjectProperty, StringProperty

...

class GroupScreen(Screen):
    groupName = ObjectProperty(None)
    popup = ObjectProperty(None)
    statecode = StringProperty('08')

...

    def select_node(self, node):
        '''Select a node in the tree.
            '''
        for r in rows:
            if node.text == r[1]:
                self.statecode = str(r[2])
                break

then in the kv:

<TreeViewLabel>:
    on_touch_down:
        app.root.stateName.text = self.text
        app.root.select_node(self)
        app.root.popup.dismiss()

...

GroupScreen:
    stateName: stateName

    GridLayout:
        cols: 2
        padding : 30,30
        spacing: 10, 10
        row_default_height: '40dp'

        CustomLabel:
            text: 'State Name'

        SingleLineTextInput:
            id: stateName
            on_text: root.display_groups(self)

        CustomLabel:
            text: 'State Code'

        CustomLabel:
            text: root.statecode

...


问:
How do I add a border header of a link on my navigation bar while removing the div's border?
This is what it looks like at the moment:
I want to remove the gray border under the 'active' class element (i.e. the Home in this picture), while having the orange thicker bottom-border replace it. How do I go about doing that?

* {
    font-family: 'Asap', sans-serif;
    margin: 0;
}

div.header {
    background-color: rgba(0, 0, 0, 0.1);
    position: absolute;
    width: 100%;
    border-bottom: solid rgba(0, 0, 0, 0.1) 2px;
}

div.header a.text {
    text-decoration: none;
    color: gray;
    padding: 20px;
    text-transform: capitalize;
    float: left;
    transition: 0.1s;
}

div.header a.text:hover {
    color: rgba(0, 0, 0, 0.7);
    background-color: rgba(0, 0, 0, 0.1);
}

div.header a.text.active {
    color: #ff5e00;
    border-bottom: solid #ff5e00;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE>
<html>
    <head>
        <title>Ant Arni's Crappy Site!</title>
        <link href="css/main.css" type="text/css" rel=stylesheet>
        <link href="https://fonts.googleapis.com/css?family=Asap" rel="stylesheet">
    </head>
    <body>
        <div class=header>
            Home
            Members
            Handbook
            Apply
            Staff
        </div>
    </body>
</html></code>```

答:
You can use after and remove border-bottom from .active class

```<code>div.header a.text.active {
    position: relative;
}

div.header a.text.active::after {
    position: absolute;
    bottom: -2px;
    content: '';
    left: 0;
    right: 0;
    height: 3px;
    background-color: #ff5e00;
    z-index: 2;
}
</code>```

Body:
This is what it looks like at the moment:
I want to remove the gray border under the 'active' class element (i.e. the Home in this picture), while having the orange thicker bottom-border replace it. How do I go about doing that?

* {
    font-family: 'Asap', sans-serif;
    margin: 0;
}

div.header {
    background-color: rgba(0, 0, 0, 0.1);
    position: absolute;
    width: 100%;
    border-bottom: solid rgba(0, 0, 0, 0.1) 2px;
}

div.header a.text {
    text-decoration: none;
    color: gray;
    padding: 20px;
    text-transform: capitalize;
    float: left;
    transition: 0.1s;
}

div.header a.text:hover {
    color: rgba(0, 0, 0, 0.7);
    background-color: rgba(0, 0, 0, 0.1);
}

div.header a.text.active {
    color: #ff5e00;
    border-bottom: solid #ff5e00;

<!DOCTYPE>

        <title>Ant Arni's Crappy Site!</title>
        <link href="css/main.css" type="text/css" rel=stylesheet>
        <link href="https://fonts.googleapis.com/css?family=Asap" rel="stylesheet">

            Home
            Members
            Handbook
            Apply
            Staff

Body:
You can use after and remove border-bottom from .active class

div.header a.text.active {
    position: relative;
}

div.header a.text.active::after {
    position: absolute;
    bottom: -2px;
    content: '';
    left: 0;
    right: 0;
    height: 3px;
    background-color: #ff5e00;
    z-index: 2;
}


问:
How to send a notification to another PC?
Is there a way i can send a notification/message to another PC in C/C++? I think something like net send, but i don't know if there is another way to send a notification/message. I created an application which will run on every PC, and i want, that if my application has finished it should send a notification to my PC, that it has finished running. I don't know if there is a solution for my question, but if yes, could someone tell me, how to do that?

Thanks,

kampi

答: If you can't use net send, how about just creating a date-stamped temp file of some sort that your other PC looks for?</p>