问:
Align a piechart in plot area
I'm generating a pie chart that I would like to incorporate into a Shiny page. The plot area (i.e.: the white space surrounding the plot) will be fluid. I'd like the plot itself (the grey area and the pie chart) to align to the left-hand side of the plot area, instead of appearing centered. Any ideas?

```<code>ggplot(treeData, aes(x = "", fill = ClassName)) +
  ggtitle("Species distribution") +
  geom_bar(width = 1) +
  coord_polar("y", start=0) +
  xlab("") + ylab("") +
  theme(
    axis.text.x=element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    panel.grid  = element_blank(),
    plot.margin=unit(c(25,0,0,0), "pt")) +
  scale_fill_manual(values= c("#ffff00", "#008080", "#00ff00"))
</code>```

答:
The more detailed explanation for why this answer works is provided here. In brief, you need to place the plot into a grid that can expand as you resize the enclosing image.

```<code>library(ggplot2)
library(grid)
library(gtable)

# some test data
animals <- as.data.frame(
  table(Species =
          c(rep("Moose", sample(1:100, 1)),
            rep("Frog", sample(1:100, 1)),
            rep("Dragonfly", sample(1:100, 1))
          )))

# make the pie chart
g <- ggplot(animals, aes(x = "", y = Freq, fill = Species)) +
  geom_bar(width = 1, stat = "identity") +
  coord_polar("y", start=0) +
  theme(
    axis.text.x=element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    panel.grid = element_blank(),
    plot.margin=unit(c(25,0,0,0), "pt"))

# set the desired width and height of the
# pie chart (need to play around to find
# numbers that work
plotwidth = unit(6.1, "inch")
plotheight = unit(5, "inch")

# place into matrix that can expand
grob <- ggplotGrob(g)
mat <- matrix(list(grob, nullGrob(), nullGrob(), nullGrob()), nrow = 2)
widths <- unit(c(1, 1), "null")
widths[1] <- plotwidth
heights <- unit(c(1, 1), "null")
heights[1] <- plotheight
gm <- gtable_matrix(NULL, mat, widths, heights)
grid.newpage()
grid.draw(gm)
</code>```

Title: Align a piechart in plot area

Body:
I'm generating a pie chart that I would like to incorporate into a Shiny page. The plot area (i.e.: the white space surrounding the plot) will be fluid. I'd like the plot itself (the grey area and the pie chart) to align to the left-hand side of the plot area, instead of appearing centered. Any ideas?

ggplot(treeData, aes(x = "", fill = ClassName)) +
  ggtitle("Species distribution") +
  geom_bar(width = 1) +
  coord_polar("y", start=0) +
  xlab("") + ylab("") +
  theme(
    axis.text.x=element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    panel.grid  = element_blank(),
    plot.margin=unit(c(25,0,0,0), "pt")) +
  scale_fill_manual(values= c("#ffff00", "#008080", "#00ff00"))

Body:
The more detailed explanation for why this answer works is provided here. In brief, you need to place the plot into a grid that can expand as you resize the enclosing image.

library(ggplot2)
library(grid)
library(gtable)

# some test data
animals <- as.data.frame(
  table(Species =
          c(rep("Moose", sample(1:100, 1)),
            rep("Frog", sample(1:100, 1)),
            rep("Dragonfly", sample(1:100, 1))
          )))

# make the pie chart
g <- ggplot(animals, aes(x = "", y = Freq, fill = Species)) +
  geom_bar(width = 1, stat = "identity") +
  coord_polar("y", start=0) +
  theme(
    axis.text.x=element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    panel.grid = element_blank(),
    plot.margin=unit(c(25,0,0,0), "pt"))

# set the desired width and height of the
# pie chart (need to play around to find
# numbers that work
plotwidth = unit(6.1, "inch")
plotheight = unit(5, "inch")

# place into matrix that can expand
grob <- ggplotGrob(g)
mat <- matrix(list(grob, nullGrob(), nullGrob(), nullGrob()), nrow = 2)
widths <- unit(c(1, 1), "null")
widths[1] <- plotwidth
heights <- unit(c(1, 1), "null")
heights[1] <- plotheight
gm <- gtable_matrix(NULL, mat, widths, heights)
grid.newpage()
grid.draw(gm)


来源: stackexchange

问:
Adding missing rows to a data frame, filling in data from last known data point
I have a data frame that has missing rows. You can identify the missing rows by looking at the gaps in the sequence.

```<code>Count<-c(1,1,1,1,2,2,2,3,3,4,4,4,4,5,5,6,6,6)
Seq<-c(1,2,3,4,1,2,4,1,4,1,2,3,5,1,3,1,2,3)
MyData<-c(5,4,5,3,4,3,2,1,2,1,3,2,4,2,3,1,4,3)
DF1<-data.frame(Count,Seq,MyData)
DF1
</code>```

The count keeps track of the sequence number, and the sequences will always run as a numeric sequence. In this case it is 1:5, but this can vary so I don't want to hard code this limitation.

My goal is to create two new data frame that contains all of the missing sequence rows. The first would have NA in the data column for the added "missing' rows.

```<code>Count2<-c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5,6,6,6,6,6)
Seq2<-c(1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
MyData2<-c(5,4,5,3,NA,4,3,NA,2,NA,1,NA,NA,2,NA,1,3,2,NA,4,2,NA,3,NA,NA,1,4,3,NA,NA)
DF2<-data.frame(Count2,Seq2,MyData2)
DF2
</code>```

The second data frame would be similar, but would contain the last known data point for that Sequence number.

```<code>Count2<-c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5,6,6,6,6,6)
Seq2<-c(1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
MyData3<-c(5,4,5,3,NA,4,3,5,2,NA,1,3,5,2,NA,1,3,2,2,4,2,3,3,2,4,1,4,3,2,4)
DF3<-data.frame(Count2,Seq2,MyData3)
DF3
</code>```

Note- the NA remains for the 5th element in the sequence for this first 3 counts as there was no initial value.

答:
Here is a solution using

base R's merge on a "skeleton" dataframe for the first question, and

zoo::na.locf to replace NAs with last known values for the second question.

As per OP's request, the maximum Seq and Count values are inferred from the data.

```<code># These are the maximum seq and count numbers from the data
maxSeq <- max(DF1$Seq);
maxCts <- max(DF1$Count);

# Replicating DF1
# Construct "skeleton" dataframe with appropriate Seq and Count sequences
df.one <- data.frame(
    Count = rep(seq(1:maxCts), each = maxSeq),
    Seq = rep(seq(1:maxSeq), maxCts)
);
# Merge with source data, and put NAs for missing entries
df.one <- merge(df.one, DF1, all = TRUE);
tail(df.one)
#   Count Seq MyData
#25     5   5     NA
#26     6   1      1
#27     6   2      4
#28     6   3      3
#29     6   4     NA
#30     6   5     NA

# Replicating DF2
# Split on Seq, replace NAs in MyData with last known value,
# and rbind into dataframe
df.two <- do.call(rbind.data.frame, lapply(split(df.two, df$Seq), function(x)  {
    x$MyData <- na.locf(x$MyData);
    return(x);
}))
# Sort by Count then Seq
df.two <- df.two[order(df.two$Count, df.two$Seq), ];
rownames(df.two) <- NULL;
tail(df.two);
#   Count Seq MyData
#25     5   5      3
#26     6   1      1
#27     6   2      4
#28     6   3      3
#29     6   4      3
#30     6   5      2
</code>```

Data

```<code>Count<-c(1,1,1,1,2,2,2,3,3,4,4,4,4,5,5,6,6,6)
Seq<-c(1,2,3,4,1,2,4,1,4,1,2,3,5,1,3,1,2,3)
MyData<-c(5,4,5,3,4,3,2,1,2,1,3,2,4,2,3,1,4,3)
DF1<-data.frame(Count,Seq,MyData)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a data frame that has missing rows. You can identify the missing rows by looking at the gaps in the sequence.

Count<-c(1,1,1,1,2,2,2,3,3,4,4,4,4,5,5,6,6,6)
Seq<-c(1,2,3,4,1,2,4,1,4,1,2,3,5,1,3,1,2,3)
MyData<-c(5,4,5,3,4,3,2,1,2,1,3,2,4,2,3,1,4,3)
DF1<-data.frame(Count,Seq,MyData)
DF1

The count keeps track of the sequence number, and the sequences will always run as a numeric sequence. In this case it is 1:5, but this can vary so I don't want to hard code this limitation.

My goal is to create two new data frame that contains all of the missing sequence rows. The first would have NA in the data column for the added "missing' rows.

Count2<-c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5,6,6,6,6,6)
Seq2<-c(1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
MyData2<-c(5,4,5,3,NA,4,3,NA,2,NA,1,NA,NA,2,NA,1,3,2,NA,4,2,NA,3,NA,NA,1,4,3,NA,NA)
DF2<-data.frame(Count2,Seq2,MyData2)
DF2

The second data frame would be similar, but would contain the last known data point for that Sequence number.

Count2<-c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5,6,6,6,6,6)
Seq2<-c(1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
MyData3<-c(5,4,5,3,NA,4,3,5,2,NA,1,3,5,2,NA,1,3,2,2,4,2,3,3,2,4,1,4,3,2,4)
DF3<-data.frame(Count2,Seq2,MyData3)
DF3

Note- the NA remains for the 5th element in the sequence for this first 3 counts as there was no initial value.

Body:
Here is a solution using

base R's merge on a "skeleton" dataframe for the first question, and

zoo::na.locf to replace NAs with last known values for the second question.

As per OP's request, the maximum Seq and Count values are inferred from the data.

# These are the maximum seq and count numbers from the data
maxSeq <- max(DF1$Seq);
maxCts <- max(DF1$Count);

# Replicating DF1
# Construct "skeleton" dataframe with appropriate Seq and Count sequences
df.one <- data.frame(
    Count = rep(seq(1:maxCts), each = maxSeq),
    Seq = rep(seq(1:maxSeq), maxCts)
);
# Merge with source data, and put NAs for missing entries
df.one <- merge(df.one, DF1, all = TRUE);
tail(df.one)
#   Count Seq MyData
#25     5   5     NA
#26     6   1      1
#27     6   2      4
#28     6   3      3
#29     6   4     NA
#30     6   5     NA

# Replicating DF2
# Split on Seq, replace NAs in MyData with last known value,
# and rbind into dataframe
df.two <- do.call(rbind.data.frame, lapply(split(df.two, df$Seq), function(x)  {
    x$MyData <- na.locf(x$MyData);
    return(x);
}))
# Sort by Count then Seq
df.two <- df.two[order(df.two$Count, df.two$Seq), ];
rownames(df.two) <- NULL;
tail(df.two);
#   Count Seq MyData
#25     5   5      3
#26     6   1      1
#27     6   2      4
#28     6   3      3
#29     6   4      3
#30     6   5      2

Data

Count<-c(1,1,1,1,2,2,2,3,3,4,4,4,4,5,5,6,6,6)
Seq<-c(1,2,3,4,1,2,4,1,4,1,2,3,5,1,3,1,2,3)
MyData<-c(5,4,5,3,4,3,2,1,2,1,3,2,4,2,3,1,4,3)
DF1<-data.frame(Count,Seq,MyData)


问:
ES6 Modules + Revealing Module Pattern
I'm just getting into using es 6 modules for front end development (we don't use Node at all), and am wondering if this pattern we've come up has any pitfalls or if you have any improvement suggestions. I guess it uses some of the rationale behind the revealing module pattern, in es6 modules. I ask this question because most es6 module "how to guides" I've seen do something different, which I'll note at the very bottom of the question.

Some things to note:

We (are pretty sure we) want each module to only export one thing. This is listed as a best practice in the Airbnb style guide, and we've just found it nice overall when consuming npm packages

We really like naming methods with "public" and "private" (guess we should be using _ for private methods as that's newer best-practice), it makes it easy to see what is available outside of the module

module.js:

```<code>// publicly available method
function publicHello() {
    return 'Hello';
};

// publicly available method
function publicHelloWorld(){
    const a = publicHello();
    const b = privateProcessWorld(a);
    return b;
};

// private method
function privateProcessWorld(x) {
    return x + ' world';
};

// create an object to export, containing only the public methods
// note that we rename them here as well, making them easier to consume
const exp = {
    h: publicHello,
    hw: publicHelloWorld,
};

// export the object as default so it can be used in an unnamed import
export default exp;
</code>```

to consume the module:

```<code>import whatever from "module.js";

whatever.h();   // "Hello"
whatever.hw();  // "Hello world"
</code>```

What I have seen in most "es6 module how to" guides is this:

```<code>var utils = {
  generateRandom: function() {
    return Math.random();
  },
  sum: function(a, b) {
    return a + b;
  }
};

export default utils;
</code>```

答:
We (are pretty sure we) want each module to only export one thing.

No. Don't do this. If your module provides multiple functionalities, like a bunch of helper functions, and does not provide a single function or single class or something, you should also export multiple things.

Just change your default export to

```<code>export {
  publicHello as h,
  publicHelloWorld as hw,
}
</code>```

and your import to

```<code>import * as whatever from "module.js";
</code>```

Title: ES6 Modules + Revealing Module Pattern

Body:
I'm just getting into using es 6 modules for front end development (we don't use Node at all), and am wondering if this pattern we've come up has any pitfalls or if you have any improvement suggestions. I guess it uses some of the rationale behind the revealing module pattern, in es6 modules. I ask this question because most es6 module "how to guides" I've seen do something different, which I'll note at the very bottom of the question.

Some things to note:

We (are pretty sure we) want each module to only export one thing. This is listed as a best practice in the Airbnb style guide, and we've just found it nice overall when consuming npm packages

We really like naming methods with "public" and "private" (guess we should be using _ for private methods as that's newer best-practice), it makes it easy to see what is available outside of the module

module.js:

// publicly available method
function publicHello() {
    return 'Hello';
};

// publicly available method
function publicHelloWorld(){
    const a = publicHello();
    const b = privateProcessWorld(a);
    return b;
};

// private method
function privateProcessWorld(x) {
    return x + ' world';
};

// create an object to export, containing only the public methods
// note that we rename them here as well, making them easier to consume
const exp = {
    h: publicHello,
    hw: publicHelloWorld,
};

// export the object as default so it can be used in an unnamed import
export default exp;

to consume the module:

import whatever from "module.js";

whatever.h();   // "Hello"
whatever.hw();  // "Hello world"

What I have seen in most "es6 module how to" guides is this:

var utils = {
  generateRandom: function() {
    return Math.random();
  },
  sum: function(a, b) {
    return a + b;
  }
};

export default utils;

Body:
We (are pretty sure we) want each module to only export one thing.

No. Don't do this. If your module provides multiple functionalities, like a bunch of helper functions, and does not provide a single function or single class or something, you should also export multiple things.

Just change your default export to

export {
  publicHello as h,
  publicHelloWorld as hw,
}

and your import to

import * as whatever from "module.js";


问:
Correct structure for a Django application and handling the views and sub views
I struggle a bit in order to understand how a Django Application should be properly structured. In particular, I struggle to get my head around the views.

So I have this file

```<code>base.html
</code>```

And I know that this file will have common elements of the whole application such as footer, navbar, head etc.

So far so good.
Inside my base.html file I will have the tag:

```<code>{% block content %}
{% endblock %}
</code>```

Which handles the dynamic content of the application.
Now I create a static page called home.html and inside that file I put

```<code>{% extends 'base.html' %}
... Whatever I want
{% block content %}
</code>```

And now comes the part that I really struggle to understand how it works.
I create a new app called dashboard. I create a dashboard.html file and similarly to home.html I extend the base, and but elements inside the content block. In the views.py of the generated application I define:

```<code>@login_required(login_url="login/")
def dashboard(request):
    return render(request, "dashboard.html")
</code>```

and the dashboard.html

```<code>{% extends 'base.html' %}
{% block content %}
    <div class="dashboard-page">
        <div class="row equal-sides">
            <div class="col-sm-2 trim-right">
                {% include 'dashboard_navigation.html' %}
            </div>
            <div class="col-sm-10 trim-left">
                <div class="dashboard-main card">
                   <h3>Welcome to your dashboard</h3>
                </div>
            </div>
        </div>
    </div>
{% endblock %}
</code>```

Happy days. Now I want to reload only the main container on the right-hand-side, depending on the selection from the navigation bar on the left-hand-side. How do I achieve that?

I thought that if I will add a new url inside my urls file and a corresponding view inside views.py file it will be all good.

```<code>def single_search(request):
    tweets = get_tweets()
    context = {'tweets': tweets}
    return render(request, "search.html", context)
</code>```

urls.py

```<code>url(r'^dashboard', views.dashboard, name='dashboard'),
url(r'^dashboard/search$', views.single_search, name='search'),
</code>```

However, what I get is the same page as the dashboard.html

I managed to go around the problem and display "proper" content with the following code:

```<code>{% extends 'base.html' %} {% block content %}
    <div class="dashboard-page">
        <div class="row equal-sides">
            <div class="col-sm-2 trim-right">
                {% include 'dashboard_navigation.html' %}
            </div>
            <div class="col-sm-10 trim-left">
                <div class="dashboard-main card">

                    {% if 'search' in request.path %}
                        {% include 'search.html' %}
                    {% else %}
                        <h3>Welcome to your dashboard</h3>
                    {% endif %}
                </div>
            </div>
        </div>
    </div> {% endblock %}
</code>```

But I know that it is not the proper way of doing it. I also know that the context that I am passing is not being returned due to the fact that it is inside the include 'search.html' tag. If I pass the same context inside the dashboard it works both in the search.html and dashboard.html unfortunately I only want to see that content in if the user is on the search.html subpage.

Additionally, I append the tree of my application:

答:
The problem is simply that you haven't terminated your dashboard URL pattern, so it matches both URLs. It should be:

```<code>url(r'^dashboard$', views.dashboard, name='dashboard'),
</code>```

If you find regexes confusing, the new path syntax in Django 2.0 might be easier.

ContentLicense: CC BY-SA 4.0

Body:
I struggle a bit in order to understand how a Django Application should be properly structured. In particular, I struggle to get my head around the views.

So I have this file

base.html

And I know that this file will have common elements of the whole application such as footer, navbar, head etc.

So far so good.
Inside my base.html file I will have the tag:

{% block content %}
{% endblock %}

Which handles the dynamic content of the application.
Now I create a static page called home.html and inside that file I put

{% extends 'base.html' %}
... Whatever I want
{% block content %}

And now comes the part that I really struggle to understand how it works.
I create a new app called dashboard. I create a dashboard.html file and similarly to home.html I extend the base, and but elements inside the content block. In the views.py of the generated application I define:

@login_required(login_url="login/")
def dashboard(request):
    return render(request, "dashboard.html")

and the dashboard.html

{% extends 'base.html' %}
{% block content %}

                {% include 'dashboard_navigation.html' %}

Welcome to your dashboard

{% endblock %}

Happy days. Now I want to reload only the main container on the right-hand-side, depending on the selection from the navigation bar on the left-hand-side. How do I achieve that?

I thought that if I will add a new url inside my urls file and a corresponding view inside views.py file it will be all good.

def single_search(request):
    tweets = get_tweets()
    context = {'tweets': tweets}
    return render(request, "search.html", context)

urls.py

url(r'^dashboard', views.dashboard, name='dashboard'),
url(r'^dashboard/search$', views.single_search, name='search'),

However, what I get is the same page as the dashboard.html

I managed to go around the problem and display "proper" content with the following code:

{% extends 'base.html' %} {% block content %}

                {% include 'dashboard_navigation.html' %}

                    {% if 'search' in request.path %}
                        {% include 'search.html' %}
                    {% else %}

Welcome to your dashboard

                    {% endif %}

 {% endblock %}

But I know that it is not the proper way of doing it. I also know that the context that I am passing is not being returned due to the fact that it is inside the include 'search.html' tag. If I pass the same context inside the dashboard it works both in the search.html and dashboard.html unfortunately I only want to see that content in if the user is on the search.html subpage.

Additionally, I append the tree of my application:

Body:
The problem is simply that you haven't terminated your dashboard URL pattern, so it matches both URLs. It should be:

url(r'^dashboard$', views.dashboard, name='dashboard'),

If you find regexes confusing, the new path syntax in Django 2.0 might be easier.


问:
I want to average the numbers inputted into the ArrayList, however it only calculates average as 0.0
It sums perfectly fine, however it averages the values as 0.0 no matter what numbers I input. How can I make it output the correct average value?</p>

```<code>import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class Calculation {
    static Toolkit tools = new Toolkit();
    public static void main(String [] args) {
        double average = 0.0;
        double sum = 0;
        int i =0;
        int num = 0;
        int nElements = 0;
        Scanner console = new Scanner(System.in);

        ArrayList<Integer> value = new ArrayList<Integer>();
        System.out.println("Enter value: ");
        num = console.nextInt();
        while(num != 0) {
            value.add(new Integer(num));
        }

        for(i = 0; i < value.size(); i++) {
             sum += value.size();
        }
        average = sum / value.size();
        System.out.println("Number of values read: " + value.size());
        System.out.println("Values sum: " + sum + "Values average: " +
                            average);
        System.exit(0);
    }
}
</code>```

答:
as is now, the loop will only end if you enter 0 the first time otherwise it will lead to an infinite loop. rather, you'll need to read the next integer within the loop as such:

```<code>while(num != 0) {
    value.add(new Integer(num));
    num = console.nextInt();  // add this line
}
</code>```

Also, change this:

```<code>sum += value.size();
</code>```

to this:

```<code>sum += value.get(i);
</code>```

as you'll want to reduce the numbers inside the ArrayList into a single value rather than performing the summation of the ArrayList's size on each iteration.

Body:
It sums perfectly fine, however it averages the values as 0.0 no matter what numbers I input. How can I make it output the correct average value?

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class Calculation {
    static Toolkit tools = new Toolkit();
    public static void main(String [] args) {
        double average = 0.0;
        double sum = 0;
        int i =0;
        int num = 0;
        int nElements = 0;
        Scanner console = new Scanner(System.in);

        ArrayList<Integer> value = new ArrayList<Integer>();
        System.out.println("Enter value: ");
        num = console.nextInt();
        while(num != 0) {
            value.add(new Integer(num));
        }

        for(i = 0; i < value.size(); i++) {
             sum += value.size();
        }
        average = sum / value.size();
        System.out.println("Number of values read: " + value.size());
        System.out.println("Values sum: " + sum + "Values average: " +
                            average);
        System.exit(0);
    }
}

Body:
as is now, the loop will only end if you enter 0 the first time otherwise it will lead to an infinite loop. rather, you'll need to read the next integer within the loop as such:

while(num != 0) {
    value.add(new Integer(num));
    num = console.nextInt();  // add this line
}

Also, change this:

sum += value.size();

to this:

sum += value.get(i);

as you'll want to reduce the numbers inside the ArrayList into a single value rather than performing the summation of the ArrayList's size on each iteration.


问:
Model in header doesn't appear in views that use the header
Model defined in the header of my pages appears on page load and refresh on the main page, but when I navigate to another view the model doesn't appear there. The rest of the header is there, just the dynamic data that isn't.

Where am I going wrong? New to both Python and Django, so if anyone can help, please don't be afraid to patronize and Eli5 :)

Model defined in models.py:

```<code>from django.db import models
from django.utils import timezone

# Create your models here.
class Propaganda(models.Model):
    slogan = models.CharField(max_length=140, blank=True, null=True)

    def __str__(self):
        return self.slogan
</code>```

header.html

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <title>Christopher's weblog</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Blog site.">

        <!-- Let's get the static files where we use them, but this could be before the html tag -->
        {% load staticfiles %}
        <link rel="stylesheet" href="{% static 'blog/css/bulma.css' %}" type="text/css"/>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
        <!-- <link rel="stylesheet" href="{% static 'blog/css/cupar.css' %}" type="text/css" /> -->
    </head>
    <body>

        <section class="hero is-success is-bold">
            <div class="hero-body">
                <div class="container">
                    {% block slogan %}
                        {% for propaganda in propagandas %}
                            <h6>{{ propaganda.slogan }} it's</h6>
                        {% endfor %}
                    {% endblock %}
                    <h1 class="title" style="display: inline-block;">
                        <span class="icon">
                            <i class="fa fa-home"></i>
                            </span>
                        <a href="{% url 'post_list' %}">The Guide</a>
                    </h1>

                    {% if user.is_authenticated %}
                    <div class="field">
                        <div class="control">
                            <a href="{% url 'post_new' %}" class="button is-warning is-pulled-right">
                                <span class="icon">
                                    <i class="fa fa-plus-square"></i>
                                </span>
                                <span>New post</span>
                            </a>
                        </div>
                    </div>
                    {% endif %}

                </div><!-- @container -->
            </div>
        </section>
        <!-- content under header in here-> -->
        {% block content %}
        {% endblock %}
    </body>
</html>
</code>```

views.py

```<code>from django.template import RequestContext
from django.shortcuts import render, get_object_or_404, redirect
from .models import Post, Propaganda
from .forms import PostForm
from django.utils import timezone

# Create your views here.
def post_list(request):
    posts = Post.objects.all()
    propagandas = Propaganda.objects.all().order_by('?')[:1]
    return render(request, 'blog/post_list.html', {'posts': posts, 'propagandas': propagandas})
</code>```

post_detail.html (where the model does not appear):

```<code>{% extends 'blog/header.html' %}

{% block content  %}
some html / form that has nothing to do with the header.
{% endblock %}
</code>```

post_list.html (the 'index' page where the model works fine)

```<code>{% extends "blog/header.html" %}

{% block content %}

    {% for post in posts %}
        <section class="section">
        more html
{% endblock %}
</code>```

答:
need to pass the data from each view function that is required in the header you are extending (re-using) in each template.

```<code>def post_detil(request, id):
    posts = Post.objects.all()
    propagandas = Propaganda.objects.all().order_by('?')[:1]

    # ... add in other stuff relevant to post details ...
    post = Post.objects.get(pk=id)

    return render(request, 'blog/post_detail.html', {'posts': posts, 'propagandas': propagandas, 'post': post})
</code>```

Stick with it @Rin and Len, you'll get there :)

Body:
Model defined in the header of my pages appears on page load and refresh on the main page, but when I navigate to another view the model doesn't appear there. The rest of the header is there, just the dynamic data that isn't.

Where am I going wrong? New to both Python and Django, so if anyone can help, please don't be afraid to patronize and Eli5 :)

Model defined in models.py:

from django.db import models
from django.utils import timezone

# Create your models here.
class Propaganda(models.Model):
    slogan = models.CharField(max_length=140, blank=True, null=True)

    def __str__(self):
        return self.slogan

header.html

<!DOCTYPE html>

        <title>Christopher's weblog</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Blog site.">

        {% load staticfiles %}
        <link rel="stylesheet" href="{% static 'blog/css/bulma.css' %}" type="text/css"/>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

                    {% block slogan %}
                        {% for propaganda in propagandas %}

{{ propaganda.slogan }} it's

                        {% endfor %}
                    {% endblock %}

                        The Guide

                    {% if user.is_authenticated %}

                                New post

                    {% endif %}

        {% block content %}
        {% endblock %}

views.py

from django.template import RequestContext
from django.shortcuts import render, get_object_or_404, redirect
from .models import Post, Propaganda
from .forms import PostForm
from django.utils import timezone

# Create your views here.
def post_list(request):
    posts = Post.objects.all()
    propagandas = Propaganda.objects.all().order_by('?')[:1]
    return render(request, 'blog/post_list.html', {'posts': posts, 'propagandas': propagandas})

post_detail.html (where the model does not appear):

{% extends 'blog/header.html' %}

{% block content  %}
some html / form that has nothing to do with the header.
{% endblock %}

post_list.html (the 'index' page where the model works fine)

{% extends "blog/header.html" %}

{% block content %}

    {% for post in posts %}

        more html
{% endblock %}

Body:
need to pass the data from each view function that is required in the header you are extending (re-using) in each template.

def post_detil(request, id):
    posts = Post.objects.all()
    propagandas = Propaganda.objects.all().order_by('?')[:1]

    # ... add in other stuff relevant to post details ...
    post = Post.objects.get(pk=id)

    return render(request, 'blog/post_detail.html', {'posts': posts, 'propagandas': propagandas, 'post': post})

Stick with it @Rin and Len, you'll get there :)


问:
Trying to assign groups in R, but it is filling in NA values and missing others that belong in the group
So I have a dataset in R (Framingham Heart Study data), and I am trying to assign BMI groups "underweight," "normal," "overweight," and "obese."

It has over 11,000 observations and 38 variables/columns, so it would be kind of hard to post some of the data here (I hope this won't be too much trouble to answer without it).

The dataset is called frm and I am trying to subset in the following way:

```<code>frm$BMIGRP <- NA  #Creating new variable (this part works and creates a BMIGRP column with all NA values)
frm$BMIGRP[which(as.numeric(frm$BMI) < 18.5)] <- "underweight"
</code>```

However, there are NA values in the data set BMI variable (indicated with a ".", which I have also tried changing to NA).

When I try to subset this way for each group, it is assigning only some of the underweight values to "underweight" and is assigning a lot of NA / "." values to underweight as well. It then tells me there are only 10 "normal" weight subjects and about 11000 in the obese category which is just not true because I can view the data set.

If done correctly, this should create the four groups with several hundred to several thousand observations in each category. But I am only getting 10 normal, 71 underweight, and ~11,000 obese.

I'm just not sure where I'm going wrong with this or if there is a different way I can create a new variable and assign it in the same kind of way. Any help is very much appreciated.

I should also mention that this is the code that my professor gave us as an example in our lab session, and I am basically copying and pasting it with the appropriate replacements for my data set.

This is my first question on this website so I apologize if it is incomplete or if I need to give more information. Thanks!

答:
Like @leeum said. Check that BMI is numeric. If you want to make a new category column based on the BMI, look at case_when from dplyr. So maybe this is what you wanted:

```<code>library(dplyr)

frm <- frm %>%
  mutate(BMI = as.numeric(BMI)) %>%
  mutate(BMIGRP = case_when(
    BMI < 18.5 ~ 'underweight',
    between(BMI, 18.5, 24.9)  ~ 'healthy weight',
    between(BMI, 25, 29.9) ~ 'overweight',
    BMI > 30 ~ 'obese')
  )
</code>```

The mutate(BMIGRP = as.numeric(BMIGRP)) converts the BMIGRP column to numeric. Then the mutate(BMIGRP = case_when(...) will create a new column called BMIGRP and assign 'underweight', 'healthy weight', 'overweight' or 'obese' based on the BMI. If the argument doesn't apply, an NA will be assigned.

Body:
So I have a dataset in R (Framingham Heart Study data), and I am trying to assign BMI groups "underweight," "normal," "overweight," and "obese."

It has over 11,000 observations and 38 variables/columns, so it would be kind of hard to post some of the data here (I hope this won't be too much trouble to answer without it).

The dataset is called frm and I am trying to subset in the following way:

frm$BMIGRP <- NA  #Creating new variable (this part works and creates a BMIGRP column with all NA values)
frm$BMIGRP[which(as.numeric(frm$BMI) < 18.5)] <- "underweight"

However, there are NA values in the data set BMI variable (indicated with a ".", which I have also tried changing to NA).

When I try to subset this way for each group, it is assigning only some of the underweight values to "underweight" and is assigning a lot of NA / "." values to underweight as well. It then tells me there are only 10 "normal" weight subjects and about 11000 in the obese category which is just not true because I can view the data set.

If done correctly, this should create the four groups with several hundred to several thousand observations in each category. But I am only getting 10 normal, 71 underweight, and ~11,000 obese.

I'm just not sure where I'm going wrong with this or if there is a different way I can create a new variable and assign it in the same kind of way. Any help is very much appreciated.

I should also mention that this is the code that my professor gave us as an example in our lab session, and I am basically copying and pasting it with the appropriate replacements for my data set.

This is my first question on this website so I apologize if it is incomplete or if I need to give more information. Thanks!

Body:
Like @leeum said. Check that BMI is numeric. If you want to make a new category column based on the BMI, look at case_when from dplyr. So maybe this is what you wanted:

library(dplyr)

frm <- frm %>%
  mutate(BMI = as.numeric(BMI)) %>%
  mutate(BMIGRP = case_when(
    BMI < 18.5 ~ 'underweight',
    between(BMI, 18.5, 24.9)  ~ 'healthy weight',
    between(BMI, 25, 29.9) ~ 'overweight',
    BMI > 30 ~ 'obese')
  )

The mutate(BMIGRP = as.numeric(BMIGRP)) converts the BMIGRP column to numeric. Then the mutate(BMIGRP = case_when(...) will create a new column called BMIGRP and assign 'underweight', 'healthy weight', 'overweight' or 'obese' based on the BMI. If the argument doesn't apply, an NA will be assigned.


问:
A Java-based Readability-like parser
I would like to know what standalone options exist for parsing and converting normal webpages to the easy to read format, provided by services like Pocket, Readability, and Instapaper.

I am primarily looking for a Java parser library to include in my app, but in general, all kinds of standalone tools are appreciated.

Thanks.

答:
Snackatory now itself states that it's outdated and recommends using Crux.

But there's also Readability4J. It's a Kotlin port of Mozilla's Readability.js, which is used for Firefox's Reader View. So Readability4J's output matches exactly Firefox's Reader View.

Disclaimer: I am the author of Readability4J. But I just ported it, kudos for the great work go to Mozilla: https://github.com/mozilla/readability.

Title: A Java-based Readability-like parser


问:
iOS - How to add sceneKit node objects on top of the front facing camera. Not ArKit
I'm trying to create some animations to be seen in the front facing camera in iOS, with SceneKit.
Something similar to what ArKit does on the back camera.
Not using iPhone X nor ArKit (ArKit does not work on the front facing camera).
Right now I'm not able to combine the camera and the sceneKit scene for both to appear. I can see either the front camera view from:

```<code>AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .front)
</code>```

or I can see the scene view.

It should look like the front facing camera live as a backdrop and all the nodes in the scene appearing in the front on top of that.

Another way to think of it is that I want the background of the scene to by a live feed from the front facing camera.

How would I do this?

答:
SCNScene.background is an instance of SCNMaterialProperty which can take an AVCaptureDevice instance as its contents. The online documentation doesn't reflect that addition to iOS 11 yet, but it's mentioned in the SceneKit headers as well as their WWDC'17 presentation.

```<code>// Setup background video
let captureDevice: AVCaptureDevice = ...
scene.background.contents = captureDevice
</code>```

Body:
I'm trying to create some animations to be seen in the front facing camera in iOS, with SceneKit.
Something similar to what ArKit does on the back camera.
Not using iPhone X nor ArKit (ArKit does not work on the front facing camera).
Right now I'm not able to combine the camera and the sceneKit scene for both to appear. I can see either the front camera view from:

AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .front)

or I can see the scene view.

It should look like the front facing camera live as a backdrop and all the nodes in the scene appearing in the front on top of that.

Another way to think of it is that I want the background of the scene to by a live feed from the front facing camera.

How would I do this?

Body:
SCNScene.background is an instance of SCNMaterialProperty which can take an AVCaptureDevice instance as its contents. The online documentation doesn't reflect that addition to iOS 11 yet, but it's mentioned in the SceneKit headers as well as their WWDC'17 presentation.

// Setup background video
let captureDevice: AVCaptureDevice = ...
scene.background.contents = captureDevice


问:
Change the color of the last cell when mouse hovers over a row, value being taken into consideration
I'm trying to make like this:
If mouse hovers over a row, the last cell becomes red or yellow depending on the value: 1 or 0.

Well, I thought classes could help me: redcell and yellowcell are added.

I am inspired by this: http://jsfiddle.net/u7tYE/1/
My by code doesn't work.

Is it possible with CSS or not?

        tr:hover ~ .redcell {
            background: red;
        }
        tr:hover ~ .yellowcell {
            background: red;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

   <head>

   </head>

   <body>
      <table id="table">
        <tr>
          <td>item1</td>
          <td>item2</td>
          <td>item3</td>
          <td class="yellowcell">1</td>
        </tr>
        <tr>
          <td>item1</td>
          <td>item2</td>
          <td>item3</td>
          <td class="redcell">0</td>
        </tr>
        <tr>
          <td>item1</td>
          <td>item2</td>
          <td>item3</td>
          <td class="yellowcell">1</td>
        </tr>
      </table>
   </body>
</html></code>```

答:
#table tr:nth-child(1):hover .yellowcell,#table tr:nth-child(3):hover .yellowcell {
  background-color: yellow;
}
#table tr:nth-child(2):hover .redcell  {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

   <head>

   </head>

   <body>
      <table id="table">
        <tr>
          <td>item1</td>
          <td>item2</td>
          <td>item3</td>
          <td class="yellowcell">1</td>
        </tr>
        <tr>
          <td>item1</td>
          <td>item2</td>
          <td>item3</td>
          <td class="redcell">0</td>
        </tr>
        <tr>
          <td>item1</td>
          <td>item2</td>
          <td>item3</td>
          <td class="yellowcell">1</td>
        </tr>
      </table>
   </body>
</html></code>```

Body:
I'm trying to make like this:
If mouse hovers over a row, the last cell becomes red or yellow depending on the value: 1 or 0.

Well, I thought classes could help me: redcell and yellowcell are added.

I am inspired by this: http://jsfiddle.net/u7tYE/1/
My by code doesn't work.

Is it possible with CSS or not?

        tr:hover ~ .redcell {
            background: red;
        }
        tr:hover ~ .yellowcell {
            background: red;
        }

<!DOCTYPE html>

          item1
          item2
          item3
          1

          item1
          item2
          item3
          0

          item1
          item2
          item3
          1

Body:
#table tr:nth-child(1):hover .yellowcell,#table tr:nth-child(3):hover .yellowcell {
  background-color: yellow;
}
#table tr:nth-child(2):hover .redcell  {
  background-color: red;
}

<!DOCTYPE html>
<html>

   <head>

   </head>

   <body>
      <table id="table">
        <tr>
          <td>item1</td>
          <td>item2</td>
          <td>item3</td>
          <td class="yellowcell">1</td>
        </tr>
        <tr>
          <td>item1</td>
          <td>item2</td>
          <td>item3</td>
          <td class="redcell">0</td>
        </tr>
        <tr>
          <td>item1</td>
          <td>item2</td>
          <td>item3</td>
          <td class="yellowcell">1</td>
        </tr>
      </table>
   </body>
</html>


问:
Lodash - '_' refers to a UMD global and lodash.js is not a module errors
If I do nothing and add the type definition it works for jquery but lodash gets a

'_' referes to a UMD global, but the current file is a module. Consider adding an import instead.

If I try to import lodash with any combination of import call, I get

lodash.js is not a module

I tried to get help by asking a question here and it was closed because there was another answer for Angular (Angular 2). I really need a real answer so I'm re-posting with my own solutions, hoping someone will eventually help me understand this problem.

In this case I am:

Not using any frameworks like Angular

Using TypeScript

Using requirejs to import modules

Using Visual Studio

Using MVC5

答:
'_' referes to a UMD global, but the current file is a module. Consider adding an import instead.

This is caused by the type definition. Go into your @types/lodash file and delete these lines:

```<code>export = _;
export as namespace _;
</code>```

This will solve the error.

***EDIT****

Removing the export statements above will cause another error if you have any global declarations in your type definition file, for example, like this:

```<code>declare global { }
</code>```

To solve this, either move the properties from the global declaration to the interfaces that reference them - or delete them entirely and change the types of the references to something generic. I'm not sure which solution will make a better final compilation but the former has not caused any problems in my application as far back as IE11.

Body:
'_' referes to a UMD global, but the current file is a module. Consider adding an import instead.

This is caused by the type definition. Go into your @types/lodash file and delete these lines:

export = _;
export as namespace _;

This will solve the error.

***EDIT****

Removing the export statements above will cause another error if you have any global declarations in your type definition file, for example, like this:

declare global { }

To solve this, either move the properties from the global declaration to the interfaces that reference them - or delete them entirely and change the types of the references to something generic. I'm not sure which solution will make a better final compilation but the former has not caused any problems in my application as far back as IE11.


问:
Why does JSHint throw a warning if I am using const?
This is the error I get when using const:

```<code><error line="2" column="1" severity="warning" message="'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz)." source="jshint.W104" />
</code>```

My code looks like this:

```<code>const Suites = {
    Spade: 1,
    Heart: 2,
    Diamond: 3,
    Club: 4
};
</code>```

The code works fine only JSHint is warning me every time.

答:
Create a file called, say jshint_opts with this content:
{
"esversion": 6
}

Then invoke jshint with something like this command line:

jshint --config jshint_opts lib/*.js

Body:
This is the error I get when using const:

<error line="2" column="1" severity="warning" message="'const' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz)." source="jshint.W104" />

My code looks like this:

const Suites = {
    Spade: 1,
    Heart: 2,
    Diamond: 3,
    Club: 4
};

The code works fine only JSHint is warning me every time.


问:
Avoid the “Expression has changed after it was checked” error by calling "ChangeDetectorRef::detectChanges()"
I am trying to implement two way data binding on a date input while applying a pipe on the model:

```<code><!-- The name variable is retrieved within the HTML from a loop expression -->
<input matInput [matDatepicker]="datePicker" placeholder="{{label}}" formControlName="{{name}}"
[ngModel]="data[name] | date"
(ngModelChange)="handleDateChange(data[name], $event)" >
</code>```

Where my component looks something like:

```<code>//...
private data: any;

constructor(private cdRef:ChangeDetectorRef) { }

handleDateChange(field: any, date: any) {
    field = date; // The code is simplified, there is more handling with the date field
    this.cdRef.detectChanges();
}
</code>```

Based on this post, the code above works well only thanks to this.cdRef.detectChanges(); If I remove it I get the following error:
Expression has changed after it was checked

My question is more general than related specifically to the above implementation. I would like to know what are the best practices to deal with the Expression has changed after it was checked error? Is calling cdRef.detectChanges() a good idea?

答:
Did you try the direct assignment  to the value on the change event?

```<code><!-- The name variable is retrieved within the HTML from a loop expression -->
<input matInput [matDatepicker]="datePicker" placeholder="{{label}}" formControlName="{{name}}"
[ngModel]="data[name] | date"
(ngModelChange)="data[name] = $event" >
</code>```

With this approach you get to use the pipe on the ngModel and you keep it simple as if it were doing the regular [(ngModel)] two way binding. No need for an additional handler.

EDIT

Another reason for this to be happening can be by trying to mix the template driven approach with the reactive forms approach. I'm assuming you're not trying to do both, correct? By seeing the formControlName attribute it might be telling me you are trying to mix both approaches and definitely you'll have this issue because of that.

The reason for this is because the ngModel will update the value whenever a change happens on the template driven approach and at the same time the reactive forms approach will also update the value on the same property. Because this happens in parallel it triggers an error when Angular runs the second check for changes in dev mode. The property update should be handled only by one of the approaches.

Check a scenario where this happens here

Body:
I am trying to implement two way data binding on a date input while applying a pipe on the model:

<input matInput [matDatepicker]="datePicker" placeholder="{{label}}" formControlName="{{name}}"
[ngModel]="data[name] | date"
(ngModelChange)="handleDateChange(data[name], $event)" >

Where my component looks something like:

//...
private data: any;

constructor(private cdRef:ChangeDetectorRef) { }

handleDateChange(field: any, date: any) {
    field = date; // The code is simplified, there is more handling with the date field
    this.cdRef.detectChanges();
}

Based on this post, the code above works well only thanks to this.cdRef.detectChanges(); If I remove it I get the following error:
Expression has changed after it was checked

My question is more general than related specifically to the above implementation. I would like to know what are the best practices to deal with the Expression has changed after it was checked error? Is calling cdRef.detectChanges() a good idea?

Body:
Did you try the direct assignment  to the value on the change event?

<!-- The name variable is retrieved within the HTML from a loop expression -->
<input matInput [matDatepicker]="datePicker" placeholder="{{label}}" formControlName="{{name}}"
[ngModel]="data[name] | date"
(ngModelChange)="data[name] = $event" >

With this approach you get to use the pipe on the ngModel and you keep it simple as if it were doing the regular [(ngModel)] two way binding. No need for an additional handler.

EDIT

Another reason for this to be happening can be by trying to mix the template driven approach with the reactive forms approach. I'm assuming you're not trying to do both, correct? By seeing the formControlName attribute it might be telling me you are trying to mix both approaches and definitely you'll have this issue because of that.

The reason for this is because the ngModel will update the value whenever a change happens on the template driven approach and at the same time the reactive forms approach will also update the value on the same property. Because this happens in parallel it triggers an error when Angular runs the second check for changes in dev mode. The property update should be handled only by one of the approaches.

Check a scenario where this happens here


问:
C struct and malloc problem (C)
It's amazing how even the littlest program can cause so much trouble in C.

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree* tree = (tree*) malloc(sizeof(tree));
    node *node = (node*) malloc(sizeof(node));
    tree->nodes[0] = node;
    return tree;
}

int main() {
    return 0;
}
</code>```

The compiler says:

```<code>main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token
</code>```

Can you please help?

答:
Interestingly, it does compile cleanly if you simply write the allocations as:

```
tree *tree = malloc( sizeof *tree );
```

It is often considered better style to use "sizeof variable"
rather than "sizeof( type )", and in this case the stylistic
convention resolves the syntax error.  Personally, I think
this example is a good case demonstrating why typecasts are
generally a bad idea, as the code is much less obfuscated if
written:

```
struct tree *tree = malloc( sizeof *tree );
```

ContentLicense: CC BY-SA 2.5

Title: C struct and malloc problem (C)

Body:
It's amazing how even the littlest program can cause so much trouble in C.

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree* tree = (tree*) malloc(sizeof(tree));
    node *node = (node*) malloc(sizeof(node));
    tree->nodes[0] = node;
    return tree;
}

int main() {
    return 0;
}

The compiler says:

main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token

Can you please help?

Body:
Interestingly, it does compile cleanly if you simply write the allocations as:

tree *tree = malloc( sizeof *tree );

It is often considered better style to use "sizeof variable"
rather than "sizeof( type )", and in this case the stylistic
convention resolves the syntax error.  Personally, I think
this example is a good case demonstrating why typecasts are
generally a bad idea, as the code is much less obfuscated if
written:

struct tree *tree = malloc( sizeof *tree );


问:
Print media queries being ignored in Chrome?
I'm creating some print specific styles using the following:

```<code>@media print {
/* Styles */
}
</code>```

As we are using SASS all the styles get compiled into one stylesheet, styles.css at runtime, which is declared in the  of the document as follows:

```<code><link rel='stylesheet' href='/assets/css/styles.css'>
</code>```

Now when I print from chrome (Ctrl+P), it completely ignores my print styles but Firefox (30.0) is fine. IE(11) is terrible but this is because we have a lot of show/hide panels which IE doesn't seem to like/

Can't for the life of me figure out what's happening. If I emulate print media in Chrome then it loads the styles fine, it's when I actually try and print that it doesn't work. I've tried loads of things, adding, media= attributes, double quotes, changing the order of href etc all to no avail!!

Note, we're not using type anymore as I thought you didn't need to use this anymore. I've tried adding this anyway but it still doesn't work!

I've even tried this: http://lawrencenaman.com/optimisation/print-media-queries-not-working/ but it still doesn't work. It's driving me crazy, any ideas?

UPDATE: So I noticed that when I hit Ctrl + P to print the page, the preview that I see seems to use some of the styles from the print stylesheet but seems to render everything using a mobile media query? I think there may be some conflict with a breakpoint, will update when I get a chance.

UPDATE2: I can see that the print stylesheet is loading at the bottom so this should in theory over write all the other media queries (at least the ones that I'm trying to over write)?

答: A problem I had was that rel='stylesheet' wasn't set in the print css link. Adding it fixed the problem.

Body:
I'm creating some print specific styles using the following:

@media print {
/* Styles */
}

As we are using SASS all the styles get compiled into one stylesheet, styles.css at runtime, which is declared in the  of the document as follows:

<link rel='stylesheet' href='/assets/css/styles.css'>

Now when I print from chrome (Ctrl+P), it completely ignores my print styles but Firefox (30.0) is fine. IE(11) is terrible but this is because we have a lot of show/hide panels which IE doesn't seem to like/

Can't for the life of me figure out what's happening. If I emulate print media in Chrome then it loads the styles fine, it's when I actually try and print that it doesn't work. I've tried loads of things, adding, media= attributes, double quotes, changing the order of href etc all to no avail!!

Note, we're not using type anymore as I thought you didn't need to use this anymore. I've tried adding this anyway but it still doesn't work!

I've even tried this: http://lawrencenaman.com/optimisation/print-media-queries-not-working/ but it still doesn't work. It's driving me crazy, any ideas?

UPDATE: So I noticed that when I hit Ctrl + P to print the page, the preview that I see seems to use some of the styles from the print stylesheet but seems to render everything using a mobile media query? I think there may be some conflict with a breakpoint, will update when I get a chance.

UPDATE2: I can see that the print stylesheet is loading at the bottom so this should in theory over write all the other media queries (at least the ones that I'm trying to over write)?


问:
Dapper reporting invalid syntax near parameter name when attempting to pass null in a DynamicParameter
I'm attempting to get all records from a table where a certain field is not a blank string or null. Due to the way I'm building the queries, ISNULL and COALESCE are not options here. Changing the schema of the database is not an option either.

This is the code I'm running to try to retrieve the records.

```<code>using System;
using System.Data.SqlClient;
using System.Linq;
using Dapper;

namespace DapperMCVE
{
    internal class UserFinder
    {
        public static void Main(string[] args)
        {
            using (var connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;Integrated Security=True"))
            {
                connection.Execute(@"IF NOT EXISTS(SELECT * FROM sys.tables WHERE name = 'Users')
                                        CREATE TABLE Users(NullableUserId varchar(50) NULL) ON [PRIMARY]");
                connection.Execute(@"DELETE Users");
                connection.Execute(@"INSERT INTO Users(NullableUserId)
                                     VALUES(''), (NULL), ('SteveSmith@fake.com'), ('Morgan@totallyreal.org')");
                var parameters = new DynamicParameters();
                parameters.Add("UserIdNull", (string)null);
                parameters.Add("UserIdBlank", "");
                try
                {
                    var users = connection.Query(@"SELECT *
                                                   FROM Users
                                                   WHERE NullableUserId IS NOT @UserIdNull
                                                     AND NullableUserId != @UserIdBlank", parameters);
                    Console.WriteLine(users.ToList());
                }
                catch (SqlException e)
                {
                    Console.WriteLine(e);
                }
                Console.ReadKey();
            }
        }
    }
}
</code>```

The error thrown is System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near '@UserIdNull'.

My assumption is that the above code should replicate this query:

```<code>SELECT *
  FROM Users
  WHERE NullableUserId IS NOT NULL
    AND NullableUserId != ''
</code>```

but it seems to be doing something closer to

```<code>SELECT *
FROM Users
WHERE NullableUserId IS NOT 'NULL'
  AND NullableUserId != ''
</code>```

If I change the query to

```<code>SELECT *
FROM Users
WHERE ISNULL(NullableUserId, '') != ISNULL(@UserIdNull, '')
</code>```

it works fine. Unfortunately, I cannot use ISNULL in this case.

I've replicated this in SQL Server 2014 and 2016. We're using 2016 in our production environment.

The profiler reports that the following command is being run:

```<code>exec sp_executesql N'SELECT *
                     FROM Users
                     WHERE NullableUserId IS NOT @UserIdNull
                       AND NullableUserId != @UserIdBlank',N'@UserIdNull nvarchar(4000),@UserIdBlank nvarchar(4000)',@UserIdNull=NULL,@UserIdBlank=N''
</code>```

Which makes me suspect this may be an issue with SQL Server itself?

Things I've tried (to no avail):

Casting the parameter to various nullable types

Using DBNull.Value

答:
IS NOT @UserIdNull genuinely isn't valid SQL syntax.... IS NOT NULL is fine. This isn't a dapper issue - this is simply an SQL feature: you need to write legal SQL.

My assumption is that the above code should replicate this query:

Nope. It uses parameters. The syntax is retained. Dapper does not inject literals. This is very deliberate and correct. I wrote about this yesterday, as it happens.

Body:
I'm attempting to get all records from a table where a certain field is not a blank string or null. Due to the way I'm building the queries, ISNULL and COALESCE are not options here. Changing the schema of the database is not an option either.

This is the code I'm running to try to retrieve the records.

using System;
using System.Data.SqlClient;
using System.Linq;
using Dapper;

namespace DapperMCVE
{
    internal class UserFinder
    {
        public static void Main(string[] args)
        {
            using (var connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;Integrated Security=True"))
            {
                connection.Execute(@"IF NOT EXISTS(SELECT * FROM sys.tables WHERE name = 'Users')
                                        CREATE TABLE Users(NullableUserId varchar(50) NULL) ON [PRIMARY]");
                connection.Execute(@"DELETE Users");
                connection.Execute(@"INSERT INTO Users(NullableUserId)
                                     VALUES(''), (NULL), ('SteveSmith@fake.com'), ('Morgan@totallyreal.org')");
                var parameters = new DynamicParameters();
                parameters.Add("UserIdNull", (string)null);
                parameters.Add("UserIdBlank", "");
                try
                {
                    var users = connection.Query(@"SELECT *
                                                   FROM Users
                                                   WHERE NullableUserId IS NOT @UserIdNull
                                                     AND NullableUserId != @UserIdBlank", parameters);
                    Console.WriteLine(users.ToList());
                }
                catch (SqlException e)
                {
                    Console.WriteLine(e);
                }
                Console.ReadKey();
            }
        }
    }
}

The error thrown is System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near '@UserIdNull'.

My assumption is that the above code should replicate this query:

SELECT *
  FROM Users
  WHERE NullableUserId IS NOT NULL
    AND NullableUserId != ''

but it seems to be doing something closer to

SELECT *
FROM Users
WHERE NullableUserId IS NOT 'NULL'
  AND NullableUserId != ''

If I change the query to

SELECT *
FROM Users
WHERE ISNULL(NullableUserId, '') != ISNULL(@UserIdNull, '')

it works fine. Unfortunately, I cannot use ISNULL in this case.

I've replicated this in SQL Server 2014 and 2016. We're using 2016 in our production environment.

The profiler reports that the following command is being run:

exec sp_executesql N'SELECT *
                     FROM Users
                     WHERE NullableUserId IS NOT @UserIdNull
                       AND NullableUserId != @UserIdBlank',N'@UserIdNull nvarchar(4000),@UserIdBlank nvarchar(4000)',@UserIdNull=NULL,@UserIdBlank=N''

Which makes me suspect this may be an issue with SQL Server itself?

Things I've tried (to no avail):

Casting the parameter to various nullable types

Using DBNull.Value


问:
Java / Groovy : Find XML node by Line number
Below is my groovy code to validate XML schema aginst an XSD

```<code>import java.io.File;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.transform.sax.SAXSource
import javax.xml.parsers.SAXParserFactory
import org.xml.sax.SAXException
import org.xml.sax.InputSource
import org.xml.sax.SAXParseException
import org.xml.sax.ErrorHandler

def validateXMLSchema(String xsdPath, String xmlPath) {
    final List < SAXParseException > exceptions = new LinkedList < SAXParseException > ();
     try {
      SchemaFactory factory =
       SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      Schema schema = factory.newSchema(new File(xsdPath));
      Validator validator = schema.newValidator();
      validator.setErrorHandler(new ErrorHandler() {
       @Override
       public void warning(SAXParseException exception) throws SAXException {
        exceptions.add(exception);
       }

       @Override
       public void fatalError(SAXParseException exception) throws SAXException {
        exceptions.add(exception);
       }

       @Override
       public void error(SAXParseException exception) throws SAXException {
        exceptions.add(exception);
       }
      });
      def xmlFile = new File(xmlPath);
      validator.validate(new StreamSource(xmlFile));
      exceptions.each {
       println 'lineNumber : ' + it.lineNumber + '; message : ' + it.message
      }
     } catch (IOException | SAXException e) {
      println("Exception: line ${e.lineNumber} " + e.getMessage());
      return false;
     }
     return exceptions.size() == 0;
}
</code>```

Below are some of the validation errors, I can access the line number for each message and am trying to find the corresponding node name

```<code>lineNumber : 106; message : cvc-datatype-valid.1.2.1: '' is not a valid value for 'date'.
lineNumber : 248; message : cvc-enumeration-valid: Value 'Associate' is not facet-valid with respect to enumeration '[ADJSTR, ADJSMT]
</code>```

Is there a simple way to find the Node name for corresponsding error message usinng the line number? Or do I have to read that specific line and parse it using XmlSlurper like below(trying to avoid this approach since it will be slower for larger XML files in production with heavy user load)?

```<code>def getNodeName(xmlFile, lineNumber){
  def xmlLine =  xmlFile.readLines().get(lineNumber)
  def node = new XmlSlurper().parseText(xmlLine.toString())
  node.name()
}
</code>```

答:
This is not elegant but the following getNodeName() should be faster (full example here):

```<code>def getNodeName(xmlFile, lineNumber) {
    def result = "unknown"
    def count = 1
    def NODE_REGEX = /.*?<(.*?)>.*/
    def br

    try {
        br = new BufferedReader(new FileReader(xmlFile))
        String line
        def isDone = false
        while ((! isDone) && (line = br.readLine()) != null) {
            if (count == lineNumber) {
                def matcher = (line =~ NODE_REGEX)
                if (matcher.matches()) {
                    result = matcher[0][1]
                }
                isDone = true
            }
            count++
        }
    } finally {
        // TODO: better exception handling
        br.close()
    }

    return result
}
</code>```

It simply reads lines until the line in question and then uses a rudimentary regular expression to get the name. You could potentially use XmlSlurper as in your example if preferred. The key thing is that the file IO/memory should be considerably less.

Body:
Below is my groovy code to validate XML schema aginst an XSD

import java.io.File;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.transform.sax.SAXSource
import javax.xml.parsers.SAXParserFactory
import org.xml.sax.SAXException
import org.xml.sax.InputSource
import org.xml.sax.SAXParseException
import org.xml.sax.ErrorHandler

def validateXMLSchema(String xsdPath, String xmlPath) {
    final List < SAXParseException > exceptions = new LinkedList < SAXParseException > ();
     try {
      SchemaFactory factory =
       SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      Schema schema = factory.newSchema(new File(xsdPath));
      Validator validator = schema.newValidator();
      validator.setErrorHandler(new ErrorHandler() {
       @Override
       public void warning(SAXParseException exception) throws SAXException {
        exceptions.add(exception);
       }

       @Override
       public void fatalError(SAXParseException exception) throws SAXException {
        exceptions.add(exception);
       }

       @Override
       public void error(SAXParseException exception) throws SAXException {
        exceptions.add(exception);
       }
      });
      def xmlFile = new File(xmlPath);
      validator.validate(new StreamSource(xmlFile));
      exceptions.each {
       println 'lineNumber : ' + it.lineNumber + '; message : ' + it.message
      }
     } catch (IOException | SAXException e) {
      println("Exception: line ${e.lineNumber} " + e.getMessage());
      return false;
     }
     return exceptions.size() == 0;
}

Below are some of the validation errors, I can access the line number for each message and am trying to find the corresponding node name

lineNumber : 106; message : cvc-datatype-valid.1.2.1: '' is not a valid value for 'date'.
lineNumber : 248; message : cvc-enumeration-valid: Value 'Associate' is not facet-valid with respect to enumeration '[ADJSTR, ADJSMT]

Is there a simple way to find the Node name for corresponsding error message usinng the line number? Or do I have to read that specific line and parse it using XmlSlurper like below(trying to avoid this approach since it will be slower for larger XML files in production with heavy user load)?

def getNodeName(xmlFile, lineNumber){
  def xmlLine =  xmlFile.readLines().get(lineNumber)
  def node = new XmlSlurper().parseText(xmlLine.toString())
  node.name()
}

Body:
This is not elegant but the following getNodeName() should be faster (full example here):

def getNodeName(xmlFile, lineNumber) {
    def result = "unknown"
    def count = 1
    def NODE_REGEX = /.*?<(.*?)>.*/
    def br

    try {
        br = new BufferedReader(new FileReader(xmlFile))
        String line
        def isDone = false
        while ((! isDone) && (line = br.readLine()) != null) {
            if (count == lineNumber) {
                def matcher = (line =~ NODE_REGEX)
                if (matcher.matches()) {
                    result = matcher[0][1]
                }
                isDone = true
            }
            count++
        }
    } finally {
        // TODO: better exception handling
        br.close()
    }

    return result
}

It simply reads lines until the line in question and then uses a rudimentary regular expression to get the name. You could potentially use XmlSlurper as in your example if preferred. The key thing is that the file IO/memory should be considerably less.


问:
Is there a way to submit multiple forms to insert data in specific column?
I have this form, but I need to use it for more users.
ex for user_id=1 to submit 1 form for user_id=2 to submit another form,
can you guys help?

The database table has a column u_userid where 1 = admin 2,3,4,5,6,7 is normal user, each user has more columns which I need to update data from database.

```<code><?php
if( $_SESSION['user_id'] == '1' || $_SESSION['user_id'] == '7' )
{
    echo '<hr class="mx-3 my-0">
            <div class="callout callout-warning m-0 py-3">
              <div>
                <strong>Sas Andreea</strong>
              </div>
              <small class="text-muted mr-3"><i class="icon-calendar"></i>Salariu Lunar:</small>
              <small class="text-muted"><i class="icon-location-pin"></i><input type="text"  name="salariulunar" value="' . $row[
  'salariulunar'] . '"  maxlength="4" size="4"> lei
              <br /> Data contract: <input type="text"  name="datacontractului"  maxlength="10" size="7" value="' . $row['datacontractului'] . ' ">
              <br /> Datorie: <input type="text"  name="datorie" value="' . $row['datorie'] . '"   maxlength="4" size="4"> Lei
              <br /> Salariu in avans: <input type="text" value="' . $row['salariuavans'] . ' " name="salariuavans"  maxlength="4" size="4"> Lei
              <br /> Zile de concediu luate: <input  type="text" value="' . $row['zileconcediu'] . '"  name="zileconcediu"  maxlength="2" size="2"> Zile
              </small>
            </div>';
}
?>
<!-- Sfarsit angajat -->
<?php
if( $_SESSION['user_id'] == '1' )
{
    echo '<button type="submit" name="submit" class="btn btn-sm btn-primary"><i class="fa fa-dot-circle-o" ></i> Modifica</button>';
}
?>
</form>
</code>```

答:
You have two options:

You can use a form, which requires that you have the

<form action="nameOfYourBackEndFile.php" method="post">

       Your existing stuff in here

</form>
 tags surrounding your existing code AND you need a button type="submit" to submit the form.

or

You can use javascript/jQuery. Either way is fine.

Also, you need a way to identify which user this form is being filled out for. You have the user_id in a session variable, so why not use that? Your submit button can look like this:

```<code><button id="submit_<?php echo $_SESSION['user_id']; />" type="submit">Go</button>
</code>```

See this example for more information about what you are trying to do:

How can I make, when clicking a button, send an email with the data included from the form?

PHP - Secure member-only pages with a login system

AJAX request callback using jQuery

Body:
I have this form, but I need to use it for more users.
ex for user_id=1 to submit 1 form for user_id=2 to submit another form,
can you guys help?

The database table has a column u_userid where 1 = admin 2,3,4,5,6,7 is normal user, each user has more columns which I need to update data from database.

<?php
if( $_SESSION['user_id'] == '1' || $_SESSION['user_id'] == '7' )
{
    echo '

                Sas Andreea

              Salariu Lunar:
              <input type="text"  name="salariulunar" value="' . $row[
  'salariulunar'] . '"  maxlength="4" size="4"> lei

 Data contract: <input type="text"  name="datacontractului"  maxlength="10" size="7" value="' . $row['datacontractului'] . ' ">

 Datorie: <input type="text"  name="datorie" value="' . $row['datorie'] . '"   maxlength="4" size="4"> Lei

 Salariu in avans: <input type="text" value="' . $row['salariuavans'] . ' " name="salariuavans"  maxlength="4" size="4"> Lei

 Zile de concediu luate: <input  type="text" value="' . $row['zileconcediu'] . '"  name="zileconcediu"  maxlength="2" size="2"> Zile

';
}
?>

<?php
if( $_SESSION['user_id'] == '1' )
{
    echo '<button type="submit" name="submit" class="btn btn-sm btn-primary"> Modifica</button>';
}
?>
</form>

Body:
You have two options:

You can use a form, which requires that you have the

<form action="nameOfYourBackEndFile.php" method="post">

       Your existing stuff in here

</form>
 tags surrounding your existing code AND you need a button type="submit" to submit the form.

or

You can use javascript/jQuery. Either way is fine.

Also, you need a way to identify which user this form is being filled out for. You have the user_id in a session variable, so why not use that? Your submit button can look like this:

<button id="submit_<?php echo $_SESSION['user_id']; />" type="submit">Go</button>

See this example for more information about what you are trying to do:

How can I make, when clicking a button, send an email with the data included from the form?

PHP - Secure member-only pages with a login system

AJAX request callback using jQuery


问:
How can i sort the dictionary by tuple value?
kn = nx.karate_club_graph()
kn.nodes(data=True)
[(0, {'club': 'Officer'}), (1, {'club': 'Mr. Hi'}), (2, {'club': 'Mr. Hi'}), (3, {'club': 'Mr. Hi'}), (4, {'club': 'Mr. Hi'}), (5, {'club': 'Officer'}), (6, {'club': 'Officer'}), (7, {'club': 'Mr. Hi'})]

And i want the output to be dictionary which will be sorted first by 'Mr. Hi' club and then by the second one. P.S. i am using Python 3.0

答:
It looks like you are just trying to sort that list of tuples. So in that case, you just need to use sorted with a lambda for the key. An example of this:

```<code>mydata =  [(0, {'club': 'Officer'}), (1, {'club': 'Mr. Hi'}), (2, {'club': 'Mr. Hi'}), (3, {'club': 'Mr. Hi'}), (4, {'club': 'Mr. Hi'}), (5, {'club': 'Officer'}), (6, {'club': 'Officer'}), (7, {'club': 'Mr. Hi'})]

mydata_sorted = sorted(mydata, key=lambda x: x[1]['club'])
print(mydata_sorted)
</code>```

will display

```<code>[(1, {'club': 'Mr. Hi'}), (2, {'club': 'Mr. Hi'}), (3, {'club': 'Mr. Hi'}), (4, {'club': 'Mr. Hi'}), (7, {'club': 'Mr. Hi'}), (0, {'club': 'Officer'}), (5, {'club': 'Officer'}), (6, {'club': 'Officer'})]
</code>```

Body:
It looks like you are just trying to sort that list of tuples. So in that case, you just need to use sorted with a lambda for the key. An example of this:

mydata =  [(0, {'club': 'Officer'}), (1, {'club': 'Mr. Hi'}), (2, {'club': 'Mr. Hi'}), (3, {'club': 'Mr. Hi'}), (4, {'club': 'Mr. Hi'}), (5, {'club': 'Officer'}), (6, {'club': 'Officer'}), (7, {'club': 'Mr. Hi'})]

mydata_sorted = sorted(mydata, key=lambda x: x[1]['club'])
print(mydata_sorted)

will display

[(1, {'club': 'Mr. Hi'}), (2, {'club': 'Mr. Hi'}), (3, {'club': 'Mr. Hi'}), (4, {'club': 'Mr. Hi'}), (7, {'club': 'Mr. Hi'}), (0, {'club': 'Officer'}), (5, {'club': 'Officer'}), (6, {'club': 'Officer'})]


问:
Problem with BufferedImage flickering
Hello I'm writing a small game and it's nearly finished, the only thing that doesn't work is the ImageBuffer. Every 10 miliseconds I call the method repaint(). My paint() method is as follows:

```<code>private Graphics2D g2D;

public void paint (Graphics g) {
    BufferedImage bimage = ((Graphics2D)g).getDeviceConfiguration().createCompatibleImage(700, 600, Transparency.OPAQUE);
    g2D = bimage.createGraphics();
    g2D.setFont(font);
    for(Wall wall: walls){
        wall.paint(g2D);
    }
    g2D.setColor(Color.orange);
    paddle.paint(g2D);
    g2D.drawString(score + "", 150,50);
    g2D.drawString("record: "+topscore  , 350,50);
    g2D.setColor(Color.red);
    ball.paint(g2D);
    g.drawImage(bimage,0,0,this);
}
</code>```

But this doesn't seem to remove the flickering. I think somehow the screen is cleared before the bufferedimage starts being painted.
Can anyone help me with solving this problem?
thanks!

答:
You should extend JComponent instead of Canvas, depending on if you are using Swing rather than AWT. Doing this gives you a nice lightweight component and doesn't need you to implement double-buffering support. Then, in your overridden paintComponent(..) draw your image with the provided Graphics object.

On the subject of the original code, creating a new compatible image every single time in paint is blooming horrible (it's a very expensive operation that uses large bytebuffers -- you'll get frequent GC pauses). If you really want double buffering in AWT (which will give you flickering when resizing but should be okay in an applet), you should look into BufferStrategy.

Edit: changed Component to JComponent, oops :)

Title: Problem with BufferedImage flickering

Body:
Hello I'm writing a small game and it's nearly finished, the only thing that doesn't work is the ImageBuffer. Every 10 miliseconds I call the method repaint(). My paint() method is as follows:

private Graphics2D g2D;

public void paint (Graphics g) {
    BufferedImage bimage = ((Graphics2D)g).getDeviceConfiguration().createCompatibleImage(700, 600, Transparency.OPAQUE);
    g2D = bimage.createGraphics();
    g2D.setFont(font);
    for(Wall wall: walls){
        wall.paint(g2D);
    }
    g2D.setColor(Color.orange);
    paddle.paint(g2D);
    g2D.drawString(score + "", 150,50);
    g2D.drawString("record: "+topscore  , 350,50);
    g2D.setColor(Color.red);
    ball.paint(g2D);
    g.drawImage(bimage,0,0,this);
}

But this doesn't seem to remove the flickering. I think somehow the screen is cleared before the bufferedimage starts being painted.
Can anyone help me with solving this problem?
thanks!


问:
Fastest way to get all the points between two (X,Y) coordinates in python
So I have a shapely LineString:

```<code>print np.round(shapely_intersecting_lines.coords).astype(np.int)
>>> array([[ 1520, -1140],
           [ 1412,  -973]])
</code>```

This can be interpreted as a numpy array as well as seen above.

I want to get all the points in between, that is I want to get the points of the line in between as integer values. The output should be something like this:

```<code>array([[ 1520, -1140],
       [ 1519, -1139],
       [ 1519, -1138],
       ...,
       [ 1413,  -975],
       [ 1412,  -974],
       [ 1412,  -973]], dtype=int32)
</code>```

I posted this earlier in gis.stackexchange hoping there was a solution in shapely that was efficient. The solution was good at first, however, the solution is now too slow as I run this over 50000 times in my code. On my computer each loop takes about 0.03s resulting in over a day of running. It is too slow for what I need here and was hoping to see if anyone knows of a vectorized solution to this.

答:
Using generators so that way you will save memory</p>

```<code>import numpy as np
import math

d = np.array(
    [
        [1520,-1140],
        [1412,-973]
    ],dtype=float);
rise = d[0,1]-d[1,1];
run = d[0,0]-d[1,0];
slope = rise/run;
print slope

fromPt = d[0];
sign = 1
if (slope<0):
    sign = -1;
points = ([d[0,0]+sign*i,math.floor(d[0,1]+(sign*i*slope))] for i in xrange(1+int(math.ceil(abs(d[0,0]-d[1,0])))))
for pt in points:
    print pt
</code>```

Body:
So I have a shapely LineString:

print np.round(shapely_intersecting_lines.coords).astype(np.int)
>>> array([[ 1520, -1140],
           [ 1412,  -973]])

This can be interpreted as a numpy array as well as seen above.

I want to get all the points in between, that is I want to get the points of the line in between as integer values. The output should be something like this:

array([[ 1520, -1140],
       [ 1519, -1139],
       [ 1519, -1138],
       ...,
       [ 1413,  -975],
       [ 1412,  -974],
       [ 1412,  -973]], dtype=int32)

I posted this earlier in gis.stackexchange hoping there was a solution in shapely that was efficient. The solution was good at first, however, the solution is now too slow as I run this over 50000 times in my code. On my computer each loop takes about 0.03s resulting in over a day of running. It is too slow for what I need here and was hoping to see if anyone knows of a vectorized solution to this.

Body:
Using generators so that way you will save memory

import numpy as np
import math

d = np.array(
    [
        [1520,-1140],
        [1412,-973]
    ],dtype=float);
rise = d[0,1]-d[1,1];
run = d[0,0]-d[1,0];
slope = rise/run;
print slope

fromPt = d[0];
sign = 1
if (slope<0):
    sign = -1;
points = ([d[0,0]+sign*i,math.floor(d[0,1]+(sign*i*slope))] for i in xrange(1+int(math.ceil(abs(d[0,0]-d[1,0])))))
for pt in points:
    print pt


问:
Why does scipy stats describe does not have median?
It might be a naive question but I couldn't find a reasonable answer. Why the median is not included in the return of stats.describe ? Even kurtosis is included but why not median ?

Thanks

答: I cannot speak for the scipy stats.describe people, but the general answer is this: mean, variance, and even kurtosis can be computed in one or two O(n) passes through the data, while median requires an O(n*log(n)) sort.</p>


答:
Here's Bresenhams line algorithm as a generator.  If you want a list just call list() on the output:</p>

```<code>def line(x0, y0, x1, y1):
    deltax = x1-x0
    dxsign = int(abs(deltax)/deltax)
    deltay = y1-y0
    dysign = int(abs(deltay)/deltay)
    deltaerr = abs(deltay/deltax)
    error = 0
    y = y0
    for x in range(x0, x1, dxsign):
        yield x, y
        error = error + deltaerr
        while error >= 0.5:
            y += dysign
            error -= 1
    yield x1, y1
</code>```

Title: Fastest way to get all the points between two (X,Y) coordinates in python

Body:
Here's Bresenhams line algorithm as a generator.  If you want a list just call list() on the output:

def line(x0, y0, x1, y1):
    deltax = x1-x0
    dxsign = int(abs(deltax)/deltax)
    deltay = y1-y0
    dysign = int(abs(deltay)/deltay)
    deltaerr = abs(deltay/deltax)
    error = 0
    y = y0
    for x in range(x0, x1, dxsign):
        yield x, y
        error = error + deltaerr
        while error >= 0.5:
            y += dysign
            error -= 1
    yield x1, y1


问:
EditText remove black underline while typing
I have bit of an issue in my EditText.

I have a piece of code that detects when a specific piece of text is underlined (so that a underline icon can be highlighted). This is achieved by detecting UnderlineSpans. However when typing there are underlines under the current word, which appears to also use UnderlineSpans, therefore leading the underline icon being selected:
https://i.stack.imgur.com/jBloM.jpg

I've already tried adding android:inputType="textNoSuggestions" to my EditText XML. However this appears to disable spell checking, but not the black underline. Is there anyway to remove this underline (preferably without removing spell checking) or an alternative for me to detect my own UnderlineSpans?

答:
Managed to fix it in my case. I created an empty UnderlineSpan class. e.g.

```<code>public class CustomUnderlineSpan extends UnderlineSpan {
}
</code>```

I then used this in my span setting and detection code. This meant that all my additional underline spans were now using this class, so the icon was only selected when one of my custom underline spans is present. The underline from Android is still there, but it isn't a problem for me in this case.

Body:
Managed to fix it in my case. I created an empty UnderlineSpan class. e.g.

public class CustomUnderlineSpan extends UnderlineSpan {
}

I then used this in my span setting and detection code. This meant that all my additional underline spans were now using this class, so the icon was only selected when one of my custom underline spans is present. The underline from Android is still there, but it isn't a problem for me in this case.


问:
Returning array from method in model in Ruby on Rails 3
I've got a method that caclulates an amount of roylaties owed to an author.

It works like this:

```<code>calculate_royalty(object_id)
</code>```

Right now, I'm using it in a view and looping through each individual author's products and spitting out a number. Like this:

```<code><%= @author.products.each do |product| %>
  <%= @author.calculate_royalty(product.id) %>
<% end %>
</code>```

Right now, that gives me a single number. What I've been trying to do is load all of those numbers into an array in my model so I can total them. I trid this:

```<code>def total_author_royalties
   products do |p|
    calculate_royalty(p.id)
   end
end
</code>```

But the array just returns as a hash of the product objects for that author. I figured once I have the values in the array, I can use Array.inject to add them all up.

答:
Well, if calculate_royalty just returns a number, then in your loop you are not assigning it to anything, it just returns and disappears.  Try pushing each royalty into an array and summing them at the end like so:

```<code>def total_author_royalties
   royalties = []
   products.each do |p|
     royalties << calculate_royalty(p.id)
   end
   royalties.sum
end
</code>```

or a more concise version:

```<code>def total_author_royalties
  products.map{|p| calculate_royalty(p.id)}.sum
end
</code>```

Body:
I've got a method that caclulates an amount of roylaties owed to an author.

It works like this:

calculate_royalty(object_id)

Right now, I'm using it in a view and looping through each individual author's products and spitting out a number. Like this:

<%= @author.products.each do |product| %>
  <%= @author.calculate_royalty(product.id) %>
<% end %>

Right now, that gives me a single number. What I've been trying to do is load all of those numbers into an array in my model so I can total them. I trid this:

def total_author_royalties
   products do |p|
    calculate_royalty(p.id)
   end
end

But the array just returns as a hash of the product objects for that author. I figured once I have the values in the array, I can use Array.inject to add them all up.

Body:
Well, if calculate_royalty just returns a number, then in your loop you are not assigning it to anything, it just returns and disappears.  Try pushing each royalty into an array and summing them at the end like so:

def total_author_royalties
   royalties = []
   products.each do |p|
     royalties << calculate_royalty(p.id)
   end
   royalties.sum
end

or a more concise version:

def total_author_royalties
  products.map{|p| calculate_royalty(p.id)}.sum
end


问:
I'm trying to read a .csv file into my sas terminal but it will only display the first row of observations
enter image description hereI'm reading a .csv file into my sas terminal using infile, but for some reason it will not display anything past my first row of observations. Here is my code:</p>

```<code>data fines;
        infile '/home/scf-09/ianscott/Acct493/Project/dataset1.csv'
                firstobs = 1
                truncover DSD
        ;
        length
                Parent $15
                Year $4
                Penalty $11
                Subtraction $10
                Net $11
                Agency $20
                Primary $20
                Secondary $20
                Country $15
                Industry $20
        ;
informat Parent Year Penalty Subtraction Net Agency Primary Secondary Country Industry 10.;
        input
                Parent $
                Year
                Penalty
                Subtraction
                Net
                Agency $
                Primary $
                Secondary $
                Country $
                Industry $;
run;

proc print data=fines(obs=5);
        title 'fines data';
run;

1 Bank of America 2011 20000000 0 20000000 Justice Department C mortgage abuses Servicemembers Civil USA financial services
</code>```

答:
If you created the CSV file using Excel on a MAC then it has a nasty habit of using CR ('0D'x) as the end of line character.  Apparently Excel never got the message that MacOS is now based on Unix and so uses LF ('0A'x) as the end of line character and not CR like the original MacOS did back in the 1980's.

You should be able to pick a different file type when you save it to make it NOT do that.

You can tell SAS how to read a file that is using just CR as the end of line marker by adding the TERMSTR= option to the INFILE statement.

```<code>infile '/home/scf-09/ianscott/Acct493/Project/dataset1.csv'
  firstobs = 1
  termstr=CR
  truncover
  DSD
;
</code>```

Body:
enter image description hereI'm reading a .csv file into my sas terminal using infile, but for some reason it will not display anything past my first row of observations. Here is my code:

data fines;
        infile '/home/scf-09/ianscott/Acct493/Project/dataset1.csv'
                firstobs = 1
                truncover DSD
        ;
        length
                Parent $15
                Year $4
                Penalty $11
                Subtraction $10
                Net $11
                Agency $20
                Primary $20
                Secondary $20
                Country $15
                Industry $20
        ;
informat Parent Year Penalty Subtraction Net Agency Primary Secondary Country Industry 10.;
        input
                Parent $
                Year
                Penalty
                Subtraction
                Net
                Agency $
                Primary $
                Secondary $
                Country $
                Industry $;
run;

proc print data=fines(obs=5);
        title 'fines data';
run;

1 Bank of America 2011 20000000 0 20000000 Justice Department C mortgage abuses Servicemembers Civil USA financial services

Body:
If you created the CSV file using Excel on a MAC then it has a nasty habit of using CR ('0D'x) as the end of line character.  Apparently Excel never got the message that MacOS is now based on Unix and so uses LF ('0A'x) as the end of line character and not CR like the original MacOS did back in the 1980's.

You should be able to pick a different file type when you save it to make it NOT do that.

You can tell SAS how to read a file that is using just CR as the end of line marker by adding the TERMSTR= option to the INFILE statement.

infile '/home/scf-09/ianscott/Acct493/Project/dataset1.csv'
  firstobs = 1
  termstr=CR
  truncover
  DSD
;


问:
Is it allowed to access memory that spans the zero boundary in x86?
Is it allowed for a single access to span the bounary between 0 and 0xFFFFFF... in x861?

For example given that eax (rax in 64-bit) is zero, is the following access allowed:

```<code>mov ebx, DWORD [eax - 2]
</code>```

I'm interested in both x86 (32-bit) and x86-64 in case the answers are different.

1 Of course given that the region is mapped in your process etc.

答:
I just tested with this EFI program. (And it worked, as expected.) If you want to reproduce this result, you would need an implementation of efi_printf, or another way to view the result.

```<code>#include <stdint.h>
#include "efi.h"

uint8_t *p = (uint8_t *)0xfffffffffffffffcULL;

int main()
{
    uint64_t cr3;
    asm("mov %%cr3, %0" : "=r"(cr3));
    uint64_t *pml4 = (uint64_t *)(cr3 & ~0xfffULL);

    efi_printf("cr3 %lx\n", cr3);
    efi_printf("pml4[0] %lx\n", pml4[0]);
    uint64_t *pdpt = (uint64_t *)(pml4[0] & ~0xfffULL);
    efi_printf("pdpt[0] %lx\n", pdpt[0]);
    if (!(pdpt[0] & 1)) {
        pdpt[0] = (uint64_t)efi_alloc_pages(EFI_BOOT_SERVICES_DATA, 1) | 0x03;
        efi_printf("pdpt[0] %lx\n", pdpt[0]);
    }
    uint64_t *pd = (uint64_t *)(pdpt[0] & ~0xfffULL);
    efi_printf("pd[0] %lx\n", pd[0]);
    if (!(pd[0] & 1)) {
        pd[0] = (uint64_t)efi_alloc_pages(EFI_BOOT_SERVICES_DATA, 1) | 0x03;
        efi_printf("pd[0] %lx\n", pd[0]);
    }
    if (!(pd[0] & 0x80)) {
        uint64_t *pt = (uint64_t *)(pd[0] & ~0xfffULL);
        efi_printf("pt[0] %lx\n", pt[0]);
        if (!(pt[0] & 1)) {
            pt[0] = (uint64_t)efi_alloc_pages(EFI_BOOT_SERVICES_DATA, 1) | 0x03;
            efi_printf("pt[0] %lx\n", pt[0]);
        }
    }

    efi_printf("[0] = %08x\n", *(uint32_t *)(p+4));

    efi_printf("pml4[0x1ff] %lx\n", pml4[0x1ff]);
    if (pml4[0x1ff] == 0) {

        uint64_t *pt = (uint64_t *)efi_alloc_pages(EFI_BOOT_SERVICES_DATA, 4);
        uint64_t x = (uint64_t)pt;

        efi_printf("pt = %p\n", pt);

        pml4[0x1ff] = x | 0x3;
        pt[0x1ff] = x + 0x1000 | 0x3;
        pt[0x3ff] = x + 0x2000 | 0x3;
        pt[0x5ff] = x + 0x3000 | 0x3;

        *(uint32_t *)p = 0xabcdabcd;
        *(uint32_t *)(p + 4) = 0x12341234;

        efi_printf("[0] = %08x\n", *(uint32_t *)(p+4));
        efi_printf("[fffffffffffc] = %08x\n", *(uint32_t *)(x + 0x3ffc));

        *(uint32_t *)(p + 2) = 0x56785678;

        efi_printf("p[0] = %08x\n", ((uint32_t *)p)[0]);
        efi_printf("p[1] = %08x\n", ((uint32_t *)p)[1]);
    }

    return 0;
}
</code>```

If it works as expected, the last 4 lines should be:

```<code>[0] = 12341234
[fffffffffffc] = ABCDABCD
p[0] = 5678ABCD
p[1] = 12345678
</code>```

A value of 0x56785678 is written starting in the last 16-bit word of memory and should wrap to the first 16-bit word of memory.

Note: p needed to be a global variable, otherwise GCC changed *(p+4) into ud2

Body:
Is it allowed for a single access to span the bounary between 0 and 0xFFFFFF... in x861?

For example given that eax (rax in 64-bit) is zero, is the following access allowed:

mov ebx, DWORD [eax - 2]

I'm interested in both x86 (32-bit) and x86-64 in case the answers are different.

1 Of course given that the region is mapped in your process etc.

Body:
I just tested with this EFI program. (And it worked, as expected.) If you want to reproduce this result, you would need an implementation of efi_printf, or another way to view the result.

#include <stdint.h>
#include "efi.h"

uint8_t *p = (uint8_t *)0xfffffffffffffffcULL;

int main()
{
    uint64_t cr3;
    asm("mov %%cr3, %0" : "=r"(cr3));
    uint64_t *pml4 = (uint64_t *)(cr3 & ~0xfffULL);

    efi_printf("cr3 %lx\n", cr3);
    efi_printf("pml4[0] %lx\n", pml4[0]);
    uint64_t *pdpt = (uint64_t *)(pml4[0] & ~0xfffULL);
    efi_printf("pdpt[0] %lx\n", pdpt[0]);
    if (!(pdpt[0] & 1)) {
        pdpt[0] = (uint64_t)efi_alloc_pages(EFI_BOOT_SERVICES_DATA, 1) | 0x03;
        efi_printf("pdpt[0] %lx\n", pdpt[0]);
    }
    uint64_t *pd = (uint64_t *)(pdpt[0] & ~0xfffULL);
    efi_printf("pd[0] %lx\n", pd[0]);
    if (!(pd[0] & 1)) {
        pd[0] = (uint64_t)efi_alloc_pages(EFI_BOOT_SERVICES_DATA, 1) | 0x03;
        efi_printf("pd[0] %lx\n", pd[0]);
    }
    if (!(pd[0] & 0x80)) {
        uint64_t *pt = (uint64_t *)(pd[0] & ~0xfffULL);
        efi_printf("pt[0] %lx\n", pt[0]);
        if (!(pt[0] & 1)) {
            pt[0] = (uint64_t)efi_alloc_pages(EFI_BOOT_SERVICES_DATA, 1) | 0x03;
            efi_printf("pt[0] %lx\n", pt[0]);
        }
    }

    efi_printf("[0] = %08x\n", *(uint32_t *)(p+4));

    efi_printf("pml4[0x1ff] %lx\n", pml4[0x1ff]);
    if (pml4[0x1ff] == 0) {

        uint64_t *pt = (uint64_t *)efi_alloc_pages(EFI_BOOT_SERVICES_DATA, 4);
        uint64_t x = (uint64_t)pt;

        efi_printf("pt = %p\n", pt);

        pml4[0x1ff] = x | 0x3;
        pt[0x1ff] = x + 0x1000 | 0x3;
        pt[0x3ff] = x + 0x2000 | 0x3;
        pt[0x5ff] = x + 0x3000 | 0x3;

        *(uint32_t *)p = 0xabcdabcd;
        *(uint32_t *)(p + 4) = 0x12341234;

        efi_printf("[0] = %08x\n", *(uint32_t *)(p+4));
        efi_printf("[fffffffffffc] = %08x\n", *(uint32_t *)(x + 0x3ffc));

        *(uint32_t *)(p + 2) = 0x56785678;

        efi_printf("p[0] = %08x\n", ((uint32_t *)p)[0]);
        efi_printf("p[1] = %08x\n", ((uint32_t *)p)[1]);
    }

    return 0;
}

If it works as expected, the last 4 lines should be:

[0] = 12341234
[fffffffffffc] = ABCDABCD
p[0] = 5678ABCD
p[1] = 12345678

A value of 0x56785678 is written starting in the last 16-bit word of memory and should wrap to the first 16-bit word of memory.

Note: p needed to be a global variable, otherwise GCC changed *(p+4) into ud2