问:
How do I create objects with a different number of arguments?
my question is what if I want to create an object that represents a person in a contact list.
The user has to enter a last name, if not, the program won't work.
Besides that the user can enter the first name, the address, phone number and so on, but these aren't necessary.
So how do I tackle these?
I could create a huge amount of constructors with the different parameter combinations, but I don't think that is the right solution.

Can you guys help me out?

答:
What you don't want to try is telescoping constructor pattern? This is easy to implement if you have lesser no of fields(thus lesser constructor required)
In terms of good design, you can consider following:
Builder Design pattern

```<code>public class Computer {

    //required parameters
    private String HDD;
    private String RAM;

    //optional parameters
    private boolean isGraphicsCardEnabled;
    private boolean isBluetoothEnabled;

    public String getHDD() {
        return HDD;
    }

    public String getRAM() {
        return RAM;
    }

    public boolean isGraphicsCardEnabled() {
        return isGraphicsCardEnabled;
    }

    public boolean isBluetoothEnabled() {
        return isBluetoothEnabled;
    }

    private Computer(ComputerBuilder builder) {
        this.HDD=builder.HDD;
        this.RAM=builder.RAM;
        this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled;
        this.isBluetoothEnabled=builder.isBluetoothEnabled;
    }

    //Builder Class
    public static class ComputerBuilder{

        // required parameters
        private String HDD;
        private String RAM;

        // optional parameters
        private boolean isGraphicsCardEnabled;
        private boolean isBluetoothEnabled;

        public ComputerBuilder(String hdd, String ram){
            this.HDD=hdd;
            this.RAM=ram;
        }

        public ComputerBuilder setGraphicsCardEnabled(boolean isGraphicsCardEnabled) {
            this.isGraphicsCardEnabled = isGraphicsCardEnabled;
            return this;
        }

        public ComputerBuilder setBluetoothEnabled(boolean isBluetoothEnabled) {
            this.isBluetoothEnabled = isBluetoothEnabled;
            return this;
        }

        public Computer build(){
            return new Computer(this);
        }

    }

}
</code>```

Body:
What you don't want to try is telescoping constructor pattern? This is easy to implement if you have lesser no of fields(thus lesser constructor required)
In terms of good design, you can consider following:
Builder Design pattern

public class Computer {

    //required parameters
    private String HDD;
    private String RAM;

    //optional parameters
    private boolean isGraphicsCardEnabled;
    private boolean isBluetoothEnabled;

    public String getHDD() {
        return HDD;
    }

    public String getRAM() {
        return RAM;
    }

    public boolean isGraphicsCardEnabled() {
        return isGraphicsCardEnabled;
    }

    public boolean isBluetoothEnabled() {
        return isBluetoothEnabled;
    }

    private Computer(ComputerBuilder builder) {
        this.HDD=builder.HDD;
        this.RAM=builder.RAM;
        this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled;
        this.isBluetoothEnabled=builder.isBluetoothEnabled;
    }

    //Builder Class
    public static class ComputerBuilder{

        // required parameters
        private String HDD;
        private String RAM;

        // optional parameters
        private boolean isGraphicsCardEnabled;
        private boolean isBluetoothEnabled;

        public ComputerBuilder(String hdd, String ram){
            this.HDD=hdd;
            this.RAM=ram;
        }

        public ComputerBuilder setGraphicsCardEnabled(boolean isGraphicsCardEnabled) {
            this.isGraphicsCardEnabled = isGraphicsCardEnabled;
            return this;
        }

        public ComputerBuilder setBluetoothEnabled(boolean isBluetoothEnabled) {
            this.isBluetoothEnabled = isBluetoothEnabled;
            return this;
        }

        public Computer build(){
            return new Computer(this);
        }

    }

}


来源: stackexchange

问:
How to configure CORS in a Spring Boot + Spring Security application?
I use Spring Boot with Spring Security and Cors Support.

If I execute following code

```<code>url = 'http://localhost:5000/api/token'
xmlhttp = new XMLHttpRequest
xmlhttp.onreadystatechange = ->
    if xmlhttp.readyState is 4
        console.log xmlhttp.status
xmlhttp.open "GET", url, true
# xmlhttp.setRequestHeader "X-Requested-With", "XMLHttpRequest"
xmlhttp.setRequestHeader 'Authorization', 'Basic ' + btoa 'a:a'
do xmlhttp.send
</code>```

I get as a result

```<code>200
</code>```

If I test with wrong credentials like

```<code>url = 'http://localhost:5000/api/token'
xmlhttp = new XMLHttpRequest
xmlhttp.onreadystatechange = ->
    if xmlhttp.readyState is 4
        console.log xmlhttp.status
xmlhttp.open "GET", url, true
# xmlhttp.setRequestHeader "X-Requested-With", "XMLHttpRequest"
xmlhttp.setRequestHeader 'Authorization', 'Basic ' + btoa 'a:aa'
do xmlhttp.send
</code>```

instead of getting 401 (that is the standard code for wrong authentication in spring security) I get

```<code>0
</code>```

with following browser notification:

GET http://localhost:5000/api/token

XMLHttpRequest cannot load http://localhost:5000. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.

I'm developing front-end code that needs useful http status codes from server responses to handle the situation. I need something more useful than 0. Also the response body is empty. I dont know if my config is wrong, or it's a software bug and I also don't know where, if it's chromium (using arch linux) or spring security.

My Spring Config is:

```<code>@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@RestController
@RequestMapping("api")
public class Controller {
    @RequestMapping("token")
    @CrossOrigin
    Map<String, String> token(HttpSession session) {
        return Collections.singletonMap("token", session.getId());
    }
}

@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("a").password("a").roles("USER");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .anyRequest().authenticated()
                .and().httpBasic();
    }
}
</code>```

If I test with curl everything works perfect, I think because no CORS support needed, but I tried to simulate the CORS with OPTION requests and the result was also ok.

```<code>$ curl -v localhost:5000/api/token -H "Authorization: Basic YTpha"
*   Trying ::1...
* Connected to localhost (::1) port 5000 (#0)
> GET /api/token HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.48.0
> Accept: */*
> Authorization: Basic YTpha
>
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< 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
< Access-Control-Allow-Origin: http://localhost:3000
< Access-Control-Allow-Methods: POST,GET,OPTIONS,DELETE
< Access-Control-Max-Age: 3600
< Access-Control-Allow-Credentials: true
< Access-Control-Allow-Headers: Origin,Accept,X-Requested-    With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization
< x-auth-token: 58e4cca9-7719-46c8-9180-2fc16aec8dff
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Sun, 01 May 2016 16:15:44 GMT
<
* Connection #0 to host localhost left intact
{"token":"58e4cca9-7719-46c8-9180-2fc16aec8dff"}
</code>```

and with wrong credentials:

```<code>$ curl -v localhost:5000/api/token -H "Authorization: Basic YTp"
*   Trying ::1...
* Connected to localhost (::1) port 5000 (#0)
> GET /api/token HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.48.0
> Accept: */*
> Authorization: Basic YTp
>
< HTTP/1.1 401 Unauthorized
< Server: Apache-Coyote/1.1
< 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
< WWW-Authenticate: Basic realm="Realm"
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Sun, 01 May 2016 16:16:15 GMT
<
* Connection #0 to host localhost left intact
{"timestamp":1462119375041,"status":401,"error":"Unauthorized","message":"Failed to decode basic authentication token","path":"/api/token"}
</code>```

Edit:
To avoid misunderstandings. I use 1.3.3 Spring Boot.
The Blog post writes:

CORS support will be available in the upcoming Spring Boot 1.3 release, and is already available in the 1.3.0.BUILD-SNAPSHOT builds.

Using controller method CORS configuration with @CrossOrigin annotations in your Spring Boot application does not require any specific configuration.

Global CORS configuration can be defined by registering a WebMvcConfigurer bean with a customized addCorsMappings(CorsRegistry) method:

I have added following code to enable global cors support. actually I have tried this before but it the result was the same. I tried it again recently and the result is the same.

```<code>@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}
</code>```

The idea, that the problem comes from a redirect between the authorization process is an interesting though. how can i change the redirect to any resources to avoid this conflict?

EDIT:

I guess I am closer to a solution. I have tested with my nodejs server that supports cors without problems by adding
Access-Control-Allow-Origin: *
to all requests.

Like Stefan Isele has already mentioned it seems that spring security redirects or doesn't add the CORS header so that's why the request seems to be broken. So while spring security is checking the authentification it has to add the proper header.

Does anyone know how to do so?

EDIT:

I found a workaround, that seems to be ugly. I have started a github issue for spring boot where I describe the workaround: https://github.com/spring-projects/spring-boot/issues/5834

答:
Found an easy solution for Spring-Boot, Spring-Security and Java-based config:</p>

```<code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.cors().configurationSource(new CorsConfigurationSource() {
            @Override
            public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
                return new CorsConfiguration().applyPermitDefaultValues();
            }
        });
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use Spring Boot with Spring Security and Cors Support.

If I execute following code

url = 'http://localhost:5000/api/token'
xmlhttp = new XMLHttpRequest
xmlhttp.onreadystatechange = ->
    if xmlhttp.readyState is 4
        console.log xmlhttp.status
xmlhttp.open "GET", url, true
# xmlhttp.setRequestHeader "X-Requested-With", "XMLHttpRequest"
xmlhttp.setRequestHeader 'Authorization', 'Basic ' + btoa 'a:a'
do xmlhttp.send

I get as a result

200

If I test with wrong credentials like

url = 'http://localhost:5000/api/token'
xmlhttp = new XMLHttpRequest
xmlhttp.onreadystatechange = ->
    if xmlhttp.readyState is 4
        console.log xmlhttp.status
xmlhttp.open "GET", url, true
# xmlhttp.setRequestHeader "X-Requested-With", "XMLHttpRequest"
xmlhttp.setRequestHeader 'Authorization', 'Basic ' + btoa 'a:aa'
do xmlhttp.send

instead of getting 401 (that is the standard code for wrong authentication in spring security) I get

0

with following browser notification:

GET http://localhost:5000/api/token

XMLHttpRequest cannot load http://localhost:5000. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.

I'm developing front-end code that needs useful http status codes from server responses to handle the situation. I need something more useful than 0. Also the response body is empty. I dont know if my config is wrong, or it's a software bug and I also don't know where, if it's chromium (using arch linux) or spring security.

My Spring Config is:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@RestController
@RequestMapping("api")
public class Controller {
    @RequestMapping("token")
    @CrossOrigin
    Map<String, String> token(HttpSession session) {
        return Collections.singletonMap("token", session.getId());
    }
}

@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("a").password("a").roles("USER");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .anyRequest().authenticated()
                .and().httpBasic();
    }
}

If I test with curl everything works perfect, I think because no CORS support needed, but I tried to simulate the CORS with OPTION requests and the result was also ok.

$ curl -v localhost:5000/api/token -H "Authorization: Basic YTpha"
*   Trying ::1...
* Connected to localhost (::1) port 5000 (#0)
> GET /api/token HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.48.0
> Accept: */*
> Authorization: Basic YTpha
>
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< 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
< Access-Control-Allow-Origin: http://localhost:3000
< Access-Control-Allow-Methods: POST,GET,OPTIONS,DELETE
< Access-Control-Max-Age: 3600
< Access-Control-Allow-Credentials: true
< Access-Control-Allow-Headers: Origin,Accept,X-Requested-    With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization
< x-auth-token: 58e4cca9-7719-46c8-9180-2fc16aec8dff
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Sun, 01 May 2016 16:15:44 GMT
<
* Connection #0 to host localhost left intact
{"token":"58e4cca9-7719-46c8-9180-2fc16aec8dff"}

and with wrong credentials:

$ curl -v localhost:5000/api/token -H "Authorization: Basic YTp"
*   Trying ::1...
* Connected to localhost (::1) port 5000 (#0)
> GET /api/token HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.48.0
> Accept: */*
> Authorization: Basic YTp
>
< HTTP/1.1 401 Unauthorized
< Server: Apache-Coyote/1.1
< 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
< WWW-Authenticate: Basic realm="Realm"
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Sun, 01 May 2016 16:16:15 GMT
<
* Connection #0 to host localhost left intact
{"timestamp":1462119375041,"status":401,"error":"Unauthorized","message":"Failed to decode basic authentication token","path":"/api/token"}

Edit:
To avoid misunderstandings. I use 1.3.3 Spring Boot.
The Blog post writes:

CORS support will be available in the upcoming Spring Boot 1.3 release, and is already available in the 1.3.0.BUILD-SNAPSHOT builds.

Using controller method CORS configuration with @CrossOrigin annotations in your Spring Boot application does not require any specific configuration.

Global CORS configuration can be defined by registering a WebMvcConfigurer bean with a customized addCorsMappings(CorsRegistry) method:

I have added following code to enable global cors support. actually I have tried this before but it the result was the same. I tried it again recently and the result is the same.

@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

The idea, that the problem comes from a redirect between the authorization process is an interesting though. how can i change the redirect to any resources to avoid this conflict?

EDIT:

I guess I am closer to a solution. I have tested with my nodejs server that supports cors without problems by adding
Access-Control-Allow-Origin: *
to all requests.

Like Stefan Isele has already mentioned it seems that spring security redirects or doesn't add the CORS header so that's why the request seems to be broken. So while spring security is checking the authentification it has to add the proper header.

Does anyone know how to do so?

EDIT:

I found a workaround, that seems to be ugly. I have started a github issue for spring boot where I describe the workaround: https://github.com/spring-projects/spring-boot/issues/5834

Body:
Found an easy solution for Spring-Boot, Spring-Security and Java-based config:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.cors().configurationSource(new CorsConfigurationSource() {
            @Override
            public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
                return new CorsConfiguration().applyPermitDefaultValues();
            }
        });
    }
}


问:
PHP - How to get all urls from many img's src?
Let's assume we have string like this:

```<code>Its really great to <img src="image2.png" /> hear from you "Today is good <img src="http://www.google.com/picture2.png" /> day" Let's listen song together! ---------<img src="images/profile.png" />\\\\\\
</code>```

This is the whole string. We have 3 img inside.

We want to produce variable from this string like

```<code>output[0] = 'image2.png';
output[1] = 'http://www.google.com/picture2.png';
output[2] = 'images/profile.png';
</code>```

I mean, we have this string, and how to process him to extract all "src" from img tags and collect it in one new array variable.

How to do it? How we can achieve that?

In addition I use CodeIgniter framework. Maybe it can be done with only this framework's method but I don't see it possible.

答:
Use preg_match_all ( string $pattern , string $subject [, array &$matches on the source of the whole page to pick out the src= values. Like this:

```<code>$src = array (); // array for src's
preg_match_all ( '/src="([^"]+)"/', $page_source, $src );
$just_urls = $src [1];
</code>```

Where $page_source is your input and $src is the resulting array of src= values, and $just_urls is an array of just the inside of the quotes.

The pattern /src="([^"]+)"/ will return only what's inside the quotes.

See:
https://secure.php.net/manual/en/function.preg-match-all.php

Body:
Let's assume we have string like this:

Its really great to  hear from you "Today is good  day" Let's listen song together! ---------\\\\\\

This is the whole string. We have 3 img inside.

We want to produce variable from this string like

output[0] = 'image2.png';
output[1] = 'http://www.google.com/picture2.png';
output[2] = 'images/profile.png';

I mean, we have this string, and how to process him to extract all "src" from img tags and collect it in one new array variable.

How to do it? How we can achieve that?

In addition I use CodeIgniter framework. Maybe it can be done with only this framework's method but I don't see it possible.

Body:
Use preg_match_all ( string $pattern , string $subject [, array &$matches on the source of the whole page to pick out the src= values. Like this:

$src = array (); // array for src's
preg_match_all ( '/src="([^"]+)"/', $page_source, $src );
$just_urls = $src [1];

Where $page_source is your input and $src is the resulting array of src= values, and $just_urls is an array of just the inside of the quotes.

The pattern /src="([^"]+)"/ will return only what's inside the quotes.

See:
https://secure.php.net/manual/en/function.preg-match-all.php


问:
MongoDb remove 2 data
I have a collection of technicians below. How to remove or pull data in both tasks and reservedDates in one command??</p>

```<code>db.technicians.find().pretty()
{
   "_id" : ObjectId("592acc916a32c48647427b2f"),
    "firstName" : "Pj",
    "lastName" : "Rizal",
    "tasks" : [
            ObjectId("593435177492fb214c3a8694"),
            ObjectId("5934389179439d2c20f07210"),
    ],
    "reservedDates" : [
            {
                    "date" : "2017-06-29T16:00:00.000Z",
                    "time" : "2017-06-04T07:14:16.130Z",
            },
            {
                    "date" : "2017-06-29T16:00:00.000Z",
                    "time" : "2017-06-04T07:14:16.130Z",
            },
    ]

}
</code>```

答:
```<code>db.technicians.update({},
    {$pull: {reservedDates: { date: '2017-06-29T16:00:00.000Z'}}},
    {multi: true}
</code>```

Title: MongoDb remove 2 data

Body:
I have a collection of technicians below. How to remove or pull data in both tasks and reservedDates in one command??

db.technicians.find().pretty()
{
   "_id" : ObjectId("592acc916a32c48647427b2f"),
    "firstName" : "Pj",
    "lastName" : "Rizal",
    "tasks" : [
            ObjectId("593435177492fb214c3a8694"),
            ObjectId("5934389179439d2c20f07210"),
    ],
    "reservedDates" : [
            {
                    "date" : "2017-06-29T16:00:00.000Z",
                    "time" : "2017-06-04T07:14:16.130Z",
            },
            {
                    "date" : "2017-06-29T16:00:00.000Z",
                    "time" : "2017-06-04T07:14:16.130Z",
            },
    ]

}


问:
Xcode Embedded navigation controller back-button not showing
I've just started learning Swift and Xcode, so I apologise in advance if my question is confusing or missing information. Please let me know if that's the case.

My question is on the automatic navigation bar created when I embed my scenes in the navigation controller.

As I've tried to show in my screenshot in the link below, my idea is to use the "Refusion" button in scene 1 to show scene 2. This works. However, scene 2 does not generate an automatic back button this way, which is what I'm trying to get.

If I create a button in scene 2 that shows scene 1 upon being pressed, scene 1 will now have an automatically generated back button. But this sends the user/me back from scene 1 to scene 2.. Which I already have my "Refusion" button for and also it just creates a confusing loop.

So, my question is: I'm trying to figure out how to get the auto-back button on my scene 2 and just scene 2, how do I do that? I'm probably doing something wrong, but would appreciate any help in where my error is.

I've embedded both scenes in the navigation controller.

Thanks,

https://ibb.co/jfZeSa

答:
You need to embed only scene 1 in navigation controller.

When you tap on Refusion button, push scene 2. Scene 2 then will be added in the navigation stack. In this case default back button will appear on the navigation bar.

In case you present scene 2 from scene 1, back button won't appear on the navigation bar. i.e. scene 2 won't be added in the navigation stack.

Back button on navigation bar only appear on the controllers that are the part of navigation stack.


问:
Can't find CSS rule that is declaring the width of
I am working on some HTML / CSS stuff and for some reason, I have a stray element that is overflowing my body and causing horizontal scroll bars.  Before you say it, I know this is a pretty n00b sounding mistake.  I typically don't have issues like this but I could really use a second set of eyes.

http://easterndancer.com.s66112.gridserver.com/

Can you find the element that's causing the scrolling overflow (horizontal)?

答: Using process of elimination (adding display: none to div's) it is the menu items in #menu-primary-navigation-1

ContentLicense: CC BY-SA 2.5

Title: Can't find CSS rule that is declaring the width of <body>


问:
Check if user is close to scrolling to bottom of element
My website has a Bootstrap modal. My end goal is to add infinite scrolling to the modal so that when the user scrolls down to the bottom of the modal, it loads more data from the server and appends the data to the modal.

Here is my code so far. All I have right now is a scroll event on the modal:

http://jsfiddle.net/DTcHh/33247/

Note: The height of the modal on my website can vary. Sometimes it can be just 1 paragraph of text.

My question is, how can I check if the user is close to scrolling to the bottom of the modal?

In more technical terms, how can I check if the bottom of the window is at the same position as the bottom of the modal?

Update

I found that this solution works, however, it seems a bit complicated/long. Any way to shorten it?

http://jsfiddle.net/DTcHh/33271/

HTML:

```<code><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
</code>```

JS:

```<code>$("#exampleModalLong").on("scroll", function() {
    console.log("scroll");
});
</code>```

答:
This answer is more of a throttled version of J.M. Echevarría's Answer (assuming the scrolling code is correct).  Sometimes issues arise that you can overwhelm the browser with events (either loading more content then desired and/or slowing down the browser which can give a user a negative experience of the website).</p>

```<code>$(document).scroll(function (){
  var timerId;
  if($(this).height() - $(this).scrollTop() - $(window).height() < 20){
    clearTimeout(timerId);
    timerId = setTimeout(function(){
      console.log('time to show new content');
      }, 250);
  }
});
</code>```

Body:
My website has a Bootstrap modal. My end goal is to add infinite scrolling to the modal so that when the user scrolls down to the bottom of the modal, it loads more data from the server and appends the data to the modal.

Here is my code so far. All I have right now is a scroll event on the modal:

http://jsfiddle.net/DTcHh/33247/

Note: The height of the modal on my website can vary. Sometimes it can be just 1 paragraph of text.

My question is, how can I check if the user is close to scrolling to the bottom of the modal?

In more technical terms, how can I check if the bottom of the window is at the same position as the bottom of the modal?

Update

I found that this solution works, however, it seems a bit complicated/long. Any way to shorten it?

http://jsfiddle.net/DTcHh/33271/

HTML:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong">
  Launch demo modal
</button>

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

JS:

$("#exampleModalLong").on("scroll", function() {
    console.log("scroll");
});

Body:
This answer is more of a throttled version of J.M. Echevarría's Answer (assuming the scrolling code is correct).  Sometimes issues arise that you can overwhelm the browser with events (either loading more content then desired and/or slowing down the browser which can give a user a negative experience of the website).

$(document).scroll(function (){
  var timerId;
  if($(this).height() - $(this).scrollTop() - $(window).height() < 20){
    clearTimeout(timerId);
    timerId = setTimeout(function(){
      console.log('time to show new content');
      }, 250);
  }
});


问:
How do I call a custom method from a button in a view to delete a file associated with an object? Rails app
I'm working on a rails app where users can post links with title, url and an uploaded image file. When displaying this link I want to have a delete picture button next to the image so that the user may click on it to delete the image.

I don't know which is the best way to do this, but here's what I did:-

Custom method in links_controller.rb:-

```<code>  def destroy_picture
    @link = current_user.links.find_by(id: params[:id])
    if @link.picture? && @link.user==current_user
      new_link = @link.dup
      new_link.picture=nil
      new_link.id = @link.id
      new_link.created_at = @link.created_at
      new_link.updated_at = Time.now
      @link.destroy
      new_link.save
      flash[:success]="Picture deleted successfully"
    end
  end
</code>```

Calling the custom method in the view:-

The complete files:-

link_controller.rb

```<code>class LinksController < ApplicationController
  before_action :logged_in_user, only: [:new, :create, :edit, :update, :destroy]
  before_action :link_owner, only: [:edit, :update, :destroy]

  def new
    @link = Link.new
  end

  def create
    @link = current_user.links.build(link_params)
    if @link.save
      flash[:success]= "Link submitted successfully"
      redirect_to root_path
    else
      render 'new'
    end
  end

  def edit
    @link = current_user.links.find_by(id: params[:id])
  end

  def update
    @link = current_user.links.find_by(id: params[:id])
    if @link.update_attributes(link_params)
      flash[:success] = "Link successfully edited"
      redirect_to current_user
    else
      flash[:danger] = "Link edit failed"
      render 'edit'
    end
  end

  def destroy
    @link = current_user.links.find_by(id: params[:id])
    @link.destroy
    flash[:success] = "Link successfully deleted"
    redirect_to root_path
  end

  def destroy_picture
    @link = current_user.links.find_by(id: params[:id])
    if @link.picture? && @link.user==current_user
      new_link = @link.dup
      new_link.picture=nil
      new_link.id = @link.id
      new_link.created_at = @link.created_at
      new_link.updated_at = Time.now
      @link.destroy
      new_link.save
      flash[:success]="Picture deleted successfully"
    end
  end

  private

    def link_params
      params.require(:link).permit(:title, :url, :picture)
    end

    def link_owner
      link = Link.find(params[:id])
      user = link.user
      redirect_to current_user unless current_user == user
    end
end
</code>```

_link.html.erb:-

```<code><div class="container">
  <li class="row">
    <span class="avatar">
      <%= image_tag link.user.avatar_url(:thumb) if link.user.avatar? %>
    </span>
    <span class="content">
      <b><%= link.title %></b> -
      <a href=<%= link.url %>><%= link.url %></a>
    </span>
    <span class="image">
      <%= image_tag link.picture.url if link.picture? %>
    </span>
    <span class="content">
      <% if link.user==current_user %>
        <%= link_to "Delete Picture", link_path(link),
            method: :destroy_picture,
            class: 'btn btn-xs btn-danger' %>
      <% end %>
    </span>
    <span class="timestamp">
      Posted <%= time_ago_in_words(link.created_at) %>
      ago by <%= link_to link.user.name, user_path(link.user)%>
    </span>
    <span class="content">
      <% if current_user==link.user %>
        <%= link_to "Edit", edit_link_path(link),
            class: 'btn btn-xs btn-primary' %>
        <%= link_to "Delete", link_path(link),
            method: :delete,
            data: {:confirm => "Are you sure?"},
            class: 'btn btn-xs btn-danger' %>
      <% end %>
    </span>
  </li>
</div>
</code>```

This link partial may appear either on the home page or the user's profile page.

Currently I am getting param is missing or the value is empty: link when I click on the "delete picture" button. How do I get around getting the method to be executed?

Also in general, what would be the simplest way of doing this?

答:
Replace your link_to helper with the route which points to the method to destroy such picture, and in the method use the corresponding HTTP verb, that's delete:

```<code><%= link_to "Delete Picture", destroy_picture_path(link), method: :delete, class: 'btn btn-xs btn-danger' %>
</code>```

Be sure you're passing the link object, to receive it in your controller and find the object in the database.

Also your routes must point as a delete action to your method:

```<code>delete '/links/:id', to: 'links#destroy_picture', as: 'destroy_picture'
</code>```

Body:
I'm working on a rails app where users can post links with title, url and an uploaded image file. When displaying this link I want to have a delete picture button next to the image so that the user may click on it to delete the image.

I don't know which is the best way to do this, but here's what I did:-

Custom method in links_controller.rb:-

  def destroy_picture
    @link = current_user.links.find_by(id: params[:id])
    if @link.picture? && @link.user==current_user
      new_link = @link.dup
      new_link.picture=nil
      new_link.id = @link.id
      new_link.created_at = @link.created_at
      new_link.updated_at = Time.now
      @link.destroy
      new_link.save
      flash[:success]="Picture deleted successfully"
    end
  end

Calling the custom method in the view:-

The complete files:-

link_controller.rb

class LinksController < ApplicationController
  before_action :logged_in_user, only: [:new, :create, :edit, :update, :destroy]
  before_action :link_owner, only: [:edit, :update, :destroy]

  def new
    @link = Link.new
  end

  def create
    @link = current_user.links.build(link_params)
    if @link.save
      flash[:success]= "Link submitted successfully"
      redirect_to root_path
    else
      render 'new'
    end
  end

  def edit
    @link = current_user.links.find_by(id: params[:id])
  end

  def update
    @link = current_user.links.find_by(id: params[:id])
    if @link.update_attributes(link_params)
      flash[:success] = "Link successfully edited"
      redirect_to current_user
    else
      flash[:danger] = "Link edit failed"
      render 'edit'
    end
  end

  def destroy
    @link = current_user.links.find_by(id: params[:id])
    @link.destroy
    flash[:success] = "Link successfully deleted"
    redirect_to root_path
  end

  def destroy_picture
    @link = current_user.links.find_by(id: params[:id])
    if @link.picture? && @link.user==current_user
      new_link = @link.dup
      new_link.picture=nil
      new_link.id = @link.id
      new_link.created_at = @link.created_at
      new_link.updated_at = Time.now
      @link.destroy
      new_link.save
      flash[:success]="Picture deleted successfully"
    end
  end

  private

    def link_params
      params.require(:link).permit(:title, :url, :picture)
    end

    def link_owner
      link = Link.find(params[:id])
      user = link.user
      redirect_to current_user unless current_user == user
    end
end

_link.html.erb:-

      <%= image_tag link.user.avatar_url(:thumb) if link.user.avatar? %>

      <%= link.title %> -
      <a href=<%= link.url %>><%= link.url %>

      <%= image_tag link.picture.url if link.picture? %>

      <% if link.user==current_user %>
        <%= link_to "Delete Picture", link_path(link),
            method: :destroy_picture,
            class: 'btn btn-xs btn-danger' %>
      <% end %>

      Posted <%= time_ago_in_words(link.created_at) %>
      ago by <%= link_to link.user.name, user_path(link.user)%>

      <% if current_user==link.user %>
        <%= link_to "Edit", edit_link_path(link),
            class: 'btn btn-xs btn-primary' %>
        <%= link_to "Delete", link_path(link),
            method: :delete,
            data: {:confirm => "Are you sure?"},
            class: 'btn btn-xs btn-danger' %>
      <% end %>

This link partial may appear either on the home page or the user's profile page.

Currently I am getting param is missing or the value is empty: link when I click on the "delete picture" button. How do I get around getting the method to be executed?

Also in general, what would be the simplest way of doing this?

Body:
Replace your link_to helper with the route which points to the method to destroy such picture, and in the method use the corresponding HTTP verb, that's delete:

<%= link_to "Delete Picture", destroy_picture_path(link), method: :delete, class: 'btn btn-xs btn-danger' %>

Be sure you're passing the link object, to receive it in your controller and find the object in the database.

Also your routes must point as a delete action to your method:

delete '/links/:id', to: 'links#destroy_picture', as: 'destroy_picture'


问:
Meteor app not finding 'xhr-sync-worker.js'?
I am trying to run a deck.gl example inside a meteor app. But I am facing this error.

```<code>modules-runtime.js?hash=8587d18…:231 Uncaught Error: Cannot find module './xhr-sync-worker.js'
    at makeMissingError (modules-runtime.js?hash=8587d18…:231)
    at Function.require.resolve (modules-runtime.js?hash=8587d18…:263)
    at xmlhttprequest.js (xml.js:30)
    at fileEvaluate (modules-runtime.js?hash=8587d18…:343)
    at require (modules-runtime.js?hash=8587d18…:238)
    at Window.js (xml.js:30)
    at fileEvaluate (modules-runtime.js?hash=8587d18…:343)
    at require (modules-runtime.js?hash=8587d18…:238)
    at api.js (xml.js:30)
    at fileEvaluate (modules-runtime.js?hash=8587d18…:343)
</code>```

However the said js module is present in the meteor app node_modules folder.

```<code>/caseview/node_modules/jsdom/lib/jsdom/living/xhr-sync-worker.js
</code>```

How can I make my app see it?. Note That I am not importing it directly in my code, as can be seen from the stack trace above. Perhaps this is a meteor bug.

答:
I had these issues in past in Meteor where it says some file is not found in node_modules. I don't know the exact reason why this occurs but yes it looks like some Meteor bug.

So, how I fixed this was by deleting node_modules folder and then doing meteor npm install again. Try this and I think this work in your case too. Let me know if it doesn't help.

Body:
I am trying to run a deck.gl example inside a meteor app. But I am facing this error.

modules-runtime.js?hash=8587d18…:231 Uncaught Error: Cannot find module './xhr-sync-worker.js'
    at makeMissingError (modules-runtime.js?hash=8587d18…:231)
    at Function.require.resolve (modules-runtime.js?hash=8587d18…:263)
    at xmlhttprequest.js (xml.js:30)
    at fileEvaluate (modules-runtime.js?hash=8587d18…:343)
    at require (modules-runtime.js?hash=8587d18…:238)
    at Window.js (xml.js:30)
    at fileEvaluate (modules-runtime.js?hash=8587d18…:343)
    at require (modules-runtime.js?hash=8587d18…:238)
    at api.js (xml.js:30)
    at fileEvaluate (modules-runtime.js?hash=8587d18…:343)

However the said js module is present in the meteor app node_modules folder.

/caseview/node_modules/jsdom/lib/jsdom/living/xhr-sync-worker.js

How can I make my app see it?. Note That I am not importing it directly in my code, as can be seen from the stack trace above. Perhaps this is a meteor bug.


问:
How to auto-close PyQt/PySide window using thread?
How can I make a PyQt5 window automatically close after 30 seconds and still keep the window respond to interaction?

I'm creating a thread which sleeps for 30 seconds, and then it calls the close() function of the window. Right now, the code hangs at self.close():

```<code>Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Users\fredrik\.conda\envs\pysidedev_py27\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Users\fredrik\.conda\envs\pysidedev_py27\lib\threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "C:\Users\fredrik\Desktop\timer.py", line 47, in <lambda>
    my_win.execute_function_threaded(func=lambda: my_win.auto_close(n=3))
  File "C:\Users\fredrik\Desktop\timer.py", line 36, in auto_close
    self.close()  # hangs
RuntimeError: Internal C++ object (MyWindow) already deleted.
</code>```

I also tried moving the threading out of the window object but then I'm still experiencing a hang on window.close().

What am I doing wrong?

The code must work with Python 2.7 and 3.5.

```<code>import sys
import time
from threading import Thread

try:
    from PyQt5 import QtWidgets
except ImportError:
    try:
        from PySide2 import QtWidgets
    except ImportError:
        try:
            from PyQt4 import QtGui as QtWidgets
        except ImportError:
            try:
                from PySide import QtGui as QtWidgets
            except ImportError:
                print('giving up!')

class MyWindow(QtWidgets.QMainWindow):
    """Auto-closing window"""
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

    def closeEvent(self, event):
        """Delete object when closed"""
        self.deleteLater()

    def auto_close(self, n):
        """Close self in n seconds"""
        print('going to sleep')
        for i in range(n):
            print('sleeping...')
            time.sleep(1)
        print('done sleeping!')
        self.close()  # hangs

    def execute_function_threaded(self, func):
        """Run given function in thread"""
        self.t = Thread(target=func)
        self.t.start()
        print('thread started')

app = QtWidgets.QApplication(sys.argv)
my_win = MyWindow()
my_win.show()
my_win.execute_function_threaded(func=lambda: my_win.auto_close(n=3))
sys.exit(app.exec_())
</code>```

Please note that the Qt binding imports are just done like that in order to make this code run easier on your end ;)

答:
Try following code instead of my_win.execute_function_threaded call:

```<code>class MyWindow(QtWidgets.QMainWindow):
    """Auto-closing window"""
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)
        QtCore.QTimer.singleShot(30000, self.close)
</code>```

Body:
How can I make a PyQt5 window automatically close after 30 seconds and still keep the window respond to interaction?

I'm creating a thread which sleeps for 30 seconds, and then it calls the close() function of the window. Right now, the code hangs at self.close():

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Users\fredrik\.conda\envs\pysidedev_py27\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Users\fredrik\.conda\envs\pysidedev_py27\lib\threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "C:\Users\fredrik\Desktop\timer.py", line 47, in <lambda>
    my_win.execute_function_threaded(func=lambda: my_win.auto_close(n=3))
  File "C:\Users\fredrik\Desktop\timer.py", line 36, in auto_close
    self.close()  # hangs
RuntimeError: Internal C++ object (MyWindow) already deleted.

I also tried moving the threading out of the window object but then I'm still experiencing a hang on window.close().

What am I doing wrong?

The code must work with Python 2.7 and 3.5.

import sys
import time
from threading import Thread

try:
    from PyQt5 import QtWidgets
except ImportError:
    try:
        from PySide2 import QtWidgets
    except ImportError:
        try:
            from PyQt4 import QtGui as QtWidgets
        except ImportError:
            try:
                from PySide import QtGui as QtWidgets
            except ImportError:
                print('giving up!')

class MyWindow(QtWidgets.QMainWindow):
    """Auto-closing window"""
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

    def closeEvent(self, event):
        """Delete object when closed"""
        self.deleteLater()

    def auto_close(self, n):
        """Close self in n seconds"""
        print('going to sleep')
        for i in range(n):
            print('sleeping...')
            time.sleep(1)
        print('done sleeping!')
        self.close()  # hangs

    def execute_function_threaded(self, func):
        """Run given function in thread"""
        self.t = Thread(target=func)
        self.t.start()
        print('thread started')

app = QtWidgets.QApplication(sys.argv)
my_win = MyWindow()
my_win.show()
my_win.execute_function_threaded(func=lambda: my_win.auto_close(n=3))
sys.exit(app.exec_())

Please note that the Qt binding imports are just done like that in order to make this code run easier on your end ;)

Body:
Try following code instead of my_win.execute_function_threaded call:

class MyWindow(QtWidgets.QMainWindow):
    """Auto-closing window"""
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)
        QtCore.QTimer.singleShot(30000, self.close)


问:
DistanceFromLocation producing extremely large (incorrect) distance
I've been having the hardest time trying to figure out why distanceFromLocation isn't calculting the correct distance for two CLLocations.  The calculated result is a number WAY larger than the actual distance but the two locations appear to be valid locations.

First of all, here are the two locations:

LOCATION 1: <+44.56697840,
  -69.55759810> +/- 0.00m (speed -1.00 mps / course -1.00) @ 2010-12-13
  21:12:03 -0500

  LOCATION 2:
  <+44.31400400, -69.79157000> +/- 0.00m
  (speed -1.00 mps / course -1.00) @
  2010-12-13 21:12:03 -0500

And here is the code where Location1 and Location2 are being declared.  I've verified that these are the correct values, but I still can't figure this out

```<code>CLLocation *newLocation = [[CLLocation alloc]
    initWithLatitude:[latitude doubleValue]
    longitude:[longitude doubleValue]];
    // CURRENT LOCATION (OR SEARCHED LOCATION)

double dLat = 0;
int tmpDistance = 0;
id returnId = nil;

id tmp = [featuredResults objectAtIndex:i];
CLLocation *newLocation2 = [[CLLocation alloc]
    initWithLatitude:[[tmp valueForKey:@"lat"] doubleValue]
    longitude:[[tmp valueForKey:@"lng"] doubleValue]];

dLat = [newLocation distanceFromLocation:newLocation2];
</code>```

The value that I'm getting for dLat is 330707027, which is way wrong.  Does anyone know where I might be going wrong?  Thanks!

答:
This test code based on the one in the question gives about 33,669 meters:

```<code>CLLocation *newLocation = [[CLLocation alloc]
    initWithLatitude:44.56697840 longitude:-69.55759810];

CLLocation *newLocation2 = [[CLLocation alloc]
    initWithLatitude:44.31400400 longitude:-69.79157000];

double dLat = [newLocation distanceFromLocation:newLocation2];

NSLog(@"distance = %f meters", dLat);

[newLocation release];
[newLocation2 release];
</code>```

Output:

distance = 33669.002406 meters

Perhaps you are logging dLat using something other than %f?

Body:
I've been having the hardest time trying to figure out why distanceFromLocation isn't calculting the correct distance for two CLLocations.  The calculated result is a number WAY larger than the actual distance but the two locations appear to be valid locations.

First of all, here are the two locations:

LOCATION 1: <+44.56697840,
  -69.55759810> +/- 0.00m (speed -1.00 mps / course -1.00) @ 2010-12-13
  21:12:03 -0500

  LOCATION 2:
  <+44.31400400, -69.79157000> +/- 0.00m
  (speed -1.00 mps / course -1.00) @
  2010-12-13 21:12:03 -0500

And here is the code where Location1 and Location2 are being declared.  I've verified that these are the correct values, but I still can't figure this out

CLLocation *newLocation = [[CLLocation alloc]
    initWithLatitude:[latitude doubleValue]
    longitude:[longitude doubleValue]];
    // CURRENT LOCATION (OR SEARCHED LOCATION)

double dLat = 0;
int tmpDistance = 0;
id returnId = nil;

id tmp = [featuredResults objectAtIndex:i];
CLLocation *newLocation2 = [[CLLocation alloc]
    initWithLatitude:[[tmp valueForKey:@"lat"] doubleValue]
    longitude:[[tmp valueForKey:@"lng"] doubleValue]];

dLat = [newLocation distanceFromLocation:newLocation2];

The value that I'm getting for dLat is 330707027, which is way wrong.  Does anyone know where I might be going wrong?  Thanks!

Body:
This test code based on the one in the question gives about 33,669 meters:

CLLocation *newLocation = [[CLLocation alloc]
    initWithLatitude:44.56697840 longitude:-69.55759810];

CLLocation *newLocation2 = [[CLLocation alloc]
    initWithLatitude:44.31400400 longitude:-69.79157000];

double dLat = [newLocation distanceFromLocation:newLocation2];

NSLog(@"distance = %f meters", dLat);

[newLocation release];
[newLocation2 release];

Output:

distance = 33669.002406 meters

Perhaps you are logging dLat using something other than %f?


问:
Custom exception with pre throw hook?
I want an Exception class that "does something" when it is thrown.
Dummy example:

```<code>class BrowserEatRamError(Exception):
    def __raise__(self):
        os.system('Killall -9 chrome')
        super(BrowserEatRamError, self).__raise__()
</code>```

When I throw it using:

```<code>raise BrowserEatRamError('Chrome is eating all ram')
</code>```

Chrome should be closed before the exception is thrown. Is there a magic method which can achieve it?  If not, what is the most elegant way to achieve similar behavior?

EDIT:

I prefer not to use init because init would be invoked even if the Exception is raised inside a try cache.

答:
No such special method exists. All of these are documented in the Data model.

Assuming you are using the (relatively good) practice of creating and initializing errors and then raising them, i.e.,

```<code>raise Error(args)
</code>```

instead of:

```<code>err = Error(args)
# Somewhere else
raise err
</code>```

You can simply overload the __intit__ method (Called to initialise it).

You can also put it in a try / except. If you do this often, you can use a context manager.

```<code>try:
     # ...
except Exception as e:
    # Reraise if the exception doesn't have a `.on_raise()` method
    # Or that method returns a falsey value.
    if not hasattr(e, 'on_raise') or not e.on_raise():
        raise
</code>```

```<code>class CustomRaiseAction(object):
    def __enter__(self):
        return
    def __exit__(exception_type, exception_value, traceback):
        if hasattr(exception_type, 'on_raise'):
            return exception_type.on_raise(exception_value)
custom_raise_action = CustomRaiseAction()

with custom_raise_action:
    # ...
</code>```

In both of these ways, if the on_raise method returns True, the exception will stop propogating. If it returns False (Or other falsey values, like None), it will be thrown further.

You can also do this without a context manager, by overwriting sys.excepthook. This is like an __exit__ for the whole program, and is called when the program is about the end, and by default, displays the error. Note that this won't work if another program overrides it, and applies in all situations, including other modules, which may cause unexpected behaviour.

```<code>import sys

old_excepthook = sys.excepthook
def new_excepthook(exception_type, exception_value, traceback):
    if hasattr(exception_type, 'on_raise'):
        exception_type.on_raise(exception_value)
    old_excepthook(exception_type, exception_value, traceback)
sys.excepthook = new_excepthook
</code>```

And also, you cannot stop the exception and continue.

Title: Custom exception with pre throw hook?

Body:
I want an Exception class that "does something" when it is thrown.
Dummy example:

class BrowserEatRamError(Exception):
    def __raise__(self):
        os.system('Killall -9 chrome')
        super(BrowserEatRamError, self).__raise__()

When I throw it using:

raise BrowserEatRamError('Chrome is eating all ram')

Chrome should be closed before the exception is thrown. Is there a magic method which can achieve it?  If not, what is the most elegant way to achieve similar behavior?

EDIT:

I prefer not to use init because init would be invoked even if the Exception is raised inside a try cache.

Body:
No such special method exists. All of these are documented in the Data model.

Assuming you are using the (relatively good) practice of creating and initializing errors and then raising them, i.e.,

raise Error(args)

instead of:

err = Error(args)
# Somewhere else
raise err

You can simply overload the __intit__ method (Called to initialise it).

You can also put it in a try / except. If you do this often, you can use a context manager.

try:
     # ...
except Exception as e:
    # Reraise if the exception doesn't have a `.on_raise()` method
    # Or that method returns a falsey value.
    if not hasattr(e, 'on_raise') or not e.on_raise():
        raise

class CustomRaiseAction(object):
    def __enter__(self):
        return
    def __exit__(exception_type, exception_value, traceback):
        if hasattr(exception_type, 'on_raise'):
            return exception_type.on_raise(exception_value)
custom_raise_action = CustomRaiseAction()

with custom_raise_action:
    # ...

In both of these ways, if the on_raise method returns True, the exception will stop propogating. If it returns False (Or other falsey values, like None), it will be thrown further.

You can also do this without a context manager, by overwriting sys.excepthook. This is like an __exit__ for the whole program, and is called when the program is about the end, and by default, displays the error. Note that this won't work if another program overrides it, and applies in all situations, including other modules, which may cause unexpected behaviour.

import sys

old_excepthook = sys.excepthook
def new_excepthook(exception_type, exception_value, traceback):
    if hasattr(exception_type, 'on_raise'):
        exception_type.on_raise(exception_value)
    old_excepthook(exception_type, exception_value, traceback)
sys.excepthook = new_excepthook

And also, you cannot stop the exception and continue.


问:
3rd Party Silverlight Grid Control
We are going through a process of selecting a 3rd party suite of controls for Silverlight 4.0.  We're mostly interested in a feature-rich grid control.  I'm surprised to find that most of the products out there focus on client side paging, filtering, sorting, and grouping.  But if the dataset is large enough to benefit from these functions isn't also too big to bring to the client in one call?  And doesn't this make most of the advertised fancy grid features useless?  In my opinion 200 rows of data is ideal upper limit on how much I'd request from the server in one request.  Yet the sites for Telerik, DevExpress, ComponentOne, Xceed, and others all have fancy demos that bring 10,000+ rows of data to the client and show off the ability to page, filter, group, and sort it.  Who brings 10,000+ rows of data to the client?  What if you have 1,000s of concurrent users?  What if that data is volatile?  What use-case does this really address?

Can you share your experiences with any of these control suites and whether you've implemented paging?  Also whether you are using RIA?

Thanks.

答: I'd like to see a control suite that boast working with concurrency issues on order fullfullment and also uses queues or stacks in order to solve data conflicts.  I see too often that this grids and list controls are really nice, pretty, and show you all the data, but they don't solve basic concurreny problems when you have more than one person working on the same set of data.   If it automates the locking of a row of one user from another, prevents duplication of work, and automatically logs error messages, then I can see purchasing the control suite.</p>

Title: 3rd Party Silverlight Grid Control


问:
select value= json_encode($array) is not returning entire array
I tested the following:

```<code><? echo json_encode($array) ?>    outputs: ["PG","Kevin Sad","8000","12"]
</code>```

When I place it inside a form option value to be chosen by my script function:

```<code><option value=<? echo json_encode($array) ?> > option1 </option>
</code>```

When I click SUBMIT button and the following function fires from the script:

```<code>function submit_button(){
    var data=  player1.options[player1.selectedIndex].value;
    document.getElementById('print_result').innerHTML = data;
}
</code>```

only the following is outputted inside the div id="print_result" :

```<code>["PG","Kevin
</code>```

Something happens with the space character " " that I cannot figure out..

I expected whole array to show up specifically including missing portion:

```<code> Sad","8000","12"]
</code>```

答:
Either you have to escape the double quotes and/or you use single quotes to contain the JSON.

See example and how it effects the outcome.

let options = document.querySelectorAll('option');
console.log(options[0].value, options[1].value);
document.getElementById('out').innerHTML = options[1].value;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><option value=["PG","Kevin Sad","8000","12"]> option1 </option>
<option value='["PG","Kevin Sad","8000","12"]'> option2 </option>
<div id="out"></div></code>```

Body:
I tested the following:

<? echo json_encode($array) ?>    outputs: ["PG","Kevin Sad","8000","12"]

When I place it inside a form option value to be chosen by my script function:

<option value=<? echo json_encode($array) ?> > option1 </option>

When I click SUBMIT button and the following function fires from the script:

function submit_button(){
    var data=  player1.options[player1.selectedIndex].value;
    document.getElementById('print_result').innerHTML = data;
}

only the following is outputted inside the div id="print_result" :

["PG","Kevin

Something happens with the space character " " that I cannot figure out..

I expected whole array to show up specifically including missing portion:

 Sad","8000","12"]

Body:
Either you have to escape the double quotes and/or you use single quotes to contain the JSON.

See example and how it effects the outcome.

let options = document.querySelectorAll('option');
console.log(options[0].value, options[1].value);
document.getElementById('out').innerHTML = options[1].value;

<option value=["PG","Kevin Sad","8000","12"]> option1 </option>
<option value='["PG","Kevin Sad","8000","12"]'> option2 </option>
<div id="out"></div>


问:
rpy2: how to get the return values from calling a R function
I would like to use the following R script in Python:

```<code>> library(bfast)
> apple <- read.csv("/Users/nskalis/Downloads/R/apple.csv", sep = ";", header=TRUE)
> data = apple
# data$in_bps: is vector of double numbers
> data.ts <- ts(data$in_bps, frequency=1)
> data.fit <- bfast(data.ts, h=0.1, season="none", max.iter=1)
> data.fit$output[[1]]$Tt
> data.fit$output[[1]]$Vt.bp
> data.fit$output[[1]]$ci.Vt
> data.fit$output[[1]]$ci.Vt$confint
</code>```

Therefore I am using rpy2 and I have done the following:

```<code>from rpy2.robjects.packages import importr
import rpy2.robjects as robjects
importr("bfast")
data = range(1,100)
data = robjects.FloatVector(data)
data = robjects.r.ts(data, frequency=1)
x = robjects.r.bfast(data, h=0.1, season="none", max_iter=1)
</code>```

The result variable x equals

```<code>In [42]: x
Out[42]:
R object with classes: ('bfast',) mapped to:
<ListVector - Python:0x7f234f7ad6c8 / R:0x76a2d60>
[Float..., ListV..., ListV..., ..., Float..., BoolV..., ListV...]
  Yt: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('ts',) mapped to:
<FloatVector - Python:0x7f234fd22dc8 / R:0x7605740>
[1.000000, 2.000000, 3.000000, ..., 97.000000, 98.000000, 99.000000]
R object with classes: ('bfast',) mapped to:
<ListVector - Python:0x7f234f7ad6c8 / R:0x76a2d60>
[Float..., ListV..., ListV..., ..., Float..., BoolV..., ListV...]
R object with classes: ('bfast',) mapped to:
<ListVector - Python:0x7f234f7ad6c8 / R:0x76a2d60>
[Float..., ListV..., ListV..., ..., Float..., BoolV..., ListV...]
  ...
  Yt: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x7f234c053388 / R:0x586b668>
[0.000000]
  output: <class 'rpy2.robjects.vectors.BoolVector'>
  R object with classes: ('logical',) mapped to:
<BoolVector - Python:0x7f234c04eac8 / R:0x57ee518>
[NA]
R object with classes: ('bfast',) mapped to:
<ListVector - Python:0x7f234f7ad6c8 / R:0x76a2d60>
[Float..., ListV..., ListV..., ..., Float..., BoolV..., ListV...]
</code>```

Could you please advise how to get the variable data.fit$output[[1]]$Vt.bp ?

PS: it is my 1st time with rpy2, so please feel free to advise me if I am doing anything wrong already.

答:
As seen, the bfast method apparently returns a nested object with layers deep of data items. Additionally, the returned Python object is of a foreign class <class 'rpy2.robjects. vectors.ListVector'> with nested, unnamed elements.

As an alternative to mining the Python object by integer position, consider importing a user-defined R function using the anonymous package import facility, STAP, that allows you to retain the R code and specifically return the variable you require using R's named elements nomenclature:

```<code>from rpy2.robjects.packages import STAP

r_fct_string ='''
bfast_out <- function(path){
    data <- read.csv(path, sep = ";", header=TRUE)

    data.ts <- ts(data$in_bps, frequency=1)
    data.fit <- bfast(data.ts, h=0.1, season="none", max.iter=1)

    data.fit$output[[1]]$Vt.bp
}
'''

r_pkg = STAP(r_fct_string, "r_pkg")

Vt_bp = r_pkg.bfast_out("/Users/nskalis/Downloads/R/apple.csv")

print(Vt_bp)
</code>```

Body:
I would like to use the following R script in Python:

> library(bfast)
> apple <- read.csv("/Users/nskalis/Downloads/R/apple.csv", sep = ";", header=TRUE)
> data = apple
# data$in_bps: is vector of double numbers
> data.ts <- ts(data$in_bps, frequency=1)
> data.fit <- bfast(data.ts, h=0.1, season="none", max.iter=1)
> data.fit$output[[1]]$Tt
> data.fit$output[[1]]$Vt.bp
> data.fit$output[[1]]$ci.Vt
> data.fit$output[[1]]$ci.Vt$confint

Therefore I am using rpy2 and I have done the following:

from rpy2.robjects.packages import importr
import rpy2.robjects as robjects
importr("bfast")
data = range(1,100)
data = robjects.FloatVector(data)
data = robjects.r.ts(data, frequency=1)
x = robjects.r.bfast(data, h=0.1, season="none", max_iter=1)

The result variable x equals

In [42]: x
Out[42]:
R object with classes: ('bfast',) mapped to:
<ListVector - Python:0x7f234f7ad6c8 / R:0x76a2d60>
[Float..., ListV..., ListV..., ..., Float..., BoolV..., ListV...]
  Yt: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('ts',) mapped to:
<FloatVector - Python:0x7f234fd22dc8 / R:0x7605740>
[1.000000, 2.000000, 3.000000, ..., 97.000000, 98.000000, 99.000000]
R object with classes: ('bfast',) mapped to:
<ListVector - Python:0x7f234f7ad6c8 / R:0x76a2d60>
[Float..., ListV..., ListV..., ..., Float..., BoolV..., ListV...]
R object with classes: ('bfast',) mapped to:
<ListVector - Python:0x7f234f7ad6c8 / R:0x76a2d60>
[Float..., ListV..., ListV..., ..., Float..., BoolV..., ListV...]
  ...
  Yt: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x7f234c053388 / R:0x586b668>
[0.000000]
  output: <class 'rpy2.robjects.vectors.BoolVector'>
  R object with classes: ('logical',) mapped to:
<BoolVector - Python:0x7f234c04eac8 / R:0x57ee518>
[NA]
R object with classes: ('bfast',) mapped to:
<ListVector - Python:0x7f234f7ad6c8 / R:0x76a2d60>
[Float..., ListV..., ListV..., ..., Float..., BoolV..., ListV...]

Could you please advise how to get the variable data.fit$output[[1]]$Vt.bp ?

PS: it is my 1st time with rpy2, so please feel free to advise me if I am doing anything wrong already.

Body:
As seen, the bfast method apparently returns a nested object with layers deep of data items. Additionally, the returned Python object is of a foreign class <class 'rpy2.robjects. vectors.ListVector'> with nested, unnamed elements.

As an alternative to mining the Python object by integer position, consider importing a user-defined R function using the anonymous package import facility, STAP, that allows you to retain the R code and specifically return the variable you require using R's named elements nomenclature:

from rpy2.robjects.packages import STAP

r_fct_string ='''
bfast_out <- function(path){
    data <- read.csv(path, sep = ";", header=TRUE)

    data.ts <- ts(data$in_bps, frequency=1)
    data.fit <- bfast(data.ts, h=0.1, season="none", max.iter=1)

    data.fit$output[[1]]$Vt.bp
}
'''

r_pkg = STAP(r_fct_string, "r_pkg")

Vt_bp = r_pkg.bfast_out("/Users/nskalis/Downloads/R/apple.csv")

print(Vt_bp)


问:
Tkinter Screen Change as Altered Display - Easy way to rectify?
I understand that a few others have asked similar questions although i cant find any that match my specific issue so please be gentle.

My issue is every display i use results in my Tkinter display completely changing and im having to reposition and resize everything again through trial and error which is massively time consuming. Is there an easy way around this? I've used place and pixel sizes in the script so i think its everytime the resolution changes im having to start over.

Anyway I thought i set the resolution to the Rpi touchscreen and built the GUI to that. However, now i've bought the touchscreen the GUI isn't even close to fitting it.

I'm not that keen on having to resize and reposition everything again so if there is an easy way to achieve what i'm after i'd be grateful if someone could share it. If not, i'll just have to get on with it.

Cheers
chris

答:
The problem is that you are using place. place should be avoided for exactly this reason. If you learn to use grid and pack properly, and do not call pack_propagate(0) or grid_propagate(0) unless you are certain it is the only solution to your problem, tkinter will do a fantastic job of adapting to different screen resolutions, font sizes, and user preferences.

In other words, the answer to "[is there] an easy way to achieve what I'm after" is "use grid and pack, and avoid place".


问:
Remove first n elements of bytes object without copying
I want to remove elements of a bytes parameter in a function. I want the parameter to be changed, not return a new object.

```<code>def f(b: bytes):
  b.pop(0)   # does not work on bytes
  del b[0]   # deleting not supported by _bytes_
  b = b[1:]  # creates a copy of b and saves it as a local variable
  io.BytesIO(b).read(1)  # same as b[1:]
</code>```

What's the solution here?

答:
Just use a bytearray:

```<code>>>> a = bytearray(b'abcdef')
>>> del a[1]
>>> a
bytearray(b'acdef')
</code>```

It's almost like bytes but mutable:

The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations.

Body:
I want to remove elements of a bytes parameter in a function. I want the parameter to be changed, not return a new object.

def f(b: bytes):
  b.pop(0)   # does not work on bytes
  del b[0]   # deleting not supported by _bytes_
  b = b[1:]  # creates a copy of b and saves it as a local variable
  io.BytesIO(b).read(1)  # same as b[1:]

What's the solution here?

Body:
Just use a bytearray:

>>> a = bytearray(b'abcdef')
>>> del a[1]
>>> a
bytearray(b'acdef')

It's almost like bytes but mutable:

The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations.


问:
Layout XML File or Values XML File?

I need to create a new file XML in my project, but I'm uncertain.

Someone can explain me what are the differnt between the Layout XML File and the Values XML File so I can choose what type of XML I should use?

答:
If you want to create a new layout file (for design) then choose Layout XML File.

If you want to create any other resourse file like color, string, etc. then choose Values XML File.

HTH - is it OK now or want to understood more?

Title: Layout XML File or Values XML File?


问:
Passing options to rackup via a Sinatra application
I'm new to ruby, learning Sinatra. While creating a Sinatra site by requiring 'sinatra' and setting up the routes directly under is pretty easy and rather well documented, creating an application by requiring 'sinatra/base' and writing a class that inherits from 'Sinatra::Base', while still relatively easy, is very poorly documented (maybe because it's a pretty recent feature of Sinatra).

And that's exactly what I am doing. I am not having too much trouble on the Sinatra part, however I am having a bit of trouble on the rackup/thin/server part. Apparently there are two ways to deploy the application: using Sinatra itself (using the run! method) and using a rackup file (typically config.ru).

Using Sinatra's run! method is extremely intuitive and works like a charm, but apparently it doesn't work if I want to deploy my app on heroku. As a matter of fact, almost all the Sinatra apps that I have encountered on GitHub use a config.ru file.

Using a rackup file might be equally intuitive, but I can't manage to understand how to pass options from the Sinatra app to the server (ir: the port). I tried to merge options to rackup's default options array:

```<code>MyApp::App.default_options.merge!(
  :run  => false,
  :env  => :production,
  :port => 4567
)

run MyApp::App
</code>```

by adding options directly to the app:

```<code>MyApp::App.set :port, 4567
MyApp::App.set :run, false
MyApp::App.set :env, :production

run MyApp::App
</code>```

by setting options from within the application class:

```<code>module MyApp
  class App < Sinatra::Base
    set :port, 4567
    set :run, false
    set :env, :production

    # ...

  # config.ru
  require 'app'

  run MyApp::App
</code>```

All the methods above failed, either by showing error messages or by just not taking any of the options into consideration. So is there any way to pass options to rackup/thin/the sever via a Sinatra app when using a rackup file? Or the options in questions should be passed directly to rackup/thin/the sever via command-line options?

As a reference to the problem, here is the little Sinatra application I am building: https://github.com/AzizLight/Wiki/

答:
You're actully going to pass options to thin on the command line directly or via a configuration file. See all options:

```<code>$ thin -h
</code>```

For production, use a configuration file:

```<code>$ thin -C thin-production.yml -R config.ru start
</code>```

Here is an example thin-production.yml file:

```<code>---
address: localhost
port: 3020
servers: 4
max_conns: 1024
max_persistent_conns: 512
timeout: 30
environment: production
pid: tmp/pids/thin-production.pid
log: log/thin-production.log
daemonize: true
</code>```

Body:
I'm new to ruby, learning Sinatra. While creating a Sinatra site by requiring 'sinatra' and setting up the routes directly under is pretty easy and rather well documented, creating an application by requiring 'sinatra/base' and writing a class that inherits from 'Sinatra::Base', while still relatively easy, is very poorly documented (maybe because it's a pretty recent feature of Sinatra).

And that's exactly what I am doing. I am not having too much trouble on the Sinatra part, however I am having a bit of trouble on the rackup/thin/server part. Apparently there are two ways to deploy the application: using Sinatra itself (using the run! method) and using a rackup file (typically config.ru).

Using Sinatra's run! method is extremely intuitive and works like a charm, but apparently it doesn't work if I want to deploy my app on heroku. As a matter of fact, almost all the Sinatra apps that I have encountered on GitHub use a config.ru file.

Using a rackup file might be equally intuitive, but I can't manage to understand how to pass options from the Sinatra app to the server (ir: the port). I tried to merge options to rackup's default options array:

MyApp::App.default_options.merge!(
  :run  => false,
  :env  => :production,
  :port => 4567
)

run MyApp::App

by adding options directly to the app:

MyApp::App.set :port, 4567
MyApp::App.set :run, false
MyApp::App.set :env, :production

run MyApp::App

by setting options from within the application class:

module MyApp
  class App < Sinatra::Base
    set :port, 4567
    set :run, false
    set :env, :production

    # ...

  # config.ru
  require 'app'

  run MyApp::App

All the methods above failed, either by showing error messages or by just not taking any of the options into consideration. So is there any way to pass options to rackup/thin/the sever via a Sinatra app when using a rackup file? Or the options in questions should be passed directly to rackup/thin/the sever via command-line options?

As a reference to the problem, here is the little Sinatra application I am building: https://github.com/AzizLight/Wiki/

Body:
You're actully going to pass options to thin on the command line directly or via a configuration file. See all options:

$ thin -h

For production, use a configuration file:

$ thin -C thin-production.yml -R config.ru start

Here is an example thin-production.yml file:

---
address: localhost
port: 3020
servers: 4
max_conns: 1024
max_persistent_conns: 512
timeout: 30
environment: production
pid: tmp/pids/thin-production.pid
log: log/thin-production.log
daemonize: true


问:
I want to increment the value of age in a table every 24hours
I have a column "age" in my database.table
So here it goes the moment i input a name the age will increment every day so ill get its day old as age
Pls help</p>

答: You don't need to increment that and moreover no need of storing Age as column in your database table since it's a computed/calculated column which can be calculated anytime using the DOB (date of birth) and current date. So while fetching records from table calculate the same and display it


问:
scanf(), field width, inf and nan
Per the C standard from 1999, scanf() and strtod() should accept infinity and NaN as inputs (if supported by the implementation).

The descriptions of both functions have peculiar language, which may be open to interpretations.

scanf():

An input item is defined as the longest sequence of input characters
  which does not exceed any specified field width and which is, or is a
  prefix of, a matching input sequence.

strtod():

The subject sequence is defined as the longest initial subsequence of
  the input string, starting with the first non-white-space character,
  that is of the expected form.

While the latter excerpt appears to be strict in requiring the specific forms of "INF", "INFINITY", "NAN" or "NAN(n-char-sequence-opt)", the former isn't and one would think that the following code should produce infinity and NaN because the field width covers prefixes of matching input sequences:

```<code>int r;
double d;
d = 0; r = sscanf("inf", "%2le", &d);
printf("%d %e\n", r, d);
d = 0; r = sscanf("nan", "%2le", &d);
printf("%d %e\n", r, d);
</code>```

There's also this bit on scanf():

a,e,f,g Matches an optionally signed floating-point number, infinity,
  or NaN, whose format is the same as expected for the subject sequence
  of the strtod function. The corresponding argument shall be a pointer
  to floating.

Is this simply a failure to document that a field width of 2, which is shorter than the expected shortest forms ("inf" or "nan"), does not make the otherwise matching prefixes "in" and "na" valid matches?

答:
In the specification of the behaviour of scanf, an "input item" is precisely the sequence of input characters consumed by the processing of a format specifier. After processing of the format specifier, whether that processing succeeds or not, the stream is positioned precisely after the last character in the input item, as is made clear by the sentence immediately following the definition of "input item" quoted in the question.

The first character, if any, after the input item remains unread.

Once the input item has been read, scanf proceeds to the next step (paragraph 10 of the same clause), in which the input item as a whole must be convertible according to the format specifier:

10 …[the input item] is converted to a type appropriate to the conversion specifier. If the input item is not a matching sequence, the execution of the directive fails: this condition is a matching failure.

"Matching sequence" is defined in the description of each format specifier; for a f specifier that will be:

the same as expected for the subject sequence of the strtod function.

as quoted in the question.

This is not the same algorithm as used by strtod. strtod finds the longest possible matching sequence, and provided there is one (even if only one character), it converts it and places the address of the next character in the supplied endptr argument.

By contrast, scanf has to deal with the limitations of an input stream, which does not allow reliable rewinding of the read pointer by more than one character. (See the definition of ungetc.) So scanf reads until it finds a character which could not extend the match, at which point it replaces that character into the input stream and attempts to convert what has been read to that point. Unlike strtod, it cannot backtrack to a shorter valid sequence, if there is one.

The other difference with strtod is that scanf can be restricted to a maximum length, useful for converting undelimited fixed-length input fields. With strtod it would be necessary to make a NUL-terminated copy of the fixed-length field, or temporarily insert a NUL at an appropriate point and later restore the overwritten character. In such a case, it would be important to verify that strtod consumed the entire input; if it did not, that would indicate garbage in the input.

The difference <s>can be seen</s> may be visible empirically. Given the input 1E-@, scanf <s>will</s> should report a matching failure and a subsequent getchar <s>will</s> should return '@'. strtod will return 1.0 with endptr pointing at E.

A specified format length can also cause scanf to return a matching error. Given input 1E-7@, scanf formats %2f and %3f <s>will</s> should; %1f will convert 1.0 and %4f (or larger) will convert .01, leaving @ for the next specifier (or subsequent input function). %2f applied to an input of inf or nan should exhibit precisely the same behaviour as 1E-7: a matching failure after absorbing two characters (because the truncated field is not a valid floating point number).

Whether the above happens or not depends on whether the implementation of the standard C library conforms with the standard. Glibc does not, and glibc is most probably what you will be using on a Linux platform regardless of whether you compile with gcc or clang, because clang does not bundle a standard C library, not even in the libcxx project.

The limited testing I was able to do on Windows (using an online compiler) suggests that the libcrt implementation of scanf does work as I would expect. My own examination of the source code for the FreeBSD library suggests that it's scanf will correctly report matching failures but may back the read cursor up by more than one character.

Title: scanf(), field width, inf and nan

Body:
Per the C standard from 1999, scanf() and strtod() should accept infinity and NaN as inputs (if supported by the implementation).

The descriptions of both functions have peculiar language, which may be open to interpretations.

scanf():

An input item is defined as the longest sequence of input characters
  which does not exceed any specified field width and which is, or is a
  prefix of, a matching input sequence.

strtod():

The subject sequence is defined as the longest initial subsequence of
  the input string, starting with the first non-white-space character,
  that is of the expected form.

While the latter excerpt appears to be strict in requiring the specific forms of "INF", "INFINITY", "NAN" or "NAN(n-char-sequence-opt)", the former isn't and one would think that the following code should produce infinity and NaN because the field width covers prefixes of matching input sequences:

int r;
double d;
d = 0; r = sscanf("inf", "%2le", &d);
printf("%d %e\n", r, d);
d = 0; r = sscanf("nan", "%2le", &d);
printf("%d %e\n", r, d);

There's also this bit on scanf():

a,e,f,g Matches an optionally signed floating-point number, infinity,
  or NaN, whose format is the same as expected for the subject sequence
  of the strtod function. The corresponding argument shall be a pointer
  to floating.

Is this simply a failure to document that a field width of 2, which is shorter than the expected shortest forms ("inf" or "nan"), does not make the otherwise matching prefixes "in" and "na" valid matches?


问:
How can i keep two values in c++
I have few pairs of elements : (3 1),(2 0),(3 0),(1 2),(4 1),(0 4),(0 1)
How or where can i keep them? In multidimensional array?
I thought about array but not sure

答:
```<code>#include <iostream>
#include <vector>

//Typedef the nasty name to a readable name
typedef std::vector<std::pair<int, int> > Container;

int main()
{
    //Make a variable of our container
    Container ctr;

    //Now make pairs and push them to the container
    ctr.push_back(std::make_pair(3,1));
    ctr.push_back(std::make_pair(2,0));
    ctr.push_back(std::make_pair(3,0));
    ctr.push_back(std::make_pair(1,2));
    ctr.push_back(std::make_pair(4,1));

    //If you don't believe the above code, print the container :)
    for(auto it = ctr.begin(); it < ctr.end(); ++it)
        std::cout << it->first << ":" << it->second << std::endl;
    return 0;
}
</code>```

Title: How can i keep two values in c++


问:
jQuery mouse event blocks default propagation
I have an issue with a full-body-overlay effect when clicking on any link.

The wanted effect is:

when any link of the page is "pushed" (mousedown or touchstart), an image overlay appears on the top of the whole body (hiding the complete content of the page)

when the link is (or should be) "released" (mouseup or touchend), the overlay should disappear and the original clicked link target should happen (the "href" attribute must be followed for instance).

The first part is OK: I added an event handler listening the "mousedown touchstart" events on every links. The second part is more complicated as the overlay does not trigger the "release" action of the link (the overlay is over the content with the link). So I attached a "mousedown touchend" event handler on the whole document, which works, but the default behavior of the clicked link (go to its "href" attribute for instance) is never fired :(

Here is my JS:

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

    // the full-page overlay selector
    var $overlay = $('.body-overlay');

    // a flag to keep a trace of clicked element
    var overlay_triggered = false;

    // the "mousedown" event handler
    function show_overlay(evt)
    {
        var $target = $(evt.target);
        if (overlay_triggered === false) {
            $overlay.show();
            overlay_triggered = $target;
            $(document).on('mouseup touchend', hide_overlay);
        }
        return true;
    }

    // the "mouseup" event handler
    function hide_overlay(evt)
    {
        if (overlay_triggered !== false) {
            $(document).off('mouseup touchend', hide_overlay);
            $overlay.hide();

            // !!! - here I try to trigger a classic click but it never works
            $(overlay_triggered).click();

            overlay_triggered = false;
        }
        return true;
    }

    // attachment of the mousedown handler on all links
    $(document).on('mousedown touchstart', 'a', show_overlay);

});
</code>```

I made a JS Fiddle to show it more clearly.

Does someone know about any mistake here ? Is my logic wrong ?

答:
The problem is caused by the way jQuery executes .click(). It is a shortcut for jQuery's trigger('click') method, and this is what the documentation says:

Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

The solution is to call the click method on the DOM element itself. It seems though that the MDN documentation announces the same limitations apply to that method:

The HTMLElement.click() method simulates a mouse click on an element.

However, the click() method will not initiate navigation on an  element.

...but in trying this with the current versions of Firefox, Chrome and Edge, the DOM click method does launch the  navigation (also when href has a http URL).

So, change this:

```<code>overlay_triggered = $target;
</code>```

to:

```<code>overlay_triggered = evt.target;
</code>```

And change this (which was overkill anyway):

```<code>$(overlay_triggered).click();
</code>```

to:

```<code>overlay_triggered.click();
</code>```

See the updated jsfiddle.

Body:
I have an issue with a full-body-overlay effect when clicking on any link.

The wanted effect is:

when any link of the page is "pushed" (mousedown or touchstart), an image overlay appears on the top of the whole body (hiding the complete content of the page)

when the link is (or should be) "released" (mouseup or touchend), the overlay should disappear and the original clicked link target should happen (the "href" attribute must be followed for instance).

The first part is OK: I added an event handler listening the "mousedown touchstart" events on every links. The second part is more complicated as the overlay does not trigger the "release" action of the link (the overlay is over the content with the link). So I attached a "mousedown touchend" event handler on the whole document, which works, but the default behavior of the clicked link (go to its "href" attribute for instance) is never fired :(

Here is my JS:

$(document).ready(function(){

    // the full-page overlay selector
    var $overlay = $('.body-overlay');

    // a flag to keep a trace of clicked element
    var overlay_triggered = false;

    // the "mousedown" event handler
    function show_overlay(evt)
    {
        var $target = $(evt.target);
        if (overlay_triggered === false) {
            $overlay.show();
            overlay_triggered = $target;
            $(document).on('mouseup touchend', hide_overlay);
        }
        return true;
    }

    // the "mouseup" event handler
    function hide_overlay(evt)
    {
        if (overlay_triggered !== false) {
            $(document).off('mouseup touchend', hide_overlay);
            $overlay.hide();

            // !!! - here I try to trigger a classic click but it never works
            $(overlay_triggered).click();

            overlay_triggered = false;
        }
        return true;
    }

    // attachment of the mousedown handler on all links
    $(document).on('mousedown touchstart', 'a', show_overlay);

});

I made a JS Fiddle to show it more clearly.

Does someone know about any mistake here ? Is my logic wrong ?

Body:
The problem is caused by the way jQuery executes .click(). It is a shortcut for jQuery's trigger('click') method, and this is what the documentation says:

Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

The solution is to call the click method on the DOM element itself. It seems though that the MDN documentation announces the same limitations apply to that method:

The HTMLElement.click() method simulates a mouse click on an element.

However, the click() method will not initiate navigation on an <a> element.

...but in trying this with the current versions of Firefox, Chrome and Edge, the DOM click method does launch the <a> navigation (also when href has a http URL).

So, change this:

overlay_triggered = $target;

to:

overlay_triggered = evt.target;

And change this (which was overkill anyway):

$(overlay_triggered).click();

to:

overlay_triggered.click();

See the updated jsfiddle.


问:
Separating Windows Forms and Classes C#
I am looking for a way to design a C# application. I understand 3-tier model, but idk how to apply this in a good C# design.

I have looked some asp.net mvc tutorials, but I am looking for a windows-form based tutorial.

is there any book or website to learn a way to implement this?

答: Hi if you are using Win Forms I recommend you to go for MVP pattern. There one more pattern MVVM (which is mostly used for WPF and Silverlight) but I dont know whether it apply for Win Forms.</p>

Title: Separating Windows Forms and Classes C#