问:
d3 v4 nested data and stacked bar chart
I am trying to make a chart that looks like this:

I have a D3.nest data structure that looks like this:

```<code>{"key":"Area 1","values":[
    {"key":"5. Validation Complete","value":12.5},
    {"key":"Deferred","value":1},
    {"key":"3. Identify & Validate Proposed Solutions","value":5},
    {"key":"1. Define & Describe the Problem or Opportunity","value":0}]},
{"key":"Area 2","values":[
    {"key":"5. Validation Complete","value":41.2},
    {"key":"4. Implement the Solutions","value":86.6},
    {"key":"3. Identify & Validate Proposed Solutions","value":6},
    {"key":"2. Identify Root Causes","value":4},
    {"key":"1. Define & Describe the Problem or Opportunity","value":9}]},
{"key":"Area 3","values":[
    {"key":"5. Validation Complete","value":40},
    {"key":"4. Implement the Solutions","value":49.2},
    {"key":"3. Identify & Validate Proposed Solutions","value":10.4}]},
{"key":"Area 4","values":[
    {"key":"Deferred","value":0.25},
    {"key":"4. Implement the Solutions","value":28},
    {"key":"3. Identify & Validate Proposed Solutions","value":84.9},
    {"key":"2. Identify Root Causes","value":0}]}
</code>```

My zKeys is structured as:

I have unsuccessfully tried Bostock's Stacked Bar Chart Example and this SO  post.

Here is my code:

```<code>    var svg = d3.select("svg"),
    margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom;

var x = d3.scaleBand().rangeRound([0, width]).padding(0.1);
var y = d3.scaleLinear().rangeRound([height, 0]);
var z = d3.scaleOrdinal().range(["#F8A11E", "#E51F36", "#582C85", "#1C92D0", "#017165", "#7F7F7F"]);

var g = svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var sharepointStatusArray = getListData("Points List","ID,Title,Color_Code");
var data=getListData("Points%20List","$select=Area,StatusID,Points,Status/Title&$expand=Status");

var zKeys = [];

sharepointStatusArray.forEach(function(d)
 {
    zKeys.push(d.Title);
 });

var nestData = d3.nest()
    .key(function(d) { return d.Area; })
    .key(function(d) { return d.Status.Title; })
    .rollup(function(v) { return d3.sum(v, function(d) { return d.Points; }); })
    .entries(data);

    nestData.sort(function(a,b) {return b.total - a.total;});
    x.domain(nestData.map(function(d) { return d.key; }));
    y.domain([0, d3.max(nestData, function(d){return d3.sum(d.values, function(d){return d.value})})+20]).nice();
    z.domain(zKeys)

  g.append("g")
    .selectAll(".serie")
    .data(d3.stack().keys(zKeys)(nestData))
    .enter().append("g")
        .attr("class","serie")
        .selectAll("rect")
        .data(function(d) { return d; })
        .enter().append("rect")
            .attr("class", "bar")
            .attr("fill", function(d) { return z(d.key);})
            .attr("x", function(d) {return x(d.data.key);})
            .attr("y", function(d) {return y(d[1]);})
            .attr("height", function(d) { return y(d[0]) - y(d[1]); })
            .attr("width", x.bandwidth());

  g.append("g")
    .attr("class", "axis axis--x")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

  g.append("g")
      .attr("class", "axis")
      .call(d3.axisLeft(y).ticks(null, "s"))
    .append("text")
      .attr("x", 2)
      .attr("y", y(y.ticks().pop()) + 0.5)
      .attr("dy", "0.32em")
      .attr("fill", "#000")
      .attr("font-weight", "bold")
      .attr("text-anchor", "start")
      .text("Hours");

    //Creating legend for colors
      var legend = g.append("g")
      .attr("font-family", "sans-serif")
      .attr("font-size", 10)
      .attr("text-anchor", "end")
    .selectAll("g")
    .data(zKeys.slice())
    .enter().append("g")
      .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

  legend.append("rect")
      .attr("x", width - 19)
      .attr("width", 19)
      .attr("height", 19)
      .attr("fill", z);

  legend.append("text")
      .attr("x", width - 24)
      .attr("y", 9.5)
      .attr("dy", "0.32em")
      .text(function(d) { return d; });
</code>```

I cannot get the stacked bar chart to draw according to the examples. Almost every example out there for this uses d3.csv and not d3.nest so I am at a loss as to how those examples translate to a d3.nest scenario with an output array.

Can anyone please help me out? Thanks.

答:
I ended up finding the answer to my own question.
One of the things I discovered was that all the information I found that dealt with d3.stack() stated that the data that was sent to the function needed to be 2D (2 dimensional). This was something that d3.nest() outputs nicely. This turned out to not be accurate.
I should have done this from the beginning, but I debugged the example Mike Bostock’s Stacked Bar Chart and discovered that the output of d3.csv() that everyone uses in their examples actually outputs a 1D array with each element containing key/value pairs of the data to be displayed in each rect.

I've probably made a very roundabout way of doing it, but here is what I did to solve my problem of not having the right data structure for d3.stack().

1) I kept my usage of d3.nest() output because it allowed me to sum up individual values into single key/value pairs for each element like this:

2) I then sanitized that data output using the following code to get it to look like the output of the d3.csv() in all the examples (adding key/value defaults for missing data and flattening the structure:

```<code>//BEGIN data cleanup for d3.stack
//Add default values for missing data points to make each array formatted the same
    nestData = nestData.map(function(keyObj) {
        return {
            key: keyObj.key,
            values: zKeys.map(function(k) {
                    value = keyObj.values.filter(function(v) { return v.key == k; })[0];
                    return value || ({key: k, value: 0});
                })
        };
    });

//Loop through the nested array and create a new array element that converts each individual nested element into a key/value pair in a single object.
var flatData = [];
nestData.forEach(function(d) {
    var obj = { Area: d.key }
        d.values.forEach(function(f) {
            obj[f.key] = f.value;
        });
    flatData.push(obj);
  });
//END data cleanup for d3.stack
</code>```

The data now looked like this:

3) After the data sanitizing I was then able to use the code from Mike's example out of the box like so:

```<code>    x.domain(flatData.map(function(d) { return d.Area; }));
    y.domain([0, d3.max(nestData, function(d){return d3.sum(d.values, function(d){return d.value})})+20]);
    z.domain(zKeys)

var g = svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  g.append("g")
    .selectAll("g")
    .data(d3.stack().keys(zKeys)(flatData))
    .enter().append("g")
      .attr("fill", function(d) { return z(d.key); })
    .selectAll("rect")
    .data(function(d) { return d; })
    .enter().append("rect")
      .attr("x", function(d) { return x(d.data.Area); })
      .attr("y", function(d) { return y(d[1]); })
      .attr("height", function(d) { return y(d[0]) - y(d[1]); })
      .attr("width", x.bandwidth());
</code>```

Title: d3 v4 nested data and stacked bar chart

Body:
I am trying to make a chart that looks like this:

I have a D3.nest data structure that looks like this:

{"key":"Area 1","values":[
    {"key":"5. Validation Complete","value":12.5},
    {"key":"Deferred","value":1},
    {"key":"3. Identify & Validate Proposed Solutions","value":5},
    {"key":"1. Define & Describe the Problem or Opportunity","value":0}]},
{"key":"Area 2","values":[
    {"key":"5. Validation Complete","value":41.2},
    {"key":"4. Implement the Solutions","value":86.6},
    {"key":"3. Identify & Validate Proposed Solutions","value":6},
    {"key":"2. Identify Root Causes","value":4},
    {"key":"1. Define & Describe the Problem or Opportunity","value":9}]},
{"key":"Area 3","values":[
    {"key":"5. Validation Complete","value":40},
    {"key":"4. Implement the Solutions","value":49.2},
    {"key":"3. Identify & Validate Proposed Solutions","value":10.4}]},
{"key":"Area 4","values":[
    {"key":"Deferred","value":0.25},
    {"key":"4. Implement the Solutions","value":28},
    {"key":"3. Identify & Validate Proposed Solutions","value":84.9},
    {"key":"2. Identify Root Causes","value":0}]}

My zKeys is structured as:

I have unsuccessfully tried Bostock's Stacked Bar Chart Example and this SO  post.

Here is my code:

    var svg = d3.select("svg"),
    margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom;

var x = d3.scaleBand().rangeRound([0, width]).padding(0.1);
var y = d3.scaleLinear().rangeRound([height, 0]);
var z = d3.scaleOrdinal().range(["#F8A11E", "#E51F36", "#582C85", "#1C92D0", "#017165", "#7F7F7F"]);

var g = svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var sharepointStatusArray = getListData("Points List","ID,Title,Color_Code");
var data=getListData("Points%20List","$select=Area,StatusID,Points,Status/Title&$expand=Status");

var zKeys = [];

sharepointStatusArray.forEach(function(d)
 {
    zKeys.push(d.Title);
 });

var nestData = d3.nest()
    .key(function(d) { return d.Area; })
    .key(function(d) { return d.Status.Title; })
    .rollup(function(v) { return d3.sum(v, function(d) { return d.Points; }); })
    .entries(data);

    nestData.sort(function(a,b) {return b.total - a.total;});
    x.domain(nestData.map(function(d) { return d.key; }));
    y.domain([0, d3.max(nestData, function(d){return d3.sum(d.values, function(d){return d.value})})+20]).nice();
    z.domain(zKeys)

  g.append("g")
    .selectAll(".serie")
    .data(d3.stack().keys(zKeys)(nestData))
    .enter().append("g")
        .attr("class","serie")
        .selectAll("rect")
        .data(function(d) { return d; })
        .enter().append("rect")
            .attr("class", "bar")
            .attr("fill", function(d) { return z(d.key);})
            .attr("x", function(d) {return x(d.data.key);})
            .attr("y", function(d) {return y(d[1]);})
            .attr("height", function(d) { return y(d[0]) - y(d[1]); })
            .attr("width", x.bandwidth());

  g.append("g")
    .attr("class", "axis axis--x")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

  g.append("g")
      .attr("class", "axis")
      .call(d3.axisLeft(y).ticks(null, "s"))
    .append("text")
      .attr("x", 2)
      .attr("y", y(y.ticks().pop()) + 0.5)
      .attr("dy", "0.32em")
      .attr("fill", "#000")
      .attr("font-weight", "bold")
      .attr("text-anchor", "start")
      .text("Hours");

    //Creating legend for colors
      var legend = g.append("g")
      .attr("font-family", "sans-serif")
      .attr("font-size", 10)
      .attr("text-anchor", "end")
    .selectAll("g")
    .data(zKeys.slice())
    .enter().append("g")
      .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

  legend.append("rect")
      .attr("x", width - 19)
      .attr("width", 19)
      .attr("height", 19)
      .attr("fill", z);

  legend.append("text")
      .attr("x", width - 24)
      .attr("y", 9.5)
      .attr("dy", "0.32em")
      .text(function(d) { return d; });

I cannot get the stacked bar chart to draw according to the examples. Almost every example out there for this uses d3.csv and not d3.nest so I am at a loss as to how those examples translate to a d3.nest scenario with an output array.

Can anyone please help me out? Thanks.

Body:
I ended up finding the answer to my own question.
One of the things I discovered was that all the information I found that dealt with d3.stack() stated that the data that was sent to the function needed to be 2D (2 dimensional). This was something that d3.nest() outputs nicely. This turned out to not be accurate.
I should have done this from the beginning, but I debugged the example Mike Bostock’s Stacked Bar Chart and discovered that the output of d3.csv() that everyone uses in their examples actually outputs a 1D array with each element containing key/value pairs of the data to be displayed in each rect.

I've probably made a very roundabout way of doing it, but here is what I did to solve my problem of not having the right data structure for d3.stack().

1) I kept my usage of d3.nest() output because it allowed me to sum up individual values into single key/value pairs for each element like this:

2) I then sanitized that data output using the following code to get it to look like the output of the d3.csv() in all the examples (adding key/value defaults for missing data and flattening the structure:

//BEGIN data cleanup for d3.stack
//Add default values for missing data points to make each array formatted the same
    nestData = nestData.map(function(keyObj) {
        return {
            key: keyObj.key,
            values: zKeys.map(function(k) {
                    value = keyObj.values.filter(function(v) { return v.key == k; })[0];
                    return value || ({key: k, value: 0});
                })
        };
    });

//Loop through the nested array and create a new array element that converts each individual nested element into a key/value pair in a single object.
var flatData = [];
nestData.forEach(function(d) {
    var obj = { Area: d.key }
        d.values.forEach(function(f) {
            obj[f.key] = f.value;
        });
    flatData.push(obj);
  });
//END data cleanup for d3.stack

The data now looked like this:

3) After the data sanitizing I was then able to use the code from Mike's example out of the box like so:

    x.domain(flatData.map(function(d) { return d.Area; }));
    y.domain([0, d3.max(nestData, function(d){return d3.sum(d.values, function(d){return d.value})})+20]);
    z.domain(zKeys)

var g = svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  g.append("g")
    .selectAll("g")
    .data(d3.stack().keys(zKeys)(flatData))
    .enter().append("g")
      .attr("fill", function(d) { return z(d.key); })
    .selectAll("rect")
    .data(function(d) { return d; })
    .enter().append("rect")
      .attr("x", function(d) { return x(d.data.Area); })
      .attr("y", function(d) { return y(d[1]); })
      .attr("height", function(d) { return y(d[0]) - y(d[1]); })
      .attr("width", x.bandwidth());


来源: stackexchange

问:
how to update command of tkinter button?
I have a function fonc(a,b,c,bool1,bool2) which takes float (a,b,c) and boolean parameters.
This function can plot different types of graphics (with matplotlib) depending on the boolean value and these graphics depend on the float value.

I'm trying to make a "graphic interface" for this function in tkinter. In this interface I could change the value of the boolean with a checkbox and float with a spinbox and a button "launch" which launches the function with the current parameters and plots in the interface.

I'll try to make it first with one checkbox and here is the problem, the function put the part command of the button launch is static. I mean that it takes the default parameter that I put and never changes even if use my checkbox to change the value of the parameter.

Here is my code, the function is testpanneau.testpanneau1 and my boolean is toutedir2:

```<code>import tkinter as tk
import testpanneau
from functools import partial

"""constantes"""
latitude = 37.77
longitude = -122.42
j = 21
m = 12
a = 2016
timezone = -8
hauteurlieu = 0.282
costheta = False
toutedir1 = False
toutedir2 = True
infonord = False
cst = 32

"""definition de la fonction de changement de booleen"""
def chgtbool1():
    print("Button clicked")
    toutedir2 = True if is_checked.get() else False
    print(toutedir2)

"""creation de ma fenetre"""
mafenetre = tk.Tk()
mafenetre.title('Test irradiance')
mafenetre.geometry('600x200')

"""definition des boolen des checkbox"""
#toutedir2
is_checked = tk.BooleanVar()
#toutedir1
#costheta
#infonord

"""creation des checkbox"""
checkbox = tk.Checkbutton(mafenetre, variable=is_checked, command=chgtbool1)

"""Création d'un widget Button (bouton Quitter)"""
Bouton1 = tk.Button(mafenetre, text = 'Quitter', command = mafenetre.destroy)

""" Création d'un widget Button (bouton Lancer)"""
BoutonLancer = tk.Button(mafenetre, text ='generer', command = partial(testpanneau.testpanneau1,latitude,longitude,j,m,a,timezone,hauteurlieu,cst,costheta,toutedir1,toutedir2,infonord))

"""Positionnement du widget avec la méthode pack()"""
checkbox.pack(side = tk.LEFT, padx = 5, pady = 7)
Bouton1.pack()
BoutonLancer.pack(side = tk.RIGHT, padx = 5, pady = 0)

""" Lancement du gestionnaire d'événements"""
mafenetre.mainloop()
</code>```

答:
Still very unsure of the goal, but this code fragment demonstrates how to update the command of a button (dynamically), which is the title of this issue.</p>

```<code>def generer() :
    Boutonint = tk.Button(mafenetre, text = 'lancer', command = someAction)
    Boutonint.pack(side = tk.RIGHT, padx = 3, pady = 0)

def noPlot():
    BoutonLancer['command'] = noPlot
    print("Making plot...")

def someAction():
    print('lancer button caused this')

"""definition de la fonction de changement de booleen"""
def chgtbool1():
    print("Button clicked")
    toutedir2 = is_checked.get()
    if toutedir2:
        BoutonLancer['command'] = generer
    else:
        BoutonLancer['command'] = noPlot
    print(toutedir2)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a function fonc(a,b,c,bool1,bool2) which takes float (a,b,c) and boolean parameters.
This function can plot different types of graphics (with matplotlib) depending on the boolean value and these graphics depend on the float value.

I'm trying to make a "graphic interface" for this function in tkinter. In this interface I could change the value of the boolean with a checkbox and float with a spinbox and a button "launch" which launches the function with the current parameters and plots in the interface.

I'll try to make it first with one checkbox and here is the problem, the function put the part command of the button launch is static. I mean that it takes the default parameter that I put and never changes even if use my checkbox to change the value of the parameter.

Here is my code, the function is testpanneau.testpanneau1 and my boolean is toutedir2:

import tkinter as tk
import testpanneau
from functools import partial

"""constantes"""
latitude = 37.77
longitude = -122.42
j = 21
m = 12
a = 2016
timezone = -8
hauteurlieu = 0.282
costheta = False
toutedir1 = False
toutedir2 = True
infonord = False
cst = 32

"""definition de la fonction de changement de booleen"""
def chgtbool1():
    print("Button clicked")
    toutedir2 = True if is_checked.get() else False
    print(toutedir2)

"""creation de ma fenetre"""
mafenetre = tk.Tk()
mafenetre.title('Test irradiance')
mafenetre.geometry('600x200')

"""definition des boolen des checkbox"""
#toutedir2
is_checked = tk.BooleanVar()
#toutedir1
#costheta
#infonord

"""creation des checkbox"""
checkbox = tk.Checkbutton(mafenetre, variable=is_checked, command=chgtbool1)

"""Création d'un widget Button (bouton Quitter)"""
Bouton1 = tk.Button(mafenetre, text = 'Quitter', command = mafenetre.destroy)

""" Création d'un widget Button (bouton Lancer)"""
BoutonLancer = tk.Button(mafenetre, text ='generer', command = partial(testpanneau.testpanneau1,latitude,longitude,j,m,a,timezone,hauteurlieu,cst,costheta,toutedir1,toutedir2,infonord))

"""Positionnement du widget avec la méthode pack()"""
checkbox.pack(side = tk.LEFT, padx = 5, pady = 7)
Bouton1.pack()
BoutonLancer.pack(side = tk.RIGHT, padx = 5, pady = 0)

""" Lancement du gestionnaire d'événements"""
mafenetre.mainloop()

Body:
Still very unsure of the goal, but this code fragment demonstrates how to update the command of a button (dynamically), which is the title of this issue.

def generer() :
    Boutonint = tk.Button(mafenetre, text = 'lancer', command = someAction)
    Boutonint.pack(side = tk.RIGHT, padx = 3, pady = 0)

def noPlot():
    BoutonLancer['command'] = noPlot
    print("Making plot...")

def someAction():
    print('lancer button caused this')

"""definition de la fonction de changement de booleen"""
def chgtbool1():
    print("Button clicked")
    toutedir2 = is_checked.get()
    if toutedir2:
        BoutonLancer['command'] = generer
    else:
        BoutonLancer['command'] = noPlot
    print(toutedir2)


问:
How to terminate a cat pipe command in shell script?
I use a command like to cat a pipe file and grep some data. A simple code such as,

```<code>temp=""
temp=$(cat file|grep "some data"| wc -c)
if [ $temp -gt 0 ]
then
    echo "I got data"
fi
</code>```

The file is a pipe(FIFO), it will output data and not stop. How can i to terminate the command of cat pipe in a finite time?

答:
Another way to do it is by using shell script.

```<code>cat <some file and conditions> &
< perform your task>

kill $(pidof cat)
</code>```

This works as long as you have one instance of "cat" running at a time.

Body:
I use a command like to cat a pipe file and grep some data. A simple code such as,

temp=""
temp=$(cat file|grep "some data"| wc -c)
if [ $temp -gt 0 ]
then
    echo "I got data"
fi

The file is a pipe(FIFO), it will output data and not stop. How can i to terminate the command of cat pipe in a finite time?

Body:
Another way to do it is by using shell script.

cat <some file and conditions> &
< perform your task>

kill $(pidof cat)

This works as long as you have one instance of "cat" running at a time.


问:
access netezza database with python without driver from IBM
Is there a way to query a netezza database without explicitly installing its driver? I am using ubuntu 64 bit OS, our IT support says the driver they have only works on red hat systems.</p>

答: If you can get your hands on the JDBC driver, you could use the Python, jaydebeapi module, with the driver to connect to the server. Note that there are a couple quirks involved. Namely things like boolean datatypes.


问:
Cursor: pointer; on svg element is not working
In my website i use svg elements. Sometimes i need them to be clickable, therefore i want pointer cursor over them.

However adding css class or style

```<code>cursor: pointer;
</code>```

not work.

That's the example element

```<code><object id="male2" type="image/svg+xml" data="course/ani/male2.svg" style="left: 87px; bottom: 56px;" es-character="male2"></object>
</code>```

It seems like it just not worki with svg. Anyone know how to fix, or how to go around it?

答:
One of the simplest solutions may be to use img tag instead of object tag

```<code><img src="course/ani/male2.svg" style="left: 87px; bottom: 56px;"  />
</code>```

although, ideally you can embed the svg in the html.
That doesn't let you cache the svg files, so I found using javascript to load the svg file as text and insert into the DOM allowed for caching and still got the SVG directly into the DOM so it could use all the css styles from your page.

Body:
In my website i use svg elements. Sometimes i need them to be clickable, therefore i want pointer cursor over them.

However adding css class or style

cursor: pointer;

not work.

That's the example element

<object id="male2" type="image/svg+xml" data="course/ani/male2.svg" style="left: 87px; bottom: 56px;" es-character="male2"></object>

It seems like it just not worki with svg. Anyone know how to fix, or how to go around it?

Body:
One of the simplest solutions may be to use img tag instead of object tag

<img src="course/ani/male2.svg" style="left: 87px; bottom: 56px;"  />

although, ideally you can embed the svg in the html.
That doesn't let you cache the svg files, so I found using javascript to load the svg file as text and insert into the DOM allowed for caching and still got the SVG directly into the DOM so it could use all the css styles from your page.


问:
-timestamp in Django
I'm trying to learn Django. I'm completely green so far. I'm learning from not very good book - first thing we're creating is a simple blog. So, at the end of this excersie they want me to sort my blog post - so the new posts are on top. In order to achieve that im adding:

```<code>class Meta:
    ordering = ('-timestamp',)
</code>```

in views.py. Unfortunately, it changes nothing - my posts are not moving. The book is not very descriptive about that. Do I have to register this class somewhere? I want my pseudo-blog to be pwetty! :P

Thanks in advance.

答:
Without any more information, I believe the solution to your problem is that the class Meta declaration needs to be in whatever model represents the blog entry (likely in models.py, not views.py). Also, double-check that timestamp is the name of the field in the BlogEntry class that stores the date/time of the blog entry.

```<code>class BlogEntry:
    class Meta:
        ordering = ('-timestamp',)

    #rest of the BlogEntry class
</code>```

ContentLicense: CC BY-SA 2.5

Title: -timestamp in Django

Body:
I'm trying to learn Django. I'm completely green so far. I'm learning from not very good book - first thing we're creating is a simple blog. So, at the end of this excersie they want me to sort my blog post - so the new posts are on top. In order to achieve that im adding:

class Meta:
    ordering = ('-timestamp',)

in views.py. Unfortunately, it changes nothing - my posts are not moving. The book is not very descriptive about that. Do I have to register this class somewhere? I want my pseudo-blog to be pwetty! :P

Thanks in advance.

Body:
Without any more information, I believe the solution to your problem is that the class Meta declaration needs to be in whatever model represents the blog entry (likely in models.py, not views.py). Also, double-check that timestamp is the name of the field in the BlogEntry class that stores the date/time of the blog entry.

class BlogEntry:
    class Meta:
        ordering = ('-timestamp',)

    #rest of the BlogEntry class


问:
Tomcat - running on VPS
I am trying to run tomcat 8 on my VPS (Debian 8.8) and I have the following problem:
During starting the tomcat:

```<code>sh startup.sh
Using CATALINA_BASE:   /usr/share/tomcat
Using CATALINA_HOME:   /usr/share/tomcat
Using CATALINA_TMPDIR: /usr/share/tomcat/temp
Using JRE_HOME:        /usr/local/java
Using CLASSPATH:       /usr/share/tomcat/bin/bootstrap.jar:/usr/share/tomcat/bin/tomcat-juli.jar
Tomcat started.
</code>```

everything looks ok but tomcat still doesn't work and when I want to shutdown the server I receive this information:

```<code>sh shutdown.sh
Using CATALINA_BASE:   /usr/share/tomcat
Using CATALINA_HOME:   /usr/share/tomcat
Using CATALINA_TMPDIR: /usr/share/tomcat/temp
Using JRE_HOME:        /usr/local/java
Using CLASSPATH:       /usr/share/tomcat/bin/bootstrap.jar:/usr/share/tomcat/bin/tomcat-juli.jar
./catalina.sh: 1: eval: /usr/local/java/bin/java: not found
</code>```

A few information about my environment:

```<code>java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

which java
/home/ovh/src/soft/jdk1.8.0_131/bin/java

printenv
JRE_HOME=/usr/local/java
PATH=/home/ovh/src/soft/jdk1.8.0_131/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/jdk/jdk1.8.0_131/bin
JAVA_HOME=/home/ovh/src/soft/jdk1.8.0_131
</code>```

答:
Check if the user, which you are using for tomcat, has execute rights for
:

/usr/local/java/bin/java

/usr/share/tomcat/bin/bootstrap.jar

/usr/share/tomcat/bin/tomcat-juli.jar

Title: Tomcat - running on VPS

Body:
I am trying to run tomcat 8 on my VPS (Debian 8.8) and I have the following problem:
During starting the tomcat:

sh startup.sh
Using CATALINA_BASE:   /usr/share/tomcat
Using CATALINA_HOME:   /usr/share/tomcat
Using CATALINA_TMPDIR: /usr/share/tomcat/temp
Using JRE_HOME:        /usr/local/java
Using CLASSPATH:       /usr/share/tomcat/bin/bootstrap.jar:/usr/share/tomcat/bin/tomcat-juli.jar
Tomcat started.

everything looks ok but tomcat still doesn't work and when I want to shutdown the server I receive this information:

sh shutdown.sh
Using CATALINA_BASE:   /usr/share/tomcat
Using CATALINA_HOME:   /usr/share/tomcat
Using CATALINA_TMPDIR: /usr/share/tomcat/temp
Using JRE_HOME:        /usr/local/java
Using CLASSPATH:       /usr/share/tomcat/bin/bootstrap.jar:/usr/share/tomcat/bin/tomcat-juli.jar
./catalina.sh: 1: eval: /usr/local/java/bin/java: not found

A few information about my environment:

java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

which java
/home/ovh/src/soft/jdk1.8.0_131/bin/java

printenv
JRE_HOME=/usr/local/java
PATH=/home/ovh/src/soft/jdk1.8.0_131/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/jdk/jdk1.8.0_131/bin
JAVA_HOME=/home/ovh/src/soft/jdk1.8.0_131


问:
change the background-color of every other element
I want to change the background-color of every other element in the following:

```<code><div class="dets">
 <div>Simple Layout</div>
 <div>Few Pictures/Links</div>
 <div>Element Uniformity</div>
</div>
</code>```

So the first [Simple Layout] would be white, the second [Few Pictures/Links] would be black, and so on. I have three of these structures nested in some other div elements. I know about the :even,:odd methods, but it doesn't do as expected. It continues through each of the "dets" classes, increasing the index each time. I want odd rows white, even rows black. Is there a way to restart the natural index for each "dets" class? I do not want to use a table.

I am currently using the following jQuery to set the background-color:

```<code>$(".dets div:odd").css('background-color', 'white');
$(".dets div:even").css('background-color', 'black');
</code>```

答:
It is better to use css nth-child.

You can use id instead of class .dets to decrease the index time like #dets

You can have other selector also you can use that as per your requirement: e.g.

tr:nth-child(2n+1)
Represents the odd rows of an HTML table.

tr:nth-child(odd)
Represents the odd rows of an HTML table.

tr:nth-child(2n)
Represents the even rows of an HTML table.

tr:nth-child(even)
Represents the even rows of an HTML table.

span:nth-child(0n+1)
Represents a span element which is the first child of its parent; this is the same as the :first-child selector.

span:nth-child(1)
Equivalent to the above.

span:nth-child(-n+3)
Matches if the element is one of the first three children of its parent and also a span.

.dets>div:nth-child(even){
background:#000;
color:#fff;
}

.dets>div:nth-child(odd){
background:#fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dets">
 <div>Simple Layout</div>
 <div>Few Pictures/Links</div>
 <div>Element Uniformity</div>
</div></code>```

Body:
I want to change the background-color of every other element in the following:

Simple Layout

Few Pictures/Links

Element Uniformity

So the first [Simple Layout] would be white, the second [Few Pictures/Links] would be black, and so on. I have three of these structures nested in some other div elements. I know about the :even,:odd methods, but it doesn't do as expected. It continues through each of the "dets" classes, increasing the index each time. I want odd rows white, even rows black. Is there a way to restart the natural index for each "dets" class? I do not want to use a table.

I am currently using the following jQuery to set the background-color:

$(".dets div:odd").css('background-color', 'white');
$(".dets div:even").css('background-color', 'black');

Body:
It is better to use css nth-child.

You can use id instead of class .dets to decrease the index time like #dets

You can have other selector also you can use that as per your requirement: e.g.

tr:nth-child(2n+1)
Represents the odd rows of an HTML table.

tr:nth-child(odd)
Represents the odd rows of an HTML table.

tr:nth-child(2n)
Represents the even rows of an HTML table.

tr:nth-child(even)
Represents the even rows of an HTML table.

span:nth-child(0n+1)
Represents a span element which is the first child of its parent; this is the same as the :first-child selector.

span:nth-child(1)
Equivalent to the above.

span:nth-child(-n+3)
Matches if the element is one of the first three children of its parent and also a span.

.dets>div:nth-child(even){
background:#000;
color:#fff;
}

.dets>div:nth-child(odd){
background:#fff;
}

<div class="dets">
 <div>Simple Layout</div>
 <div>Few Pictures/Links</div>
 <div>Element Uniformity</div>
</div>


问:
Loading fonts with webpack
I'm trying to use custom fonts in a Project website with angular4.

This is my Project structure

This is my webpack.config.js

```<code>const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: [ '.js', '.ts' ] },
        output: {
            filename: '[name].js',
            publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.ts$/, include: /ClientApp/, use: ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: [ 'to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' },
                // Font Definitions
                { test: /\.svg$/, loader: 'url?limit=65000&mimetype=image/svg+xml&name=font/[name].[ext]' },
                { test: /\.woff$/, loader: 'url?limit=65000&mimetype=application/font-woff&name=font/[name].[ext]' },
                { test: /\.woff2$/, loader: 'url?limit=65000&mimetype=application/font-woff2&name=font/[name].[ext]' },
                { test: /\.[ot]tf$/, loader: 'url?limit=65000&mimetype=application/octet-stream&name=font/[name].[ext]' },
                { test: /\.eot$/, loader: 'url?limit=65000&mimetype=application/vnd.ms-fontobject&name=font/[name].[ext]' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };
</code>```

This is my css with @font-face

```<code>@font-face {
    font-family: "FuturaMaxiLight";
    src: url('/fonts/FuturaMaxi/Futura-Maxi-Light.eot') format('embedded-opentype'), /*for IE */
    url('/fonts/FuturaMaxi/Futura-Maxi-Light.ttf') format('truetype'), /* for CSS3 browsers */
    url('/fonts/FuturaMaxi/Futura-Maxi-Light.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: "FuturaMaxiDemi";
    src: url('/fonts/FuturaMaxi/Futura-Maxi-Demi.eot') format('embedded-opentype'), /*for IE */
    url('/fonts/FuturaMaxi/Futura-Maxi-Demi.ttf') format('truetype'), /* for CSS3 browsers */
    url('/fonts/FuturaMaxi/Futura-Maxi-Demi.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: "FuturaMaxiBold";
    src: url('/fonts/FuturaMaxi/Futura-Maxi-Bold.eot') format('embedded-opentype'), /*for IE */
    url('/fonts/FuturaMaxi/Futura-Maxi-Bold.ttf') format('truetype'), /* for CSS3 browsers */
    url('/fonts/FuturaMaxi/Futura-Maxi-Bold.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}
</code>```

This is the error when I try like that

If I change the css and try to include a dot before the import.
1 dot gives errors.
2 dots breaks the app.

```<code>@font-face {
    font-family: "FuturaMaxiBold";
    src: url('./fonts/FuturaMaxi/Futura-Maxi-Bold.eot') format('embedded-opentype'), /*for IE */
    url('./fonts/FuturaMaxi/Futura-Maxi-Bold.ttf') format('truetype'), /* for CSS3 browsers */
    url('./fonts/FuturaMaxi/Futura-Maxi-Bold.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}
</code>```

答:
Your loaders are specifying name=font/[name].[ext] and your css is looking at /fonts/FuturaMaxi/[name].[ext].

Try changing the loaders to use name=[path][name].[ext] or name=fonts/FuturaMaxi/[name].[ext]

Title: Loading fonts with webpack

Body:
I'm trying to use custom fonts in a Project website with angular4.

This is my Project structure

This is my webpack.config.js

const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: [ '.js', '.ts' ] },
        output: {
            filename: '[name].js',
            publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.ts$/, include: /ClientApp/, use: ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: [ 'to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' },
                // Font Definitions
                { test: /\.svg$/, loader: 'url?limit=65000&mimetype=image/svg+xml&name=font/[name].[ext]' },
                { test: /\.woff$/, loader: 'url?limit=65000&mimetype=application/font-woff&name=font/[name].[ext]' },
                { test: /\.woff2$/, loader: 'url?limit=65000&mimetype=application/font-woff2&name=font/[name].[ext]' },
                { test: /\.[ot]tf$/, loader: 'url?limit=65000&mimetype=application/octet-stream&name=font/[name].[ext]' },
                { test: /\.eot$/, loader: 'url?limit=65000&mimetype=application/vnd.ms-fontobject&name=font/[name].[ext]' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

This is my css with @font-face

@font-face {
    font-family: "FuturaMaxiLight";
    src: url('/fonts/FuturaMaxi/Futura-Maxi-Light.eot') format('embedded-opentype'), /*for IE */
    url('/fonts/FuturaMaxi/Futura-Maxi-Light.ttf') format('truetype'), /* for CSS3 browsers */
    url('/fonts/FuturaMaxi/Futura-Maxi-Light.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: "FuturaMaxiDemi";
    src: url('/fonts/FuturaMaxi/Futura-Maxi-Demi.eot') format('embedded-opentype'), /*for IE */
    url('/fonts/FuturaMaxi/Futura-Maxi-Demi.ttf') format('truetype'), /* for CSS3 browsers */
    url('/fonts/FuturaMaxi/Futura-Maxi-Demi.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: "FuturaMaxiBold";
    src: url('/fonts/FuturaMaxi/Futura-Maxi-Bold.eot') format('embedded-opentype'), /*for IE */
    url('/fonts/FuturaMaxi/Futura-Maxi-Bold.ttf') format('truetype'), /* for CSS3 browsers */
    url('/fonts/FuturaMaxi/Futura-Maxi-Bold.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}

This is the error when I try like that

If I change the css and try to include a dot before the import.
1 dot gives errors.
2 dots breaks the app.

@font-face {
    font-family: "FuturaMaxiBold";
    src: url('./fonts/FuturaMaxi/Futura-Maxi-Bold.eot') format('embedded-opentype'), /*for IE */
    url('./fonts/FuturaMaxi/Futura-Maxi-Bold.ttf') format('truetype'), /* for CSS3 browsers */
    url('./fonts/FuturaMaxi/Futura-Maxi-Bold.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}


问:
Swift - Shrink Navigation Bar on scroll
I'm really stuck here. I would like to shrink the Navigation Bar when I scroll down a UITableView and enlarge it again when scrolling up. I managed to alter the size of the Navigation Bar, but the title image is not shrinking with the Navigation Bar.

I want to do it exactly like Safari, and the problem is that the height of my TitleView is shrinking but the width never changes.

Here's the code I've used to get the height of the scrollbar to change.

```<code>func scrollViewDidScroll(scrollView: UIScrollView) {
    var navbar = navigationController?.navigationBar
    var dir:CGPoint = tableview.panGestureRecognizer.translationInView(self.tableview)
    var scrollViewHeight = tableview.frame.size.height
    var scrollContentSizeHeight = tableview.contentSize.height
    var scrollOffset = tableview.contentOffset.y

    if (dir.y > 0 && self.formernavstate == "small") {
        self.formernavstate = "big"

        UIView.animateWithDuration(0.5, delay:0.0, options: UIViewAnimationOptions.AllowAnimatedContent, animations: { () -> Void in

        println("")
        navbar?.frame.origin.y = 20
        self.navigationItem.titleView?.transform = CGAffineTransformMakeScale(0.52, 0.6)
        }, completion: nil)
    }

    if (dir.y < 0 && self.formernavstate == "big") {
        self.formernavstate = "small"
        navbar?.frame.origin.y = 0
        navigationItem.titleView?.transform = CGAffineTransformMakeScale(0.0001, 0.2)
    }
}
</code>```

答:
I implemented a Swift 3 version with a custom "header" and resizing it's height constraint based on @chauhan's answer:

```<code>extension ViewController: UIScrollViewDelegate {

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollViewOffset < scrollView.contentOffset.y {
            shrinkHeader(shrink: true)
        } else if scrollViewOffset > scrollView.contentOffset.y {
            shrinkHeader(shrink: false)
        }
    }

    func shrinkHeader(shrink: Bool) {
        if shrink {
            if self.headerContainerHeightConstraint.constant > CGFloat(minHeaderHeight) {
                UIView.animate(withDuration: 0.1, animations: {
                    self.headerContainerHeightConstraint.constant = self.headerContainerHeightConstraint.constant - 2
                    self.view.layoutIfNeeded()
                })
            }
        } else {
            if self.headerContainerHeightConstraint.constant < CGFloat(maxHeaderHeight) {
                UIView.animate(withDuration: 0.1, animations: {
                    self.headerContainerHeightConstraint.constant = self.headerContainerHeightConstraint.constant + 6
                    self.view.layoutIfNeeded()
                })
            }
        }
    }
}
</code>```

Title: Swift - Shrink Navigation Bar on scroll

Body:
I'm really stuck here. I would like to shrink the Navigation Bar when I scroll down a UITableView and enlarge it again when scrolling up. I managed to alter the size of the Navigation Bar, but the title image is not shrinking with the Navigation Bar.

I want to do it exactly like Safari, and the problem is that the height of my TitleView is shrinking but the width never changes.

Here's the code I've used to get the height of the scrollbar to change.

func scrollViewDidScroll(scrollView: UIScrollView) {
    var navbar = navigationController?.navigationBar
    var dir:CGPoint = tableview.panGestureRecognizer.translationInView(self.tableview)
    var scrollViewHeight = tableview.frame.size.height
    var scrollContentSizeHeight = tableview.contentSize.height
    var scrollOffset = tableview.contentOffset.y

    if (dir.y > 0 && self.formernavstate == "small") {
        self.formernavstate = "big"

        UIView.animateWithDuration(0.5, delay:0.0, options: UIViewAnimationOptions.AllowAnimatedContent, animations: { () -> Void in

        println("")
        navbar?.frame.origin.y = 20
        self.navigationItem.titleView?.transform = CGAffineTransformMakeScale(0.52, 0.6)
        }, completion: nil)
    }

    if (dir.y < 0 && self.formernavstate == "big") {
        self.formernavstate = "small"
        navbar?.frame.origin.y = 0
        navigationItem.titleView?.transform = CGAffineTransformMakeScale(0.0001, 0.2)
    }
}

Body:
I implemented a Swift 3 version with a custom "header" and resizing it's height constraint based on @chauhan's answer:

extension ViewController: UIScrollViewDelegate {

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollViewOffset < scrollView.contentOffset.y {
            shrinkHeader(shrink: true)
        } else if scrollViewOffset > scrollView.contentOffset.y {
            shrinkHeader(shrink: false)
        }
    }

    func shrinkHeader(shrink: Bool) {
        if shrink {
            if self.headerContainerHeightConstraint.constant > CGFloat(minHeaderHeight) {
                UIView.animate(withDuration: 0.1, animations: {
                    self.headerContainerHeightConstraint.constant = self.headerContainerHeightConstraint.constant - 2
                    self.view.layoutIfNeeded()
                })
            }
        } else {
            if self.headerContainerHeightConstraint.constant < CGFloat(maxHeaderHeight) {
                UIView.animate(withDuration: 0.1, animations: {
                    self.headerContainerHeightConstraint.constant = self.headerContainerHeightConstraint.constant + 6
                    self.view.layoutIfNeeded()
                })
            }
        }
    }
}


问:
jquery ui drag easing/inertia
How do you enable easing or inertia when dragging an element using jquery ui draggable (http://jqueryui.com/demos/draggable/)?  I'd like to recreate the easing similar to maps.google.com that as you throw/drag the map it eases into place.  Ideally, I'd like to move the element move based on the force you throw/drag the element.  How do you accomplish this functionality?  Maybe jquery ui draggable isn't necessary, but I'm looking to emulate the dragging and easing found on Google Maps.

Thanks!

答:
I used some ideas from here but integrated them with jQuery UI instead.  You'll have to implement logic to handle a momentum animation that pushes the element out-of-bounds (outside it's parent container's boundaries)

The resulting code:

```<code>$(function() {
    var $d = $("#draggable");

    var x1, x2,
        y1, y2,
        t1, t2;  // Time

    var minDistance = 40; // Minimum px distance object must be dragged to enable momentum.

    var onMouseMove = function(e) {
        var mouseEvents = $d.data("mouseEvents");
        if (e.timeStamp - mouseEvents[mouseEvents.length-1].timeStamp > 40) {
            mouseEvents.push(e);
            if (mouseEvents.length > 2) {
                mouseEvents.shift();
            }
        }
    }

    var onMouseUp = function() {
        $(document).unbind("mousemove mouseup");
    }

    $d.draggable({
        start: function(e, ui) {
            $d.data("mouseEvents", [e]);
            $(document)
                .mousemove(onMouseMove)
                .mouseup(onMouseUp);
        },
        stop: function(e, ui) {
            $d.stop();
            $d.css("text-indent", 100);

            var lastE = $d.data("mouseEvents").shift();

            x1 = lastE.pageX;
            y1 = lastE.pageY;
            t1 = lastE.timeStamp;
            x2 = e.pageX;
            y2 = e.pageY;
            t2 = e.timeStamp;

            // Deltas
            var dX = x2 - x1,
                dY = y2 - y1,
                dMs = Math.max(t2 - t1, 1);

            // Speeds
            var speedX = Math.max(Math.min(dX/dMs, 1), -1),
                speedY = Math.max(Math.min(dY/dMs, 1), -1);

            // Distance moved (Euclidean distance)
            var distance = Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2));

            if (distance > minDistance) {
                // Momentum
                var lastStepTime = new Date();
                $d.animate({ textIndent: 0 }, {
                    duration: Math.max(Math.abs(speedX), Math.abs(speedY)) * 2000,
                    step: function(currentStep){
                        speedX *= (currentStep / 100);
                        speedY *= (currentStep / 100);

                        var now = new Date();
                        var stepDuration = now.getTime() - lastStepTime.getTime();

                        lastStepTime = now;

                        var position = $d.position();

                        var newLeft = (position.left + (speedX * stepDuration / 4)),
                            newTop = (position.top + (speedY * stepDuration / 4));

                        $d.css({
                            left: newLeft+"px",
                            top: newTop+"px"
                        });
                    }
                });
            }
        }
    });
});</code>```

Try it out

Title: jquery ui drag easing/inertia

Body:
I used some ideas from here but integrated them with jQuery UI instead.  You'll have to implement logic to handle a momentum animation that pushes the element out-of-bounds (outside it's parent container's boundaries)

The resulting code:

$(function() {
    var $d = $("#draggable");

    var x1, x2,
        y1, y2,
        t1, t2;  // Time

    var minDistance = 40; // Minimum px distance object must be dragged to enable momentum.

    var onMouseMove = function(e) {
        var mouseEvents = $d.data("mouseEvents");
        if (e.timeStamp - mouseEvents[mouseEvents.length-1].timeStamp > 40) {
            mouseEvents.push(e);
            if (mouseEvents.length > 2) {
                mouseEvents.shift();
            }
        }
    }

    var onMouseUp = function() {
        $(document).unbind("mousemove mouseup");
    }

    $d.draggable({
        start: function(e, ui) {
            $d.data("mouseEvents", [e]);
            $(document)
                .mousemove(onMouseMove)
                .mouseup(onMouseUp);
        },
        stop: function(e, ui) {
            $d.stop();
            $d.css("text-indent", 100);

            var lastE = $d.data("mouseEvents").shift();

            x1 = lastE.pageX;
            y1 = lastE.pageY;
            t1 = lastE.timeStamp;
            x2 = e.pageX;
            y2 = e.pageY;
            t2 = e.timeStamp;

            // Deltas
            var dX = x2 - x1,
                dY = y2 - y1,
                dMs = Math.max(t2 - t1, 1);

            // Speeds
            var speedX = Math.max(Math.min(dX/dMs, 1), -1),
                speedY = Math.max(Math.min(dY/dMs, 1), -1);

            // Distance moved (Euclidean distance)
            var distance = Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2));

            if (distance > minDistance) {
                // Momentum
                var lastStepTime = new Date();
                $d.animate({ textIndent: 0 }, {
                    duration: Math.max(Math.abs(speedX), Math.abs(speedY)) * 2000,
                    step: function(currentStep){
                        speedX *= (currentStep / 100);
                        speedY *= (currentStep / 100);

                        var now = new Date();
                        var stepDuration = now.getTime() - lastStepTime.getTime();

                        lastStepTime = now;

                        var position = $d.position();

                        var newLeft = (position.left + (speedX * stepDuration / 4)),
                            newTop = (position.top + (speedY * stepDuration / 4));

                        $d.css({
                            left: newLeft+"px",
                            top: newTop+"px"
                        });
                    }
                });
            }
        }
    });
});

Try it out


问:
How to make the java wait for x seconds and then execute
I making an app and I would run in to a problem that I can't fix.
I am using Android Studio and I need to make a Button that I have already made. Do more then it already does. I want it to after display a text also close the app. Do you know how I should program that. It would be very helpful. Thanks in advance.

Here is the Java code:

```<code>package test.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void buttonOnClick(View v) {
    Button button=(Button) v;
    ((Button) v).setText("Correct");
}

public void buttonAnClick(View q) {
    Button button=(Button) q;
    ((Button) q).setText("Niet goed");
}
</code>```

}

So I have already made the button in XML and told it:

android:onClick="buttonOnClick"

Hope you can help me out!

答:
Check out CountDownTimer</p>

```<code>CountDownTimer(30000, 1000) {

             public void onTick(long millisUntilFinished) {
                 mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
             }

         public void onFinish() {
             mTextField.setText("done!");
         }
      }.start();
</code>```

Body:
I making an app and I would run in to a problem that I can't fix.
I am using Android Studio and I need to make a Button that I have already made. Do more then it already does. I want it to after display a text also close the app. Do you know how I should program that. It would be very helpful. Thanks in advance.

Here is the Java code:

package test.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void buttonOnClick(View v) {
    Button button=(Button) v;
    ((Button) v).setText("Correct");
}

public void buttonAnClick(View q) {
    Button button=(Button) q;
    ((Button) q).setText("Niet goed");
}

}

So I have already made the button in XML and told it:

android:onClick="buttonOnClick"

Hope you can help me out!

Body:
Check out CountDownTimer

CountDownTimer(30000, 1000) {

             public void onTick(long millisUntilFinished) {
                 mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
             }

         public void onFinish() {
             mTextField.setText("done!");
         }
      }.start();


问:
Can I delay jQuery addClass?
Is there a way to delay the addClass() of jQuery? For example this code

```<code>$('#sampleID').delay(2000).fadeOut(500).delay(2000).addClass('aNewClass');
</code>```

When I load the page, it has the class 'aNewClass' already on id 'sampleID'. How to solve this problem? What I want is the addClass will happen after it ended the fadeOut().

答:
You can also use setTimeout, with CSS transition :

```<code>setTimeout(function() {
    $('#sampleID').addClass('aNewClass');
}, 2000);
</code>```

And the CSS

```<code>#sampleID {
transition: opacity 1s ease;
opacity: 0;
}

#sampleID.aNewClass {
opacity: 1;
}
</code>```

Title: Can I delay jQuery addClass?

Body:
Is there a way to delay the addClass() of jQuery? For example this code

$('#sampleID').delay(2000).fadeOut(500).delay(2000).addClass('aNewClass');

When I load the page, it has the class 'aNewClass' already on id 'sampleID'. How to solve this problem? What I want is the addClass will happen after it ended the fadeOut().

Body:
You can also use setTimeout, with CSS transition :

setTimeout(function() {
    $('#sampleID').addClass('aNewClass');
}, 2000);

And the CSS

#sampleID {
transition: opacity 1s ease;
opacity: 0;
}

#sampleID.aNewClass {
opacity: 1;
}


问:
Variable name from template argument?
Is there any way to generate the name of a variable inside a class based on a template argument?

```<code>template<class T, (someconstruct) t>

class Item {
    public:
        T t;
};

Item<float, "Position"> myItem;

myItem.Position = 0.123f;
</code>```

Such that what I have instantiated is a variable of type T, with the identifier t (where t is passed in by the programmer, i.e. Position, so we have a T called Position? Or is this stretching the template meta-programming concept a little too far? :p

答:
No, you can't achieve this with templates.  Variable names (known as "identifiers") cannot be programatically manipulated by templates.  Only the preprocessor can do that.

Regardless, this seems like a bad idea.  Why do you want to do this?

Title: Variable name from template argument?

Body:
Is there any way to generate the name of a variable inside a class based on a template argument?

template<class T, (someconstruct) t>

class Item {
    public:
        T t;
};

Item<float, "Position"> myItem;

myItem.Position = 0.123f;

Such that what I have instantiated is a variable of type T, with the identifier t (where t is passed in by the programmer, i.e. Position, so we have a T called Position? Or is this stretching the template meta-programming concept a little too far? :p


答:
If you're looking to have something happen afterwards what you're looking for is this:

```<code>        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                //What you want to happen later
            }
        }, 1500); //1500 = 1.5 seconds, time in milli before it happens.
</code>```

Put that in your button's method.

If you want to close your app you should call

```<code>      finish();
</code>```

Finish closes out the current activity. If you have other activities on the stack you'd return to them but since you likely only have 1 it should take you out.

Title: How to make the java wait for x seconds and then execute

Body:
If you're looking to have something happen afterwards what you're looking for is this:

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                //What you want to happen later
            }
        }, 1500); //1500 = 1.5 seconds, time in milli before it happens.

Put that in your button's method.

If you want to close your app you should call

      finish();

Finish closes out the current activity. If you have other activities on the stack you'd return to them but since you likely only have 1 it should take you out.


问:
Remove Black background from Alert Dialog Box - Android
I am working on an Android Application , Here I have created a custom dialog box , The dialog box was appearing on complete height of the device , but I wanted to leave margins from top and bottom , so I set margin using below code

```<code>  WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(alertDialog.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
    lp.height = Utility.convertDPtoPixel(400, screen);

    alertDialog.show();
    alertDialog.getWindow().setAttributes(lp);
</code>```

Above code worked perfectly, but the dialog appears with black surroundings.

Here is the screen shot:

Now I want to remove these black surroundings from the dialog box.

Here is the code of dialog box:

```<code>public void showDialog() {
    AlertDialog.Builder builder;
    final AlertDialog alertDialog;
    //final Dialog alertDialog;
    Context mContext;
    mContext = screen;
    LayoutInflater inflater = (LayoutInflater) LoginActivity.screen.getSystemService(LoginActivity.screen.LAYOUT_INFLATER_SERVICE);
    layout = inflater.inflate(R.layout.countrylist, null);
    LinearLayout rellayout = (LinearLayout) layout.findViewById(R.id.rellayout);

    RelativeLayout closeAcessCodeDialog = (RelativeLayout)layout.findViewById(R.id.closeAcessCodeDialog) ;

    ListView listview = (ListView) layout.findViewById(R.id.listview);
    listview.setAdapter(new CustomAdapter1(LoginActivity.screen, countryList));

    builder = new AlertDialog.Builder(LoginActivity.screen);
    builder.setView(layout);
    alertDialog = builder.create();
    alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(alertDialog.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
    lp.height = Utility.convertDPtoPixel(400, screen);

    alertDialog.show();
    alertDialog.getWindow().setAttributes(lp);

    listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int pos,
                                long id) {
            countryName = idCountry.get(pos);
            System.out.println("Country code is: " + countryName);
            alertDialog.cancel();
            text.setText(countryList.get(pos));
        }
    });

    closeAcessCodeDialog.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            alertDialog.dismiss();
        }
    });

}
</code>```

countrylist.xml

```<code> <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#ffe264"
    app:cardCornerRadius="10dp"
    >

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/rellayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_above="@+id/listview"
            android:gravity="center_vertical"
            >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Select your Country"
                android:textColor="#000"
                android:textSize="18sp"
                android:textStyle="bold"
                android:layout_centerInParent="true"
                />

            <RelativeLayout
                android:id="@+id/closeAcessCodeDialog"
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_alignParentRight="true"
                android:gravity="center">

                <ImageButton
                    android:id="@+id/closeDialog"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:background="@drawable/close_country_dialog" />

            </RelativeLayout>
        </RelativeLayout>

        <ListView
            android:id="@+id/listview"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:cacheColorHint="@android:color/transparent"
            android:divider="#e5e5e5"
            android:background="@drawable/list_bacground"
            android:dividerHeight="1px" />

    </LinearLayout>
</code>```

I visited many similar links over stackoverflow , but no one was helpfull .

答:
Try this.</p>

```<code>Dialog alertDialog = new Dialog(this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.yourlayout);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
alertDialog.show();
</code>```

Body:
I am working on an Android Application , Here I have created a custom dialog box , The dialog box was appearing on complete height of the device , but I wanted to leave margins from top and bottom , so I set margin using below code

  WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(alertDialog.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
    lp.height = Utility.convertDPtoPixel(400, screen);

    alertDialog.show();
    alertDialog.getWindow().setAttributes(lp);

Above code worked perfectly, but the dialog appears with black surroundings.

Here is the screen shot:

Now I want to remove these black surroundings from the dialog box.

Here is the code of dialog box:

public void showDialog() {
    AlertDialog.Builder builder;
    final AlertDialog alertDialog;
    //final Dialog alertDialog;
    Context mContext;
    mContext = screen;
    LayoutInflater inflater = (LayoutInflater) LoginActivity.screen.getSystemService(LoginActivity.screen.LAYOUT_INFLATER_SERVICE);
    layout = inflater.inflate(R.layout.countrylist, null);
    LinearLayout rellayout = (LinearLayout) layout.findViewById(R.id.rellayout);

    RelativeLayout closeAcessCodeDialog = (RelativeLayout)layout.findViewById(R.id.closeAcessCodeDialog) ;

    ListView listview = (ListView) layout.findViewById(R.id.listview);
    listview.setAdapter(new CustomAdapter1(LoginActivity.screen, countryList));

    builder = new AlertDialog.Builder(LoginActivity.screen);
    builder.setView(layout);
    alertDialog = builder.create();
    alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(alertDialog.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
    lp.height = Utility.convertDPtoPixel(400, screen);

    alertDialog.show();
    alertDialog.getWindow().setAttributes(lp);

    listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int pos,
                                long id) {
            countryName = idCountry.get(pos);
            System.out.println("Country code is: " + countryName);
            alertDialog.cancel();
            text.setText(countryList.get(pos));
        }
    });

    closeAcessCodeDialog.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            alertDialog.dismiss();
        }
    });

}

countrylist.xml

 <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#ffe264"
    app:cardCornerRadius="10dp"
    >

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/rellayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_above="@+id/listview"
            android:gravity="center_vertical"
            >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Select your Country"
                android:textColor="#000"
                android:textSize="18sp"
                android:textStyle="bold"
                android:layout_centerInParent="true"
                />

            <RelativeLayout
                android:id="@+id/closeAcessCodeDialog"
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_alignParentRight="true"
                android:gravity="center">

                <ImageButton
                    android:id="@+id/closeDialog"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:background="@drawable/close_country_dialog" />

            </RelativeLayout>
        </RelativeLayout>

        <ListView
            android:id="@+id/listview"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:cacheColorHint="@android:color/transparent"
            android:divider="#e5e5e5"
            android:background="@drawable/list_bacground"
            android:dividerHeight="1px" />

    </LinearLayout>

I visited many similar links over stackoverflow , but no one was helpfull .

Body:
Try this.

Dialog alertDialog = new Dialog(this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.yourlayout);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
alertDialog.show();


问:
postgresql how to use boolean in where statement
I'm a really bad in sql , my query is

```<code> select * from car_wash where
           (select ST_Within((select car_wash.lon_lat from car_wash),(select ST_Buffer(ST_GeomFromText('POINT(65.3 323.2)'),20)))) = true
        AND car_wash.was_deleted=false;
</code>```

But i know that it isn't correct because nested query can return more than 1 column, how to modify this query to use where clause

答:
```<code>select *
from car_wash cw
where
   ST_Within (
       cw.lon_lat,
       ST_Buffer(ST_GeomFromText('POINT(65.3 323.2)'),20)
   )
   AND
   not car_wash.was_deleted
</code>```

Body:
I'm a really bad in sql , my query is

 select * from car_wash where
           (select ST_Within((select car_wash.lon_lat from car_wash),(select ST_Buffer(ST_GeomFromText('POINT(65.3 323.2)'),20)))) = true
        AND car_wash.was_deleted=false;

But i know that it isn't correct because nested query can return more than 1 column, how to modify this query to use where clause


问:
Android instrumentation test with Bitbucket pipelane and Docker
I am new in Docker, and I need help with instrumentation tests. I create a Dockerfile (get it from here and make little modifiers)

```<code>FROM ubuntu:14.04

# Install java7
RUN apt-get update && \
  apt-get install -y software-properties-common && \
  add-apt-repository -y ppa:webupd8team/java && \
  (echo oracle-java7-installer shared/accepted-oracle-license-v1-1 select     true | /usr/bin/debconf-set-selections) && \
  apt-get update && \
  apt-get install -y oracle-java7-installer && \
  apt-get clean && \
  rm -fr /var/lib/apt/lists/* /tmp/* /var/tmp/*
ENV JAVA7_HOME /usr/lib/jvm/java-8-oracle

# Install java8
RUN apt-get update && \
  apt-get install -y software-properties-common && \
  add-apt-repository -y ppa:webupd8team/java && \
  (echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections) && \
  apt-get update && \
  apt-get install -y oracle-java8-installer && \
  apt-get clean && \
  rm -fr /var/lib/apt/lists/* /tmp/* /var/tmp/*
ENV JAVA8_HOME /usr/lib/jvm/java-8-oracle

# Install Deps
RUN dpkg --add-architecture i386 && apt-get update && apt-get install -y --    force-yes expect git wget libc6-i386 lib32stdc++6 lib32gcc1 lib32ncurses5 lib32z1     libpulse0 python curl libqt5widgets5 && apt-get clean && rm -fr     /var/lib/apt/lists/* /tmp/* /var/tmp/*

# Copy install tools
COPY tools /opt/tools

RUN chmod +x /opt/tools/android-accept-licenses.sh
RUN chmod +x /opt/tools/android-wait-for-emulator.sh

ENV PATH ${PATH}:/opt/tools

# Install Android SDK
RUN cd /opt && wget --output-document=android-sdk.tgz --quiet         https://dl.google.com/android/android-sdk_r24.4.1-linux.tgz && \
  tar xzf android-sdk.tgz && \
  rm -f android-sdk.tgz && \
  chown -R root.root android-sdk-linux && \
  /opt/tools/android-accept-licenses.sh "android-sdk-linux/tools/android     update     sdk --all --no-ui --filter platform-tools,tools" && \
  /opt/tools/android-accept-licenses.sh "android-sdk-linux/tools/android update    sdk --all --no-ui --filter platform-tools,tools,build-tools-25.0.2,android-14,android-23,android-25,extra-android-support,extra-android-m2repository,extra-  google-m2repository,extra-google-google_play_services,sys-img-armeabi-v7a-  google_apis-23"

# Setup environment
ENV ANDROID_HOME /opt/android-sdk-linux
ENV PATH ${PATH}:${ANDROID_HOME}/tools:${ANDROID_HOME}/platform-tools

RUN which adb
RUN which android

# Create emulator
RUN echo "no" | android create avd \
            --force \
            --device "Nexus 5" \
            --name nexus5_23 \
            --target android-23 \
            --abi google_apis/armeabi-v7a \
            --sdcard 512M

# Cleaning
RUN apt-get clean

# Start up the emulator
RUN ["/bin/bash", "-c", "SHELL=/bin/bash emulator -avd nexus5_23 -no-window & /opt/tools/android-wait-for-emulator.sh"]

# GO to workspace
RUN mkdir -p /opt/workspace
WORKDIR /opt/workspace
</code>```

When I build it, it works, and emulator running.
My bitbucket pipeline is

```<code>image: xxx/android-23:latest
pipelines:
  default:
    - step:
        script:
          - bash ./gradlew cAT
</code>```

But all my pipelines filed with error:

com.android.builder.testing.api.DeviceException: No connected devices!

Is it possible to run instrumentation tests automatically? May be I must use not Docker, but something else?

答:
RUN commands are run when building the container, you can think of this as running the emulator and shutting down the computer. When you restart the container, it's not running any more. You need a 'CMD' as the last line, which gets run when the container is started. See this link for more info

It's not easy to get GUI apps working in docker, good luck and please post back if you get it working!

Body:
I am new in Docker, and I need help with instrumentation tests. I create a Dockerfile (get it from here and make little modifiers)

FROM ubuntu:14.04

# Install java7
RUN apt-get update && \
  apt-get install -y software-properties-common && \
  add-apt-repository -y ppa:webupd8team/java && \
  (echo oracle-java7-installer shared/accepted-oracle-license-v1-1 select     true | /usr/bin/debconf-set-selections) && \
  apt-get update && \
  apt-get install -y oracle-java7-installer && \
  apt-get clean && \
  rm -fr /var/lib/apt/lists/* /tmp/* /var/tmp/*
ENV JAVA7_HOME /usr/lib/jvm/java-8-oracle

# Install java8
RUN apt-get update && \
  apt-get install -y software-properties-common && \
  add-apt-repository -y ppa:webupd8team/java && \
  (echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections) && \
  apt-get update && \
  apt-get install -y oracle-java8-installer && \
  apt-get clean && \
  rm -fr /var/lib/apt/lists/* /tmp/* /var/tmp/*
ENV JAVA8_HOME /usr/lib/jvm/java-8-oracle

# Install Deps
RUN dpkg --add-architecture i386 && apt-get update && apt-get install -y --    force-yes expect git wget libc6-i386 lib32stdc++6 lib32gcc1 lib32ncurses5 lib32z1     libpulse0 python curl libqt5widgets5 && apt-get clean && rm -fr     /var/lib/apt/lists/* /tmp/* /var/tmp/*

# Copy install tools
COPY tools /opt/tools

RUN chmod +x /opt/tools/android-accept-licenses.sh
RUN chmod +x /opt/tools/android-wait-for-emulator.sh

ENV PATH ${PATH}:/opt/tools

# Install Android SDK
RUN cd /opt && wget --output-document=android-sdk.tgz --quiet         https://dl.google.com/android/android-sdk_r24.4.1-linux.tgz && \
  tar xzf android-sdk.tgz && \
  rm -f android-sdk.tgz && \
  chown -R root.root android-sdk-linux && \
  /opt/tools/android-accept-licenses.sh "android-sdk-linux/tools/android     update     sdk --all --no-ui --filter platform-tools,tools" && \
  /opt/tools/android-accept-licenses.sh "android-sdk-linux/tools/android update    sdk --all --no-ui --filter platform-tools,tools,build-tools-25.0.2,android-14,android-23,android-25,extra-android-support,extra-android-m2repository,extra-  google-m2repository,extra-google-google_play_services,sys-img-armeabi-v7a-  google_apis-23"

# Setup environment
ENV ANDROID_HOME /opt/android-sdk-linux
ENV PATH ${PATH}:${ANDROID_HOME}/tools:${ANDROID_HOME}/platform-tools

RUN which adb
RUN which android

# Create emulator
RUN echo "no" | android create avd \
            --force \
            --device "Nexus 5" \
            --name nexus5_23 \
            --target android-23 \
            --abi google_apis/armeabi-v7a \
            --sdcard 512M

# Cleaning
RUN apt-get clean

# Start up the emulator
RUN ["/bin/bash", "-c", "SHELL=/bin/bash emulator -avd nexus5_23 -no-window & /opt/tools/android-wait-for-emulator.sh"]

# GO to workspace
RUN mkdir -p /opt/workspace
WORKDIR /opt/workspace

When I build it, it works, and emulator running.
My bitbucket pipeline is

image: xxx/android-23:latest
pipelines:
  default:
    - step:
        script:
          - bash ./gradlew cAT

But all my pipelines filed with error:

com.android.builder.testing.api.DeviceException: No connected devices!

Is it possible to run instrumentation tests automatically? May be I must use not Docker, but something else?


问:
Consolidate rows in report

If a row has the same ID as the last one, I want to combine them - summing up the cubicFt and Savings. $perFt divides the savings by the cubicFt, so it wouldn't be summed, simply dividing the new results.  I also want the Descriptions to be concatenated, like this:

答:
Make a Group based on ID (or whatever the leftmost column is). Then suppress the Details section and the Group Header. Instead, you'll be putting all the fields you want to display in the Group Footer. From there it's simple:

Create a Summary or Running Total for both cubicFt and Savings.

Reconfigure your $PerFt to use the summary/running total fields you made in step 1.

Combine the Descriptions by creating a shared string variable Descriptions. Whenever the  group changes, reset it with Descriptions = "". Whenever the group doesn't change, add the description string to your variable. Something like:

```<code>Descriptions = Descriptions & " ; " & {yourtable.Description}
</code>```

Then create a final formula ShowDescription in the Group Footer to display the results with RIGHT(Descriptions, LEN(Descriptions)-2)

Title: Consolidate rows in report

Body:
Make a Group based on ID (or whatever the leftmost column is). Then suppress the Details section and the Group Header. Instead, you'll be putting all the fields you want to display in the Group Footer. From there it's simple:

Create a Summary or Running Total for both cubicFt and Savings.

Reconfigure your $PerFt to use the summary/running total fields you made in step 1.

Combine the Descriptions by creating a shared string variable Descriptions. Whenever the  group changes, reset it with Descriptions = "". Whenever the group doesn't change, add the description string to your variable. Something like:

Descriptions = Descriptions & " ; " & {yourtable.Description}

Then create a final formula ShowDescription in the Group Footer to display the results with RIGHT(Descriptions, LEN(Descriptions)-2)


问:
Best method for gathering NTFS file access statistics?
I'd like advice on choosing a method to collect file access statistics on NTFS volumes under Windows Vista and Windows 7 (32 & 64-bit).  I'd like to count file create/open, delete, read/write accesses for every file.

API hooking is out.  I need system-wide counts, and both 32 and 64-bit OS without mucking up the OS.  Also, I don't think Shell Notification would work.

I know I could do it by installing a file system filter driver.  The Windows DDK has a samples, and that's how Mark Russinovich's FileMon (Sysinternals) works.

I think I might also accomplish this using WMI, but I'm not sure.  That is one crazy messed up API.  But if Microsoft will gather the stats for me, I'll use it.

So the question is, which method would be best & why.  Am I missing another possibility, and would WMI do it?

答:
The Windows Change Journal should do the job:
http://msdn.microsoft.com/en-us/library/aa363798%28VS.85%29.aspx

It gives you exacly what you need.

Getting the full filename is a bit of a problem but there is a nice article around that describes exacly how to do that.


问:
What is the appropriate way to delete a service in Service Fabric?
I have an application running in service fabric.  One of the services that compose the application is a stateful service that only has a run method. It queries other services, does some record keeping as it goes, and then produces an output.  Upon successful completion of the work, it saves the output to Blob Storage and then deletes itself.  I use this for on demand elastic compute around reporting.

If I call into the ServiceManager service to delete the service itself, it appears to deadlock.  This makes sense to me, since the call is likely awaiting the run method's completion before returning to the caller (in this case the caller is in the run method itself so it is effectively awaiting itself).  My next approach was to essentially ignore a Task to asynchronously delete the service like so:

```<code>protected override async Task RunAsync(CancellationToken can)
{

    //do work as described above

    Task ignored = Task.Factory.Run(async ()=>{
       await s_FabricClient.ServiceManager.DeleteServiceAsync(/*blah blah*/);
    }
    await Task.Delay(30000);
}
</code>```

What is the appropriate way to delete a service, when I know the service should under all circumstances be deleted. I would like to avoid a 'manager' service which tracks these things, because right now they are very well self contained.

答:
So the only solution I have found is as follows:

Before, I was using the DeleteServiceAsync (Uri) override which was deprecated.  When I saw this warning (embarrassed to say i hadn't checked warnings in a while).  I converted to the DeleteServiceAsync(DeleteServiceDescription) overload which has a property called ForceDelete.  This basically does not give the service a chance to gracefully shut down.  Since the service itself is making the request, and I know that by this time my service is done working, I can safely call this.

It may not be the end all solution for every use case, but this seems reasonable given my requirements.

```<code>s_FabricClient.DeleteServiceAsync(new Uri("fabric:/myapp/myservice/instance123"));
</code>```

Is now:

```<code>Uri serviceUri = new Uri("fabric:/myapp/myservice/instance123");
DeleteServiceDescription description = new DeleteServiceDescription(serviceUri)
{
 ForceDelete = true
};
s_FabricClient.DeleteServiceAsync(description);
</code>```

Body:
I have an application running in service fabric.  One of the services that compose the application is a stateful service that only has a run method. It queries other services, does some record keeping as it goes, and then produces an output.  Upon successful completion of the work, it saves the output to Blob Storage and then deletes itself.  I use this for on demand elastic compute around reporting.

If I call into the ServiceManager service to delete the service itself, it appears to deadlock.  This makes sense to me, since the call is likely awaiting the run method's completion before returning to the caller (in this case the caller is in the run method itself so it is effectively awaiting itself).  My next approach was to essentially ignore a Task to asynchronously delete the service like so:

protected override async Task RunAsync(CancellationToken can)
{

    //do work as described above

    Task ignored = Task.Factory.Run(async ()=>{
       await s_FabricClient.ServiceManager.DeleteServiceAsync(/*blah blah*/);
    }
    await Task.Delay(30000);
}

What is the appropriate way to delete a service, when I know the service should under all circumstances be deleted. I would like to avoid a 'manager' service which tracks these things, because right now they are very well self contained.

Body:
So the only solution I have found is as follows:

Before, I was using the DeleteServiceAsync (Uri) override which was deprecated.  When I saw this warning (embarrassed to say i hadn't checked warnings in a while).  I converted to the DeleteServiceAsync(DeleteServiceDescription) overload which has a property called ForceDelete.  This basically does not give the service a chance to gracefully shut down.  Since the service itself is making the request, and I know that by this time my service is done working, I can safely call this.

It may not be the end all solution for every use case, but this seems reasonable given my requirements.

s_FabricClient.DeleteServiceAsync(new Uri("fabric:/myapp/myservice/instance123"));

Is now:

Uri serviceUri = new Uri("fabric:/myapp/myservice/instance123");
DeleteServiceDescription description = new DeleteServiceDescription(serviceUri)
{
 ForceDelete = true
};
s_FabricClient.DeleteServiceAsync(description);


问:
Xero SDK is allow to access for 30 mins
I Created a public app in Xero and integrate it in my .net MVC application using XERO SDK,
While i Connect to xero it allow me only for 30 mins, after that authentication token got expire. How can I manage it without expire time?</p>

答:
Afraid you can't. As mentioned on the doc - https://developer.xero.com/documentation/auth-and-limits/public-applications - access token on Public application expire after 30 minutes.

You need to use other application types - https://developer.xero.com/documentation/getting-started/api-application-types

Title: Xero SDK is allow to access for 30 mins


问:
kafka streaming reading all data in the first batch itself
I have inserted 50 records in Kafka topic with 1 second latency between each record, so 50 records in 50+ seconds.

While consuming the records from this topic, as you can see in below code, i am keeping the batch interval to 1 second. So ideally i should be getting ~50 RDDs.
I am using foreachRDD to get the data in batches , and then process data for each RDD.
In below code, each time "call" method is called, i am counting records in each RDD. The surprising thing is that the first RDD itself is showing 50 records , and obviously subsequent RDD are showing 0 records.
I don't understand this behaviour, it should be ideally 1 record per RDD.

Can anyone suggest if my understanding is wrong?

JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, Durations.seconds(1));

```<code>messages.foreachRDD(new VoidFunction<JavaRDD<ConsumerRecord<K, String>>>() {
            public void call(JavaRDD<ConsumerRecord<K, V>> rdd) {
                System.out.println("NUmber of elements in RDD : "+ rdd.count());

                List<Row> rows = rdd.map(record -> processData(record))
                        .reduce((rows1, rows2) -> {
                            rows1.addAll(rows2);
                            return rows1;
                        });

                StructType schema = DataTypes.createStructType(fields);
                Dataset ds = ss.createDataFrame(rows, schema);
                ds.createOrReplaceTempView("trades");
                ds.show();
            }
        });
</code>```

答:
This is the expected behavior of spark what you are seeing. Had you started your streaming job and then populated the Kafka topic with data (Say 1 record every second) your batch size would have been according to your expectation. (Not quite... Because of Kafka topic partitions)

But it is possible to achieve what you want by using a spark streaming parameter called max.rate.per.partition

You have to keep in mind that it works per Kafka partition.

Example:

So if your Kafka topic has 3 partitions. And your batch size is 1 second. and max.rate.per.partition = 1

In the below mentioned configuration will get 3 items per RDD batch.

Sample Streaming Context:

```<code>```
val sparkConf = new SparkConf().
    set("spark.streaming.kafka.maxRatePerPartition",
        inputParam.maxRatePerPartition)

val ssc = new StreamingContext(sparkConf, inputParam.batchDuration)
```
</code>```

If your Kafka topic has 1 partition then you will get exactly what you want.

Body:
I have inserted 50 records in Kafka topic with 1 second latency between each record, so 50 records in 50+ seconds.

While consuming the records from this topic, as you can see in below code, i am keeping the batch interval to 1 second. So ideally i should be getting ~50 RDDs.
I am using foreachRDD to get the data in batches , and then process data for each RDD.
In below code, each time "call" method is called, i am counting records in each RDD. The surprising thing is that the first RDD itself is showing 50 records , and obviously subsequent RDD are showing 0 records.
I don't understand this behaviour, it should be ideally 1 record per RDD.

Can anyone suggest if my understanding is wrong?

JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, Durations.seconds(1));

messages.foreachRDD(new VoidFunction<JavaRDD<ConsumerRecord<K, String>>>() {
            public void call(JavaRDD<ConsumerRecord<K, V>> rdd) {
                System.out.println("NUmber of elements in RDD : "+ rdd.count());

                List<Row> rows = rdd.map(record -> processData(record))
                        .reduce((rows1, rows2) -> {
                            rows1.addAll(rows2);
                            return rows1;
                        });

                StructType schema = DataTypes.createStructType(fields);
                Dataset ds = ss.createDataFrame(rows, schema);
                ds.createOrReplaceTempView("trades");
                ds.show();
            }
        });

Body:
This is the expected behavior of spark what you are seeing. Had you started your streaming job and then populated the Kafka topic with data (Say 1 record every second) your batch size would have been according to your expectation. (Not quite... Because of Kafka topic partitions)

But it is possible to achieve what you want by using a spark streaming parameter called max.rate.per.partition

You have to keep in mind that it works per Kafka partition.

Example:

So if your Kafka topic has 3 partitions. And your batch size is 1 second. and max.rate.per.partition = 1

In the below mentioned configuration will get 3 items per RDD batch.

Sample Streaming Context:

```
val sparkConf = new SparkConf().
    set("spark.streaming.kafka.maxRatePerPartition",
        inputParam.maxRatePerPartition)

val ssc = new StreamingContext(sparkConf, inputParam.batchDuration)
```

If your Kafka topic has 1 partition then you will get exactly what you want.