问:
Why setImmediate() execute before fs.readFile() in Nodejs Event Loop's works?

I have read a lot of related documents.But I still can't understand how it works.

```<code>const fs = require('fs')
const now = Date.now();

setTimeout(() => console.log('timer'), 10);
fs.readFile(__filename, () => console.log('readfile'));
setImmediate(() => console.log('immediate'));
while(Date.now() - now < 1000) {
}
</code>```

```<code>const now = Date.now();

setImmediate(() => console.log('immediate'));
setTimeout(() => console.log('timer'), 10);
while(Date.now() - now < 1000) {
}
</code>```

I think the first piece of code should log:

```<code>readfile
immediate
</code>```

And the second piece of code logs.

```<code>timer
immediate
</code>```

I think it is ok.

Problem：
I don't understand why the first piece of code logs

```<code>immediate
readfile
</code>```

I think that the file has been read completely and its callback function enqueue  I/O callbacks phase's queque after 1 second.

And then I think event loop will move to timers(none),I/O callbacks(fs.readFile's callback),idle/prepare(none),poll(none),check(setImmediate's callback)and finally close callbacks(none) in order, but result is that setImmediate() still run first.

答:
The behavior you see is because there are multiple types of queues in the event loop and the system runs events in an order according to their type.  It is not just one giant event queue where everything runs in FIFO order based on when it was added to the event queue.  Instead, it likes to run all the events of one type (up to a limit), advance to the next type, runs all those and so on.

And, I/O events are only added to their queue at one specific point in the cycle so they are forced into a particular order.  This is the reason that setImmediate() callback executes before the readFile() callback even though both are ready to go when the while loop is done.

And then I think event loop will move to timers(none),I/O callbacks(fs.readFile's callback),idle/prepare(none),poll(none),check(setImmediate's callback)and finally close callbacks(none) in order, but result is that setImmediate() still run first.

The issue is that the I/O callbacks stage of the event loop runs I/O callbacks that are already in the event queue, but they don't get put into the event queue automatically when they are done.  Instead, they are only put into the event queue later in the process in the I/O poll step (see diagram below).  So, the first time through the I/O callbacks stage, there are no I/O callbacks to run yet, thus you don't get the readfile output when you think you would.

But, the setImmediate() callback is ready the first time through the event loop so it gets to run before the readFile() callback.

This delayed addition of I/O callbacks is likely the explanation for why you are surprised that the readFile() callback happens last instead of before the setImmediate() callback.

Here's what happens when the while loop finishes:

When the while loop finishes, it starts with timer callbacks and sees that the timer is ready to run so it runs that.

Then, it goes to run any I/O callbacks that are already there, but there are none yet.  The I/O callback from the readFile() has not been collected yet.  It will get collected later in this cycle.

Then, it goes through several other stages and gets to I/O poll.  There is collects the readFile() callback event and puts it in the I/O queue (but does not run it yet).

Then, it goes to the checkHandlers phase where it runs the setImmediate() callback.

Then, it starts the event loop over again.  There are no timers so it goes to I/O callbacks and it finally finds and runs the readFile() callback.

So let's document what actually happens in your code in a little more detail for those that are not as familiar with the event loop process.  When you run this code (with timing added to the output):

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

let begin = 0;
function log(msg) {
    if (!begin) {
        begin = Date.now();
    }
    let t = ((Date.now() - begin) / 1000).toFixed(3);
    console.log("" + t + ": " + msg);
}

log('start program');

setTimeout(() => log('timer'), 10);
setImmediate(() => log('immediate'));
fs.readFile(__filename, () => log('readfile'));

const now = Date.now();
log('start loop');
while(Date.now() - now < 1000) {}
log('done loop');
</code>```

You get this output:

```<code>0.000: start program
0.004: start loop
1.004: done loop
1.005: timer
1.006: immediate
1.008: readfile
</code>```

I've added timing in seconds relative to when the program started so you can see when things are executed.

Here's what happens:

Timer is started and set for 10ms from now, other code continues to run

fs.readFile() operation is started, other code continues to run

setImmediate() is registered into the event system and its event is in the appropriate event queue, other code continues to run

while loop starts looping

During the while loop, the fs.readFile() finishes its work (running in the background).  It's event is ready, but not yet in the appropriate event queue (more on this later)

while loop finishes after 1 second of looping and this initial sequence of Javascript is done and returns back to the system

The interpreter now needs to get the "next" event from the event loop.  But, all types of events are not treated equally.  The event system has a particular order that it processes different types of events in the queue.  In our case, here, the timer event gets processed first (I will explain this in the following text).  The system checks to see if any timers have "expired" and are ready to call their callback.  In this case it finds that our timer has "expired" and is ready to go.

Timer callback is called and we see the console message timer.

There are no more timers so the event loop advances to its next stage.  The next stage of the event loop is to run any pending I/O callbacks.  But, there are no pending I/O callbacks in the event queue yet.  Even though the readFile() is done by now, it is not yet in the queue (explanation coming).

Then, the next step is to gather any I/O events that have finished and get them ready to run.  Here, the readFile() event will be collected (though not run yet) and put into the I/O event queue.

Then the next step is to run any setImmediate() handlers that are pending.  When it does that, we get the output immediate.

Then, the next step in the event process is to run any close handlers (there are none here to run).

Then, the event loop starts over again by checking for timers.  There are no pending timers to run.

Then, the event loop runs any pending I/O callbacks.  Here the readFile() callback runs and we see readfile in the console.

The program has no more events to wait for so it executes.

The event loop itself is a series of queues for different types of events and (with some exceptions), each queue is processed before moving onto the next type of queue.  This causes groupings of events (timers in one group, pending I/O callbacks in another group, setImmediate() in another group and so on).  It is not a strict FIFO queue among all types.  Events are FIFO within a group.  But, all pending timer callbacks (up to some limit to keep one type of event from hogging the event loop indefinitely) are processed before other types of callbacks.

You can see the basic structure in this diagram:

which comes from this very excellent article.  If you really want to understand all this stuff, then read this referenced article several times over.

What initially surprised me is why the readFile always comes at the end.  This is because even though the readFile() operation is done, it is not immediately put in the queue.  Instead, there's a step in the event loop where completed I/O events are collected (to be processed in the next cycle through the event loop) and setImmediate() events are processed at the end of the current cycle before the I/O events that were just collected.  This makes the readFile() callback go after the setImmediate() callback, even though they both are ready to go during the while loop.

And, further, it doesn't matter which order you execute the readFile() and the setImmediate().  Because they both are ready to go before the while loop is done, their execution order is determined by the sequencing though the event loop as it runs different types of events, not by exactly when they finished .

In your second code block, you remove the readFile() and put the setImmediate() before the setTimeout().  Using my timed version, that would be this:

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

let begin = 0;
function log(msg) {
    if (!begin) {
        begin = Date.now();
    }
    let t = ((Date.now() - begin) / 1000).toFixed(3);
    console.log("" + t + ": " + msg);
}

log('start program');

setImmediate(() => log('immediate'));
setTimeout(() => log('timer'), 10);

const now = Date.now();
log('start loop');
while(Date.now() - now < 1000) {}
log('done loop');
</code>```

And, it generates this output:

```<code>0.000: start program
0.003: start loop
1.003: done loop
1.005: timer
1.008: immediate
</code>```

The explanation is similar (shortened a bit this time since lots of detail was explained earlier).

setImmediate() is registered into the appropriate queue.

setTimeout() is registered into the timer queue.

The while loop runs for its 1000ms

The code finishes executing and returns control back to the system

The system starts at the top of the event logic which starts with timer events.  The timer we started earlier is done now so it runs its callback and logs timer.

With no more timers, the event loop runs through several other types of event queues until it gets to where it runs setImmediate() handlers and it logs immediate.

If, you have multiple items schedule to start within an I/O callback such as this:

```<code>// timeout_vs_immediate.js
const fs = require('fs');

fs.readFile(__filename, () => {
  setTimeout(() => {
    console.log('timeout');
  }, 0);
  setImmediate(() => {
    console.log('immediate');
  });
});
</code>```

Then, you get slightly different behavior because the setTimeout() and setImmediate() will be scheduled when the event loop is in a different part of its cycle.  In this particular example, the setImmediate() will always execute BEFORE the timer so the output will be:

```<code> immediate
 timeout
</code>```

In the flow chart above, you can see where the "run completed I/O handlers" step is.  Because the setTimeout() and setImmediate() calls will be scheduled from within an I/O handler, they are going to be scheduled at the "Run completed I/O handlers" phase of the event loop.  Follow the flow of the event loop, the setImmediate() will get serviced in the "check handlers" phase before the event loop gets back around to service timers.

If the setImmediate() and setTimeout() are scheduled at a different point in the event loop, then the timer may fire before setImmediate() which is what happens in the earlier example.  So, the relative timing of the two depends upon what phase the event loop is in when the functions are called.

Body:
I have read a lot of related documents.But I still can't understand how it works.

const fs = require('fs')
const now = Date.now();

setTimeout(() => console.log('timer'), 10);
fs.readFile(__filename, () => console.log('readfile'));
setImmediate(() => console.log('immediate'));
while(Date.now() - now < 1000) {
}

const now = Date.now();

setImmediate(() => console.log('immediate'));
setTimeout(() => console.log('timer'), 10);
while(Date.now() - now < 1000) {
}

I think the first piece of code should log:

readfile
immediate

And the second piece of code logs.

timer
immediate

I think it is ok.

Problem：
I don't understand why the first piece of code logs

immediate
readfile

I think that the file has been read completely and its callback function enqueue  I/O callbacks phase's queque after 1 second.

And then I think event loop will move to timers(none),I/O callbacks(fs.readFile's callback),idle/prepare(none),poll(none),check(setImmediate's callback)and finally close callbacks(none) in order, but result is that setImmediate() still run first.

Body:
The behavior you see is because there are multiple types of queues in the event loop and the system runs events in an order according to their type.  It is not just one giant event queue where everything runs in FIFO order based on when it was added to the event queue.  Instead, it likes to run all the events of one type (up to a limit), advance to the next type, runs all those and so on.

And, I/O events are only added to their queue at one specific point in the cycle so they are forced into a particular order.  This is the reason that setImmediate() callback executes before the readFile() callback even though both are ready to go when the while loop is done.

And then I think event loop will move to timers(none),I/O callbacks(fs.readFile's callback),idle/prepare(none),poll(none),check(setImmediate's callback)and finally close callbacks(none) in order, but result is that setImmediate() still run first.

The issue is that the I/O callbacks stage of the event loop runs I/O callbacks that are already in the event queue, but they don't get put into the event queue automatically when they are done.  Instead, they are only put into the event queue later in the process in the I/O poll step (see diagram below).  So, the first time through the I/O callbacks stage, there are no I/O callbacks to run yet, thus you don't get the readfile output when you think you would.

But, the setImmediate() callback is ready the first time through the event loop so it gets to run before the readFile() callback.

This delayed addition of I/O callbacks is likely the explanation for why you are surprised that the readFile() callback happens last instead of before the setImmediate() callback.

Here's what happens when the while loop finishes:

When the while loop finishes, it starts with timer callbacks and sees that the timer is ready to run so it runs that.

Then, it goes to run any I/O callbacks that are already there, but there are none yet.  The I/O callback from the readFile() has not been collected yet.  It will get collected later in this cycle.

Then, it goes through several other stages and gets to I/O poll.  There is collects the readFile() callback event and puts it in the I/O queue (but does not run it yet).

Then, it goes to the checkHandlers phase where it runs the setImmediate() callback.

Then, it starts the event loop over again.  There are no timers so it goes to I/O callbacks and it finally finds and runs the readFile() callback.

So let's document what actually happens in your code in a little more detail for those that are not as familiar with the event loop process.  When you run this code (with timing added to the output):

const fs = require('fs')

let begin = 0;
function log(msg) {
    if (!begin) {
        begin = Date.now();
    }
    let t = ((Date.now() - begin) / 1000).toFixed(3);
    console.log("" + t + ": " + msg);
}

log('start program');

setTimeout(() => log('timer'), 10);
setImmediate(() => log('immediate'));
fs.readFile(__filename, () => log('readfile'));

const now = Date.now();
log('start loop');
while(Date.now() - now < 1000) {}
log('done loop');

You get this output:

0.000: start program
0.004: start loop
1.004: done loop
1.005: timer
1.006: immediate
1.008: readfile

I've added timing in seconds relative to when the program started so you can see when things are executed.

Here's what happens:

Timer is started and set for 10ms from now, other code continues to run

fs.readFile() operation is started, other code continues to run

setImmediate() is registered into the event system and its event is in the appropriate event queue, other code continues to run

while loop starts looping

During the while loop, the fs.readFile() finishes its work (running in the background).  It's event is ready, but not yet in the appropriate event queue (more on this later)

while loop finishes after 1 second of looping and this initial sequence of Javascript is done and returns back to the system

The interpreter now needs to get the "next" event from the event loop.  But, all types of events are not treated equally.  The event system has a particular order that it processes different types of events in the queue.  In our case, here, the timer event gets processed first (I will explain this in the following text).  The system checks to see if any timers have "expired" and are ready to call their callback.  In this case it finds that our timer has "expired" and is ready to go.

Timer callback is called and we see the console message timer.

There are no more timers so the event loop advances to its next stage.  The next stage of the event loop is to run any pending I/O callbacks.  But, there are no pending I/O callbacks in the event queue yet.  Even though the readFile() is done by now, it is not yet in the queue (explanation coming).

Then, the next step is to gather any I/O events that have finished and get them ready to run.  Here, the readFile() event will be collected (though not run yet) and put into the I/O event queue.

Then the next step is to run any setImmediate() handlers that are pending.  When it does that, we get the output immediate.

Then, the next step in the event process is to run any close handlers (there are none here to run).

Then, the event loop starts over again by checking for timers.  There are no pending timers to run.

Then, the event loop runs any pending I/O callbacks.  Here the readFile() callback runs and we see readfile in the console.

The program has no more events to wait for so it executes.

The event loop itself is a series of queues for different types of events and (with some exceptions), each queue is processed before moving onto the next type of queue.  This causes groupings of events (timers in one group, pending I/O callbacks in another group, setImmediate() in another group and so on).  It is not a strict FIFO queue among all types.  Events are FIFO within a group.  But, all pending timer callbacks (up to some limit to keep one type of event from hogging the event loop indefinitely) are processed before other types of callbacks.

You can see the basic structure in this diagram:

which comes from this very excellent article.  If you really want to understand all this stuff, then read this referenced article several times over.

What initially surprised me is why the readFile always comes at the end.  This is because even though the readFile() operation is done, it is not immediately put in the queue.  Instead, there's a step in the event loop where completed I/O events are collected (to be processed in the next cycle through the event loop) and setImmediate() events are processed at the end of the current cycle before the I/O events that were just collected.  This makes the readFile() callback go after the setImmediate() callback, even though they both are ready to go during the while loop.

And, further, it doesn't matter which order you execute the readFile() and the setImmediate().  Because they both are ready to go before the while loop is done, their execution order is determined by the sequencing though the event loop as it runs different types of events, not by exactly when they finished .

In your second code block, you remove the readFile() and put the setImmediate() before the setTimeout().  Using my timed version, that would be this:

const fs = require('fs')

let begin = 0;
function log(msg) {
    if (!begin) {
        begin = Date.now();
    }
    let t = ((Date.now() - begin) / 1000).toFixed(3);
    console.log("" + t + ": " + msg);
}

log('start program');

setImmediate(() => log('immediate'));
setTimeout(() => log('timer'), 10);

const now = Date.now();
log('start loop');
while(Date.now() - now < 1000) {}
log('done loop');

And, it generates this output:

0.000: start program
0.003: start loop
1.003: done loop
1.005: timer
1.008: immediate

The explanation is similar (shortened a bit this time since lots of detail was explained earlier).

setImmediate() is registered into the appropriate queue.

setTimeout() is registered into the timer queue.

The while loop runs for its 1000ms

The code finishes executing and returns control back to the system

The system starts at the top of the event logic which starts with timer events.  The timer we started earlier is done now so it runs its callback and logs timer.

With no more timers, the event loop runs through several other types of event queues until it gets to where it runs setImmediate() handlers and it logs immediate.

If, you have multiple items schedule to start within an I/O callback such as this:

// timeout_vs_immediate.js
const fs = require('fs');

fs.readFile(__filename, () => {
  setTimeout(() => {
    console.log('timeout');
  }, 0);
  setImmediate(() => {
    console.log('immediate');
  });
});

Then, you get slightly different behavior because the setTimeout() and setImmediate() will be scheduled when the event loop is in a different part of its cycle.  In this particular example, the setImmediate() will always execute BEFORE the timer so the output will be:

 immediate
 timeout

In the flow chart above, you can see where the "run completed I/O handlers" step is.  Because the setTimeout() and setImmediate() calls will be scheduled from within an I/O handler, they are going to be scheduled at the "Run completed I/O handlers" phase of the event loop.  Follow the flow of the event loop, the setImmediate() will get serviced in the "check handlers" phase before the event loop gets back around to service timers.

If the setImmediate() and setTimeout() are scheduled at a different point in the event loop, then the timer may fire before setImmediate() which is what happens in the earlier example.  So, the relative timing of the two depends upon what phase the event loop is in when the functions are called.


来源: stackexchange

问:
Is multi_query in PHP necessarily subsequent
Given the following example:

```<code>$mysqli->query("SELECT * FROM `table`");
$mysqli->query("INSERT INTO `table` SET `x` = 'y' WHERE `x` = 2");
</code>```

I have no guarantee that all queries are necessarily executed subsequently. Another process may intercept and a deadlock may occur.

Does MySQL guarantee that they are executed subsequently without any other process making a query in between?

Please do not suggest transactions / locks. This question is regarding multi_query and its specifics.

Example Code in PHP:

```<code>$query = "SELECT * FROM `table`;";
$query .= "INSERT INTO `table` SET `x` = 'y' WHERE `x` = 2;";
$mysqli->multi_query($query);
</code>```

答:
Of course no. It would make a hell of any site using multi query, if it would make all the other world to wait.

What you are looking for is locks and possibly transactions

ContentLicense: CC BY-SA 3.0

Body:
Given the following example:

$mysqli->query("SELECT * FROM `table`");
$mysqli->query("INSERT INTO `table` SET `x` = 'y' WHERE `x` = 2");

I have no guarantee that all queries are necessarily executed subsequently. Another process may intercept and a deadlock may occur.

Does MySQL guarantee that they are executed subsequently without any other process making a query in between?

Please do not suggest transactions / locks. This question is regarding multi_query and its specifics.

Example Code in PHP:

$query = "SELECT * FROM `table`;";
$query .= "INSERT INTO `table` SET `x` = 'y' WHERE `x` = 2;";
$mysqli->multi_query($query);


问:
Finding out completed tasks in rails
I need to show records based on a column completed_at. What is the best way to check at controller.task belongs to the user and user has_many tasks. Can I check based whether the column is nil or have some value?. Or any other best ways? </p>

答:
The best way would be to use scope in the task model in rails 4,

```<code>scope :completed_task, ->{ where('completed_at IS NOT NULL') }
</code>```

Now You can get all completed task of the user by

```<code>@user.tasks.completed_task
</code>```

Title: Finding out completed tasks in rails

Body:
The best way would be to use scope in the task model in rails 4,

scope :completed_task, ->{ where('completed_at IS NOT NULL') }

Now You can get all completed task of the user by

@user.tasks.completed_task


问:
Automatically determining IMAP server name by email address
I am working on my own email client app. And currently, when a user adds a new mailbox, I make them to input IMAP server name manually (say, imap.gmail.com). By I've notices that there are mail client apps that somehow figure out the correct IMAP server name automatically.

So the question is, is there any database or something, that would take login as input and return IMAP server name as output?

If this is important, I am using Python (Django) and MySQL on the backend.

答: There is/was such a database, yes. Mozilla operates/operated it, for Thunderbird and I think most others copy the approaches usied in Thunderbird's source code.</p>


问:
python data frame key error on calling columns by index
```<code>subset = df[['country', 'continent', 'year']]
subset.head()
</code>```

This code is working fine but

```<code>subset = df[[1, 2, 3]]
</code>```

is giving me an error

```<code>KeyError: '[1 2 3] not in index'
</code>```

答:
If you want to get the columns by index try:

```<code>subset = df.iloc[:,[1, 2, 3]]
</code>```

or use df.columns and pass the list same way above.

```<code>subset = df[df.columns[[1, 2, 3]]]
</code>```

Assuming your column country is at 1 column index.

Body:
subset = df[['country', 'continent', 'year']]
subset.head()

This code is working fine but

subset = df[[1, 2, 3]]

is giving me an error

KeyError: '[1 2 3] not in index'

Body:
If you want to get the columns by index try:

subset = df.iloc[:,[1, 2, 3]]

or use df.columns and pass the list same way above.

subset = df[df.columns[[1, 2, 3]]]

Assuming your column country is at 1 column index.


问:
Animating a UIImage or UIImageView?
I'm trying to animate an image's height (from height of 0 pixels to 480 pixels) to create the effect of the image being rendered top-down.

With an UIImageView i noticed that it appears correct in the Interface Builder. But when it runs in the simulator the size (width and height) is always set to whatever the size of the image is; meaning, if I set the height of the image view to be 50% the original height, the image is still rendered in full height.

I also tried do this effect with an UIImage. However, although the size of the image appears correct, the image is scaled to reflect the size/aspect-ratio.

Question:
How can i achieve this dynamic sizing (i.e. animation of an image's size) while NOT scaling the image? I thought about using CGImageCreateWithMask, but im pretty sure that would create huge performance hiccups.

* Update *

The effect that im looking for is this:
Animate an image by making it grow in height, from to-down (like a set of blinds being pulled on a window). This image cannot be scaled (as it would lose the visual effect of looking like a "blind"). This image must also be rendered on top of another image. So there are 2 images total.

* ANSWER *

For the top-most imageview, i set the content mode to Top (so it doesnt scale). Then in code, i set the clipsToBounds to True. Now i am able to animate the top-most imageview height thus giving me the effect i am looking for.

答:
You may want to check out Animation Blocks. They're documented quite thoroughly here:

http://developer.apple.com/library/ios/#documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/AnimatingViews/AnimatingViews.html

All the code there is relevant, because UIImageView is a subclass of UIView.

Happy coding.

ContentLicense: CC BY-SA 2.5

Title: Animating a UIImage or UIImageView?


答:
You can use not to check whether a column is not nil

```<code>Task.where.not(completed_at: nil)
</code>```

or for user

```<code>user.tasks.where.not(completed_at: nil)
</code>```

Title: Finding out completed tasks in rails

Body: I need to show records based on a column completed_at. What is the best way to check at controller.task belongs to the user and user has_many tasks. Can I check based whether the column is nil or have some value?. Or any other best ways?

Body:
You can use not to check whether a column is not nil

Task.where.not(completed_at: nil)

or for user

user.tasks.where.not(completed_at: nil)


问:
Finding included or non-included points
I am writing for Python 3.5.2. I have a list named coordinate_list:

```<code>[
    ['x1', '120;40', '100;0;60;40'],
    ['x2', '200;50', '80;10;30;5'],
    ['x3', '150;15', '120;0;25;10'],
    ['x4', '240;60', '100;10;0;40'],
    ['x5', '260;45', '70;0;10;25'],
    ['x6', '225;15', '75;10;5;10'],
    ['x7', '273;20', '75;0;0;0'],
    ['x8', '221;5', '0;0;0;0'],
    ['x9', '345;20', '0;0;0;0'],
]
</code>```

Firstly, I want to explain the meaning of the list elements. Each row in the list identifies a point. The first element, like

"x1" , "x2" ," x3",...

is the name of the point. The next element is the point's coordinates, separated by ;. The final element is the point's range. For example, x1's coordinates are (120, 40). And it reaches to (120 + 100) on the east, (120 - 0) on the west, (40 + 60) on the north, and (40 - 40) on the south.

If any other point is in this range, I must put it in a dictionary or a list. For instance, x1's range is (220, 120, 100, 0) (east, west, north, south) so x1 includes x2 and x3.

How can I do that? I wrote something but it is very unpythonic. I created lots of list, and it is not readable. Also, I got stuck finding the included possible points.

答:
The question isn't very clear (understandable language difficulties) so apologies if I have misinterpreted the question.

I believe you wish to determine if each 'point' lays within the bounds of a rectangle around each other point.

To solve this we first create a class to represent each Rectangle:

```<code>class Rectangle:
    def __init__(self, center_x, center_y, east, west, north, south):
        self._center_x = center_x
        self._center_y = center_y
        self._north = center_y + north
        self._south = center_y - south
        self._west = center_x - west
        self._east = center_x + east

    def containsPoint(self, other):
        return other._center_y <= self._north and other._center_y >= self._south and other._center_x >= self._west and other._center_x <= self._east

    def __repr__(self):
        return "center=({}, {}), east={}, west={}, north={}, south={}".format(self._center_x, self._center_y, self._east, self._west, self._north, self._south)
</code>```

Each instance of this class stores the north, east, south & west values along with the center point coordinates.  The containsPoint function then determines whether the center of any given Rectangle is within the bounds of another Rectangle

Next we take the raw input data and do some simple parsing to get it into a more manageable form:

```<code>data = [['x1', '120;40', '100;0;60;40'], ['x2', '200;50', '80;10;30;5'], ['x3', '150;15', '120;0;25;10'],
        ['x4', '240;60', '100;10;0;40'], ['x5', '260;45', '70;0;10;25'], ['x6', '225;15', '75;10;5;10'],
        ['x7', '273;20', '75;0;0;0'], ['x8', '221;5', '0;0;0;0'], ['x9', '345;20', '0;0;0;0']]

coords = {}
for coord in data:
    name = coord[0]
    center_x, center_y = [int(n) for n in coord[1].split(';')]
    east, west, north, south = [int(n) for n in coord[2].split(';')]
    coords[name] = Rectangle(center_x, center_y, east, west, north, south)
</code>```

So now we have a map of names (i.e. x1, x2 and so on) to an instance of the Rectangle class.

Now we have this we can write a simple O(n^2) algorithm to compare each rectangle's center with every other rectangle:

```<code>for name1, coord1 in coords.iteritems():
    for name2, coord2 in coords.iteritems():
        if name1 == name2:
            continue
        print("testing if centre of {}({}) is in {}({}), result is {}".format(name1, coord1, name2, coord2, coord2.containsPoint(coord1)))
</code>```

Produces the output:

```<code>testing if centre of x8(center=(221, 5), east=221, west=221, north=5, south=5) is in x9(center=(345, 20), east=345, west=345, north=20, south=20), result is False
testing if centre of x8(center=(221, 5), east=221, west=221, north=5, south=5) is in x2(center=(200, 50), east=280, west=190, north=80, south=45), result is False
testing if centre of x8(center=(221, 5), east=221, west=221, north=5, south=5) is in x3(center=(150, 15), east=270, west=150, north=40, south=5), result is True
testing if centre of x8(center=(221, 5), east=221, west=221, north=5, south=5) is in x1(center=(120, 40), east=220, west=120, north=100, south=0), result is False
... snip long output ...
</code>```

I hope even if I've misinterpreted your requirement that this gives you enough of a clue to get you going.

Title: Finding included or non-included points

Body:
I am writing for Python 3.5.2. I have a list named coordinate_list:

[
    ['x1', '120;40', '100;0;60;40'],
    ['x2', '200;50', '80;10;30;5'],
    ['x3', '150;15', '120;0;25;10'],
    ['x4', '240;60', '100;10;0;40'],
    ['x5', '260;45', '70;0;10;25'],
    ['x6', '225;15', '75;10;5;10'],
    ['x7', '273;20', '75;0;0;0'],
    ['x8', '221;5', '0;0;0;0'],
    ['x9', '345;20', '0;0;0;0'],
]

Firstly, I want to explain the meaning of the list elements. Each row in the list identifies a point. The first element, like

"x1" , "x2" ," x3",...

is the name of the point. The next element is the point's coordinates, separated by ;. The final element is the point's range. For example, x1's coordinates are (120, 40). And it reaches to (120 + 100) on the east, (120 - 0) on the west, (40 + 60) on the north, and (40 - 40) on the south.

If any other point is in this range, I must put it in a dictionary or a list. For instance, x1's range is (220, 120, 100, 0) (east, west, north, south) so x1 includes x2 and x3.

How can I do that? I wrote something but it is very unpythonic. I created lots of list, and it is not readable. Also, I got stuck finding the included possible points.

Body:
The question isn't very clear (understandable language difficulties) so apologies if I have misinterpreted the question.

I believe you wish to determine if each 'point' lays within the bounds of a rectangle around each other point.

To solve this we first create a class to represent each Rectangle:

class Rectangle:
    def __init__(self, center_x, center_y, east, west, north, south):
        self._center_x = center_x
        self._center_y = center_y
        self._north = center_y + north
        self._south = center_y - south
        self._west = center_x - west
        self._east = center_x + east

    def containsPoint(self, other):
        return other._center_y <= self._north and other._center_y >= self._south and other._center_x >= self._west and other._center_x <= self._east

    def __repr__(self):
        return "center=({}, {}), east={}, west={}, north={}, south={}".format(self._center_x, self._center_y, self._east, self._west, self._north, self._south)

Each instance of this class stores the north, east, south & west values along with the center point coordinates.  The containsPoint function then determines whether the center of any given Rectangle is within the bounds of another Rectangle

Next we take the raw input data and do some simple parsing to get it into a more manageable form:

data = [['x1', '120;40', '100;0;60;40'], ['x2', '200;50', '80;10;30;5'], ['x3', '150;15', '120;0;25;10'],
        ['x4', '240;60', '100;10;0;40'], ['x5', '260;45', '70;0;10;25'], ['x6', '225;15', '75;10;5;10'],
        ['x7', '273;20', '75;0;0;0'], ['x8', '221;5', '0;0;0;0'], ['x9', '345;20', '0;0;0;0']]

coords = {}
for coord in data:
    name = coord[0]
    center_x, center_y = [int(n) for n in coord[1].split(';')]
    east, west, north, south = [int(n) for n in coord[2].split(';')]
    coords[name] = Rectangle(center_x, center_y, east, west, north, south)

So now we have a map of names (i.e. x1, x2 and so on) to an instance of the Rectangle class.

Now we have this we can write a simple O(n^2) algorithm to compare each rectangle's center with every other rectangle:

for name1, coord1 in coords.iteritems():
    for name2, coord2 in coords.iteritems():
        if name1 == name2:
            continue
        print("testing if centre of {}({}) is in {}({}), result is {}".format(name1, coord1, name2, coord2, coord2.containsPoint(coord1)))

Produces the output:

testing if centre of x8(center=(221, 5), east=221, west=221, north=5, south=5) is in x9(center=(345, 20), east=345, west=345, north=20, south=20), result is False
testing if centre of x8(center=(221, 5), east=221, west=221, north=5, south=5) is in x2(center=(200, 50), east=280, west=190, north=80, south=45), result is False
testing if centre of x8(center=(221, 5), east=221, west=221, north=5, south=5) is in x3(center=(150, 15), east=270, west=150, north=40, south=5), result is True
testing if centre of x8(center=(221, 5), east=221, west=221, north=5, south=5) is in x1(center=(120, 40), east=220, west=120, north=100, south=0), result is False
... snip long output ...

I hope even if I've misinterpreted your requirement that this gives you enough of a clue to get you going.


问:
HTML colspan and rowspan not working
I have got a table 18 columns by 7 rows and i want to make td element to take 10 columns and 3 rows,so here is my code

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18

      1

        Protons

      2

      3

        4

        5

        6

        7

```

As you see bigInfo has an attribute of colspan equal to 10 and rowspan equal to 3,but unfortunately i only get cell 6 by 70 with a padding of 1 while i want that row to take a width of 10 columns and 3 rows.

答:
A table that large with a odd block of spans is difficult to visualize in HTML. Mark the  by column.row and determine the col.row coords are for each of the span's corners.

Details commented in Demo

Demo

table, td {outline:1px solid blue}
td {padding:2px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--7x18 | 3x10
Get the 4 corners as row.column coordinates
start at the top left corner then continue in a
clockwise direction.
1. To determine the left corner columns, count the
   number of columns before the big span begins:

Start=3

2. Next add start number to the min and max of colspan:

Start=3 Min=1
Left Corners=4

Start=3 Max=10
Right Corners=13

3. The row numbers are done the same way but vertically.

Top Left (Start). 1.4
Top Right........ 1.13
Bottom Right..... 3.13
Bottom Left (End) 3.4
-->
<table>
<tr>
<td>1.1</td><td>1.2</td><td>1.3</td>
<td colspan='10' rowspan='3'>1.4---------------------------------------1.13<br>
3.4---------------------------------------3.13</td>
<td>1.14</td><td>1.15</td><td>1.16</td><td>1.17</td><td>1.18</td>
</tr>
<tr>
<td>2.1</td><td>2.2</td><td>2.3</td>
<td>2.x</td><td>2.x</td><td>2.x</td><td>2.x</td><td>2.x</td>
</tr>
<tr>
<td>3.1</td><td>3.2</td><td>3.3</td>
<td>3.x</td><td>3.x</td><td>3.x</td><td>3.x</td><td>3.x</td>
</tr>
<tr>
<td>4.1</td><td>4.2</td><td>4.3</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td>
</tr>
<tr>
<td>5.1</td><td>5.2</td><td>5.3</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td>
</tr>
<tr>
<td>6.1</td><td>6.2</td><td>6.3</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td>
</tr>
<tr>
<td>7.1</td><td>7.2</td><td>7.3</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td>
</tr>
</table></code>```

Title: HTML colspan and rowspan not working

Body:
I have got a table 18 columns by 7 rows and i want to make td element to take 10 columns and 3 rows,so here is my code

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18

      1

        Protons

      2

      3

        4

        5

        6

        7

As you see bigInfo has an attribute of colspan equal to 10 and rowspan equal to 3,but unfortunately i only get cell 6 by 70 with a padding of 1 while i want that row to take a width of 10 columns and 3 rows.

Body:
A table that large with a odd block of spans is difficult to visualize in HTML. Mark the <td> by column.row and determine the col.row coords are for each of the span's corners.

Details commented in Demo

Demo

table, td {outline:1px solid blue}
td {padding:2px;}

<!--7x18 | 3x10
Get the 4 corners as row.column coordinates
start at the top left corner then continue in a
clockwise direction.
1. To determine the left corner columns, count the
   number of columns before the big span begins:

Start=3

2. Next add start number to the min and max of colspan:

Start=3 Min=1
Left Corners=4

Start=3 Max=10
Right Corners=13

3. The row numbers are done the same way but vertically.

Top Left (Start). 1.4
Top Right........ 1.13
Bottom Right..... 3.13
Bottom Left (End) 3.4
-->
<table>
<tr>
<td>1.1</td><td>1.2</td><td>1.3</td>
<td colspan='10' rowspan='3'>1.4---------------------------------------1.13<br>
3.4---------------------------------------3.13</td>
<td>1.14</td><td>1.15</td><td>1.16</td><td>1.17</td><td>1.18</td>
</tr>
<tr>
<td>2.1</td><td>2.2</td><td>2.3</td>
<td>2.x</td><td>2.x</td><td>2.x</td><td>2.x</td><td>2.x</td>
</tr>
<tr>
<td>3.1</td><td>3.2</td><td>3.3</td>
<td>3.x</td><td>3.x</td><td>3.x</td><td>3.x</td><td>3.x</td>
</tr>
<tr>
<td>4.1</td><td>4.2</td><td>4.3</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td><td>4.x</td>
</tr>
<tr>
<td>5.1</td><td>5.2</td><td>5.3</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td><td>5.x</td>
</tr>
<tr>
<td>6.1</td><td>6.2</td><td>6.3</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td><td>6.x</td>
</tr>
<tr>
<td>7.1</td><td>7.2</td><td>7.3</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td><td>7.x</td>
</tr>
</table>


问:
How to Get Left Join old ID
My tlb_comments are given,this table are tlb_comments table

tlb_comments :

```<code>| ID |  post_id    |   user_id     | comments  |  cm_parent  |
+----+-------------+---------------+-----------+-------------+
| 11 |      18     |  29           |  Nice     | 11          |
| 12 |      24     |  30           |  Good     | 12          |
</code>```

tlb_avatar Table are Given ,this table are tlb_avatar table

tlb_avatar:

```<code>| id |  vw_id      |   image                                 |
+----+-------------+-----------------------------------------+
|  1 |      29     |  1510553363_User_Avatar_2.png           |
|  2 |      30     |  d968c2fe95629e238b04ee34599c5013.jpg   |
</code>```

tlb_viewer Are Given this table are tlb_viewer table

tlb_viewer:

```<code>| id |  name         |
+----+---------------+
|  1 |      john     |
|  2 |      Quotos   |
</code>```

My Left Join Query Output.

This Out put was perfect working,but I  want add to the tbl_comments id to The each row.Now time it is does not call the tbl_comments id

```<code>| id  |  post_id|  user_id | comments|  cm_parent|  vw_id | image |
+----+----------+----------+---------+-----------+--------+-------+
|  29 |  18     |   29     |  Nice   |  11       | 29     | 2.png |
|  30 |  24     |   30     |  Good   |  12       | 30     | 2.png |
</code>```

Its Query Output was Good. However I want tlb comment Id(tbl_comments id)   to each row.

I'm Explain Given  table. Here we want last column tbl_comments id(comment ID).

This table is I'm Expecting Table.HOW TO GET???????

```<code>| id  |  post_id|  user_id | comments|  cm_parent|  vw_id |comment ID  |
+----+----------+----------+---------+-----------+--------+------------+
|  29 |  18     |   29     |  Nice   |  11       | 29     | 11         |
|  30 |  24     |   30     |  Good   |  12       | 30     | 12         |
</code>```

MYSQLI QUERY:
That Query is my mysqli query :

```<code>$qid = $quotos->id;

 $avatar = mysqli_query($conn,"SELECT * FROM tlb_comments LEFT JOIN     tlb_avatar ON tlb_avatar.vw_id = tlb_comments.user_id LEFT JOIN tlb_viewer
                                                        ON tlb_viewer.id = tlb_comments.user_id  WHERE   tlb_comments.post_id = '".$qid."'"  );
                            while($comments = mysqli_fetch_object($avatar)){}
</code>```

答:
If you use select * then the column lists of the joined tables are output in the same order as their tables are joined. If you want the columns in a different order then list the columns.

```<code>select user_id as id,
    post_id, user_id, comments, cm_parent,
    vw_id, image,
    tlb_comments.ID as 'comment ID'
from tlb_comments
left join tlb_avatar
...
</code>```

Title: How to Get Left Join old ID

Body:
My tlb_comments are given,this table are tlb_comments table

tlb_comments :

| ID |  post_id    |   user_id     | comments  |  cm_parent  |
+----+-------------+---------------+-----------+-------------+
| 11 |      18     |  29           |  Nice     | 11          |
| 12 |      24     |  30           |  Good     | 12          |

tlb_avatar Table are Given ,this table are tlb_avatar table

tlb_avatar:

| id |  vw_id      |   image                                 |
+----+-------------+-----------------------------------------+
|  1 |      29     |  1510553363_User_Avatar_2.png           |
|  2 |      30     |  d968c2fe95629e238b04ee34599c5013.jpg   |

tlb_viewer Are Given this table are tlb_viewer table

tlb_viewer:

| id |  name         |
+----+---------------+
|  1 |      john     |
|  2 |      Quotos   |

My Left Join Query Output.

This Out put was perfect working,but I  want add to the tbl_comments id to The each row.Now time it is does not call the tbl_comments id

| id  |  post_id|  user_id | comments|  cm_parent|  vw_id | image |
+----+----------+----------+---------+-----------+--------+-------+
|  29 |  18     |   29     |  Nice   |  11       | 29     | 2.png |
|  30 |  24     |   30     |  Good   |  12       | 30     | 2.png |

Its Query Output was Good. However I want tlb comment Id(tbl_comments id)   to each row.

I'm Explain Given  table. Here we want last column tbl_comments id(comment ID).

This table is I'm Expecting Table.HOW TO GET???????

| id  |  post_id|  user_id | comments|  cm_parent|  vw_id |comment ID  |
+----+----------+----------+---------+-----------+--------+------------+
|  29 |  18     |   29     |  Nice   |  11       | 29     | 11         |
|  30 |  24     |   30     |  Good   |  12       | 30     | 12         |

MYSQLI QUERY:
That Query is my mysqli query :

$qid = $quotos->id;

 $avatar = mysqli_query($conn,"SELECT * FROM tlb_comments LEFT JOIN     tlb_avatar ON tlb_avatar.vw_id = tlb_comments.user_id LEFT JOIN tlb_viewer
                                                        ON tlb_viewer.id = tlb_comments.user_id  WHERE   tlb_comments.post_id = '".$qid."'"  );
                            while($comments = mysqli_fetch_object($avatar)){}

Body:
If you use select * then the column lists of the joined tables are output in the same order as their tables are joined. If you want the columns in a different order then list the columns.

select user_id as id,
    post_id, user_id, comments, cm_parent,
    vw_id, image,
    tlb_comments.ID as 'comment ID'
from tlb_comments
left join tlb_avatar
...


问:
Highcharts columnrange custom legend
I am creating a highcharts columnrange chart. I want a custom legend so that the legend would display according to "legendGrouping" and the associated colour for that series. From the jsfiddle example below I would expect the legend to show:

Running (green)

Failure (red)

Non-Failure (yellow)

Excluded (grey)

Here is the jsfiddle so far.

```<code>Highcharts.chart('ChartColumnRangeMtbf', {
  chart: {
    type: 'columnrange',
    height: 300,
    inverted: true
  },
  title: {
    text: null
  },
  xAxis: {
    lineColor: 'transparent',
    labels: {
      enabled: false
    },
    tickLength: 0
  },
  yAxis: {
    gridLineWidth: 0,
    max: 1511182800000,
    min: 1510318800000,
    lineColor: 'transparent',
    startOnTick: false,
    endOnTick: false,
    labels: {
      enabled: false
    },
    title: {
      text: null,
    },
    type: 'datetime'
  },
  plotOptions: {
    bar: {
      dataLabels: {
        enabled: true
      },
      animation: true
    },
    series: {
      cursor: 'pointer',
      borderWidth: 0,
      point: {
        events: {
          click: function() {
            location.href = '../eventview?EventID=' + this.options.id;
          }
        }
      }
    }
  },
  tooltip: {
    formatter: function() {
      return '<b>' + this.series.name + '</b><br/>' +
        Highcharts.dateFormat('%H:%M', this.point.low) +
        ' - ' + Highcharts.dateFormat('%H:%M', this.point.high);
    }
  },
  legend: {
    enabled: true
  },
  exporting: {
    enabled: false
  },
  credits: {
    enabled: false
  },
  series: [{
    name: 'Running',
    legendGrouping: 'Running',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 0,
    data: [{
      low: 1510318800000,
      high: 1511182800000,
      color: '#6cc14c'
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Excluded',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 294,
      "low": 1510750800000,
      "high": 1510751592000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Non-Failure',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 256,
      "low": 1510664400000,
      "high": 1510677352000,
      "color": "#fde54a"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Excluded',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 238,
      "low": 1510663020000,
      "high": 1510664400000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Excluded',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 236,
      "low": 1510662963000,
      "high": 1510662967000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Failure',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 213,
      "low": 1510661669000,
      "high": 1510662860000,
      "color": "#d9534f"
    }]
  }]
});
</code>```

Thanks all

答:
Used series.bar.linkedTo to make common legend for Excluded (3 events).

legend.labelFormatter to format legend

Highcharts.chart('ChartColumnRangeMtbf', {
  chart: {
    type: 'columnrange',
    height: 300,
    inverted: true,
  },
  title: {
    text: null
  },
  xAxis: {
    lineColor: 'transparent',
    labels: {
      enabled: false
    },
    tickLength: 0
  },
  yAxis: {
    gridLineWidth: 0,
    max: 1511182800000,
    min: 1510318800000,
    lineColor: 'transparent',
    startOnTick: false,
    endOnTick: false,
    labels: {
      enabled: false
    },
    title: {
      text: null,
    },
    type: 'datetime'
  },
  plotOptions: {
    bar: {
      dataLabels: {
        enabled: true
      },
      animation: true
    },
    series: {
      cursor: 'pointer',
      borderWidth: 0,
      point: {
        events: {
          click: function() {
            location.href = '../eventview?EventID=' + this.options.id;
          }
        }
      }
    }
  },
  tooltip: {
    formatter: function() {
      return '' + this.series.name + '
' +
        Highcharts.dateFormat('%H:%M', this.point.low) +
        ' - ' + Highcharts.dateFormat('%H:%M', this.point.high);
    }
  },
  legend: {
    symbolPadding: 0,
    symbolWidth: 0.1,
    symbolHeight: 0.1,
    symbolRadius: 0,
    useHTML: true,
    labelFormatter: function() {
    //console.log(this.userOptions.legendGrouping)
            return '
' +
            '

' +
            " " + this.userOptions.legendGrouping + " " +
            '
'
        }
  },
  exporting: {
    enabled: false
  },
  credits: {
    enabled: false
  },
  series: [{
    name: 'Running',
    legendGrouping: 'Running',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 0,
    data: [{
      low: 1510318800000,
      high: 1511182800000,
      color: '#6cc14c'
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Excluded',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    id:'ex',
    data: [{
      "id": 294,
      "low": 1510750800000,
      "high": 1510751592000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Non-Failure',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 256,
      "low": 1510664400000,
      "high": 1510677352000,
      "color": "#fde54a"
    }]
  }, {
    name: 'Events',
    linkedTo:'ex',
    legendGrouping: 'Excluded',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 238,
      "low": 1510663020000,
      "high": 1510664400000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Excluded',
    linkedTo:'ex',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 236,
      "low": 1510662963000,
      "high": 1510662967000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Failure',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 213,
      "low": 1510661669000,
      "high": 1510662860000,
      "color": "#d9534f"
    }]
  }]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>

<div id="ChartColumnRangeMtbf" style="min-width: 300px; height: 300px; margin: 0 auto"></div></code>```

Or

If you can update series data and add color as attribute as you added in series data. And also remove colorByPoint: true,

Highcharts.chart('ChartColumnRangeMtbf', {
  chart: {
    type: 'columnrange',
    height: 300,
    inverted: true,
  },
  title: {
    text: null
  },
  xAxis: {
    lineColor: 'transparent',
    labels: {
      enabled: false
    },
    tickLength: 0
  },
  yAxis: {
    gridLineWidth: 0,
    max: 1511182800000,
    min: 1510318800000,
    lineColor: 'transparent',
    startOnTick: false,
    endOnTick: false,
    labels: {
      enabled: false
    },
    title: {
      text: null,
    },
    type: 'datetime'
  },
  plotOptions: {
    bar: {
      dataLabels: {
        enabled: true
      },
      animation: true
    },
    series: {
      cursor: 'pointer',
      borderWidth: 0,
      point: {
        events: {
          click: function() {
            location.href = '../eventview?EventID=' + this.options.id;
          }
        }
      }
    }
  },
  tooltip: {
    formatter: function() {
      return '' + this.series.name + '
' +
        Highcharts.dateFormat('%H:%M', this.point.low) +
        ' - ' + Highcharts.dateFormat('%H:%M', this.point.high);
    }
  },
  legend: {

    useHTML: true,
    labelFormatter: function() {
            return  this.userOptions.legendGrouping
        }
  },
  exporting: {
    enabled: false
  },
  credits: {
    enabled: false
  },
  series: [{
    name: 'Running',
    legendGrouping: 'Running',
     color: '#6cc14c',
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 0,
    data: [{
      low: 1510318800000,
      high: 1511182800000,
      color: '#6cc14c'
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Excluded',
    "color": "#b5b2b2",
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    id:'ex',
    data: [{
      "id": 294,
      "low": 1510750800000,
      "high": 1510751592000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Non-Failure',
    "color": "#fde54a",
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 256,
      "low": 1510664400000,
      "high": 1510677352000,
      "color": "#fde54a"
    }]
  }, {
    name: 'Events',
    linkedTo:'ex',
    legendGrouping: 'Excluded',
     "color": "#b5b2b2",
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 238,
      "low": 1510663020000,
      "high": 1510664400000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Excluded',
    linkedTo:'ex',
    "color": "#b5b2b2",
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 236,
      "low": 1510662963000,
      "high": 1510662967000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Failure',
    "color": "#d9534f",
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 213,
      "low": 1510661669000,
      "high": 1510662860000,
      "color": "#d9534f"
    }]
  }]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>

<div id="ChartColumnRangeMtbf" style="min-width: 300px; height: 300px; margin: 0 auto"></div></code>```

Title: Highcharts columnrange custom legend

Body:
I am creating a highcharts columnrange chart. I want a custom legend so that the legend would display according to "legendGrouping" and the associated colour for that series. From the jsfiddle example below I would expect the legend to show:

Running (green)

Failure (red)

Non-Failure (yellow)

Excluded (grey)

Here is the jsfiddle so far.

Highcharts.chart('ChartColumnRangeMtbf', {
  chart: {
    type: 'columnrange',
    height: 300,
    inverted: true
  },
  title: {
    text: null
  },
  xAxis: {
    lineColor: 'transparent',
    labels: {
      enabled: false
    },
    tickLength: 0
  },
  yAxis: {
    gridLineWidth: 0,
    max: 1511182800000,
    min: 1510318800000,
    lineColor: 'transparent',
    startOnTick: false,
    endOnTick: false,
    labels: {
      enabled: false
    },
    title: {
      text: null,
    },
    type: 'datetime'
  },
  plotOptions: {
    bar: {
      dataLabels: {
        enabled: true
      },
      animation: true
    },
    series: {
      cursor: 'pointer',
      borderWidth: 0,
      point: {
        events: {
          click: function() {
            location.href = '../eventview?EventID=' + this.options.id;
          }
        }
      }
    }
  },
  tooltip: {
    formatter: function() {
      return '' + this.series.name + '
' +
        Highcharts.dateFormat('%H:%M', this.point.low) +
        ' - ' + Highcharts.dateFormat('%H:%M', this.point.high);
    }
  },
  legend: {
    enabled: true
  },
  exporting: {
    enabled: false
  },
  credits: {
    enabled: false
  },
  series: [{
    name: 'Running',
    legendGrouping: 'Running',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 0,
    data: [{
      low: 1510318800000,
      high: 1511182800000,
      color: '#6cc14c'
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Excluded',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 294,
      "low": 1510750800000,
      "high": 1510751592000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Non-Failure',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 256,
      "low": 1510664400000,
      "high": 1510677352000,
      "color": "#fde54a"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Excluded',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 238,
      "low": 1510663020000,
      "high": 1510664400000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Excluded',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 236,
      "low": 1510662963000,
      "high": 1510662967000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Failure',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 213,
      "low": 1510661669000,
      "high": 1510662860000,
      "color": "#d9534f"
    }]
  }]
});

Thanks all

Body:
Used series.bar.linkedTo to make common legend for Excluded (3 events).

legend.labelFormatter to format legend

Highcharts.chart('ChartColumnRangeMtbf', {
  chart: {
    type: 'columnrange',
    height: 300,
    inverted: true,
  },
  title: {
    text: null
  },
  xAxis: {
    lineColor: 'transparent',
    labels: {
      enabled: false
    },
    tickLength: 0
  },
  yAxis: {
    gridLineWidth: 0,
    max: 1511182800000,
    min: 1510318800000,
    lineColor: 'transparent',
    startOnTick: false,
    endOnTick: false,
    labels: {
      enabled: false
    },
    title: {
      text: null,
    },
    type: 'datetime'
  },
  plotOptions: {
    bar: {
      dataLabels: {
        enabled: true
      },
      animation: true
    },
    series: {
      cursor: 'pointer',
      borderWidth: 0,
      point: {
        events: {
          click: function() {
            location.href = '../eventview?EventID=' + this.options.id;
          }
        }
      }
    }
  },
  tooltip: {
    formatter: function() {
      return '<b>' + this.series.name + '</b><br/>' +
        Highcharts.dateFormat('%H:%M', this.point.low) +
        ' - ' + Highcharts.dateFormat('%H:%M', this.point.high);
    }
  },
  legend: {
    symbolPadding: 0,
    symbolWidth: 0.1,
    symbolHeight: 0.1,
    symbolRadius: 0,
    useHTML: true,
    labelFormatter: function() {
    //console.log(this.userOptions.legendGrouping)
            return '<div>' +
            '<div style="width: 18px; height: 12px; display: inline-block; background-color: ' + this.options.data[0].color + ';"> </div>' +
            "<span> " + this.userOptions.legendGrouping + " </span>" +
            '</div>'
        }
  },
  exporting: {
    enabled: false
  },
  credits: {
    enabled: false
  },
  series: [{
    name: 'Running',
    legendGrouping: 'Running',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 0,
    data: [{
      low: 1510318800000,
      high: 1511182800000,
      color: '#6cc14c'
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Excluded',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    id:'ex',
    data: [{
      "id": 294,
      "low": 1510750800000,
      "high": 1510751592000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Non-Failure',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 256,
      "low": 1510664400000,
      "high": 1510677352000,
      "color": "#fde54a"
    }]
  }, {
    name: 'Events',
    linkedTo:'ex',
    legendGrouping: 'Excluded',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 238,
      "low": 1510663020000,
      "high": 1510664400000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Excluded',
    linkedTo:'ex',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 236,
      "low": 1510662963000,
      "high": 1510662967000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Failure',
    colorByPoint: true,
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 213,
      "low": 1510661669000,
      "high": 1510662860000,
      "color": "#d9534f"
    }]
  }]
});

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>

<div id="ChartColumnRangeMtbf" style="min-width: 300px; height: 300px; margin: 0 auto"></div>

Or

If you can update series data and add color as attribute as you added in series data. And also remove colorByPoint: true,

Highcharts.chart('ChartColumnRangeMtbf', {
  chart: {
    type: 'columnrange',
    height: 300,
    inverted: true,
  },
  title: {
    text: null
  },
  xAxis: {
    lineColor: 'transparent',
    labels: {
      enabled: false
    },
    tickLength: 0
  },
  yAxis: {
    gridLineWidth: 0,
    max: 1511182800000,
    min: 1510318800000,
    lineColor: 'transparent',
    startOnTick: false,
    endOnTick: false,
    labels: {
      enabled: false
    },
    title: {
      text: null,
    },
    type: 'datetime'
  },
  plotOptions: {
    bar: {
      dataLabels: {
        enabled: true
      },
      animation: true
    },
    series: {
      cursor: 'pointer',
      borderWidth: 0,
      point: {
        events: {
          click: function() {
            location.href = '../eventview?EventID=' + this.options.id;
          }
        }
      }
    }
  },
  tooltip: {
    formatter: function() {
      return '<b>' + this.series.name + '</b><br/>' +
        Highcharts.dateFormat('%H:%M', this.point.low) +
        ' - ' + Highcharts.dateFormat('%H:%M', this.point.high);
    }
  },
  legend: {

    useHTML: true,
    labelFormatter: function() {
            return  this.userOptions.legendGrouping
        }
  },
  exporting: {
    enabled: false
  },
  credits: {
    enabled: false
  },
  series: [{
    name: 'Running',
    legendGrouping: 'Running',
     color: '#6cc14c',
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 0,
    data: [{
      low: 1510318800000,
      high: 1511182800000,
      color: '#6cc14c'
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Excluded',
    "color": "#b5b2b2",
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    id:'ex',
    data: [{
      "id": 294,
      "low": 1510750800000,
      "high": 1510751592000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Non-Failure',
    "color": "#fde54a",
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 256,
      "low": 1510664400000,
      "high": 1510677352000,
      "color": "#fde54a"
    }]
  }, {
    name: 'Events',
    linkedTo:'ex',
    legendGrouping: 'Excluded',
     "color": "#b5b2b2",
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 238,
      "low": 1510663020000,
      "high": 1510664400000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Excluded',
    linkedTo:'ex',
    "color": "#b5b2b2",
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 236,
      "low": 1510662963000,
      "high": 1510662967000,
      "color": "#b5b2b2"
    }]
  }, {
    name: 'Events',
    legendGrouping: 'Failure',
    "color": "#d9534f",
    groupPadding: 0.5,
    pointWidth: 50,
    zIndex: 2,
    data: [{
      "id": 213,
      "low": 1510661669000,
      "high": 1510662860000,
      "color": "#d9534f"
    }]
  }]
});

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>

<div id="ChartColumnRangeMtbf" style="min-width: 300px; height: 300px; margin: 0 auto"></div>


问:
How can I write a ESLint rule for "linebreak-style", changing depending on Windows or Unix?
As we all know, the linebreaks (new line) used in Windows are usually carriage returns (CR) followed by a line feed (LF) i.e. (CRLF) whereas, Linux and Unix use a simple line feed (LF)

Now, in my case, my build server uses supports Linux and Unix format so, below rule is working perfectly on build server:

```<code>linebreak-style: ["error", "unix"]
</code>```

But I am doing development on Windows and I need to update rule on each git pull/git push as below,

```<code>linebreak-style: ["error", "windows"]
</code>```

So, is there any way to write a generic linebreak-style rule to support both environments, Linux/Unix and Windows?

Note: I am using ECMAScript6[js], WebStorm[ide] for development

Any solutions/suggestions would be highly appreciated. Thanks!

答:
The location of the config file required to alter ESLint rules for linebreak-style may change depending on whether you want to alter local, project or global settings, it searches for local first which overrides those further up the tree, so alter at the top of the tree to propagate down for global

I used airbnb style and my global settings were located here: node_modules/eslint-config-airbnb-base/rules/style.js:

If you are unsure on the location of the file you can always search for a list of files that contain text relating to the settings, on Linux to find all files with linebreak settings navigate to the folder where ESLint was installed and use:

```<code>grep -r linebreak
</code>```

Body:
As we all know, the linebreaks (new line) used in Windows are usually carriage returns (CR) followed by a line feed (LF) i.e. (CRLF) whereas, Linux and Unix use a simple line feed (LF)

Now, in my case, my build server uses supports Linux and Unix format so, below rule is working perfectly on build server:

linebreak-style: ["error", "unix"]

But I am doing development on Windows and I need to update rule on each git pull/git push as below,

linebreak-style: ["error", "windows"]

So, is there any way to write a generic linebreak-style rule to support both environments, Linux/Unix and Windows?

Note: I am using ECMAScript6[js], WebStorm[ide] for development

Any solutions/suggestions would be highly appreciated. Thanks!

Body:
The location of the config file required to alter ESLint rules for linebreak-style may change depending on whether you want to alter local, project or global settings, it searches for local first which overrides those further up the tree, so alter at the top of the tree to propagate down for global

I used airbnb style and my global settings were located here: node_modules/eslint-config-airbnb-base/rules/style.js:

If you are unsure on the location of the file you can always search for a list of files that contain text relating to the settings, on Linux to find all files with linebreak settings navigate to the folder where ESLint was installed and use:

grep -r linebreak


问:
laravel: function in model must return a relationship instance
I try to build a path for a model on laravel

I created a function in my model:

```<code>public function path()
{
    return App\Helper\GeneralController::getURL($this);
}
</code>```

with dd(App\Helper\GeneralController::getURL($this)) test I got the right answer. (output is a URL)

but in view with the call: $article->path  I get this error:

```<code>App\Article:: path must return a relationship instance.
</code>```

What is wrong?

答:
You need to call it:

```<code>$article->path()
</code>```

When you do $article->path, you're trying to use Eloquent relationship which you don't have.

ContentLicense: CC BY-SA 4.0

Body:
I try to build a path for a model on laravel

I created a function in my model:

public function path()
{
    return App\Helper\GeneralController::getURL($this);
}

with dd(App\Helper\GeneralController::getURL($this)) test I got the right answer. (output is a URL)

but in view with the call: $article->path  I get this error:

App\Article:: path must return a relationship instance.

What is wrong?

Body:
You need to call it:

$article->path()

When you do $article->path, you're trying to use Eloquent relationship which you don't have.


问:
Returning object in http response with NODE.JS
I want to send an sql query result object from http server back to the client.
I get this error:
"TypeError: First argument must be a string or Buffer"

If I turn the response content into string it works fine, but then it becomes useless for me.

What is the solution for the problem? Maybe there another way of making http response, or something else?

```<code>retrieve.retrieveAllStores(function(data){
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write(data);
  res.end();
});
</code>```

答:
You can try using JSON.stringify() to convert data to a string and then using JSON.parse() to convert back to JS object.

```<code>retrieve.retrieveAllStores(function(data){
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write(JSON.stringify(data));
    res.end();
});
</code>```

Body:
I want to send an sql query result object from http server back to the client.
I get this error:
"TypeError: First argument must be a string or Buffer"

If I turn the response content into string it works fine, but then it becomes useless for me.

What is the solution for the problem? Maybe there another way of making http response, or something else?

retrieve.retrieveAllStores(function(data){
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write(data);
  res.end();
});

Body:
You can try using JSON.stringify() to convert data to a string and then using JSON.parse() to convert back to JS object.

retrieve.retrieveAllStores(function(data){
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write(JSON.stringify(data));
    res.end();
});


问:
FadeIn / FadeOut Slider not fading out (JQuery / Javascript)
I'm working on a slider to fade in and out. It fades in correctly but the slide instantly disappears instead of fading out. Do you have any idea of why is this happening and any changes that you would do in the code?

I appreciate your help and suggestions :)

$(".slider > div:gt(0)").hide();

setInterval(function() {
    $('.slider > div:first')
        .fadeOut(2400)
        .next()
        .fadeIn(2400)
        .end()
        .appendTo('.slider');
}, 5000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  box-sizing: border-box;
  padding: 3rem;
}

.slider {
  background-color: #fff;
}

.slider__slide img {
    display: block;
    height: 100vh;
    width: 100%;
    object-fit: cover;
}</code>```

```

答:
You just need to set position: absolute on .slider__slide. you need to use absolute position because you trying to put the images on each other, well an element with absolute position can do this, but by default an element have static position, static or relative can't overlay on each other.

$(".slider > div:gt(0)").hide();

setInterval(function() {
    $('.slider > div:first')
        .fadeOut(2400)
        .next()
        .fadeIn(2400)
        .end()
        .appendTo('.slider');
}, 5000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  box-sizing: border-box;
  padding: 3rem;
}

.slider {
  background-color: #fff;
}

.slider__slide {
position: absolute;
}

.slider__slide img {
    display: block;
    height: 100vh;
    width: 100%;
    object-fit: cover;
}</code>```

```

Body:
I'm working on a slider to fade in and out. It fades in correctly but the slide instantly disappears instead of fading out. Do you have any idea of why is this happening and any changes that you would do in the code?

I appreciate your help and suggestions :)

$(".slider > div:gt(0)").hide();

setInterval(function() {
    $('.slider > div:first')
        .fadeOut(2400)
        .next()
        .fadeIn(2400)
        .end()
        .appendTo('.slider');
}, 5000);

body {
  box-sizing: border-box;
  padding: 3rem;
}

.slider {
  background-color: #fff;
}

.slider__slide img {
    display: block;
    height: 100vh;
    width: 100%;
    object-fit: cover;
}

Body:
You just need to set position: absolute on .slider__slide. you need to use absolute position because you trying to put the images on each other, well an element with absolute position can do this, but by default an element have static position, static or relative can't overlay on each other.

$(".slider > div:gt(0)").hide();

setInterval(function() {
    $('.slider > div:first')
        .fadeOut(2400)
        .next()
        .fadeIn(2400)
        .end()
        .appendTo('.slider');
}, 5000);

body {
  box-sizing: border-box;
  padding: 3rem;
}

.slider {
  background-color: #fff;
}

.slider__slide {
position: absolute;
}

.slider__slide img {
    display: block;
    height: 100vh;
    width: 100%;
    object-fit: cover;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<html>
  <body>
  <div class="slider">
    <div class="slider__slide"><img src="https://images.pexels.com/photos/6464/desk-technology-music-white.jpg?w=940&h=650&auto=compress&cs=tinysrgb" alt="Image 1"></div>
    <div class="slider__slide"><img src="https://images.pexels.com/photos/712321/pexels-photo-712321.jpeg?w=940&h=650&auto=compress&cs=tinysrgb" alt="Image 2"></div>
    <div class="slider__slide"><img src="https://images.pexels.com/photos/715546/pexels-photo-715546.jpeg?w=940&h=650&auto=compress&cs=tinysrgb" alt="Image 3"></div>
</div>
</body>

</html>


答:
path() is method not object element you need to call as method

```<code>$article->path();
</code>```

Title: laravel: function in model must return a relationship instance

Body:
path() is method not object element you need to call as method

$article->path();


问:
How to display only Fragment Layout
I have a list of beers, which is my main activity MainActivity. Whenever I click in one of them, I want to display a new screen showing the beer info.

This is how my list looks and the code that is executed to create my fragment.

```<code>@Override
    public void onClick(View view) {

        // Data to send to fragment
        Beer beer = displayedList.get(getAdapterPosition());
        Bundle bundle = new Bundle();
        bundle.putParcelable("Beer", beer);
        bundle.putParcelableArrayList("BeerList", (ArrayList<? extends Parcelable>) beerList);

        // Begin the transaction
        FragmentTransaction ft = context.getSupportFragmentManager().beginTransaction();
        // Replace the contents of the container with the new fragment
        BeerInfoFragment beerInfoFragment = new BeerInfoFragment();
        beerInfoFragment.setArguments(bundle);
        ft.replace(R.id.frame_layout, beerInfoFragment);
        // or ft.add(R.id.your_placeholder, new FooFragment());
        // Complete the changes added above
        ft.commit();
    }
}
</code>```

However, instead of displaying the beer's info on a new screen, I got both layouts at the same time:

QUESTION: How can I make to just display the Fragment Layout instead of both?

This is how my MainActivity layout looks like:

```<code><android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:scrollbars="vertical"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<FrameLayout
    android:id="@+id/frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>
</code>```

答:
You need to have two fragments.

BeerListFragment: this fragment will have the recyclerview to display the list of beers you have.

BeerInfoFragment: This fragment will display the detail of the beer item clicked / selected.

Now, on Launch of your MainActivity add the BeerListFragment to the container. Capture the click of the item and after processing it open the BeerInfoFragment as you have mentioned in the question.

Title: How to display only Fragment Layout

Body:
I have a list of beers, which is my main activity MainActivity. Whenever I click in one of them, I want to display a new screen showing the beer info.

This is how my list looks and the code that is executed to create my fragment.

@Override
    public void onClick(View view) {

        // Data to send to fragment
        Beer beer = displayedList.get(getAdapterPosition());
        Bundle bundle = new Bundle();
        bundle.putParcelable("Beer", beer);
        bundle.putParcelableArrayList("BeerList", (ArrayList<? extends Parcelable>) beerList);

        // Begin the transaction
        FragmentTransaction ft = context.getSupportFragmentManager().beginTransaction();
        // Replace the contents of the container with the new fragment
        BeerInfoFragment beerInfoFragment = new BeerInfoFragment();
        beerInfoFragment.setArguments(bundle);
        ft.replace(R.id.frame_layout, beerInfoFragment);
        // or ft.add(R.id.your_placeholder, new FooFragment());
        // Complete the changes added above
        ft.commit();
    }
}

However, instead of displaying the beer's info on a new screen, I got both layouts at the same time:

QUESTION: How can I make to just display the Fragment Layout instead of both?

This is how my MainActivity layout looks like:

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:scrollbars="vertical"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<FrameLayout
    android:id="@+id/frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>


问:
Remove webkit browser scrollbar's top margin css
CODE:

```<code><style>
::-webkit-scrollbar{
    width: 23px;
}
::-webkit-scrollbar-track{
    background-color: transparent;
}
::-webkit-scrollbar-thumb {
      background-color: silver;
}
::-webkit-scrollbar-button {
      background-color: transparent;
}
::-webkit-scrollbar-corner {
      background-color: transparent;
}
</style>
<body>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</body>
</code>```

jsfiddle : https://jsfiddle.net/2zcxnL66/

On that code in chrome, other things about scrollbar is good and nicely working.

But I care some margin of scrollbar.
It looks like there are some margin for top corner or bottom corner of scrollbar track.

Question:
How can I remove these margin? I want to make scrollbar goes top fully as if margin-top_or_bottom-of-scrollbar-track:0;

答:
These aren't margin but the spaces taken by the arrows you made transparent. So instead you can make them display:none :

::-webkit-scrollbar{
    width: 23px;
}
::-webkit-scrollbar-track{
    background-color: transparent;
}
::-webkit-scrollbar-thumb {
      background-color: silver;
}
::-webkit-scrollbar-button {
      background-color: transparent;
      display:none; /*added this */
}
::-webkit-scrollbar-corner {
      background-color: transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<p style="padding-top:0; margin-top:0; text-align:right">
Here is problem --------------------------------->
</p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

<p style="padding-top:0; margin-top:0; text-align:right">
Here is problem --------------------------------->
</p>
</body></code>```

Body:
CODE:

jsfiddle : https://jsfiddle.net/2zcxnL66/

On that code in chrome, other things about scrollbar is good and nicely working.

But I care some margin of scrollbar.
It looks like there are some margin for top corner or bottom corner of scrollbar track.

Question:
How can I remove these margin? I want to make scrollbar goes top fully as if margin-top_or_bottom-of-scrollbar-track:0;

Body:
These aren't margin but the spaces taken by the arrows you made transparent. So instead you can make them display:none :

::-webkit-scrollbar{
    width: 23px;
}
::-webkit-scrollbar-track{
    background-color: transparent;
}
::-webkit-scrollbar-thumb {
      background-color: silver;
}
::-webkit-scrollbar-button {
      background-color: transparent;
      display:none; /*added this */
}
::-webkit-scrollbar-corner {
      background-color: transparent;
}

<body>
<p style="padding-top:0; margin-top:0; text-align:right">
Here is problem --------------------------------->
</p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

<p style="padding-top:0; margin-top:0; text-align:right">
Here is problem --------------------------------->
</p>
</body>


问:
Show that the estimator of the mean is independent of the estimator of the variance in R
I'm trying to illustrate with R the fact that if X1, ..., Xn are random Gaussian variables N(μ, σ^2), then the estimator of the mean (X1 + ... + Xn)/n is independent of the estimator of the variance ((X1-μ)^2 + ... (Xn-μ)^2))/n.

I have established that mathematically with the Cochran's theorem.
Now with R, I'm introducing

```<code>x = rnorm(50, 3, 1) #50 N(3,1) random variables for instance.
piX1 = rep_len(mean(x), 50) #(this gives me a 50-length vector containing mean(x)
piX2 = rep_len(x - mean(x), 50)
tab1 = table(piXV1, piXV2)
chi = chisq.test(tab1)
</code>```

This give me a p-value of 1, which makes me skeptical as to whether the Chi Square test actually tests if piX1 and piX2 are independent.. Can anyone tell me if it's actually working?
Thanks!

答:
The code below generates 10000 independent samples and calculates mean and variance. Then, a test on Pearson's correlation between mean and variance estimates was applied.</p>

```<code>mnvr <- sapply(1:10000, function(k) {
  x = rnorm(50, 3, 1)
  mn <- mean(x)
  vr <- var(x)
  return(c(mn,vr))
})

cor.test(mnvr[1,], mnvr[2,])

#         Pearson's product-moment correlation
#
# data:  mnvr[1, ] and mnvr[2, ]
# t = -0.001029, df = 9998, p-value = 0.9992
# alternative hypothesis: true correlation is not equal to 0
# 95 percent confidence interval:
#  -0.01961036  0.01958978
# sample estimates:
#          cor
# -1.02906e-05
</code>```

Body:
I'm trying to illustrate with R the fact that if X1, ..., Xn are random Gaussian variables N(μ, σ^2), then the estimator of the mean (X1 + ... + Xn)/n is independent of the estimator of the variance ((X1-μ)^2 + ... (Xn-μ)^2))/n.

I have established that mathematically with the Cochran's theorem.
Now with R, I'm introducing

x = rnorm(50, 3, 1) #50 N(3,1) random variables for instance.
piX1 = rep_len(mean(x), 50) #(this gives me a 50-length vector containing mean(x)
piX2 = rep_len(x - mean(x), 50)
tab1 = table(piXV1, piXV2)
chi = chisq.test(tab1)

This give me a p-value of 1, which makes me skeptical as to whether the Chi Square test actually tests if piX1 and piX2 are independent.. Can anyone tell me if it's actually working?
Thanks!

Body:
The code below generates 10000 independent samples and calculates mean and variance. Then, a test on Pearson's correlation between mean and variance estimates was applied.

mnvr <- sapply(1:10000, function(k) {
  x = rnorm(50, 3, 1)
  mn <- mean(x)
  vr <- var(x)
  return(c(mn,vr))
})

cor.test(mnvr[1,], mnvr[2,])

#         Pearson's product-moment correlation
#
# data:  mnvr[1, ] and mnvr[2, ]
# t = -0.001029, df = 9998, p-value = 0.9992
# alternative hypothesis: true correlation is not equal to 0
# 95 percent confidence interval:
#  -0.01961036  0.01958978
# sample estimates:
#          cor
# -1.02906e-05


问:
Run an emulator on an AMD processor
I have created an emulator with Google API of API 25 in Android Studio and my machine has AMD Processor. Can I run the emulator?

答:
Yes you can,Just Follow below things

open Android AVD Manager: Tools -> Android -> AVD Manager and create an emulator:

-Create Virtual Device

-Choose any hardware

-Now in system image you need to click on the "Other Images" tab

-Select an image to install. IMPORTANT: Notice that for AMD in the "ABI" column it has to say: ARM EABI v7a or ARM 64 v8a

-Install it and restart Android Studio

This works for me.

Title: Run an emulator on an AMD processor


问:
Combine two sets conditionally
I have a Person object which has a name attribute and some other attributes. I have two HashSet with Person objects. Note that name is not an unique attribute meaning that two Persons with same name can have different height so using HashSet does not guarantee that two Persons with same name are not in the same set.

I need to add one set to another so there are no Persons in the result with the same name. So something like this:

```<code>public void combine(HashSet<Person> set1, HashSet<Person> set2){
    for (String item2 : set2) {
        boolean exists = false;
        for (String item1 : set1) {
            if(item2.name.equals(item1.name)){
                exists = true;
            }
        }
        if(!exists){
            set1.add(item2);
        }
    }
}
</code>```

Is there a cleaner way of doing this in java8?

答:
```<code>set1.addAll(set2.stream().filter(e -> set1.stream()
                    .noneMatch(p -> p.getName().equals(e.getName())))
                    .collect(Collectors.toSet()));
</code>```

Title: Combine two sets conditionally

Body:
I have a Person object which has a name attribute and some other attributes. I have two HashSet with Person objects. Note that name is not an unique attribute meaning that two Persons with same name can have different height so using HashSet does not guarantee that two Persons with same name are not in the same set.

I need to add one set to another so there are no Persons in the result with the same name. So something like this:

public void combine(HashSet<Person> set1, HashSet<Person> set2){
    for (String item2 : set2) {
        boolean exists = false;
        for (String item1 : set1) {
            if(item2.name.equals(item1.name)){
                exists = true;
            }
        }
        if(!exists){
            set1.add(item2);
        }
    }
}

Is there a cleaner way of doing this in java8?


问:
Forwarding references for non-reference types
```<code> template<typename T>
 void F(T&& x) {}
</code>```

If we call it with argument of type int& everything is clear - reference collapsing takes place and we still have lvalue-reference. But what happens if we call it with, for example, int argument. My thoughts: we have deduced type T=int, decorate it with rvalue-reference, so F takes int&& argument and calling it with int type will result in error. But in real F takes such argument as lvalue-reference. Where does lvalue-reference come from? What rules did compiler apply to get int& from int?

答:
Since C++17, there is the concept of forwarding reference in the C++ standard. Normaly the template parameter is deduced as a non reference. But for the specific case of a forwarding reference if the corresponding argument is a lvalue, the parameter is deduced as a reference. C++ standard (N4700)[temp.over.deduct.call]/3:

[...]A forwarding reference is an rvalue reference to a cv-unqualified template parameter that does not represent a template parameter of a class template (during class template argument deduction ([over.match.class.deduct])). If P is a forwarding reference and the argument is an lvalue, the type “lvalue reference to A” is used in place of A for type deduction.[...]

For the concern of function call, it has the same meaning as this equivalent paragraph in the C++11(N337) and C++14(N414) [temp.over.deduct.call]/3:

[...]If P is an rvalue reference to a cv-unqualified template parameter and the argument is an lvalue, the type “lvalue reference to A” is used in place of A for type deduction[...]

Body:
 template<typename T>
 void F(T&& x) {}

If we call it with argument of type int& everything is clear - reference collapsing takes place and we still have lvalue-reference. But what happens if we call it with, for example, int argument. My thoughts: we have deduced type T=int, decorate it with rvalue-reference, so F takes int&& argument and calling it with int type will result in error. But in real F takes such argument as lvalue-reference. Where does lvalue-reference come from? What rules did compiler apply to get int& from int?


问:
When creating a google actions the name not allowed and blocking me from Saving
I am trying to create a Google Action and I am getting this error:

Your sample invocations are structured incorrectly. Make sure they all
  include either your app name or pronunciation, and trigger your app.

Even if I set the name to

Dr. Detroit

and the pronunciation to

doctor detroit

I'm totally confused with this.  any help is appreciated.

答: I also got the same error. It comes because of the fact that your sample invocations does not include the full name of your app/action. Try to make it exactly the same and it might work. I got mine working the same way. </p>


问:
proper way to configure d3 to work with angular2 and typescript
trying to include d3 library into an angular2 typescript project. I added d3 via npm install d3 and the typings via typing install d3 --save, the project local server doesn't start (tsc && concurrently "npm
run tsc:w" "npm run lite"), with the following error:

```<code>typings/browser/definitions/d3/index.d.ts(3319,1): error TS2300: Duplicate identifier 'export='.
typings/browser/definitions/d3/index.d.ts(3323,1): error TS2300: Duplicate identifier 'export='.
typings/browser/definitions/d3/index.d.ts(3327,1): error TS2300: Duplicate identifier 'export='.
typings/modules/d3/index.d.ts(3319,1): error TS2300: Duplicate identifier 'export='.
typings/modules/d3/index.d.ts(3323,1): error TS2300: Duplicate identifier 'export='.
typings/modules/d3/index.d.ts(3327,1): error TS2300: Duplicate identifier 'export='.
</code>```

these are my config files:

typings.json:

```<code>{
  "ambientDependencies": {
    "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd",
    "jasmine": "github:DefinitelyTyped/DefinitelyTyped/jasmine/jasmine.d.ts#5c182b9af717f73146399c2485f70f1e2ac0ff2b",
    "gapi": "github:DefinitelyTyped/DefinitelyTyped/gapi.auth2/gapi.auth2.d.ts"
  },
  "dependencies": {
    "d3": "registry:npm/d3#3.0.0+20160211003958"
  }
}
</code>```

package.json:

```<code>{
  "name": "session-explorer",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.15",
    "systemjs": "0.19.26",
    "es6-shim": "^0.35.0",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.6.10",
    "d3": "^3.0.0"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings": "^0.7.12"
  }
}
</code>```

答:
There are too many different answers here. Because the maintain status of Typed d3.

For now, 2017/12/09, there is already d3 type, with latest version 4.12.0. So no need to downgrade to version 3.x, or declare something.

Body:
trying to include d3 library into an angular2 typescript project. I added d3 via npm install d3 and the typings via typing install d3 --save, the project local server doesn't start (tsc && concurrently "npm
run tsc:w" "npm run lite"), with the following error:

typings/browser/definitions/d3/index.d.ts(3319,1): error TS2300: Duplicate identifier 'export='.
typings/browser/definitions/d3/index.d.ts(3323,1): error TS2300: Duplicate identifier 'export='.
typings/browser/definitions/d3/index.d.ts(3327,1): error TS2300: Duplicate identifier 'export='.
typings/modules/d3/index.d.ts(3319,1): error TS2300: Duplicate identifier 'export='.
typings/modules/d3/index.d.ts(3323,1): error TS2300: Duplicate identifier 'export='.
typings/modules/d3/index.d.ts(3327,1): error TS2300: Duplicate identifier 'export='.

these are my config files:

typings.json:

{
  "ambientDependencies": {
    "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd",
    "jasmine": "github:DefinitelyTyped/DefinitelyTyped/jasmine/jasmine.d.ts#5c182b9af717f73146399c2485f70f1e2ac0ff2b",
    "gapi": "github:DefinitelyTyped/DefinitelyTyped/gapi.auth2/gapi.auth2.d.ts"
  },
  "dependencies": {
    "d3": "registry:npm/d3#3.0.0+20160211003958"
  }
}

package.json:

{
  "name": "session-explorer",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.15",
    "systemjs": "0.19.26",
    "es6-shim": "^0.35.0",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.6.10",
    "d3": "^3.0.0"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings": "^0.7.12"
  }
}