问:
retrieve unique data from firebase
I have some information being sent to firebase. In my app, users enter info about themselves and it's stored under the uids. Here is the hierarchy:

```<code>{
  "gJRhIOfmckTq9cRWNnwhg7tdxxv1" : {
    "City" : "New York, New York",
    "College" : "New York University of New York",
    "Major" : "Nursing",
    "uid" : "gJRhIOfmckTq9cRWNnwhg7tdxxv1"
  },
  "ix7JSoW5JZMSmDjwQRUUd8W7fi2" : {
    "City" : "Miami, Florida",
    "College" : "University of Miami",
    "Major" : "Neuroscience ",
    "uid" : "ix7JSoW5JZMSmDjwQRUUd8W7fi2"
  }
}
</code>```

Here is the path to uploading the data:

```<code>FIRDatabase.database().reference().child("info").child(self.loggedInUser!.uid)
  .observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in
</code>```

The issue is that when a particular user is logged in, they should be able to see other user's information but when I try to retrieve the not logged in user's information, I run into a problem because of the uid. I get only the logged in user's information displayed in the non-logged in user information page. How can I make .child(self.loggedInUser!.uid)so that it does not only capture the logged in user's uid but all uids.

答:
Based on your response to my comment, it seems like you need all of the information about a user when, say, their profile is selected. This is where denormalization will come in handy. This blog post and this YouTube video go into detail on the what and why of denormalization, so I won't get into that too much here.

Using denormalization, you could include a child that lists all users with a username as a key and the user's uid as the value. Then when a user selects that user by username, say from a list in a table, you can find the user's uid and then listen to the value of the user's profile. The database structure would be something like this:

```<code>{
    users: {
        "thisperson": "gJRhIOfmckTq9cRWNnwhg7tdxxv1",
        "anotherperson": "ix7JSoW5JZMSmDjwQRUUd8W7fi2",
        ...
    },
    info: {
        "gJRhIOfmckTq9cRWNnwhg7tdxxv1" : {
            "City" : "New York, New York",
            "College" : "New York University of New York",
            "Major" : "Nursing",
            "uid" : "gJRhIOfmckTq9cRWNnwhg7tdxxv1"
        },
        "ix7JSoW5JZMSmDjwQRUUd8W7fi2" : {
            "City" : "Miami, Florida",
            "College" : "University of Miami",
            "Major" : "Neuroscience ",
            "uid" : "ix7JSoW5JZMSmDjwQRUUd8W7fi2"
        },
        ...
    }
}
</code>```

Then instead of listening to the values for the logged in user, you listen for the value of the selected user's uid, then listen using that instead:

```<code> FIRDatabase.database().reference().child("info").child(otheruid)
   .observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in
</code>```

Where otheruid is the value of FIRDatabase.database().reference().child("users").child(username)

Title: retrieve unique data from firebase

Body:
I have some information being sent to firebase. In my app, users enter info about themselves and it's stored under the uids. Here is the hierarchy:

{
  "gJRhIOfmckTq9cRWNnwhg7tdxxv1" : {
    "City" : "New York, New York",
    "College" : "New York University of New York",
    "Major" : "Nursing",
    "uid" : "gJRhIOfmckTq9cRWNnwhg7tdxxv1"
  },
  "ix7JSoW5JZMSmDjwQRUUd8W7fi2" : {
    "City" : "Miami, Florida",
    "College" : "University of Miami",
    "Major" : "Neuroscience ",
    "uid" : "ix7JSoW5JZMSmDjwQRUUd8W7fi2"
  }
}

Here is the path to uploading the data:

FIRDatabase.database().reference().child("info").child(self.loggedInUser!.uid)
  .observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in

The issue is that when a particular user is logged in, they should be able to see other user's information but when I try to retrieve the not logged in user's information, I run into a problem because of the uid. I get only the logged in user's information displayed in the non-logged in user information page. How can I make .child(self.loggedInUser!.uid)so that it does not only capture the logged in user's uid but all uids.

Body:
Based on your response to my comment, it seems like you need all of the information about a user when, say, their profile is selected. This is where denormalization will come in handy. This blog post and this YouTube video go into detail on the what and why of denormalization, so I won't get into that too much here.

Using denormalization, you could include a child that lists all users with a username as a key and the user's uid as the value. Then when a user selects that user by username, say from a list in a table, you can find the user's uid and then listen to the value of the user's profile. The database structure would be something like this:

{
    users: {
        "thisperson": "gJRhIOfmckTq9cRWNnwhg7tdxxv1",
        "anotherperson": "ix7JSoW5JZMSmDjwQRUUd8W7fi2",
        ...
    },
    info: {
        "gJRhIOfmckTq9cRWNnwhg7tdxxv1" : {
            "City" : "New York, New York",
            "College" : "New York University of New York",
            "Major" : "Nursing",
            "uid" : "gJRhIOfmckTq9cRWNnwhg7tdxxv1"
        },
        "ix7JSoW5JZMSmDjwQRUUd8W7fi2" : {
            "City" : "Miami, Florida",
            "College" : "University of Miami",
            "Major" : "Neuroscience ",
            "uid" : "ix7JSoW5JZMSmDjwQRUUd8W7fi2"
        },
        ...
    }
}

Then instead of listening to the values for the logged in user, you listen for the value of the selected user's uid, then listen using that instead:

 FIRDatabase.database().reference().child("info").child(otheruid)
   .observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in

Where otheruid is the value of FIRDatabase.database().reference().child("users").child(username)


来源: stackexchange

问:
Trying to get an object value in from a key in Javascript
I'm trying to get a country label (name) from a value (country code) in an object.

In Vue.js I'm trying to build a computed property to return the name of the country based on the country code from an API request.

In the template:

```<code>countryLabel () {
    var countries = require('../../plugins/countries')
    var countryCode = this.content.country
    function getLabelByValue(countries, countryCode) {
        return Object.keys(countries).find(label => countries[value] === countryCode)
    }
}
</code>```

From a list of countries:

```<code>module.exports = [
    { value: 'AF', label: 'Afghanistan' },
    { value: 'AX', label: 'Aland Islands' },
    { value: 'AL', label: 'Albania' },
    { value: 'DZ', label: 'Algeria' },
    { value: 'AS', label: 'American Samoa' },
    { value: 'AD', label: 'Andorra' },
    { value: 'AO', label: 'Angola' },
    { value: 'AI', label: 'Anguilla' },
    { value: 'AQ', label: 'Antarctica' },
    { value: 'AG', label: 'Antigua and Barbuda' },
    ...
]
</code>```

答:
Based on rossipedia's answer this is working for me:</p>

```<code>countryLabel () {
    const countries = require('../../plugins/countries')
    return countries.find(item => item.value === this.content.country).label
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get a country label (name) from a value (country code) in an object.

In Vue.js I'm trying to build a computed property to return the name of the country based on the country code from an API request.

In the template:

countryLabel () {
    var countries = require('../../plugins/countries')
    var countryCode = this.content.country
    function getLabelByValue(countries, countryCode) {
        return Object.keys(countries).find(label => countries[value] === countryCode)
    }
}

From a list of countries:

module.exports = [
    { value: 'AF', label: 'Afghanistan' },
    { value: 'AX', label: 'Aland Islands' },
    { value: 'AL', label: 'Albania' },
    { value: 'DZ', label: 'Algeria' },
    { value: 'AS', label: 'American Samoa' },
    { value: 'AD', label: 'Andorra' },
    { value: 'AO', label: 'Angola' },
    { value: 'AI', label: 'Anguilla' },
    { value: 'AQ', label: 'Antarctica' },
    { value: 'AG', label: 'Antigua and Barbuda' },
    ...
]

Body:
Based on rossipedia's answer this is working for me:

countryLabel () {
    const countries = require('../../plugins/countries')
    return countries.find(item => item.value === this.content.country).label
}


问:
Int stream and collect
So I am having trouble understanding the principle of this supplier ,accumulator  and combiner in the collect from IntStream. I found an example.

```<code>IntStream.range(6,11)
         .collect(StringBuilder::new,
                  StringBuilder::appendCodePoint,
                  StringBuilder::append);
</code>```

Anyone mind explaining the StringBuilder::appendCodePoint part?

答:
Let's wrap this stream to make byte[] out of it and then String from the resulting array:

```<code>Arrays.toString(IntStream.range(6,11).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString().getBytes())
</code>```

That would give us:

```<code>[6, 7, 8, 9, 10]
</code>```

How does the collect work?

It takes the stream of 6..10 and collects it in the following order:

It builds a new StringBuilder instance

It accumulates, that is appends Unicode code point using StringBuilder::appendCodePoint to an accumulator. (equivalent to: (StringBuilder sb, int x) -> sb.appendCodePoint(x))

It combines, that is adds the result of (2) to to the StringBuilder instance created in (1). (equivalent to: (StringBuilder sb1, StringBuilder sb2) -> sb1.append(sb2))

The type signature of this parametrized collect() call looks like this:

```<code>collect(Supplier<StrinBuilder> supplier,
                  ObjIntConsumer<StrinBuilder> accumulator,
                  BiConsumer<StrinBuilder, StrinBuilder> combiner);
</code>```

Title: Int stream and collect

Body:
So I am having trouble understanding the principle of this supplier ,accumulator  and combiner in the collect from IntStream. I found an example.

IntStream.range(6,11)
         .collect(StringBuilder::new,
                  StringBuilder::appendCodePoint,
                  StringBuilder::append);

Anyone mind explaining the StringBuilder::appendCodePoint part?

Body:
Let's wrap this stream to make byte[] out of it and then String from the resulting array:

Arrays.toString(IntStream.range(6,11).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString().getBytes())

That would give us:

[6, 7, 8, 9, 10]

How does the collect work?

It takes the stream of 6..10 and collects it in the following order:

It builds a new StringBuilder instance

It accumulates, that is appends Unicode code point using StringBuilder::appendCodePoint to an accumulator. (equivalent to: (StringBuilder sb, int x) -> sb.appendCodePoint(x))

It combines, that is adds the result of (2) to to the StringBuilder instance created in (1). (equivalent to: (StringBuilder sb1, StringBuilder sb2) -> sb1.append(sb2))

The type signature of this parametrized collect() call looks like this:

collect(Supplier<StrinBuilder> supplier,
                  ObjIntConsumer<StrinBuilder> accumulator,
                  BiConsumer<StrinBuilder, StrinBuilder> combiner);


问:
Instagram API SyntaxError: Unexpected end of input
I have a site that needs to load some images from Instagram. I'm using Fetch to make the request to Instagram's API. The request is successful but I get this error when processing the request, error SyntaxError: Unexpected end of input.

The request comes back as 200 and with valid JSON. It seems like once the Fetch response completes the response is empty thus resulting in the SyntaxError.

http://jsbin.com/kohito/edit?html,js,console

I removed my access token from the example.

答:
You'll need to go with jsonp to consume the Instagram API using the Client-Side (Implicit) Authentication method. You can bring in fetch-jsonp to make a "fetch-like" request.
</p>

```<code>  <script src="https://cdnjs.cloudflare.com/ajax/libs/fetch-jsonp/1.1.0/fetch-jsonp.min.js"></script>
  <script>
  fetchJsonp('https://api.instagram.com/v1/users/self/media/recent/?' + window.location.hash.split('#')[1], {
    method: 'GET',
  }).then(response => {
    response.json().then((json) => {
      console.log(json);
    });
  });
  </script>
</code>```

Body:
You'll need to go with jsonp to consume the Instagram API using the Client-Side (Implicit) Authentication method. You can bring in fetch-jsonp to make a "fetch-like" request.

  <script src="https://cdnjs.cloudflare.com/ajax/libs/fetch-jsonp/1.1.0/fetch-jsonp.min.js"></script>
  <script>
  fetchJsonp('https://api.instagram.com/v1/users/self/media/recent/?' + window.location.hash.split('#')[1], {
    method: 'GET',
  }).then(response => {
    response.json().then((json) => {
      console.log(json);
    });
  });
  </script>


问:
how to install cpp_check.vmb in vim
I've found that cpp_check vim plugin on http://www.vim.org/scripts/script.php?script_id=5192 and I want to install it my vim plugin list. I have downloaded the .vmb from the link above, copied and I ran vim cpp_cppcheck.vmb & :so &, which copied the cpp_check.vim to ~/.vim/ftplugin/, I tried it out but it ddn't seem to work. I then moved the .vimfile into the plugin/ directory which allows me to execute :Cppcheck on a new vim instance but as soon as I launch :NERDTree in my vim environment, I loose the command :Cppcheck why is this and how can I fix it?

And if I close NERDTree again with NERDTreeClose, I get the :Cppcheck functionality back, too.

My .vimrc looks like:

```<code>$ cat ~/.vimrc
" Pathogen
execute pathogen#infect()
call pathogen#helptags() " generate helptags for everything in 'runtimepath'
syntax on
filetype plugin indent on

set tabstop=4
set shiftwidth=4
set expandtab
set autoindent
set autochdir

set tags=./tags,tags;$HOME

nmap <F8> :TagbarToggle<CR>

if has('cscope')
    set cscopetag cscopeverbose
    if has('quickfix')
        set cscopequickfix=s-,c-,d-,i-,t-,e-
    endif

    cnoreabbrev csa cs add
    cnoreabbrev csf cs find
    cnoreabbrev csk cs kill
    cnoreabbrev csr cs reset
    cnoreabbrev css cs show
    cnoreabbrev csh cs help

    command -nargs=0 Cscope cs add $VIMSRC/src/cscope.out $VIMSRC/src
endif

" g:CCTreeCscopeDb = "./cscope.out"
</code>```

答:
This is meant to be a C++ ftplugin.

Activate filetype plugins in your vimrc

Title: how to install cpp_check.vmb in vim

Body:
I've found that cpp_check vim plugin on http://www.vim.org/scripts/script.php?script_id=5192 and I want to install it my vim plugin list. I have downloaded the .vmb from the link above, copied and I ran vim cpp_cppcheck.vmb & :so &, which copied the cpp_check.vim to ~/.vim/ftplugin/, I tried it out but it ddn't seem to work. I then moved the .vimfile into the plugin/ directory which allows me to execute :Cppcheck on a new vim instance but as soon as I launch :NERDTree in my vim environment, I loose the command :Cppcheck why is this and how can I fix it?

And if I close NERDTree again with NERDTreeClose, I get the :Cppcheck functionality back, too.

My .vimrc looks like:

$ cat ~/.vimrc
" Pathogen
execute pathogen#infect()
call pathogen#helptags() " generate helptags for everything in 'runtimepath'
syntax on
filetype plugin indent on

set tabstop=4
set shiftwidth=4
set expandtab
set autoindent
set autochdir

set tags=./tags,tags;$HOME

nmap <F8> :TagbarToggle<CR>

if has('cscope')
    set cscopetag cscopeverbose
    if has('quickfix')
        set cscopequickfix=s-,c-,d-,i-,t-,e-
    endif

    cnoreabbrev csa cs add
    cnoreabbrev csf cs find
    cnoreabbrev csk cs kill
    cnoreabbrev csr cs reset
    cnoreabbrev css cs show
    cnoreabbrev csh cs help

    command -nargs=0 Cscope cs add $VIMSRC/src/cscope.out $VIMSRC/src
endif

" g:CCTreeCscopeDb = "./cscope.out"


问:
R Shiny App - window opens with no content
this is a quite weird issue which I was unable to solve with the support of prof.google.
When I start a Shiny App, the window (or alternatively the browser) open up but
- in case of the RStudio window: no content is shown
- in case of the IE: loading for 30 sec, then "page cannot be displayed" error

When I try to log, using

```<code>options(shiny.reactlog=TRUE)
<starting app here>
showReactLog()
</code>```

the HTML page for the log opens with no content.
I assume, it could be a Java issue (I am using Java 32bit, version 8, update 111)

Any support would be highly appreciated.

All the best; G

ps:
R version used: 3.3.1
shiny package 0.14.1
app used:

```<code>runExample("01_hello")
</code>```

答:
This have nothing to do with java.

This probably have nothing to do with reactive log too.

More likely packages not installed right, or some dependency problems. Why will you use shiny 0.14 when the latest is 1.0.3?

What's the complete procedures of your whole operation?

Body:
this is a quite weird issue which I was unable to solve with the support of prof.google.
When I start a Shiny App, the window (or alternatively the browser) open up but
- in case of the RStudio window: no content is shown
- in case of the IE: loading for 30 sec, then "page cannot be displayed" error

When I try to log, using

options(shiny.reactlog=TRUE)
<starting app here>
showReactLog()

the HTML page for the log opens with no content.
I assume, it could be a Java issue (I am using Java 32bit, version 8, update 111)

Any support would be highly appreciated.

All the best; G

ps:
R version used: 3.3.1
shiny package 0.14.1
app used:

runExample("01_hello")


问:
Convert String to NSURL is return nil in swift
I am trying to convert a String to NSURL and my code for that is Below:

```<code>var url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=\(self.latitude),\(self.longitude)&destinations=\(self.stringForDistance)&language=en-US"
    println("This is String: \(url)")
    var remoteUrl : NSURL? = NSURL(string: url)
    println("This is URL: \(remoteUrl)")
</code>```

And console prints something like this:

```<code>This is String: https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997|-34.4356434,150.8858692|-34.4250728,150.89314939999997|-34.4356434,150.8858692|-34.4250728,150.89314939999997|-34.4356434,150.8858692|-34.423234,150.88658899999996|-34.423234,150.88658899999996|-34.428251,150.899673|-34.4257439,150.89870229999997|-34.423234,150.88658899999996|-34.4257439,150.89870229999997|-34.425376,150.89388299999996&language=en-US

This is URL: nil
</code>```

The remoteUrl is nil and I don't know what is the problem here.

After that I try sort String like this:

```<code>var url : String = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997&language=en-US"
    println("This is String: \(url)")
    var remoteUrl : NSURL? = NSURL(string: url)
    println("This is URL: \(remoteUrl)")
</code>```

And console prints:

```<code>This is String: https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997&language=en-US
This is URL: Optional(https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997&language=en-US)
</code>```

This is working fine.

So can anybody please tell me what is wrong with my first case?

答:
SWIFT 3.0

A safe way to fix a bad string being converted to NSURL is by unwrapping the urlPath string variable using "guard let"

```<code>guard let url = NSURL(string: urlPath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
            else
            {
                print("Couldn't parse myURL = \(urlPath)")
                return
            }
</code>```

The variable called "urlPath" in my above example would be the url string you have already declared somewhere else in your code.

I came across this answer because randomly I was getting the nil error with XCode breaking at the point my string was made into a NSURL. No logic as to why it was random even when I printed the url's they would look fine. As soon as I added the .addingPercentEncoding it was back working without any issues whatsoever.

tl;dr For anyone reading this, try my above code and swap out "urlPath" for your own local string url.

Body:
I am trying to convert a String to NSURL and my code for that is Below:

var url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=\(self.latitude),\(self.longitude)&destinations=\(self.stringForDistance)&language=en-US"
    println("This is String: \(url)")
    var remoteUrl : NSURL? = NSURL(string: url)
    println("This is URL: \(remoteUrl)")

And console prints something like this:

This is String: https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997|-34.4356434,150.8858692|-34.4250728,150.89314939999997|-34.4356434,150.8858692|-34.4250728,150.89314939999997|-34.4356434,150.8858692|-34.423234,150.88658899999996|-34.423234,150.88658899999996|-34.428251,150.899673|-34.4257439,150.89870229999997|-34.423234,150.88658899999996|-34.4257439,150.89870229999997|-34.425376,150.89388299999996&language=en-US

This is URL: nil

The remoteUrl is nil and I don't know what is the problem here.

After that I try sort String like this:

var url : String = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997&language=en-US"
    println("This is String: \(url)")
    var remoteUrl : NSURL? = NSURL(string: url)
    println("This is URL: \(remoteUrl)")

And console prints:

This is String: https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997&language=en-US
This is URL: Optional(https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997&language=en-US)

This is working fine.

So can anybody please tell me what is wrong with my first case?

Body:
SWIFT 3.0

A safe way to fix a bad string being converted to NSURL is by unwrapping the urlPath string variable using "guard let"

guard let url = NSURL(string: urlPath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
            else
            {
                print("Couldn't parse myURL = \(urlPath)")
                return
            }

The variable called "urlPath" in my above example would be the url string you have already declared somewhere else in your code.

I came across this answer because randomly I was getting the nil error with XCode breaking at the point my string was made into a NSURL. No logic as to why it was random even when I printed the url's they would look fine. As soon as I added the .addingPercentEncoding it was back working without any issues whatsoever.

tl;dr For anyone reading this, try my above code and swap out "urlPath" for your own local string url.


问:
You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli
I had the latest angular-cli installed globally and my project was building successfully.

While reading a suggested solution for another issue, (https://github.com/angular/angular-cli/issues/917) I uninstalled the  global angular-cli and installed it as a dev-dependency.

That other issue wasn't solved so I uninstalled the dev-dependency and reinstalled angular-cli globally once again.
Now when I try to do an ng build I'm getting the error:

You have to be inside an angular-cli project in order to use the build command

My angular-cli version did not change. Why isn't my project being recognised as an angular-cli project??

答:
```<code>npm uninstall -g angular-cli @angular/cli
npm cache clean
npm install -g @angular/cli
</code>```

use sudo on Mac/Linux.

Body:
npm uninstall -g angular-cli @angular/cli
npm cache clean
npm install -g @angular/cli

use sudo on Mac/Linux.


问:
Spring Boot: Inject Bean into HttpServlet
I've got a Spring Boot where I've autoconfigured a Router bean.
This all works perfect but it becomes a problem when I want to inject that bean into a custom servlet:

```<code>public class MembraneServlet extends HttpServlet {
    @Autowired
    private Router router;

    @Override
    public void init() throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        new HttpServletHandler(req, resp, router.getTransport()).run();
    }
}
</code>```

This should be the way to go, but

```<code>SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
</code>```

won't autowire the Router because the WebapplicationContext is always null. The application is running in an MVC environment.

答:
What about injecting 'Router' as constructor parameter.

So you would have this:

```<code>public class MembraneServlet extends HttpServlet {

    private Router router;

    public MembraneServlet(Router router){
        this.router = router;
    }

    @Override
    public void init() throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        new HttpServletHandler(req, resp, router.getTransport()).run();
    }
}
</code>```

then you can programatically create servlet registration like this:

```<code>@Bean
public ServletRegistrationBean membraneServletRegistrationBean(){
    return new ServletRegistrationBean(new MembraneServlet(),"/*");
}
</code>```

Body:
I've got a Spring Boot where I've autoconfigured a Router bean.
This all works perfect but it becomes a problem when I want to inject that bean into a custom servlet:

public class MembraneServlet extends HttpServlet {
    @Autowired
    private Router router;

    @Override
    public void init() throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        new HttpServletHandler(req, resp, router.getTransport()).run();
    }
}

This should be the way to go, but

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

won't autowire the Router because the WebapplicationContext is always null. The application is running in an MVC environment.

Body:
What about injecting 'Router' as constructor parameter.

So you would have this:

public class MembraneServlet extends HttpServlet {

    private Router router;

    public MembraneServlet(Router router){
        this.router = router;
    }

    @Override
    public void init() throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        new HttpServletHandler(req, resp, router.getTransport()).run();
    }
}

then you can programatically create servlet registration like this:

@Bean
public ServletRegistrationBean membraneServletRegistrationBean(){
    return new ServletRegistrationBean(new MembraneServlet(),"/*");
}


问:
How do you iterate through a mixed List<t> and print contents to console in C#?
I have a List<object> which contains strings and even additional lists.

```<code>List<object> NewArray = new List<object>();
</code>```

so basically the list contains a mixture....

As a sanity check, I want to print out the contents to the console.  I start by iterating through and test to see whether the element is a list.  If it isn't then it will be a string and can be printed to the console.  If it is a list, I want to iterate through and print the string contents to the console but with a tab to indent it.

I have this so far:

```<code>    for (int outer = 0; outer < NewArray.Count; outer++)
            {

                var innerList = NewArray[outer];

                if (innerList.GetType().IsGenericType && innerList.GetType().GetGenericTypeDefinition() == typeof(List<>))
                {

                    for (int inner = 0; inner < innerList.Count; inner++)
                    {

                        //print string
                    }
                }
                else
                {
                    //print string
                }
    }
</code>```

I didn't want to use a foreach loop as I'm not sure the order of the list would be guaranteed and will be in the future adding a increment number (which can be provided by the inner and outer variables).

The issue I am getting is an error here:

```<code>inner < innerList.Count
</code>```

which is:

Operator '<' cannot be applied to operands of type 'int' and 'method group'

What do I need to do to overcome this?  I'm not sure it is the most efficient way of achieving the end result but....

答:
Here is more simplistic way of doing what you want:

```<code>public static void DeepPrint(object obj, int recursionLevel)
{
    if(obj == null)
    {
        //print null
        return;
    }
    var str = obj as string;
    if(str != null)
    {
        //print str
        return;
    }
    var enumer = obj as IEnumerable;
    if(enumer != null)
    {
        foreach(var e in enumer)
        {
            DeepPrint(e, recursionLevel+1);
        }
        return;
    }
    //print obj.ToString();
}
</code>```

Then call it like this on whatever you desire:

```<code>DeepPrint(myObjectOrList, 0);
</code>```

PS

For those who say about "random crap" - embrace the string.Format(...), embrace serialization in general, embrace WCF and dynamic, and etc. There is many random things in this world, what doesn't really need strong typing. In fact it will just become "crap" if you provide strong typing to some common used functions.

ContentLicense: CC BY-SA 4.0

Body:
I have a List<object> which contains strings and even additional lists.

List<object> NewArray = new List<object>();

so basically the list contains a mixture....

As a sanity check, I want to print out the contents to the console.  I start by iterating through and test to see whether the element is a list.  If it isn't then it will be a string and can be printed to the console.  If it is a list, I want to iterate through and print the string contents to the console but with a tab to indent it.

I have this so far:

    for (int outer = 0; outer < NewArray.Count; outer++)
            {

                var innerList = NewArray[outer];

                if (innerList.GetType().IsGenericType && innerList.GetType().GetGenericTypeDefinition() == typeof(List<>))
                {

                    for (int inner = 0; inner < innerList.Count; inner++)
                    {

                        //print string
                    }
                }
                else
                {
                    //print string
                }
    }

I didn't want to use a foreach loop as I'm not sure the order of the list would be guaranteed and will be in the future adding a increment number (which can be provided by the inner and outer variables).

The issue I am getting is an error here:

inner < innerList.Count

which is:

Operator '<' cannot be applied to operands of type 'int' and 'method group'

What do I need to do to overcome this?  I'm not sure it is the most efficient way of achieving the end result but....

Body:
Here is more simplistic way of doing what you want:

public static void DeepPrint(object obj, int recursionLevel)
{
    if(obj == null)
    {
        //print null
        return;
    }
    var str = obj as string;
    if(str != null)
    {
        //print str
        return;
    }
    var enumer = obj as IEnumerable;
    if(enumer != null)
    {
        foreach(var e in enumer)
        {
            DeepPrint(e, recursionLevel+1);
        }
        return;
    }
    //print obj.ToString();
}

Then call it like this on whatever you desire:

DeepPrint(myObjectOrList, 0);

PS

For those who say about "random crap" - embrace the string.Format(...), embrace serialization in general, embrace WCF and dynamic, and etc. There is many random things in this world, what doesn't really need strong typing. In fact it will just become "crap" if you provide strong typing to some common used functions.


问:
Is_Integer returning incorrect result - Python 2.X
```<code>dig = 16807
digcount = len(str(dig))
minroot = dig ** (1 / float(digcount))

print minroot
print minroot.is_integer()
</code>```

minroot returns as 7.0 as a float, but is_integer returns FALSE.

I tried (7.0).is_integer(), and it returns TRUE. What gives?

答:
SNote that minroot is not precisely 7.0, due to floating-point imprecision.  is_integer requires that precision.  Here's your code, with a little more detail.

```<code>dig = 16807
digcount = len(str(dig))
minroot = dig ** (1 / float(digcount))

print repr(minroot)
print minroot.is_integer()
a = 7.0
print a, type(a)
print a.is_integer()
</code>```

Output:

```<code>7.0000000000000009
False
7.0 <type 'float'>
True
</code>```

UPDATE: HOW TO HANDLE "VERY CLOSE"

See here for code to handle almost equal.  The general approach is to set a tolerance and use something such as:

```<code>if abs(a-b) <= tolerance:
</code>```

Or, "is the difference too small to matter?"

Body:
dig = 16807
digcount = len(str(dig))
minroot = dig ** (1 / float(digcount))

print minroot
print minroot.is_integer()

minroot returns as 7.0 as a float, but is_integer returns FALSE.

I tried (7.0).is_integer(), and it returns TRUE. What gives?

Body:
SNote that minroot is not precisely 7.0, due to floating-point imprecision.  is_integer requires that precision.  Here's your code, with a little more detail.

dig = 16807
digcount = len(str(dig))
minroot = dig ** (1 / float(digcount))

print repr(minroot)
print minroot.is_integer()
a = 7.0
print a, type(a)
print a.is_integer()

Output:

7.0000000000000009
False
7.0 <type 'float'>
True

UPDATE: HOW TO HANDLE "VERY CLOSE"

See here for code to handle almost equal.  The general approach is to set a tolerance and use something such as:

if abs(a-b) <= tolerance:

Or, "is the difference too small to matter?"


问:
Is it bad to have your test and production environments on the same machine?
Would it be bad to have things set up so that MySite.com is production and test.MySite.com is test?  Both running off the same machine.  The site doesn't get a lot of traffic.

UPDATE

I am talking about an ASP.NET web application running on a Windows server.

答:
"Good, bad, I'm the guy with the gun." - Ash

Bad is really a range.  It can be anywhere between replacing motherboards with the power plugged in and wet hands, to using excessively short variable names.  What you really want to know is what are the tradeoffs.  You obviously know some of the benefits or you wouldn't be thinking about using the production server for testing.

The big con is the test code is running in a shared environment with production.  If there is no sandbox (process limits, memory limits, disk limits, chroot file system, etc) you risk impacting the production server is something goes awry in the testing.  You may accidentally DOS your self by consuming all of a particular resource.  You may accidentally remove the production site.  Someone may think it's okay to do a load test.  If you are fine with taking those risks, then you can go ahead an run your test app on the production server.

BTW: It is bad.

ContentLicense: CC BY-SA 2.5


问:
No data from magnetometer on MPU9255
I have a problem with reading data from the magnetometer on an MPU9255. The accelerometer and gyroscope work properly, but I do not receive any data from the magnetometer. I am working on the STM32F103 target.

Has anyone any idea what is wrong with code below?

```<code>uint8_t Settings = 0x00;
uint8_t SettingsM = 0x00;
uint8_t SettingsL = 0x22;   //mode2 16bit
//settings accelerometer and gyroscope
HAL_I2C_Mem_Write(&hi2c1, 0xD0, 27, I2C_MEMADD_SIZE_8BIT, &Settings,1,1000);
HAL_I2C_Mem_Write(&hi2c1, 0xD0, 28, I2C_MEMADD_SIZE_8BIT, &Settings,1,1000);

//Power Down mode
HAL_I2C_Mem_Write(&hi2c1, 0x0C, 0x0A, I2C_MEMADD_SIZE_8BIT, &SettingsM,1,1000);
HAL_Delay(100);
//16 bit output mode 2
HAL_I2C_Mem_Write(&hi2c1, 0x0C, 0x0A, I2C_MEMADD_SIZE_8BIT, &SettingsL,1,1000);
while (1)
{
    //A X
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 59, I2C_MEMADD_SIZE_8BIT, &DAHx,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 60, I2C_MEMADD_SIZE_8BIT, &DALx,1,100);
    //A Y
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 61, I2C_MEMADD_SIZE_8BIT, &DAHy,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 62, I2C_MEMADD_SIZE_8BIT, &DALy,1,100);
    //A Z
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 63, I2C_MEMADD_SIZE_8BIT, &DAHz,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 64, I2C_MEMADD_SIZE_8BIT, &DALz,1,100);
    //Temp
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 65, I2C_MEMADD_SIZE_8BIT, &DHT,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 66, I2C_MEMADD_SIZE_8BIT, &DLT,1,100);
    //G X
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 67, I2C_MEMADD_SIZE_8BIT, &DGHx,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 68, I2C_MEMADD_SIZE_8BIT, &DGLx,1,100);
    //G Y
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 69, I2C_MEMADD_SIZE_8BIT, &DGHy,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 70, I2C_MEMADD_SIZE_8BIT, &DGLy,1,100);
    //G Z
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 71, I2C_MEMADD_SIZE_8BIT, &DGHz,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 72, I2C_MEMADD_SIZE_8BIT, &DGLz,1,100);

    do
    {
        HAL_I2C_Mem_Read(&hi2c1, 0x0C, 0x02, I2C_MEMADD_SIZE_8BIT, &ST1,1,100);
    }
    while (!(ST1&0x01));

    //0x0C - adress AK8963, 0x03-0x08 => HLx-HHz
    HAL_I2C_Mem_Read(&hi2c1, 0x0C, 0x03, I2C_MEMADD_SIZE_8BIT, &HLx,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0x0C, 0x04, I2C_MEMADD_SIZE_8BIT, &HHx,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0x0C, 0x05, I2C_MEMADD_SIZE_8BIT, &HLy,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0x0C, 0x06, I2C_MEMADD_SIZE_8BIT, &HHy,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0x0C, 0x07, I2C_MEMADD_SIZE_8BIT, &HLz,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0x0C, 0x08, I2C_MEMADD_SIZE_8BIT, &HHz,1,100);

    HAL_I2C_Mem_Read(&hi2c1, 0x0C, 0x09, I2C_MEMADD_SIZE_8BIT, &H,1,100);

    //accelerometer
    Ax = (int16_t)(DAHx << 8 | DALx);
    Ay = (int16_t)(DAHy << 8 | DALy);
    Az = (int16_t)(DAHz << 8 | DALz);
    //temperature
    T = (int16_t)(DHT << 8 | DLT);
    //gyroscope
    Gx = (int16_t)(DGHx << 8 | DGLx);
    Gy = (int16_t)(DGHy << 8 | DGLy);
    Gz = (int16_t)(DGHz << 8 | DGLz);
    //magnetometer
    Hx= (int16_t)(HHx << 8 | HLx);
    Hy= (int16_t)(HHy << 8 | HLy);
    Hz= (int16_t)(HHz << 8 | HLz);

    Ax_g = (float)Ax/16384.0;
    Ay_g = (float)Ay/16384.0;
    Az_g = (float)Az/16384.0;
    Gx_g = (float)Gx/131.0;
    Gy_g = (float)Gy/131.0;
    Gz_g = (float)Gz/131.0;

    arx = (180.0/3.141592) * atanf(Ax_g / sqrtf(Ay_g*Ay_g + Az_g*Az_g));
    ary = (180.0/3.141592) * atanf(Ay_g / sqrtf((Ax_g*Ax_g + Az_g*Az_g)));

    rx = (0.96 * arx) + (0.04 * Gx_g);
    ry = (0.96 * ary) + (0.04 * Gy_g);
}
</code>```

答:
You need to enable the I2C bypass mode on the MPU9255 to communicate with the AK8963 directly. Set the BYPASS_EN bit in the INT Pin / Bypass Enable Configuration register (register 55) at the beginning of your program with:

```<code>uint8_t BypassEnable = 0x02;
HAL_I2C_Mem_Write(&hi2c1, 0xD0, 55, I2C_MEMADD_SIZE_8BIT, &BypassEnable,1,1000);
</code>```

See here for a working example: Arduino Sensor 10DOF MPU9255 cannot fetch magnetometer data

Title: No data from magnetometer on MPU9255

Body:
I have a problem with reading data from the magnetometer on an MPU9255. The accelerometer and gyroscope work properly, but I do not receive any data from the magnetometer. I am working on the STM32F103 target.

Has anyone any idea what is wrong with code below?

uint8_t Settings = 0x00;
uint8_t SettingsM = 0x00;
uint8_t SettingsL = 0x22;   //mode2 16bit
//settings accelerometer and gyroscope
HAL_I2C_Mem_Write(&hi2c1, 0xD0, 27, I2C_MEMADD_SIZE_8BIT, &Settings,1,1000);
HAL_I2C_Mem_Write(&hi2c1, 0xD0, 28, I2C_MEMADD_SIZE_8BIT, &Settings,1,1000);

//Power Down mode
HAL_I2C_Mem_Write(&hi2c1, 0x0C, 0x0A, I2C_MEMADD_SIZE_8BIT, &SettingsM,1,1000);
HAL_Delay(100);
//16 bit output mode 2
HAL_I2C_Mem_Write(&hi2c1, 0x0C, 0x0A, I2C_MEMADD_SIZE_8BIT, &SettingsL,1,1000);
while (1)
{
    //A X
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 59, I2C_MEMADD_SIZE_8BIT, &DAHx,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 60, I2C_MEMADD_SIZE_8BIT, &DALx,1,100);
    //A Y
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 61, I2C_MEMADD_SIZE_8BIT, &DAHy,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 62, I2C_MEMADD_SIZE_8BIT, &DALy,1,100);
    //A Z
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 63, I2C_MEMADD_SIZE_8BIT, &DAHz,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 64, I2C_MEMADD_SIZE_8BIT, &DALz,1,100);
    //Temp
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 65, I2C_MEMADD_SIZE_8BIT, &DHT,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 66, I2C_MEMADD_SIZE_8BIT, &DLT,1,100);
    //G X
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 67, I2C_MEMADD_SIZE_8BIT, &DGHx,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 68, I2C_MEMADD_SIZE_8BIT, &DGLx,1,100);
    //G Y
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 69, I2C_MEMADD_SIZE_8BIT, &DGHy,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 70, I2C_MEMADD_SIZE_8BIT, &DGLy,1,100);
    //G Z
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 71, I2C_MEMADD_SIZE_8BIT, &DGHz,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0xD0, 72, I2C_MEMADD_SIZE_8BIT, &DGLz,1,100);

    do
    {
        HAL_I2C_Mem_Read(&hi2c1, 0x0C, 0x02, I2C_MEMADD_SIZE_8BIT, &ST1,1,100);
    }
    while (!(ST1&0x01));

    //0x0C - adress AK8963, 0x03-0x08 => HLx-HHz
    HAL_I2C_Mem_Read(&hi2c1, 0x0C, 0x03, I2C_MEMADD_SIZE_8BIT, &HLx,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0x0C, 0x04, I2C_MEMADD_SIZE_8BIT, &HHx,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0x0C, 0x05, I2C_MEMADD_SIZE_8BIT, &HLy,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0x0C, 0x06, I2C_MEMADD_SIZE_8BIT, &HHy,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0x0C, 0x07, I2C_MEMADD_SIZE_8BIT, &HLz,1,100);
    HAL_I2C_Mem_Read(&hi2c1, 0x0C, 0x08, I2C_MEMADD_SIZE_8BIT, &HHz,1,100);

    HAL_I2C_Mem_Read(&hi2c1, 0x0C, 0x09, I2C_MEMADD_SIZE_8BIT, &H,1,100);

    //accelerometer
    Ax = (int16_t)(DAHx << 8 | DALx);
    Ay = (int16_t)(DAHy << 8 | DALy);
    Az = (int16_t)(DAHz << 8 | DALz);
    //temperature
    T = (int16_t)(DHT << 8 | DLT);
    //gyroscope
    Gx = (int16_t)(DGHx << 8 | DGLx);
    Gy = (int16_t)(DGHy << 8 | DGLy);
    Gz = (int16_t)(DGHz << 8 | DGLz);
    //magnetometer
    Hx= (int16_t)(HHx << 8 | HLx);
    Hy= (int16_t)(HHy << 8 | HLy);
    Hz= (int16_t)(HHz << 8 | HLz);

    Ax_g = (float)Ax/16384.0;
    Ay_g = (float)Ay/16384.0;
    Az_g = (float)Az/16384.0;
    Gx_g = (float)Gx/131.0;
    Gy_g = (float)Gy/131.0;
    Gz_g = (float)Gz/131.0;

    arx = (180.0/3.141592) * atanf(Ax_g / sqrtf(Ay_g*Ay_g + Az_g*Az_g));
    ary = (180.0/3.141592) * atanf(Ay_g / sqrtf((Ax_g*Ax_g + Az_g*Az_g)));

    rx = (0.96 * arx) + (0.04 * Gx_g);
    ry = (0.96 * ary) + (0.04 * Gy_g);
}

Body:
You need to enable the I2C bypass mode on the MPU9255 to communicate with the AK8963 directly. Set the BYPASS_EN bit in the INT Pin / Bypass Enable Configuration register (register 55) at the beginning of your program with:

uint8_t BypassEnable = 0x02;
HAL_I2C_Mem_Write(&hi2c1, 0xD0, 55, I2C_MEMADD_SIZE_8BIT, &BypassEnable,1,1000);

See here for a working example: Arduino Sensor 10DOF MPU9255 cannot fetch magnetometer data


问:
Delete duplicates, and reassign FK value in SQL
I have two tables:

```<code> Table1:
 [id], [ColA]

 Table2:
 [id], [Table1Id]
</code>```

A previous update caused duplicates in Table1 and those duplicates to be assocated with rows in Table2.  It looks like this in the db:

```<code>Table1
1, 89
2, 89

Table2
6, 1
7, 2
</code>```

I would like to delete the duplicates and reassign the value of the Table2.Table1Id to the one Table1.id row that should be left.  Is this possible in a single statement?  Ive seen this post on how to delete all but one, but I am lost on how to reassign the Table2.Table1Id value.

edit:
 The end result should look like this:

```<code>Table1
2, 89

Table2
6, 2
7, 2
</code>```

答:
```<code>drop table if exists dbo.Table2;
drop table if exists dbo.Table1;

create table dbo.Table1 (
ID int primary key
, ColA int
);

create table dbo.Table2 (
ID int
, Table1ID int
);

alter table dbo.Table2
add constraint FK_Table2_Table1
foreign key (Table1ID)
references dbo.Table1 (ID);

insert into dbo.Table1 (ID, ColA)
values (1, 89), (2, 89);

insert into dbo.Table2 (ID, Table1ID)
values (6, 1), (7, 2);

drop table if exists #temp;

select
ttt.ID
into #temp
from (
select
    t.ID
    , t.ColA
    , ROW_NUMBER() over (order by t.ID) as Rbr
from dbo.Table1 t
    inner join (
        select
            t.ColA
        from dbo.Table1 t
        group by t.ColA
        having COUNT (t.ID) > 1
    ) tt on t.ColA = tt.ColA
) ttt
where ttt.Rbr > 1

update t2
set
Table1ID = t1i.ID
from #temp t
inner join dbo.Table2 t2 on t.ID = t2.Table1ID
inner join dbo.Table1 t1 on t.ID = t1.ID
inner join dbo.Table1 t1i on t1.ColA = t1i.ColA
        and t1i.ID not in (select t.ID from #temp t)

delete t1
from #temp t
inner join dbo.Table1 t1 on t.ID = t1.ID

select
*
from dbo.Table1 t

select
*
from dbo.Table2 t
</code>```

Body:
I have two tables:

 Table1:
 [id], [ColA]

 Table2:
 [id], [Table1Id]

A previous update caused duplicates in Table1 and those duplicates to be assocated with rows in Table2.  It looks like this in the db:

Table1
1, 89
2, 89

Table2
6, 1
7, 2

I would like to delete the duplicates and reassign the value of the Table2.Table1Id to the one Table1.id row that should be left.  Is this possible in a single statement?  Ive seen this post on how to delete all but one, but I am lost on how to reassign the Table2.Table1Id value.

edit:
 The end result should look like this:

Table1
2, 89

Table2
6, 2
7, 2


问:
I can't get iframe to get data from textarea
I am trying to make an iframe which shows text putted in the textarea.

How can I do that? Am I missing something here?

```<code><html>
<head>
    <title>Code Player</title>
    <script type="text/javascript" src="jquery.min.js"></script>
    <!--i am using the latest jquery-->
    <style type="text/css">
        body{
            font-family: sans-serif;
            margin: 0;
            padding: 0;
        }
        #header{
            width: 100%;
            background-color: #EEEEEE;
            padding: 5px;
            height: 30px;
        }
        #logo{
            float: left;
            font-weight: bold;
            font-size: 120%;
            padding: 3px 5px;
        }
        #buttonContainer{
            width: 240px;
            margin: 0 auto;
        }
        .toggleButton{
            float: left;
            border: 1px solid gray;
            padding: 6px;
            border-right: none;
            font-size: 90%;
        }
        #html{
            border-top-left-radius: 4px;
            border-bottom-left-radius: 4px;
        }
        #output{
            border-top-right-radius: 4px;
            border-bottom-right-radius: 4px;
            border-right: 1px solid gray;
        }
        .active{
            background-color: #E8F2FF;
        }
        .highlightedButton{
            background-color: gray;
        }
        textarea{
            resize: none;
            border-top: none;
            border-color: gray;
        }
        .panel{
            float: left;
            width: 49%;
            border-left: none;
        }
        iframe{
            border: none;
        }
    </style>
</head>
<body>
    <div id="header">
        <div id="logo">
            CodePlayer
        </div>
        <div id="buttonContainer">
            <div class="toggleButton active" id="html">HTML</div>
            <div class="toggleButton" id="css">CSS</div>
            <div class="toggleButton" id="javascript">JavaScript</div>
            <div class="toggleButton active" id="output">Output</div>
        </div>

    </div>
    <div id="bodyContainer">
<!--I want to get iframe data from the textarea section-->
        <textarea id="htmlPanel" class="panel">Hello World!</textarea>
        <iframe id="outputPanel" class="panel"></iframe>
    </div>
    <script type="text/javascript">
        $(".toggleButton").hover(function () {
            $(this).addClass("highlightedButton");
        }, function () {
            $(this).removeClass("highlightedButton");
        });
        $(".toggleButton").click(function () {
            $(this).toggleClass("active");
            $(this).removeClass("highlightedButton");
        });
        $(".panel").height($(window).height() - $("#header").height() - 15);
        $(".panel").width($((window).width() / 2));
        $("iframe").contents().find("html").html($("#htmlPanel").val());

        $("textarea").on('change keyup paste', function() {
            $("iframe").contents().find("html").html($("#htmlPanel").val());
        });
    </script>
</body>
</html>
</code>```

Everything in this code works expect the iframe. I can't get the data from textarea.

答:
You have a syntax error, otherwise it works fine.  Demo

$(".panel").width($((window).width() / 2));

should be

$(".panel").width($(window).width() / 2);

Body:
I am trying to make an iframe which shows text putted in the textarea.

How can I do that? Am I missing something here?

    <title>Code Player</title>

            CodePlayer

HTML

CSS

JavaScript

Output

        <textarea id="htmlPanel" class="panel">Hello World!</textarea>

Everything in this code works expect the iframe. I can't get the data from textarea.


问:
what is the springframework version dependency in spring-kafka master
I'm getting the impression that spring-kafka 2.0.0.BUILD-SNAPSHOT requires a build snapshot of the basic spring framework in order to run. is this true?

When I run code compiled against it, it errors out during initialization due to a call to Assert(expr, Supplier), which doesn't exist in the most up to date release of springframework.  I have to look at the master branch to find a version of Assert.java that can take a Function instead of a string.  (called from MessagingMessageListenerAdapter.java:387 in spring-kafka)

The difference between

```<code>Assert.state(expr, String.format("error message: %s", myVar))
</code>```

and

```<code>Assert.state(expr, () -> {
  return String.format("error message: %s", myVar);
});
</code>```

is a pretty darn small optimization - especially in code that only executes during initialization rather than for every incoming message.  Would it not make sense to keep dependencies on unreleased code to an absolute minimum so that spring-kafka doesn't end up in the position of being unable to release because it relies on an unreleased version of springframework itself?

I don't mind a dependence on spring-kafka that is not quite released, since that's a small codebase that I can isolate within my own, if need be.  But if it forces a snapshot of the entirety of spring on me, there's no way I can consider using it, which means the project then doesn't benefit from bugs I uncover and/or fix on its way to production release.

答:
2.0.0 requires Spring Framework 5.0.

1.2.2.BUILD-SNAPSHOT and 1.1.6.BUILD-SNAPSHOT are available for older Spring releases.

1.2.2 and 1.1.6 should be relased today.

Body:
I'm getting the impression that spring-kafka 2.0.0.BUILD-SNAPSHOT requires a build snapshot of the basic spring framework in order to run. is this true?

When I run code compiled against it, it errors out during initialization due to a call to Assert(expr, Supplier), which doesn't exist in the most up to date release of springframework.  I have to look at the master branch to find a version of Assert.java that can take a Function instead of a string.  (called from MessagingMessageListenerAdapter.java:387 in spring-kafka)

The difference between

Assert.state(expr, String.format("error message: %s", myVar))

and

Assert.state(expr, () -> {
  return String.format("error message: %s", myVar);
});

is a pretty darn small optimization - especially in code that only executes during initialization rather than for every incoming message.  Would it not make sense to keep dependencies on unreleased code to an absolute minimum so that spring-kafka doesn't end up in the position of being unable to release because it relies on an unreleased version of springframework itself?

I don't mind a dependence on spring-kafka that is not quite released, since that's a small codebase that I can isolate within my own, if need be.  But if it forces a snapshot of the entirety of spring on me, there's no way I can consider using it, which means the project then doesn't benefit from bugs I uncover and/or fix on its way to production release.


问:
How to determine count of a value in a column based on constraints?
I have a large dataset and I was wondering how to calculate the most common occurrences of a certain attribute's value.

For instance, let's say I have a hypothetical table called Cats. I insert the following values into it:

```<code>Create table Cats (Cat_ID int, Cat_name varchar(max), Cat_Hometown varchar(max), Gender varchar(max), Birth_Year int)

INSERT INTO CATS (Cat_ID, Cat_Name, Cat_Hometown, Gender, Birth_year)
VALUES (1, 'Blue','Boston','M', 1980),
(2, 'Steamer','Plymouth','F', 1999),
(3, 'Stack','Newton','F', 1980),
(4, 'Overflow','Boston','M', 1978),
(5, 'CatorDog','Allston','F', 1999);
</code>```

What if I want to determine the most common city for female cats in the year 1980? How would I do so? I can't seem to wrap my head around it.

答:
You can try the below query to do so.

select Cat_Hometown, count(Cat_Hometown) as Cats_Count from Cats where gender='F' and Birth_year=1980 group by Cat_Hometown order by count(Cat_Hometown) desc limit 1;

:)

Body:
I have a large dataset and I was wondering how to calculate the most common occurrences of a certain attribute's value.

For instance, let's say I have a hypothetical table called Cats. I insert the following values into it:

Create table Cats (Cat_ID int, Cat_name varchar(max), Cat_Hometown varchar(max), Gender varchar(max), Birth_Year int)

INSERT INTO CATS (Cat_ID, Cat_Name, Cat_Hometown, Gender, Birth_year)
VALUES (1, 'Blue','Boston','M', 1980),
(2, 'Steamer','Plymouth','F', 1999),
(3, 'Stack','Newton','F', 1980),
(4, 'Overflow','Boston','M', 1978),
(5, 'CatorDog','Allston','F', 1999);

What if I want to determine the most common city for female cats in the year 1980? How would I do so? I can't seem to wrap my head around it.


问:
Logical Operators not subsetting as expected
I am trying to create a subset of the rows that have a value of 1 for variable A, and a value of 1 for at least one of the following variables: B, C, or D.

```<code>Subset1 <-  subset(Data,
              Data$A==1 &
                Data$B ==1  ||
                Data$C ==1 |
                Data$D == 1,
              select= A)
Subset1
</code>```

The problem is that the code above returns some  rows that have A=0 and I am not sure why.

To troublehsoot:

I know that && and || are the long forms or and and or which vectorizes it.
I have run this code several times using  &&,  ||,& and | in different places. Nothing returns what I am looking for exactly.

When I shorten the code, it works fine and I subset only the rows that I would expect:

Subset1 <- subset(Data,
                       Data$A==1 &
                       Data$B==0,
                      select= A)

Subset1

Unfortunately, this doesn't suffice since I also need to capture rows whose C or D value = 1.
Can anyone explain why my first code block is not subsetting what I am expecting it to?

答:
Since you didn't provide the data you're working with, I've replicated some here.

```<code>set.seed(20)
Data = data.frame(A = sample(0:1, 10, replace=TRUE),
                  B = sample(0:1, 10, replace=TRUE),
                  C = sample(0:1, 10, replace=TRUE),
                  D = sample(0:1, 10, replace=TRUE))
</code>```

If you use parenthesis, which can evaluate to a logical function, you can achieve what you're looking for.

```<code>Subset1 <- subset(Data,
                  Data$A==1 &
                    (Data$B == 1 |
                    Data$C == 1 |
                    Data$D ==1),
                  select=A)
Subset1
  A
1 1
2 1
4 1
5 1
</code>```

Body:
I am trying to create a subset of the rows that have a value of 1 for variable A, and a value of 1 for at least one of the following variables: B, C, or D.

Subset1 <-  subset(Data,
              Data$A==1 &
                Data$B ==1  ||
                Data$C ==1 |
                Data$D == 1,
              select= A)
Subset1

The problem is that the code above returns some  rows that have A=0 and I am not sure why.

To troublehsoot:

I know that && and || are the long forms or and and or which vectorizes it.
I have run this code several times using  &&,  ||,& and | in different places. Nothing returns what I am looking for exactly.

When I shorten the code, it works fine and I subset only the rows that I would expect:

Subset1 <- subset(Data,
                       Data$A==1 &
                       Data$B==0,
                      select= A)

Subset1

Unfortunately, this doesn't suffice since I also need to capture rows whose C or D value = 1.
Can anyone explain why my first code block is not subsetting what I am expecting it to?

Body:
Since you didn't provide the data you're working with, I've replicated some here.

set.seed(20)
Data = data.frame(A = sample(0:1, 10, replace=TRUE),
                  B = sample(0:1, 10, replace=TRUE),
                  C = sample(0:1, 10, replace=TRUE),
                  D = sample(0:1, 10, replace=TRUE))

If you use parenthesis, which can evaluate to a logical function, you can achieve what you're looking for.

Subset1 <- subset(Data,
                  Data$A==1 &
                    (Data$B == 1 |
                    Data$C == 1 |
                    Data$D ==1),
                  select=A)
Subset1
  A
1 1
2 1
4 1
5 1


问:
How do I prevent replay attacks?
This is related to another question I asked. In summary, I have a special case of a URL where, when a form is POSTed to it, I can't rely on cookies for authentication or to maintain the user's session, but I somehow need to know who they are, and I need to know they're logged in!

I think I came up with a solution to my problem, but it needs fleshing out. Here's what I'm thinking. I create a hidden form field called "username", and place within it the user's username, encrypted. Then, when the form POSTs, even though I don't receive any cookies from the browser, I know they're logged in because I can decrypt the hidden form  field and get the username.

The major security flaw I can see is replay attacks. How do I prevent someone from getting ahold of that encrypted string, and POSTing as that user? I know I can use SSL to make it harder to steal that string, and maybe I can rotate the encryption key on a regular basis to limit the amount of time that the string is good for, but I'd really like to find a bulletproof solution. Anybody have any ideas? Does the ASP.Net ViewState prevent replay? If so, how do they do it?

Edit: I'm hoping for a solution that doesn't require anything stored in a database. Application state would be okay, except that it won't survive an IIS restart or work at all in a web farm or garden scenario. I'm accepting Chris's answer, for now, because I'm not convinced it's even possible to secure this without a database. But if someone comes up with an answer that does not involve the database, I'll accept it!

答:
Can you use memory or a database to maintain any information about the user or request at all?

If so, then on request for the form, I would include a hidden form field whose contents are a randomly generated number. Save this token to in application context or some sort of store (a database, flat file, etc.) when the request is rendered. When the form is submitted, check the application context or database to see if that randomly generated number is still valid (however you define valid - maybe it can expire after X minutes). If so, remove this token from the list of "allowed tokens".

Thus any replayed requests would include this same token which is no longer considered valid on the server.

OwnerDisplayName: Josh Hinman

Title: How do I prevent replay attacks?

LastEditorDisplayName: Josh Hinman

OwnerDisplayName: matt b


问:
What is the best way to write a contract for CSS usage in Web Development?
Our Dev team had been developing enterprise web page more than 2 years ago.  We are curious to know what is the best way to write a contract for CSS usage.  For example, if we have a COMP, how we agree on a contract so our developers and our designers agree and we don't have to go back.

Is there a tool that is available for this type of technical writing?

What is the threadhold of information put in the CSS versus on the HTML page?  Some of our designers thing that some things should go directly into the HTML page.  The general opinion is that everything that is style should go in a CSS and all else in the html.

Thanks for your input.

答:
I'm a purist, so for me HTML is for content and structure and CSS is for layout & styling. That's really what each of them were created for.

See CSS Zen Garden for a great example of this. Same HTML and hundreds of different layouts & designs.

What are the reasons your designers give for styling to be in the HTML?

Edit: The main goal here is consistency across the site, correct? The more you have abstracted away from each page, the fewer changes you'll have to make.

OwnerDisplayName: Geo

OwnerDisplayName: Nathan


问:
Blurred UIImageView Sizing Problems
A UIViewController I'm presenting has a UIImageView, namely backgroundImageView, to be the VC's background and set to fill the whole screen.

I want the UIImageView to be presented with a dark blur effect provided by iOS but the following sizing issue temporarily occurs(on device but not on the simulator) when I first present the view controller:

Inside viewDidLoad():

```<code>// `locationImage` is passed during the segue
backgroundImageView.image = locationImage
backgroundImageView.contentMode = .scaleAspectFill

let blurEffect = UIBlurEffect(style: .dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = backgroundImageView.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
backgroundImageView.addSubview(blurEffectView)
</code>```

The above view controller's modalPresentationStyle is set to be as currentContext.

If I temporarily remove the blur effect, I see that the background image I gave the view controller got properly set. However once the blur effect is applied, sizing issues occur momentarily.

What exactly is causing this?

答:
Try to set the frame of blurEffectView inside viewWillLayoutSubviews() or in viewDidLayoutSuviews()

here you can find more information  about viewcontroller's lifecycle

Title: Blurred UIImageView Sizing Problems

Body:
A UIViewController I'm presenting has a UIImageView, namely backgroundImageView, to be the VC's background and set to fill the whole screen.

I want the UIImageView to be presented with a dark blur effect provided by iOS but the following sizing issue temporarily occurs(on device but not on the simulator) when I first present the view controller:

Inside viewDidLoad():

// `locationImage` is passed during the segue
backgroundImageView.image = locationImage
backgroundImageView.contentMode = .scaleAspectFill

let blurEffect = UIBlurEffect(style: .dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = backgroundImageView.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
backgroundImageView.addSubview(blurEffectView)

The above view controller's modalPresentationStyle is set to be as currentContext.

If I temporarily remove the blur effect, I see that the background image I gave the view controller got properly set. However once the blur effect is applied, sizing issues occur momentarily.

What exactly is causing this?


问:
How to write a dynamic string replacement in git bash?
This is on Windows 10 using the Linuxy environment provided with Git Bash.

I have this line in my target source file:

```<code>'version' => 'v1.1.023',
</code>```

I have this function in my ~/.bash_profile:

```<code>function tag() {
    ....
    tagname="$1"
    cmd="s:v[0-9]\\.[0-9]\\.[0-9]+:$tagname:g;"
    perl -p -i -e "$cmd" config/app.php
    ...
}
</code>```

When I run the command:

```<code>$ tag v.1.1.024
</code>```

The string is not replaced, therefore the version is not updated in my code. I tried a very similar script with sed instead of perl. The file isn't getting changed. I tried the same perl replacement syntax on CentOS and it worked. Note that the double-backslash appears to be required in order for the command to work on the next line when it's run in perl. That is to say, the variable string representation of the command has a double backslash so that it becomes a literal "." in the replacement.

Any ideas?

答:
Hi @phpguru I would follow the KISS principle.

Using sed and avoiding perl

6.3. When should I use sed?

When you need a small, fast program to modify words, lines, or blocks
  of lines in a textfile.

```<code>function tag() {
    tagname="$1"
    sed -i -e "s:v[0-9]\.[0-9]\.[0-9]\+:$tagname:g" test.php
}
</code>```

Output in my environment:

```<code>m.ortiz.montealegre@CPX-XYR3G1DTHBU MINGW64 ~
$ cat .bash_profile
function tag() {

    tagname="$1"
    sed -i -e "s:v[0-9]\.[0-9]\.[0-9]\+:$tagname:g" test.php
}

m.ortiz.montealegre@CPX-XYR3G1DTHBU MINGW64 ~
$ cat test.php
'version' => 'v1.1.023,

m.ortiz.montealegre@CPX-XYR3G1DTHBU MINGW64 ~
$ tag v1.1.024

m.ortiz.montealegre@CPX-XYR3G1DTHBU MINGW64 ~
$ cat test.php
'version' => 'v1.1.024,
</code>```

Body:
This is on Windows 10 using the Linuxy environment provided with Git Bash.

I have this line in my target source file:

'version' => 'v1.1.023',

I have this function in my ~/.bash_profile:

function tag() {
    ....
    tagname="$1"
    cmd="s:v[0-9]\\.[0-9]\\.[0-9]+:$tagname:g;"
    perl -p -i -e "$cmd" config/app.php
    ...
}

When I run the command:

$ tag v.1.1.024

The string is not replaced, therefore the version is not updated in my code. I tried a very similar script with sed instead of perl. The file isn't getting changed. I tried the same perl replacement syntax on CentOS and it worked. Note that the double-backslash appears to be required in order for the command to work on the next line when it's run in perl. That is to say, the variable string representation of the command has a double backslash so that it becomes a literal "." in the replacement.

Any ideas?

Body:
Hi @phpguru I would follow the KISS principle.

Using sed and avoiding perl

6.3. When should I use sed?

When you need a small, fast program to modify words, lines, or blocks
  of lines in a textfile.

function tag() {
    tagname="$1"
    sed -i -e "s:v[0-9]\.[0-9]\.[0-9]\+:$tagname:g" test.php
}

Output in my environment:

m.ortiz.montealegre@CPX-XYR3G1DTHBU MINGW64 ~
$ cat .bash_profile
function tag() {

    tagname="$1"
    sed -i -e "s:v[0-9]\.[0-9]\.[0-9]\+:$tagname:g" test.php
}

m.ortiz.montealegre@CPX-XYR3G1DTHBU MINGW64 ~
$ cat test.php
'version' => 'v1.1.023,

m.ortiz.montealegre@CPX-XYR3G1DTHBU MINGW64 ~
$ tag v1.1.024

m.ortiz.montealegre@CPX-XYR3G1DTHBU MINGW64 ~
$ cat test.php
'version' => 'v1.1.024,


答: From the docs "Return True if the float instance is finite with integral value, and False otherwise". Only zeroes in decimal places makes it return true as an integer.</p>

Title: Is_Integer returning incorrect result - Python 2.X


问:
Mock final class with Mockito 2
I'm removing Powermock from the project I'm currently working on, so I'm trying to rewrite some existing unitary test only with Mockito (mockito-core-2.2.28).

When I run the test, I have the following error:

org.mockito.exceptions.base.MockitoException:

Cannot mock/spy class com.ExternalpackagePath.Externalclass

Mockito cannot mock/spy because :

final class

I know that this question has already been asked (How to mock a final class with mockito, Mock objects calling final classes static methods with Mockito), but I didn't find the answer I'm looking for.

Here is an extract of my code :

```<code>public class MyClassToTest extends TestCase {
    private MyClass myClass;
    @Mock private Externalclass ext;  // This class is final, I would like to mock it

    @Override
    protected void setUp() throws Exception {
        MockitoAnnotations.initMocks(this); // <<<< The exception is thrown here
        ext = Mockito.mock(Externalclass.class);
    }
}
</code>```

As mentioned in the Mockito documentation (https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2, §Mock the unmockable), I added the org.mockito.plugins.MockMaker file. This is the tree of my project :

project

src

com.packagePath.myPackage

myClass

test

com.packagePath.myPackage

myClassToTest

resources

mockito-extensions

org.mockito.plugins.MockMaker

I also tries to put the "resources" directory in "src", in a subdir called "test", but the result is still the same.

I thought that mocking a final was possible with Mockito v2. Does someone have an idea of what is missing here ?

Thanks!

答:
I couldn't get it working with the configuration file either; however, the Mockito team is so kind and also provides a pre-configured Mockito artifact that requires no configuration in the target project.

As a convenience, the Mockito team provides an artifact where this mock maker is preconfigured. Instead of using the mockito-core artifact, include the mockito-inline artifact in your project. Note that this artifact is likely to be discontinued once mocking of final classes and methods gets integrated into the default mock maker.

So, if you use Gradle and want to test your Kotlin code, just add this to your project's dependencies:

```<code>testCompile 'org.mockito:mockito-inline:2.8.9'
testCompile('com.nhaarman:mockito-kotlin:1.5.0') {
    exclude group: 'org.jetbrains.kotlin'
    exclude group: 'org.mockito'
}
</code>```

Title: Mock final class with Mockito 2

Body:
I'm removing Powermock from the project I'm currently working on, so I'm trying to rewrite some existing unitary test only with Mockito (mockito-core-2.2.28).

When I run the test, I have the following error:

org.mockito.exceptions.base.MockitoException:

Cannot mock/spy class com.ExternalpackagePath.Externalclass

Mockito cannot mock/spy because :

final class

I know that this question has already been asked (How to mock a final class with mockito, Mock objects calling final classes static methods with Mockito), but I didn't find the answer I'm looking for.

Here is an extract of my code :

public class MyClassToTest extends TestCase {
    private MyClass myClass;
    @Mock private Externalclass ext;  // This class is final, I would like to mock it

    @Override
    protected void setUp() throws Exception {
        MockitoAnnotations.initMocks(this); // <<<< The exception is thrown here
        ext = Mockito.mock(Externalclass.class);
    }
}

As mentioned in the Mockito documentation (https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2, §Mock the unmockable), I added the org.mockito.plugins.MockMaker file. This is the tree of my project :

project

src

com.packagePath.myPackage

myClass

test

com.packagePath.myPackage

myClassToTest

resources

mockito-extensions

org.mockito.plugins.MockMaker

I also tries to put the "resources" directory in "src", in a subdir called "test", but the result is still the same.

I thought that mocking a final was possible with Mockito v2. Does someone have an idea of what is missing here ?

Thanks!

Body:
I couldn't get it working with the configuration file either; however, the Mockito team is so kind and also provides a pre-configured Mockito artifact that requires no configuration in the target project.

As a convenience, the Mockito team provides an artifact where this mock maker is preconfigured. Instead of using the mockito-core artifact, include the mockito-inline artifact in your project. Note that this artifact is likely to be discontinued once mocking of final classes and methods gets integrated into the default mock maker.

So, if you use Gradle and want to test your Kotlin code, just add this to your project's dependencies:

testCompile 'org.mockito:mockito-inline:2.8.9'
testCompile('com.nhaarman:mockito-kotlin:1.5.0') {
    exclude group: 'org.jetbrains.kotlin'
    exclude group: 'org.mockito'
}


问:
Converting an ArrayList<someObjects> to an HTML table
I have a couple of ArrayLists with variable length and sometimes null. This ArrayList contains a bunch of objects.
The table should have columns based on (some) attributes of the object. And the table should be displayed on a jsp.

I have two ideas, one is to use a JSTL tag the other is to use JavaScript. And library suggestions are welcome.

答:
Javascript doesn't have access to the Java objects that live (I presume) on the server. The server code can make the ArrayLists available to the JSP which can then loop over them with a JSTL forEach tag.

How you make the ArrayLists "available" depends on the framework you're using, but the plain servlet way is just setting an attribute from the doPost method.

```<code>request.setAttribute("list1", arrayList1);
</code>```

The loop would be something like

```<code><table>
<tr><th>Column 1</th> <th>Column 2</th> <th>Column 3</th></tr>
<c:forEach var="row" items="${list1}">
    <tr><td>${row.col1data}</td> <td>${row.col2data}</td> <td>${row.col3data}</td></tr>
</c:forEach>
</table>
</code>```

Body:
Javascript doesn't have access to the Java objects that live (I presume) on the server. The server code can make the ArrayLists available to the JSP which can then loop over them with a JSTL forEach tag.

How you make the ArrayLists "available" depends on the framework you're using, but the plain servlet way is just setting an attribute from the doPost method.

request.setAttribute("list1", arrayList1);

The loop would be something like

<table>
<tr><th>Column 1</th> <th>Column 2</th> <th>Column 3</th></tr>
<c:forEach var="row" items="${list1}">
    <tr><td>${row.col1data}</td> <td>${row.col2data}</td> <td>${row.col3data}</td></tr>
</c:forEach>
</table>


问:
use text-align smartly (if english dir=ltr if arabic dir=rtl)
I have a community web site and I want that users write

English posts with direction LTR / text-align: left) and

Arabic posts with direction RTL / text-align: right.

E.g. Google+ and twitter provides such an POST solution.

I want add automatically direction  attribute to post when i read it from data base post load in rtl or ltr ! but i don't know how ?!

答:
it's very easy. You can use dir='auto' Attribiute in Html Element. So if your text is Arabic or Persian Text use RTL and if your text is English automatic text use LTR.</p>

```<code><p dir='auto'>Hello</p>
<p dir='auto'>سلام</p>
</code>```

Body:
it's very easy. You can use dir='auto' Attribiute in Html Element. So if your text is Arabic or Persian Text use RTL and if your text is English automatic text use LTR.

<p dir='auto'>Hello</p>
<p dir='auto'>سلام</p>


问:
Display WooCommerce Flat Rate Shipping Options on Cart page
I'm building a WooCommerce site and I have a need to display shipping options on the cart page vs the checkout page.

Shipping is flat rate across a single country and not dependent on user location.

Is there a way to accomplish this task?

Cheers!

答:
Go to the General tab in Woocommerce Settings.

Set the shop base address to be the Default Customer Location

If you only have a flat rate and your shop's base address is under it, that's the one that will be displayed by default.


问:
C++ how to check if among N objects some of them are equal
I have some C++ objects and I would like to check if some of them are equal.

```<code>bool IsEqual(const Board& b)
{
    if( b.From() != from_ )
        return false;

    if (b.To() != to_ )
        return false;

    if( b.Selection() != selection_ )
        return false;

    return true;
}
</code>```

My objects consist of some integers ( from_, to_, selection_) and the class offers the IsEqual method to compare two objects.

calling obj1.IsEqual(obj2) returns true if both objects have the same values.

However how do I compare N objects? Is it possible to push_back objects to an std::vector<Board> and use std::unique?

答:
Put the objects in a set. After you're done the set will contain only unique objects.

You can choose between std::set and std::unordered_set, depending on how many objects you have and the cost of the compare function.

std::set requires a compare function (operator<). O(N*logN) complexity.

std::unordered_set requires a hash and equality functions (std::equal_to taking 2 const references to your object and std::hash taking in a const reference to an object). O(N) complexity.

NB. A double-nested loop is going to be O(N2) complexity.

NB2. std::unique requires the vector to be sorted, as it compares only adjacent elements.

Example compare function:

```<code>    bool operator< (const Board& b) const {
        if (from_ < b.from_)
            return true;
        if (from_ > b.from_)
            return false;
        if (to_ < b.to_)
            return true;
        if (to_ > b.to_)
            return false;
        if (selection_ < b.selection_)
            return true;
        return false;
    }
</code>```

Body:
I have some C++ objects and I would like to check if some of them are equal.

bool IsEqual(const Board& b)
{
    if( b.From() != from_ )
        return false;

    if (b.To() != to_ )
        return false;

    if( b.Selection() != selection_ )
        return false;

    return true;
}

My objects consist of some integers ( from_, to_, selection_) and the class offers the IsEqual method to compare two objects.

calling obj1.IsEqual(obj2) returns true if both objects have the same values.

However how do I compare N objects? Is it possible to push_back objects to an std::vector<Board> and use std::unique?

Body:
Put the objects in a set. After you're done the set will contain only unique objects.

You can choose between std::set and std::unordered_set, depending on how many objects you have and the cost of the compare function.

std::set requires a compare function (operator<). O(N*logN) complexity.

std::unordered_set requires a hash and equality functions (std::equal_to taking 2 const references to your object and std::hash taking in a const reference to an object). O(N) complexity.

NB. A double-nested loop is going to be O(N2) complexity.

NB2. std::unique requires the vector to be sorted, as it compares only adjacent elements.

Example compare function:

    bool operator< (const Board& b) const {
        if (from_ < b.from_)
            return true;
        if (from_ > b.from_)
            return false;
        if (to_ < b.to_)
            return true;
        if (to_ > b.to_)
            return false;
        if (selection_ < b.selection_)
            return true;
        return false;
    }


问:
IPv6 App Store Rejection
Our update has been rejected twice today for ipv6 network connectivity issues. Our networking code has not changed between the previous release and this current release.

The app only makes https network requests to api.metooapp.io, which is correctly configured for ipv6 [0] and runs behind route53 on AWS. There are no hard-coded IP addresses in the code.

I am unable to reproduce this issue, even after following the steps to create an ipv6 network at [1] which is the link that was provided in the rejection notice. It looks like I'm not the only one experiencing this issue, either [2].

答:
I ran into the same app rejection when using the Facebook SDK. If you are using the Facebook SDK for login, it is incredibly important to logout the user when ending a session. Otherwise you will face similar app rejections in the future. I have included the code below to help those who may be experiencing similar issues.</p>

```<code>let loginManager = FBSDKLoginManager()
loginManager.logOut()
</code>```

Title: IPv6 App Store Rejection

Body:
I ran into the same app rejection when using the Facebook SDK. If you are using the Facebook SDK for login, it is incredibly important to logout the user when ending a session. Otherwise you will face similar app rejections in the future. I have included the code below to help those who may be experiencing similar issues.

let loginManager = FBSDKLoginManager()
loginManager.logOut()


问:
netCDF files in R
I have netCDF file obtained from here with name precip.mon.total.v6.nc. I am using ncdf package in R to open and analyse the file.

```<code> new <- open.ncdf("precip.mon.total.v6.nc")
    > new
    [1] "file precip.mon.total.v6.nc has 4 dimensions:"
    [1] "lat   Size: 360"
    [1] "lon   Size: 720"
    [1] "nbnds   Size: 2"
    [1] "time   Size: 1320"
    [1] "------------------------"
    [1] "file precip.mon.total.v6.nc has 1 variables:"
    [1] "float precip[lon,lat,time]  Longname:GPCC Monthly total of     precipitation Missval:-9.96920996838687e+36"
</code>```

But when I extract the variable, I got the error

```<code>      > get.var.ncdf(new, "precip")
Error: cannot allocate vector of size 2.5 Gb
In addition: Warning messages:
1: In double(totvarsize) :
  Reached total allocation of 2047Mb: see help(memory.size)
2: In double(totvarsize) :
  Reached total allocation of 2047Mb: see help(memory.size)
3: In double(totvarsize) :
  Reached total allocation of 2047Mb: see help(memory.size)
4: In double(totvarsize) :
  Reached total allocation of 2047Mb: see help(memory.size)
</code>```

My queries are:
         (a) How to handle memory issue?
         (b) How can I change the resolution of this netCDF file from 0.5*0.5 to 0.25*0.25 data? I have tried the similar problem in MATLAB. It can tackle memory issue better than R for netCDF files. But changing resolution is still a problem as I am not good at MATLAB. I will be very thankful for any help in this direction.

答:
(a) memory:

If on a linux box [sudo apt-get install cdo] (or also windows with cygwin installed) you can use cdo to help you out.

For example, if you are only interested in a specific date you can select that first to keep the file size down:

```<code>cdo seldate,date in.nc out.nc
</code>```

or you might have wanted to view the time mean:

```<code>cdo timmean in.nc out.nc
</code>```

That will keep the file size down, and you can then open it in R to make your plot (or use ncview for a quickview investigation).

(b) remapping

cdo can also interpolate the file to 0.25 degrees, (although I am not sure why you would want to do this, as you are not adding any information and you are making the files four times larger!!!)

```<code>cdo remapcon,r1440x720 in.nc out.nc
</code>```

or

```<code>cdo remapnn,r1440x720 in.nc out.nc
</code>```

But as I said, if you want to interpolate to compare to another 0.25 degree product (e.g. TRMM), better to go the other way and interpolate the finer dataset to 0.5 degree.

By the way, in 2015, v7 was released of GPCC, still at 0.5 degree.

Title: netCDF files in R

Body:
I have netCDF file obtained from here with name precip.mon.total.v6.nc. I am using ncdf package in R to open and analyse the file.

 new <- open.ncdf("precip.mon.total.v6.nc")
    > new
    [1] "file precip.mon.total.v6.nc has 4 dimensions:"
    [1] "lat   Size: 360"
    [1] "lon   Size: 720"
    [1] "nbnds   Size: 2"
    [1] "time   Size: 1320"
    [1] "------------------------"
    [1] "file precip.mon.total.v6.nc has 1 variables:"
    [1] "float precip[lon,lat,time]  Longname:GPCC Monthly total of     precipitation Missval:-9.96920996838687e+36"

But when I extract the variable, I got the error

      > get.var.ncdf(new, "precip")
Error: cannot allocate vector of size 2.5 Gb
In addition: Warning messages:
1: In double(totvarsize) :
  Reached total allocation of 2047Mb: see help(memory.size)
2: In double(totvarsize) :
  Reached total allocation of 2047Mb: see help(memory.size)
3: In double(totvarsize) :
  Reached total allocation of 2047Mb: see help(memory.size)
4: In double(totvarsize) :
  Reached total allocation of 2047Mb: see help(memory.size)

My queries are:
         (a) How to handle memory issue?
         (b) How can I change the resolution of this netCDF file from 0.5*0.5 to 0.25*0.25 data? I have tried the similar problem in MATLAB. It can tackle memory issue better than R for netCDF files. But changing resolution is still a problem as I am not good at MATLAB. I will be very thankful for any help in this direction.

Body:
(a) memory:

If on a linux box [sudo apt-get install cdo] (or also windows with cygwin installed) you can use cdo to help you out.

For example, if you are only interested in a specific date you can select that first to keep the file size down:

cdo seldate,date in.nc out.nc

or you might have wanted to view the time mean:

cdo timmean in.nc out.nc

That will keep the file size down, and you can then open it in R to make your plot (or use ncview for a quickview investigation).

(b) remapping

cdo can also interpolate the file to 0.25 degrees, (although I am not sure why you would want to do this, as you are not adding any information and you are making the files four times larger!!!)

cdo remapcon,r1440x720 in.nc out.nc

or

cdo remapnn,r1440x720 in.nc out.nc

But as I said, if you want to interpolate to compare to another 0.25 degree product (e.g. TRMM), better to go the other way and interpolate the finer dataset to 0.5 degree.

By the way, in 2015, v7 was released of GPCC, still at 0.5 degree.


问:
How can I draw two impulses plot in gnuplot using a rowstacked option?
I am trying to plot an impulses plot and this is my current script:

```<code>set terminal pngcairo transparent enhanced font "arial,10" fontscale 1.0 size 500, 350
set output 'test.png'
set key bmargin left horizontal Right noreverse enhanced autotitles box linetype -1 linewidth 1.000
plot 'example.csv' using 2:xtic(1) title col with impulses lw 15, \
                '' using 3:xtic(1) title col with impulses lw 15, \
                '' using 4:xtic(1) title col with impulses lw 15
</code>```

The data input is:

```<code>var basis out1 out2
param1 0.1 0.3 0.5
param2 -0.1 0.4 -0.6
param3 0.4 0.6 0.8
param4 -0.4 -0.5 -0.6
param -0.1 0.0 0.1
</code>```

And this is the current output:

gnuplot example.gnu

So I was trying to stack the bars in a row position similar to an option for histograms (set style histogram rowstacked), but I was unsuccessful.

The example for what I want with histograms would be:

Is there something similar for impulses plot?

答:
If you want to have a rowstacked histogram, why don't you simply use one? With

```<code>set style data histogram
</code>```

you set histogram as global plotting style for all plots, and with

```<code>set style histogram rowstacked clustered
</code>```

you get clustering of all values in a row. A full example script (with some visual enhancements) is:

```<code>reset
set style data histogram
set style histogram rowstacked clustered gap 2
set boxwidth 0.9 relative
set style fill solid noborder
set key auto columnheader tmargin horizontal Right
set xzeroaxis
plot for [i=2:4] 'example.csv' u i:xtic(1)
</code>```

with the output

Body:
I am trying to plot an impulses plot and this is my current script:

set terminal pngcairo transparent enhanced font "arial,10" fontscale 1.0 size 500, 350
set output 'test.png'
set key bmargin left horizontal Right noreverse enhanced autotitles box linetype -1 linewidth 1.000
plot 'example.csv' using 2:xtic(1) title col with impulses lw 15, \
                '' using 3:xtic(1) title col with impulses lw 15, \
                '' using 4:xtic(1) title col with impulses lw 15

The data input is:

var basis out1 out2
param1 0.1 0.3 0.5
param2 -0.1 0.4 -0.6
param3 0.4 0.6 0.8
param4 -0.4 -0.5 -0.6
param -0.1 0.0 0.1

And this is the current output:

gnuplot example.gnu

So I was trying to stack the bars in a row position similar to an option for histograms (set style histogram rowstacked), but I was unsuccessful.

The example for what I want with histograms would be:

Is there something similar for impulses plot?

Body:
If you want to have a rowstacked histogram, why don't you simply use one? With

set style data histogram

you set histogram as global plotting style for all plots, and with

set style histogram rowstacked clustered

you get clustering of all values in a row. A full example script (with some visual enhancements) is:

reset
set style data histogram
set style histogram rowstacked clustered gap 2
set boxwidth 0.9 relative
set style fill solid noborder
set key auto columnheader tmargin horizontal Right
set xzeroaxis
plot for [i=2:4] 'example.csv' u i:xtic(1)

with the output


问:
Throwing an exception from Mockito
I want to throw a ContentIOException from a method whose signature look like this.

```<code>public void putContent(InputStream is) throws ContentIOException.
</code>```

When I try to throw ContentIOException from Mockito like such:

```<code>when(StubbedObject.putContent(contentStream)).thenThrow(ContentIOException.class);
</code>```

I get the following compilation error:

```<code>The method when(T) in the type Mockito is not applicable for the arguments (void).
</code>```

What am I doing wrong?

答:
You can use following code

```<code>    when(testRepositoryMock.findOne(123)).thenThrow(new NullPointerException());
</code>```

Then after you can check your logic

```<code>        String erroResponse= service.testMethodForResponse(accountNum);
        JSONObject jsonObj = new JSONObject(erroResponse);
         String _acNo = jsonObj.getString("accountNum");
        assertEquals(accountNum, _acNo);
        }
</code>```

If you are using Spring boot then add top of class

```<code>@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
</code>```

Inside of class you need to inject object

```<code>@InjectMocks //actual object you want to get test coverage
private TestService testService;
@Mock //Mock object which call by actual object for mocking
private testRepository testRepositoryMock;
</code>```

Reference link :http://www.baeldung.com/mockito-behavior

Title: Throwing an exception from Mockito

Body:
I want to throw a ContentIOException from a method whose signature look like this.

public void putContent(InputStream is) throws ContentIOException.

When I try to throw ContentIOException from Mockito like such:

when(StubbedObject.putContent(contentStream)).thenThrow(ContentIOException.class);

I get the following compilation error:

The method when(T) in the type Mockito is not applicable for the arguments (void).

What am I doing wrong?

Body:
You can use following code

    when(testRepositoryMock.findOne(123)).thenThrow(new NullPointerException());

Then after you can check your logic

        String erroResponse= service.testMethodForResponse(accountNum);
        JSONObject jsonObj = new JSONObject(erroResponse);
         String _acNo = jsonObj.getString("accountNum");
        assertEquals(accountNum, _acNo);
        }

If you are using Spring boot then add top of class

@SpringBootTest
@RunWith(MockitoJUnitRunner.class)

Inside of class you need to inject object

@InjectMocks //actual object you want to get test coverage
private TestService testService;
@Mock //Mock object which call by actual object for mocking
private testRepository testRepositoryMock;

Reference link :http://www.baeldung.com/mockito-behavior


问:
Javascript change Typeof
I am new in JavaScript.

My code allows me to list the elements of a JSON document as well as their types, and concatenate all its in a string donnees_types.

The problem is that the typeof in JavaScript returns only number for a number and string for a string. I want to return double instead of number and varchar instead of string in order to get:

temperature double, humidite double, built varchar, fire varchar

I know I can replace in my string using replace, but is there any other method to change the typeof?

 var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

var keys = Object.keys(event);

donnees_types = "";

for(var i= 0; i < keys.length -1; i++)
donnees_types +=  keys[i] + " " +  typeof(event[keys[i]]) + ", ";

var donnees_t = donnees_types.substring(0, donnees_types.length - 2);
console.log(donnees_t);
 ```

答:
No, you can't change typeof. You could write your own function to map to the outputs you want.

function typeLabel(o){
  switch(typeof(o)){
    case "number" :
      return "double";
    case "string":
      return "varchar";
    default :
      return typeof(o);
  }
}
var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charonea",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

var keys = Object.keys(event);

donnees_types = "";

for(var i= 0; i < keys.length -1; i++)
donnees_types +=  keys[i] + " " +  typeLabel(event[keys[i]]) + ", ";

var donnees_t = donnees_types.substring(0, donnees_types.length - 2);
console.log(donnees_t);```

Title: Javascript change Typeof