问:
d3js - How to move x- domain values towards right
I am working on one chart using d3.js version 4.
So I want to move plotting of bar chart towards right as shown below.

Usually the bar renders from starting position as shown below

Please help ....!
    Demo fiddle

答:
In D3 v4.x there is no native method to set the absolute amount of padding before the first tick in a band scale.

There are several hacks, though, if you accept a hacky solution.

One of those hacky solutions consists in simply adding fake values before the real domain...

```<code>xScale.domain(["foo", "bar", "baz"].concat(stackedData[0].map(function(d) {
    return d.data.day;
})));
</code>```

... and showing only the real domain in the axis:

```<code>xAxis.scale(xScale)
    .tickValues(stackedData[0].map(function(d) {
        return d.data.day;
    }));
</code>```

Here is the result:

var self = this;
self.plannedHours = 80;
self.averagePlannedHours = 70;
self.averagPlannedItems = 7;
self.isStoryPoints = false;
self.availableHours = 0;
self.data = [{
  "day": "Mon",
  "avgPlannedHours": 70,
  "overPlannedHours": 80,
  "doneWork": 0
}, {
  "day": "Tue",
  "avgPlannedHours": 70,
  "overPlannedHours": 80,
  "doneWork": 30
}, {
  "day": "Wed",
  "avgPlannedHours": 70,
  "overPlannedHours": 90,
  "doneWork": 35
}, {
  "day": "Thu",
  "avgPlannedHours": 70,
  "overPlannedHours": 90,
  "doneWork": 50
}, {
  "day": "Fri",
  "avgPlannedHours": 70,
  "overPlannedHours": 90,
  "doneWork": 55
}, {
  "day": "Sat",
  "avgPlannedHours": 0,
  "overPlannedHours": 0,
  "doneWork": 0
}, {
  "day": "Sun",
  "avgPlannedHours": 0,
  "overPlannedHours": 0,
  "doneWork": 0
}, {
  "day": "Mon1",
  "avgPlannedHours": 70,
  "overPlannedHours": 80,
  "doneWork": 0
}, {
  "day": "Tue1",
  "avgPlannedHours": 70,
  "overPlannedHours": 80,
  "doneWork": 30
}, {
  "day": "Wed1",
  "avgPlannedHours": 70,
  "overPlannedHours": 90,
  "doneWork": 35
}, {
  "day": "Thu1",
  "avgPlannedHours": 70,
  "overPlannedHours": 90,
  "doneWork": 50
}, {
  "day": "Fri1",
  "avgPlannedHours": 70,
  "overPlannedHours": 90,
  "doneWork": 55
}, {
  "day": "Sat1",
  "avgPlannedHours": 0,
  "overPlannedHours": 0,
  "doneWork": 0
}, {
  "day": "Sun1",
  "avgPlannedHours": 0,
  "overPlannedHours": 0,
  "doneWork": 0
}];
self.dataCopy = self.data.slice();
self.normalisedData = [];
normalizeData();

function normalizeData() {
  self.normalisedData = self.data.map(function(data, index) {
    if (self.plannedHours > self.averagePlannedHours) {
      data.overPlannedHours = data.overPlannedHours - data.avgPlannedHours;
    } else if (self.plannedHours < self.averagePlannedHours) {
      data.avgPlannedHours = data.avgPlannedHours - data.overPlannedHours;
    }
    return data;
  });
}

renderChart();

function renderChart() {

  var colors1 = ['#FFD692', '#A9EEFF'],
    avgPlannedHoursLineColor = "#36CFF5",
    plannedHoursLineColor = self.plannedHours > self.averagePlannedHours ? "#F5A623" : "#A8EEFF",
    color = d3.scaleOrdinal(colors1),
    margin = {
      top: 25,
      right: 180,
      bottom: 30,
      left: 40
    },
    svg = d3.select("#chart-container"),
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom;

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

  // var stackedData = d3.layout.stack()(self.normalisedData);
  var stack = d3.stack().keys(["avgPlannedHours", "overPlannedHours"]);
  var stackedData = stack(self.normalisedData);
  stackedData[1] = stackedData[1].map(function(stData, index) {
    stData[0] = 0;
    return stData;
  });

  var xAxis = d3.axisBottom();
  if (self.plannedHours > self.averagePlannedHours) {
    var swappedStack = stackedData[0];
    stackedData[0] = stackedData[1];
    stackedData[1] = swappedStack;
  }

  var yAxis = d3.axisLeft()

  var xScale = d3.scaleBand()
    .rangeRound([0, width])
    .padding(0.4)
    .align(0.3);

  xScale.domain(["foo", "bar", "baz"].concat(stackedData[0].map(function(d) {
    return d.data.day;
  })));

  var x1Scale = d3.scaleBand()
    .rangeRound([0, width])
    .padding(0.6);

  x1Scale.domain(["foo", "bar", "baz"].concat(stackedData[0].map(function(d) {
    return d.data.day;
  })));

  xAxis.scale(xScale)
    .tickValues(stackedData[0].map(function(d) {
      return d.data.day;
    }));

  var yScale = d3.scaleLinear()
    .rangeRound([height, 0]);
  if (self.plannedHours > self.averagePlannedHours) {
    yScale.domain([0,
      d3.max(stackedData[0],
        function(d) {
          return d[0] + d[1];
        })
    ]).nice();
  } else {
    yScale.domain([0,
      d3.max(stackedData[stackedData.length - 1],
        function(d) {
          return d[0] + d[1];
        })
    ]).nice();
  }

  yAxis.scale(yScale)
    .ticks(10);

  var layer = g.selectAll(".stack")
    .data(stackedData)
    .enter().append("g")
    .attr("class", "stack")
    .style("fill", function(d, i) {
      return color(i);
    });

  layer.selectAll("rect")
    .data(function(d) {
      return d;
    })
    .enter().append("rect")
    .attr("x", function(d) {
      return xScale(d.data.day);
    })
    .attr("y", function(d) {
      return yScale(d[1] + d[0]);
    })
    .attr("height", function(d) {
      return yScale(d[0]) - yScale(d[1] + d[0]);
    })
    .attr("width", 24);

  var workDoneLayer = g.selectAll(".work-done")
    .data(self.dataCopy)
    .enter().append("rect")
    .attr("class", "work-done")
    .attr("x", function(d) {
      return x1Scale(d.day);
    })
    .attr("y", function(d) {
      return yScale(d.doneWork);
    })
    .attr("width", 24)
    .attr("height", function(d) {
      return height - yScale(d.doneWork);
    });

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

  g.append("g")
    .attr("class", "y-axis")
    .call(yAxis);

  var averagLineData = self.dataCopy[0].avgPlannedHours;
  var plannedHoursDotted = d3.max(self.dataCopy, function(d) {
    return d.overPlannedHours;
  });
  g.append("svg:line")
    .attr("x1", 0)
    .attr("x2", width)
    .attr("y1", yScale(averagLineData))
    .attr("y2", yScale(averagLineData))
    .attr("stroke-dasharray", ("5, 5"))
    .style("stroke", avgPlannedHoursLineColor);
  g.append("svg:line")
    .attr("x1", 0)
    .attr("x2", width)
    .attr("y1", yScale(plannedHoursDotted))
    .attr("y2", yScale(plannedHoursDotted))
    .attr("stroke-dasharray", ("5, 5"))
    .style("stroke", plannedHoursLineColor);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<svg id="chart-container" width="750" height="251"> </svg></code>```

Body:
In D3 v4.x there is no native method to set the absolute amount of padding before the first tick in a band scale.

There are several hacks, though, if you accept a hacky solution.

One of those hacky solutions consists in simply adding fake values before the real domain...

xScale.domain(["foo", "bar", "baz"].concat(stackedData[0].map(function(d) {
    return d.data.day;
})));

... and showing only the real domain in the axis:

xAxis.scale(xScale)
    .tickValues(stackedData[0].map(function(d) {
        return d.data.day;
    }));

Here is the result:

var self = this;
self.plannedHours = 80;
self.averagePlannedHours = 70;
self.averagPlannedItems = 7;
self.isStoryPoints = false;
self.availableHours = 0;
self.data = [{
  "day": "Mon",
  "avgPlannedHours": 70,
  "overPlannedHours": 80,
  "doneWork": 0
}, {
  "day": "Tue",
  "avgPlannedHours": 70,
  "overPlannedHours": 80,
  "doneWork": 30
}, {
  "day": "Wed",
  "avgPlannedHours": 70,
  "overPlannedHours": 90,
  "doneWork": 35
}, {
  "day": "Thu",
  "avgPlannedHours": 70,
  "overPlannedHours": 90,
  "doneWork": 50
}, {
  "day": "Fri",
  "avgPlannedHours": 70,
  "overPlannedHours": 90,
  "doneWork": 55
}, {
  "day": "Sat",
  "avgPlannedHours": 0,
  "overPlannedHours": 0,
  "doneWork": 0
}, {
  "day": "Sun",
  "avgPlannedHours": 0,
  "overPlannedHours": 0,
  "doneWork": 0
}, {
  "day": "Mon1",
  "avgPlannedHours": 70,
  "overPlannedHours": 80,
  "doneWork": 0
}, {
  "day": "Tue1",
  "avgPlannedHours": 70,
  "overPlannedHours": 80,
  "doneWork": 30
}, {
  "day": "Wed1",
  "avgPlannedHours": 70,
  "overPlannedHours": 90,
  "doneWork": 35
}, {
  "day": "Thu1",
  "avgPlannedHours": 70,
  "overPlannedHours": 90,
  "doneWork": 50
}, {
  "day": "Fri1",
  "avgPlannedHours": 70,
  "overPlannedHours": 90,
  "doneWork": 55
}, {
  "day": "Sat1",
  "avgPlannedHours": 0,
  "overPlannedHours": 0,
  "doneWork": 0
}, {
  "day": "Sun1",
  "avgPlannedHours": 0,
  "overPlannedHours": 0,
  "doneWork": 0
}];
self.dataCopy = self.data.slice();
self.normalisedData = [];
normalizeData();

function normalizeData() {
  self.normalisedData = self.data.map(function(data, index) {
    if (self.plannedHours > self.averagePlannedHours) {
      data.overPlannedHours = data.overPlannedHours - data.avgPlannedHours;
    } else if (self.plannedHours < self.averagePlannedHours) {
      data.avgPlannedHours = data.avgPlannedHours - data.overPlannedHours;
    }
    return data;
  });
}

renderChart();

function renderChart() {

  var colors1 = ['#FFD692', '#A9EEFF'],
    avgPlannedHoursLineColor = "#36CFF5",
    plannedHoursLineColor = self.plannedHours > self.averagePlannedHours ? "#F5A623" : "#A8EEFF",
    color = d3.scaleOrdinal(colors1),
    margin = {
      top: 25,
      right: 180,
      bottom: 30,
      left: 40
    },
    svg = d3.select("#chart-container"),
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom;

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

  // var stackedData = d3.layout.stack()(self.normalisedData);
  var stack = d3.stack().keys(["avgPlannedHours", "overPlannedHours"]);
  var stackedData = stack(self.normalisedData);
  stackedData[1] = stackedData[1].map(function(stData, index) {
    stData[0] = 0;
    return stData;
  });

  var xAxis = d3.axisBottom();
  if (self.plannedHours > self.averagePlannedHours) {
    var swappedStack = stackedData[0];
    stackedData[0] = stackedData[1];
    stackedData[1] = swappedStack;
  }

  var yAxis = d3.axisLeft()

  var xScale = d3.scaleBand()
    .rangeRound([0, width])
    .padding(0.4)
    .align(0.3);

  xScale.domain(["foo", "bar", "baz"].concat(stackedData[0].map(function(d) {
    return d.data.day;
  })));

  var x1Scale = d3.scaleBand()
    .rangeRound([0, width])
    .padding(0.6);

  x1Scale.domain(["foo", "bar", "baz"].concat(stackedData[0].map(function(d) {
    return d.data.day;
  })));

  xAxis.scale(xScale)
    .tickValues(stackedData[0].map(function(d) {
      return d.data.day;
    }));

  var yScale = d3.scaleLinear()
    .rangeRound([height, 0]);
  if (self.plannedHours > self.averagePlannedHours) {
    yScale.domain([0,
      d3.max(stackedData[0],
        function(d) {
          return d[0] + d[1];
        })
    ]).nice();
  } else {
    yScale.domain([0,
      d3.max(stackedData[stackedData.length - 1],
        function(d) {
          return d[0] + d[1];
        })
    ]).nice();
  }

  yAxis.scale(yScale)
    .ticks(10);

  var layer = g.selectAll(".stack")
    .data(stackedData)
    .enter().append("g")
    .attr("class", "stack")
    .style("fill", function(d, i) {
      return color(i);
    });

  layer.selectAll("rect")
    .data(function(d) {
      return d;
    })
    .enter().append("rect")
    .attr("x", function(d) {
      return xScale(d.data.day);
    })
    .attr("y", function(d) {
      return yScale(d[1] + d[0]);
    })
    .attr("height", function(d) {
      return yScale(d[0]) - yScale(d[1] + d[0]);
    })
    .attr("width", 24);

  var workDoneLayer = g.selectAll(".work-done")
    .data(self.dataCopy)
    .enter().append("rect")
    .attr("class", "work-done")
    .attr("x", function(d) {
      return x1Scale(d.day);
    })
    .attr("y", function(d) {
      return yScale(d.doneWork);
    })
    .attr("width", 24)
    .attr("height", function(d) {
      return height - yScale(d.doneWork);
    });

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

  g.append("g")
    .attr("class", "y-axis")
    .call(yAxis);

  var averagLineData = self.dataCopy[0].avgPlannedHours;
  var plannedHoursDotted = d3.max(self.dataCopy, function(d) {
    return d.overPlannedHours;
  });
  g.append("svg:line")
    .attr("x1", 0)
    .attr("x2", width)
    .attr("y1", yScale(averagLineData))
    .attr("y2", yScale(averagLineData))
    .attr("stroke-dasharray", ("5, 5"))
    .style("stroke", avgPlannedHoursLineColor);
  g.append("svg:line")
    .attr("x1", 0)
    .attr("x2", width)
    .attr("y1", yScale(plannedHoursDotted))
    .attr("y2", yScale(plannedHoursDotted))
    .attr("stroke-dasharray", ("5, 5"))
    .style("stroke", plannedHoursLineColor);
}

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg id="chart-container" width="750" height="251"> </svg>


来源: stackexchange

问:
Unpack a two-dimensional list through the loop
I have a need of unpacking two-dimensional list (list of lists) with a dynamic length. The whole task is to form a full-featured HTML-table from my list with the help of lxml framework.

Having been used this excellent answer as a backbone I came to the following code for my task:

```<code> page = (
    E.html(
        E.body(
        E.table(
                E.tr(
                    E.th(E.div("header1")),
                      ...
                    E.th(E.div("header40")),
                    ),
                *[E.tr(
                     *[
                        E.td(str(col)) for col in p_list[1] <<- how to put N here???
                     ]
                    ) for row in range(len(p_list))]
                , border="2"
                )
            )
        )
    )
</code>```

The first E.tr is a header for my table, the second one *[E.tr is unpacked from the list p_list. The list has N elements (aka rows) each of which is a list itself consisting of around 50 elements (aka columns of N row).

The p_list is declared and filled like this:

```<code>p_list = list()
rows = table.iter('div')
p_list.append([c.text for c in rows])
rows = table.xpath("body/table")[0].findall("tr")
for row in rows[2:]:
   p_list.append([c.text for c in row.getchildren()])
</code>```

Now this code can only output the same row of p_list N times and works only with a hard-coded row number, but what if I want to specify it dynamically to output the whole table?

Cannot figure out how to do this.

答:
Replace p_list[1] with p_list[row]. Even better, don't use range:

```<code>*[E.tr(
   *[ E.td(str(col)) for col in row ]
) for row in p_list ]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a need of unpacking two-dimensional list (list of lists) with a dynamic length. The whole task is to form a full-featured HTML-table from my list with the help of lxml framework.

Having been used this excellent answer as a backbone I came to the following code for my task:

 page = (
    E.html(
        E.body(
        E.table(
                E.tr(
                    E.th(E.div("header1")),
                      ...
                    E.th(E.div("header40")),
                    ),
                *[E.tr(
                     *[
                        E.td(str(col)) for col in p_list[1] <<- how to put N here???
                     ]
                    ) for row in range(len(p_list))]
                , border="2"
                )
            )
        )
    )

The first E.tr is a header for my table, the second one *[E.tr is unpacked from the list p_list. The list has N elements (aka rows) each of which is a list itself consisting of around 50 elements (aka columns of N row).

The p_list is declared and filled like this:

p_list = list()
rows = table.iter('div')
p_list.append([c.text for c in rows])
rows = table.xpath("body/table")[0].findall("tr")
for row in rows[2:]:
   p_list.append([c.text for c in row.getchildren()])

Now this code can only output the same row of p_list N times and works only with a hard-coded row number, but what if I want to specify it dynamically to output the whole table?

Cannot figure out how to do this.

Body:
Replace p_list[1] with p_list[row]. Even better, don't use range:

*[E.tr(
   *[ E.td(str(col)) for col in row ]
) for row in p_list ]


问:
Two column of several divs
I'm making a 2-column layout with divs.
It should be something like this: http://dl.dropbox.com/u/4976861/html-demo.html

But there is a problem. If content stretches the side blocks vertically, the left blocks shift downwards: http://dl.dropbox.com/u/4976861/html-demo-2.html

If I put the sidebar into a wrapper div, it works fine, but it will make the code quiet messy because of the paddings and some background issues which I removed to simplify the demo, so I would like to leave this option for now.

答:
I don't think that you're going to be able to produce the results that you would like without changing the underlying HTML. You're trying to allow elements to flow (both vertically and horizontally) within the page, but the order in which you have the elements is not going to allow this.

I might be teaching you to suck eggs, but my preference for the HTML output would be something like this:

```<code><div class="wrap">
        <div class="column1">
            <div>left 1</div>
            <div>left 2</div>
            <div>left 3</div>
        </div>
        <div class="column2">
            <div>right 1</div>
            <div>right 2</div>
        </div>
 </div>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Two column of several divs

Body:
I don't think that you're going to be able to produce the results that you would like without changing the underlying HTML. You're trying to allow elements to flow (both vertically and horizontally) within the page, but the order in which you have the elements is not going to allow this.

I might be teaching you to suck eggs, but my preference for the HTML output would be something like this:

<div class="wrap">
        <div class="column1">
            <div>left 1</div>
            <div>left 2</div>
            <div>left 3</div>
        </div>
        <div class="column2">
            <div>right 1</div>
            <div>right 2</div>
        </div>
 </div>


问:
Sklearn syntax error?
I am learning by this site(https://pythonprogramming.net/training-testing-machine-learning-tutorial/), part 4. This is my code(copied, with Quandl having lowercase q as is correct in newer version and model_selection instead of cross_validation for same reason).

```<code>import quandl, math
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn import model_selection
from sklearn import svm
from sklearn.linear_model import LinearRegression

df = quandl.get("WIKI/GOOGL")
print(df.head())
print(df.tail())
df = df[['Adj. Open',  'Adj. High',  'Adj. Low',  'Adj.
             Close', 'Adj. Volume']]

df['HL_PCT'] = (df['Adj. High'] - df['Adj. Low']) /
df['Adj. Close'] * 100.0
df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) /
    df['Adj. Open'] * 100.0
df = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj.
   Volume']]
print(df.head())
forecast_col = 'Adj. Close'
df.fillna(value=-99999, inplace=True)
forecast_out = int(math.ceil(0.01 * len(df)))
df['label'] = df[forecast_col].shift(-forecast_out)
df.dropna(inplace=True)
X = np.array(df.drop(['label'], 1))
y = np.array(df['label'])
X = preprocessing.scale(X)
y = np.array(df['label'])
X_train, X_test, y_train, y_test =
    model_selection.train_test_split(X, y, test_size=0.2)

clf = svm.SVR()
clf.fit(X_train, y_train)
confidence = clf.score(X_test, y_test)
print(confidence)
</code>```

Error is:

```<code>Traceback (most recent call last):
  File "C:/Users/PycharmProjects/learn_python_the_hard_way/LEARN.py", line 4, in <module>
    from sklearn import preprocessing
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\__init__.py", line 57, in <module>
    from .base import clone
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\base.py", line 10, in <module>
    from scipy import sparse
  File "C:\Users\PycharmProjects\learn_python_the_hard_way\scipy.py", line 1
    from scip
            ^
SyntaxError: invalid syntax
</code>```

I don't have any idea how to solve this, any help will be greatly appreciated!

UPDATE:
I had scipy.py file created for doing scipy exercises in same file as is the one I'm practicing right now and now deleted it. Error is:

```<code>Traceback (most recent call last):
  File "C:/Users/PycharmProjects/learn_python_the_hard_way/LEARN.py", line 4, in <module>
    from sklearn import preprocessing
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\__init__.py", line 57, in <module>
    from .base import clone
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\base.py", line 10, in <module>
    from scipy import sparse
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\scipy\__init__.py", line 61, in <module>
    from numpy._distributor_init import NUMPY_MKL  # requires numpy+mkl
ImportError: cannot import name 'NUMPY_MKL'
</code>```

I checked, numpy is installed and working!

答: You have a file named scipy.py (in C:\Users\PycharmProjects\learn_python_the_hard_way) that is being found before the actual SciPy installation (presumably in your Python lib directory).  You need to rename it.

Title: Sklearn syntax error?

Body:
I am learning by this site(https://pythonprogramming.net/training-testing-machine-learning-tutorial/), part 4. This is my code(copied, with Quandl having lowercase q as is correct in newer version and model_selection instead of cross_validation for same reason).

import quandl, math
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn import model_selection
from sklearn import svm
from sklearn.linear_model import LinearRegression

df = quandl.get("WIKI/GOOGL")
print(df.head())
print(df.tail())
df = df[['Adj. Open',  'Adj. High',  'Adj. Low',  'Adj.
             Close', 'Adj. Volume']]

df['HL_PCT'] = (df['Adj. High'] - df['Adj. Low']) /
df['Adj. Close'] * 100.0
df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) /
    df['Adj. Open'] * 100.0
df = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj.
   Volume']]
print(df.head())
forecast_col = 'Adj. Close'
df.fillna(value=-99999, inplace=True)
forecast_out = int(math.ceil(0.01 * len(df)))
df['label'] = df[forecast_col].shift(-forecast_out)
df.dropna(inplace=True)
X = np.array(df.drop(['label'], 1))
y = np.array(df['label'])
X = preprocessing.scale(X)
y = np.array(df['label'])
X_train, X_test, y_train, y_test =
    model_selection.train_test_split(X, y, test_size=0.2)

clf = svm.SVR()
clf.fit(X_train, y_train)
confidence = clf.score(X_test, y_test)
print(confidence)

Error is:

Traceback (most recent call last):
  File "C:/Users/PycharmProjects/learn_python_the_hard_way/LEARN.py", line 4, in <module>
    from sklearn import preprocessing
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\__init__.py", line 57, in <module>
    from .base import clone
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\base.py", line 10, in <module>
    from scipy import sparse
  File "C:\Users\PycharmProjects\learn_python_the_hard_way\scipy.py", line 1
    from scip
            ^
SyntaxError: invalid syntax

I don't have any idea how to solve this, any help will be greatly appreciated!

UPDATE:
I had scipy.py file created for doing scipy exercises in same file as is the one I'm practicing right now and now deleted it. Error is:

Traceback (most recent call last):
  File "C:/Users/PycharmProjects/learn_python_the_hard_way/LEARN.py", line 4, in <module>
    from sklearn import preprocessing
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\__init__.py", line 57, in <module>
    from .base import clone
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\base.py", line 10, in <module>
    from scipy import sparse
  File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\scipy\__init__.py", line 61, in <module>
    from numpy._distributor_init import NUMPY_MKL  # requires numpy+mkl
ImportError: cannot import name 'NUMPY_MKL'

I checked, numpy is installed and working!


问:
Multiple parameters on jquery ajax call asp.net
I am trying to pass two parameters on an ajax call. I already tried several ways suggested on StakeOverflow but none worked. Here is my method signature on controller:

```<code>[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase[] files, string[] usersToShare)
</code>```

Here is my function:

```<code>function uploadFile() {
        var formData = new FormData();
        var totalFiles = document.getElementById("files").files.length;

        for (var i = 0; i < totalFiles; i++) {
            var file = document.getElementById("files").files[i];
            formData.append("files", file);
        }

        //get the selected usernames (email) to share the file
        var selectedUsers = [];
        $("#costumerUsersListSelect :selected").each(function () {
            selectedUsers.push($(this).val());
        });

        $.ajax({
            type: 'post',
            url: '/ManageFiles/UploadFile',
            data: "files=" + formData + "usersToShare=" + selectedUsers,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: function (data) {
            },
            error: function (error) {
            }
        });
    }
</code>```

So I want to pass to the controller the formData and the selectedUsers. If I pass just the formData (Data: formData) everything works but I need to pass the selectedUsers too.

Here what I already tried without any success:

```<code>data: JSON.stringify({ files: formData, usersToShare: selectedUsers }),
data: { files: formData, usersToShare: JSON.stringify(selectedUsers)},
data: "files=" + formData + "&usersToShare=" + selectedUsers,
data: "files=" + formData + "usersToShare=" + selectedUsers,
</code>```

I am not sure if this is a syntax issue.

Thanks in advance for any help.

答:
Instead of:

```<code>data: "files=" + formData + "usersToShare=" + selectedUsers,
</code>```

append the selectedUsers in formData and send only formData to the server like:

```<code>data: formData,
</code>```

and try again.

Body:
I am trying to pass two parameters on an ajax call. I already tried several ways suggested on StakeOverflow but none worked. Here is my method signature on controller:

[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase[] files, string[] usersToShare)

Here is my function:

function uploadFile() {
        var formData = new FormData();
        var totalFiles = document.getElementById("files").files.length;

        for (var i = 0; i < totalFiles; i++) {
            var file = document.getElementById("files").files[i];
            formData.append("files", file);
        }

        //get the selected usernames (email) to share the file
        var selectedUsers = [];
        $("#costumerUsersListSelect :selected").each(function () {
            selectedUsers.push($(this).val());
        });

        $.ajax({
            type: 'post',
            url: '/ManageFiles/UploadFile',
            data: "files=" + formData + "usersToShare=" + selectedUsers,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: function (data) {
            },
            error: function (error) {
            }
        });
    }

So I want to pass to the controller the formData and the selectedUsers. If I pass just the formData (Data: formData) everything works but I need to pass the selectedUsers too.

Here what I already tried without any success:

data: JSON.stringify({ files: formData, usersToShare: selectedUsers }),
data: { files: formData, usersToShare: JSON.stringify(selectedUsers)},
data: "files=" + formData + "&usersToShare=" + selectedUsers,
data: "files=" + formData + "usersToShare=" + selectedUsers,

I am not sure if this is a syntax issue.

Thanks in advance for any help.

Body:
Instead of:

data: "files=" + formData + "usersToShare=" + selectedUsers,

append the selectedUsers in formData and send only formData to the server like:

data: formData,

and try again.


问:
PHP app deploy Ubuntu 16.04 nginx apache setting
It's been a 3rd day I'm trying to deploy a little php app.
We moving our apps, which is 3 rails apps and 1 php to the same server.
Rails apps working fine. PHP doesn't.
I've never really deployed PHP app, so I am doing it through guides. So far, I get this situation:
If I try to open PHP app in a browser I see default Apache page. If I refresh the page it will show me the content of index.php file, but as a blank text. Refresh again - default Apache page, and again - content of index.php.

My settings:

nginx/sites-available/my.site (enabled in sites-enabled)

```<code>server {
     listen 80 default_server;
     listen [::]:80 default_server;

 root /var/www/my.site/httpdocs;

 # Add index.php to the list if you are using PHP
 index index.php index.html index.htm index.nginx-debian.html;

 server_name my.site www.my.site;

 location / {
   proxy_pass http://localhost:8000;
   include /etc/nginx/proxy_params;
 }

 location ~* \.(js|css|jpg|jpeg|gif|png|svg|ico|pdf|html|htm)$ {
expires      30d;
 }

 location @proxy {
    proxy_pass http://127.0.0.1:8000;
    include /etc/nginx/proxy_params;
 }
 location ~* \.php$ {
    proxy_pass http://127.0.0.1:8000;
    include /etc/nginx/proxy_params;
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
 }
}
</code>```

apache2/sites-available/my.site

```<code>ServerName my.site
ServerAlias www.my.site

ServerAdmin webmaster@localhost
DocumentRoot /var/www/my.site/httpdocs

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</code>```

apache2/ports.conf

```<code>NameVirtualHost 127.0.0.1:8000
Listen 8000

<IfModule ssl_module>
    Listen 443
</IfModule>

<IfModule mod_gnutls.c>
    Listen 443
</IfModule>
</code>```

At the work in day off with no idea how to fix the server. Any advice is appreciated.

答:
nginx config

```<code>map $sent_http_content_type $expires {
    default               off;
    ~css                  max;
    ~javascript       max;
    ~image             max;
    ~font-woff        max;
    ~video               max;
    ~zip                   max;
    ~txt                    max;
  }
expires                 $expires;

server {
listen 80;
    server_name exemple.com;
    root /home/to/exemple.com;
    index index.php index.html;

gzip                    on;
gzip_min_length         128;
gzip_http_version       1.1;
gzip_buffers           128 32k;
gzip_types
    text/css
    text/javascript
    text/xml
    text/plain
    text/x-component
    application/javascript
    application/x-javascript
    application/json
    application/xml
    application/rss+xml
    application/atom+xml
    font/truetype
    font/opentype
    application/vnd.ms-fontobject
    image/svg+xml;
gzip_static  on;
gzip_proxied            expired no-cache no-store private auth;
gzip_disable            "msie6";
gzip_vary                on;

location / {
   proxy_pass http://127.0.0.1:8000;
   proxy_set_header Host $host;
   proxy_set_header X-Real-IP $remote_addr;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_set_header X-Forwarded-Proto $scheme;
   }
}
</code>```

apache config

php 7 mod

```<code>apt install libapache2-mod-php7.0
</code>```

php5 mod

```<code>apt install libapache2-mod-php
</code>```

Include for example php7.0 mod

```<code>a2enmod php7.0
</code>```

VirtualHost config apache

```<code><VirtualHost *:8000>
  ServerName exemple.com
  DocumentRoot /home/to/exemple.com
  ErrorLog ${APACHE_LOG_DIR}/error.log
  CustomLog ${APACHE_LOG_DIR}/access.log combined
  RewriteEngine On
<Directory /home/to/exemple.com/>
  php_admin_flag engine on
  Options -ExecCGI -Indexes +FollowSymLinks
  AllowOverride All
  Require all granted
</Directory>
</VirtualHost>
</code>```

Remove NameVirtualHost 127.0.0.1:8000 in apache2.conf
Paste ServerName 127.0.0.1

```<code>systemctl restart apache2
systemctl restart nginx
</code>```

Original post apache2+nginx proxy

Body:
It's been a 3rd day I'm trying to deploy a little php app.
We moving our apps, which is 3 rails apps and 1 php to the same server.
Rails apps working fine. PHP doesn't.
I've never really deployed PHP app, so I am doing it through guides. So far, I get this situation:
If I try to open PHP app in a browser I see default Apache page. If I refresh the page it will show me the content of index.php file, but as a blank text. Refresh again - default Apache page, and again - content of index.php.

My settings:

nginx/sites-available/my.site (enabled in sites-enabled)

server {
     listen 80 default_server;
     listen [::]:80 default_server;

 root /var/www/my.site/httpdocs;

 # Add index.php to the list if you are using PHP
 index index.php index.html index.htm index.nginx-debian.html;

 server_name my.site www.my.site;

 location / {
   proxy_pass http://localhost:8000;
   include /etc/nginx/proxy_params;
 }

 location ~* \.(js|css|jpg|jpeg|gif|png|svg|ico|pdf|html|htm)$ {
expires      30d;
 }

 location @proxy {
    proxy_pass http://127.0.0.1:8000;
    include /etc/nginx/proxy_params;
 }
 location ~* \.php$ {
    proxy_pass http://127.0.0.1:8000;
    include /etc/nginx/proxy_params;
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
 }
}

apache2/sites-available/my.site

ServerName my.site
ServerAlias www.my.site

ServerAdmin webmaster@localhost
DocumentRoot /var/www/my.site/httpdocs

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

apache2/ports.conf

NameVirtualHost 127.0.0.1:8000
Listen 8000

<IfModule ssl_module>
    Listen 443
</IfModule>

<IfModule mod_gnutls.c>
    Listen 443
</IfModule>

At the work in day off with no idea how to fix the server. Any advice is appreciated.

Body:
nginx config

map $sent_http_content_type $expires {
    default               off;
    ~css                  max;
    ~javascript       max;
    ~image             max;
    ~font-woff        max;
    ~video               max;
    ~zip                   max;
    ~txt                    max;
  }
expires                 $expires;

server {
listen 80;
    server_name exemple.com;
    root /home/to/exemple.com;
    index index.php index.html;

gzip                    on;
gzip_min_length         128;
gzip_http_version       1.1;
gzip_buffers           128 32k;
gzip_types
    text/css
    text/javascript
    text/xml
    text/plain
    text/x-component
    application/javascript
    application/x-javascript
    application/json
    application/xml
    application/rss+xml
    application/atom+xml
    font/truetype
    font/opentype
    application/vnd.ms-fontobject
    image/svg+xml;
gzip_static  on;
gzip_proxied            expired no-cache no-store private auth;
gzip_disable            "msie6";
gzip_vary                on;

location / {
   proxy_pass http://127.0.0.1:8000;
   proxy_set_header Host $host;
   proxy_set_header X-Real-IP $remote_addr;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_set_header X-Forwarded-Proto $scheme;
   }
}

apache config

php 7 mod

apt install libapache2-mod-php7.0

php5 mod

apt install libapache2-mod-php

Include for example php7.0 mod

a2enmod php7.0

VirtualHost config apache

<VirtualHost *:8000>
  ServerName exemple.com
  DocumentRoot /home/to/exemple.com
  ErrorLog ${APACHE_LOG_DIR}/error.log
  CustomLog ${APACHE_LOG_DIR}/access.log combined
  RewriteEngine On
<Directory /home/to/exemple.com/>
  php_admin_flag engine on
  Options -ExecCGI -Indexes +FollowSymLinks
  AllowOverride All
  Require all granted
</Directory>
</VirtualHost>

Remove NameVirtualHost 127.0.0.1:8000 in apache2.conf
Paste ServerName 127.0.0.1

systemctl restart apache2
systemctl restart nginx

Original post apache2+nginx proxy


问:
how to see summary image of former steps in tensorboard
I'm using tensorboard to visualize the image(CelebA) generated by dcgan
Specifically, I created a writer and image summary with:

```<code>tf.summary.image('generated', image_output)
summary_op = tf.summary.merge_all()
writer = tf.summary.FileWriter(logdir, graph)
summary = sess.run(summary_op)
</code>```

after each 100 step I would add a image summary with:

```<code>writer.add_summary(image, step)
</code>```

I think the event file of tensorboard save all the images generated at each step since the event file keeps growing larger. But when I run tensorboard I can only see the latest image.
Is there any way to see the former images? Or they are not saved in the event file and I can't see them.

答:
The issue that you have raised was common enough to warrant a feature request several months ago that was rolled into TensorFlow 1.1.0.

A small sliding bar appears below each image summary in Tensorboard with which you can scroll through the summary steps if you upgrade to TensorFlow 1.1.0+.

Body:
I'm using tensorboard to visualize the image(CelebA) generated by dcgan
Specifically, I created a writer and image summary with:

tf.summary.image('generated', image_output)
summary_op = tf.summary.merge_all()
writer = tf.summary.FileWriter(logdir, graph)
summary = sess.run(summary_op)

after each 100 step I would add a image summary with:

writer.add_summary(image, step)

I think the event file of tensorboard save all the images generated at each step since the event file keeps growing larger. But when I run tensorboard I can only see the latest image.
Is there any way to see the former images? Or they are not saved in the event file and I can't see them.


问:
How to get numbers after comma in F#
I want to get 4 numbers after comma in F# :
This is my code : </p>

```<code>// Learn more about F# at http://fsharp.org
// See the 'F# Tutorial' project for more help.

open System

[<EntryPoint>]
let main argv =

    let num = Console.ReadLine() |> float
    Console.WriteLine(num)

    Console.Read() |>ignore
    0
</code>```

答:
And this's result :</p>

```<code>open System

[<EntryPoint>]
let main argv =

    let num = Math.Round(Console.ReadLine() |> float, 3)
    Console.WriteLine(num)

    Console.Read() |>ignore
    0
</code>```

Title: How to get numbers after comma in F#

Body:
I want to get 4 numbers after comma in F# :
This is my code :

// Learn more about F# at http://fsharp.org
// See the 'F# Tutorial' project for more help.

open System

[<EntryPoint>]
let main argv =

    let num = Console.ReadLine() |> float
    Console.WriteLine(num)

    Console.Read() |>ignore
    0

Body:
And this's result :

open System

[<EntryPoint>]
let main argv =

    let num = Math.Round(Console.ReadLine() |> float, 3)
    Console.WriteLine(num)

    Console.Read() |>ignore
    0


问:
how fetch multiple rows from mysql using prepared statements
With prepare statement i am fetching only one row , i tried while to loop all rows but is only one row witch is being fetched.please assist me on how i fetch all rows from database instead of one

PHP function :
     .....

```<code>  public function StudentsOfParent($mobile){
 $stmt = $this->conn->prepare("SELECT
                         a.id,
                         a.name,
                         a.mobile,
                         c.id as sutdentId,
                         c.user_id,
                         c.full_name,
                         c.school,
                         c.level,
                         c.year,
                         c.id
                         from users a
                         join students c
                         on a.id = c.user_id where a.mobile= ?");

    $stmt->bind_param("i", $mobile);
    if ($stmt->execute()) {

   while ($user = $stmt->get_result()->fetch_assoc())
            {
        $stmt->close();

            // return user's results
            return $user;
                }
            }
        else {
        return NULL;
    }
}
  .....
</code>```

External php file to access above function :  retrieve.php:

```<code>  <?php
  include './DbHandler.php';
   $db = new DbHandler();
    // json response array
  $response = array("error" => FALSE);
     if (isset($_POST['mobile'])){
  $mobile = $_POST['mobile'];
   $user = $db->StudentsOfParent($mobile);
    if ($user != false) {
      // user found successfully
        $response["error"] = FALSE;
        $response["user"]["id"] = $user["id"];
 $response["user"]["sutdentId"] = $user["sutdentId"];
 $response["user"]["user_id"] = $user["user_id"];
 $response["user"]["full_name"] = $user["full_name"];
 $response["user"]["school"] = $user["school"];
 $response["user"]["level"] = $user["level"];
 $response["user"]["year"] = $user["year"];
        // $response["user"]["photo"] = $user["photo"];
                     echo json_encode($response);
         // $json = json_encode($response);
    }    else {
    // user is not found with the credentials
    $response["error"] = TRUE;
    $response["error_msg"] = "Sorry we could not find you !";
    echo json_encode($response);
   }
    }
   else {
    // required post params is missing
   $response["error"] = TRUE;
    $response["error_msg"] = "Required parameter is missing!";
   echo json_encode($response);
   }
  ?>
</code>```

答:
With prepare statement i am fetching only one row , i tried while to loop all rows but is only one row witch is being fetched.

That's because you're returning $user in the first iteration of while loop itself, the loop won't even go on for the 2nd iteration. Plus, you're also closing the statement object $stmt->close(); in the first iteration itself. Instead your code block should be like this:

```<code>// your code
$stmt->execute();
$result = $stmt->get_result();
$usersArr = array();
while ($user = $result->fetch_assoc()){
    $usersArr[] = $user;
}
return $usersArr;
</code>```

Now the returned $usersArr array is a multidimensional array, which you need to appropriately loop through to get all users' details. If you want to see the complete array structure, do var_dump($usersArr);.

Body:
With prepare statement i am fetching only one row , i tried while to loop all rows but is only one row witch is being fetched.please assist me on how i fetch all rows from database instead of one

PHP function :
     .....

  public function StudentsOfParent($mobile){
 $stmt = $this->conn->prepare("SELECT
                         a.id,
                         a.name,
                         a.mobile,
                         c.id as sutdentId,
                         c.user_id,
                         c.full_name,
                         c.school,
                         c.level,
                         c.year,
                         c.id
                         from users a
                         join students c
                         on a.id = c.user_id where a.mobile= ?");

    $stmt->bind_param("i", $mobile);
    if ($stmt->execute()) {

   while ($user = $stmt->get_result()->fetch_assoc())
            {
        $stmt->close();

            // return user's results
            return $user;
                }
            }
        else {
        return NULL;
    }
}
  .....

External php file to access above function :  retrieve.php:

  <?php
  include './DbHandler.php';
   $db = new DbHandler();
    // json response array
  $response = array("error" => FALSE);
     if (isset($_POST['mobile'])){
  $mobile = $_POST['mobile'];
   $user = $db->StudentsOfParent($mobile);
    if ($user != false) {
      // user found successfully
        $response["error"] = FALSE;
        $response["user"]["id"] = $user["id"];
 $response["user"]["sutdentId"] = $user["sutdentId"];
 $response["user"]["user_id"] = $user["user_id"];
 $response["user"]["full_name"] = $user["full_name"];
 $response["user"]["school"] = $user["school"];
 $response["user"]["level"] = $user["level"];
 $response["user"]["year"] = $user["year"];
        // $response["user"]["photo"] = $user["photo"];
                     echo json_encode($response);
         // $json = json_encode($response);
    }    else {
    // user is not found with the credentials
    $response["error"] = TRUE;
    $response["error_msg"] = "Sorry we could not find you !";
    echo json_encode($response);
   }
    }
   else {
    // required post params is missing
   $response["error"] = TRUE;
    $response["error_msg"] = "Required parameter is missing!";
   echo json_encode($response);
   }
  ?>

Body:
With prepare statement i am fetching only one row , i tried while to loop all rows but is only one row witch is being fetched.

That's because you're returning $user in the first iteration of while loop itself, the loop won't even go on for the 2nd iteration. Plus, you're also closing the statement object $stmt->close(); in the first iteration itself. Instead your code block should be like this:

// your code
$stmt->execute();
$result = $stmt->get_result();
$usersArr = array();
while ($user = $result->fetch_assoc()){
    $usersArr[] = $user;
}
return $usersArr;

Now the returned $usersArr array is a multidimensional array, which you need to appropriately loop through to get all users' details. If you want to see the complete array structure, do var_dump($usersArr);.

ContentLicense: CC BY-SA 4.0


问:
SQL construct and renew date intervals for entities based on daily incoming data
I have a daily incoming data with following format:
(id, dat, state, val) where id is unique entity, dat is date (i.e. ISO 'yyyy-MM-dd'), state is a state of an entity, val is a value of an entity at this state.

I need to transform it into data like that format: (id, state, val, dat1, dat2, month) where dat1 and dat2 are datestamps between which the entity id has state state with val value within month.

I'm struggling to find out a correct way to collect and persist data like this format. I understand that solution must meet the following requirements:

1) If id has changed his state from st1 to st2 in new daily data(i.e. on 2017-01-27), there should be a row with closed period like that:

```<code>(id=1, state=st1, val=2.5, dat1='2017-01-15', dat2='2017-01-26', month='2017-01-01')
</code>```

and a row for state st2 like that:

```<code>(id=1, state=st2, val=5.5, dat1='2017-01-27', dat2='2017-01-31', month='2017-01-01')
</code>```

2) If on 2017-02-14 there is a new id for a table, there should be an inserted row like that:

(id=2, state=st3, val=1.5, dat1='2017-02-01', dat2='2017-02-28', month='2017-02-01'),
so if there is a new id in daily data and this id doesn't exist in previous periods we put his birth date as beginning of the period and hold the closing date as end of month until there is a change of state of this id within February month.

3) A table should be designed in the way allowing having history of table versions before insert\update a new daily piece of data (bi-temporal table?) in order to have an opportunity to discard wrong data and rollback.

4) There should be a query for table which is able to detect overlapping date intervals of the same ID (force ID integrity over time).

5) There should be some necessary indexes for this kind of data. Id should be a foreign key.

6) Should there be a trigger which works when a new piece of data has arrived into load-table and makes operations described in 1),2),3) ?

Could anyone tell the literature or known approaches for this kind of tasks?
I believe it is solved task but I couldn't determine the proper name of data model and find any clear examples for that kind of data.

答:
Below code updates Entity state table based on "Daily Data".
I have created my own sample data, that to the best of my understanding fits your requirements.

```<code>CREATE TABLE #DailyData( id INT, [state] VARCHAR( 10 ), val FLOAT, dat1 DATETIME )
CREATE TABLE #EntityState( id INT, [state] VARCHAR( 10 ), val FLOAT, dat1 DATETIME, dat2 DATETIME, [month] DATETIME )
INSERT INTO #EntityState
SELECT 1, 'st2', 4.6, '01-Jul-2017', '08-Jul-2017', '01-Jul-2017' UNION ALL
SELECT 1, 'st1', 1.2, '09-Jul-2017', '31-Jul-2017', '01-Jul-2017' UNION ALL
SELECT 2, 'st1', 2.2, '08-Jul-2017', '31-Jul-2017', '01-Jul-2017'

INSERT INTO #DailyData
SELECT 1, 'st3', 5.6, '15-Jul-2017' UNION ALL
SELECT 1, 'st2', 4.6, '01-Aug-2017' UNION ALL
SELECT 2, 'st2', 2.5, '10-Jul-2017'

SELECT 'Before', * FROM #EntityState
;WITH Q0 AS(
    -- Insert current state
    SELECT id, [state], val, dat1
    FROM
    ( SELECT id, [state], val, dat1, ROW_NUMBER() OVER( PARTITION BY id ORDER BY dat1 DESC ) AS LatestDate
    FROM #EntityState ) AS CurrentState
    WHERE LatestDate = 1
    UNION ALL
    -- Combine with Daily Import
    SELECT id, [state], val, dat1
    FROM #DailyData
)
,
-- Add Date order column
Q1 AS (
    SELECT id, [state], val, dat1, ROW_NUMBER() OVER( PARTITION BY id ORDER BY dat1 ASC ) AS DateOrder
    FROM Q0
    )
-- Merge new Entity states with Existing
MERGE INTO #EntityState AS T
    USING
            -- New Entity states
            ( SELECT Prev.id, Prev.[state], Prev.val, Prev.dat1, Next.dat1 AS dat2
            FROM Q1 AS Prev
                LEFT JOIN Q1 AS Next ON Prev.id = Next.id AND Prev.DateOrder + 1 = Next.DateOrder ) AS S
        ON T.id = S.id AND T.dat1 = S.dat1 AND T.[state] = S.[state]
    -- Update dat2 on last day's state
    WHEN MATCHED AND T.dat2 = EOMONTH( T.dat1 )
        THEN UPDATE
            SET T.dat2 = S.dat2
    -- Add new Entity State
    WHEN NOT MATCHED BY TARGET THEN
        INSERT( id, state, val, dat1, dat2, [month] )
            VALUES( S.id, S.state, S.val, S.dat1, ISNULL( S.dat2, EOMONTH( S.dat1 )),
                    DATEADD( month, DATEDIFF( month, 0, S.dat1 ), 0 ));

SELECT 'After', * FROM #EntityState
</code>```

This code was adapted from:
Count seconds on switch interval SQL Server

Body:
I have a daily incoming data with following format:
(id, dat, state, val) where id is unique entity, dat is date (i.e. ISO 'yyyy-MM-dd'), state is a state of an entity, val is a value of an entity at this state.

I need to transform it into data like that format: (id, state, val, dat1, dat2, month) where dat1 and dat2 are datestamps between which the entity id has state state with val value within month.

I'm struggling to find out a correct way to collect and persist data like this format. I understand that solution must meet the following requirements:

1) If id has changed his state from st1 to st2 in new daily data(i.e. on 2017-01-27), there should be a row with closed period like that:

(id=1, state=st1, val=2.5, dat1='2017-01-15', dat2='2017-01-26', month='2017-01-01')

and a row for state st2 like that:

(id=1, state=st2, val=5.5, dat1='2017-01-27', dat2='2017-01-31', month='2017-01-01')

2) If on 2017-02-14 there is a new id for a table, there should be an inserted row like that:

(id=2, state=st3, val=1.5, dat1='2017-02-01', dat2='2017-02-28', month='2017-02-01'),
so if there is a new id in daily data and this id doesn't exist in previous periods we put his birth date as beginning of the period and hold the closing date as end of month until there is a change of state of this id within February month.

3) A table should be designed in the way allowing having history of table versions before insert\update a new daily piece of data (bi-temporal table?) in order to have an opportunity to discard wrong data and rollback.

4) There should be a query for table which is able to detect overlapping date intervals of the same ID (force ID integrity over time).

5) There should be some necessary indexes for this kind of data. Id should be a foreign key.

6) Should there be a trigger which works when a new piece of data has arrived into load-table and makes operations described in 1),2),3) ?

Could anyone tell the literature or known approaches for this kind of tasks?
I believe it is solved task but I couldn't determine the proper name of data model and find any clear examples for that kind of data.

Body:
Below code updates Entity state table based on "Daily Data".
I have created my own sample data, that to the best of my understanding fits your requirements.

CREATE TABLE #DailyData( id INT, [state] VARCHAR( 10 ), val FLOAT, dat1 DATETIME )
CREATE TABLE #EntityState( id INT, [state] VARCHAR( 10 ), val FLOAT, dat1 DATETIME, dat2 DATETIME, [month] DATETIME )
INSERT INTO #EntityState
SELECT 1, 'st2', 4.6, '01-Jul-2017', '08-Jul-2017', '01-Jul-2017' UNION ALL
SELECT 1, 'st1', 1.2, '09-Jul-2017', '31-Jul-2017', '01-Jul-2017' UNION ALL
SELECT 2, 'st1', 2.2, '08-Jul-2017', '31-Jul-2017', '01-Jul-2017'

INSERT INTO #DailyData
SELECT 1, 'st3', 5.6, '15-Jul-2017' UNION ALL
SELECT 1, 'st2', 4.6, '01-Aug-2017' UNION ALL
SELECT 2, 'st2', 2.5, '10-Jul-2017'

SELECT 'Before', * FROM #EntityState
;WITH Q0 AS(
    -- Insert current state
    SELECT id, [state], val, dat1
    FROM
    ( SELECT id, [state], val, dat1, ROW_NUMBER() OVER( PARTITION BY id ORDER BY dat1 DESC ) AS LatestDate
    FROM #EntityState ) AS CurrentState
    WHERE LatestDate = 1
    UNION ALL
    -- Combine with Daily Import
    SELECT id, [state], val, dat1
    FROM #DailyData
)
,
-- Add Date order column
Q1 AS (
    SELECT id, [state], val, dat1, ROW_NUMBER() OVER( PARTITION BY id ORDER BY dat1 ASC ) AS DateOrder
    FROM Q0
    )
-- Merge new Entity states with Existing
MERGE INTO #EntityState AS T
    USING
            -- New Entity states
            ( SELECT Prev.id, Prev.[state], Prev.val, Prev.dat1, Next.dat1 AS dat2
            FROM Q1 AS Prev
                LEFT JOIN Q1 AS Next ON Prev.id = Next.id AND Prev.DateOrder + 1 = Next.DateOrder ) AS S
        ON T.id = S.id AND T.dat1 = S.dat1 AND T.[state] = S.[state]
    -- Update dat2 on last day's state
    WHEN MATCHED AND T.dat2 = EOMONTH( T.dat1 )
        THEN UPDATE
            SET T.dat2 = S.dat2
    -- Add new Entity State
    WHEN NOT MATCHED BY TARGET THEN
        INSERT( id, state, val, dat1, dat2, [month] )
            VALUES( S.id, S.state, S.val, S.dat1, ISNULL( S.dat2, EOMONTH( S.dat1 )),
                    DATEADD( month, DATEDIFF( month, 0, S.dat1 ), 0 ));

SELECT 'After', * FROM #EntityState

This code was adapted from:
Count seconds on switch interval SQL Server


问:
Is there a Java equivalent for Python's map function?
I would like to easily transform a collection (list) of objects of class A to a collection of objects of class B, just as Python's map function does it. Is there any "well-known" implementation of this (some kind of library)? I've already searched for it in Apache's commons-lang but with no luck. </p>

答:
There are several functional libraries mentioned here, most of which probably cover map:

http://www.cs.chalmers.se/~bringert/hoj/
  programmer (includes Java 5.0 generics
  support). Little documentation.

http://jakarta.apache.org/commons/sandbox/functor/
  doesn't look like it is maintained,
  doesn't support generics. Little
  documentation.

http://devnet.developerpipeline.com/documents/s=9851/q=1/ddj0511i/0511i.html
  library.

http://functionalj.sourceforge.net

http://www.functologic.com/orbital/

http://jga.sourceforge.net/
  programming in java (includes
  generics). Looking forward to more
  documentation, perhaps better
  organization of the API.


问:
div has as extra unwanted space on top inside pre
I can't understand why there is an empty space on the top. I haven't applied any styles to it

```
  <div class="codeBlock">
    <ol>
     <li>(function() {</li>
     <li>function $codeBlock() {</li>
     <li>return {};</li>
     </li>}</li>
    </ol>
  </div>
``````

答:
pre has white-space: pre default style. From W3Schrools about white-space: pre:

Whitespace is preserved by the browser. Text will only wrap on line breaks. Acts like the ```</code> tag in HTML</p>
</blockquote>

<p>Of course you can move <code>pre</code>'s content to one line but not sure this will flexible and maintainable.</p>

<p>So you can change <code>white-space</code> CSS property to <code>normal</code> or <code>nowrap</code> (depending on need of wrapping):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>pre {
  white-space: nowrap;
}

.codeBlock ol, li {
  margin: 0;
}</code>```

```
  <div class="codeBlock">
    <ol>
     <li>(function() {</li>
     <li>function $codeBlock() {</li>
     <li>return {};</li>
     </li>}</li>
    </ol>
  </div>
``````
</div>
</div>
</p>

<p>If you want to return <code>white-space</code> behaviour for <code>ol</code> you can also set </p>

```.codeBlock ol { white-space: pre }
```

Body:
I can't understand why there is an empty space on the top. I haven't applied any styles to it

(function() {

function $codeBlock() {

return {};

}

Body:
pre has white-space: pre default style. From W3Schrools about white-space: pre:

Whitespace is preserved by the browser. Text will only wrap on line breaks. Acts like the <pre> tag in HTML

Of course you can move pre's content to one line but not sure this will flexible and maintainable.

So you can change white-space CSS property to normal or nowrap (depending on need of wrapping):

pre {
  white-space: nowrap;
}

.codeBlock ol, li {
  margin: 0;
}

<pre>
  <div class="codeBlock">
    <ol>
     <li>(function() {</li>
     <li>function $codeBlock() {</li>
     <li>return {};</li>
     </li>}</li>
    </ol>
  </div>
</pre>

If you want to return white-space behaviour for ol you can also set

.codeBlock ol { white-space: pre }


问:
Enum Types: get raw value from key
How to get the raw value from a enum passing the key value? Must work for any enum types working like an extension of enum types.
Any mirror reflection, mappable or RawRepresentable solutions are welcome.

I would like something like this:

```<code>enum Test : String {
     case One = "1"
}

Test.rawValueFromKey(keyValue: "One") // Must return "1"
// I don't want the solution below, I must get the rawValue through the key name as String.
Test.One.rawValue
</code>```

I do need to get the rawValue passing the name of the key as a String. Otherwise, I will need to make a switch or many if/else conditions. I have a big Enum and I don't want to check the string passed in a switch for example and pass Test.One.rawValue. I would like to get the rawValue directly through the key as String, just like in a dictionary.

I also don't want the code below, because I have a Enum of 40 items and I think it is ugly to make a switch of 40 items.

```<code>switch keyValue {
      case "One":
          return Test.One.rawValue
          break
}
</code>```

I want something like this:

```<code>func rawValueFromKey (keyValue: String) -> Test {
    // code here to get the rawValue through the keyValue as String
    // return the proper Test Enum
}
</code>```

I tried some possible solutions using Mirror reflection and enum iterations to find the rawValue through the keyValue but didn't work.

Please give the solution in both Swift 2 and 3.

Thanks

答: As far as I know, you can't reflect on types so I think you will be able to achieve this only with CustomReflectable or maybe using localized strings for mapping the values/keys. Invariably you'll have to map somehow.

Title: Enum Types: get raw value from key

Body:
How to get the raw value from a enum passing the key value? Must work for any enum types working like an extension of enum types.
Any mirror reflection, mappable or RawRepresentable solutions are welcome.

I would like something like this:

enum Test : String {
     case One = "1"
}

Test.rawValueFromKey(keyValue: "One") // Must return "1"
// I don't want the solution below, I must get the rawValue through the key name as String.
Test.One.rawValue

I do need to get the rawValue passing the name of the key as a String. Otherwise, I will need to make a switch or many if/else conditions. I have a big Enum and I don't want to check the string passed in a switch for example and pass Test.One.rawValue. I would like to get the rawValue directly through the key as String, just like in a dictionary.

I also don't want the code below, because I have a Enum of 40 items and I think it is ugly to make a switch of 40 items.

switch keyValue {
      case "One":
          return Test.One.rawValue
          break
}

I want something like this:

func rawValueFromKey (keyValue: String) -> Test {
    // code here to get the rawValue through the keyValue as String
    // return the proper Test Enum
}

I tried some possible solutions using Mirror reflection and enum iterations to find the rawValue through the keyValue but didn't work.

Please give the solution in both Swift 2 and 3.

Thanks


问:
How to decompress zlib files created with ByteArray.compress?
I work on a Flex application that creates compressed files and uploads them on a server. The files are created with ByteArray.compress method, which is zlib compression. I can decompress them using Python API on the server but I prefer to keep the files compressed there. I want to be able to download and decompress the files later, however WinZip and WinRar fail to decompress them. When I google for zlib utility, I only find zlib dll library. I need a simple application for Windows (and/or Linux) that is capable of decompressing zlib files.</p>

答:
So, zlib compression will certainly compress the data down, but it doesn't include the file headers that make it a "ZIP" file that can be opened using apps like Windows, WinZip or WinRar.

Adobe has some documents that explain how to READ a zip file, including information about the header.  If you want to WRITE a zip file, just use this information to write out the header with the data.

Good luck!


问:
select column names containing string programmatically
Given a data frame like:

```<code>df <- data.frame(z_a = 1:2,
                 z_b = 1:2,
                 y_a = 3:4,
                 y_b = 3:4)
</code>```

I can select columns names that contain a character with:

```<code>library(dplyr)
df %>% select(contains("a"), contains("b"))

  z_a y_a z_b y_b
1   1   3   1   3
2   2   4   2   4
</code>```

NOTE that the column order has changed. Columns containing a come first before columns containing b

I'd like to select column names that contain characters in a vector and that reorders the columns.

```<code>searchfor <- letters[1:2]
</code>```

Using searchfor, I'd like to make the following expression and use it in a select statement:

```<code>E <- quote(contains(searchfor[1]), contains(searchfor[2]))
df %>% select_(E)
</code>```

答:
purrr solution:

```<code>library(purrr)
ind_lgl <- map(letters[1:2], ~ grepl(.x, names(df), fixed = TRUE)) %>%
  pmap_lgl(`|`)

df[ind_lgl]
</code>```

With the pipe:

```<code>df %>%
  `[`(map(letters[1:2], ~ grepl(.x, names(df), fixed = TRUE)) %>%
        pmap_lgl(`|`))
</code>```

If you to get the right order:

```<code>rank <- map(letters[1:2], ~ grepl(.x, names(df), fixed = TRUE)) %>%
  pmap(c) %>%
  map(which)

ind_chr <- data_frame(colnames = names(df), rank) %>%
  mutate(l = lengths(rank)) %>%
  filter(l > 0) %>%
  mutate(rank = unlist(map(rank, ~ .x[[1]]))) %>%
  arrange(rank) %>%
  pull(colnames)

df[ind_chr]
</code>```

But it is not pretty...

Body:
Given a data frame like:

df <- data.frame(z_a = 1:2,
                 z_b = 1:2,
                 y_a = 3:4,
                 y_b = 3:4)

I can select columns names that contain a character with:

library(dplyr)
df %>% select(contains("a"), contains("b"))

  z_a y_a z_b y_b
1   1   3   1   3
2   2   4   2   4

NOTE that the column order has changed. Columns containing a come first before columns containing b

I'd like to select column names that contain characters in a vector and that reorders the columns.

searchfor <- letters[1:2]

Using searchfor, I'd like to make the following expression and use it in a select statement:

E <- quote(contains(searchfor[1]), contains(searchfor[2]))
df %>% select_(E)

Body:
purrr solution:

library(purrr)
ind_lgl <- map(letters[1:2], ~ grepl(.x, names(df), fixed = TRUE)) %>%
  pmap_lgl(`|`)

df[ind_lgl]

With the pipe:

df %>%
  `[`(map(letters[1:2], ~ grepl(.x, names(df), fixed = TRUE)) %>%
        pmap_lgl(`|`))

If you to get the right order:

rank <- map(letters[1:2], ~ grepl(.x, names(df), fixed = TRUE)) %>%
  pmap(c) %>%
  map(which)

ind_chr <- data_frame(colnames = names(df), rank) %>%
  mutate(l = lengths(rank)) %>%
  filter(l > 0) %>%
  mutate(rank = unlist(map(rank, ~ .x[[1]]))) %>%
  arrange(rank) %>%
  pull(colnames)

df[ind_chr]

But it is not pretty...


问:
Django CRUD operations for multiple records - transaction.atomic vs bulk_create
I have a Django 1.10 model, and a simple model:

I have a simple REST endpoint designed for testing purposes:

```<code>@api_view(['POST'])
@transaction.atomic
def r_test(request):
    for record in request.data:
        serializer = TestSerializer(data = record)
        if serializer.is_valid():
           serializer.save()
</code>```

...that takes 9 seconds (too slow) to execute for one 100 records.

If I rewrite it the following way, it executes instantly.

```<code>@api_view(['POST'])
def r_test(request):
    obj_list = []
    for record in request.data:
       obj = Test(field1 = record['field1'])
       obj_list.append(obj)
    Test.objects.bulk_create(obj_list)
</code>```

What bothers me is that I have read in many sources that wrapping function into a transaction (which I do by adding a decorator @transaction.atomic) would significantly improve insert operations in case of multiple operations. But I can't see this now.

So the question is, does only bulk_create() deliver super-fast speed for inserting big data, or there's something I am doing wrong with transaction.atomic?

Update: Moreover, I have ATOMIC_REQUESTS set to True in my settings. BTW, could it be that something is wrong in the settings? Like, say, Debug = True hinders Django from executing queries in a single transaction ?

Update 2 I have tried both ways with decorator and by wrapping the for loop in with transaction.atomic():. And still I observe instant execution only with bulk_create()

Update 3. My DB is MySQL

答:
Transactions do generally speed up the inserting process. Since you are already in a transaction due to ATOMIC_REQUESTS = True, you won't notice a difference when using @transaction.atomic(). The main reason transaction are faster is that committing takes time. Without a transaction, Django uses auto-commit mode, so every query results in a commit.

Transactions are not a magic bullet when it comes to performance. You are still performing 100 queries, and 100 roundtrips to the database. Even if your database runs on the same system, that is going to take some time. That's where bulk_create comes into play. It performs a single query to insert all the data at once. You've just saved yourself 99 database roundtrips. That is way more significant than any speedup caused by transactions.

Body:
I have a Django 1.10 model, and a simple model:

I have a simple REST endpoint designed for testing purposes:

@api_view(['POST'])
@transaction.atomic
def r_test(request):
    for record in request.data:
        serializer = TestSerializer(data = record)
        if serializer.is_valid():
           serializer.save()

...that takes 9 seconds (too slow) to execute for one 100 records.

If I rewrite it the following way, it executes instantly.

@api_view(['POST'])
def r_test(request):
    obj_list = []
    for record in request.data:
       obj = Test(field1 = record['field1'])
       obj_list.append(obj)
    Test.objects.bulk_create(obj_list)

What bothers me is that I have read in many sources that wrapping function into a transaction (which I do by adding a decorator @transaction.atomic) would significantly improve insert operations in case of multiple operations. But I can't see this now.

So the question is, does only bulk_create() deliver super-fast speed for inserting big data, or there's something I am doing wrong with transaction.atomic?

Update: Moreover, I have ATOMIC_REQUESTS set to True in my settings. BTW, could it be that something is wrong in the settings? Like, say, Debug = True hinders Django from executing queries in a single transaction ?

Update 2 I have tried both ways with decorator and by wrapping the for loop in with transaction.atomic():. And still I observe instant execution only with bulk_create()

Update 3. My DB is MySQL


问:
Find the issues of SQL
I got a questions from a test, it seems an concept question or logic question, so no data at all. Please read:

Assuming there's no syntax error and the column names and table names are correct, what's wrong with the MySQL query below?

-- FOR EVERY USER WE HAVE, this is supposed to return the number of messages they sent

```<code>select u.user_id, sum(case when um.message_id is not null then 1 else 0 end) as number_of_messages_sent
from users u left join
     users_messages um
     on um.user_id = u.user_id
where um.status = 'sent'
group by u.user_id;
</code>```

If anyone have any ideas, please help me.

答:
The where clause is turning the left join into an inner join.  So it is only returning users who have sent at least one message.  That is not the intent of the question.

A better way to write the query uses count() and fixes the problem by moving condition to the on clause:

```<code>select u.user_id, count(um.message_id) as number_of_messages_sent
from users u left join
     users_messages um
     on um.user_id = u.user_id and um.status = 'sent'
group by u.user_id;
</code>```

Title: Find the issues of SQL

Body:
I got a questions from a test, it seems an concept question or logic question, so no data at all. Please read:

Assuming there's no syntax error and the column names and table names are correct, what's wrong with the MySQL query below?

-- FOR EVERY USER WE HAVE, this is supposed to return the number of messages they sent

select u.user_id, sum(case when um.message_id is not null then 1 else 0 end) as number_of_messages_sent
from users u left join
     users_messages um
     on um.user_id = u.user_id
where um.status = 'sent'
group by u.user_id;

If anyone have any ideas, please help me.

Body:
The where clause is turning the left join into an inner join.  So it is only returning users who have sent at least one message.  That is not the intent of the question.

A better way to write the query uses count() and fixes the problem by moving condition to the on clause:

select u.user_id, count(um.message_id) as number_of_messages_sent
from users u left join
     users_messages um
     on um.user_id = u.user_id and um.status = 'sent'
group by u.user_id;


问:
Building fragment stack for One Activity Many Fragment App
My App has only one activity and lots of fragments.

In my activty's XML, I just have a FrameLayout on which I replace/add/hide/show various fragments.

Imagine Fragment A is the first fragment the user sees when they open the app.

Click something in Fragment A to launch Fragment B and click something in Fragment B to launch Fragment C.

So the navigation is can be illustrated as follows :

Fragment A  --> Fragment B -->  Fragment C

I want to launch the app and show Fragment C directly from notification.

However, how can I provide back navigation from Fragment C, as such clicking back would go to Fragment B and clicking back again go to Fragment A ?

i.e How can I inject the following stack structure ?

Fragment A  <-- Fragment B <-- Fragment C

答:
Yes, you can do this. Since support library v26 you can build the stack with fragments without significant cost.
In your activity make the following:

```<code>    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, new FragmentA())
            .addToBackStack("fragmentA")
            .setReorderingAllowed(true)
            .commit();

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, new FragmentB())
            .addToBackStack("fragmentB")
            .setReorderingAllowed(true)
            .commit();

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, new FragmentC())
            .addToBackStack("fragmentC")
            .setReorderingAllowed(true)
            .commit();
</code>```

Keep in mind that FragmentA and FragmentB will behave in a bit different way after pressing back on FragmentC due to setReorderingAllowed. onCreateView won't be called for FragmentA and FragmentB after they were added to stack, only in FragmentC onCreateView will be called. For FragmentA and FragmentB only onCreate will be called.

Body:
Yes, you can do this. Since support library v26 you can build the stack with fragments without significant cost.
In your activity make the following:

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, new FragmentA())
            .addToBackStack("fragmentA")
            .setReorderingAllowed(true)
            .commit();

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, new FragmentB())
            .addToBackStack("fragmentB")
            .setReorderingAllowed(true)
            .commit();

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, new FragmentC())
            .addToBackStack("fragmentC")
            .setReorderingAllowed(true)
            .commit();

Keep in mind that FragmentA and FragmentB will behave in a bit different way after pressing back on FragmentC due to setReorderingAllowed. onCreateView won't be called for FragmentA and FragmentB after they were added to stack, only in FragmentC onCreateView will be called. For FragmentA and FragmentB only onCreate will be called.


问:
Setting toolbar title not working in onCreate()
I am having issues setting the title of my toolbar, which only seems to work when there is a delay.

For example a simple oncreate() method for my app 'Forecast'

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    setSupportActionBar(_toolbar);
    setTitle("ABCDEFG");
}
</code>```

When the app is run, the toolbar has the name of my app, not 'ABCDEFG'.

However, if I put a 200 millisecond delay before setting the title..

```<code>    Observable.just("ABCDEFG")
            .delay(200,TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(this::setTitle);
</code>```

My Toolbar title is correctly displayed as "ABCDEFG"

this is the same when it comes to doing anything with the Toolbar, does anyone know what is actually going on here? and how I can solve this without having to put a delay in?

Here is my toolbar xml..

```<code><android.support.design.widget.AppBarLayout
    android:id="@+id/appBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        app:layout_collapseMode="pin"
        app:layout_scrollFlags="scroll"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>
</code>```

Thanks for your help!

EDIT forgot to mention setTitle() simply calls _toolbar.setTitle(title)

答: As maRShmallow stated, I changed _toolbar.setTitle() to getSupportActionBar().setTitle()</p>

Body:
I am having issues setting the title of my toolbar, which only seems to work when there is a delay.

For example a simple oncreate() method for my app 'Forecast'

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    setSupportActionBar(_toolbar);
    setTitle("ABCDEFG");
}

When the app is run, the toolbar has the name of my app, not 'ABCDEFG'.

However, if I put a 200 millisecond delay before setting the title..

    Observable.just("ABCDEFG")
            .delay(200,TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(this::setTitle);

My Toolbar title is correctly displayed as "ABCDEFG"

this is the same when it comes to doing anything with the Toolbar, does anyone know what is actually going on here? and how I can solve this without having to put a delay in?

Here is my toolbar xml..

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        app:layout_collapseMode="pin"
        app:layout_scrollFlags="scroll"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

Thanks for your help!

EDIT forgot to mention setTitle() simply calls _toolbar.setTitle(title)


问:
how to replace a character INSIDE the text content of many files automatically?
I have a folder /myfolder containing many latex tables.

I need to replace a character in each of them, namely replacing any minus sign -, by an en dash –.

Just to be sure: we are replacing hypens INSIDE all of the tex file in that folder. I dont care about the tex file names.

Doing that manually would be a nightmare (too many files, too many minuses). Is there a way to loop over the files automatically and do the replacement? A solution in Python/R would be great.

Thanks!

答:
First, back all your files up before removing the ".bak" in the code. I don't want to cause you to lose something, or if my script misfires, I'd like you to be able to recreate what you have.

Second, this is probably not very good Python code, because I am not an expert. But it works, if you are editing in utf-8. Because en dash is not an ASCII character, a straight replace doesn't work. I confess I'm not quite sure what's going on here, so bigger python experts may be able to sort out where I can do better.

```<code>#-*- coding: utf-8 -*-

import codecs
import glob
import re
import os

def replace_file(file):
    endash = "–".encode('utf-8')
    print ("Replacing " + file)
    temp = codecs.open("temp", "w", "utf-8")
    with codecs.open(file) as f:
        for line in f:
            line = re.sub("-", "–", line)
            temp.write(line)
    temp.close()
    f.close()
    os.system("copy temp \"" + file + ".bak\"")

x = glob.glob("*.tex")

for y in x:
    replace_file(y)
</code>```

Body:
First, back all your files up before removing the ".bak" in the code. I don't want to cause you to lose something, or if my script misfires, I'd like you to be able to recreate what you have.

Second, this is probably not very good Python code, because I am not an expert. But it works, if you are editing in utf-8. Because en dash is not an ASCII character, a straight replace doesn't work. I confess I'm not quite sure what's going on here, so bigger python experts may be able to sort out where I can do better.

#-*- coding: utf-8 -*-

import codecs
import glob
import re
import os

def replace_file(file):
    endash = "–".encode('utf-8')
    print ("Replacing " + file)
    temp = codecs.open("temp", "w", "utf-8")
    with codecs.open(file) as f:
        for line in f:
            line = re.sub("-", "–", line)
            temp.write(line)
    temp.close()
    f.close()
    os.system("copy temp \"" + file + ".bak\"")

x = glob.glob("*.tex")

for y in x:
    replace_file(y)


问:
matplotlib show single graph out of object of subplots
I have 18 data sets, and I've done showing all of 18 graphs using plt.subplots as below.

```<code>import matplotlib.pyplot as plt

f,ax_array=plt.subplots(6,3)
for i in range(0,6):
    for j in range(0,3):
        ax_array[i][j].plot(modified_data[3*i+j])
plt.show()
#modified data is my data set
</code>```

What I want to do is show a single graph.  For example, how can I show a graph corresponding to ax_array[3][2]?

答:
That turns out to be not so easy, the easiest solution would be to create a new figure and issue the plot command again with the required data. Sharing axes objects across multiple figures is quite difficult.

However, solution below allows you to zoom in on a particular subplot using shift+left click.

```<code>def add_subplot_zoom(figure):

    zoomed_axes = [None]
    def on_click(event):
        ax = event.inaxes

        if ax is None:
            # occurs when a region not in an axis is clicked...
            return

        # we want to allow other navigation modes as well. Only act in case
        # shift was pressed and the correct mouse button was used
        if event.key != 'shift' or event.button != 1:
            return

        if zoomed_axes[0] is None:
            # not zoomed so far. Perform zoom

            # store the original position of the axes
            zoomed_axes[0] = (ax, ax.get_position())
            ax.set_position([0.1, 0.1, 0.85, 0.85])

            # hide all the other axes...
            for axis in event.canvas.figure.axes:
                if axis is not ax:
                    axis.set_visible(False)

        else:
            # restore the original state

            zoomed_axes[0][0].set_position(zoomed_axes[0][1])
            zoomed_axes[0] = None

            # make other axes visible again
            for axis in event.canvas.figure.axes:
                axis.set_visible(True)

        # redraw to make changes visible.
        event.canvas.draw()

    figure.canvas.mpl_connect('button_press_event', on_click)
</code>```

Source. Calling the function in your example as:

```<code>import matplotlib.pyplot as plt

f,ax_array=plt.subplots(6,3)
for i in range(0,6):
    for j in range(0,3):
        ax_array[i][j].plot(modified_data[3*i+j])

add_subplot_zoom(f)

plt.show()
</code>```

Body:
I have 18 data sets, and I've done showing all of 18 graphs using plt.subplots as below.

import matplotlib.pyplot as plt

f,ax_array=plt.subplots(6,3)
for i in range(0,6):
    for j in range(0,3):
        ax_array[i][j].plot(modified_data[3*i+j])
plt.show()
#modified data is my data set

What I want to do is show a single graph.  For example, how can I show a graph corresponding to ax_array[3][2]?

Body:
That turns out to be not so easy, the easiest solution would be to create a new figure and issue the plot command again with the required data. Sharing axes objects across multiple figures is quite difficult.

However, solution below allows you to zoom in on a particular subplot using shift+left click.

def add_subplot_zoom(figure):

    zoomed_axes = [None]
    def on_click(event):
        ax = event.inaxes

        if ax is None:
            # occurs when a region not in an axis is clicked...
            return

        # we want to allow other navigation modes as well. Only act in case
        # shift was pressed and the correct mouse button was used
        if event.key != 'shift' or event.button != 1:
            return

        if zoomed_axes[0] is None:
            # not zoomed so far. Perform zoom

            # store the original position of the axes
            zoomed_axes[0] = (ax, ax.get_position())
            ax.set_position([0.1, 0.1, 0.85, 0.85])

            # hide all the other axes...
            for axis in event.canvas.figure.axes:
                if axis is not ax:
                    axis.set_visible(False)

        else:
            # restore the original state

            zoomed_axes[0][0].set_position(zoomed_axes[0][1])
            zoomed_axes[0] = None

            # make other axes visible again
            for axis in event.canvas.figure.axes:
                axis.set_visible(True)

        # redraw to make changes visible.
        event.canvas.draw()

    figure.canvas.mpl_connect('button_press_event', on_click)

Source. Calling the function in your example as:

import matplotlib.pyplot as plt

f,ax_array=plt.subplots(6,3)
for i in range(0,6):
    for j in range(0,3):
        ax_array[i][j].plot(modified_data[3*i+j])

add_subplot_zoom(f)

plt.show()


答: The column in the select query is u.user_i and the column in the group by is u.user_id

Title: Find the issues of SQL


问:
How to specify the version of RxJava when using RxKotlin?
Docs in the RxKotlin repository on GitHub doesn't specify a way to explicitly depend on the latest RxJava versionn.

If we see the build.gradle file of the library, it as of now uses compile 'io.reactivex.rxjava2:rxjava:2.1.0'

But what if we want to keep up with the latest RxJava releases and not the one present in the library.

答:
You can override the version of RxJava in your projects build.gradle.

The specified version of RxJava will be chosen (and override RxKotlin's) if you just explicitly specify it like this in Gradle/Maven:

```<code>dependencies {
    compile 'io.reactivex.rxjava2:rxjava:2.1.1'
    compile 'io.reactivex.rxjava2:rxkotlin:2.1.0'
}
</code>```

This is also stated in the RxAndroid readme file.
I had a little chat with one of the contributors of the RxKotlin and he said that just like RxAndroid, they also internally use the same policy.

Body:
You can override the version of RxJava in your projects build.gradle.

The specified version of RxJava will be chosen (and override RxKotlin's) if you just explicitly specify it like this in Gradle/Maven:

dependencies {
    compile 'io.reactivex.rxjava2:rxjava:2.1.1'
    compile 'io.reactivex.rxjava2:rxkotlin:2.1.0'
}

This is also stated in the RxAndroid readme file.
I had a little chat with one of the contributors of the RxKotlin and he said that just like RxAndroid, they also internally use the same policy.


问:
Multiple parameters on jquery ajax call asp.net
I am trying to pass two parameters on an ajax call. I already tried several ways suggested on StakeOverflow but none worked. Here is my method signature on controller:

```<code>[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase[] files, string[] usersToShare)
</code>```

Here is my function:

```<code>function uploadFile() {
        var formData = new FormData();
        var totalFiles = document.getElementById("files").files.length;

        for (var i = 0; i < totalFiles; i++) {
            var file = document.getElementById("files").files[i];
            formData.append("files", file);
        }

        //get the selected usernames (email) to share the file
        var selectedUsers = [];
        $("#costumerUsersListSelect :selected").each(function () {
            selectedUsers.push($(this).val());
        });

        $.ajax({
            type: 'post',
            url: '/ManageFiles/UploadFile',
            data: "files=" + formData + "usersToShare=" + selectedUsers,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: function (data) {
            },
            error: function (error) {
            }
        });
    }
</code>```

So I want to pass to the controller the formData and the selectedUsers. If I pass just the formData (Data: formData) everything works but I need to pass the selectedUsers too.

Here what I already tried without any success:

```<code>data: JSON.stringify({ files: formData, usersToShare: selectedUsers }),
data: { files: formData, usersToShare: JSON.stringify(selectedUsers)},
data: "files=" + formData + "&usersToShare=" + selectedUsers,
data: "files=" + formData + "usersToShare=" + selectedUsers,
</code>```

I am not sure if this is a syntax issue.

Thanks in advance for any help.

答:
You need to use different keys for each value you append to formData, and then just append both files and users the same way</p>

```<code>function uploadFile() {
  var formData   = new FormData();
  var allFiles   = $("#files").get(0).files;

  for (var i = 0; i < allFiles.length; i++) {
    formData.append("files_" + i, allFiles[i]);
  }

  $("#costumerUsersListSelect :selected").each(function(_,i) {
    formData.append('user_' + i, this.value);
  });

  $.ajax({
    type: 'post',
    url: '/ManageFiles/UploadFile',
    data: formData,
    dataType: 'json',
    contentType: false,
    processData: false,
    success: function(data) {},
    error: function(error) {}
  });
}
</code>```

Body:
I am trying to pass two parameters on an ajax call. I already tried several ways suggested on StakeOverflow but none worked. Here is my method signature on controller:

[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase[] files, string[] usersToShare)

Here is my function:

function uploadFile() {
        var formData = new FormData();
        var totalFiles = document.getElementById("files").files.length;

        for (var i = 0; i < totalFiles; i++) {
            var file = document.getElementById("files").files[i];
            formData.append("files", file);
        }

        //get the selected usernames (email) to share the file
        var selectedUsers = [];
        $("#costumerUsersListSelect :selected").each(function () {
            selectedUsers.push($(this).val());
        });

        $.ajax({
            type: 'post',
            url: '/ManageFiles/UploadFile',
            data: "files=" + formData + "usersToShare=" + selectedUsers,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: function (data) {
            },
            error: function (error) {
            }
        });
    }

So I want to pass to the controller the formData and the selectedUsers. If I pass just the formData (Data: formData) everything works but I need to pass the selectedUsers too.

Here what I already tried without any success:

data: JSON.stringify({ files: formData, usersToShare: selectedUsers }),
data: { files: formData, usersToShare: JSON.stringify(selectedUsers)},
data: "files=" + formData + "&usersToShare=" + selectedUsers,
data: "files=" + formData + "usersToShare=" + selectedUsers,

I am not sure if this is a syntax issue.

Thanks in advance for any help.

Body:
You need to use different keys for each value you append to formData, and then just append both files and users the same way

function uploadFile() {
  var formData   = new FormData();
  var allFiles   = $("#files").get(0).files;

  for (var i = 0; i < allFiles.length; i++) {
    formData.append("files_" + i, allFiles[i]);
  }

  $("#costumerUsersListSelect :selected").each(function(_,i) {
    formData.append('user_' + i, this.value);
  });

  $.ajax({
    type: 'post',
    url: '/ManageFiles/UploadFile',
    data: formData,
    dataType: 'json',
    contentType: false,
    processData: false,
    success: function(data) {},
    error: function(error) {}
  });
}


问:
How do i architect automatic update of my clients
I have a distributed application written in C# (4.0). It has become a substantial task to update all clients each time i create a new release. I do not want to go the ClickOnce way, since organisations that has bought my software in some cases do not wish to upgrade their clients.

How do i build such an update mechanism, for my clients? My thoughts are to implement a kind of launcher application that checks a server for newest version, updates that if required, and starts the new one. If no updates are available it simple starts the client application. Then i see a problem of updating the launcher application, should the client then be the one responsible for this?

How do I solve this in a proper and robust way, that ensures that the customer can configurate their clients for updates or not, and then allow the clients to function completely autonomically? That is, without user supervision.

Cheers,

答:
Create a clearly separated multi tier application. Add all your business logic in a classLibrary. Add this Library as reference to your application. Afterwards create a checkFunction in your UI. (e.g. check a version "number" by calling a webService)

In case remote version > localVersion download new DLL (register in GAC if necessary) and demand restart of your application.

If your UI logic has changed too, download a complete new setup file (with removeOlder version = true) and demand user to start it or call process.Start on closed..

just a few ideas on your topic - hope this might help


问:
/usr/bin/ld: cannot find -lauparse
How can I install the auparse library on Fedora 26?

```<code>$ gcc -lauparse me.c
/usr/bin/ld: cannot find -lauparse
</code>```

I have tried many things, including these.

```<code>$ sudo find / -name *auparse.so
/usr/lib64/python3.6/site-packages/auparse.so
$ export LD_LIBRARY_PATH=/usr/lib64/python3.6/site-packages/
didnt help :{
sudo ln -s /usr/lib64/python3.6/site-packages/auparse.so /usr/lib/gcc/x86_64-redhat-linux/7/auparse.so
didnt help :{
$ pkg-config --libs auparse
Package auparse was not found in the pkg-config search path.
</code>```

I'd really appreciate help.

答:
You need audit-libs-devel. Here's how I found that:

```<code>$ sudo dnf install /usr/lib64/libauparse.so
Dependencies resolved.
================================================================================
 Package               Arch        Version           Repository            Size
================================================================================
Installing:
 audit-libs-devel      x86_64      2.7.7-1.fc26      updates-testing       81 k
</code>```

In general:

Libraries are gonna be in /usr/lib64 on x86_64 systems.

-lsomething means to look for /usr/lib64/libsomething.so

And DNF has this neat feature where it can find things by file, so there you go.

Also, for most libraries on Fedora, there's a runtime package (here, audit-libs and then a devel package (audit-libs-devel) which contains the .so symlink and usually header files and stuff.

Title: /usr/bin/ld: cannot find -lauparse

Body:
How can I install the auparse library on Fedora 26?

$ gcc -lauparse me.c
/usr/bin/ld: cannot find -lauparse

I have tried many things, including these.

$ sudo find / -name *auparse.so
/usr/lib64/python3.6/site-packages/auparse.so
$ export LD_LIBRARY_PATH=/usr/lib64/python3.6/site-packages/
didnt help :{
sudo ln -s /usr/lib64/python3.6/site-packages/auparse.so /usr/lib/gcc/x86_64-redhat-linux/7/auparse.so
didnt help :{
$ pkg-config --libs auparse
Package auparse was not found in the pkg-config search path.

I'd really appreciate help.

Body:
You need audit-libs-devel. Here's how I found that:

$ sudo dnf install /usr/lib64/libauparse.so
Dependencies resolved.
================================================================================
 Package               Arch        Version           Repository            Size
================================================================================
Installing:
 audit-libs-devel      x86_64      2.7.7-1.fc26      updates-testing       81 k

In general:

Libraries are gonna be in /usr/lib64 on x86_64 systems.

-lsomething means to look for /usr/lib64/libsomething.so

And DNF has this neat feature where it can find things by file, so there you go.

Also, for most libraries on Fedora, there's a runtime package (here, audit-libs and then a devel package (audit-libs-devel) which contains the .so symlink and usually header files and stuff.