问:
missing one "bin" of data in rose graph
I am following the following tutorial that is copy/paste reproducible here.

http://rstudio-pubs-static.s3.amazonaws.com/3369_998f8b2d788e4a0384ae565c4280aa47.html

On my setup, when I run this, I get an error

```<code>Error: Width` is deprecated. Do you want `geom_bar()`?
</code>```

So I swap geom_hist for geom_bar, making my code...

```<code>ggplot(eventdata, aes(x = eventhour)) + geom_bar(breaks = seq(0, 24), width = 1, colour = "grey") + coord_polar(start = 0) + theme_minimal() + scale_fill_brewer() + ylab("Count") + ggtitle("Events by Time of day") + scale_x_continuous("", limits = c(0, 24), breaks = seq(0, 24), labels = seq(0, 24))
</code>```

However, the graph I get is very different. Inspecting, it seems its "missing" the data from midnight to 1 AM ( 00:00:00 to 00:59:59, event_hour=0 )

I've tried running this on my own dataset (dput below) and I get a similar weird error....it combines the "0" bin and the "23" bin giving me 1 massive bin.

```<code>gplotAll = ggplot( eventdataAll, aes(x=eventdataAll$eventhour) ) +
  geom_histogram(breaks=seq(0,24), colour="purple") + coord_polar(start=0) +
  theme_minimal() + scale_fill_manual(values="blue") + ylab("Frequency") +
  ggtitle("All Sources") + scale_x_continuous("", limits=c(0,24),
  breaks=seq(0,24), labels=seq(0,24))
</code>```

Note this is a very small subset of my data, as its millions of timestamps.

```<code>dput(eventdataAll[1:100,] )

structure(list(datetime = structure(c(1499433307, 1499428942,
1499426105, 1499422506, 1499466293, 1499408104, 1499476505, 1499411705,
1499400905, 1499466368, 1499454358, 1499453483, 1499405930, 1499484602,
1499483709, 1499480109, 1499408108, 1499445444, 1499439817, 1499427520,
1499418054, 1499416518, 1499414449, 1499410178, 1499409748, 1499409317,
1499405867, 1499402279, 1499485071, 1499481544, 1499481527, 1499481459,
1499481423, 1499481407, 1499477859, 1499475634, 1499474292, 1499474275,
1499474253, 1499470435, 1499468435, 1499468413, 1499468398, 1499467032,
1499464834, 1499463580, 1499463425, 1499461391, 1499460152, 1499460150,
1499459806, 1499459745, 1499459366, 1499458914, 1499458463, 1499458012,
1499457635, 1499457619, 1499455777, 1499454624, 1499454035, 1499454020,
1499452801, 1499452695, 1499450434, 1499450414, 1499450404, 1499450403,
1499450156, 1499446834, 1499446818, 1499446803, 1499445621, 1499444273,
1499443234, 1499443218, 1499443201, 1499441873, 1499441806, 1499441700,
1499441096, 1499441095, 1499440418, 1499440417, 1499436056, 1499434899,
1499432434, 1499431018, 1499428801, 1499427491, 1499425201, 1499423442,
1499421620, 1499421134, 1499427667, 1499421549, 1499472830, 1499451306,
1499450792, 1499482802), class = c("POSIXct", "POSIXt"), tzone = ""),
    eventhour = c(9L, 8L, 7L, 6L, 18L, 2L, 21L, 3L, 0L, 18L,
    15L, 14L, 1L, 23L, 23L, 22L, 2L, 12L, 11L, 7L, 5L, 4L, 4L,
    2L, 2L, 2L, 1L, 0L, 23L, 22L, 22L, 22L, 22L, 22L, 21L, 21L,
    20L, 20L, 20L, 19L, 19L, 19L, 18L, 18L, 18L, 17L, 17L, 17L,
    16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 15L, 15L,
    15L, 15L, 14L, 14L, 14L, 14L, 14L, 14L, 13L, 13L, 13L, 13L,
    12L, 12L, 12L, 12L, 12L, 11L, 11L, 11L, 11L, 11L, 11L, 11L,
    10L, 9L, 9L, 8L, 8L, 7L, 7L, 6L, 6L, 5L, 7L, 5L, 20L, 14L,
    14L, 23L)), .Names = c("datetime", "eventhour"), row.names = c(NA,
100L), class = "data.frame")
</code>```

Any info on

(1) Why does the first, copy/pasted example not provide the data for "0" in the graph

and

(2) Why does my example combine the "23" and "0" bin

would be greatly appreciated.

EDIT -- The following code fixed the issue, but gave a warning. I do not think the warning is a problem, but am curious if anyone can interpret this. I believe the original issue is with R interpreting a break as (val1, val2] and not [val1, val2] like I expected.  As such, the 0 groupings were never kept.  Changing my breaks to seq(-1:23) is now inclusive on all values 0 through 23.

The fix :

```<code>gplotAll = ggplot( eventdataAll, aes(x=eventdataAll$eventhour) ) +
  geom_histogram(breaks=seq(-1,24), colour="purple") + coord_polar(start=0) +
  theme_minimal() + scale_fill_manual(values="purple") + ylab("Frequency") +
  ggtitle("All Sources") + scale_x_continuous("", limits=c(-1,23),
  breaks=seq(-1,23), labels=seq(0,2) )
</code>```

The warning :

```<code>Removed 1 rows containing missing values (geom_bar).
</code>```

答:
Your data are continuous in the sense that eventhour is numeric, but eventhour behaves like an ordered categorical variable because all of the eventhour values are integer hours of the day. Thus, you can do the plot with either geom_bar or geom_histogram. I'll use geom_bar (which is for categorical data) in the examples below and then show a version with geom_histogram (which is for continuous data) at the end.

The issue you're having with geom_bar is due to the fact that the bars are placed on integer hours, but have a default width of 1 unit. This means that, due to it's finite width, the bar at zero (midnight) extends below zero by 0.5 units. When you set the x-axis limit to be zero, the bar at zero gets excluded, because scale_x_continuous excludes data that are outside the limits range. However, if you set the limit to be at -0.5, then the polar scale is no longer a 0 - 24 hour clock.

I'm going to show multiple examples below, but they all have some similar plot elements, so let's save those common elements in an object that we can reuse.

```<code>my_plot = list(coord_polar(start=0),
               geom_bar(colour="grey"),
               theme_minimal(),
               scale_fill_brewer(),
               ylab("Count"))
</code>```

Now let's see what happens with geom_bar without coord_polar (we exclude the coord_polar statment in my_plot by doing my_plot[-1]). Note how the bar for midnight (eventhour = 0) is excluded when the width of the bar extends outside the x-range (first plot below) but appears when we extend the range to -0.5 (second plot below), which is the edge of the bar.

```<code>ggplot(eventdata, aes(x = eventhour)) +
  my_plot[-1] +
  scale_x_continuous(limits = c(0,24), breaks=0:23) +
  ggtitle("x-limits: c(0,24)")

ggplot(eventdata, aes(x = eventhour)) +
  my_plot[-1] +
  scale_x_continuous(limits = c(-0.5,24), breaks=0:23) +
  ggtitle("x-limits: c(-0.5,24)")
</code>```

Now let's add coord_polar to the second plot above. The code is just below and the plot is on the left below. Note that 0 is now rotated clockwise and there's an extra half-hour wedge before 0.

To fix these issues, we'll change the coord_polar statement to rotate the plot counter-clockwise by 7.5 degrees (1/48 of the circle) and remove half an hour from the other end of the plot by changing the limit to 23.5 instead of 24. This doesn't remove any data because the highest hour value is 23.

We also remove the minor gridlines to get rid of an unwanted gridline that would otherwise appear at 23.5 hours. There are actually minor gridlines at all of the half-hours, but this one gets plotted twice (because it represents both -0.5 and 23.5 hours) and is therefore more prominent than the others. We don't really need minor gridlines here, so we just get rid of them completely.

The code for this plot is the second ggplot block below and the plot is on the right.

```<code>ggplot(eventdata, aes(x = eventhour)) +
  my_plot +
  scale_x_continuous(limits = c(-0.5,24), breaks=0:23) +
  ggtitle("x-limits: c(-0.5,24)")

ggplot(eventdata, aes(x = eventhour)) +
  my_plot[-1] +
  scale_x_continuous(limits = c(-0.5,23.5), breaks=0:23) +
  ggtitle("x-limits: c(-0.5,23.5)")  +
  coord_polar(start=-48/360) +
  theme(panel.grid.minor=element_blank())
</code>```

So, the final plot code is:

```<code>ggplot(eventdata, aes(x=eventhour)) +
  geom_bar(colour="grey") +
  theme_minimal() +
  scale_fill_brewer() +
  ylab("Count") +
  coord_polar(start=-48/360) +
  scale_x_continuous(limits=c(-0.5,23.5), breaks=0:23) +
  theme(panel.grid.minor=element_blank())
</code>```

The equivalent plot with geom_histogram is below. binwidth=1 means that each bar will be 1 hour wide. center=0 ensures that each bar will be centered on a whole number (we could have chosen any whole number here instead of 0). In some cases it also matters whether the bins are closed on the left or the right (it would matter here if we set, say, center=0.5). You can set that with the closed argument; closed="right" or closed="left".

```<code>ggplot(eventdata, aes(x=eventhour)) +
  geom_histogram(colour="grey", center=0, binwidth=1) +
  theme_minimal() +
  scale_fill_brewer() +
  ylab("Count") +
  coord_polar(start=-48/360) +
  scale_x_continuous(limits=c(-0.5,23.5), breaks=0:23) +
  theme(panel.grid.minor=element_blank())
</code>```

Title: missing one "bin" of data in rose graph

Body:
I am following the following tutorial that is copy/paste reproducible here.

http://rstudio-pubs-static.s3.amazonaws.com/3369_998f8b2d788e4a0384ae565c4280aa47.html

On my setup, when I run this, I get an error

Error: Width` is deprecated. Do you want `geom_bar()`?

So I swap geom_hist for geom_bar, making my code...

ggplot(eventdata, aes(x = eventhour)) + geom_bar(breaks = seq(0, 24), width = 1, colour = "grey") + coord_polar(start = 0) + theme_minimal() + scale_fill_brewer() + ylab("Count") + ggtitle("Events by Time of day") + scale_x_continuous("", limits = c(0, 24), breaks = seq(0, 24), labels = seq(0, 24))

However, the graph I get is very different. Inspecting, it seems its "missing" the data from midnight to 1 AM ( 00:00:00 to 00:59:59, event_hour=0 )

I've tried running this on my own dataset (dput below) and I get a similar weird error....it combines the "0" bin and the "23" bin giving me 1 massive bin.

gplotAll = ggplot( eventdataAll, aes(x=eventdataAll$eventhour) ) +
  geom_histogram(breaks=seq(0,24), colour="purple") + coord_polar(start=0) +
  theme_minimal() + scale_fill_manual(values="blue") + ylab("Frequency") +
  ggtitle("All Sources") + scale_x_continuous("", limits=c(0,24),
  breaks=seq(0,24), labels=seq(0,24))

Note this is a very small subset of my data, as its millions of timestamps.

dput(eventdataAll[1:100,] )

structure(list(datetime = structure(c(1499433307, 1499428942,
1499426105, 1499422506, 1499466293, 1499408104, 1499476505, 1499411705,
1499400905, 1499466368, 1499454358, 1499453483, 1499405930, 1499484602,
1499483709, 1499480109, 1499408108, 1499445444, 1499439817, 1499427520,
1499418054, 1499416518, 1499414449, 1499410178, 1499409748, 1499409317,
1499405867, 1499402279, 1499485071, 1499481544, 1499481527, 1499481459,
1499481423, 1499481407, 1499477859, 1499475634, 1499474292, 1499474275,
1499474253, 1499470435, 1499468435, 1499468413, 1499468398, 1499467032,
1499464834, 1499463580, 1499463425, 1499461391, 1499460152, 1499460150,
1499459806, 1499459745, 1499459366, 1499458914, 1499458463, 1499458012,
1499457635, 1499457619, 1499455777, 1499454624, 1499454035, 1499454020,
1499452801, 1499452695, 1499450434, 1499450414, 1499450404, 1499450403,
1499450156, 1499446834, 1499446818, 1499446803, 1499445621, 1499444273,
1499443234, 1499443218, 1499443201, 1499441873, 1499441806, 1499441700,
1499441096, 1499441095, 1499440418, 1499440417, 1499436056, 1499434899,
1499432434, 1499431018, 1499428801, 1499427491, 1499425201, 1499423442,
1499421620, 1499421134, 1499427667, 1499421549, 1499472830, 1499451306,
1499450792, 1499482802), class = c("POSIXct", "POSIXt"), tzone = ""),
    eventhour = c(9L, 8L, 7L, 6L, 18L, 2L, 21L, 3L, 0L, 18L,
    15L, 14L, 1L, 23L, 23L, 22L, 2L, 12L, 11L, 7L, 5L, 4L, 4L,
    2L, 2L, 2L, 1L, 0L, 23L, 22L, 22L, 22L, 22L, 22L, 21L, 21L,
    20L, 20L, 20L, 19L, 19L, 19L, 18L, 18L, 18L, 17L, 17L, 17L,
    16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 15L, 15L,
    15L, 15L, 14L, 14L, 14L, 14L, 14L, 14L, 13L, 13L, 13L, 13L,
    12L, 12L, 12L, 12L, 12L, 11L, 11L, 11L, 11L, 11L, 11L, 11L,
    10L, 9L, 9L, 8L, 8L, 7L, 7L, 6L, 6L, 5L, 7L, 5L, 20L, 14L,
    14L, 23L)), .Names = c("datetime", "eventhour"), row.names = c(NA,
100L), class = "data.frame")

Any info on

(1) Why does the first, copy/pasted example not provide the data for "0" in the graph

and

(2) Why does my example combine the "23" and "0" bin

would be greatly appreciated.

EDIT -- The following code fixed the issue, but gave a warning. I do not think the warning is a problem, but am curious if anyone can interpret this. I believe the original issue is with R interpreting a break as (val1, val2] and not [val1, val2] like I expected.  As such, the 0 groupings were never kept.  Changing my breaks to seq(-1:23) is now inclusive on all values 0 through 23.

The fix :

gplotAll = ggplot( eventdataAll, aes(x=eventdataAll$eventhour) ) +
  geom_histogram(breaks=seq(-1,24), colour="purple") + coord_polar(start=0) +
  theme_minimal() + scale_fill_manual(values="purple") + ylab("Frequency") +
  ggtitle("All Sources") + scale_x_continuous("", limits=c(-1,23),
  breaks=seq(-1,23), labels=seq(0,2) )

The warning :

Removed 1 rows containing missing values (geom_bar).

Body:
Your data are continuous in the sense that eventhour is numeric, but eventhour behaves like an ordered categorical variable because all of the eventhour values are integer hours of the day. Thus, you can do the plot with either geom_bar or geom_histogram. I'll use geom_bar (which is for categorical data) in the examples below and then show a version with geom_histogram (which is for continuous data) at the end.

The issue you're having with geom_bar is due to the fact that the bars are placed on integer hours, but have a default width of 1 unit. This means that, due to it's finite width, the bar at zero (midnight) extends below zero by 0.5 units. When you set the x-axis limit to be zero, the bar at zero gets excluded, because scale_x_continuous excludes data that are outside the limits range. However, if you set the limit to be at -0.5, then the polar scale is no longer a 0 - 24 hour clock.

I'm going to show multiple examples below, but they all have some similar plot elements, so let's save those common elements in an object that we can reuse.

my_plot = list(coord_polar(start=0),
               geom_bar(colour="grey"),
               theme_minimal(),
               scale_fill_brewer(),
               ylab("Count"))

Now let's see what happens with geom_bar without coord_polar (we exclude the coord_polar statment in my_plot by doing my_plot[-1]). Note how the bar for midnight (eventhour = 0) is excluded when the width of the bar extends outside the x-range (first plot below) but appears when we extend the range to -0.5 (second plot below), which is the edge of the bar.

ggplot(eventdata, aes(x = eventhour)) +
  my_plot[-1] +
  scale_x_continuous(limits = c(0,24), breaks=0:23) +
  ggtitle("x-limits: c(0,24)")

ggplot(eventdata, aes(x = eventhour)) +
  my_plot[-1] +
  scale_x_continuous(limits = c(-0.5,24), breaks=0:23) +
  ggtitle("x-limits: c(-0.5,24)")

Now let's add coord_polar to the second plot above. The code is just below and the plot is on the left below. Note that 0 is now rotated clockwise and there's an extra half-hour wedge before 0.

To fix these issues, we'll change the coord_polar statement to rotate the plot counter-clockwise by 7.5 degrees (1/48 of the circle) and remove half an hour from the other end of the plot by changing the limit to 23.5 instead of 24. This doesn't remove any data because the highest hour value is 23.

We also remove the minor gridlines to get rid of an unwanted gridline that would otherwise appear at 23.5 hours. There are actually minor gridlines at all of the half-hours, but this one gets plotted twice (because it represents both -0.5 and 23.5 hours) and is therefore more prominent than the others. We don't really need minor gridlines here, so we just get rid of them completely.

The code for this plot is the second ggplot block below and the plot is on the right.

ggplot(eventdata, aes(x = eventhour)) +
  my_plot +
  scale_x_continuous(limits = c(-0.5,24), breaks=0:23) +
  ggtitle("x-limits: c(-0.5,24)")

ggplot(eventdata, aes(x = eventhour)) +
  my_plot[-1] +
  scale_x_continuous(limits = c(-0.5,23.5), breaks=0:23) +
  ggtitle("x-limits: c(-0.5,23.5)")  +
  coord_polar(start=-48/360) +
  theme(panel.grid.minor=element_blank())

So, the final plot code is:

ggplot(eventdata, aes(x=eventhour)) +
  geom_bar(colour="grey") +
  theme_minimal() +
  scale_fill_brewer() +
  ylab("Count") +
  coord_polar(start=-48/360) +
  scale_x_continuous(limits=c(-0.5,23.5), breaks=0:23) +
  theme(panel.grid.minor=element_blank())

The equivalent plot with geom_histogram is below. binwidth=1 means that each bar will be 1 hour wide. center=0 ensures that each bar will be centered on a whole number (we could have chosen any whole number here instead of 0). In some cases it also matters whether the bins are closed on the left or the right (it would matter here if we set, say, center=0.5). You can set that with the closed argument; closed="right" or closed="left".

ggplot(eventdata, aes(x=eventhour)) +
  geom_histogram(colour="grey", center=0, binwidth=1) +
  theme_minimal() +
  scale_fill_brewer() +
  ylab("Count") +
  coord_polar(start=-48/360) +
  scale_x_continuous(limits=c(-0.5,23.5), breaks=0:23) +
  theme(panel.grid.minor=element_blank())


来源: stackexchange

问:
Bash script - Lookup one variable from source .csv file to provide the other
What we want to accomplish. Have one source file (data.csv) to be referenced with the following data:

```<code>userone,password1
usertwo,password2
userthree,password3
</code>```

Use the source file to find a username and then provide the password after the comma as another variable.
Example

```<code>Variables:
User1=userone
User1Password=password1

#!/usr/bin/env bash
source data.csv
read data.csv
If $User1=userone
    then
$User1Password=password1
</code>```

We are using this to create a local user account on a Mac with a different line of code but need to reference a .csv file to get the variables.

Thanks in advance for any support.

答:
```<code>cat data.csv | \                                         # piping file contents to the loop
while read line; do                                      # reading the input stream line by line
    username=$(echo $line | awk -F',' '{print $1}')      # username is the 1st string if a , is the delimiter
    password=$(echo $line | awk -F',' '{print $2}')      # password is the 2nd string if a , is the delimiter
    echo ${username} ${password}                         # test
done
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What we want to accomplish. Have one source file (data.csv) to be referenced with the following data:

userone,password1
usertwo,password2
userthree,password3

Use the source file to find a username and then provide the password after the comma as another variable.
Example

Variables:
User1=userone
User1Password=password1

#!/usr/bin/env bash
source data.csv
read data.csv
If $User1=userone
    then
$User1Password=password1

We are using this to create a local user account on a Mac with a different line of code but need to reference a .csv file to get the variables.

Thanks in advance for any support.


问:
SSH heredoc: bash prompt
I am attempting to write a shell script which SSHs into a server and then prompts the user to enter a file/folder.

```<code>ssh $SERVER <<EOF
cd downloads/
read -e -p "Enter the path to the file: " FILEPATH
echo $FILEPATH
eval FILEPATH="$FILEPATH"

echo "Downloading $FILEPATH to $CLIENT"
EOF
</code>```

I am using heredoc instead of double quotes after the SSH to execute these commands because my shell script is rather large and I don't want to be escaping every double quote.

When I was using double quotes, the prompt worked fine. However, now that I am using heredoc, the prompt no longer works.

What can I do to get the prompt to work with heredoc? And if not, is there any way I layout my script so that the prompt does work without wrapping everything in double quotes and escaping, like so:

```<code>ssh $SERVER "
cd downloads/
read -e -p \"Enter the path to the file: \" FILEPATH
echo $FILEPATH
eval FILEPATH=\"$FILEPATH\"

echo \"Downloading $FILEPATH to $CLIENT\"
exit
"
</code>```

答:
To make it work with a heredoc, it should be sufficient to invoke bash, or whatever shell you want to use on the remote server. Like so:

```<code>ssh $SERVER bash <<EOF
cd downloads/
read -e -p "Enter the path to the file: " FILEPATH
echo $FILEPATH
eval FILEPATH="$FILEPATH"

echo "Downloading $FILEPATH to $CLIENT"
EOF
</code>```

Note that you probably want to escape the $ on FILEPATH, since currently that will be interpolated by the local shell rather than the remote shell.

Title: SSH heredoc: bash prompt

Body:
I am attempting to write a shell script which SSHs into a server and then prompts the user to enter a file/folder.

ssh $SERVER <<EOF
cd downloads/
read -e -p "Enter the path to the file: " FILEPATH
echo $FILEPATH
eval FILEPATH="$FILEPATH"

echo "Downloading $FILEPATH to $CLIENT"
EOF

I am using heredoc instead of double quotes after the SSH to execute these commands because my shell script is rather large and I don't want to be escaping every double quote.

When I was using double quotes, the prompt worked fine. However, now that I am using heredoc, the prompt no longer works.

What can I do to get the prompt to work with heredoc? And if not, is there any way I layout my script so that the prompt does work without wrapping everything in double quotes and escaping, like so:

ssh $SERVER "
cd downloads/
read -e -p \"Enter the path to the file: \" FILEPATH
echo $FILEPATH
eval FILEPATH=\"$FILEPATH\"

echo \"Downloading $FILEPATH to $CLIENT\"
exit
"

Body:
To make it work with a heredoc, it should be sufficient to invoke bash, or whatever shell you want to use on the remote server. Like so:

ssh $SERVER bash <<EOF
cd downloads/
read -e -p "Enter the path to the file: " FILEPATH
echo $FILEPATH
eval FILEPATH="$FILEPATH"

echo "Downloading $FILEPATH to $CLIENT"
EOF

Note that you probably want to escape the $ on FILEPATH, since currently that will be interpolated by the local shell rather than the remote shell.


问:
Why rancher service disconnected sometimes?
I used Rancher to deploy a Rails application.

I created two services. One used for install node packages and db migration. The other one used for Rails application.

The second service works well. But the first one sometimes disconnected. So it is necessary to install the node packages again. It's crazy!

The services are:

a. myapp_setup service: sometimes disconnected

b. myapp service: works well

c. postgres service: works well

a depends on c. b depends on a and c.

Addition

For example, I created a service to setup the main application. When running it to install something like database migration and node.js npm packages. From the log I know, it sometimes disconnected. And when restart again, it will reinstall the packages again. So the main project in container b can't works well.

答: disconnected is not one of the possible states for a Service so I'm not sure what you mean.  Are you talking about the Host(s) the Service is running on?  Hosts have a disconnected state, which means the agent container on it does not have an active connection to the rancher/server container.


问:
Using UITableViewController logics in UITableViewDataSource class
I'm doing a refactor because my UITableViewController is bloating very badly. The first thing I'm trying to do is refactoring the data source out of the table view controller like this:

```<code>// In my UITableViewController
let ds = MyDataSource()

func viewDidLoad() {
  tableView.dataSource = ds
}
</code>```

In my data source class, I want to use some logic that I feel should belong in the table view controller.

```<code>class MyDataSource: UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int {
    // I want to use the variable showMore here
    return showMore ? 2 : 1
  }

  // More data source doe
}
</code>```

The variable showMore is a boolean variable defined in my table view controller and is updated by a button in the footer view of a section.

Question is then, if showMore belongs in the table view controller, how can I access it from my data source class? If it doesn't belong in the
table view controller, where does it belong and why?

Thanks!

答: UITableViewController is Apple's convenient implementation of a UIViewController that contains a tableView instead of a view, as well as conforming immediately to UITableViewDataSource and UITableViewDelegate. I'd recommend you just use a UIViewController and add a tableView, and then proceed as you have by setting the table's delegate and datasource to MyCustomTableController, which would conform to both UITableViewDataSource and UITableViewDelegate. All logic should be handled inside the controller.

Body:
I'm doing a refactor because my UITableViewController is bloating very badly. The first thing I'm trying to do is refactoring the data source out of the table view controller like this:

// In my UITableViewController
let ds = MyDataSource()

func viewDidLoad() {
  tableView.dataSource = ds
}

In my data source class, I want to use some logic that I feel should belong in the table view controller.

class MyDataSource: UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int {
    // I want to use the variable showMore here
    return showMore ? 2 : 1
  }

  // More data source doe
}

The variable showMore is a boolean variable defined in my table view controller and is updated by a button in the footer view of a section.

Question is then, if showMore belongs in the table view controller, how can I access it from my data source class? If it doesn't belong in the
table view controller, where does it belong and why?

Thanks!


问:
Subsequent HTML not being displayed after PHP call
I am relatively new to PHP programming. I am building a small crud app (to-do list) to be exact for practice. I am working on fleshing out the UI and testing how information displays from my database on the page.

When a user logs in, they are shown a table of all the items they have saved.

table listing items

```<code>  <div class="container">
    <table class="table">
      <tr>
        <th>Completed</th>
        <th>Description</th>
        <th>Actions</th>
      </tr>
      <tr>
        <td colspan="3"></td>
      </tr>
      <?php
      $document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
      while($match_value = mysql_fetch_array($document_get)) {
      ?>
      <tr>
        <td>
          Hi
        </td>
      </tr>
    </table>
    <?php
    }
    ?>
  </div>
</code>```

php call to display list item

```<code>      <?php
      $document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
      while($match_value = mysql_fetch_array($document_get)) {
      ?>
</code>```

Anything under this PHP request does not show up for some reason. I have looked at other posts where people have mentioned the same thing but I did not see anything specific that matched my issue per say.

答:
```<code>enter code here  <?php
  $document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
  while($match_value = mysql_fetch_array($document_get)) {
  echo "
  <tr>
    <td>
      Hi
    </td>
  </tr>
</code>```

";

```<code>}
echo    " </table>";
?>
</code>```

Do the whole thing in php using echo to display the table elemts and Hi. Remove the extra php tags so loop and echo all php. Also look at security issues mentioned in comments. By the way, I moved the table end tag outside loop after reading comment below the question.

Body:
I am relatively new to PHP programming. I am building a small crud app (to-do list) to be exact for practice. I am working on fleshing out the UI and testing how information displays from my database on the page.

When a user logs in, they are shown a table of all the items they have saved.

table listing items

        Completed
        Description
        Actions

      <?php
      $document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
      while($match_value = mysql_fetch_array($document_get)) {
      ?>

          Hi

    <?php
    }
    ?>

php call to display list item

      <?php
      $document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
      while($match_value = mysql_fetch_array($document_get)) {
      ?>

Anything under this PHP request does not show up for some reason. I have looked at other posts where people have mentioned the same thing but I did not see anything specific that matched my issue per say.

Body:
enter code here  <?php
  $document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
  while($match_value = mysql_fetch_array($document_get)) {
  echo "
  <tr>
    <td>
      Hi
    </td>
  </tr>

";

}
echo    " </table>";
?>

Do the whole thing in php using echo to display the table elemts and Hi. Remove the extra php tags so loop and echo all php. Also look at security issues mentioned in comments. By the way, I moved the table end tag outside loop after reading comment below the question.


问:
ld.exe: cannot open output file ... : Permission denied
I recently installed CodeBlocks with mingw32 on Windows 7 Ultimate 32bit in order to dust off my c skills, but this problem has me somewhat stumped.

I decided to fire off a short Fibonacci generator to make sure my setup was working, but I ran into a hurdle.

The program compiles, links and whatnot like a charm and I get a corresponding executable which runs as expected.

The problems occur if I try to compile again, then I get the following:

```<code>c:/codeblocks/mingw/bin/../lib/gcc/mingw32/4.4.1/../../../../mingw32/bin/ld.exe: cannot open output file bin\Debug\Fibonacci.exe: Permission denied
</code>```

I can't even edit the permissions of the generated executable.

I've checked the usual suspects:

Executable is verily not running.

Path to executable is read/writable to mingw32 (otherwise it wouldn't be able to build in the first place)

I'm not running cygwin in any shape or form.

And now for the funny bit: Usually after a few minutes, any executables generated by mingw32 which are displaying this Access Denied behaviour will automatically vanish without any intervention from me.

I've googled this somewhat, but most of the other results were either vague or inapplicable.

I wonder whether there is some Windows 7 security setting playing havoc with my .exe's, but I'm not that knowledgeable about Win 7 as to know where to begin searching.

Any one have any ideas?

答:
It may be your Antivirus Software.

In my case Malwarebytes was holding a handle on my program's executable:

Using Process Explorer to close the handle, or just disabling antivirus for a bit work just fine.

Body:
I recently installed CodeBlocks with mingw32 on Windows 7 Ultimate 32bit in order to dust off my c skills, but this problem has me somewhat stumped.

I decided to fire off a short Fibonacci generator to make sure my setup was working, but I ran into a hurdle.

The program compiles, links and whatnot like a charm and I get a corresponding executable which runs as expected.

The problems occur if I try to compile again, then I get the following:

c:/codeblocks/mingw/bin/../lib/gcc/mingw32/4.4.1/../../../../mingw32/bin/ld.exe: cannot open output file bin\Debug\Fibonacci.exe: Permission denied

I can't even edit the permissions of the generated executable.

I've checked the usual suspects:

Executable is verily not running.

Path to executable is read/writable to mingw32 (otherwise it wouldn't be able to build in the first place)

I'm not running cygwin in any shape or form.

And now for the funny bit: Usually after a few minutes, any executables generated by mingw32 which are displaying this Access Denied behaviour will automatically vanish without any intervention from me.

I've googled this somewhat, but most of the other results were either vague or inapplicable.

I wonder whether there is some Windows 7 security setting playing havoc with my .exe's, but I'm not that knowledgeable about Win 7 as to know where to begin searching.

Any one have any ideas?


问:
ruby on rails - validation in nested class shows the error screen on failing
I currently have a problem with a simple validation.
On saving my model this validation is ran.

A user has multiple questions, questions have multiple answers

This validates statement is part of my joined table class

```<code>validates :answers, length: { maximum: 6 }
</code>```

The answer will be the one updated, so I ask the question to validate itself

```<code>validates_associated :user_question
</code>```

This validation is failed correctly when the number of answers selected exceeds 6.
However, instead of returning to my form. It shows me a big error message stating that the validation has failed.

I would like to display these problems on the form so the user knows what's wrong.

Other validation errors for the form are displaying as intended. It's just this nested attribute that is causing problems for some reason.

This is the error that is being shown

```<code>ActiveRecord::RecordInvalid

Validation failed: User question is invalid
</code>```

On the following line: @user.attributes=(user_params)

That's indeed the moment when it validates (I think), but it is too abstracted to see what is wrong with the validation exactly (If there is anything wrong).

Any help is appreciated.

答:
The validates_associated statement will do two things:

run validations on the named association, populating errors on that associated object

log an error on the association itself so that the validating object will also be considered invalid.

So the details of why your question is invalid should be available from @user.user_question.errors.

Body:
I currently have a problem with a simple validation.
On saving my model this validation is ran.

A user has multiple questions, questions have multiple answers

This validates statement is part of my joined table class

validates :answers, length: { maximum: 6 }

The answer will be the one updated, so I ask the question to validate itself

validates_associated :user_question

This validation is failed correctly when the number of answers selected exceeds 6.
However, instead of returning to my form. It shows me a big error message stating that the validation has failed.

I would like to display these problems on the form so the user knows what's wrong.

Other validation errors for the form are displaying as intended. It's just this nested attribute that is causing problems for some reason.

This is the error that is being shown

ActiveRecord::RecordInvalid

Validation failed: User question is invalid

On the following line: @user.attributes=(user_params)

That's indeed the moment when it validates (I think), but it is too abstracted to see what is wrong with the validation exactly (If there is anything wrong).

Any help is appreciated.


问:
DFA for binary number equivalent decimal divisible by 3
DFA for generating binary numbers that are divisible by 3 ,2&5 have been known in that we read string for eg 1 next 0 next 0   100 is string  for this first we  read string and assing base 2 ( binary powers) from right to left ......

Suppose if we read same string in same order but first placing numbers sequentially in power of 2 if we read 1 it be first bit and 0 2nd bit  so we will read as 001 for above DFA we read the string oppositely ....so what is DFA for this by placing bits from left to right

答:
The usual way of making a DFA that computes something like this is to first make an NFA (since NFAs are must easier to compose vis union/intersection/etc), and then convert the NFA to a DFA.

So how do you compute if a binary number is divisible by 3?  Well, given a number in base-b, you can easily compute mod b-1 of it by adding the digits of mod b-1.  Given a binary number you can generate base 2k digits by simply taking them in groups.  So for mod 3, you need base 4 digits (pairs of bits).  You can get mod 7 by using groups of 3 bits, and mod 15 with groups of 4.  mod 15 can then be trivially converted to mod 5 and mod 3.

So how do you make an NFA that adds mod n?  You need a loop of n states that correspond to the value 0..n-1 and have transitions between them for adding bits.  For the base 3 case, that is 3 states

```<code>state      00 01 10 11
  0         0  1  2  0
  1         1  2  0  1
  2         2  0  1  2
</code>```

This is an NFA, so a 2-bit transition goes through an intermediate state that is otherwise unconnected.  Your start and accepting state is 0.  One final subtlety is dealing with an odd number of bits.  How you handle that depends on whether your number is big-endian or little-endian.  For little-endian you want to treat the final odd bit as a digit, so make the edge-intermediate states that transition to 0 on a 0 bit accepting states.  For big endian, you instead add an additional start state that transitions to 0 and 1 on a single 0 or 1 bit.

Body:
The usual way of making a DFA that computes something like this is to first make an NFA (since NFAs are must easier to compose vis union/intersection/etc), and then convert the NFA to a DFA.

So how do you compute if a binary number is divisible by 3?  Well, given a number in base-b, you can easily compute mod b-1 of it by adding the digits of mod b-1.  Given a binary number you can generate base 2k digits by simply taking them in groups.  So for mod 3, you need base 4 digits (pairs of bits).  You can get mod 7 by using groups of 3 bits, and mod 15 with groups of 4.  mod 15 can then be trivially converted to mod 5 and mod 3.

So how do you make an NFA that adds mod n?  You need a loop of n states that correspond to the value 0..n-1 and have transitions between them for adding bits.  For the base 3 case, that is 3 states

state      00 01 10 11
  0         0  1  2  0
  1         1  2  0  1
  2         2  0  1  2

This is an NFA, so a 2-bit transition goes through an intermediate state that is otherwise unconnected.  Your start and accepting state is 0.  One final subtlety is dealing with an odd number of bits.  How you handle that depends on whether your number is big-endian or little-endian.  For little-endian you want to treat the final odd bit as a digit, so make the edge-intermediate states that transition to 0 on a 0 bit accepting states.  For big endian, you instead add an additional start state that transitions to 0 and 1 on a single 0 or 1 bit.


问:
Dividing workload on several threads
I was wondering if anyone knows about a good article which describes dividing workload on to several Threads? Preferebly it would be written for C# but it's really the concept I'm after, so it's not an issue if it's written for a different, similar, language.

I have a problem where I would have to divide a large amount of computing into several threads and then Sum the generated data after one iteration completes (so I would need to know that all threads have finished) and then start a new iteration, supplying all the threads with the data generated in the last iteration (the data would be modified before the end of each iteration).

I hope this makes sense, and is possible. Either way I would appreciate some advice on how to tackle the problem of computing large amounts of data divided on to several threads (so I can use more than one processor's core).

Thank you for your answers!

答:
Lasse and Marc have already spoken about Parallel Extensions. I have a couple of blog articles (with code) about using and benchmarking it:

Conway's Game of Life

Visualising the Mandelbrot set

These might be helpful to show various different ways that work can be broken up.

OwnerDisplayName: Rekreativc

ContentLicense: CC BY-SA 2.5

Title: Dividing workload on several threads

OwnerDisplayName: Jon Skeet


问:
boto3 file_upload does it check if file exists
I was looking through the boto3 documentation and could not find if it natively supports a check to see if the file already exists in s3 and if not do not try and re-upload.

Here's what I have working:

```<code>import boto3

s3_client = boto3.client('s3')
s3_bucket = 'bucketName'
s3_folder = 'folder1234/'
temp_log_dir = "tempLogs/"

s3_client.upload_file(temp_log_dir + file_name, s3_bucket, s3_folder + file_name)
</code>```

What I'm noticing is that if the file exits in S3 already , the .upload_file() from boto3 still transfers the file. I did this check by looking at iftop.

Is there some arg i'm missing to disable "auto overwrite if file exists"?

Thanks

edit trying the head method

```<code>s3 = boto3.resource('s3')
file_name = 'somelogfile.gz'

try:
    s3.Object(s3_bucket+ s3_folder+s3_filename).load()
    print 'success'
except botocore.exceptions.ClientError as e:
    print e
</code>```

答:
You can test the existence of an object using s3_client.head_object() or s3_service.Object().load():

```<code>import boto3
from botocore.exceptions import ClientError

def check(s3_client, bucket, key):
    try:
        s3_client.head_object(Bucket=bucket, Key=key)
    except ClientError as e:
        return int(e.response['Error']['Code']) != 404
    return True

s3_client = boto3.client('s3')
print(check(s3_client, <bucket>, <key>))
</code>```

With s3 service resource this would achieve the same:

```<code>def check(s3_service, bucket, key):
    try:
        s3_service.Object(bucket, key).load()
    except ClientError as e:
        return int(e.response['Error']['Code']) != 404
    return True

s3_service = boto3.resource(service_name='s3')
print(check(s3_service, <bucket>, <key>))
</code>```

Body:
I was looking through the boto3 documentation and could not find if it natively supports a check to see if the file already exists in s3 and if not do not try and re-upload.

Here's what I have working:

import boto3

s3_client = boto3.client('s3')
s3_bucket = 'bucketName'
s3_folder = 'folder1234/'
temp_log_dir = "tempLogs/"

s3_client.upload_file(temp_log_dir + file_name, s3_bucket, s3_folder + file_name)

What I'm noticing is that if the file exits in S3 already , the .upload_file() from boto3 still transfers the file. I did this check by looking at iftop.

Is there some arg i'm missing to disable "auto overwrite if file exists"?

Thanks

edit trying the head method

s3 = boto3.resource('s3')
file_name = 'somelogfile.gz'

try:
    s3.Object(s3_bucket+ s3_folder+s3_filename).load()
    print 'success'
except botocore.exceptions.ClientError as e:
    print e

Body:
You can test the existence of an object using s3_client.head_object() or s3_service.Object().load():

import boto3
from botocore.exceptions import ClientError

def check(s3_client, bucket, key):
    try:
        s3_client.head_object(Bucket=bucket, Key=key)
    except ClientError as e:
        return int(e.response['Error']['Code']) != 404
    return True

s3_client = boto3.client('s3')
print(check(s3_client, <bucket>, <key>))

With s3 service resource this would achieve the same:

def check(s3_service, bucket, key):
    try:
        s3_service.Object(bucket, key).load()
    except ClientError as e:
        return int(e.response['Error']['Code']) != 404
    return True

s3_service = boto3.resource(service_name='s3')
print(check(s3_service, <bucket>, <key>))

ContentLicense: CC BY-SA 4.0


问:
The length -1 is not valid for function "SUBSTRING". The length parameter cannot be negative in SSIS
I am trying to convert a data from a flat file to a SQL date. I am using variables to separate the Month, Day, and Year and added necessary "0" when needed then concatenate them back together. the job works fine except when I run into a date that is blank and it throws out three errors: "The length -1 is not valid for function "SUBSTRING". The length parameter cannot be negative. Change the length parameter to zero or a positive value.", "Evaluating function "SUBSTRING" failed with error code 0xC004708B.", AND "Evaluating function "LEN" failed with error code 0xC00470C5.". I have a variable for the date 1/2/1995 to find the "/" using Y FINDSTRING( @[User::Scan_Date] , "/", 1 )

and then the example I have for the month is

```<code>@[User::Y] < 1 ?  (DT_STR, 2, 1252) NULL(DT_STR, 2, 1252) :  (LEN( SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 )) < 2 ? "0" + SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 ) : SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 ))
</code>```

As I said, the expression works fine if there is a date, but if it is blank then I receive an error.

答:
You have to check if @[User::Scan_Date] is null using ISNULL() function, if it is null you can return a  blank string or NULL value, else calculate your expression.

```<code>ISNULL(@[User::Scan_Date]) ? "" :
(@[User::Y] < 1 ?  (DT_STR, 2, 1252) NULL(DT_STR, 2, 1252) :  (LEN( SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 )) < 2 ? "0" + SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 ) : SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 )))
</code>```

Body:
I am trying to convert a data from a flat file to a SQL date. I am using variables to separate the Month, Day, and Year and added necessary "0" when needed then concatenate them back together. the job works fine except when I run into a date that is blank and it throws out three errors: "The length -1 is not valid for function "SUBSTRING". The length parameter cannot be negative. Change the length parameter to zero or a positive value.", "Evaluating function "SUBSTRING" failed with error code 0xC004708B.", AND "Evaluating function "LEN" failed with error code 0xC00470C5.". I have a variable for the date 1/2/1995 to find the "/" using Y FINDSTRING( @[User::Scan_Date] , "/", 1 )

and then the example I have for the month is

@[User::Y] < 1 ?  (DT_STR, 2, 1252) NULL(DT_STR, 2, 1252) :  (LEN( SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 )) < 2 ? "0" + SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 ) : SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 ))

As I said, the expression works fine if there is a date, but if it is blank then I receive an error.

Body:
You have to check if @[User::Scan_Date] is null using ISNULL() function, if it is null you can return a  blank string or NULL value, else calculate your expression.

ISNULL(@[User::Scan_Date]) ? "" :
(@[User::Y] < 1 ?  (DT_STR, 2, 1252) NULL(DT_STR, 2, 1252) :  (LEN( SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 )) < 2 ? "0" + SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 ) : SUBSTRING( @[User::Scan_Date] , 1, @[User::Y] -1 )))


问:
IQueryable with Linq expression resulting in NullReferenceException
The following function results in a NullReferenceException because it is referencing m.tags, which has not been declared in the JSON object. This is intentional. I need to query for all JSON objects that have no existing tags object.

SelectNext

```<code>TweetModel tweet = client
    .CreateDocumentQuery<TweetModel>( UriFactory.CreateDocumentCollectionUri( databaseName, collectionName), queryOptions )
    .Where( m => m.tags == null )
    .ToList()
    .FirstOrDefault();
</code>```

Example Document

```<code>{
  "timestamp": "2017-07-05T19:31:18.918Z",
  "topic": "Trump",
  "score": "1",
  "sentiment": "positive",
  "text": "@gjacquette @travi44 @WSJ Where did I say trump shouldn't hire a lawyer? I said the fact his lawyers are hiring law… ",
  "id": "882683325495816192",
  "retweet_count": 0,
  "time_zone": null,
  "lang": "en",
  "screen_name": "bernielove1969"
}
</code>```

Declaring empty values for the tags object solves the exception, so I am certain that this is the problem, I'm just not sure how to fix it.

I have tried modifying m => m.tags == null to !(m => m.tags != null) with no luck as well as a variety of other solutions throughout the last couple of hours. Suggestions are welcomed.

答:
Change this:

```<code>.Where(m => m.tags == null)
</code>```

to this:

```<code>.Where(m => m?.tags == null)
</code>```

With the use of the Null-conditional Operator, you will not hit a NullReferenceException if m doesn't refer to an object.

Update

When dealing with IQueryable<T> queries, the lambda expressions are converted into expression trees and expression trees don't support the null conditional operator. therefore you can do .Where(m => m != null && m.tags == null) instead.

Body:
The following function results in a NullReferenceException because it is referencing m.tags, which has not been declared in the JSON object. This is intentional. I need to query for all JSON objects that have no existing tags object.

SelectNext

TweetModel tweet = client
    .CreateDocumentQuery<TweetModel>( UriFactory.CreateDocumentCollectionUri( databaseName, collectionName), queryOptions )
    .Where( m => m.tags == null )
    .ToList()
    .FirstOrDefault();

Example Document

{
  "timestamp": "2017-07-05T19:31:18.918Z",
  "topic": "Trump",
  "score": "1",
  "sentiment": "positive",
  "text": "@gjacquette @travi44 @WSJ Where did I say trump shouldn't hire a lawyer? I said the fact his lawyers are hiring law… ",
  "id": "882683325495816192",
  "retweet_count": 0,
  "time_zone": null,
  "lang": "en",
  "screen_name": "bernielove1969"
}

Declaring empty values for the tags object solves the exception, so I am certain that this is the problem, I'm just not sure how to fix it.

I have tried modifying m => m.tags == null to !(m => m.tags != null) with no luck as well as a variety of other solutions throughout the last couple of hours. Suggestions are welcomed.

Body:
Change this:

.Where(m => m.tags == null)

to this:

.Where(m => m?.tags == null)

With the use of the Null-conditional Operator, you will not hit a NullReferenceException if m doesn't refer to an object.

Update

When dealing with IQueryable<T> queries, the lambda expressions are converted into expression trees and expression trees don't support the null conditional operator. therefore you can do .Where(m => m != null && m.tags == null) instead.


问:
Firebase DynamicLinks - Can i see analytics of link created by the new buildShortDynamicLink API?
I'm using the new buildShortDynamicLink API of Firebase (And it's great).
And i see there are two methodes for the ShortDynamicLink result:

```<code>Uri shortLink = task.getResult().getShortLink();
Uri flowchartLink = task.getResult().getPreviewLink();
</code>```

I tried to use both but still the link doesn't apear in the Firebase dashboard.

What is getPreviewLink used for anyway?

Thanks.

答:
Only analytics for links created in the console will show up in the console.

You can still access the analytics for your short links created via the API by using the Firebase Dynamic Links Rest API as described here (https://firebase.google.com/docs/reference/dynamic-links/analytics).

The getPreview returns the url to a visual flowchart that helps illustrate clearly how the link will work in each context. You can use it to debug the link if you want and to visually see how it will behave in different contexts.

 Full disclosure: I work for Firebase.

Body:
I'm using the new buildShortDynamicLink API of Firebase (And it's great).
And i see there are two methodes for the ShortDynamicLink result:

Uri shortLink = task.getResult().getShortLink();
Uri flowchartLink = task.getResult().getPreviewLink();

I tried to use both but still the link doesn't apear in the Firebase dashboard.

What is getPreviewLink used for anyway?

Thanks.


问:
How to check Kafka consumer state
I have Kafka High level consumer.

```<code>public class KafkaHighLevelConsumer implements Runnable {
    private final KafkaConsumer<String, String> consumer;
    private final List<String> topics;
    private final int id;

    public KafkaHighLevelConsumer(int id,
                        String groupId,
                        List<String> topics,BlockingQueue<String> storyQueue) {
        this.id = id;
        this.topics = topics;
        Properties props = new Properties();
        props.put("bootstrap.servers", "localhost:9091");
        props.put("group.id", groupId);
        props.put("key.deserializer", StringDeserializer.class.getName());
        props.put("value.deserializer", StringDeserializer.class.getName());
        this.consumer = new KafkaConsumer<>(props);
    }

    @Override
    public void run() {
        try {
            consumer.subscribe(topics);

            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(100);
                for (ConsumerRecord<String, String> record : records) {
                    Map<String, Object> data = new HashMap<>();
                    data.put("partition", record.partition());
                    data.put("offset", record.offset());
                    data.put("value", record.value());
                    System.out.println(this.id + ": " + data);
                }
            }
        } catch (WakeupException e) {
            // ignore for shutdown
        }finally {
            consumer.close();
        }
    }

    public void shutdown() {
        consumer.wakeup();
    }
}
</code>```

The consumer works fine, but I need to monitor the state of consumer.
Why don't we have Exception if server ip or port is incorrect?

If I change port to some incorrect props.put("bootstrap.servers", "localhost:9091"); to props.put("bootstrap.servers", "localhost:100500"); I still can't get any exception.

I would like to know if I successfully connected to Kafka or not! Is it possible to handle such case?

I use such Maven deps

```<code><dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>
            <version>0.9.0.1</version>
        </dependency>
</code>```

Thanks!

答:
According to the client documentation (https://kafka.apache.org/090/javadoc/org/apache/kafka/clients/consumer/KafkaConsumer.html):

It will transparently handle the failure of servers in the Kafka cluster

The library cannot tell the difference between a temporary failure, a permanent failure or a misconfiguration. So it considers every failure to be "retryable", and does exactly this, retries forever, never returning an error.

This is a workaround to check the state of the connection: Ask for some information that is guaranteed to return, wait for some reasonable time and if nothing returns then you know that the connection has some problem:

```<code>int CONNECTION_TEST_TIMEOUT_SECONDS = 10; // or whatever is appropriate for your environment

ExecutorService executor = Executors.newSingleThreadExecutor();
Runnable testTask = consumer::listTopics;

Future future = executor.submit(testTask);
try {
    future.get(CONNECTION_TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (TimeoutException te) {
    consumer.wakeup();
    throw new IOException("Could not communicate with the server within " + CONNECTION_TEST_TIMEOUT_SECONDS + " seconds");
} catch (InterruptedException e) {
    // Nothing to do. Maybe a warning in the log?
} catch (ExecutionException e) {
    throw new IOException("Exception while running connection test: " + e.getMessage(), e);
}
</code>```

Title: How to check Kafka consumer state

Body:
I have Kafka High level consumer.

public class KafkaHighLevelConsumer implements Runnable {
    private final KafkaConsumer<String, String> consumer;
    private final List<String> topics;
    private final int id;

    public KafkaHighLevelConsumer(int id,
                        String groupId,
                        List<String> topics,BlockingQueue<String> storyQueue) {
        this.id = id;
        this.topics = topics;
        Properties props = new Properties();
        props.put("bootstrap.servers", "localhost:9091");
        props.put("group.id", groupId);
        props.put("key.deserializer", StringDeserializer.class.getName());
        props.put("value.deserializer", StringDeserializer.class.getName());
        this.consumer = new KafkaConsumer<>(props);
    }

    @Override
    public void run() {
        try {
            consumer.subscribe(topics);

            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(100);
                for (ConsumerRecord<String, String> record : records) {
                    Map<String, Object> data = new HashMap<>();
                    data.put("partition", record.partition());
                    data.put("offset", record.offset());
                    data.put("value", record.value());
                    System.out.println(this.id + ": " + data);
                }
            }
        } catch (WakeupException e) {
            // ignore for shutdown
        }finally {
            consumer.close();
        }
    }

    public void shutdown() {
        consumer.wakeup();
    }
}

The consumer works fine, but I need to monitor the state of consumer.
Why don't we have Exception if server ip or port is incorrect?

If I change port to some incorrect props.put("bootstrap.servers", "localhost:9091"); to props.put("bootstrap.servers", "localhost:100500"); I still can't get any exception.

I would like to know if I successfully connected to Kafka or not! Is it possible to handle such case?

I use such Maven deps

<dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>
            <version>0.9.0.1</version>
        </dependency>

Thanks!

Body:
According to the client documentation (https://kafka.apache.org/090/javadoc/org/apache/kafka/clients/consumer/KafkaConsumer.html):

It will transparently handle the failure of servers in the Kafka cluster

The library cannot tell the difference between a temporary failure, a permanent failure or a misconfiguration. So it considers every failure to be "retryable", and does exactly this, retries forever, never returning an error.

This is a workaround to check the state of the connection: Ask for some information that is guaranteed to return, wait for some reasonable time and if nothing returns then you know that the connection has some problem:

int CONNECTION_TEST_TIMEOUT_SECONDS = 10; // or whatever is appropriate for your environment

ExecutorService executor = Executors.newSingleThreadExecutor();
Runnable testTask = consumer::listTopics;

Future future = executor.submit(testTask);
try {
    future.get(CONNECTION_TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (TimeoutException te) {
    consumer.wakeup();
    throw new IOException("Could not communicate with the server within " + CONNECTION_TEST_TIMEOUT_SECONDS + " seconds");
} catch (InterruptedException e) {
    // Nothing to do. Maybe a warning in the log?
} catch (ExecutionException e) {
    throw new IOException("Exception while running connection test: " + e.getMessage(), e);
}


问:
Scala flatMap, what are ms and e?
I'm learning Scala and in the below code using flatMap (taken from 99 Scala problems) I have

```<code>def myflatten(somelist : List[Any]): List[Any] = somelist flatMap {
    case ms: List[_] => flatten(ms)
    case e => List(e)
}
</code>```

Now Im totally confused what the 'ms' and 'e' are? they must be something key as if I change ms to say dd, I get the error "not found value ms". If I hover over them i get a tool-tip saying 'ms' is a 'List[ ][ ]' and 'e' is 'Any'.

I've tried googling for "Scala List elements ms and e" or "Scala flatMap ms and e" or "Scala what do case ms and  case e mean?" but I have not seem to find anything that explains what these 'ms' and 'e' are.

Are they keywords? Where can I find info on them in the Scala documentation?

P.S. I understand the code, but just not what ms and e are

答: In general you are comparing with two different cases (ie) case ms having list of any and the other one is of case default specified by e. so if you have list[_] then will implement flat map or else the second option you specified</p>

Title: Scala flatMap, what are ms and e?

Body:
I'm learning Scala and in the below code using flatMap (taken from 99 Scala problems) I have

def myflatten(somelist : List[Any]): List[Any] = somelist flatMap {
    case ms: List[_] => flatten(ms)
    case e => List(e)
}

Now Im totally confused what the 'ms' and 'e' are? they must be something key as if I change ms to say dd, I get the error "not found value ms". If I hover over them i get a tool-tip saying 'ms' is a 'List[ ][ ]' and 'e' is 'Any'.

I've tried googling for "Scala List elements ms and e" or "Scala flatMap ms and e" or "Scala what do case ms and  case e mean?" but I have not seem to find anything that explains what these 'ms' and 'e' are.

Are they keywords? Where can I find info on them in the Scala documentation?

P.S. I understand the code, but just not what ms and e are


问:
Making a "Mad Lib" using the string.replace method and replacing multiple terms
This is a question on an assignment, the important part reading: "Prompt the user for strings to replace the various parts of speech that you have specified.  Print out the revised story.  [Hint:  the string method replace(old,new)may be helpful]"

Here is the code I have so far:

```<code>story = "A long time ago, in a(n) PLACE-ONE far away, lived a BOY-OR-GIRL named NAME. " \
    "They lived with their mother, father, and pet ANIMAL named PET NAME. " \
    "One day, while NAME and PET NAME were playing in the PLACE-TWO, PET NAME " \
    "ran away, and NAME heard a loud SOUND and discovered that PET NAME collided " \
    "with a NOUN, and PET NAME was covered in MESSY-NOUN. As NAME went to go help PET NAME, " \
    "They too became covered in MESSY-NOUN. So they both had to ACTIVE-VERB back to PLACE-ONE and bathe in LIQUID " \
    "to get all clean. The End."
print(story)

place1 = str(input("Enter a place: "))
boyGirl = str(input("Enter a gender (can be a boy or girl): "))
bgName = str(input("Enter a name for your boy or girl: "))
animal = str(input("Enter an animal: "))
animalName = str(input("Enter a name for the animal: "))
place2 = str(input("Enter another place: "))
sound = str(input("Enter a sound: "))
noun1 = str(input("Enter a noun, preferably a large one: "))
messyNoun = str(input("Enter a noun that is messy/dirty: "))
activeVerb = str(input("Enter an action verb: "))
liquid = str(input("Enter a liquid: "))

print(story.replace("PLACE-ONE", place1))
print(story.replace("BOY-OR-GIRL", boyGirl))
print(story.replace("NAME", bgName))
print(story.replace("ANIMAL", animal))
print(story.replace("PET NAME", animalName))
print(story.replace("PLACE-TWO", place2))
print(story.replace("SOUND", sound))
print(story.replace("NOUN", noun1))
print(story.replace("MESSY-NOUN", messyNoun))
print(story.replace("ACTIVE-VERB", activeVerb))
print(story.replace("LIQUID", liquid))
</code>```

Do I need to make a loop to replace everything in the strings?

When I run it, it replaces just that term instead of it, so I just have a bunch of copies of the story with each one only having one term replaced. Or do I need to create a function to do the replacements?

答:
story.replace() returns a new string, it doesn't change the original string. So every time you call it, you're starting from the original, losing the replacements from the previous line. You need to reassign the result back to story:

```<code>story = story.replace("PLACE-ONE", place1)
story = story.replace("BOY-OR-GIRL", boyGirl)
story = story.replace("NAME", bgName)
story = story.replace("ANIMAL", animal)
story = story.replace("PET NAME", animalName)
story = story.replace("PLACE-TWO", place2)
story = story.replace("SOUND", sound)
story = story.replace("NOUN", noun1)
story = story.replace("MESSY-NOUN", messyNoun)
story = story.replace("ACTIVE-VERB", activeVerb)
story = story.replace("LIQUID", liquid)
print(story)
</code>```

Body:
This is a question on an assignment, the important part reading: "Prompt the user for strings to replace the various parts of speech that you have specified.  Print out the revised story.  [Hint:  the string method replace(old,new)may be helpful]"

Here is the code I have so far:

story = "A long time ago, in a(n) PLACE-ONE far away, lived a BOY-OR-GIRL named NAME. " \
    "They lived with their mother, father, and pet ANIMAL named PET NAME. " \
    "One day, while NAME and PET NAME were playing in the PLACE-TWO, PET NAME " \
    "ran away, and NAME heard a loud SOUND and discovered that PET NAME collided " \
    "with a NOUN, and PET NAME was covered in MESSY-NOUN. As NAME went to go help PET NAME, " \
    "They too became covered in MESSY-NOUN. So they both had to ACTIVE-VERB back to PLACE-ONE and bathe in LIQUID " \
    "to get all clean. The End."
print(story)

place1 = str(input("Enter a place: "))
boyGirl = str(input("Enter a gender (can be a boy or girl): "))
bgName = str(input("Enter a name for your boy or girl: "))
animal = str(input("Enter an animal: "))
animalName = str(input("Enter a name for the animal: "))
place2 = str(input("Enter another place: "))
sound = str(input("Enter a sound: "))
noun1 = str(input("Enter a noun, preferably a large one: "))
messyNoun = str(input("Enter a noun that is messy/dirty: "))
activeVerb = str(input("Enter an action verb: "))
liquid = str(input("Enter a liquid: "))

print(story.replace("PLACE-ONE", place1))
print(story.replace("BOY-OR-GIRL", boyGirl))
print(story.replace("NAME", bgName))
print(story.replace("ANIMAL", animal))
print(story.replace("PET NAME", animalName))
print(story.replace("PLACE-TWO", place2))
print(story.replace("SOUND", sound))
print(story.replace("NOUN", noun1))
print(story.replace("MESSY-NOUN", messyNoun))
print(story.replace("ACTIVE-VERB", activeVerb))
print(story.replace("LIQUID", liquid))

Do I need to make a loop to replace everything in the strings?

When I run it, it replaces just that term instead of it, so I just have a bunch of copies of the story with each one only having one term replaced. Or do I need to create a function to do the replacements?

Body:
story.replace() returns a new string, it doesn't change the original string. So every time you call it, you're starting from the original, losing the replacements from the previous line. You need to reassign the result back to story:

story = story.replace("PLACE-ONE", place1)
story = story.replace("BOY-OR-GIRL", boyGirl)
story = story.replace("NAME", bgName)
story = story.replace("ANIMAL", animal)
story = story.replace("PET NAME", animalName)
story = story.replace("PLACE-TWO", place2)
story = story.replace("SOUND", sound)
story = story.replace("NOUN", noun1)
story = story.replace("MESSY-NOUN", messyNoun)
story = story.replace("ACTIVE-VERB", activeVerb)
story = story.replace("LIQUID", liquid)
print(story)


问:
how to save codes history in QT Console python?
I just switched from R to Python, and find Jupyter Qt Console is really handy and helpful for running codes line by line.

But I have a question: how to save the codes already input? I mean just like Rstudio, the top left part is the code editor, the bottom left is the console window. So I can get a whole picture of my codes and debug them line by line.

I have tried Spyder(Rstudio like), but it has some problems in auto-completion. Qt console is much better. Is there a way to combine a text editor and qt console into one single IDE?

Thanks!

答:
From the jupyter qtconsole you can use the %save magic to save your work.  It's more cumbersome than I would like because you have to specify which input cells you want to save, but still quite handy.

For example, to save input cells 2 through 7 to a file called MyCommands.py, you simply type

```<code>%save MyCommands.py 2-7
</code>```

Which will save the file in your current working directory.  It'll even warn you and ask for confirmation if the file already exists.

For more information, use jupyter's extremely useful built-in help functionality by adding a question mark after the item you want help with.

```<code>%save?
</code>```

Which prints the docstring

Docstring: Save a set of lines or a macro to a given filename.

Usage:   %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...

Options:

-r: use 'raw' input.  By default, the 'processed' history is used,

  so that magics are loaded in their transformed version to valid

  Python.  If this option is given, the raw input as typed as the

  command line is used instead.
       -f: force overwrite.  If file exists, %save will prompt for overwrite   unless -f is given.

-a: append to the file instead of overwriting it.

This function uses the same syntax as %history for input ranges, then
  saves the lines to the filename you specify.

It adds a '.py' extension to the file if you don't do so yourself, and
  it asks for confirmation before overwriting existing files.

If -r option is used, the default extension is .ipy. File:

  ~/anaconda3/lib/python3.5/site-packages/IPython/core/magics/code.py

Note that you can use the question mark to investigate any function or object with a docstring (i.e. enumerate?, range?).

Body:
From the jupyter qtconsole you can use the %save magic to save your work.  It's more cumbersome than I would like because you have to specify which input cells you want to save, but still quite handy.

For example, to save input cells 2 through 7 to a file called MyCommands.py, you simply type

%save MyCommands.py 2-7

Which will save the file in your current working directory.  It'll even warn you and ask for confirmation if the file already exists.

For more information, use jupyter's extremely useful built-in help functionality by adding a question mark after the item you want help with.

%save?

Which prints the docstring

Docstring: Save a set of lines or a macro to a given filename.

Usage:   %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...

Options:

-r: use 'raw' input.  By default, the 'processed' history is used,

  so that magics are loaded in their transformed version to valid

  Python.  If this option is given, the raw input as typed as the

  command line is used instead.
       -f: force overwrite.  If file exists, %save will prompt for overwrite   unless -f is given.

-a: append to the file instead of overwriting it.

This function uses the same syntax as %history for input ranges, then
  saves the lines to the filename you specify.

It adds a '.py' extension to the file if you don't do so yourself, and
  it asks for confirmation before overwriting existing files.

If -r option is used, the default extension is .ipy. File:

  ~/anaconda3/lib/python3.5/site-packages/IPython/core/magics/code.py

Note that you can use the question mark to investigate any function or object with a docstring (i.e. enumerate?, range?).


问:
Error trying to store new object from related model on form submit Laravel
guys I have this error y trying to fixing with no luck: (this is the error
Call to undefined method Illuminate\Database\Query\Builder::encuesta()

just failing on insertion of Integrante,
Image works properly no errors

this is my relation on integrante model

```<code>public function integrantes()
{
    return $this->belongsTo(Encuesta::class);
}
</code>```

this is image relation on image model

```<code>public function encuesta()
    {
        return $this->belongsTo(Encuesta::class);
    }
</code>```

this is my relation on encuestas model

```<code>public function integrantes()
{
  return $this->hasMany(Integrante::class, 'encuesta_id');
}
</code>```

and this this my function action on my controller

```<code>public function store(EncuestaRequest $request){

    // Image Upload
    $file = $request->file('image');
    $file_count = count($file);
    $fileupload = 0;
    $name = 'imagen_' . time() . '.' . $file->getClientOriginalExtension();
    $path = public_path() . '/uploads';
    $file->move($path, $name);

    $encuestas = new Encuesta($request->all());
    $encuestas->save();
    // Saving Integrante
    $integrantes = new Integrante();
    $integrantes->nombres = $request->nombres;
    $integrantes->curp = $request->curp;
    $integrantes->parentesco = $request->parentesco;
    $integrantes->fecha_nacimiento = $request->fecha_nacimiento;
    $integrantes->genero = $request->genero;
    $integrantes->estado_nacimiento = $request->estado_nacimiento;
    $integrantes->encuesta()->associate($encuestas);
    $integrantes->save();

    // Saving Image
    $image = new Image();
    $image->name = $name;
    $image->encuesta()->associate($encuestas);
    $image->save();

    return redirect('encuesta');
}
</code>```

答:
Change your Integrante model like this,

From:

```<code>public function integrantes()
{
    return $this->belongsTo(Encuesta::class);
}
</code>```

To:

```<code>public function encuesta()
{
    return $this->belongsTo(Encuesta::class);
}
</code>```

In the below line, you're trying to call encuesta() method from Integrante model, but you used a wrong function name(integrantes()) in the model. So, thats why you are getting undefined method error.

```<code>$integrantes->encuesta()->associate($encuestas);
</code>```

Body:
guys I have this error y trying to fixing with no luck: (this is the error
Call to undefined method Illuminate\Database\Query\Builder::encuesta()

just failing on insertion of Integrante,
Image works properly no errors

this is my relation on integrante model

public function integrantes()
{
    return $this->belongsTo(Encuesta::class);
}

this is image relation on image model

public function encuesta()
    {
        return $this->belongsTo(Encuesta::class);
    }

this is my relation on encuestas model

public function integrantes()
{
  return $this->hasMany(Integrante::class, 'encuesta_id');
}

and this this my function action on my controller

public function store(EncuestaRequest $request){

    // Image Upload
    $file = $request->file('image');
    $file_count = count($file);
    $fileupload = 0;
    $name = 'imagen_' . time() . '.' . $file->getClientOriginalExtension();
    $path = public_path() . '/uploads';
    $file->move($path, $name);

    $encuestas = new Encuesta($request->all());
    $encuestas->save();
    // Saving Integrante
    $integrantes = new Integrante();
    $integrantes->nombres = $request->nombres;
    $integrantes->curp = $request->curp;
    $integrantes->parentesco = $request->parentesco;
    $integrantes->fecha_nacimiento = $request->fecha_nacimiento;
    $integrantes->genero = $request->genero;
    $integrantes->estado_nacimiento = $request->estado_nacimiento;
    $integrantes->encuesta()->associate($encuestas);
    $integrantes->save();

    // Saving Image
    $image = new Image();
    $image->name = $name;
    $image->encuesta()->associate($encuestas);
    $image->save();

    return redirect('encuesta');
}

Body:
Change your Integrante model like this,

From:

public function integrantes()
{
    return $this->belongsTo(Encuesta::class);
}

To:

public function encuesta()
{
    return $this->belongsTo(Encuesta::class);
}

In the below line, you're trying to call encuesta() method from Integrante model, but you used a wrong function name(integrantes()) in the model. So, thats why you are getting undefined method error.

$integrantes->encuesta()->associate($encuestas);


问:
vSphere Web Client Object properties
In vSphere web client extension development , i want to fetch the properties of VM , In the sample code model they are adding some annotations like

```<code>[Model(property="name")]
    /**
     * The name of this VirtualMachine.
     */
    public var name:String;
</code>```

Where can i get the List of available properties for all objects (like vm  , datastore , hosts)

答: The properties correspond to the properties of Managed and Data Objects as described in the vSphere Managment SDK documentation. In particular the example you gave corresponds to Managed Object VirtualMachine's name property. Since VirtualMachine inherits from ManagedEntity, this is where the name property is actually defined (see http://pubs.vmware.com/vsphere-51/index.jsp?topic=%2Fcom.vmware.wssdk.apiref.doc%2Fvim.ManagedEntity.html for details). You can also use property.paths.into.data.objects to access properties of nested data objects.

Title: vSphere Web Client Object properties

Body:
In vSphere web client extension development , i want to fetch the properties of VM , In the sample code model they are adding some annotations like

[Model(property="name")]
    /**
     * The name of this VirtualMachine.
     */
    public var name:String;

Where can i get the List of available properties for all objects (like vm  , datastore , hosts)


问:
ImageView increases slightly in size when moving RelativeLayout (Android)
I've got an annoying problem where when i move my RelativeLayout, the ImageView in it increases in size to fill the full screen in width. I've replaced the image with a colored background so it's easier to see.

Don't mind the way it looks, the layout is a W.I.P

GIF here to show the problem: https://gyazo.com/ae31b8e70e4f96fe89ba041549db22bb

Below is the code for my OnTouchListener

```<code>private View.OnTouchListener relativeListener = new View.OnTouchListener()
{
    @Override
    public boolean onTouch(View view, MotionEvent event)
    {
        final int X = (int) event.getRawX();
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                LinearLayout.LayoutParams lParams = (LinearLayout.LayoutParams) view.getLayoutParams();
                _xDelta = X - lParams.leftMargin;
                break;
            case MotionEvent.ACTION_UP:
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                break;
            case MotionEvent.ACTION_POINTER_UP:
                break;
            case MotionEvent.ACTION_MOVE:
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams();
                layoutParams.leftMargin = (X - _xDelta);
                layoutParams.rightMargin = -(X - _xDelta);
                view.setLayoutParams(layoutParams);
                break;
        }
        _root.invalidate();
        return true;
    }
};
</code>```

Below is the xml that defines the ImageView and RelativeLayout

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="me.tech.myapp.Fragments.HomeFragment">
<TextView
    android:id="@+id/tvCurrentTheme"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_margin="16dp"
    android:text="StringCurrentTheme"
    android:textAlignment="center"
    android:textSize="18sp" />

<RelativeLayout
    android:id="@+id/relativeRoot"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp">

    <ImageView
        android:id="@+id/ivMainImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:contentDescription="Foto jonguh"
        android:cropToPadding="false"
        android:scaleType="centerCrop"
        app:srcCompat="@android:color/holo_blue_bright" />

    <Button
        android:id="@+id/btnReportImage"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_alignTop="@+id/ivMainImage"
        android:layout_margin="16dp"
        android:background="@drawable/ic_menu_send"
        android:visibility="visible" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fabSendImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/btnReportImage"
        android:layout_alignParentBottom="true"
        android:layout_marginEnd="17dp"
        android:clickable="true"
        app:backgroundTint="@android:color/holo_orange_dark"
        app:elevation="4dp"
        app:fabSize="normal"
        app:srcCompat="@drawable/ic_menu_camera" />

</RelativeLayout>
</LinearLayout>
</code>```

答:
It is normal that the ImageView to occupy the entire layout if you have

```<code><ImageView
        android:id="@+id/ivMainImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
....
</code>```

try wrap_content instead match_parent

Body:
I've got an annoying problem where when i move my RelativeLayout, the ImageView in it increases in size to fill the full screen in width. I've replaced the image with a colored background so it's easier to see.

Don't mind the way it looks, the layout is a W.I.P

GIF here to show the problem: https://gyazo.com/ae31b8e70e4f96fe89ba041549db22bb

Below is the code for my OnTouchListener

private View.OnTouchListener relativeListener = new View.OnTouchListener()
{
    @Override
    public boolean onTouch(View view, MotionEvent event)
    {
        final int X = (int) event.getRawX();
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                LinearLayout.LayoutParams lParams = (LinearLayout.LayoutParams) view.getLayoutParams();
                _xDelta = X - lParams.leftMargin;
                break;
            case MotionEvent.ACTION_UP:
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                break;
            case MotionEvent.ACTION_POINTER_UP:
                break;
            case MotionEvent.ACTION_MOVE:
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams();
                layoutParams.leftMargin = (X - _xDelta);
                layoutParams.rightMargin = -(X - _xDelta);
                view.setLayoutParams(layoutParams);
                break;
        }
        _root.invalidate();
        return true;
    }
};

Below is the xml that defines the ImageView and RelativeLayout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="me.tech.myapp.Fragments.HomeFragment">
<TextView
    android:id="@+id/tvCurrentTheme"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_margin="16dp"
    android:text="StringCurrentTheme"
    android:textAlignment="center"
    android:textSize="18sp" />

<RelativeLayout
    android:id="@+id/relativeRoot"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp">

    <ImageView
        android:id="@+id/ivMainImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:contentDescription="Foto jonguh"
        android:cropToPadding="false"
        android:scaleType="centerCrop"
        app:srcCompat="@android:color/holo_blue_bright" />

    <Button
        android:id="@+id/btnReportImage"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_alignTop="@+id/ivMainImage"
        android:layout_margin="16dp"
        android:background="@drawable/ic_menu_send"
        android:visibility="visible" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fabSendImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/btnReportImage"
        android:layout_alignParentBottom="true"
        android:layout_marginEnd="17dp"
        android:clickable="true"
        app:backgroundTint="@android:color/holo_orange_dark"
        app:elevation="4dp"
        app:fabSize="normal"
        app:srcCompat="@drawable/ic_menu_camera" />

</RelativeLayout>
</LinearLayout>

Body:
It is normal that the ImageView to occupy the entire layout if you have

<ImageView
        android:id="@+id/ivMainImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
....

try wrap_content instead match_parent


问:
Service layer in Java or Only Repository
If i have Spring data repository which includes save, delete and modify operations. Should I create the following methods operations in service layer? And adding annotation @Transactional?
Or leave them as is? Or should I have them in repository layer?

Example service

```<code>@Service
public class RepositoryOperations{

@Autowired
ProductRepository productRepository;

@Transactional
public void saveProduct(){
    productRepository.save();
    }

...

}
</code>```

答:
We keep three layers generally.

The controller which defines API endpoints and calls appropriate service to process the request.

The service layer contains business logic and is meant to do heavy processing as we call it. If service layer needs to save or retrieve data from the database, it will use the dao layer to achieve this.

Dao layer's only role is to save or retrieve data from the database and provide it back to the service layer. It should not contain any business logic.

Annotate your dao layer with annotation @Repository

Annotate your service layer with annotation @Service

Annotate your controllers with annotation @Controller or @RestController(in case you have REST APIs)

@Transactional annotation is used when you want a code to be rolled back if it fails. If your service places three dao calls for three different operations and you want all or none of those three operations to be performed, annotate your service method with @Transactional

Same applies for dao methods.

So you have now fair amount of information to decide upon.

Body:
If i have Spring data repository which includes save, delete and modify operations. Should I create the following methods operations in service layer? And adding annotation @Transactional?
Or leave them as is? Or should I have them in repository layer?

Example service

@Service
public class RepositoryOperations{

@Autowired
ProductRepository productRepository;

@Transactional
public void saveProduct(){
    productRepository.save();
    }

...

}


问:
Add Access-Control-Allow-Origin: * easily to JSON
On my web server I have a folder (say the link is: www.foo.com/json/).

Inside this link, I have a json file, like foo.json. I want to access this file from another website. I've tried to research "CORS" but it seems pretty complicated, and I don't use any backend in on my website foo.com. I've heard you can simply use php and put this in:

```<code><?php
header("Access-Control-Allow-Origin: *");
</code>```

How do I add this to that folder that has the .json so that when I do:

```<code>$.getJSON("http://foo.com/json/foo.json", function(json) {
    console.log(json
)});
</code>```

It won't throw the error. I want this to be simple to let any website do it, I just don't know how to connect it all.

答:
Option 1: Use PHP

You can't add it to the .json file. You would need to create a php file which returns the JSON data. A crude example might be:

/json/index.php?f=foo

```<code>header("Access-Control-Allow-Origin: *");
header("content-type: application/json");
echo file_get_contents($_REQUEST['f'].".json");
</code>```

This will allow you to set the Access-Control-Allow-Origin header and return the desired json file content to your remote call:

```<code>$.getJSON("http://foo.com/json/index.php?f=foo", function(json) {
    console.log(json);
});
</code>```

Option 2: Use Server Configuration

Another option would be to configure the header to apply to json files in your server config. Using Apache2 you could add the following to your server config or create a .htaccess file in the /json directory to include:

```<code><Files "*.json">
  Header set Access-Control-Allow-Origin "*"
</Files>
</code>```

This would include the header for all the json files automatically.

Body:
On my web server I have a folder (say the link is: www.foo.com/json/).

Inside this link, I have a json file, like foo.json. I want to access this file from another website. I've tried to research "CORS" but it seems pretty complicated, and I don't use any backend in on my website foo.com. I've heard you can simply use php and put this in:

<?php
header("Access-Control-Allow-Origin: *");

How do I add this to that folder that has the .json so that when I do:

$.getJSON("http://foo.com/json/foo.json", function(json) {
    console.log(json
)});

It won't throw the error. I want this to be simple to let any website do it, I just don't know how to connect it all.

Body:
Option 1: Use PHP

You can't add it to the .json file. You would need to create a php file which returns the JSON data. A crude example might be:

/json/index.php?f=foo

header("Access-Control-Allow-Origin: *");
header("content-type: application/json");
echo file_get_contents($_REQUEST['f'].".json");

This will allow you to set the Access-Control-Allow-Origin header and return the desired json file content to your remote call:

$.getJSON("http://foo.com/json/index.php?f=foo", function(json) {
    console.log(json);
});

Option 2: Use Server Configuration

Another option would be to configure the header to apply to json files in your server config. Using Apache2 you could add the following to your server config or create a .htaccess file in the /json directory to include:

<Files "*.json">
  Header set Access-Control-Allow-Origin "*"
</Files>

This would include the header for all the json files automatically.


问:
ObjectDataSource direct binding
I have 2 SQL tables with a single relationship.
Table A: Id, ApplicationID, Message.
Table B: Id, ApplicationName.
Relationship: A.ApplicationID = B.Id

I want to use a objectdatasource to bind them directly to a gridview but i want to show ApplicationName instead of ApplicationID.

How can i do that?

Thank U ALL.

答:
What sort of data access are you using? Ado.net? Linq2Sql? Entity Framework?

A sample would require data access which would query both tables and provide the data for the selectMethod of the object datasource.

Title: ObjectDataSource direct binding


问:
How do i get refs value from dynamically generated array in React
I got my data from firebase, looped through it and displayed it on the frontend. Now I am trying to get the refs value of the already displayed value when I click on it. For example, when I click on Dino, i should be able to see the value 'Dino' on my console tab of Chrome browser.

Here is a link to the picture of the array list displayed on react frontend

```<code><ul>
    <li onClick={this.handleSubmit}>
        {
            Object.keys(this.props.group).map(function(keyName, keyIndex) {
                return(
                    <div key={keyIndex}>{keyName}</div>
                )
            })
        }
    </li>
</ul>
</code>```

答:
Assuming that those "dino, magic & muu" are the keys in this.props.group you need to add an onClick handler to that div, so:

```<code><div key={keyIndex} onClick={() => console.log(keyName)}>{keyName}</div>
</code>```

Body:
I got my data from firebase, looped through it and displayed it on the frontend. Now I am trying to get the refs value of the already displayed value when I click on it. For example, when I click on Dino, i should be able to see the value 'Dino' on my console tab of Chrome browser.

Here is a link to the picture of the array list displayed on react frontend

        {
            Object.keys(this.props.group).map(function(keyName, keyIndex) {
                return(

{keyName}

                )
            })
        }

Body:
Assuming that those "dino, magic & muu" are the keys in this.props.group you need to add an onClick handler to that div, so:

<div key={keyIndex} onClick={() => console.log(keyName)}>{keyName}</div>


问:
c++ rest sdk https server implemention (Windows)
I have dabbled with the c++ rest sdk for a while now and got around making a server and client fully.

The problem is that http requests from the client to the server seem to always be plaintext so when i want to try logging in,

the URI is http://... login?email=anemail@gmail.com&password=123456
I am new to network programming but this doesn't seem very secure and from what i understand https is the way to go... so far no info though as to how to setup a http over SSL server with casablanca c++ rest sdk.

Has anyone here tried to do this? maybe i need an additional library for this specifically?

答:
This is what I see in the http_listener code. It doesn't appear to support Windows at all.</p>

```<code>#ifndef _WIN32
    /// <summary>
    /// Get the callback of ssl context
    /// </summary>
    /// <returns>The function defined by the user of http_listener_config to configure a ssl context.</returns>
    const std::function<void(boost::asio::ssl::context&)>& get_ssl_context_callback() const
    {
        return m_ssl_context_callback;
    }

    /// <summary>
    /// Set the callback of ssl context
    /// </summary>
    /// <param name="ssl_context_callback">The function to configure a ssl context which will setup https connections.</param>
    void set_ssl_context_callback(const std::function<void(boost::asio::ssl::context&)> &ssl_context_callback)
    {
        m_ssl_context_callback = ssl_context_callback;
    }
#endif
</code>```

Body:
This is what I see in the http_listener code. It doesn't appear to support Windows at all.

#ifndef _WIN32
    /// <summary>
    /// Get the callback of ssl context
    /// </summary>
    /// <returns>The function defined by the user of http_listener_config to configure a ssl context.</returns>
    const std::function<void(boost::asio::ssl::context&)>& get_ssl_context_callback() const
    {
        return m_ssl_context_callback;
    }

    /// <summary>
    /// Set the callback of ssl context
    /// </summary>
    /// <param name="ssl_context_callback">The function to configure a ssl context which will setup https connections.</param>
    void set_ssl_context_callback(const std::function<void(boost::asio::ssl::context&)> &ssl_context_callback)
    {
        m_ssl_context_callback = ssl_context_callback;
    }
#endif


问:
Subsequent HTML not being displayed after PHP call
I am relatively new to PHP programming. I am building a small crud app (to-do list) to be exact for practice. I am working on fleshing out the UI and testing how information displays from my database on the page.

When a user logs in, they are shown a table of all the items they have saved.

table listing items

```<code>  <div class="container">
    <table class="table">
      <tr>
        <th>Completed</th>
        <th>Description</th>
        <th>Actions</th>
      </tr>
      <tr>
        <td colspan="3"></td>
      </tr>
      <?php
      $document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
      while($match_value = mysql_fetch_array($document_get)) {
      ?>
      <tr>
        <td>
          Hi
        </td>
      </tr>
    </table>
    <?php
    }
    ?>
  </div>
</code>```

php call to display list item

```<code>      <?php
      $document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
      while($match_value = mysql_fetch_array($document_get)) {
      ?>
</code>```

Anything under this PHP request does not show up for some reason. I have looked at other posts where people have mentioned the same thing but I did not see anything specific that matched my issue per say.

答:
Try to alter your query from:

```<code>$document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
</code>```

to

```<code>$document_get = mysql_query("SELECT * FROM todolist WHERE user_id='".$user_id."' ORDER BY id DESC");
</code>```

Body:
I am relatively new to PHP programming. I am building a small crud app (to-do list) to be exact for practice. I am working on fleshing out the UI and testing how information displays from my database on the page.

When a user logs in, they are shown a table of all the items they have saved.

table listing items

        Completed
        Description
        Actions

      <?php
      $document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
      while($match_value = mysql_fetch_array($document_get)) {
      ?>

          Hi

    <?php
    }
    ?>

php call to display list item

      <?php
      $document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
      while($match_value = mysql_fetch_array($document_get)) {
      ?>

Anything under this PHP request does not show up for some reason. I have looked at other posts where people have mentioned the same thing but I did not see anything specific that matched my issue per say.

Body:
Try to alter your query from:

$document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");

to

$document_get = mysql_query("SELECT * FROM todolist WHERE user_id='".$user_id."' ORDER BY id DESC");