问:
How to expand the only one piece of arc in d3.js?
I'm trying to expand the inner element of arc, I have tried the below thing

```<code>var data = [96,4];
var svg = d3.select("body").append("svg")
.attr("width", "400")
.attr("height", "400")
.attr("id","table_pie_"+idname);

var width = 500,
    height = 700,
    radius = 100;

svgid = d3.select("#table_pie_"+idname);

var colors = ["#06f","#099","#548235","#ED7D31","#C30","rgb(244,189,23)"];
var color = d3.scaleOrdinal()
    .range(colors);

var arc = d3.arc()
    .outerRadius(radius - 10)
    .innerRadius(0);

var labelArc = d3.arc()
    .outerRadius(radius - 40)
    .innerRadius(radius - 40);

var pie = d3.pie()
    .sort(null)
    .value(function(d) { return d; });

  var arcOver = d3.arc()
      .innerRadius(0)
      .outerRadius(150 + 10);

 var svg = svgid.append("g")
    .attr("transform", "translate(100 200)");
i = 0;
  var g = svg.selectAll(".arcH")
      .data(pie(data))
    .enter().append("g")
      .attr("class", "arcH");

  g.append("path")
      .attr("d", arc)
      .style("fill", function(d) { m=i; i++; return colors[m]; })
    .attr("stroke", "white")
    .attr("stroke-width", "5")
    ;

  g.append("text")
      .attr("transform", function(d) { return "translate(" + labelArc.centroid(d) + ")"; })
      .attr("dy", ".30em")
      .attr("fill", "white")
      .style("font"," 13px 'Tw Cen MT Condensed'")
      .style("text-anchor","middle")
      .text(function(d) { return d.data.toFixed(2)+"%"; });
</code>```

For expanding the inner arc I tried the following thing

```<code>$( ".arcH path" ).last().attr( "d",  arcOver);
</code>```

But it is not working. Actually I have copied the code from here.

And I have tried this also

```<code>g.append("path")
.attr("d", function(d){if(i==0){ return arc; } else{ return arcOver;} })
.style("fill", function(d) { m=i; i++; return colors[m]; })
.attr("stroke", "white")
.attr("stroke-width", "5")
</code>```

答:
Let's analyze your mistakes.

```<code>$( ".arcH path" ).last().attr( "d",  arcOver);
</code>```

This code did not work because of you used jQuery selection, you must use d3 selection.

```<code>g.append("path")
  .attr("d", function(d){if(i==0){ return arc; } else{ return arcOver;} })
</code>```

This code did not work because of you should return the function invocation result, not the function itself.

So rewrite your path variable this way:

```<code>var paths = g.append("path")
  .attr("d", function(dataItem, index, dataSet) {
    // here we get one of arc functions by index
    // if it is the last sector we use arcOver
    var currentArc = index === dataSet.length - 1 ? arcOver : arc;

    return currentArc(dataItem)
  })
  .style("fill", function(d, i) { return colors[i]; })
  .attr("stroke", "white")
  .attr("stroke-width", "5");
</code>```

Check demo below:

var data = [96, 4];
var idname = '';
var svg = d3.select("body").append("svg")
  .attr("width", "400")
  .attr("height", "400")
  .attr("id", "table_pie_" + idname);

var width = 500,
  height = 700,
  radius = 100;

svgid = d3.select("#table_pie_" + idname);

var colors = ["#06f", "#099", "#548235", "#ED7D31", "#C30", "rgb(244,189,23)"];
var color = d3.scaleOrdinal()
  .range(colors);

var arc = d3.arc()
  .outerRadius(radius - 10)
  .innerRadius(0);

var labelArc = d3.arc()
  .outerRadius(radius - 40)
  .innerRadius(radius - 40);

var pie = d3.pie()
  .sort(null)
  .value(function(d) {
    return d;
  });

var arcOver = d3.arc()
  .innerRadius(0)
  .outerRadius(150 + 10);

var svg = svgid.append("g")
  .attr("transform", "translate(100 200)");
i = 0;
var g = svg.selectAll(".arcH")
  .data(pie(data))
  .enter().append("g")
  .attr("class", "arcH");

var paths = g.append("path")
  .attr("d", function(dataItem, index, dataSet) {
   var currentArc = index === dataSet.length - 1 ? arcOver : arc;

   return currentArc(dataItem)
  })
  .style("fill", function(d, i) {
    return colors[i];
  })
  .attr("stroke", "white")
  .attr("stroke-width", "5");

g.append("text")
  .attr("transform", function(d) {
    return "translate(" + labelArc.centroid(d) + ")";
  })
  .attr("dy", ".30em")
  .attr("fill", "white")
  .style("font", " 13px 'Tw Cen MT Condensed'")
  .style("text-anchor", "middle")
  .text(function(d) {
    return d.data.toFixed(2) + "%";
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.js"></script>
<div id="chart"></div></code>```

Body:
I'm trying to expand the inner element of arc, I have tried the below thing

var data = [96,4];
var svg = d3.select("body").append("svg")
.attr("width", "400")
.attr("height", "400")
.attr("id","table_pie_"+idname);

var width = 500,
    height = 700,
    radius = 100;

svgid = d3.select("#table_pie_"+idname);

var colors = ["#06f","#099","#548235","#ED7D31","#C30","rgb(244,189,23)"];
var color = d3.scaleOrdinal()
    .range(colors);

var arc = d3.arc()
    .outerRadius(radius - 10)
    .innerRadius(0);

var labelArc = d3.arc()
    .outerRadius(radius - 40)
    .innerRadius(radius - 40);

var pie = d3.pie()
    .sort(null)
    .value(function(d) { return d; });

  var arcOver = d3.arc()
      .innerRadius(0)
      .outerRadius(150 + 10);

 var svg = svgid.append("g")
    .attr("transform", "translate(100 200)");
i = 0;
  var g = svg.selectAll(".arcH")
      .data(pie(data))
    .enter().append("g")
      .attr("class", "arcH");

  g.append("path")
      .attr("d", arc)
      .style("fill", function(d) { m=i; i++; return colors[m]; })
    .attr("stroke", "white")
    .attr("stroke-width", "5")
    ;

  g.append("text")
      .attr("transform", function(d) { return "translate(" + labelArc.centroid(d) + ")"; })
      .attr("dy", ".30em")
      .attr("fill", "white")
      .style("font"," 13px 'Tw Cen MT Condensed'")
      .style("text-anchor","middle")
      .text(function(d) { return d.data.toFixed(2)+"%"; });

For expanding the inner arc I tried the following thing

$( ".arcH path" ).last().attr( "d",  arcOver);

But it is not working. Actually I have copied the code from here.

And I have tried this also

g.append("path")
.attr("d", function(d){if(i==0){ return arc; } else{ return arcOver;} })
.style("fill", function(d) { m=i; i++; return colors[m]; })
.attr("stroke", "white")
.attr("stroke-width", "5")

Body:
Let's analyze your mistakes.

$( ".arcH path" ).last().attr( "d",  arcOver);

This code did not work because of you used jQuery selection, you must use d3 selection.

g.append("path")
  .attr("d", function(d){if(i==0){ return arc; } else{ return arcOver;} })

This code did not work because of you should return the function invocation result, not the function itself.

So rewrite your path variable this way:

var paths = g.append("path")
  .attr("d", function(dataItem, index, dataSet) {
    // here we get one of arc functions by index
    // if it is the last sector we use arcOver
    var currentArc = index === dataSet.length - 1 ? arcOver : arc;

    return currentArc(dataItem)
  })
  .style("fill", function(d, i) { return colors[i]; })
  .attr("stroke", "white")
  .attr("stroke-width", "5");

Check demo below:

var data = [96, 4];
var idname = '';
var svg = d3.select("body").append("svg")
  .attr("width", "400")
  .attr("height", "400")
  .attr("id", "table_pie_" + idname);

var width = 500,
  height = 700,
  radius = 100;

svgid = d3.select("#table_pie_" + idname);

var colors = ["#06f", "#099", "#548235", "#ED7D31", "#C30", "rgb(244,189,23)"];
var color = d3.scaleOrdinal()
  .range(colors);

var arc = d3.arc()
  .outerRadius(radius - 10)
  .innerRadius(0);

var labelArc = d3.arc()
  .outerRadius(radius - 40)
  .innerRadius(radius - 40);

var pie = d3.pie()
  .sort(null)
  .value(function(d) {
    return d;
  });

var arcOver = d3.arc()
  .innerRadius(0)
  .outerRadius(150 + 10);

var svg = svgid.append("g")
  .attr("transform", "translate(100 200)");
i = 0;
var g = svg.selectAll(".arcH")
  .data(pie(data))
  .enter().append("g")
  .attr("class", "arcH");

var paths = g.append("path")
  .attr("d", function(dataItem, index, dataSet) {
   var currentArc = index === dataSet.length - 1 ? arcOver : arc;

   return currentArc(dataItem)
  })
  .style("fill", function(d, i) {
    return colors[i];
  })
  .attr("stroke", "white")
  .attr("stroke-width", "5");

g.append("text")
  .attr("transform", function(d) {
    return "translate(" + labelArc.centroid(d) + ")";
  })
  .attr("dy", ".30em")
  .attr("fill", "white")
  .style("font", " 13px 'Tw Cen MT Condensed'")
  .style("text-anchor", "middle")
  .text(function(d) {
    return d.data.toFixed(2) + "%";
  });

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.js"></script>
<div id="chart"></div>


来源: stackexchange

问:
Is there any function in Perl similar to GetType() in C#?
I have been learning Perl for a bit now and found it very different from other OOP languages I know.
I tried to translate a C# code which goes like:

```<code>class Car{}, class CarList{}, class Program{}
</code>```

and a method (pseudocode) :

```<code>if (var.GetType() == Car)
{
}
else if (var.GetType == CarList)
{
}
</code>```

how do I write this in perl without a GetType function or is there one?

答:
In a lot of Perl code, the ref operator is what you want if you're seeking the exact name of the class of the object. Since it's undefined if the value is not a reference, you need to check the value before using string comparisons.

```<code>if(ref $var) {
    if(ref($var) eq 'Car') {
        # ...
    } elsif(ref($var) eq 'CarList') {
        # ...
    }
}
</code>```

It's more likely that you want something like C#'s is operator. That would be the isa method of UNIVERSAL which is inherited by all objects. An example from the doc at http://perldoc.perl.org/UNIVERSAL.html:

```<code>use Scalar::Util 'blessed';

# Tests first whether $obj is a class instance and second whether it is an
# instance of a subclass of Some::Class
if ( blessed($obj) && $obj->isa("Some::Class") ) {
    ...
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have been learning Perl for a bit now and found it very different from other OOP languages I know.
I tried to translate a C# code which goes like:

class Car{}, class CarList{}, class Program{}

and a method (pseudocode) :

if (var.GetType() == Car)
{
}
else if (var.GetType == CarList)
{
}

how do I write this in perl without a GetType function or is there one?

Body:
In a lot of Perl code, the ref operator is what you want if you're seeking the exact name of the class of the object. Since it's undefined if the value is not a reference, you need to check the value before using string comparisons.

if(ref $var) {
    if(ref($var) eq 'Car') {
        # ...
    } elsif(ref($var) eq 'CarList') {
        # ...
    }
}

It's more likely that you want something like C#'s is operator. That would be the isa method of UNIVERSAL which is inherited by all objects. An example from the doc at http://perldoc.perl.org/UNIVERSAL.html:

use Scalar::Util 'blessed';

# Tests first whether $obj is a class instance and second whether it is an
# instance of a subclass of Some::Class
if ( blessed($obj) && $obj->isa("Some::Class") ) {
    ...
}


问:
Mock methods on Static Instance
I have a class as :

```<code>public class Factory {
   private static final Factory instance = new Factory();
   private Factory() {
   }
   public static Factory getInstance() {
       return instance;
   }
   private Client client = null;

   //To be mocked
   //Failing at this point
   //Not actually using mocked method
   public Client getClient(Properties properties) {
      //doSomething
      //...
      return client;
   }
}
</code>```

In another class above method is used as:

```<code>public class Service {
  protected Client client = null;
  protected void keySetup() {
     //Should be mocked
     client = Factory.getInstance().getClient(properties());

     ...
     ...
  }
}
</code>```

For unit testing the keySetup() method, I am trying to mock the Factory.getInstance().getClient(properties()) but I am failing.

I try doing the following:

```<code>@Test
public void testKeySetupTrue(){
    Client client = mock(Client.class);
    Factory factory = mock(Factory.class);
    ReflectionTestUtils.setField(factory, "client", client);
    Properties properties = mock(Properties.class);

    Mockito.doReturn(client).when(factory)
    .getClient(properties);

    Service service = new Service();

    service.keySetup();
    ...
    ...
}
</code>```

When I was running in debug mode I saw it was actually executing the getClient(Properties properties) which was mocked.

How to resolve this?

答:
static final is not a great design.
It is better to inject the dependency and let the framework (spring or other) worry about controlling the singleton.
That said,
in your case,
use reflection to set the Factory instance variable with a mock Factory.

ContentLicense: CC BY-SA 3.0

Title: Mock methods on Static Instance

Body:
I have a class as :

public class Factory {
   private static final Factory instance = new Factory();
   private Factory() {
   }
   public static Factory getInstance() {
       return instance;
   }
   private Client client = null;

   //To be mocked
   //Failing at this point
   //Not actually using mocked method
   public Client getClient(Properties properties) {
      //doSomething
      //...
      return client;
   }
}

In another class above method is used as:

public class Service {
  protected Client client = null;
  protected void keySetup() {
     //Should be mocked
     client = Factory.getInstance().getClient(properties());

     ...
     ...
  }
}

For unit testing the keySetup() method, I am trying to mock the Factory.getInstance().getClient(properties()) but I am failing.

I try doing the following:

@Test
public void testKeySetupTrue(){
    Client client = mock(Client.class);
    Factory factory = mock(Factory.class);
    ReflectionTestUtils.setField(factory, "client", client);
    Properties properties = mock(Properties.class);

    Mockito.doReturn(client).when(factory)
    .getClient(properties);

    Service service = new Service();

    service.keySetup();
    ...
    ...
}

When I was running in debug mode I saw it was actually executing the getClient(Properties properties) which was mocked.

How to resolve this?


问:
How to pack and distribute python program (.py source code) so that other developers can easily install all required dependencies?
I'm developing a Python application built with some packages I've installed with pip such as Flask, requests, PIL.

So how can I distribute my program so that other people can easily install every required dependency/package and simply make it work on every computer? Is setup.py what I'm looking for or not at all? If so, could you please explain what it does and provide an example setup.py that does what I'm trying to do?

PS: I've also got this little question: do I need to provide a __init__.py in the top level folder of my program or just in subdirectories?

答:
Unfortunately, python packaging has a complicated history, and new tools are still emerging. My understanding is that the current "gold standard" is to use setup_tools to define a setup.py file. This file will allow others to install your project's source code using pip. If you want to be able to install with pip without explicitly downloading the source first, you will need to publish your project to pypi using python setup.py upload.

Below is the setup.py boilerplate I use as a starting point:

```<code>#!/usr/bin/env python
""" boilerplate for new project setup.py """

from setuptools import setup
import io

import projectname

def read(*filenames, **kwargs):
    encoding = kwargs.get('encoding', 'utf-8')
    sep = kwargs.get('sep', '\n')
    buf = []
    for filename in filenames:
        with io.open(filename, encoding=encoding) as f:
            buf.append(f.read())
    return sep.join(buf)

long_description = read('README.md') #, 'CHANGES.txt')

setup(name='projectname',
    version=projectname.__version__,
    description='short desc of projectname',
    long_description=long_description,
    author='Tylar Murray',
    author_email='code+projectname@tylar.info',
    url='https://github.com/7yl4r/projectname',

    tests_require=['nose'],
    install_requires=[
        'networkx'  # or whatever
    ],
    #cmdclass={'test': PyTest},

    packages=['projectname', 'OtherProjectProvidedPackage2']
)
</code>```

NOTE: this template requires you to have a README.md and something like __version__="0.1.23" in your top-level __init__.py

Regarding your P.S. question: Technically you should open a new question for this but in short the answer is you should include both as covered here and in this answer particularly.

Body:
Unfortunately, python packaging has a complicated history, and new tools are still emerging. My understanding is that the current "gold standard" is to use setup_tools to define a setup.py file. This file will allow others to install your project's source code using pip. If you want to be able to install with pip without explicitly downloading the source first, you will need to publish your project to pypi using python setup.py upload.

Below is the setup.py boilerplate I use as a starting point:

#!/usr/bin/env python
""" boilerplate for new project setup.py """

from setuptools import setup
import io

import projectname

def read(*filenames, **kwargs):
    encoding = kwargs.get('encoding', 'utf-8')
    sep = kwargs.get('sep', '\n')
    buf = []
    for filename in filenames:
        with io.open(filename, encoding=encoding) as f:
            buf.append(f.read())
    return sep.join(buf)

long_description = read('README.md') #, 'CHANGES.txt')

setup(name='projectname',
    version=projectname.__version__,
    description='short desc of projectname',
    long_description=long_description,
    author='Tylar Murray',
    author_email='code+projectname@tylar.info',
    url='https://github.com/7yl4r/projectname',

    tests_require=['nose'],
    install_requires=[
        'networkx'  # or whatever
    ],
    #cmdclass={'test': PyTest},

    packages=['projectname', 'OtherProjectProvidedPackage2']
)

NOTE: this template requires you to have a README.md and something like __version__="0.1.23" in your top-level __init__.py

Regarding your P.S. question: Technically you should open a new question for this but in short the answer is you should include both as covered here and in this answer particularly.


问:
Text-decoration: none not working
Totally baffled! I've tried rewriting the text-decoration: none line several different ways. I also managed to re-size the text by targeting it but the text-decoration: none code will not take.

Help much appreciated.

Code

.widget
{
     height: 320px;
     width: 220px;
     background-color: #e6e6e6;
     position: relative;
     overflow: hidden;
}

.title
{
     font-family: Georgia, Times New Roman, serif;
     font-size: 12px;
     color: #E6E6E6;
     text-align: center;
     letter-spacing: 1px;
     text-transform: uppercase;
     background-color: #4D4D4D;
     position: absolute;
     top: 0;
     padding: 5px;
     width: 100%;
     margin-bottom: 1px;
     height: 28px;
     text-decoration: none;
}

a .title
{
     text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
    <div class="widget">
        <div class="title">Underlined. Why?</div>
    </div>
</code>```

答:
I had lots of headache when I tried to customize a WordPress theme and the text-decoration didn't help me.
In my case I had to remove the box-shadow as well.</p>

```<code>a:hover {
    text-decoration: none;
    box-shadow: none;
}
</code>```

Title: Text-decoration: none not working

Body:
Totally baffled! I've tried rewriting the text-decoration: none line several different ways. I also managed to re-size the text by targeting it but the text-decoration: none code will not take.

Help much appreciated.

Code

.widget
{
     height: 320px;
     width: 220px;
     background-color: #e6e6e6;
     position: relative;
     overflow: hidden;
}

.title
{
     font-family: Georgia, Times New Roman, serif;
     font-size: 12px;
     color: #E6E6E6;
     text-align: center;
     letter-spacing: 1px;
     text-transform: uppercase;
     background-color: #4D4D4D;
     position: absolute;
     top: 0;
     padding: 5px;
     width: 100%;
     margin-bottom: 1px;
     height: 28px;
     text-decoration: none;
}

a .title
{
     text-decoration: none;
}

Underlined. Why?

Body:
I had lots of headache when I tried to customize a WordPress theme and the text-decoration didn't help me.
In my case I had to remove the box-shadow as well.

a:hover {
    text-decoration: none;
    box-shadow: none;
}


问:
Express not serving static files
I'm having an issue serving static javascript files using express. I've tried many different variations of the express documentation to no avail.I've also tried many of the responses to similar questions on S/O.

My folder structure is

```<code>-MyApp
 -client
 -server
   -public
    foo.js
  server.js
</code>```

server.js:

```<code>require('rootpath')();
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
var expressJwt = require('express-jwt');
var config = require('config.json');
var path = require('path');

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// use JWT auth to secure the api, the token can be passed in the authorization header or querystring
app.use(expressJwt({
    secret: config.secret,
    getToken: function (req) {
        if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
            return req.headers.authorization.split(' ')[1];
        } else if (req.query && req.query.token) {
            return req.query.token;
        }
        return null;
    }
}).unless({ path: ['/users/authenticate', '/users/register'] }));
// serve static files
app.use(express.static(path.join(__dirname, 'public')));
// routes
app.use('/users', require('./controllers/users.controller'));
app.use('/listings', require('./controllers/listings.controller'));

// start server
var port = process.env.NODE_ENV === 'production' ? 80 : 4000;
var server = app.listen(port, function () {
    console.log('Server listening on port ' + port);
});
</code>```

I am trying to access foo.js through localhost:4000/foo.js but im getting 404 errors constantly.

Any help greatly appreciated

答:
See comment from @MysterX on original post.  Your directory in incorrect.

```<code>app.use(express.static(path.join(__dirname, 'public')));
</code>```

Should be

```<code>app.use(express.static(path.join(__dirname, 'server/public')));
</code>```

Title: Express not serving static files

Body:
I'm having an issue serving static javascript files using express. I've tried many different variations of the express documentation to no avail.I've also tried many of the responses to similar questions on S/O.

My folder structure is

-MyApp
 -client
 -server
   -public
    foo.js
  server.js

server.js:

require('rootpath')();
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
var expressJwt = require('express-jwt');
var config = require('config.json');
var path = require('path');

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// use JWT auth to secure the api, the token can be passed in the authorization header or querystring
app.use(expressJwt({
    secret: config.secret,
    getToken: function (req) {
        if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
            return req.headers.authorization.split(' ')[1];
        } else if (req.query && req.query.token) {
            return req.query.token;
        }
        return null;
    }
}).unless({ path: ['/users/authenticate', '/users/register'] }));
// serve static files
app.use(express.static(path.join(__dirname, 'public')));
// routes
app.use('/users', require('./controllers/users.controller'));
app.use('/listings', require('./controllers/listings.controller'));

// start server
var port = process.env.NODE_ENV === 'production' ? 80 : 4000;
var server = app.listen(port, function () {
    console.log('Server listening on port ' + port);
});

I am trying to access foo.js through localhost:4000/foo.js but im getting 404 errors constantly.

Any help greatly appreciated

Body:
See comment from @MysterX on original post.  Your directory in incorrect.

app.use(express.static(path.join(__dirname, 'public')));

Should be

app.use(express.static(path.join(__dirname, 'server/public')));


问:
New divs inside pre-existing div with slanted borders
I am trying to make a header as shown in the image attached. I tried the other answers on this website too but none actually helped very much.
I already have figured out the text and logo parts but need someone to help with the slanting div borders.

The effect that I want:

答:
Depending on what you have going on in your header, you could try using triangles to mimic the slanted borders;

header{
  width: 100%;
  height: 200px;
  background: #2c2d2e;
}

.triangle-right {
  width: 0;
  height: 0;
  border-top: 100px solid transparent;
  border-bottom: 100px solid transparent;
  position: absolute;
  left: 0;

  border-left: 200px solid white;
}

.triangle-left {
  width: 0;
  height: 0;
  border-top: 100px solid transparent;
  border-bottom: 100px solid transparent;

  border-right: 200px solid white;
  position: absolute;
  right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div class="triangle-left"></div>
  <div class="triangle-right"></div>
</header></code>```

Body:
Depending on what you have going on in your header, you could try using triangles to mimic the slanted borders;

header{
  width: 100%;
  height: 200px;
  background: #2c2d2e;
}

.triangle-right {
  width: 0;
  height: 0;
  border-top: 100px solid transparent;
  border-bottom: 100px solid transparent;
  position: absolute;
  left: 0;

  border-left: 200px solid white;
}

.triangle-left {
  width: 0;
  height: 0;
  border-top: 100px solid transparent;
  border-bottom: 100px solid transparent;

  border-right: 200px solid white;
  position: absolute;
  right: 0;
}

<header>
  <div class="triangle-left"></div>
  <div class="triangle-right"></div>
</header>


问:
Adding edge attribute causes TypeError: 'AtlasView' object does not support item assignment
Using networkx 2.0 I try to dynamically add an additional edge attribute by looping through all the edges. The graph is a MultiDiGraph.

According to the tutorial it seems to be possible to add edge attributes the way I do in the code below:

```<code>g = nx.read_gpickle("../pickles/" + gname)
yearmonth = gname[:7]
g.name = yearmonth  # works
for source, target in g.edges():
    g[source][target]['yearmonth'] = yearmonth
</code>```

This code throws the following error:

```<code>TypeError: 'AtlasView' object does not support item assignment
</code>```

What am I doing wrong?

答:
That should happen if your graph is a nx.MultiGraph. From which case you need an extra index going from 0 to n where n is the number of  edges between the two nodes.

Try:

```<code>for source, target in g.edges():
    g[source][target][0]['yearmonth'] = yearmonth
</code>```

The tutorial example is intended for a  nx.Graph.

Body:
Using networkx 2.0 I try to dynamically add an additional edge attribute by looping through all the edges. The graph is a MultiDiGraph.

According to the tutorial it seems to be possible to add edge attributes the way I do in the code below:

g = nx.read_gpickle("../pickles/" + gname)
yearmonth = gname[:7]
g.name = yearmonth  # works
for source, target in g.edges():
    g[source][target]['yearmonth'] = yearmonth

This code throws the following error:

TypeError: 'AtlasView' object does not support item assignment

What am I doing wrong?

Body:
That should happen if your graph is a nx.MultiGraph. From which case you need an extra index going from 0 to n where n is the number of  edges between the two nodes.

Try:

for source, target in g.edges():
    g[source][target][0]['yearmonth'] = yearmonth

The tutorial example is intended for a  nx.Graph.


问:
ShellExecute not working from IDE but works otherwise
I want to create and then open a txt file using the ShellExecute command.

I have used this code for years with Delphi 7 and it worked:

```<code>function Execute(CONST ExeName, Parameters: string): Boolean;
begin
 Result:= ShellExecute(0, 'open', PChar(ExeName), PChar(Parameters), nil, SW_SHOWNORMAL)> 32;
end;
</code>```

Now, I switched to Windows 7 and the code is not working anymore when it runs from IDE. Delphi shows the CPU window with the caption "CPU-Process unknown (2352)". I close the CU windows and everything works fine until I close the application, when Delphi shows the CPU window one more time.
If I run the app  from outside IDE, it works fine.

Looks like the debugger has something to say to me, but I don't know what.

答:
Same by me , i solved it by replacing ShellExecute with following:</p>

```<code>function TformMain.CreateProcessSimple(
  sExecutableFilePath : string )
    : string;

function GetExeByExtension(sExt : string) : string;
var
   sExtDesc:string;
begin
   with TRegistry.Create do
   begin
     try
       RootKey:=HKEY_CLASSES_ROOT;
       if OpenKeyReadOnly(sExt) then
       begin
         sExtDesc:=ReadString('') ;
         CloseKey;
       end;
       if sExtDesc <>'' then
       begin
         if OpenKeyReadOnly(sExtDesc + '\Shell\Open\Command') then
         begin
           Result:= ReadString('') ;
         end
       end;
     finally
       Free;
     end;
   end;
end;
var
  pi: TProcessInformation;
  si: TStartupInfo;
  fapp: string;
begin
  fapp:=GetExeByExtension(ExtractFileExt(sExecutableFilePath));
  FillMemory( @si, sizeof( si ), 0 );
  si.cb := sizeof( si );
  if Pos('%1',fApp)>0 then begin
    sExecutableFilePath:=StringReplace(fapp,'%1',sExecutableFilePath,[rfReplaceAll]);
  end else begin
    sExecutableFilePath:=fApp+' "'+sExecutableFilePath+'"';
  end;
  CreateProcess(
    Nil,

    // path to the executable file:
    PChar( sExecutableFilePath ),

    Nil, Nil, False,
    NORMAL_PRIORITY_CLASS, Nil, Nil,
    si, pi );

  // "after calling code" such as
  // the code to wait until the
  // process is done should go here

  CloseHandle( pi.hProcess );
  CloseHandle( pi.hThread );
end;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to create and then open a txt file using the ShellExecute command.

I have used this code for years with Delphi 7 and it worked:

function Execute(CONST ExeName, Parameters: string): Boolean;
begin
 Result:= ShellExecute(0, 'open', PChar(ExeName), PChar(Parameters), nil, SW_SHOWNORMAL)> 32;
end;

Now, I switched to Windows 7 and the code is not working anymore when it runs from IDE. Delphi shows the CPU window with the caption "CPU-Process unknown (2352)". I close the CU windows and everything works fine until I close the application, when Delphi shows the CPU window one more time.
If I run the app  from outside IDE, it works fine.

Looks like the debugger has something to say to me, but I don't know what.

Body:
Same by me , i solved it by replacing ShellExecute with following:

function TformMain.CreateProcessSimple(
  sExecutableFilePath : string )
    : string;

function GetExeByExtension(sExt : string) : string;
var
   sExtDesc:string;
begin
   with TRegistry.Create do
   begin
     try
       RootKey:=HKEY_CLASSES_ROOT;
       if OpenKeyReadOnly(sExt) then
       begin
         sExtDesc:=ReadString('') ;
         CloseKey;
       end;
       if sExtDesc <>'' then
       begin
         if OpenKeyReadOnly(sExtDesc + '\Shell\Open\Command') then
         begin
           Result:= ReadString('') ;
         end
       end;
     finally
       Free;
     end;
   end;
end;
var
  pi: TProcessInformation;
  si: TStartupInfo;
  fapp: string;
begin
  fapp:=GetExeByExtension(ExtractFileExt(sExecutableFilePath));
  FillMemory( @si, sizeof( si ), 0 );
  si.cb := sizeof( si );
  if Pos('%1',fApp)>0 then begin
    sExecutableFilePath:=StringReplace(fapp,'%1',sExecutableFilePath,[rfReplaceAll]);
  end else begin
    sExecutableFilePath:=fApp+' "'+sExecutableFilePath+'"';
  end;
  CreateProcess(
    Nil,

    // path to the executable file:
    PChar( sExecutableFilePath ),

    Nil, Nil, False,
    NORMAL_PRIORITY_CLASS, Nil, Nil,
    si, pi );

  // "after calling code" such as
  // the code to wait until the
  // process is done should go here

  CloseHandle( pi.hProcess );
  CloseHandle( pi.hThread );
end;


问:
Gradle Project Sync Failed Android Studio 3.0 (JDK 9.0.1)
I tried all solutions to fix it, but nothing has succeeded. (Turned gradle to "offline work", deleted .gradle files, invalidated and restarted. I also removed the jdk-android studio completely and installed again.)

Here is the problem's screenshot:
Android Studio 3.0 Gradle Sync Problem

Here is my java version

and here is the system/log file:

答:
Do it this way

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 23
defaultConfig {
    applicationId "com.example.hackl.happybirthday"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
   "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:23.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'}
</code>```

and click sync now (it will be automatically appear when you make changes in this file)

Body:
Do it this way

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
defaultConfig {
    applicationId "com.example.hackl.happybirthday"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
   "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:23.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'}

and click sync now (it will be automatically appear when you make changes in this file)


问:
Can't restart scrapy spider
I have scrapy project (Scrapy 1.4, Python 3.x). I want to rerun my spider when condition isn't fulfilled. I do it in my spider_closed function

```<code>def __init__(self):
    dispatcher.connect(self.spider_closed, signals.spider_closed)

def spider_closed(self):
    if sth1 != sth2:
        RESTART SPIDER
    else:
        FINISH SPIDER
</code>```

I tried every possible method: run spider using os command, run spider in bash script, run spider using CrawlerProcess, etc ... but every time I got error

```<code>ImportError: No module named ~my project name~
</code>```

Could anybody help?

答:
```<code>ImportError: No module named ~my project name~
</code>```

means it didnt find the path/folder of your project, you have to CD into that project folder before running spider using bash or whatever.

HERE IS WHAT I DID WHEN I WAS IN SAME SCENARIO

I installed ScrapyD and then inside close method, I started my scraper again using scrapyD's schedule endpoint.

```<code>def spider_closed(self, spider):

    resp = requests.post("http://localhost:6800/schedule.json", data={'project': "default", 'spider': self.name})
    logging.info(resp.text)
</code>```

Title: Can't restart scrapy spider

Body:
I have scrapy project (Scrapy 1.4, Python 3.x). I want to rerun my spider when condition isn't fulfilled. I do it in my spider_closed function

def __init__(self):
    dispatcher.connect(self.spider_closed, signals.spider_closed)

def spider_closed(self):
    if sth1 != sth2:
        RESTART SPIDER
    else:
        FINISH SPIDER

I tried every possible method: run spider using os command, run spider in bash script, run spider using CrawlerProcess, etc ... but every time I got error

ImportError: No module named ~my project name~

Could anybody help?

Body:
ImportError: No module named ~my project name~

means it didnt find the path/folder of your project, you have to CD into that project folder before running spider using bash or whatever.

HERE IS WHAT I DID WHEN I WAS IN SAME SCENARIO

I installed ScrapyD and then inside close method, I started my scraper again using scrapyD's schedule endpoint.

def spider_closed(self, spider):

    resp = requests.post("http://localhost:6800/schedule.json", data={'project': "default", 'spider': self.name})
    logging.info(resp.text)


问:
Alternative to using static factory (as cannot have abstract static methods)
I'm trying to build a functional package parser. I have a base class Datagram, now I was naively imagining I'd have it defined like this:

(Note on edit, this class is not abstract!)

```<code>public class Datagram
{
    public abstract static Datagram CreateFromDatagram(Datagram datagram);
}
</code>```

And then for specfic datagrams, say Ethernet and Tcp as an exampe:

```<code>public class EthernetDatagram : Datagram, IPayloadDatagram
{
    public override static Datagram CreateFromDatagram(Datagram datagram)
    {
        return new EthernetDatagram();
    }

    public Datagram Payload { get; }
}

public class TcpDatagram : Datagram, IPayloadDatagram
{
    public overrides static Datagram CreateFromDatagram(Datagram datagram)
    {
        return new TcpDatagram();
    }

    public Datagram Payload { get; }
}
</code>```

The reason for this (impossible) abstract static method is I want to have an extension method which allows me to "chain" all these packets together:

```<code>public static class DatagramExtensions
{
    public static T As<T>(this IPayloadDatagram datagram) where T : Datagram
    {
        return (T)T.CreateFromDatagram(datagram.Payload);
    }
}
</code>```

So, all I'd need to do to have a completely new datagram type ANewDatagram is have it define it's factory method CreateFromDatagram, and I'll be able to then merrily use my functional extension:

```<code>SomeDatagram.As<EthernetDatagram>().As<TcpDatagram>().As<ANewDatagram>()...
</code>```

and it'll all be extensible.

Given this isn't going to work as I can't inherit abstract classes, what would be a good alternative to instantiating a generic class like this?

I could use reflection, but then that's hiding it from the user. When I try create ANewDatagram I have to remember that I'm reflecting a CreateFromDatagram method later on.

I am currently using reflection to get the constructor - but there's no way for me to enforce there's a specific constructor that takes the payload. If someone creates a new Datagram there's no guarantee they add the right constructor, I'd have to inform them this in comments, which will very likely be missed, and the point of failure is at run-time at the latest possible point.

Is there a better alternative, architecturally, or with some form of interface/inheritence that could get around this issue?

(If anyone wants to see the full source code I'm working with, I'm trying to add these extensions to the packet interpretation library as part of https://github.com/PcapDotNet/Pcap.Net, with as little modification as possible)

答:
What if you had a single static method, but that method references an implementation defined action?  </p>

<p>This adds a compile time check so the user should at least be aware of conversion.  </p>

```<code>public interface IPayloadDatagram
{
    Datagram Payload { get; }
}

public abstract class Datagram
{
    public static Datagram CreateFromDatagram(Datagram datagram)
    {
        var action = datagram.GetConverter();
        return action(datagram);
    }

    protected abstract Func<Datagram, Datagram> GetConverter();
}

public class EthernetDatagram : Datagram, IPayloadDatagram
{
    protected override Func<Datagram, Datagram> GetConverter()
    {
        return x => new EthernetDatagram();
    }

    public Datagram Payload { get; set; }
}

public class TcpDatagram : Datagram, IPayloadDatagram
{
    protected override Func<Datagram, Datagram> GetConverter()
    {
        return x => new TcpDatagram();
    }

    public Datagram Payload { get; set; }
}

public static class DatagramExtensions
{
    public static T As<T>(this IPayloadDatagram datagram) where T : Datagram
    {
        return (T)Datagram.CreateFromDatagram(datagram.Payload);
    }
}
</code>```

Body:
I'm trying to build a functional package parser. I have a base class Datagram, now I was naively imagining I'd have it defined like this:

(Note on edit, this class is not abstract!)

public class Datagram
{
    public abstract static Datagram CreateFromDatagram(Datagram datagram);
}

And then for specfic datagrams, say Ethernet and Tcp as an exampe:

public class EthernetDatagram : Datagram, IPayloadDatagram
{
    public override static Datagram CreateFromDatagram(Datagram datagram)
    {
        return new EthernetDatagram();
    }

    public Datagram Payload { get; }
}

public class TcpDatagram : Datagram, IPayloadDatagram
{
    public overrides static Datagram CreateFromDatagram(Datagram datagram)
    {
        return new TcpDatagram();
    }

    public Datagram Payload { get; }
}

The reason for this (impossible) abstract static method is I want to have an extension method which allows me to "chain" all these packets together:

public static class DatagramExtensions
{
    public static T As<T>(this IPayloadDatagram datagram) where T : Datagram
    {
        return (T)T.CreateFromDatagram(datagram.Payload);
    }
}

So, all I'd need to do to have a completely new datagram type ANewDatagram is have it define it's factory method CreateFromDatagram, and I'll be able to then merrily use my functional extension:

SomeDatagram.As<EthernetDatagram>().As<TcpDatagram>().As<ANewDatagram>()...

and it'll all be extensible.

Given this isn't going to work as I can't inherit abstract classes, what would be a good alternative to instantiating a generic class like this?

I could use reflection, but then that's hiding it from the user. When I try create ANewDatagram I have to remember that I'm reflecting a CreateFromDatagram method later on.

I am currently using reflection to get the constructor - but there's no way for me to enforce there's a specific constructor that takes the payload. If someone creates a new Datagram there's no guarantee they add the right constructor, I'd have to inform them this in comments, which will very likely be missed, and the point of failure is at run-time at the latest possible point.

Is there a better alternative, architecturally, or with some form of interface/inheritence that could get around this issue?

(If anyone wants to see the full source code I'm working with, I'm trying to add these extensions to the packet interpretation library as part of https://github.com/PcapDotNet/Pcap.Net, with as little modification as possible)

Body:
What if you had a single static method, but that method references an implementation defined action?

This adds a compile time check so the user should at least be aware of conversion.

public interface IPayloadDatagram
{
    Datagram Payload { get; }
}

public abstract class Datagram
{
    public static Datagram CreateFromDatagram(Datagram datagram)
    {
        var action = datagram.GetConverter();
        return action(datagram);
    }

    protected abstract Func<Datagram, Datagram> GetConverter();
}

public class EthernetDatagram : Datagram, IPayloadDatagram
{
    protected override Func<Datagram, Datagram> GetConverter()
    {
        return x => new EthernetDatagram();
    }

    public Datagram Payload { get; set; }
}

public class TcpDatagram : Datagram, IPayloadDatagram
{
    protected override Func<Datagram, Datagram> GetConverter()
    {
        return x => new TcpDatagram();
    }

    public Datagram Payload { get; set; }
}

public static class DatagramExtensions
{
    public static T As<T>(this IPayloadDatagram datagram) where T : Datagram
    {
        return (T)Datagram.CreateFromDatagram(datagram.Payload);
    }
}


问:
Align image in center and middle within div
I have following div

```<code><div id="over" style="position:absolute; width:100%; height:100%>
 <img src="img.png">
</div>
</code>```

How to align the image so as to be located in the middle and center of div ?

答:
You can do this easily by using display:flex CSS property:

```<code>#over {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

</code>```

Body:
I have following div

How to align the image so as to be located in the middle and center of div ?

Body:
You can do this easily by using display:flex CSS property:

#over {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}


问:
Has anyone tried IPVS as a load balancer for diameter protocol?
I want to know if IPVS can be used as a load balancer for diameter protocol which has TCP base. </p>

答:
I used LVS to balance diameter connections, it works fine
The possible issue is that it balances connections, not messages, so back end load will not be equal.</p>


问:
WPF Animation on MouseDown and do the changes back on MouseUp
I want to make a little animation when the user clicks.
So I set up the following style and set it on my grid - but the MouseUp Animation doesn't work.</p>

```<code><Style x:Key="AnimatedButton" TargetType="Grid">
    <Style.Triggers>
        <EventTrigger RoutedEvent="MouseDown">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation Duration="00:00:0.1" From="1.0" To="0.8" Storyboard.TargetProperty="Opacity" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
        <EventTrigger RoutedEvent="PreviewMouseUp">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation Duration="00:00:0.1" From="0.8" To="1.0" Storyboard.TargetProperty="Opacity" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Style.Triggers>
</Style>
</code>```

答:
That was hard!
The styled Grid is part of a UserControl.

Now this UserControl is capturing the mouse on MouseDown and release the capture on MouseUp. So the captured MouseUp is going to the UserControl. But the style was definied for the underlying Grid. Due to the capture the Grid never gets the MouseUp.

So I changed the TargetType of the Style to "UserControl" and set the UserControl.Style to this instead of a styled grid and all is working.

Body:
I want to make a little animation when the user clicks.
So I set up the following style and set it on my grid - but the MouseUp Animation doesn't work.

</Style>


问:
Select of 2 related tables in MySQL
I have these 2 tables:

Table Users:

```<code>id | name
---------
1  | Joe
2  | Sara
3  | Michael
</code>```

Table Sales:

```<code>id |  product  | user_id
------------------------
1  |    Car    | 2
2  |   Truck   | 3
3  | motorcycle| 1
4  |    Car    | 2
5  |   Truck   | 1
6  |    Car    | 3
7  |    Car    | 2
8  |   Truck   | 3
9  |    Car    | 2
10 |    Car    | 3
</code>```

I want the following:

```<code>User Name  | Car | Truck | Motorcycle
Joe        |  0  |   1   |     1
Sara       |  4  |   0   |     0
Michael    |  2  |   2   |     0
</code>```

Any help would be appreciated

答:
```<code>SELECT Users.name,
SUM(Case
   WHEN product='Car' then 1
   ELSE 0
) AS Car,
SUM(Case
   WHEN product='Truck' then 1
   ELSE 0
) AS Truck   ,
SUM(Case
   WHEN product='Motorcycle' then 1
   ELSE 0
) AS Motorcycle,
FROM Users
LEFT JOIN Sales ON Users.id = Sales.user_id
GROUP BY Users.name
</code>```

Title: Select of 2 related tables in MySQL

Body:
I have these 2 tables:

Table Users:

id | name
---------
1  | Joe
2  | Sara
3  | Michael

Table Sales:

id |  product  | user_id
------------------------
1  |    Car    | 2
2  |   Truck   | 3
3  | motorcycle| 1
4  |    Car    | 2
5  |   Truck   | 1
6  |    Car    | 3
7  |    Car    | 2
8  |   Truck   | 3
9  |    Car    | 2
10 |    Car    | 3

I want the following:

User Name  | Car | Truck | Motorcycle
Joe        |  0  |   1   |     1
Sara       |  4  |   0   |     0
Michael    |  2  |   2   |     0

Any help would be appreciated


问:
Covalent datatable error: cannot read property 'name' of undefined
I recently started using covalent datatable's atomic components as I hav to display a custom column with action buttons.  Right now I am just trying to bind/display my data but something is going wrong.  I get the following error:

ng:///AppModule/CashierMaintenanceComponent.ngfactory.js:45 ERROR TypeError: Cannot read property 'name' of undefined

I have no idea what could be causing this...  Any idea what's going on here/how to fix it?

```<code>my html code:

<br /><br /><br />
<div class="noOverflow" fxLayout fxLayoutAlign="center start" fxLayoutWrap>
    <div fxFlex="100%">
        <div fxLayout fxLayoutAlign="start start">
            <div fxFlex="50%">
                <h1>Cashier Maintenance</h1>
            </div>
            <div fxFlex="40%" fxFlexOffset="60%">
                <button color="primary" mat-raised-button><mat-icon class="fa fa-plus"></mat-icon> New</button>
                <button mat-raised-button><mat-icon class="fa fa-edit"></mat-icon> Edit</button>
                <button mat-raised-button><mat-icon class="fa fa-trash"></mat-icon> Delete</button>
            </div>
        </div>
        <div fxLayout fxLayoutAlign="center start">
        <div fxFlex="100%">
            <mat-form-field floatPlaceholder="never">
                <input matInput #filterTbl placeholder="filter">
            </mat-form-field>
        </div>
    </div>

    <div fxLayout class="noOverflow" fxLayoutAlign="center start">
        <div fxFlex="80%" fxFlexOffset="10%">
        <div class="mat-elevation-z8 noOverflow">
            <table *ngIf="filteredEmployees.length > 0" td-data-table>
                <thead>
                    <tr td-data-table-column-row>
                        <th td-data-table-column [sortable]="true" [sortOrder]="ASC"  *ngFor="let column of columns">
                            {{column.label}}
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <tr td-data-table-row *ngFor="let row of filteredEmployees">
                        <td td-data-table-cell="let column of columns">
                                {{row[column.name]}}
                        </td>
                    </tr>
                </tbody>
            </table>

            <td-paging-bar #pagingBar [pageSize]="pageSize" [total]="filteredTotal" (change)="page($event)">
                <span>Rows per page:</span>
                <mat-select class="noOverflow" [style.width.px]="50" [(ngModel)]="pageSize">
                    <mat-option *ngFor="let size of [10, 20, 50,100,200,500]" [value]="size">
                        {{size}}
                    </mat-option>
                </mat-select>
                <span class="noOverflow">{{pagingBar.range}} of {{pagingBar.total}}</span>
            </td-paging-bar>
        </div>
        </div>
    </div>
    </div>
</div>

my ts/component code:

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

import { TdDataTableService, TdDataTableSortingOrder, ITdDataTableSortChangeEvent, ITdDataTableColumn } from '@covalent/core';
import { IPageChangeEvent } from '@covalent/core';

import { RestService } from '../../services/rest.service';
import { IEmployee } from '../../interfaces/employee.interface';

import { StringToDatePipe } from '../../pipes/string-to-date.pipe';

@Component({
  selector: 'app-cashier-maintenance',
  templateUrl: './cashier-maintenance.component.html',
  styleUrls: ['./cashier-maintenance.component.css']
})
export class CashierMaintenanceComponent implements OnInit {
    @ViewChild('filterTbl') filterTbl: ElementRef;
    employees: IEmployee[];
    filteredEmployees: IEmployee[] = [];
    filteredTotal: number = 100;
  columns: ITdDataTableColumn[] = [
  { name: 'EMP_ID', label: 'ID', sortable: true, width: 100 },
  { name: 'EMP_NM', label: 'Name', sortable: true, width: 200 },
  { name: 'EMP_TYP', label: 'Type', sortable: true, width: 200 },
  { name: 'TEL', label: 'Telephone', sortable: true, width: 200 },
  { name: 'ADDR', label: 'Address', sortable: true, width: 200 },
  { name: 'DT_STRT', label: 'Start Date', sortable: false, width: 200 }
];
searchTerm: string = '';
sortBy: string = 'EMP_NM';
fromRow: number = 1;
currentPage: number = 1;
pageSize: number = 10;
  sortOrder: TdDataTableSortingOrder = TdDataTableSortingOrder.Ascending;

  constructor(private _dataTableService: TdDataTableService, private restService: RestService)  { }

    sort(sortEvent: ITdDataTableSortChangeEvent): void {
        this.sortBy = sortEvent.name;
        console.log(sortEvent.name);
        this.filter();
    }

    search(searchTerm: string): void {
        this.searchTerm = searchTerm;
        this.filter();
    }

    page(pagingEvent: IPageChangeEvent): void {
        this.fromRow = pagingEvent.fromRow;
        this.currentPage = pagingEvent.page;
        this.pageSize = pagingEvent.pageSize;
        this.filter();
    }

    filter(): void {
        let newData: IEmployee[] = this.employees;
        let excludedColumns: string[] = this.columns
            .filter((column: ITdDataTableColumn) => {
                return ((column.filter === undefined && column.hidden === true) ||
                (column.filter !== undefined && column.filter === false));
            }).map((column: ITdDataTableColumn) => {
            return column.name;
        });
    newData = this._dataTableService.filterData(newData, this.searchTerm, true, excludedColumns);
    this.filteredTotal = newData.length;
    newData = this._dataTableService.sortData(newData, this.sortBy, this.sortOrder);
    newData = this._dataTableService.pageData(newData, this.fromRow, this.currentPage * this.pageSize);
    this.filteredEmployees = newData;
  }

  getEmployees() {
      this.restService.getEmployees()
    .subscribe(
    (res) => {
        console.log(res);
        this.employees = res;
        this.employees.forEach((emp: IEmployee) => {
            emp.DT_STRT = new StringToDatePipe().transform(emp.DT_STRT);
        });
        this.filter();
    }, (err) => {
        console.log(err);
    });
  }

  ngOnInit() {
         Observable.fromEvent(this.filterTbl.nativeElement, 'keyup')
        .debounceTime(150)
        .distinctUntilChanged()
        .subscribe(() => {
          this.searchTerm = this.filterTbl.nativeElement.value;
          this.filter();
        });

      this.getEmployees();
  }

}
</code>```

答:
There is a typo in your td-data-table-row component. You should be using *ngFor. See this stackblitz for the working code

```<code><tr td-data-table-row *ngFor="let row of filteredEmployees">
    <td td-data-table-cell *ngFor="let column of columns">
            {{row[column.name]}}
    </td>
</tr>
</code>```

For simple use cases, using the data table without the atomic components can help avoid the more complex template code. Simply pass in your data and configuration as inputs to

```<code><td-data-table
  #dataTable
  [data]="filteredData"
  [columns]="columns"
  [sortable]="true"
  sortOrder="ASC"
  [style.height.px]="200">
</td-data-table>
</code>```

Body:
I recently started using covalent datatable's atomic components as I hav to display a custom column with action buttons.  Right now I am just trying to bind/display my data but something is going wrong.  I get the following error:

ng:///AppModule/CashierMaintenanceComponent.ngfactory.js:45 ERROR TypeError: Cannot read property 'name' of undefined

I have no idea what could be causing this...  Any idea what's going on here/how to fix it?

my html code:

Cashier Maintenance

                <button color="primary" mat-raised-button><mat-icon class="fa fa-plus"></mat-icon> New</button>
                <button mat-raised-button><mat-icon class="fa fa-edit"></mat-icon> Edit</button>
                <button mat-raised-button><mat-icon class="fa fa-trash"></mat-icon> Delete</button>

            <mat-form-field floatPlaceholder="never">
                <input matInput #filterTbl placeholder="filter">
            </mat-form-field>

 0" td-data-table>

                            {{column.label}}

                                {{row[column.name]}}

                Rows per page:
                <mat-select class="noOverflow" [style.width.px]="50" [(ngModel)]="pageSize">
                    <mat-option *ngFor="let size of [10, 20, 50,100,200,500]" [value]="size">
                        {{size}}
                    </mat-option>
                </mat-select>
                {{pagingBar.range}} of {{pagingBar.total}}

my ts/component code:

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

import { TdDataTableService, TdDataTableSortingOrder, ITdDataTableSortChangeEvent, ITdDataTableColumn } from '@covalent/core';
import { IPageChangeEvent } from '@covalent/core';

import { RestService } from '../../services/rest.service';
import { IEmployee } from '../../interfaces/employee.interface';

import { StringToDatePipe } from '../../pipes/string-to-date.pipe';

@Component({
  selector: 'app-cashier-maintenance',
  templateUrl: './cashier-maintenance.component.html',
  styleUrls: ['./cashier-maintenance.component.css']
})
export class CashierMaintenanceComponent implements OnInit {
    @ViewChild('filterTbl') filterTbl: ElementRef;
    employees: IEmployee[];
    filteredEmployees: IEmployee[] = [];
    filteredTotal: number = 100;
  columns: ITdDataTableColumn[] = [
  { name: 'EMP_ID', label: 'ID', sortable: true, width: 100 },
  { name: 'EMP_NM', label: 'Name', sortable: true, width: 200 },
  { name: 'EMP_TYP', label: 'Type', sortable: true, width: 200 },
  { name: 'TEL', label: 'Telephone', sortable: true, width: 200 },
  { name: 'ADDR', label: 'Address', sortable: true, width: 200 },
  { name: 'DT_STRT', label: 'Start Date', sortable: false, width: 200 }
];
searchTerm: string = '';
sortBy: string = 'EMP_NM';
fromRow: number = 1;
currentPage: number = 1;
pageSize: number = 10;
  sortOrder: TdDataTableSortingOrder = TdDataTableSortingOrder.Ascending;

  constructor(private _dataTableService: TdDataTableService, private restService: RestService)  { }

    sort(sortEvent: ITdDataTableSortChangeEvent): void {
        this.sortBy = sortEvent.name;
        console.log(sortEvent.name);
        this.filter();
    }

    search(searchTerm: string): void {
        this.searchTerm = searchTerm;
        this.filter();
    }

    page(pagingEvent: IPageChangeEvent): void {
        this.fromRow = pagingEvent.fromRow;
        this.currentPage = pagingEvent.page;
        this.pageSize = pagingEvent.pageSize;
        this.filter();
    }

    filter(): void {
        let newData: IEmployee[] = this.employees;
        let excludedColumns: string[] = this.columns
            .filter((column: ITdDataTableColumn) => {
                return ((column.filter === undefined && column.hidden === true) ||
                (column.filter !== undefined && column.filter === false));
            }).map((column: ITdDataTableColumn) => {
            return column.name;
        });
    newData = this._dataTableService.filterData(newData, this.searchTerm, true, excludedColumns);
    this.filteredTotal = newData.length;
    newData = this._dataTableService.sortData(newData, this.sortBy, this.sortOrder);
    newData = this._dataTableService.pageData(newData, this.fromRow, this.currentPage * this.pageSize);
    this.filteredEmployees = newData;
  }

  getEmployees() {
      this.restService.getEmployees()
    .subscribe(
    (res) => {
        console.log(res);
        this.employees = res;
        this.employees.forEach((emp: IEmployee) => {
            emp.DT_STRT = new StringToDatePipe().transform(emp.DT_STRT);
        });
        this.filter();
    }, (err) => {
        console.log(err);
    });
  }

  ngOnInit() {
         Observable.fromEvent(this.filterTbl.nativeElement, 'keyup')
        .debounceTime(150)
        .distinctUntilChanged()
        .subscribe(() => {
          this.searchTerm = this.filterTbl.nativeElement.value;
          this.filter();
        });

      this.getEmployees();
  }

}

Body:
There is a typo in your td-data-table-row component. You should be using *ngFor. See this stackblitz for the working code

<tr td-data-table-row *ngFor="let row of filteredEmployees">
    <td td-data-table-cell *ngFor="let column of columns">
            {{row[column.name]}}
    </td>
</tr>

For simple use cases, using the data table without the atomic components can help avoid the more complex template code. Simply pass in your data and configuration as inputs to <td-data-table>

<td-data-table
  #dataTable
  [data]="filteredData"
  [columns]="columns"
  [sortable]="true"
  sortOrder="ASC"
  [style.height.px]="200">
</td-data-table>


问:
How to replace values in data frame with 2-level columns based on condition in Python?
I use Python 3.6.1. Here is my data frame myDF I want to manipulate values for:

```<code>    a     b          c
    a    X1    X2   X1    X2
 0  10    .     o    o     o
 1  20    .     o    o     o
 2  30    .     o    o     o
</code>```

As you can see there are columns 'a', 'b', 'c' on level 0, and there are columns 'a', 'X1', 'X2' on level 1.

I need to compare whether a value in X1 is equal to a corresponding value in X2 under b/c and if so, remove the values. So the operation on the above data frame should return this:

```<code>    a     b          c
    a    X1    X2   X1    X2
 0  10    .     o
 1  20    .     o
 2  30    .     o
</code>```

This is how to get the source data frame:

```<code>import numpy
import pandas

X1 = pandas.DataFrame(data=[[10,'.','o'],[20,'.','o'],[30,'.','o']],
                      columns=['a','b','c'])
X2 = pandas.DataFrame(data=[[10,'o','o'],[20,'o','o'],[30,'o','o']],
                      columns=['a','b','c'])

myDF = pandas.concat([X1.set_index('a'), X2.set_index('a')],
                     axis='columns', keys=['X1','X2'])
myDF = myDF.swaplevel(axis='columns')[X1.columns[1:]]
myDF = myDF.reset_index(col_level=1, col_fill='a')
</code>```

What I have tried so far is:

```<code>other = myDF.xs('X1', axis=1, level=-1)
main = numpy.where(myDF.eq(other, level=0), 'x', 'y')
pandas.DataFrame(main, index=myDF.index, columns=myDF.columns)
</code>```

Which gives:

```<code>   a    b          c
   a   X1    X2   X1    X2
0  F    T     F    T     T
1  F    T     F    T     T
2  F    T     F    T     T
</code>```

And have no idea how to move forward ...

答:
My whole goal is to create a temporary dataframe with two columns, ['X1', 'X2'] so I can mask the rows where they are equal.  This gets me the two columns:

```<code>myDF.set_index(('a', 'a')).stack(0)

         X1 X2
(a, a)
10     b  .  o
       c  o  o
20     b  .  o
       c  o  o
30     b  .  o
       c  o  o
</code>```

I could save this to a temp name then manipulate in several additional lines.  Or I can perform the task in line with a pipe.

```<code>myDF.set_index(('a', 'a')).stack(0).pipe(
    lambda d: d.mask(d.X1 == d.X2, '')
)

         X1 X2
(a, a)
10     b  .  o
       c
20     b  .  o
       c
30     b  .  o
       c
</code>```

The rest is just accounting work to get things back into their place.

```<code>myDF.set_index(('a', 'a')).stack(0).pipe(
    lambda d: d.mask(d.X1 == d.X2, '')
).unstack().swaplevel(0, 1, 1).sort_index(1).reset_index()

    a  b     c
    a X1 X2 X1 X2
0  10  .  o
1  20  .  o
2  30  .  o
</code>```

Body:
I use Python 3.6.1. Here is my data frame myDF I want to manipulate values for:

    a     b          c
    a    X1    X2   X1    X2
 0  10    .     o    o     o
 1  20    .     o    o     o
 2  30    .     o    o     o

As you can see there are columns 'a', 'b', 'c' on level 0, and there are columns 'a', 'X1', 'X2' on level 1.

I need to compare whether a value in X1 is equal to a corresponding value in X2 under b/c and if so, remove the values. So the operation on the above data frame should return this:

    a     b          c
    a    X1    X2   X1    X2
 0  10    .     o
 1  20    .     o
 2  30    .     o

This is how to get the source data frame:

import numpy
import pandas

X1 = pandas.DataFrame(data=[[10,'.','o'],[20,'.','o'],[30,'.','o']],
                      columns=['a','b','c'])
X2 = pandas.DataFrame(data=[[10,'o','o'],[20,'o','o'],[30,'o','o']],
                      columns=['a','b','c'])

myDF = pandas.concat([X1.set_index('a'), X2.set_index('a')],
                     axis='columns', keys=['X1','X2'])
myDF = myDF.swaplevel(axis='columns')[X1.columns[1:]]
myDF = myDF.reset_index(col_level=1, col_fill='a')

What I have tried so far is:

other = myDF.xs('X1', axis=1, level=-1)
main = numpy.where(myDF.eq(other, level=0), 'x', 'y')
pandas.DataFrame(main, index=myDF.index, columns=myDF.columns)

Which gives:

   a    b          c
   a   X1    X2   X1    X2
0  F    T     F    T     T
1  F    T     F    T     T
2  F    T     F    T     T

And have no idea how to move forward ...

Body:
My whole goal is to create a temporary dataframe with two columns, ['X1', 'X2'] so I can mask the rows where they are equal.  This gets me the two columns:

myDF.set_index(('a', 'a')).stack(0)

         X1 X2
(a, a)
10     b  .  o
       c  o  o
20     b  .  o
       c  o  o
30     b  .  o
       c  o  o

I could save this to a temp name then manipulate in several additional lines.  Or I can perform the task in line with a pipe.

myDF.set_index(('a', 'a')).stack(0).pipe(
    lambda d: d.mask(d.X1 == d.X2, '')
)

         X1 X2
(a, a)
10     b  .  o
       c
20     b  .  o
       c
30     b  .  o
       c

The rest is just accounting work to get things back into their place.

myDF.set_index(('a', 'a')).stack(0).pipe(
    lambda d: d.mask(d.X1 == d.X2, '')
).unstack().swaplevel(0, 1, 1).sort_index(1).reset_index()

    a  b     c
    a X1 X2 X1 X2
0  10  .  o
1  20  .  o
2  30  .  o


问:
Java Recognize specific objects in image
I need to classify bolt, nut, and washer from the image,

but I don't know how to detect those objects from the image.

(This is the part of the image)

I copied every color (used java.awt.Color) value from the image to 2D array,

but I have no idea what I have to do with this.

If I want to classify them, program have to recognize which part is not a background at least.

Does java has library for this?

答:
Have you try openCV.
Here is the face detection exemple your problem is a bit similar.
May be it will help</p>


问:
Application overhead design decision: store needed value on database row or find it dynamically in queryset
I'm developing a simple price tracker application. I'm a bit new to web application design and could use an experienced opinion here. My application pulls price points for hundreds of thousand of products per day by unique product SKU.

For each SKU I want to be able to show:

All time high price

All time low price

Average price

When my API writes a new SKU price to the database I am able to figure out these three values and write them to the latest/current price row. Is this a better design decision than say using a Django Queryset in my View to query for and/or calculate and display them?

EDIT:

Sure, I'm currently feeding them to a Django Class Based View with def get_context_data.

```<code>context['high_price'] = prices.order_by('price').last()
context['low_price'] = prices.order_by('-price').last()
context['avg_price'] = prices.aggregate(average=Avg('price'))
</code>```

Note that I am not using aggregate MIN/MAX as I need the date with each price as well so I need to entire price row (Price model is structured in columns of 'Date of Price' and 'Price').

Original question still stands. Should I Queryset this or write the high/low/average each time I bring in a new price? Here's how I could do that (example for highest all time price):

```<code>if product.high_price is None or (price.value is not None and price.value >= product.high_price.value):
            product.high_price = price
</code>```

答:
Using a queryset for this should be fast, provided you have an index.  It would be interesting to benchmark what you have, then in your model, add index and repeat.  eg.

```<code>  price = models.DecimalField(db_index=True)
</code>```

See https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.Field.db_index

Calculating the average will be the slow one and it might be worth have a job that calculates the average and stores it somewhere.  You can use celery/redis to do this in the background or do it once when you pull the data in, depending on your setup.

Body:
I'm developing a simple price tracker application. I'm a bit new to web application design and could use an experienced opinion here. My application pulls price points for hundreds of thousand of products per day by unique product SKU.

For each SKU I want to be able to show:

All time high price

All time low price

Average price

When my API writes a new SKU price to the database I am able to figure out these three values and write them to the latest/current price row. Is this a better design decision than say using a Django Queryset in my View to query for and/or calculate and display them?

EDIT:

Sure, I'm currently feeding them to a Django Class Based View with def get_context_data.

context['high_price'] = prices.order_by('price').last()
context['low_price'] = prices.order_by('-price').last()
context['avg_price'] = prices.aggregate(average=Avg('price'))

Note that I am not using aggregate MIN/MAX as I need the date with each price as well so I need to entire price row (Price model is structured in columns of 'Date of Price' and 'Price').

Original question still stands. Should I Queryset this or write the high/low/average each time I bring in a new price? Here's how I could do that (example for highest all time price):

if product.high_price is None or (price.value is not None and price.value >= product.high_price.value):
            product.high_price = price

Body:
Using a queryset for this should be fast, provided you have an index.  It would be interesting to benchmark what you have, then in your model, add index and repeat.  eg.

  price = models.DecimalField(db_index=True)

See https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.Field.db_index

Calculating the average will be the slow one and it might be worth have a job that calculates the average and stores it somewhere.  You can use celery/redis to do this in the background or do it once when you pull the data in, depending on your setup.


问:
merge an array by parent id using lodashjs api
I have an array with structure as below:

```<code>[
  {
    "id": 1,
    "type": "SUB",
    "username": "jksub04m1s8"
  },
  {
    "id": 2,
    "parent_id": 1,
    "type": "SUB",
    "username": "jksub04m2s4"
  },
  {
    "id": 3,
    "parent_id": 1,
    "type": "OPERATOR",
    "username": "mountbetoperator"
  },
  {
    "id": 4,
    "parent_id": 2,
    "type": "SUB",
    "username": "jksub04m2s2"
  },
  {
    "id": 5,
    "type": "SUB",
    "username": "jksub04m1s8"
  },
  {
    "id": 6,
    "type": "SUB",
    "parent_id": 2,
    "username": "jksub04m1s8"
  }
]
</code>```

I write an function to restructure it by mapping it parent id as below:

```<code>[
  {
    "id": 1,
    "type": "SUB",
    "username": "jksub04m1s8",
    "children": [
      {
        "id": 2,
        "parent_id": 1,
        "type": "SUB",
        "username": "jksub04m2s4",
        "children": [
          {
            "id": 4,
            "parent_id": 2,
            "type": "SUB",
            "username": "jksub04m2s2"
          },
          {
            "id": 6,
            "type": "SUB",
            "parent_id": 2,
            "username": "jksub04m1s8"
          }
        ]
      }...
]
</code>```

But my function is so long and make the process so slow, actually I have about 10000+ records like this.

Could I use lodash api to restructure it?

答:
You can simply right a JS function, using a map and iterate the array twice you can achieve this, you don't even need recursive function or complex code. here is a example I have written you can try.

var arr = arr = [{
        "id": 1,
        "type": "SUB",
        "username": "jksub04m1s8"
    },
    {
        "id": 2,
        "parent_id": 1,
        "type": "SUB",
        "username": "jksub04m2s4"
    },
    {
        "id": 3,
        "parent_id": 1,
        "type": "OPERATOR",
        "username": "mountbetoperator"
    },
    {
        "id": 4,
        "parent_id": 2,
        "type": "SUB",
        "username": "jksub04m2s2"
    },
    {
        "id": 5,
        "type": "SUB",
        "username": "jksub04m1s8"
    },
    {
        "id": 6,
        "type": "SUB",
        "parent_id": 2,
        "username": "jksub04m1s8"
    }
];

function transform(input) {
    var res = [],
        idx,
        map = {},
        addedToParentMap = {},
        temp,
        tempParent,
        curr,
        twiceLen = input.length * 2;
    for (idx = 0; idx < twiceLen; idx++) {
        curr = input[idx % input.length];
        temp = map[curr.id] || Object.assign({
            children: []
        }, curr);

        if (!temp.parent_id && !map[curr.id]) {
            res.push(temp);
        } else {
            tempParent = map[temp.parent_id];
            if (tempParent && !addedToParentMap[temp.id]) {
                tempParent.children.push(temp);
                addedToParentMap[temp.id] = true;
            }
        }
        map[curr.id] = temp;
    }
    return res;
}

var res = transform(arr);
console.log(res);```

Body:
I have an array with structure as below:

[
  {
    "id": 1,
    "type": "SUB",
    "username": "jksub04m1s8"
  },
  {
    "id": 2,
    "parent_id": 1,
    "type": "SUB",
    "username": "jksub04m2s4"
  },
  {
    "id": 3,
    "parent_id": 1,
    "type": "OPERATOR",
    "username": "mountbetoperator"
  },
  {
    "id": 4,
    "parent_id": 2,
    "type": "SUB",
    "username": "jksub04m2s2"
  },
  {
    "id": 5,
    "type": "SUB",
    "username": "jksub04m1s8"
  },
  {
    "id": 6,
    "type": "SUB",
    "parent_id": 2,
    "username": "jksub04m1s8"
  }
]

I write an function to restructure it by mapping it parent id as below:

[
  {
    "id": 1,
    "type": "SUB",
    "username": "jksub04m1s8",
    "children": [
      {
        "id": 2,
        "parent_id": 1,
        "type": "SUB",
        "username": "jksub04m2s4",
        "children": [
          {
            "id": 4,
            "parent_id": 2,
            "type": "SUB",
            "username": "jksub04m2s2"
          },
          {
            "id": 6,
            "type": "SUB",
            "parent_id": 2,
            "username": "jksub04m1s8"
          }
        ]
      }...
]

But my function is so long and make the process so slow, actually I have about 10000+ records like this.

Could I use lodash api to restructure it?


问:
RESTORE .bak-file from c:\users\ directories on SQL Server
I have this update tool for my program. The tool updates the SQL Server database with this code (vb and sql).

```<code>Dim sql As Process = Process.Start("sqlcmd.exe", Param + " -i update.sql -o log.txt")
</code>```

Param contains the name of the .bak file myprogram_update.bak among others.

update.sql starts with

```<code>RESTORE DATABASE [myprogram_tmp]
FROM DISK = N'$(db_src)'
WITH FILE = 1,
MOVE N'myprogram_tmp' TO @mdf,
MOVE N'myprogram_tmp_log' TO @ldf,
NOUNLOAD, STATS = 5
</code>```

@mdf and @ldf are standard paths read from the SQL Server settings.

The update tool is shipped to customers and the problem is that usually SQL Servers aren't allowed to read in user directories of windows like Desktop or Downloads. But many customers unzip the archive to these directories and then they get this error.

Could not access myprogram_update.bak / access denied.

I can't change the settings on every customers server, so is there any way to make it work for these directories? One idea of mine was to run a setup first and unzip it to program files but maybe there is a smarter solution.

Edit: the tool runs in administrator mode.

答:
You should ask for elevation and run as an administrator account, maybe this will help:

http://www.downloadinformer.com/how-to-make-a-vb-net-application-always-run-in-administrator-mode/

Body:
I have this update tool for my program. The tool updates the SQL Server database with this code (vb and sql).

Dim sql As Process = Process.Start("sqlcmd.exe", Param + " -i update.sql -o log.txt")

Param contains the name of the .bak file myprogram_update.bak among others.

update.sql starts with

RESTORE DATABASE [myprogram_tmp]
FROM DISK = N'$(db_src)'
WITH FILE = 1,
MOVE N'myprogram_tmp' TO @mdf,
MOVE N'myprogram_tmp_log' TO @ldf,
NOUNLOAD, STATS = 5

@mdf and @ldf are standard paths read from the SQL Server settings.

The update tool is shipped to customers and the problem is that usually SQL Servers aren't allowed to read in user directories of windows like Desktop or Downloads. But many customers unzip the archive to these directories and then they get this error.

Could not access myprogram_update.bak / access denied.

I can't change the settings on every customers server, so is there any way to make it work for these directories? One idea of mine was to run a setup first and unzip it to program files but maybe there is a smarter solution.

Edit: the tool runs in administrator mode.


问:
Nativescript : Error: More than one view found in list template! Nesting level: 0
The layout inside template solution doesn't work

list.html

```<code><ActionBar title="View Team Members">
    <NavigationButton text="Back" android.systemIcon="ic_menu_back"></NavigationButton>
</ActionBar>
<GridLayout>
    <ListView [items]="teamList" class="small-spacing">
        <template let-item="item">
            <StackLayout>
              <Label [text]="item.name" class="medium-spacing"></Label>
              <Label [text]="item.email" class="medium-spacing"></Label>
            </StackLayout>
        </template>
    </ListView>
</GridLayout>
</code>```

Same error trace  :

```<code>com.tns.NativeScriptException:
Calling js method getView failed

Error: More than one view found in list template! Nesting level: 0
File: "/data/data/org.nativescript.finlyng/files/app/tns_modules/nativescript-angular/directives/list-view-comp.js,
</code>```

line: 138, column: 8

```<code>StackTrace:
  Frame: function:'getSingleViewRecursive', file:'/data/data/org.nativescript.finlyng/files/app/tns_modules/nativescript-angular/directives/list-view-comp.js',
</code>```

line: 138, column: 15
        Frame: function:'getSingleViewFromViewRef', file:'/data/data/org.nativescript.finlyng/files/app/tns_modules/nativescript-angular/directives/list-view-comp.js',
  line: 154, column: 12
        Frame: function:'ListViewComponent.onItemLoading', file:'/data/data/org.nativescript.finlyng/files/app/tns_modules/nativescript-angular/directives/list-view-comp.js',
  line: 72, column: 25
        Frame: function:'Observable.notify', file:'/data/data/org.nativescript.finlyng/files/app/tns_modules/data/observable/observable.js',
  line: 146, column: 32
        Frame: function:'ListViewAdap

答:
This is pretty old but I had a similar issue.

I fixed it by nesting the Labels inside a GridLayout. Something like this in my case:

```<code><GridLayout rows="auto, *">
  <ListView [items]="newsList" row="1" class="news">
    <ng-template let-item="item">
      <GridLayout rows="auto, *">
        <Image [src]="item.image"></Image>
        <Label [text]="item.title" class="news__item"></Label>
      </GridLayout>
    </ng-template>
  </ListView>
</GridLayout>
</code>```

Body:
The layout inside template solution doesn't work

list.html

<ActionBar title="View Team Members">
    <NavigationButton text="Back" android.systemIcon="ic_menu_back"></NavigationButton>
</ActionBar>
<GridLayout>
    <ListView [items]="teamList" class="small-spacing">
        <template let-item="item">
            <StackLayout>

            </StackLayout>
        </template>
    </ListView>
</GridLayout>

Same error trace  :

com.tns.NativeScriptException:
Calling js method getView failed

Error: More than one view found in list template! Nesting level: 0
File: "/data/data/org.nativescript.finlyng/files/app/tns_modules/nativescript-angular/directives/list-view-comp.js,

line: 138, column: 8

StackTrace:
  Frame: function:'getSingleViewRecursive', file:'/data/data/org.nativescript.finlyng/files/app/tns_modules/nativescript-angular/directives/list-view-comp.js',

line: 138, column: 15
        Frame: function:'getSingleViewFromViewRef', file:'/data/data/org.nativescript.finlyng/files/app/tns_modules/nativescript-angular/directives/list-view-comp.js',
  line: 154, column: 12
        Frame: function:'ListViewComponent.onItemLoading', file:'/data/data/org.nativescript.finlyng/files/app/tns_modules/nativescript-angular/directives/list-view-comp.js',
  line: 72, column: 25
        Frame: function:'Observable.notify', file:'/data/data/org.nativescript.finlyng/files/app/tns_modules/data/observable/observable.js',
  line: 146, column: 32
        Frame: function:'ListViewAdap

Body:
This is pretty old but I had a similar issue.

I fixed it by nesting the Labels inside a GridLayout. Something like this in my case:

<GridLayout rows="auto, *">
  <ListView [items]="newsList" row="1" class="news">
    <ng-template let-item="item">
      <GridLayout rows="auto, *">
        <Image [src]="item.image"></Image>
        <Label [text]="item.title" class="news__item"></Label>
      </GridLayout>
    </ng-template>
  </ListView>
</GridLayout>


问:
Charting in Gtk / Gtk#
i would like to create a simple charting system for stock in Gtk# (and C#), with the possibilities to draw inside it.
I don't know where to start: it's best to start from scratch ?
Or using something pre-made ?
Is it best to use Cairo ? Or System.Drawing ?
Are there some piece of code i can reuse ?

Thanks

答:
You can try
nplot :

NPlot includes controls for Windows.Forms, ASP.NET and a class for creating Bitmaps. A GTK# control is also available.

Title: Charting in Gtk / Gtk#


问:
Attempt to invoke virtual method getStreetViewPanoramaAsync() on a null object reference
I am trying to start a streetview panorama from a menu item on the action bar. I tried using intent (don't know if I am correct). The app launches fine but when I click on the menu item, I get this runtime error:

Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportStreetViewPanoramaFragment.getStreetViewPanoramaAsync(com.google.android.gms.maps.OnStreetViewPanoramaReadyCallback)' on a null object reference

MapsActivity.java:

```<code>package com.example.user.streetview;

import...

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private static final LatLng HOME = new LatLng(6.450957, 3.363493);

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

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.maps);
    mapFragment.getMapAsync(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.get_panorama, menu);
    return true;

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.get_panorama:
            Intent intent = new Intent(this, StreetViewPanoramaActivity.class);
            startActivity(intent);
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker for HOME and move the camera
    mMap.addMarker(new MarkerOptions().position(HOME).title("Home marker"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(HOME));
}
</code>```

}

StreetViewPanoramaActivity.java

```<code>package com.example.user.streetview;

import...

public class StreetViewPanoramaActivity extends FragmentActivity implements StreetViewPanorama.OnStreetViewPanoramaChangeListener {

private StreetViewPanorama mStreetViewPanorama;
private static final LatLng HOME = new LatLng(6.450957, 3.363493);
public static final float ZOOM_BY = 0.5f;

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

    // Get the Intent that started this activity and extract the string
    Intent intent = getIntent();

    //Then use getStreetViewPanoramaAsync() to set the callback on the fragment.
    SupportStreetViewPanoramaFragment streetViewPanoramaFragment = (SupportStreetViewPanoramaFragment) getSupportFragmentManager().findFragmentById(R.id.street_view_panorama);
    streetViewPanoramaFragment.getStreetViewPanoramaAsync(new OnStreetViewPanoramaReadyCallback() {
        @Override
        public void onStreetViewPanoramaReady(StreetViewPanorama panorama) {
            mStreetViewPanorama = panorama;
            mStreetViewPanorama.setPosition(HOME);
            mStreetViewPanorama.setStreetNamesEnabled(true);

            StreetViewPanoramaCamera camera = new StreetViewPanoramaCamera.Builder()
                    .zoom(mStreetViewPanorama.getPanoramaCamera().zoom + ZOOM_BY)
                    .tilt(mStreetViewPanorama.getPanoramaCamera().tilt)
                    .bearing(mStreetViewPanorama.getPanoramaCamera().bearing)
                    .build();
        }
    });

@Override
public void onStreetViewPanoramaChange(StreetViewPanoramaLocation location) {
    location = mStreetViewPanorama.getLocation();
    if (location != null && location.links != null) {
        mStreetViewPanorama.setPosition(location.links[0].panoId);
    }
 }

}
</code>```

Menu layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
  <item
      android:id="@+id/get_panorama"
      android:orderInCategory="100"
      android:title="@string/get_panorama"
      app:showAsAction="always">
  </item>
</menu>
</code>```

Thank you!

答: Null Pointer Exceptions Occur most likely if an object is used before it's being instialized</p>

Body:
I am trying to start a streetview panorama from a menu item on the action bar. I tried using intent (don't know if I am correct). The app launches fine but when I click on the menu item, I get this runtime error:

Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportStreetViewPanoramaFragment.getStreetViewPanoramaAsync(com.google.android.gms.maps.OnStreetViewPanoramaReadyCallback)' on a null object reference

MapsActivity.java:

package com.example.user.streetview;

import...

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private static final LatLng HOME = new LatLng(6.450957, 3.363493);

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

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.maps);
    mapFragment.getMapAsync(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.get_panorama, menu);
    return true;

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.get_panorama:
            Intent intent = new Intent(this, StreetViewPanoramaActivity.class);
            startActivity(intent);
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker for HOME and move the camera
    mMap.addMarker(new MarkerOptions().position(HOME).title("Home marker"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(HOME));
}

}

StreetViewPanoramaActivity.java

package com.example.user.streetview;

import...

public class StreetViewPanoramaActivity extends FragmentActivity implements StreetViewPanorama.OnStreetViewPanoramaChangeListener {

private StreetViewPanorama mStreetViewPanorama;
private static final LatLng HOME = new LatLng(6.450957, 3.363493);
public static final float ZOOM_BY = 0.5f;

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

    // Get the Intent that started this activity and extract the string
    Intent intent = getIntent();

    //Then use getStreetViewPanoramaAsync() to set the callback on the fragment.
    SupportStreetViewPanoramaFragment streetViewPanoramaFragment = (SupportStreetViewPanoramaFragment) getSupportFragmentManager().findFragmentById(R.id.street_view_panorama);
    streetViewPanoramaFragment.getStreetViewPanoramaAsync(new OnStreetViewPanoramaReadyCallback() {
        @Override
        public void onStreetViewPanoramaReady(StreetViewPanorama panorama) {
            mStreetViewPanorama = panorama;
            mStreetViewPanorama.setPosition(HOME);
            mStreetViewPanorama.setStreetNamesEnabled(true);

            StreetViewPanoramaCamera camera = new StreetViewPanoramaCamera.Builder()
                    .zoom(mStreetViewPanorama.getPanoramaCamera().zoom + ZOOM_BY)
                    .tilt(mStreetViewPanorama.getPanoramaCamera().tilt)
                    .bearing(mStreetViewPanorama.getPanoramaCamera().bearing)
                    .build();
        }
    });

@Override
public void onStreetViewPanoramaChange(StreetViewPanoramaLocation location) {
    location = mStreetViewPanorama.getLocation();
    if (location != null && location.links != null) {
        mStreetViewPanorama.setPosition(location.links[0].panoId);
    }
 }

}

Menu layout:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
  <item
      android:id="@+id/get_panorama"
      android:orderInCategory="100"
      android:title="@string/get_panorama"
      app:showAsAction="always">
  </item>
</menu>

Thank you!


问:
How to stream data via BLE?
I am currently evaluating the board of Maxim Integrated MAXREFDES100#. As part of my thesis, I would like to examine whether there is the possibility of using BLE for data streaming.

The supplied software is fully functional and can already transfer data. Of course, only smaller data packets over a longer period like Temperature or precalculated Heart Rate values. I am aware that BLE is not suitable and has not been designed to transmit data continuously. Nevertheless, I would like to try to transfer the ECG raw data also via the BLE interface. So that I can check whether my data has been arrived completely and correctly in time (prerequisite for ECG data), I have developed the following test setup:

Currently, I store data of a sine wave to a large FIFO and transfer 20-byte sine packets to a characteristic. So far everything works wonderfully. Using an Android device and a BLE sniffer I catch the data packets and check if the sine has any interruptions. The following graphic is taken from a longer measurement: (I have tested my FIFO and the sine datas are complete without any inerruption): This is a capture of my Android and my BLE Sniffer: Data packets are missing.

Sine & Spektrogram Image

Further measurements show that the errors do not occur sequentially, they can always be found at different times. (The Fifo Implementation must be correct)

Sine & Spektrogram Image 2

Since my phone and my Adafruit BLE sniffer have identical errors in the same place, the data packages on the board-side must be corrupt. I suspect they are lost at some protocol level (GAP maybe?). Interestingly, errors affect at least 200 following bytes (256 bytes data are a complete sine). This means that at least 10 data packets each 20 Bytes would have to be in order to get such a graphic.

What options are there for continuously sending data via the BLE interface?

Is it possible to send the data directly via L2CAP without GATT/ATT?

Are there any more wireless, low power protocols that allow data streaming? (So with acknowledgment like TCP for completeness and chronological correctness)

Best regards, Emin

答:
What options are there for continuously sending data via the BLE interface?

Is it possible to send the data directly via L2CAP without GATT/ATT?

BLE v4.1 introduced LE Connection-Oriented Channels which is a way to send data directly via L2CAP without GATT/ATT (think about network sockets). See also Bluetooth Core Specification Vol. 3 Part A Section 3.4.

The board you are using has a EM9301 BLE chip which seems to support BLE v4.1. However, the mbed library you are using doesn't allow you to use them. See here, you have an interface for connect/disconnect callbacks and GATT characteristics read/write/notification. Nothing about LE Connection-Oriented Channel.

Title: How to stream data via BLE?


问:
DAX Custom Financial Periods
I have an SSAS Tabular model that I am attempting to use a DAX expression to calculate Year over Year metrics on.  I have a table called fact_transaction and a table called dimdate that are relevant to the calculation I am trying to do.   The dimdate table has a date key, a date field, a Year field, a month field,  a period field and a quarter field.  As A result of needing to use the financial Periods rather than months, SAMEPERIODLASTYEAR will not work for my calculations.  </p>

<p>The financial periods do not correspond directly to months of the year and can vary in length by up to 2 days.  Is there any way to calculate this without getting too convoluted?  within a SQL query I would just join it to itself with [Year] = [YEAR] -1 and Period = Period (Along with the various account fields used in the relationships).  Not particularly sure how to do this in DAX. </p>

答:
Yes, you should be able to do something very similar in DAX with filters. It's hard to write exactly what you need without more details, but maybe try something like this:

```<code>YoY Metric =
VAR CurrentYear = SELECTEDVALUE(DimDate[Year])
VAR CurrentPeriod = SELECTEDVALUE(DimDate[Period])
RETURN CALCULATE([Expression],
           FILTER(ALL(DimDate),
               DimDate[Year] = CurrentYear - 1 &&
               DimDate[Period] = CurrentPeriod))
</code>```

Edit

If SELECTEDVALUE is not available, then define the variables like this:

```<code>VAR CurrentYear = IF(HASONEVALUE(DimDate[Year]), VALUES(DimDate[Year]))
VAR CurrentPeriod = IF(HASONEVALUE(DimDate[Period]), VALUES(DimDate[Period]))
</code>```

Title: DAX Custom Financial Periods

Body:
I have an SSAS Tabular model that I am attempting to use a DAX expression to calculate Year over Year metrics on.  I have a table called fact_transaction and a table called dimdate that are relevant to the calculation I am trying to do.   The dimdate table has a date key, a date field, a Year field, a month field,  a period field and a quarter field.  As A result of needing to use the financial Periods rather than months, SAMEPERIODLASTYEAR will not work for my calculations.

The financial periods do not correspond directly to months of the year and can vary in length by up to 2 days.  Is there any way to calculate this without getting too convoluted?  within a SQL query I would just join it to itself with [Year] = [YEAR] -1 and Period = Period (Along with the various account fields used in the relationships).  Not particularly sure how to do this in DAX.

Body:
Yes, you should be able to do something very similar in DAX with filters. It's hard to write exactly what you need without more details, but maybe try something like this:

YoY Metric =
VAR CurrentYear = SELECTEDVALUE(DimDate[Year])
VAR CurrentPeriod = SELECTEDVALUE(DimDate[Period])
RETURN CALCULATE([Expression],
           FILTER(ALL(DimDate),
               DimDate[Year] = CurrentYear - 1 &&
               DimDate[Period] = CurrentPeriod))

Edit

If SELECTEDVALUE is not available, then define the variables like this:

VAR CurrentYear = IF(HASONEVALUE(DimDate[Year]), VALUES(DimDate[Year]))
VAR CurrentPeriod = IF(HASONEVALUE(DimDate[Period]), VALUES(DimDate[Period]))