问:
Pointers to Interfaces c++
Disclaimer: I am a complete C++ beginner, and if there is a similar answer to this question, please direct me to it, as I may have missed it, not knowing much in the way of theory.

So I was looking through some c++ code, and I found something like this:

shared_ptr<anObjectsInterface>

Which got me wondering, how can there be a pointer to an interface? Surely a pointer points to an object in memory, or am I reading something wrong here.

Thank you

答:
Don't forget that in the C++ object models, objects are composed of subobjects, which include base subobjects and member subobjects. An abstract class, or more generally an "interface" as you might call it, may not itself be a complete object, but it may well be the subobject of a "more complete" object. And pointers can point to arbitrary objects, including subobjects.

Schematically:

 +-- class Der --------------------------------------+
 | +---------+  +---------+ +----------+ +---------+ |
 | |*********|  |*********| |**********| |*********| |
 | +- int x -+  +- Base1 -+ +- bool b -+ +- Base2 -+ |
 +---------------------------------------------------+
 ^ ^            ^
 | |            |
 | +-- &a.x     +-- static_cast<Base1*>(&x)
 &a;
```

<p>Here we used:</p>

```struct Base1 { virtual void f() = 0; };
struct Base2 {};
struct Der : Base2, Base1 { int x; bool b; void f() override {} };

Der a;
```

The entire purpose of the virtual function dispatch mechanism is that you can call a (virtual) member function on an object that may not be a most-derived, but we will look up at runtime whether we are a subobject of a more-derived object, and we will use that object's class's implementation of the function.

Title: Pointers to Interfaces c++

Body:
Don't forget that in the C++ object models, objects are composed of subobjects, which include base subobjects and member subobjects. An abstract class, or more generally an "interface" as you might call it, may not itself be a complete object, but it may well be the subobject of a "more complete" object. And pointers can point to arbitrary objects, including subobjects.

Schematically:

 +-- class Der --------------------------------------+
 | +---------+  +---------+ +----------+ +---------+ |
 | |*********|  |*********| |**********| |*********| |
 | +- int x -+  +- Base1 -+ +- bool b -+ +- Base2 -+ |
 +---------------------------------------------------+
 ^ ^            ^
 | |            |
 | +-- &a.x     +-- static_cast<Base1*>(&x)
 &a;

Here we used:

struct Base1 { virtual void f() = 0; };
struct Base2 {};
struct Der : Base2, Base1 { int x; bool b; void f() override {} };

Der a;

The entire purpose of the virtual function dispatch mechanism is that you can call a (virtual) member function on an object that may not be a most-derived, but we will look up at runtime whether we are a subobject of a more-derived object, and we will use that object's class's implementation of the function.


来源: stackexchange

问:
php prevent & creating codes in a string
Ok so I'm sure there's a super simple solution for this, but I have to generate a string to use to grab a json file. I know I should be using & amp; instead of &, but for some reason it's not working for me. My problem is I'm getting ¤ when trying to create my string:

```<code>$apistr     = 'https://remitradar.com/JsonRequests.aspx?action=getOnlineQuotes&companyKey='.$companyKey.'&countryFrom='.$countryFrom.'&countryTo='.$countryTo.'&currencyFrom='.$currencyFrom.'&currencyTo='.$currencyTo.'&amount='.$amount;
</code>```

It's spitting out:

```<code>https://remitradar.com/JsonRequests.aspx?action=getOnlineQuotes&companyKey=23e9b66aspp6z&countryFrom=AU&countryTo=FJ¤cyFrom=AUD¤cyTo=FJD&amount=200
</code>```

Instead of:

```<code>https://remitradar.com/JsonRequests.aspx?action=getOnlineQuotes&companyKey=23e9b66aspp6z&countryFrom=AU&countryTo=FJ&CurrencyFrom=AUD&CurrencyTo=FJD&amount=200
</code>```

Any help would be great.

Edit:

This is the var_dump of the variables and the url:

```<code>string(13) "23e9b66aspp6z"
string(2) "AU"
string(2) "FJ"
string(3) "AUD"
string(3) "FJD"
string(3) "200"
string(159) "https://remitradar.com/JsonRequests.aspx?action=getOnlineQuotes&companyKey=23e9b66aspp6z&countryFrom=AU&countryTo=FJ¤cyFrom=AUD¤cyTo=FJD&amount=200"
</code>```

答:
You should urlencode the content of the variables:

```<code>$apistr     = 'https://remitradar.com/JsonRequests.aspx?action=getOnlineQuotes&companyKey='.urlencode($companyKey).'&countryFrom='.urlencode($countryFrom).'&countryTo='.urlencode($countryTo).'&currencyFrom='.urlencode($currencyFrom).'&currencyTo='.urlencode($currencyTo).'&amount='.urlencode($amount);
</code>```

Than it may also get more clear if there is content in them you did not expect.

And no, you should not use & to code an & in the url.

To check the contents of the variables you may do:

```<code>var_dump($companyKey);
var_dump($countryFrom);
var_dump($countryTo);
var_dump($currencyFrom);
var_dump($currencyTo);
var_dump($amount);
var_dump($apistr);
</code>```

If you echo the content of $apistr to your webbrowser &curren will be displayed as the currency glyph ¤ as the html entity ¤ is reserved.

Try to echo it this way to your browser instead (but dont use this as url! The variable $apistr contains what you expect - only the debug echo output was wrong in case of the rendering of your browser):

echo htmlspecialchars($apistr);

When ever you just output a string of characters your rendering application is your webbrowser. You also may look at the sourcecode of the webside containing the presumed wrong url. You should see the correct characters in the source. The output of htmlspecialchars($apistr); however would be look wrong in the source code but correct in the rendered webpage.

ContentLicense: CC BY-SA 3.0

Body:
Ok so I'm sure there's a super simple solution for this, but I have to generate a string to use to grab a json file. I know I should be using & amp; instead of &, but for some reason it's not working for me. My problem is I'm getting ¤ when trying to create my string:

$apistr     = 'https://remitradar.com/JsonRequests.aspx?action=getOnlineQuotes&companyKey='.$companyKey.'&countryFrom='.$countryFrom.'&countryTo='.$countryTo.'&currencyFrom='.$currencyFrom.'&currencyTo='.$currencyTo.'&amount='.$amount;

It's spitting out:

https://remitradar.com/JsonRequests.aspx?action=getOnlineQuotes&companyKey=23e9b66aspp6z&countryFrom=AU&countryTo=FJ¤cyFrom=AUD¤cyTo=FJD&amount=200

Instead of:

https://remitradar.com/JsonRequests.aspx?action=getOnlineQuotes&companyKey=23e9b66aspp6z&countryFrom=AU&countryTo=FJ&CurrencyFrom=AUD&CurrencyTo=FJD&amount=200

Any help would be great.

Edit:

This is the var_dump of the variables and the url:

string(13) "23e9b66aspp6z"
string(2) "AU"
string(2) "FJ"
string(3) "AUD"
string(3) "FJD"
string(3) "200"
string(159) "https://remitradar.com/JsonRequests.aspx?action=getOnlineQuotes&companyKey=23e9b66aspp6z&countryFrom=AU&countryTo=FJ¤cyFrom=AUD¤cyTo=FJD&amount=200"

Body:
You should urlencode the content of the variables:

$apistr     = 'https://remitradar.com/JsonRequests.aspx?action=getOnlineQuotes&companyKey='.urlencode($companyKey).'&countryFrom='.urlencode($countryFrom).'&countryTo='.urlencode($countryTo).'&currencyFrom='.urlencode($currencyFrom).'&currencyTo='.urlencode($currencyTo).'&amount='.urlencode($amount);

Than it may also get more clear if there is content in them you did not expect.

And no, you should not use &amp; to code an & in the url.

To check the contents of the variables you may do:

var_dump($companyKey);
var_dump($countryFrom);
var_dump($countryTo);
var_dump($currencyFrom);
var_dump($currencyTo);
var_dump($amount);
var_dump($apistr);

If you echo the content of $apistr to your webbrowser &curren will be displayed as the currency glyph ¤ as the html entity &curren; is reserved.

Try to echo it this way to your browser instead (but dont use this as url! The variable $apistr contains what you expect - only the debug echo output was wrong in case of the rendering of your browser):

echo htmlspecialchars($apistr);

When ever you just output a string of characters your rendering application is your webbrowser. You also may look at the sourcecode of the webside containing the presumed wrong url. You should see the correct characters in the source. The output of htmlspecialchars($apistr); however would be look wrong in the source code but correct in the rendered webpage.


问:
What's your most controversial programming opinion?
This is definitely subjective, but I'd like to try to avoid it becoming argumentative. I think it could be an interesting question if people treat it appropriately.

The idea for this question came from the comment thread from my answer to the "What are five things you hate about your favorite language?" question. I contended that classes in C# should be sealed by default - I won't put my reasoning in the question, but I might write a fuller explanation as an answer to this question. I was surprised at the heat of the discussion in the comments (25 comments currently).

So, what contentious opinions do you hold? I'd rather avoid the kind of thing which ends up being pretty religious with relatively little basis (e.g. brace placing) but examples might include things like "unit testing isn't actually terribly helpful" or "public fields are okay really". The important thing (to me, anyway) is that you've got reasons behind your opinions.

Please present your opinion and reasoning - I would encourage people to vote for opinions which are well-argued and interesting, whether or not you happen to agree with them.

答:
If you can only think of one way to do it, don't do it.

Whether it's an interface layout, a task flow, or a block of code, just stop.  Do something to collect more ideas, like asking other people how they would do it, and don't go back to implementing until you have at least three completely different ideas and at least one crisis of confidence.

Generally, when I think something can only be done one way, or think only one method has any merit, it's because I haven't thought through the factors which ought to be influencing the design thoroughly enough.  If I had, some of them would clearly be in conflict, leading to a mess and thus an actual decision rather than a rote default.

Being a solid programmer does not make you a solid interface designer

And following all of the interface guidelines in the world will only begin to help.  If it's even humanly possible...  There seems to be a peculiar addiction to making things 'cute' and 'clever'.

OwnerDisplayName: Jon Skeet

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: brian d foy

OwnerDisplayName: feonixrift


问:
Not able to create rooms using Exchange Webservice Managed API
https://msdn.microsoft.com/en-us/library/office/hh532568(v=exchg.80).aspx

Why does Exchange Webservices Managed API does not support creating of rooms?

答: EWS is a Mailbox Access API for accessing Mailbox data as a user (like MAPI,IMAP,POP etc). Creating Mailboxes,Meeting Room, contacts, distribution groups are administrative functions so you need to use an administrative API.</p>


问:
In R, find whether two files differ
I would like a pure R way to test whether two arbitrary files are different. So, the equivalent to diff -q in Unix, but should work on Windows and without external dependencies.

I'm aware of tools::Rdiff, but it seems to only want to deal with R output files and complains loudly if I feed it something else.

答:
Without using memory, if the files are too large:</p>

```<code>library(tools)
md5sum("file_1.txt") == md5sum("file_2.txt")
</code>```

Title: In R, find whether two files differ

Body:
Without using memory, if the files are too large:

library(tools)
md5sum("file_1.txt") == md5sum("file_2.txt")


问:
Clearing a line of output in Python
So, I'm super super new to Python and programming in general. I'm still learning the most basic of commands and terminology. My question is I'm trying to print the datetime in an infinite loop, but only on one line.

I would like the output in the shell to display the date and time and then clear the previously displayed datetime and replace it with the new value. I can't seem to figure out what I'm missing, and reading through different questions, I can't seem to find what I'm looking for. Any thoughts, help, or guidance would be appreciated. Trying to read the Python Documentation is not helping me at all at this point. This is what I've figured out so far:

```<code>import datetime
import time

while True:
    today = datetime.date.today()
    now = datetime.datetime.now()
    print ("The Current date is ", (today.strftime('%m/%d/%Y')))
    print ("The Current Time is ", (now.strftime('%H:%M')))
    time.sleep(30)
</code>```

This Generates:

```<code>The Current date is  03/28/2017
The Current Time is  19:09
The Current date is  03/28/2017
The Current Time is  19:10
</code>```

I'd like it to say:

```<code>The Current date is  03/28/2017
The Current Time is  19:09
</code>```

Then, text above removed and replaced with

```<code>The Current date is  03/28/2017
The Current Time is  19:10
</code>```

Datetime screenshot

答:
One way is to use ANSI escape sequences:

```<code>import datetime
import time
import sys

while True:
    today = datetime.date.today()
    now = datetime.datetime.now()
    print ("The Current date is ", (today.strftime('%m/%d/%Y')))
    print ("The Current Time is  ", (now.strftime('%H:%M')))
    sys.stdout.write("\033[F") # Cursor up one line
    sys.stdout.write("\033[F") # Cursor up one line
    time.sleep(30)
</code>```

Another option:

import datetime
import time
import os

```<code>while True:
    today = datetime.date.today()
    now = datetime.datetime.now()
    print ("The Current date is ", (today.strftime('%m/%d/%Y')))
    print ("The Current Time is ", (now.strftime('%H:%M')))
    time.sleep(30)
    os.system('clear')
</code>```

Title: Clearing a line of output in Python

Body:
So, I'm super super new to Python and programming in general. I'm still learning the most basic of commands and terminology. My question is I'm trying to print the datetime in an infinite loop, but only on one line.

I would like the output in the shell to display the date and time and then clear the previously displayed datetime and replace it with the new value. I can't seem to figure out what I'm missing, and reading through different questions, I can't seem to find what I'm looking for. Any thoughts, help, or guidance would be appreciated. Trying to read the Python Documentation is not helping me at all at this point. This is what I've figured out so far:

import datetime
import time

while True:
    today = datetime.date.today()
    now = datetime.datetime.now()
    print ("The Current date is ", (today.strftime('%m/%d/%Y')))
    print ("The Current Time is ", (now.strftime('%H:%M')))
    time.sleep(30)

This Generates:

The Current date is  03/28/2017
The Current Time is  19:09
The Current date is  03/28/2017
The Current Time is  19:10

I'd like it to say:

The Current date is  03/28/2017
The Current Time is  19:09

Then, text above removed and replaced with

The Current date is  03/28/2017
The Current Time is  19:10

Datetime screenshot

Body:
One way is to use ANSI escape sequences:

import datetime
import time
import sys

while True:
    today = datetime.date.today()
    now = datetime.datetime.now()
    print ("The Current date is ", (today.strftime('%m/%d/%Y')))
    print ("The Current Time is  ", (now.strftime('%H:%M')))
    sys.stdout.write("\033[F") # Cursor up one line
    sys.stdout.write("\033[F") # Cursor up one line
    time.sleep(30)

Another option:

import datetime
import time
import os

while True:
    today = datetime.date.today()
    now = datetime.datetime.now()
    print ("The Current date is ", (today.strftime('%m/%d/%Y')))
    print ("The Current Time is ", (now.strftime('%H:%M')))
    time.sleep(30)
    os.system('clear')


问:
Node.js async.series with existing functions
I'm struggling with the following problem. Say I have a wait function that takes a callback function (here foo) as an parameter:

```<code>function foo(data){
  console.log('foo says: ' + data);
}

function wait(count,callback) {
    console.log("waiting " + count + "s ...");
    setTimeout(function(){
      callback("just waited " + count + "s");
    },count*1000);
};
</code>```

Calling wait(5,foo) returns:

```<code>waiting 5s ...
foo says: just waited 5s
</code>```

I now want to use async.series where I first wait 7s and then 3s (i.e. 10s in total). It would be something like:

```<code>async.series([wait(7,foo),wait(3,foo)], function(err,result){ console.log(result); });
</code>```

But for something like this to work, I would have to modify my wait function so that callback(null,"just waited " + count + "s") is called (instead of callback("just waited " + count + "s") and I also would have to modify the foo function (from foo(data) to foo(null,data)). Or is there a way to use async without modifying the existing functions?

Not: if I try async.series([wait(7,foo),wait(3,foo)], function(err,result){ console.log(result); });
I obtain the following error:

```<code>node_modules/async/dist/async.js:3671
            task(rest(function (err, args) {
            ^

TypeError: task is not a function
</code>```

Thanks for any help provided.

答:
I really think its a bad idea to use the async module to handle this. It used to be a decent solution a few years ago, but async/await keywords are now built into the latest Node, and if you really can't use the latest Node its not hard to add babel transpilation.

```<code>const delay = require('delay')

async function wait(seconds) {
  console.log(`Waiting ${seconds} seconds`);
  await delay(seconds);
}

async function test() {
  await wait(7);
  await wait(3);
}

test().catch(console.error);
</code>```

Body:
I'm struggling with the following problem. Say I have a wait function that takes a callback function (here foo) as an parameter:

function foo(data){
  console.log('foo says: ' + data);
}

function wait(count,callback) {
    console.log("waiting " + count + "s ...");
    setTimeout(function(){
      callback("just waited " + count + "s");
    },count*1000);
};

Calling wait(5,foo) returns:

waiting 5s ...
foo says: just waited 5s

I now want to use async.series where I first wait 7s and then 3s (i.e. 10s in total). It would be something like:

async.series([wait(7,foo),wait(3,foo)], function(err,result){ console.log(result); });

But for something like this to work, I would have to modify my wait function so that callback(null,"just waited " + count + "s") is called (instead of callback("just waited " + count + "s") and I also would have to modify the foo function (from foo(data) to foo(null,data)). Or is there a way to use async without modifying the existing functions?

Not: if I try async.series([wait(7,foo),wait(3,foo)], function(err,result){ console.log(result); });
I obtain the following error:

node_modules/async/dist/async.js:3671
            task(rest(function (err, args) {
            ^

TypeError: task is not a function

Thanks for any help provided.

Body:
I really think its a bad idea to use the async module to handle this. It used to be a decent solution a few years ago, but async/await keywords are now built into the latest Node, and if you really can't use the latest Node its not hard to add babel transpilation.

const delay = require('delay')

async function wait(seconds) {
  console.log(`Waiting ${seconds} seconds`);
  await delay(seconds);
}

async function test() {
  await wait(7);
  await wait(3);
}

test().catch(console.error);


问:
AppEngine's urlfetch, how to force timeout to be respected
I'm using Urlfetch from Google Appengine, and I add the deadline parameter to force the deadline to be short (3 seconds), like the following :

```<code>try:
    urlfetch.set_default_fetch_deadline(3)
    return urlfetch.fetch(url='http://www.example.com', method=urlfetch.GET, deadline=3)
except google.appengine.runtime.apiproxy_errors.DeadlineExceededError:
    pass
except google.appengine.api.urlfetch_errors.DeadlineExceededError:
    pass

return None
</code>```

But no matter what, my thread goes on and on for 60 seconds (the max execution time for an http request on Appengine) and then fail miserably on a DeadlineException ("Thread running after request.").

Is there a way to ensure that the upper query will be strictly stopped in 3 seconds?

答:
I can share some code I currently have running in one of my production projects. I use a deadline of 0.5 seconds in this example. Last I checked, it's still working:

```<code>t_rpc = urlfetch.create_rpc(deadline=0.5)
urlfetch.make_fetch_call(t_rpc, url)
# and then later...
try:
    result = t_rpc.get_result()
except:
    # handle errors...
    pass

# use the result...
</code>```

This is actually using the asynchronous version of the API so you can technically do things in between calling make_fetch_call and get_result. Otherwise, you can just call them back-to-back and it will function the same as a synchronous API.

Body:
I'm using Urlfetch from Google Appengine, and I add the deadline parameter to force the deadline to be short (3 seconds), like the following :

try:
    urlfetch.set_default_fetch_deadline(3)
    return urlfetch.fetch(url='http://www.example.com', method=urlfetch.GET, deadline=3)
except google.appengine.runtime.apiproxy_errors.DeadlineExceededError:
    pass
except google.appengine.api.urlfetch_errors.DeadlineExceededError:
    pass

return None

But no matter what, my thread goes on and on for 60 seconds (the max execution time for an http request on Appengine) and then fail miserably on a DeadlineException ("Thread running after request.").

Is there a way to ensure that the upper query will be strictly stopped in 3 seconds?

Body:
I can share some code I currently have running in one of my production projects. I use a deadline of 0.5 seconds in this example. Last I checked, it's still working:

t_rpc = urlfetch.create_rpc(deadline=0.5)
urlfetch.make_fetch_call(t_rpc, url)
# and then later...
try:
    result = t_rpc.get_result()
except:
    # handle errors...
    pass

# use the result...

This is actually using the asynchronous version of the API so you can technically do things in between calling make_fetch_call and get_result. Otherwise, you can just call them back-to-back and it will function the same as a synchronous API.


问:
mask only where consecutive nans exceeds x
I was answering a question about pandas interpolation method.  The OP wanted to use only interpolate where the number of consecutive np.nans was one.  The limit=1 option for interpolate will interpolate the first np.nan and stop there.  OP wanted to be able to tell that there were in fact more than one np.nan and not even bother with the first one.

I boiled this down to just executing the interpolate as is and mask the consecutive np.nan after the fact.

The question is: What is a generalized solution that takes a 1-d array a and an integer x and produces a boolean mask with False in the positions of x or more consecutive np.nan

Consider the 1-d array a

```<code>a = np.array([1, np.nan, np.nan, np.nan, 1, np.nan, 1, 1, np.nan, np.nan, 1, 1])
</code>```

I'd expect that for x = 2 the mask would look like this

```<code># assume 1 for True and 0 for False
# a is [  1.  nan  nan  nan   1.  nan   1.   1.  nan  nan   1.   1.]
# mask [  1.   0.   0.   0.   1.   1.   1.   1.   0.   0.   1.   1.]
#                                  ^
#                                  |
#   Notice that this is not masked because there is only one np.nan
</code>```

I'd expect that for x = 3 the mask would look like this

```<code># assume 1 for True and 0 for False
# a is [  1.  nan  nan  nan   1.  nan   1.   1.  nan  nan   1.   1.]
# mask [  1.   0.   0.   0.   1.   1.   1.   1.   1.   1.   1.   1.]
#                                  ^              ^    ^
#                                  |              |    |
# Notice that this is not masked because there is less than 3 np.nan's
</code>```

I look forward to learning from others ideas ;-)

答:
I created this generalized solution

```<code>import pandas as pd
import numpy as np
from numpy.lib.stride_tricks import as_strided as strided

def mask_knans(a, x):
    a = np.asarray(a)
    k = a.shape[0]

    # I will stride n.  I want to pad with 1 less False than
    # the required number of np.nan's
    n = np.append(np.isnan(a), [False] * (x - 1))

    # prepare the mask and fill it with True
    m = np.empty(k, np.bool8)
    m.fill(True)

    # stride n into a number of columns equal to
    # the required number of np.nan's to mask
    # this is essentially a rolling all operation on isnull
    # also reshape with `[:, None]` in preparation for broadcasting
    # np.where finds the indices where we successfully start
    # x consecutive np.nan's
    s = n.strides[0]
    i = np.where(strided(n, (k + 1 - x, x), (s, s)).all(1))[0][:, None]

    # since I prepped with `[:, None]` when I add `np.arange(x)`
    # I'm including the subsequent indices where the remaining
    # x - 1 np.nan's are
    i = i + np.arange(x)

    # I use `pd.unique` because it doesn't sort and I don't need to sort
    i = pd.unique(i[i < k])

    m[i] = False

    return m
</code>```

w/o comments

```<code>import pandas as pd
import numpy as np
from numpy.lib.stride_tricks import as_strided as strided

def mask_knans(a, x):
    a = np.asarray(a)
    k = a.shape[0]
    n = np.append(np.isnan(a), [False] * (x - 1))
    m = np.empty(k, np.bool8)
    m.fill(True)
    s = n.strides[0]
    i = np.where(strided(n, (k + 1 - x, x), (s, s)).all(1))[0][:, None]
    i = i + np.arange(x)
    i = pd.unique(i[i < k])
    m[i] = False
    return m
</code>```

demo

```<code>mask_knans(a, 2)

[ True False False False  True  True  True  True False False  True  True]
</code>```

```<code>mask_knans(a, 3)

[ True False False False  True  True  True  True  True  True  True  True]
</code>```

Body:
I was answering a question about pandas interpolation method.  The OP wanted to use only interpolate where the number of consecutive np.nans was one.  The limit=1 option for interpolate will interpolate the first np.nan and stop there.  OP wanted to be able to tell that there were in fact more than one np.nan and not even bother with the first one.

I boiled this down to just executing the interpolate as is and mask the consecutive np.nan after the fact.

The question is: What is a generalized solution that takes a 1-d array a and an integer x and produces a boolean mask with False in the positions of x or more consecutive np.nan

Consider the 1-d array a

a = np.array([1, np.nan, np.nan, np.nan, 1, np.nan, 1, 1, np.nan, np.nan, 1, 1])

I'd expect that for x = 2 the mask would look like this

# assume 1 for True and 0 for False
# a is [  1.  nan  nan  nan   1.  nan   1.   1.  nan  nan   1.   1.]
# mask [  1.   0.   0.   0.   1.   1.   1.   1.   0.   0.   1.   1.]
#                                  ^
#                                  |
#   Notice that this is not masked because there is only one np.nan

I'd expect that for x = 3 the mask would look like this

# assume 1 for True and 0 for False
# a is [  1.  nan  nan  nan   1.  nan   1.   1.  nan  nan   1.   1.]
# mask [  1.   0.   0.   0.   1.   1.   1.   1.   1.   1.   1.   1.]
#                                  ^              ^    ^
#                                  |              |    |
# Notice that this is not masked because there is less than 3 np.nan's

I look forward to learning from others ideas ;-)

Body:
I created this generalized solution

import pandas as pd
import numpy as np
from numpy.lib.stride_tricks import as_strided as strided

def mask_knans(a, x):
    a = np.asarray(a)
    k = a.shape[0]

    # I will stride n.  I want to pad with 1 less False than
    # the required number of np.nan's
    n = np.append(np.isnan(a), [False] * (x - 1))

    # prepare the mask and fill it with True
    m = np.empty(k, np.bool8)
    m.fill(True)

    # stride n into a number of columns equal to
    # the required number of np.nan's to mask
    # this is essentially a rolling all operation on isnull
    # also reshape with `[:, None]` in preparation for broadcasting
    # np.where finds the indices where we successfully start
    # x consecutive np.nan's
    s = n.strides[0]
    i = np.where(strided(n, (k + 1 - x, x), (s, s)).all(1))[0][:, None]

    # since I prepped with `[:, None]` when I add `np.arange(x)`
    # I'm including the subsequent indices where the remaining
    # x - 1 np.nan's are
    i = i + np.arange(x)

    # I use `pd.unique` because it doesn't sort and I don't need to sort
    i = pd.unique(i[i < k])

    m[i] = False

    return m

w/o comments

import pandas as pd
import numpy as np
from numpy.lib.stride_tricks import as_strided as strided

def mask_knans(a, x):
    a = np.asarray(a)
    k = a.shape[0]
    n = np.append(np.isnan(a), [False] * (x - 1))
    m = np.empty(k, np.bool8)
    m.fill(True)
    s = n.strides[0]
    i = np.where(strided(n, (k + 1 - x, x), (s, s)).all(1))[0][:, None]
    i = i + np.arange(x)
    i = pd.unique(i[i < k])
    m[i] = False
    return m

demo

mask_knans(a, 2)

[ True False False False  True  True  True  True False False  True  True]

mask_knans(a, 3)

[ True False False False  True  True  True  True  True  True  True  True]


问:
Kubernetes node high disk IO and CPU usage
I run a Kubernetes cluster with version 1.5.2, setup with Kops on AWS. The setup has nothing exotic. My nodes run on m4.xlarge with 70 Gb of disk storage with 1000 iops.

I have periods where some of my nodes get crazy with iops. Here is what I see:

So du take all my iops in the docker overlay directory. Here is what the kubelet logs display:

```<code>fsHandler.go:131] du and find on following dirs took 4.22914425s: [/var/lib/docker/overlay/592c1d88d1fd115f21e8fe6f198a8a27cd44efefb9b5dc58940fbf6d7999eda3 /var/lib/docker/containers/2347d28886bc0e6b74fc326538e1483927ddeb89b38e035acd845d5db621cb79]
fsHandler.go:131] du and find on following dirs took 24.94283434s: [/var/lib/docker/overlay/81f24df3624ebf7b7e45edc38fafeb41958bc675ae57fd0126c44cb2c3a6d6d6 /var/lib/docker/containers/43d576931081500fd4cd316afe5bfc6ff2442ff20e8e8266c27e930a0a77dd34]
fsHandler.go:131] du and find on following dirs took 18.478782737s: [/var/lib/docker/overlay/422ef31413df4e76de51acaa7d6ff6f77edc65fabde88a7c70e7edad3b1e55e5 /var/lib/docker/containers/1519a33729c8fb13297358edc53fe22f0b4b684636884976dfcb67c47fbf320b]
helpers.go:101] Unable to get network stats from pid 13515: couldn't read network stats: failure opening /proc/13515/net/dev: open /proc/13515/net/dev: no such file or directory
fsHandler.go:131] du and find on following dirs took 7.971745844s: [/var/lib/docker/overlay/45b83939bd1b4ec7dfa627bb6a9eb8b89a380007f9e22a93fff2ba4054252271 /var/lib/docker/containers/f6d3387423398d7dd4fac6c19ee0a1446d0465b5f9cf90289fcd605ad28c0d6e]
fsHandler.go:131] du and find on following dirs took 5.886763577s: [/var/lib/docker/overlay/8c01a73671eedb2e62c58fa12fc2d25df58c506545b6ea048fa0db1756d19f2c /var/lib/docker/containers/1d9c0ebcc6dbbd7065923f7f81c05c0d9d710aed0d353a1bab90ce1c994dfb57]
fsHandler.go:131] du and find on following dirs took 5.714942029s: [/var/lib/docker/overlay/26213ba30a17f240a9b9756a0d23ab32550f921de533667c9ab91cfb7f10ed5b /var/lib/docker/containers/7c27c242a49d8d33cee8b2e8335dae450af13b26f010794dc83ef5750a212d0d]
fsHandler.go:131] du and find on following dirs took 6.111478835s: [/var/lib/docker/overlay/0fe2bd0feeda24699bd6d443ca126ac1a33071cdff039ae9fd9159bbef80867b /var/lib/docker/containers/ec6fb966139e9666ec0be5e13399773f1971ddd99841b84167a7463402e28d73]
fsHandler.go:131] du and find on following dirs took 2.661604836s: [/var/lib/docker/overlay/04f9d01a8863cfee26e678e938fced84f826dda6ed03626dda11b6aad6901465 /var/lib/docker/containers/a4e37aee69c7523c46c5252c1834fa3fcd5a804a7aee256a468e44b4d6bcbd64]
fsHandler.go:131] du and find on following dirs took 11.834409809s: [/var/lib/docker/overlay/4cb1476621b90e2c2ee2b1131c0e6ac62f62dc3ca418129812b487bffac1d827 /var/lib/docker/containers/5a01521cfdd3041aff128dce7353ab336ddafa60c8c0b2254fb6bae697cb1676]
</code>```

答:
I recommend upgrading to k8s version 1.6, there are many updates noted in the CHANGELOG that should help debug your issue.

Generally, EBS volumes are not fully available in terms of IO unless you have fully "pre-warmed" them by reading and writing to every block on the device.

Body:
I run a Kubernetes cluster with version 1.5.2, setup with Kops on AWS. The setup has nothing exotic. My nodes run on m4.xlarge with 70 Gb of disk storage with 1000 iops.

I have periods where some of my nodes get crazy with iops. Here is what I see:

So du take all my iops in the docker overlay directory. Here is what the kubelet logs display:

fsHandler.go:131] du and find on following dirs took 4.22914425s: [/var/lib/docker/overlay/592c1d88d1fd115f21e8fe6f198a8a27cd44efefb9b5dc58940fbf6d7999eda3 /var/lib/docker/containers/2347d28886bc0e6b74fc326538e1483927ddeb89b38e035acd845d5db621cb79]
fsHandler.go:131] du and find on following dirs took 24.94283434s: [/var/lib/docker/overlay/81f24df3624ebf7b7e45edc38fafeb41958bc675ae57fd0126c44cb2c3a6d6d6 /var/lib/docker/containers/43d576931081500fd4cd316afe5bfc6ff2442ff20e8e8266c27e930a0a77dd34]
fsHandler.go:131] du and find on following dirs took 18.478782737s: [/var/lib/docker/overlay/422ef31413df4e76de51acaa7d6ff6f77edc65fabde88a7c70e7edad3b1e55e5 /var/lib/docker/containers/1519a33729c8fb13297358edc53fe22f0b4b684636884976dfcb67c47fbf320b]
helpers.go:101] Unable to get network stats from pid 13515: couldn't read network stats: failure opening /proc/13515/net/dev: open /proc/13515/net/dev: no such file or directory
fsHandler.go:131] du and find on following dirs took 7.971745844s: [/var/lib/docker/overlay/45b83939bd1b4ec7dfa627bb6a9eb8b89a380007f9e22a93fff2ba4054252271 /var/lib/docker/containers/f6d3387423398d7dd4fac6c19ee0a1446d0465b5f9cf90289fcd605ad28c0d6e]
fsHandler.go:131] du and find on following dirs took 5.886763577s: [/var/lib/docker/overlay/8c01a73671eedb2e62c58fa12fc2d25df58c506545b6ea048fa0db1756d19f2c /var/lib/docker/containers/1d9c0ebcc6dbbd7065923f7f81c05c0d9d710aed0d353a1bab90ce1c994dfb57]
fsHandler.go:131] du and find on following dirs took 5.714942029s: [/var/lib/docker/overlay/26213ba30a17f240a9b9756a0d23ab32550f921de533667c9ab91cfb7f10ed5b /var/lib/docker/containers/7c27c242a49d8d33cee8b2e8335dae450af13b26f010794dc83ef5750a212d0d]
fsHandler.go:131] du and find on following dirs took 6.111478835s: [/var/lib/docker/overlay/0fe2bd0feeda24699bd6d443ca126ac1a33071cdff039ae9fd9159bbef80867b /var/lib/docker/containers/ec6fb966139e9666ec0be5e13399773f1971ddd99841b84167a7463402e28d73]
fsHandler.go:131] du and find on following dirs took 2.661604836s: [/var/lib/docker/overlay/04f9d01a8863cfee26e678e938fced84f826dda6ed03626dda11b6aad6901465 /var/lib/docker/containers/a4e37aee69c7523c46c5252c1834fa3fcd5a804a7aee256a468e44b4d6bcbd64]
fsHandler.go:131] du and find on following dirs took 11.834409809s: [/var/lib/docker/overlay/4cb1476621b90e2c2ee2b1131c0e6ac62f62dc3ca418129812b487bffac1d827 /var/lib/docker/containers/5a01521cfdd3041aff128dce7353ab336ddafa60c8c0b2254fb6bae697cb1676]


问:
Check all other checkboxes when one is checked
I have a form and group of checkboxes in it. (These checkboxes are dynamically created but I dont think it is important for this question). The code that generates them looks like this (part of the form):

```<code><div id="ScrollCB">
    <input type="checkbox" name="ALL" value="checked" checked="checked">
    All (if nothing selected, this is default) <br>
    <c:forEach items="${serviceList}" var="service">
       <input type="checkbox" name="${service}" value="checked"> ${service} <br>
    </c:forEach>
</div>
</code>```

What I want to do is control, whether the checkbox labeled "ALL" is checked and if yes - check all other checkboxes (and when unchecked, uncheck them all).

I tried doing this with javascript like this (found some tutorial), but it doesnt work (and Im real newbie in javascript, no wonder):

```<code><script type="text/javascript">
  $ui.find('#ScrollCB').find('label[for="ALL"]').prev().bind('click',function(){
  $(this).parent().siblings().find(':checkbox').attr('checked',this.checked).attr('disabled',this.checked);
}); });
</script>
</code>```

Could you tell me some simple approach how to get it work? Thanks a lot!

答:
Thanks to @Ashish, I have expanded it slightly to allow the "master" checkbox to be automatically checked or unchecked, if you manually tick all the sub checkboxes.

FIDDLE

HTML

```<code><label><input type="checkbox" name="sample" class="selectall"/>Select all</label>

<div id="checkboxlist">
    <label><input type="checkbox" class="justone" name="sample[]"/>checkbox1</label><br/>
    <label><input type="checkbox" class="justone" name="sample[]"/>checkbox2</label><br />
    <label><input type="checkbox" class="justone" name="sample[]"/>checkbox3</label><br />
    <label><input type="checkbox" class="justone" name="sample[]"/>checkbox4</label><br />
</div>
</code>```

SCRIPT

```<code>$('.selectall').click(function() {
    if ($(this).is(':checked')) {
        $('input:checkbox').prop('checked', true);
    } else {
        $('input:checkbox').prop('checked', false);
    }
});
</code>```

And now add this to manage the master checkbox as well...

```<code>$("input[type='checkbox'].justone").change(function(){
    var a = $("input[type='checkbox'].justone");
    if(a.length == a.filter(":checked").length){
        $('.selectall').prop('checked', true);
    }
    else {
        $('.selectall').prop('checked', false);
    }
});
</code>```

Body:
I have a form and group of checkboxes in it. (These checkboxes are dynamically created but I dont think it is important for this question). The code that generates them looks like this (part of the form):

    <input type="checkbox" name="ALL" value="checked" checked="checked">
    All (if nothing selected, this is default)

    <c:forEach items="${serviceList}" var="service">
       <input type="checkbox" name="${service}" value="checked"> ${service}

    </c:forEach>

What I want to do is control, whether the checkbox labeled "ALL" is checked and if yes - check all other checkboxes (and when unchecked, uncheck them all).

I tried doing this with javascript like this (found some tutorial), but it doesnt work (and Im real newbie in javascript, no wonder):

Could you tell me some simple approach how to get it work? Thanks a lot!

Body:
Thanks to @Ashish, I have expanded it slightly to allow the "master" checkbox to be automatically checked or unchecked, if you manually tick all the sub checkboxes.

FIDDLE

HTML

<label><input type="checkbox" name="sample" class="selectall"/>Select all</label>

<div id="checkboxlist">
    <label><input type="checkbox" class="justone" name="sample[]"/>checkbox1</label><br/>
    <label><input type="checkbox" class="justone" name="sample[]"/>checkbox2</label><br />
    <label><input type="checkbox" class="justone" name="sample[]"/>checkbox3</label><br />
    <label><input type="checkbox" class="justone" name="sample[]"/>checkbox4</label><br />
</div>

SCRIPT

$('.selectall').click(function() {
    if ($(this).is(':checked')) {
        $('input:checkbox').prop('checked', true);
    } else {
        $('input:checkbox').prop('checked', false);
    }
});

And now add this to manage the master checkbox as well...

$("input[type='checkbox'].justone").change(function(){
    var a = $("input[type='checkbox'].justone");
    if(a.length == a.filter(":checked").length){
        $('.selectall').prop('checked', true);
    }
    else {
        $('.selectall').prop('checked', false);
    }
});


问:
How to output multiple numbers at once in a for loop using Java
I'm very new to Java programming (2 weeks in) and currently am practicing arrays.

My code is as follows:

```<code>import java.util.Scanner;

public class LA2_2_1 {
    public static void main (String[] args)
    {
        Scanner scan = new Scanner(System.in);
        int x;
        double avg;
        double num = 0;

        System.out.print("Enter the number of items: ");
        x = scan.nextInt();

        int [] numbers = new int [x];
        double sum = 0;
        sum = sum + num;

        for (int index = 0; index < numbers.length; index++)
        {
            System.out.print("Enter the numbers: ");
            num = scan.nextDouble();
            sum = sum + num;
            System.out.println(sum);
        }
        avg = sum/x;
        System.out.println("The average is " + avg);
    }
}
</code>```

Output:

```<code>Enter the number of items: 10

Enter the numbers: 3.4 5 6 1 6.5 7.8 3.5 8.5 6.3 9.5

3.4

Enter the numbers: 8.4

Enter the numbers: 14.4

Enter the numbers: 15.4

Enter the numbers: 21.9

Enter the numbers: 29.7

Enter the numbers: 33.2

Enter the numbers: 41.7

Enter the numbers: 48.0

Enter the numbers: 57.5

The average is 5.75
</code>```

My question is, how can I format the code so that I get "Enter the numbers" to appear only once? I just want the program to ask the user for the series of numbers they want to input. I do not want it to output multiple "Enter the numbers".

I think this may have to do with the output being within a for loop, but I am not too positive. I tried taking it out, and both the average and output for "Enter the numbers" turned to 0.0.

Any input would be helpful.

Thank you

答:
Just change your for loop from

```<code>for (int index = 0; index < numbers.length; index++)
{
    System.out.print("Enter the numbers: ");
    num = scan.nextDouble();
    sum = sum + num;
    System.out.println(sum);
}
</code>```

to

```<code>System.out.print("Enter the numbers: ");
for (int index = 0; index < numbers.length; index++)
{
    num = scan.nextDouble();
    sum = sum + num;
}
System.out.println(sum);
</code>```

Body:
I'm very new to Java programming (2 weeks in) and currently am practicing arrays.

My code is as follows:

import java.util.Scanner;

public class LA2_2_1 {
    public static void main (String[] args)
    {
        Scanner scan = new Scanner(System.in);
        int x;
        double avg;
        double num = 0;

        System.out.print("Enter the number of items: ");
        x = scan.nextInt();

        int [] numbers = new int [x];
        double sum = 0;
        sum = sum + num;

        for (int index = 0; index < numbers.length; index++)
        {
            System.out.print("Enter the numbers: ");
            num = scan.nextDouble();
            sum = sum + num;
            System.out.println(sum);
        }
        avg = sum/x;
        System.out.println("The average is " + avg);
    }
}

Output:

Enter the number of items: 10

Enter the numbers: 3.4 5 6 1 6.5 7.8 3.5 8.5 6.3 9.5

3.4

Enter the numbers: 8.4

Enter the numbers: 14.4

Enter the numbers: 15.4

Enter the numbers: 21.9

Enter the numbers: 29.7

Enter the numbers: 33.2

Enter the numbers: 41.7

Enter the numbers: 48.0

Enter the numbers: 57.5

The average is 5.75

My question is, how can I format the code so that I get "Enter the numbers" to appear only once? I just want the program to ask the user for the series of numbers they want to input. I do not want it to output multiple "Enter the numbers".

I think this may have to do with the output being within a for loop, but I am not too positive. I tried taking it out, and both the average and output for "Enter the numbers" turned to 0.0.

Any input would be helpful.

Thank you

Body:
Just change your for loop from

for (int index = 0; index < numbers.length; index++)
{
    System.out.print("Enter the numbers: ");
    num = scan.nextDouble();
    sum = sum + num;
    System.out.println(sum);
}

to

System.out.print("Enter the numbers: ");
for (int index = 0; index < numbers.length; index++)
{
    num = scan.nextDouble();
    sum = sum + num;
}
System.out.println(sum);


问:
Docker-machine - set configuration as default
Everytime I start docker-machine, I need to set a configuration like below.

```<code>host> docker-machine ssh default
docker> sudo sysctl -w vm.max_map_count=262144
</code>```

I would like to this configuration as default, so I don't need to set it no more.

答:
Boot2Docker allows for local customisation.

Add your sysctl command to /var/lib/boot2docker/bootsync.sh to have it run before docker starts.

```<code>echo 'sysctl -w vm.max_map_count=262144' >> /var/lib/boot2docker/bootsync.sh
chmod 755 /var/lib/boot2docker/bootsync.sh
</code>```

Body:
Everytime I start docker-machine, I need to set a configuration like below.

host> docker-machine ssh default
docker> sudo sysctl -w vm.max_map_count=262144

I would like to this configuration as default, so I don't need to set it no more.

Body:
Boot2Docker allows for local customisation.

Add your sysctl command to /var/lib/boot2docker/bootsync.sh to have it run before docker starts.

echo 'sysctl -w vm.max_map_count=262144' >> /var/lib/boot2docker/bootsync.sh
chmod 755 /var/lib/boot2docker/bootsync.sh


问:
How to read files recursively in awk
I have a bunch of latex files witch use the \input{filename.tex} macro (it works like an #include from C), and I want to resolve them so I can output all of them to a single .tex file (the file must be pasted at the place of the \input{} macro, it is safe to assume that each file is referenced only once).

Example:

tesis.tex:

```<code>My thesis.
\input{chapter1.tex}
More things
\input{chapter2.tex}
</code>```

chapter1.tex:

```<code>Chapter 1 content.
</code>```

chapter2.tex:

```<code>Chapter 2 content.
\include{section2-2.tex}
</code>```

section2-2.tex:

```<code>Section 1.
</code>```

The desired result should be:

```<code>My thesis.
Chapter 1 content.
More things
Chapter 2 content.
Section 1.
</code>```

If there was only a \input{foo.tex} level I would be able to solve this with this AWK program:

```<code>/\\input\{.*\}/{
    sub(/^[^{]*{/,"",$0)
    sub(/}[^}]*$/,"",$0)
    system("cat " $0)
    next
}

{
    print $0
}
</code>```

Is there any way to read files recursively in AWK?

(I am open to do it with any other language, but the posixest the better)

Thanks!

答:
Since you have tag it also bash, something like this could work in bash, but it is not tested:

```<code>#!/bin/bash
function texextract {
while read -r line;do
    if [[ "$line" =~ "input" || "$line" =~ "include" ]];then  #regex may need finetune
      filename="${line: 0:-1}"  #removes the last } from \include{section2-2.tex}
      filename="${filename##*{}" #removes from start up to { ---> filename=section2-2.tex
      texextract "$filename"  #call itself with new args
    else
      echo "$line" >>commonbigfile
    fi
done <"$1" #$1 holds the filename send by caller
return
}

texextract tesis.tex #masterfile
</code>```

In bash 4.4 (and maybe in other versions also) a function can call itself. This is what i make use of here.

Title: How to read files recursively in awk

Body:
I have a bunch of latex files witch use the \input{filename.tex} macro (it works like an #include from C), and I want to resolve them so I can output all of them to a single .tex file (the file must be pasted at the place of the \input{} macro, it is safe to assume that each file is referenced only once).

Example:

tesis.tex:

My thesis.
\input{chapter1.tex}
More things
\input{chapter2.tex}

chapter1.tex:

Chapter 1 content.

chapter2.tex:

Chapter 2 content.
\include{section2-2.tex}

section2-2.tex:

Section 1.

The desired result should be:

My thesis.
Chapter 1 content.
More things
Chapter 2 content.
Section 1.

If there was only a \input{foo.tex} level I would be able to solve this with this AWK program:

/\\input\{.*\}/{
    sub(/^[^{]*{/,"",$0)
    sub(/}[^}]*$/,"",$0)
    system("cat " $0)
    next
}

{
    print $0
}

Is there any way to read files recursively in AWK?

(I am open to do it with any other language, but the posixest the better)

Thanks!

Body:
Since you have tag it also bash, something like this could work in bash, but it is not tested:

#!/bin/bash
function texextract {
while read -r line;do
    if [[ "$line" =~ "input" || "$line" =~ "include" ]];then  #regex may need finetune
      filename="${line: 0:-1}"  #removes the last } from \include{section2-2.tex}
      filename="${filename##*{}" #removes from start up to { ---> filename=section2-2.tex
      texextract "$filename"  #call itself with new args
    else
      echo "$line" >>commonbigfile
    fi
done <"$1" #$1 holds the filename send by caller
return
}

texextract tesis.tex #masterfile

In bash 4.4 (and maybe in other versions also) a function can call itself. This is what i make use of here.


问:
How to show infowindow without cluster click
I have little problem of Cluster and Custom InfoWindow.

I don't want to show Infowindow when i click cluster.
But my application is show Infowindow when i click clusterItem and click Cluter. It show last click ClusterItem's Infowindow.

Code :

```<code>public class MapsLActivity extends FragmentActivity implements OnMapReadyCallback, ClusterManager.OnClusterItemClickListener<House>, GoogleMap.OnMapClickListener, ClusterManager.OnClusterClickListener<House>{

private GoogleMap mMap;
private View infoWindow;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps_k);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.getUiSettings().setZoomControlsEnabled(true);

    ClusterManager<House> mClusterManager = new ClusterManager<>(this, mMap);

    mMap.setOnMapClickListener(this);
    mMap.setOnMarkerClickListener(mClusterManager);
    mMap.setOnCameraChangeListener(mClusterManager);

    AssetManager assetManager = getResources().getAssets();
    try {
        AssetManager.AssetInputStream ais = (AssetManager.AssetInputStream) assetManager.open("yb_edu.json");
        BufferedReader br = new BufferedReader(new InputStreamReader(ais));
        StringBuilder sb = new StringBuilder();

        int bufferSize = 1024 * 1024;
        char readBuf[] = new char[bufferSize];
        int resultSize = 0;

        while ((resultSize = br.read(readBuf)) != -1) {
            if (resultSize == bufferSize) {
                sb.append(readBuf);
            } else {
                for (int i = 0; i < resultSize; i++) {
                    sb.append(readBuf[i]);
                }
            }
        }

        String jString = sb.toString();
        JSONObject object = new JSONObject(jString);
        JSONArray list = new JSONArray(object.getString("yb_edu"));

        for (int i = 0; i < list.length(); i++) {
            JSONObject inside = list.getJSONObject(i);

            String title = inside.getString("title");
            String lats = inside.getString("lat");
            String lngs = inside.getString("lng");

            double lat = Double.parseDouble(lats);
            double lng = Double.parseDouble(lngs);

            LatLng position = new LatLng(lat, lng);

            Log.v("@@@", "postion : " + position);

            Log.v("@@i=@@", String.valueOf(i));

            i++;

            mClusterManager.addItem(new House(position, title));
        }
        mClusterManager.cluster(); //클러스터 새로고침
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    mClusterManager.setOnClusterItemClickListener(this);
    mClusterManager.setOnClusterClickListener(this);
}

@Override
public boolean onClusterItemClick(final House house) {
    Toast.makeText(this, "onClusterItemClick", Toast.LENGTH_SHORT).show();

    LatLng latLng = house.getLatLng();

    Log.v("@@", "LatLng : " + latLng);

    infoWindow = getLayoutInflater().inflate(R.layout.markerinfo, null);
    mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
        @Override
        public View getInfoWindow(Marker marker) {
            ((TextView)infoWindow.findViewById(R.id.tx_infoWindowTitle)).setText(house.getTitle());
            ((TextView)infoWindow.findViewById(R.id.tx_infoWindowContent)).setText(house.getLatLng().toString());
            return infoWindow;
        }

        @Override
        public View getInfoContents(Marker marker) {
            return null;
        }
    });

    return false;
}

@Override
public boolean onClusterClick(Cluster<House> cluster) {
    mMap.moveCamera(CameraUpdateFactory.zoomIn());
    Toast.makeText(this, "onClusterClick", Toast.LENGTH_SHORT).show();
    return false;
}

@Override
public void onMapClick(LatLng latLng) {
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
</code>```

答:
Finally i resolve it....

public class MapsPActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnCameraMoveListener {

```<code>private GoogleMap mMap;
private float pastZoom = 0;
private ArrayList<House> edulList;

private int clusters = 0;
private int marks = 0;

private View infoWindow;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps_m);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.getUiSettings().setZoomControlsEnabled(true);

    edulList = new ArrayList<>();

    addEdu();

    mMap.setOnMarkerClickListener(null);
    mMap.setInfoWindowAdapter(null);
    mMap.setOnCameraMoveListener(this);

}

private void addEdu() {
    try {
        AssetManager assetManager = getResources().getAssets();
        AssetManager.AssetInputStream ais = (AssetManager.AssetInputStream) assetManager.open("list.json");
        BufferedReader br = new BufferedReader(new InputStreamReader(ais));
        StringBuilder sb = new StringBuilder();

        int bufferSize = 1024 * 1024;
        char readBuf[] = new char[bufferSize];
        int resultSize = 0;

        while ((resultSize = br.read(readBuf)) != -1) {
            if (resultSize == bufferSize) {
                sb.append(readBuf);
            } else {
                for (int i = 0; i < resultSize; i++) {
                    sb.append(readBuf[i]);
                }
            }
        }

        String jString = sb.toString();
        JSONObject object = new JSONObject(jString);
        JSONArray list = new JSONArray(object.getString("list"));

        for (int i = 0; i < list.length(); i++) {
            JSONObject inside = list.getJSONObject(i);

            String title = inside.getString("title");
            String lats = inside.getString("lat");
            String lngs = inside.getString("lng");

            double lat = Double.parseDouble(lats);
            double lng = Double.parseDouble(lngs);

            LatLng position = new LatLng(lat, lng);

            Log.v("@@@", lats + ", " + lngs + ", " + title);

            Log.v("@@i=@@", String.valueOf(i));

            edulList.add(new House(position, title));

            i++;
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

private void createMarker() {
    mMap.clear();
    mMap.setOnMarkerClickListener(null);
    mMap.setInfoWindowAdapter(null);

    MarkerOptions markerOptions = new MarkerOptions();

    for (int i = 0; i < edulList.size(); i++) {
        LatLng position = edulList.get(i).getLatLng();
        String title = edulList.get(i).getTitle();

        markerOptions.position(position);
        markerOptions.title(title);
        mMap.addMarker(markerOptions).hideInfoWindow();
    }

    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            infoWindow = getLayoutInflater().inflate(R.layout.markerinfo, null);
            mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
                @Override
                public View getInfoWindow(Marker marker) {
                    ((TextView)infoWindow.findViewById(R.id.tx_infoWindowTitle)).setText(marker.getTitle());
                    ((TextView)infoWindow.findViewById(R.id.tx_infoWindowContent)).setText(marker.getPosition().toString());
                    return infoWindow;
                }

                @Override
                public View getInfoContents(Marker marker) {
                    return null;
                }
            });

            return false;

        }
    });
}

private void createCluster() {
    mMap.clear();
    mMap.setOnMarkerClickListener(null);
    mMap.setInfoWindowAdapter(null);

    ClusterManager mClusterManager = new ClusterManager<>(this, mMap);

    for (int i = 0; i < edulList.size(); i++) {
        LatLng position = edulList.get(i).getLatLng();
        String title = edulList.get(i).getTitle();

        mClusterManager.addItem(edulList.get(i));
    }
    mClusterManager.cluster();

    mMap.setOnMarkerClickListener(mClusterManager);

    mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener() {
        @Override
        public boolean onClusterItemClick(final ClusterItem clusterItem) {
            infoWindow = getLayoutInflater().inflate(R.layout.markerinfo, null);
            mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
                @Override
                public View getInfoWindow(Marker marker) {
                    ((TextView)infoWindow.findViewById(R.id.tx_infoWindowTitle)).setText(marker.getTitle());
                    ((TextView)infoWindow.findViewById(R.id.tx_infoWindowContent)).setText(marker.getPosition().toString());
                    return infoWindow;
                }

                @Override
                public View getInfoContents(Marker marker) {
                    return null;
                }
            });

            return false;
        }
    });

    mClusterManager.setOnClusterClickListener(new ClusterManager.OnClusterClickListener() {
        @Override
        public boolean onClusterClick(Cluster cluster) {
            mMap.setInfoWindowAdapter(null);
            mMap.moveCamera(CameraUpdateFactory.zoomIn());
            return false;
        }
    });
}

@Override
public void onCameraMove() {
    CameraPosition cameraPosition = mMap.getCameraPosition();
    float zoom = cameraPosition.zoom;

    Log.v("@@", "" + pastZoom + " / " + zoom);

    if (pastZoom == zoom) {

    } else {
        if (zoom < 13) {
            if(clusters == 0){
                createCluster();
                marks = 0;
                clusters = 1;
            }

        } else {
            if(marks == 0){
                createMarker();
                marks = 1;
                clusters = 0;
            }
        }
        pastZoom = zoom;
    }
}
</code>```

}

Body:
I have little problem of Cluster and Custom InfoWindow.

I don't want to show Infowindow when i click cluster.
But my application is show Infowindow when i click clusterItem and click Cluter. It show last click ClusterItem's Infowindow.

Code :

public class MapsLActivity extends FragmentActivity implements OnMapReadyCallback, ClusterManager.OnClusterItemClickListener<House>, GoogleMap.OnMapClickListener, ClusterManager.OnClusterClickListener<House>{

private GoogleMap mMap;
private View infoWindow;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps_k);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.getUiSettings().setZoomControlsEnabled(true);

    ClusterManager<House> mClusterManager = new ClusterManager<>(this, mMap);

    mMap.setOnMapClickListener(this);
    mMap.setOnMarkerClickListener(mClusterManager);
    mMap.setOnCameraChangeListener(mClusterManager);

    AssetManager assetManager = getResources().getAssets();
    try {
        AssetManager.AssetInputStream ais = (AssetManager.AssetInputStream) assetManager.open("yb_edu.json");
        BufferedReader br = new BufferedReader(new InputStreamReader(ais));
        StringBuilder sb = new StringBuilder();

        int bufferSize = 1024 * 1024;
        char readBuf[] = new char[bufferSize];
        int resultSize = 0;

        while ((resultSize = br.read(readBuf)) != -1) {
            if (resultSize == bufferSize) {
                sb.append(readBuf);
            } else {
                for (int i = 0; i < resultSize; i++) {
                    sb.append(readBuf[i]);
                }
            }
        }

        String jString = sb.toString();
        JSONObject object = new JSONObject(jString);
        JSONArray list = new JSONArray(object.getString("yb_edu"));

        for (int i = 0; i < list.length(); i++) {
            JSONObject inside = list.getJSONObject(i);

            String title = inside.getString("title");
            String lats = inside.getString("lat");
            String lngs = inside.getString("lng");

            double lat = Double.parseDouble(lats);
            double lng = Double.parseDouble(lngs);

            LatLng position = new LatLng(lat, lng);

            Log.v("@@@", "postion : " + position);

            Log.v("@@i=@@", String.valueOf(i));

            i++;

            mClusterManager.addItem(new House(position, title));
        }
        mClusterManager.cluster(); //클러스터 새로고침
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    mClusterManager.setOnClusterItemClickListener(this);
    mClusterManager.setOnClusterClickListener(this);
}

@Override
public boolean onClusterItemClick(final House house) {
    Toast.makeText(this, "onClusterItemClick", Toast.LENGTH_SHORT).show();

    LatLng latLng = house.getLatLng();

    Log.v("@@", "LatLng : " + latLng);

    infoWindow = getLayoutInflater().inflate(R.layout.markerinfo, null);
    mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
        @Override
        public View getInfoWindow(Marker marker) {
            ((TextView)infoWindow.findViewById(R.id.tx_infoWindowTitle)).setText(house.getTitle());
            ((TextView)infoWindow.findViewById(R.id.tx_infoWindowContent)).setText(house.getLatLng().toString());
            return infoWindow;
        }

        @Override
        public View getInfoContents(Marker marker) {
            return null;
        }
    });

    return false;
}

@Override
public boolean onClusterClick(Cluster<House> cluster) {
    mMap.moveCamera(CameraUpdateFactory.zoomIn());
    Toast.makeText(this, "onClusterClick", Toast.LENGTH_SHORT).show();
    return false;
}

@Override
public void onMapClick(LatLng latLng) {
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
}

Body:
Finally i resolve it....

public class MapsPActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnCameraMoveListener {

private GoogleMap mMap;
private float pastZoom = 0;
private ArrayList<House> edulList;

private int clusters = 0;
private int marks = 0;

private View infoWindow;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps_m);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.getUiSettings().setZoomControlsEnabled(true);

    edulList = new ArrayList<>();

    addEdu();

    mMap.setOnMarkerClickListener(null);
    mMap.setInfoWindowAdapter(null);
    mMap.setOnCameraMoveListener(this);

}

private void addEdu() {
    try {
        AssetManager assetManager = getResources().getAssets();
        AssetManager.AssetInputStream ais = (AssetManager.AssetInputStream) assetManager.open("list.json");
        BufferedReader br = new BufferedReader(new InputStreamReader(ais));
        StringBuilder sb = new StringBuilder();

        int bufferSize = 1024 * 1024;
        char readBuf[] = new char[bufferSize];
        int resultSize = 0;

        while ((resultSize = br.read(readBuf)) != -1) {
            if (resultSize == bufferSize) {
                sb.append(readBuf);
            } else {
                for (int i = 0; i < resultSize; i++) {
                    sb.append(readBuf[i]);
                }
            }
        }

        String jString = sb.toString();
        JSONObject object = new JSONObject(jString);
        JSONArray list = new JSONArray(object.getString("list"));

        for (int i = 0; i < list.length(); i++) {
            JSONObject inside = list.getJSONObject(i);

            String title = inside.getString("title");
            String lats = inside.getString("lat");
            String lngs = inside.getString("lng");

            double lat = Double.parseDouble(lats);
            double lng = Double.parseDouble(lngs);

            LatLng position = new LatLng(lat, lng);

            Log.v("@@@", lats + ", " + lngs + ", " + title);

            Log.v("@@i=@@", String.valueOf(i));

            edulList.add(new House(position, title));

            i++;
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

private void createMarker() {
    mMap.clear();
    mMap.setOnMarkerClickListener(null);
    mMap.setInfoWindowAdapter(null);

    MarkerOptions markerOptions = new MarkerOptions();

    for (int i = 0; i < edulList.size(); i++) {
        LatLng position = edulList.get(i).getLatLng();
        String title = edulList.get(i).getTitle();

        markerOptions.position(position);
        markerOptions.title(title);
        mMap.addMarker(markerOptions).hideInfoWindow();
    }

    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            infoWindow = getLayoutInflater().inflate(R.layout.markerinfo, null);
            mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
                @Override
                public View getInfoWindow(Marker marker) {
                    ((TextView)infoWindow.findViewById(R.id.tx_infoWindowTitle)).setText(marker.getTitle());
                    ((TextView)infoWindow.findViewById(R.id.tx_infoWindowContent)).setText(marker.getPosition().toString());
                    return infoWindow;
                }

                @Override
                public View getInfoContents(Marker marker) {
                    return null;
                }
            });

            return false;

        }
    });
}

private void createCluster() {
    mMap.clear();
    mMap.setOnMarkerClickListener(null);
    mMap.setInfoWindowAdapter(null);

    ClusterManager mClusterManager = new ClusterManager<>(this, mMap);

    for (int i = 0; i < edulList.size(); i++) {
        LatLng position = edulList.get(i).getLatLng();
        String title = edulList.get(i).getTitle();

        mClusterManager.addItem(edulList.get(i));
    }
    mClusterManager.cluster();

    mMap.setOnMarkerClickListener(mClusterManager);

    mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener() {
        @Override
        public boolean onClusterItemClick(final ClusterItem clusterItem) {
            infoWindow = getLayoutInflater().inflate(R.layout.markerinfo, null);
            mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
                @Override
                public View getInfoWindow(Marker marker) {
                    ((TextView)infoWindow.findViewById(R.id.tx_infoWindowTitle)).setText(marker.getTitle());
                    ((TextView)infoWindow.findViewById(R.id.tx_infoWindowContent)).setText(marker.getPosition().toString());
                    return infoWindow;
                }

                @Override
                public View getInfoContents(Marker marker) {
                    return null;
                }
            });

            return false;
        }
    });

    mClusterManager.setOnClusterClickListener(new ClusterManager.OnClusterClickListener() {
        @Override
        public boolean onClusterClick(Cluster cluster) {
            mMap.setInfoWindowAdapter(null);
            mMap.moveCamera(CameraUpdateFactory.zoomIn());
            return false;
        }
    });
}

@Override
public void onCameraMove() {
    CameraPosition cameraPosition = mMap.getCameraPosition();
    float zoom = cameraPosition.zoom;

    Log.v("@@", "" + pastZoom + " / " + zoom);

    if (pastZoom == zoom) {

    } else {
        if (zoom < 13) {
            if(clusters == 0){
                createCluster();
                marks = 0;
                clusters = 1;
            }

        } else {
            if(marks == 0){
                createMarker();
                marks = 1;
                clusters = 0;
            }
        }
        pastZoom = zoom;
    }
}

}


问:
Correct mongo database is not picked up from the connection parameter, instead have to map it manually
I am having an issue where I need to manually map the correct database to the domain instead of it being picked up from the connection argument.
I am using grails 3.2.8, plugin "org.grails.plugins:mongodb:6.1.0". I have both hibernate and mongodb plugin enabled.

I have define my connection URL as

```<code>//application.yml
   mongodb:
      url: 'mongodb://${MONGODB_USERNAME}:${MONGODB_PASSWORD}@${MONGODB_REPLICA_SET}/${MONGODB_DATABASE}?${MONGODB_CONNECTION_OPTIONS}'
</code>```

My domain object is defined as :

```<code>class ReportData {

    String id
    Long someField

    static mapWith = "mongo"
    static mapping = {
        //database "db-name" DOESN'T WORK WHEN COMMENTING OUT THIS LINE
    }
}
</code>```

Shouldn't the database(system property MONGODB_DATABASE) be picked up auto-magically from the connection url? I am not sure if this is a bug or I am missing some configuration aspect.

答:
I realized that I had not added following in my build.gradle file:

```<code>bootRun {
    systemProperties = System.properties
}
</code>```

so my application environment settings were not even getting applied correctly and hence my connection url was invalid.

I found that detail here: http://docs.grails.org/latest/guide/conf.html

Body:
I am having an issue where I need to manually map the correct database to the domain instead of it being picked up from the connection argument.
I am using grails 3.2.8, plugin "org.grails.plugins:mongodb:6.1.0". I have both hibernate and mongodb plugin enabled.

I have define my connection URL as

//application.yml
   mongodb:
      url: 'mongodb://${MONGODB_USERNAME}:${MONGODB_PASSWORD}@${MONGODB_REPLICA_SET}/${MONGODB_DATABASE}?${MONGODB_CONNECTION_OPTIONS}'

My domain object is defined as :

class ReportData {

    String id
    Long someField

    static mapWith = "mongo"
    static mapping = {
        //database "db-name" DOESN'T WORK WHEN COMMENTING OUT THIS LINE
    }
}

Shouldn't the database(system property MONGODB_DATABASE) be picked up auto-magically from the connection url? I am not sure if this is a bug or I am missing some configuration aspect.

Body:
I realized that I had not added following in my build.gradle file:

bootRun {
    systemProperties = System.properties
}

so my application environment settings were not even getting applied correctly and hence my connection url was invalid.

I found that detail here: http://docs.grails.org/latest/guide/conf.html


问:
How do I log out of TFS plugin in Eclipse?
I have added a TFS to my eclipse IDE on my Mac.

I signed into the TFS server and everything was fine. I would now like to sign out so that my collegue could sign in.

But there is no clear way to do this!

How do I sign out of my TFS account in the Eclipse TFS plugin on my Mac?

The only thing I could find was the image below in Preferences but there is no entry in the Keychain for TFS

答: it uses the credentials from keychain because you checked checkbox to save them at the first place. Simple solution would be to update those credentials from your keychain. You can also just delete them from your keychain so next time you launch eclipse you'll see "sign in to your TFS" link in Team Explorer </p>


问:
How to use single quotes in the MySQL query in Python
So I am trying to create a script with a MySQL Query "show databases like 'login';"

I am able to use string substitution and use "login" but i am unable to get the single quotes around it.

Below is how I am trying to do it but i cant get the single quotes even if I escape it using "\".

```<code>  db = "'"+val+"'"
  print "DB...", db
  run.cmd("echo 'res = cur.execute(\"SHOW DATABASES like  %s;\")\n' >> /run.py" % (db))
</code>```

答:
Since your string is wrapped in double quotes you shouldn't need to escape the single quotes. Just add the val directly into the format, then add the single quotes to the string being formatted.

```<code>run.cmd("echo 'res = cur.execute(\"SHOW DATABASES like  '%s';\")\n' >> /run.py" % (val))
</code>```

Also, is there any reason why you're appending a bash command into a python script?

Body:
So I am trying to create a script with a MySQL Query "show databases like 'login';"

I am able to use string substitution and use "login" but i am unable to get the single quotes around it.

Below is how I am trying to do it but i cant get the single quotes even if I escape it using "\".

  db = "'"+val+"'"
  print "DB...", db
  run.cmd("echo 'res = cur.execute(\"SHOW DATABASES like  %s;\")\n' >> /run.py" % (db))

Body:
Since your string is wrapped in double quotes you shouldn't need to escape the single quotes. Just add the val directly into the format, then add the single quotes to the string being formatted.

run.cmd("echo 'res = cur.execute(\"SHOW DATABASES like  '%s';\")\n' >> /run.py" % (val))

Also, is there any reason why you're appending a bash command into a python script?


问:
jQuery add # to all internal links
Can someone tell me how to add hashes to all the internal links on a page?

For example:

```<code>page.html > page.html#
</code>```

Thank you,
d

答:
```<code>$("a").each(function() {
  $this = $(this);
  $this.attr("href", $this.attr("href") + "#");
});
</code>```

Title: jQuery add # to all internal links

Body:
Can someone tell me how to add hashes to all the internal links on a page?

For example:

page.html > page.html#

Thank you,
d


问:
Extract an unassigned subnet CIDR block from a fragmented VPC
Lets suppose you have a VPC with a given cidr block. Let's say 10.0.0.0/16.
Now let's say you have assigned about 20 subnets from the VPC. And those subnets are neither contiguous nor of the same width. ie one given subnet is 10.0.0.7/27, and some other subnet is 10.0.128.0/25 and so forth.

What if I want to carve a subnet with 32 IP addresses (or n ip addresses). How do I get its cidr block?

Are there any good aws libraries, terraform libraries or anyone has encountered this problem and solved it. I want to be able to create new subnets with given widths.

I am aware of ec2.describe-subnets, jq, ipcalc and so forth.

答:
I'd use the Python netaddr package to solve your problem:</p>

```<code>from netaddr import *
import math

cidr = '10.0.0.0/16' # Your VPC's CIDR block

assigned = [ # Networks you've already used
  '10.0.0.7/27',
  '10.0.128.0/25'
]

needed_ips = 32 # Number of IP addresses needed

available = IPSet([cidr]) - IPSet(assigned)
needed_prefix = 32 - math.ceil(math.log2(needed_ips))
for net in available.iter_cidrs():
  if net.prefixlen <= needed_prefix:
    print(next(net.subnet(needed_prefix, 1)))
    break
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'd use the Python netaddr package to solve your problem:

from netaddr import *
import math

cidr = '10.0.0.0/16' # Your VPC's CIDR block

assigned = [ # Networks you've already used
  '10.0.0.7/27',
  '10.0.128.0/25'
]

needed_ips = 32 # Number of IP addresses needed

available = IPSet([cidr]) - IPSet(assigned)
needed_prefix = 32 - math.ceil(math.log2(needed_ips))
for net in available.iter_cidrs():
  if net.prefixlen <= needed_prefix:
    print(next(net.subnet(needed_prefix, 1)))
    break


问:
angular 2 ngrx/store unavailable data breaks async pipe
If my initial state is something like

```<code>export const initialState: State = {
  release: '',
  shape: '',
  story: '',
  keyFeatures: [''],
  colors: []
};

export function reducer(state = initialState, action): State {
    switch(action.type) {
        case "UPDATE_PRODUCT": return Object.assign({}, action.payload || state);
        case "UPDATE_COLOR":
            return Object.assign({}, state, {currentColor: action.payload.currentColor, imagePaths: action.payload.imagePaths})
        default:
            return state;
    }
}
</code>```

and the the component is consuming the state like this

```<code><img class="glassesImg" [images]="paths | async" >

_store.select('product')
      .subscribe((product: State) => {
        this.collection = product.collection;
        this.release = product.release;
        this.sku = product.sku;
        this.paths = product.imagePaths;
    })
</code>```

I'm getting the error "Invalid argument '' for pipe 'AsyncPipe'" when there isn't any available data. I'd expect that the AsyncPipe simply can subscribe to '' as a valid string value for that property? What am I missing?

答:
Why do you need the async pipe with normal sync values? async needs to be used with Observable or Promise, but paths is just a normal value type.

If you want to use async, you could do something like

```<code><something [blah]="(model$ | async)?.someProperty">

class Component {
  model$
  ...
  this.model$ = store.select(..)
}
</code>```

Or just don't use async and just initialize your component properties with a default value, until the first value comes in from the store.

Body:
If my initial state is something like

export const initialState: State = {
  release: '',
  shape: '',
  story: '',
  keyFeatures: [''],
  colors: []
};

export function reducer(state = initialState, action): State {
    switch(action.type) {
        case "UPDATE_PRODUCT": return Object.assign({}, action.payload || state);
        case "UPDATE_COLOR":
            return Object.assign({}, state, {currentColor: action.payload.currentColor, imagePaths: action.payload.imagePaths})
        default:
            return state;
    }
}

and the the component is consuming the state like this

_store.select('product')
      .subscribe((product: State) => {
        this.collection = product.collection;
        this.release = product.release;
        this.sku = product.sku;
        this.paths = product.imagePaths;
    })

I'm getting the error "Invalid argument '' for pipe 'AsyncPipe'" when there isn't any available data. I'd expect that the AsyncPipe simply can subscribe to '' as a valid string value for that property? What am I missing?

Body:
Why do you need the async pipe with normal sync values? async needs to be used with Observable or Promise, but paths is just a normal value type.

If you want to use async, you could do something like

<something [blah]="(model$ | async)?.someProperty">

class Component {
  model$
  ...
  this.model$ = store.select(..)
}

Or just don't use async and just initialize your component properties with a default value, until the first value comes in from the store.


问:
MQ message received as byte array instead of String
I am using Websphere MQ and reading messages from the queue using Spring integration and a jms adapter.

When I manually add messages to the queue the application is reading them and reading the data as a String and everything is fine.

However, when an external party is adding messages to the queue the application is reading them as a byte array and then throwing this exception:

```<code>Caused by: java.lang.ClassCastException: [B cannot be cast to java.lang.String
</code>```

The messages look the same to me in MQExplorer.

Although I have noticed a Format column, where the messages that are being processed as Strings have the value MQSTR and the message being processed as a Byte[] has nothing in there. Could this be related? If so any ideas how to set the "format" of the message?

Does anybody know what determines the payload content type of a message, that way I may be able to recreate the issue at least?

答:
On native MQ message sender side, set the mqmd["Format"] = 'MQSTR' will make sure the message is sent in jms_text format, otherwise by default it's in bytes format.

I got it working in Python2.7 with Pymqi.

Body:
I am using Websphere MQ and reading messages from the queue using Spring integration and a jms adapter.

When I manually add messages to the queue the application is reading them and reading the data as a String and everything is fine.

However, when an external party is adding messages to the queue the application is reading them as a byte array and then throwing this exception:

Caused by: java.lang.ClassCastException: [B cannot be cast to java.lang.String

The messages look the same to me in MQExplorer.

Although I have noticed a Format column, where the messages that are being processed as Strings have the value MQSTR and the message being processed as a Byte[] has nothing in there. Could this be related? If so any ideas how to set the "format" of the message?

Does anybody know what determines the payload content type of a message, that way I may be able to recreate the issue at least?


问:
laravel 5 - Eloquent Relationships (permissions table)
I think am struggling to get the relationships correctly in the scenario I have.

I have three tables

```<code>Table: users

|  id  |   username  |
----------------------
|   1  |    pluto    |
|------|-------------|

Table: permissions

|  id  |   user_id   |   level_id   |   app_id   |
--------------------------------------------------
|   1  |      1      |       2      |     9      |
|------|-------------|--------------|------------|

Table: levels

|  id  |    level    |
----------------------
|   1  |    admin    |
|------|-------------|
|   2  |   manager   |
|------|-------------|
|   3  |    editor   |
|------|-------------|
</code>```

The result I am looking to get is

```<code>manager //through User:: model or Auth::
</code>```

I would like to get a value from levels table in level column either through User model. This is the last version on what I have in my classes...

```<code>class User extends Authenticatable
{
    public function permissions()
    {
        return $this->hasOne('App\Permissions');
    }
}

class Permissions extends Model
{
    public function user()
    {
        return $this->hasMany('App\User');
    }

    public function levels()
    {
        return $this->hasMany('App\Levels');
    }
}

class Levels extends Model
{
    public function permissions()
    {
        return $this->belongsTo('Modules\Ecosystem\Entities\permissions');
    }
}
</code>```

Using this in the controller I am able to retrieve values from permissions table. However I am unable to get values from levels table...

```<code>$user = User::with('permissions')->find(Auth::user()->id);
</code>```

However I am unable to get values from levels table when I try this...

```<code>$user = User::with('permissions.levels')->find(Auth::user()->id);
</code>```

That produces an error:

```<code>Column not found: 1054 Unknown column 'levels.permissions_id' in 'where clause' (SQL: select * from `levels` where `levels`.`permissions_id` in (1))
</code>```

I understand that I am not understanding exactly how relationships would work in this instance but I don't want to just guess a solution. I'd like to understand it.

The thing is ,, Levels table serves only as a list of permission levels (roles). I recognize that I can define permission levels in some other way but for the moment this is how everything is set up.

答:
If you are making a usual user permission system, where 'roles' is replaced by 'levels', then you need to reorganized your tables and relationships.

```<code>Table: users

|  id  |   username  |    level_id    |
---------------------------------------
|   1  |    pluto    |       2        |
|------|-------------|----------------|

Table: levels

|  id  |    level    |
----------------------
|   1  |    admin    |
|------|-------------|
|   2  |   manager   |
|------|-------------|
|   3  |    editor   |
|------|-------------|

Table: permissions

|  id  |  level_id   |   app_id   |
-----------------------------------
|   1  |      2      |     9      |
|------|-------------|------------|
</code>```

So now User

```<code>hasOne('App\Levels', 'level_id');
</code>```

Levels

```<code>hasMany('Modules\Ecosystem\Entities\permissions', 'level_id');
</code>```

Permissions

```<code>belongsTo('App\Levels', 'level_id');
</code>```

That is probably what you were trying to do, and it will works.

However, if many roles may have similar permissions, e.g: admin, manager & editor can all have access to a 'Page' or 'Content' or whatever that they all have access to, then you will need a 4th table to have many-to-many relationship between permissions and levels.

```<code>Table: permissions

|  id  |   app_id   |
---------------------
|   1  |     9      |
|------|------------|

Table: levels_permissions

|  level_id   |   permission_id   |
-----------------------------------
|      2      |         1         |
|-------------|-------------------|
</code>```

With this, in Levels

```<code>belongsToMany('Modules\Ecosystem\Entities\permissions', 'levels_permissions', 'level_id', 'permission_id');
</code>```

Inverse the relation in Permissions

```<code>belongsToMany('App\Levels', 'levels_permissions', 'permission_id', 'level_id');
</code>```

In both approaches, you can now do

```<code>$user = User::with('levels.permissions')->find(Auth::user()->id);
</code>```

Body:
I think am struggling to get the relationships correctly in the scenario I have.

I have three tables

Table: users

|  id  |   username  |
----------------------
|   1  |    pluto    |
|------|-------------|

Table: permissions

|  id  |   user_id   |   level_id   |   app_id   |
--------------------------------------------------
|   1  |      1      |       2      |     9      |
|------|-------------|--------------|------------|

Table: levels

|  id  |    level    |
----------------------
|   1  |    admin    |
|------|-------------|
|   2  |   manager   |
|------|-------------|
|   3  |    editor   |
|------|-------------|

The result I am looking to get is

manager //through User:: model or Auth::

I would like to get a value from levels table in level column either through User model. This is the last version on what I have in my classes...

class User extends Authenticatable
{
    public function permissions()
    {
        return $this->hasOne('App\Permissions');
    }
}

class Permissions extends Model
{
    public function user()
    {
        return $this->hasMany('App\User');
    }

    public function levels()
    {
        return $this->hasMany('App\Levels');
    }
}

class Levels extends Model
{
    public function permissions()
    {
        return $this->belongsTo('Modules\Ecosystem\Entities\permissions');
    }
}

Using this in the controller I am able to retrieve values from permissions table. However I am unable to get values from levels table...

$user = User::with('permissions')->find(Auth::user()->id);

However I am unable to get values from levels table when I try this...

$user = User::with('permissions.levels')->find(Auth::user()->id);

That produces an error:

Column not found: 1054 Unknown column 'levels.permissions_id' in 'where clause' (SQL: select * from `levels` where `levels`.`permissions_id` in (1))

I understand that I am not understanding exactly how relationships would work in this instance but I don't want to just guess a solution. I'd like to understand it.

The thing is ,, Levels table serves only as a list of permission levels (roles). I recognize that I can define permission levels in some other way but for the moment this is how everything is set up.

Body:
If you are making a usual user permission system, where 'roles' is replaced by 'levels', then you need to reorganized your tables and relationships.

Table: users

|  id  |   username  |    level_id    |
---------------------------------------
|   1  |    pluto    |       2        |
|------|-------------|----------------|

Table: levels

|  id  |    level    |
----------------------
|   1  |    admin    |
|------|-------------|
|   2  |   manager   |
|------|-------------|
|   3  |    editor   |
|------|-------------|

Table: permissions

|  id  |  level_id   |   app_id   |
-----------------------------------
|   1  |      2      |     9      |
|------|-------------|------------|

So now User

hasOne('App\Levels', 'level_id');

Levels

hasMany('Modules\Ecosystem\Entities\permissions', 'level_id');

Permissions

belongsTo('App\Levels', 'level_id');

That is probably what you were trying to do, and it will works.

However, if many roles may have similar permissions, e.g: admin, manager & editor can all have access to a 'Page' or 'Content' or whatever that they all have access to, then you will need a 4th table to have many-to-many relationship between permissions and levels.

Table: permissions

|  id  |   app_id   |
---------------------
|   1  |     9      |
|------|------------|

Table: levels_permissions

|  level_id   |   permission_id   |
-----------------------------------
|      2      |         1         |
|-------------|-------------------|

With this, in Levels

belongsToMany('Modules\Ecosystem\Entities\permissions', 'levels_permissions', 'level_id', 'permission_id');

Inverse the relation in Permissions

belongsToMany('App\Levels', 'levels_permissions', 'permission_id', 'level_id');

In both approaches, you can now do

$user = User::with('levels.permissions')->find(Auth::user()->id);


问:
Template matrix with std vector
I've tryed to make a 2D Matrix template Class unsing std vectors. So far so good most functions work as exepted. But when I try to write accessor or getter and setter functions I get some problems.
At first this the basic layout of my class:

```<code>template <class T>
class DynamicMatrix
{
private:
    vector<vector<T>> map;
...
}
</code>```

My first attempt were accessor functions:

```<code>template <class T>
T& DynamicMatrix<T>::at(size_t x, size_t y)
{
    return(map.at(x).at(y));
}
template <class T>
const T& DynamicMatrix<T>::at(size_t x, size_t y) const
{
    return(map.at(x).at(y));
}
</code>```

but when I try to call gameMap.at(x, y) = objxy; the compiler says its a deleted function.

So I tryed getters and setters and came to the same result when trying to assign a Value.

答: You didn't mention what T is in your gameMap but I suppose it doesn't have an accessible copy constructor thus assigning objxy fails.

Title: Template matrix with std vector

Body:
I've tryed to make a 2D Matrix template Class unsing std vectors. So far so good most functions work as exepted. But when I try to write accessor or getter and setter functions I get some problems.
At first this the basic layout of my class:

template <class T>
class DynamicMatrix
{
private:
    vector<vector<T>> map;
...
}

My first attempt were accessor functions:

template <class T>
T& DynamicMatrix<T>::at(size_t x, size_t y)
{
    return(map.at(x).at(y));
}
template <class T>
const T& DynamicMatrix<T>::at(size_t x, size_t y) const
{
    return(map.at(x).at(y));
}

but when I try to call gameMap.at(x, y) = objxy; the compiler says its a deleted function.

So I tryed getters and setters and came to the same result when trying to assign a Value.


答:
Well looking over your code every time your for loop runs it will print out the line

```<code> System.out.print("Enter the numbers: ");
</code>```

For as many times as you set the amount of numbers, in this case 10.

In order to fix this you would want to add System.out.print("Enter the numbers: "); before the for loop.

Title: How to output multiple numbers at once in a for loop using Java

Body:
I'm very new to Java programming (2 weeks in) and currently am practicing arrays.

My code is as follows:

import java.util.Scanner;

public class LA2_2_1 {
    public static void main (String[] args)
    {
        Scanner scan = new Scanner(System.in);
        int x;
        double avg;
        double num = 0;

        System.out.print("Enter the number of items: ");
        x = scan.nextInt();

        int [] numbers = new int [x];
        double sum = 0;
        sum = sum + num;

        for (int index = 0; index < numbers.length; index++)
        {
            System.out.print("Enter the numbers: ");
            num = scan.nextDouble();
            sum = sum + num;
            System.out.println(sum);
        }
        avg = sum/x;
        System.out.println("The average is " + avg);
    }
}

Output:

Enter the number of items: 10

Enter the numbers: 3.4 5 6 1 6.5 7.8 3.5 8.5 6.3 9.5

3.4

Enter the numbers: 8.4

Enter the numbers: 14.4

Enter the numbers: 15.4

Enter the numbers: 21.9

Enter the numbers: 29.7

Enter the numbers: 33.2

Enter the numbers: 41.7

Enter the numbers: 48.0

Enter the numbers: 57.5

The average is 5.75

My question is, how can I format the code so that I get "Enter the numbers" to appear only once? I just want the program to ask the user for the series of numbers they want to input. I do not want it to output multiple "Enter the numbers".

I think this may have to do with the output being within a for loop, but I am not too positive. I tried taking it out, and both the average and output for "Enter the numbers" turned to 0.0.

Any input would be helpful.

Thank you

Body:
Well looking over your code every time your for loop runs it will print out the line

 System.out.print("Enter the numbers: ");

For as many times as you set the amount of numbers, in this case 10.

In order to fix this you would want to add System.out.print("Enter the numbers: "); before the for loop.


答:
it's simple just put input prompt statement outside for loop:</p>

```<code>System.out.print("Enter the numbers: ");

for (int index = 0; index < numbers.length; index++)
{
        num = scan.nextDouble();
        sum = sum + num;
}
System.out.println(sum); // sum print statement outside loop to get total sum
</code>```

Body:
it's simple just put input prompt statement outside for loop:

System.out.print("Enter the numbers: ");

for (int index = 0; index < numbers.length; index++)
{
        num = scan.nextDouble();
        sum = sum + num;
}
System.out.println(sum); // sum print statement outside loop to get total sum


答:
Perhaps you could try this:</p>

```<code>$(document).ready(function() {
    var attr = $('a').attr('href');
    attr = attr + '#';
    $('a').attr('href', attr);
});
</code>```

Title: jQuery add # to all internal links

Body:
Perhaps you could try this:

$(document).ready(function() {
    var attr = $('a').attr('href');
    attr = attr + '#';
    $('a').attr('href', attr);
});