问:
Question on Excel document level deployment
We have a VSTO excel document level project. The excel document created as part of this project has a worksheet (named Start Sheet) which has some winforms controls (like button, checkbox etc) and there are many other worksheets which mainly contains data. We
deploy this solution using Windows Installer to client’s machines. The excel version is excel 2007 and VSTO 2010.

Whenever our solution is deployed on client’s machines, the clients usually customize the excel document on their machine. Like they will add some new worksheets apart from the ones we have added. They also install some addins like PI to bring in data to these worksheets. Now we usually have enhancement request from our clients and most of these enhancements
are adding new sheets to the excel document. Almost 99% of the requests are adding a new sheet. The code behind each sheet is some business logic which is mainly triggered by the winform controls on Start sheet.

Now every time, they install a enhanced version of the solution, they end up getting a new excel document and then they have to customize it again (like adding some sheets, writing macros etc), which is lot of work for them. This is a huge problem for us these days
as our clients do not like it at all.

Is there a way that they can deploy the new versions of solution and still keep their excel document customizations unchanged ? My experience with VSTO is not much and help will be much appreciated.

答:
I would change the design of the project so that the code and template elements (sheets, formatting, formulae, controls, encapsulated data etc) are separated from the users excel documents but can generate or modify the users documents. The EUI would be Excel Menus/Toolbars or Ribbon Tabs.

Usually you would do this by creating an Excel Addin (XLA, XLL, COM or Automation Addin).


来源: stackexchange

问:
Is there any issue sharing class member on either both of doInBackground and onPostExecute of AsyncTask of android?
```<code>The following is my example code.

private class PostLikes extends AsyncTask<Integer, Void, Void> {
 String type_id, msg;

 @Override
 protected Void doInBackground(Integer... params) {
//....
//....
  type_id = jsonobject2.getString("type_id");
  msg = jsonobject2.getString("msg");
  return null;
 }

 @Override
 protected void onPostExecute(Void result) {
  if (type_id.equals("1")) {
    Toast.makeText(getApplicationContext(), "error, Toast.LENGTH_SHORT).show();
  } else {
    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
  }
 }

}
</code>```

<p>The standard way of using AsyncTask is to make doInBackground function return some result of the background thread to onPostExecute function.
That code is working well but I want to know whether any issue exist in the above code.
Thanks. </p>

答: I believe that you are OK with how this is set up. Your member variables type_id and msg are referenced from onPostExecute() like any other member variables. doInBackground() will have completed by the time onPostExecute() run, so there will not be a threading conflict.

ContentLicense: CC BY-SA 3.0

Body:
The following is my example code.

private class PostLikes extends AsyncTask<Integer, Void, Void> {
 String type_id, msg;

 @Override
 protected Void doInBackground(Integer... params) {
//....
//....
  type_id = jsonobject2.getString("type_id");
  msg = jsonobject2.getString("msg");
  return null;
 }

 @Override
 protected void onPostExecute(Void result) {
  if (type_id.equals("1")) {
    Toast.makeText(getApplicationContext(), "error, Toast.LENGTH_SHORT).show();
  } else {
    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
  }
 }

}

The standard way of using AsyncTask is to make doInBackground function return some result of the background thread to onPostExecute function.
That code is working well but I want to know whether any issue exist in the above code.
Thanks.


问:
Where was scala_home homebrew installed on OSX?
I can't get scalac working despite scala successfully opening scala> in the terminal.
I suspect this is something to do with setting scala_home in my .bash_profile, on my mac.

What is the correct value for SCALA_HOME, or how do I find that correct value? (it was homebrewed)

And is the method to scale-compile the following:

to cd into the lower src folder and scalac IntroducingScala.HelloWorld.scala?

答:
Homebrew usually tells you where it installs if you do brew info <name>. It's usually points at /usr/local/opt/<name>, which will be a symlink to the current version you're running.

When I run brew info scala it also comes with a helpful caveat:

```<code>==> Caveats
To use with IntelliJ, set the Scala home to:
/usr/local/opt/scala/idea
</code>```

Body:
Homebrew usually tells you where it installs if you do brew info <name>. It's usually points at /usr/local/opt/<name>, which will be a symlink to the current version you're running.

When I run brew info scala it also comes with a helpful caveat:

==> Caveats
To use with IntelliJ, set the Scala home to:
/usr/local/opt/scala/idea


问:
Trick to loop/autorefresh docker ps view like top/htop in bash
Is it possible - and if yes, how - to have a self-refreshing view of current Docker containers printed by "docker ps" alike top/htop utilities?</p>

答:
Few options:

You can try command docker stats, which will give you some details about current running containers id, cpu%, memory etc. Something similar to top/htop which you asked for.

Command docker top CONTAINER [ps OPTIONS] : It displays the running processes of a container.

There are also some applications available which gives nice view of your docker ecosystem. Eg- Kitematic, Kevana


问:
Android DataBinding with selector view
I want to use selector with view (favorite button) and Data Binding library.
This is my layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<layout ...>
<data>
    <variable
            name="obj"
            type="com.zor.dev.simplebelnewsreader.instance.News"/>

    <variable
            name="handler"
            type="com.zor.dev.simplebelnewsreader.handler.Handlers"/>
</data>
<View
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:id="@+id/selectorButton"
            android:onClick="@{() -> handler.setFavorite(obj)}"
            android:background="@drawable/fav_button2"
            app:selected="@{obj.favorite}"
            android:layout_marginStart="20dp"/>
</code>```

This is my Handler:

```<code> public void setFavorite(News news) {
    news.setFavorite(!news.isFavorite());
}
</code>```

and this is selector:

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
      android:state_selected="true"
      android:drawable="@drawable/ic_star_purple_a400_24dp"
      >
</item>
<item android:drawable="@drawable/star_favorite_not">

</item>
</code>```

And nothing, when i clicked item. What wrong in my code?

答:
Xml:

```<code><View
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:id="@+id/selectorButton"
            android:onClick="@{() -> handler.setFavorite(obj)}"
            android:background="@drawable/fav_button2"
            app:selected="@={obj.favorite}"
            android:layout_marginStart="20dp"/>
</code>```

Handler:

```<code>public void setFavorite(News news) {
    news.setFavorite(!news.isFavorite());
    notifyPropertyChanged(BR.favorite); //'favorite' is the boolean variable name
}
</code>```

Title: Android DataBinding with selector view

Body:
I want to use selector with view (favorite button) and Data Binding library.
This is my layout:

<?xml version="1.0" encoding="utf-8"?>
<layout ...>
<data>
    <variable
            name="obj"
            type="com.zor.dev.simplebelnewsreader.instance.News"/>

    <variable
            name="handler"
            type="com.zor.dev.simplebelnewsreader.handler.Handlers"/>
</data>
<View
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:id="@+id/selectorButton"
            android:onClick="@{() -> handler.setFavorite(obj)}"
            android:background="@drawable/fav_button2"
            app:selected="@{obj.favorite}"
            android:layout_marginStart="20dp"/>

This is my Handler:

 public void setFavorite(News news) {
    news.setFavorite(!news.isFavorite());
}

and this is selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
      android:state_selected="true"
      android:drawable="@drawable/ic_star_purple_a400_24dp"
      >
</item>
<item android:drawable="@drawable/star_favorite_not">

</item>

And nothing, when i clicked item. What wrong in my code?

Body:
Xml:

<View
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:id="@+id/selectorButton"
            android:onClick="@{() -> handler.setFavorite(obj)}"
            android:background="@drawable/fav_button2"
            app:selected="@={obj.favorite}"
            android:layout_marginStart="20dp"/>

Handler:

public void setFavorite(News news) {
    news.setFavorite(!news.isFavorite());
    notifyPropertyChanged(BR.favorite); //'favorite' is the boolean variable name
}


问:
Find the most frequent number in a NumPy array
Suppose I have the following NumPy array:

```<code>a = np.array([1,2,3,1,2,1,1,1,3,2,2,1])
</code>```

How can I find the most frequent number in this array?

答:
Here is a general solution that may be applied along an axis, regardless of values, using purely numpy.  I've also found that this is much faster than scipy.stats.mode if there are a lot of unique values.</p>

```<code>import numpy

def mode(ndarray, axis=0):
    # Check inputs
    ndarray = numpy.asarray(ndarray)
    ndim = ndarray.ndim
    if ndarray.size == 1:
        return (ndarray[0], 1)
    elif ndarray.size == 0:
        raise Exception('Cannot compute mode on empty array')
    try:
        axis = range(ndarray.ndim)[axis]
    except:
        raise Exception('Axis "{}" incompatible with the {}-dimension array'.format(axis, ndim))

    # If array is 1-D and numpy version is > 1.9 numpy.unique will suffice
    if all([ndim == 1,
            int(numpy.__version__.split('.')[0]) >= 1,
            int(numpy.__version__.split('.')[1]) >= 9]):
        modals, counts = numpy.unique(ndarray, return_counts=True)
        index = numpy.argmax(counts)
        return modals[index], counts[index]

    # Sort array
    sort = numpy.sort(ndarray, axis=axis)
    # Create array to transpose along the axis and get padding shape
    transpose = numpy.roll(numpy.arange(ndim)[::-1], axis)
    shape = list(sort.shape)
    shape[axis] = 1
    # Create a boolean array along strides of unique values
    strides = numpy.concatenate([numpy.zeros(shape=shape, dtype='bool'),
                                 numpy.diff(sort, axis=axis) == 0,
                                 numpy.zeros(shape=shape, dtype='bool')],
                                axis=axis).transpose(transpose).ravel()
    # Count the stride lengths
    counts = numpy.cumsum(strides)
    counts[~strides] = numpy.concatenate([[0], numpy.diff(counts[~strides])])
    counts[strides] = 0
    # Get shape of padded counts and slice to return to the original shape
    shape = numpy.array(sort.shape)
    shape[axis] += 1
    shape = shape[transpose]
    slices = [slice(None)] * ndim
    slices[axis] = slice(1, None)
    # Reshape and compute final counts
    counts = counts.reshape(shape).transpose(transpose)[slices] + 1

    # Find maximum counts and return modals/counts
    slices = [slice(None, i) for i in sort.shape]
    del slices[axis]
    index = numpy.ogrid[slices]
    index.insert(axis, numpy.argmax(counts, axis=axis))
    return sort[index], counts[index]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Suppose I have the following NumPy array:

a = np.array([1,2,3,1,2,1,1,1,3,2,2,1])

How can I find the most frequent number in this array?

Body:
Here is a general solution that may be applied along an axis, regardless of values, using purely numpy.  I've also found that this is much faster than scipy.stats.mode if there are a lot of unique values.

import numpy

def mode(ndarray, axis=0):
    # Check inputs
    ndarray = numpy.asarray(ndarray)
    ndim = ndarray.ndim
    if ndarray.size == 1:
        return (ndarray[0], 1)
    elif ndarray.size == 0:
        raise Exception('Cannot compute mode on empty array')
    try:
        axis = range(ndarray.ndim)[axis]
    except:
        raise Exception('Axis "{}" incompatible with the {}-dimension array'.format(axis, ndim))

    # If array is 1-D and numpy version is > 1.9 numpy.unique will suffice
    if all([ndim == 1,
            int(numpy.__version__.split('.')[0]) >= 1,
            int(numpy.__version__.split('.')[1]) >= 9]):
        modals, counts = numpy.unique(ndarray, return_counts=True)
        index = numpy.argmax(counts)
        return modals[index], counts[index]

    # Sort array
    sort = numpy.sort(ndarray, axis=axis)
    # Create array to transpose along the axis and get padding shape
    transpose = numpy.roll(numpy.arange(ndim)[::-1], axis)
    shape = list(sort.shape)
    shape[axis] = 1
    # Create a boolean array along strides of unique values
    strides = numpy.concatenate([numpy.zeros(shape=shape, dtype='bool'),
                                 numpy.diff(sort, axis=axis) == 0,
                                 numpy.zeros(shape=shape, dtype='bool')],
                                axis=axis).transpose(transpose).ravel()
    # Count the stride lengths
    counts = numpy.cumsum(strides)
    counts[~strides] = numpy.concatenate([[0], numpy.diff(counts[~strides])])
    counts[strides] = 0
    # Get shape of padded counts and slice to return to the original shape
    shape = numpy.array(sort.shape)
    shape[axis] += 1
    shape = shape[transpose]
    slices = [slice(None)] * ndim
    slices[axis] = slice(1, None)
    # Reshape and compute final counts
    counts = counts.reshape(shape).transpose(transpose)[slices] + 1

    # Find maximum counts and return modals/counts
    slices = [slice(None, i) for i in sort.shape]
    del slices[axis]
    index = numpy.ogrid[slices]
    index.insert(axis, numpy.argmax(counts, axis=axis))
    return sort[index], counts[index]


问:
Whats the easiest way to determine if a user is online? (PHP/MYSQL)
Is there a way I can piggy back sessions to know if the user is online?

I.e: use logs on, I set a $_SESSION variable, user times out- cookie Garbage collector updates the database to update their status as offline.

EDIT: I want a solution that does not involve times or dates.  I want something to ride on sessions or something similar.  Guessing if someone is online is not good enough for what I need.

答:
You can also use the onunload tag... On the body
More information here (https://www.w3schools.com/jsref/event_onunload.asp)

This way you don't have to wait 4 -5 minutes for the user to get offline.

But you should still use the ajax update method in-case the user's browser crashes...

Edit:
As @Quentin pointed out in the comments you may not be able to send out requests but there is a way you can do it...
Explained in more detail in this Article.

So basically they are using the sendBeacon()
Here is an Example

window.addEventListener("unload", function logData() {
  navigator.sendBeacon("/log", analyticsData);
});
```

NOTE: Although it should be kept in mind that this should not be the only method you should depend upon, and should implement for redundancy...

Body:
You can also use the onunload tag... On the body
More information here (https://www.w3schools.com/jsref/event_onunload.asp)

This way you don't have to wait 4 -5 minutes for the user to get offline.

But you should still use the ajax update method in-case the user's browser crashes...

Edit:
As @Quentin pointed out in the comments you may not be able to send out requests but there is a way you can do it...
Explained in more detail in this Article.

So basically they are using the sendBeacon()
Here is an Example

window.addEventListener("unload", function logData() {
  navigator.sendBeacon("/log", analyticsData);
});

NOTE: Although it should be kept in mind that this should not be the only method you should depend upon, and should implement for redundancy...


问:
Equivalent laravel relationship query for this join
this is my query

```<code>$personnel_info = \DB::table('assigns AS a')
        ->join('boxes AS b','b.id','=', 'a.box_id')
        ->join('positions AS p','p.id','=', 'b.position_id')
        ->select('a.id','b.id AS box_id','p.id as position_id','p.title','a.status','a.end_date')
        ->where('a.personnel_id','=',$personnel_id)
        ->get();
</code>```

and this realtionship for boxes:

```<code>    class Boxes extends Model
{
    public function position()
    {
        return $this->belongsTo('Positions');
    }

    public function assign()
    {
        return $this->hasOne('Assigns', 'box_id');
    }
}
</code>```

how to use eloquent query(also realtionship) for replace DB facade query?
i want select some field for tables.without define fileds in boxes model
tnx

答:
Try

```<code>$personnel_info = Assign::with('box.position')
->where('personnel_id', $personnel_id)
->get();
</code>```

Then dd($personnel_info) to see everything  that was returned. If you don't like the values, then add your select() clause.

Body:
this is my query

$personnel_info = \DB::table('assigns AS a')
        ->join('boxes AS b','b.id','=', 'a.box_id')
        ->join('positions AS p','p.id','=', 'b.position_id')
        ->select('a.id','b.id AS box_id','p.id as position_id','p.title','a.status','a.end_date')
        ->where('a.personnel_id','=',$personnel_id)
        ->get();

and this realtionship for boxes:

    class Boxes extends Model
{
    public function position()
    {
        return $this->belongsTo('Positions');
    }

    public function assign()
    {
        return $this->hasOne('Assigns', 'box_id');
    }
}

how to use eloquent query(also realtionship) for replace DB facade query?
i want select some field for tables.without define fileds in boxes model
tnx

Body:
Try

$personnel_info = Assign::with('box.position')
->where('personnel_id', $personnel_id)
->get();

Then dd($personnel_info) to see everything  that was returned. If you don't like the values, then add your select() clause.


问: Are

答:
Best place for your script tags is before your closing body tag.

```<code><html>
      <head>
      <title>Example</title>
      </head>
      <body>
            Your Content
      <script type="text/javascript" src="yourScriptHere.js"></script>
      <script type="text/javascript">//Inline scripts etc.</script>
      </body>
</html>
</code>```

That said they can be other places without a problem however the reason you want them at the end is that you want to ensure the page has loaded before execution and you also do not want to stall client download progress making them wait on large scripts.

Title: Are <script>'s not in <head> ok?

Body:
I have had this question niggling at the curious bit of my mind for a while now and I thought I'd ask your collective expertise for an answer to this question.

To elaborate on the title, say I have this:

alert("Some JS outside ");

Outside the  tags of my HTML file. My question is whether it's ok to do this or not, and how much it is used like this.

My instincts tell me it's ok - I reckon browsers look through all HTML for

Body:
Best place for your script tags is before your closing body tag.

<html>
      <head>
      <title>Example</title>
      </head>
      <body>
            Your Content
      <script type="text/javascript" src="yourScriptHere.js"></script>
      <script type="text/javascript">//Inline scripts etc.</script>
      </body>
</html>

That said they can be other places without a problem however the reason you want them at the end is that you want to ensure the page has loaded before execution and you also do not want to stall client download progress making them wait on large scripts.

ContentLicense: CC BY-SA 2.5


问:
How to clickable for markers in google map
I'm using google map and I set markers to my map like this:

```<code>var marker = GMSMarker(position: CLLocationCoordinate2D(latitude: Double(item.lat)!, longitude: Double(item.lon)!))

 marker.map = mapview
</code>```

now,I would like to detect when user click on these markers.

How can I do?

答:
you should set your mapview delegate to self UIViewController in viewDidLoad

```<code>self.mapview.delegate = self
</code>```

your UIViewController should

```<code>extension ViewControllerClass: GMSMapViewDelegate {
    //class code

    @objc(mapView:didTapMarker:) func mapView(_: GMSMapView, didTap marker: GMSMarker) -> Bool {
        //do something
        return true
    }
}
</code>```

maybe this method can be implemented some other way already, but Xcode forced me to make it this way while migrating from Swift 2 to Swift 3

Body:
I'm using google map and I set markers to my map like this:

var marker = GMSMarker(position: CLLocationCoordinate2D(latitude: Double(item.lat)!, longitude: Double(item.lon)!))

 marker.map = mapview

now,I would like to detect when user click on these markers.

How can I do?

Body:
you should set your mapview delegate to self UIViewController in viewDidLoad

self.mapview.delegate = self

your UIViewController should

extension ViewControllerClass: GMSMapViewDelegate {
    //class code

    @objc(mapView:didTapMarker:) func mapView(_: GMSMapView, didTap marker: GMSMarker) -> Bool {
        //do something
        return true
    }
}

maybe this method can be implemented some other way already, but Xcode forced me to make it this way while migrating from Swift 2 to Swift 3


问:
Form Submit 404 Not Found Error
Hi I am currently learning NodeJS and the Express framework, but I am having issue with when I try to submit the form it suppose to go the '/users/register' URL but it seems that my app.js is not finding the register.jade file although I have a register.jade under the view folder. Here is some of my codes:

register.jade:

```<code>extends layout

block content
    h1 Register
    p Please register using the form below
    ul.errors
        if errors
            each error, i in errors
                li.alert.alert-danger #{error.msg}
    form(method='post', action='/users/register', enctype='multipart/form-data') ...
</code>```

user.js:

```<code>router.post('/users/register', function(req, res, next) { ... });
</code>```

app.js:

```<code>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var local = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
...
app.use('/', index);
app.use('/users', users);

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});
</code>```

Error on my Git Bash:

Error from the browser:

Here is my folder structure:

I am not sure why it errors out 404, thank you in advance!

答:
The routes in your users router are relative to the mounted path, you should instead try:

```<code>router.post('/register', function(req, res, next) { ... });
</code>```

Title: Form Submit 404 Not Found Error

Body:
Hi I am currently learning NodeJS and the Express framework, but I am having issue with when I try to submit the form it suppose to go the '/users/register' URL but it seems that my app.js is not finding the register.jade file although I have a register.jade under the view folder. Here is some of my codes:

register.jade:

extends layout

block content
    h1 Register
    p Please register using the form below
    ul.errors
        if errors
            each error, i in errors
                li.alert.alert-danger #{error.msg}
    form(method='post', action='/users/register', enctype='multipart/form-data') ...

user.js:

router.post('/users/register', function(req, res, next) { ... });

app.js:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var local = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
...
app.use('/', index);
app.use('/users', users);

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

Error on my Git Bash:

Error from the browser:

Here is my folder structure:

I am not sure why it errors out 404, thank you in advance!

Body:
The routes in your users router are relative to the mounted path, you should instead try:

router.post('/register', function(req, res, next) { ... });


问:
Magento development learning curve
Our company just launched a new website based on Magento.  Me and my fellow developer have been working on asp.net and would start learning Magento.  Can anyone please explain where to begin.  What are the important points that we need to consider so we can manage and extend the website.  </p>

答:
I would highly recommend this blog for understanding magento. Explained in the best and in-depth way.

magento blog by Alan storm

Title: Magento development learning curve


问:
How to deal with tax in quotation with multi company option?
This question is about how to deal with tax in quotation with multi company option. Please take below scenario:

1) I have enabled multi companies feature and lets say I have 2 comapnies C1, C2.

2) I have two taxes T1(with company C1) and T2(with company C2).

3) I made products P1 with tax T1 and P2 with tax T2.

4) Consider I have set C1 as current company in the user settings.

5) Now, whenever I make Quotation and select both these products then, for P1 it shows tax in order line and for P2 it does not show taxes. It is so because I have set C1 as current company.

6) If i change current company in user settings from C1 to C2 then in the new quotation, now it will show tax for product P2 not for P1. It is so because I have set C2 as current company!!! i have to set the taxes manually for product P1.

How to get rid of this? I want to apply tax on the order line irrespective of the current company.

答:
In Account Tax company field is available and required, when you create sale order line then system will set tax based on login user company.now let say if you select product P2 but if there is not any login user company tax available in product P2 then system will not set any tax in P2 product line.

You need to create two taxes for both company.

Ex : You should create tax T1/T2 for both company, so total there are four taxes in your system.two taxes per company.

In Product you can set multiple taxes.In product P1 you can set tax T1/T2 same in product P2 you can set tax T1/T2.

After that When you login with company C1 and add two products then system will set C1 company tax in both product lines. It will work for another company as well.

This may help you.


问:
Display orders placed before April 1, 2009. Write the query in two different ways
I did it the usual way. I don't get how to write the query in another way.

```<code>SELECT Order#, Shipdate
FROM Orders
WHERE Shipdate < '01-APR-2009';
</code>```

What can be the another way to write the same query?

答:
You could use negation, for logically the same query:

```<code>SELECT Order#, Shipdate
FROM Orders
WHERE NOT Shipdate >= DATE '2009-04-01';
</code>```

Or you could look at the date elements separately:

```<code>SELECT Order#, Shipdate
FROM Orders
WHERE EXTRACT(year FROM Shipdate) < 2009
OR (EXTRACT(year FROM Shipdate) = 2009
  AND EXTRACT(month FROM Shipdate) < 4);
</code>```

though that sort of thing would prevent an index on the date column being used.

Body:
I did it the usual way. I don't get how to write the query in another way.

SELECT Order#, Shipdate
FROM Orders
WHERE Shipdate < '01-APR-2009';

What can be the another way to write the same query?

Body:
You could use negation, for logically the same query:

SELECT Order#, Shipdate
FROM Orders
WHERE NOT Shipdate >= DATE '2009-04-01';

Or you could look at the date elements separately:

SELECT Order#, Shipdate
FROM Orders
WHERE EXTRACT(year FROM Shipdate) < 2009
OR (EXTRACT(year FROM Shipdate) = 2009
  AND EXTRACT(month FROM Shipdate) < 4);

though that sort of thing would prevent an index on the date column being used.


问:
Using Actors to exploit cores
I'm new to Scala in general and Actors in particular and my problem is so basic, the online resources I have found don't cover it.

I have a CPU-intensive, easily parallelized algorithm that will be run on an n-core machine (I don't know n).  How do I implement this in Actors so that all available cores address the problem?

The first way I thought of was to simple break the problem into m pieces (where m is some medium number like 10,000) and create m Actors, one for each piece, give each Actor its little piece and let 'em go.

Somehow, this struck me as inefficient.  Zillions of Actors just hanging around, waiting for some CPU love, pointlessly switching contexts...

Then I thought, make some smaller number of Actors, and feed each one several pieces.  The problem was, there's no reason to expect the pieces are the same size, so one core might get bogged down, with many of its tasks still queued, while other cores are idle.

I noodled around with a Supervisor that knew which Actors were busy, and eventually realized that this has to be a solved problem.  There must be a standard pattern (maybe even a standard library) for dealing with this very generic issue.  Any suggestions?

答:
The upcoming Scala 2.9 is expected to include parallel data structures which should automatically handle this for some uses.  While it does not use Actors, it may be something to consider for your problem.

While this feature was originally slated for 2.8, it has been postponed until the next major release.

A presentation from the last ScalaDays is here:

http://days2010.scala-lang.org/node/138/140

Title: Using Actors to exploit cores


问:
SQLException: No suitable driver found for jdbc:derby://localhost:1527
I get this error in Netbeans:

```<code>java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/
</code>```

How is this caused and how can I solve it?

答:
This error occurs when the syntax of connection string is not valid.

You can use the connection string as

```<code>'jdbc:derby:MyDbTest;create=true'
</code>```

or

you can use the following command in the command prompt, the command below creates a new database called MyDbTest succesfully:

```<code>connect 'jdbc:derby:MyDbTest;create=true';
</code>```

Body:
I get this error in Netbeans:

java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/

How is this caused and how can I solve it?

Body:
This error occurs when the syntax of connection string is not valid.

You can use the connection string as

'jdbc:derby:MyDbTest;create=true'

or

you can use the following command in the command prompt, the command below creates a new database called MyDbTest succesfully:

connect 'jdbc:derby:MyDbTest;create=true';


问:
How to sum all 32-bit or 64-bit sub-registers in an SSE XMM, or AVX YMM, and ZMM register?
Say your task results in a subtotal in each floating-point subregister.  I'm not seeing an instruction that would sum the subtotals down to one floating-point total.  Do I need to store the MM register in plain old memory then do the sum with simple instructions?

(It's unresolved whether these will be double or single-precision, and I plan on coding for every CPU variation up to the forthcoming (?) 512-bit AVX version if I can find the opcodes.)

答:
I have implemented the following inline function for AVX2. It sums all elements and returns the result. You can look this as a suggestion answer to develop your own function for this purpose.

Note: _mm256_extract_epi32 is not presented for AVX you can use your own method with vmovss such as float _mm256_cvtss_f32 (__m256 a) instead and develop your horizontal addition functions.

// my horizontal addition of epi32
inline int _mm256_hadd2_epi32(__m256i a)
{
    __m256i a_hi;
    a_hi = _mm256_permute2x128_si256(a, a, 1); //maybe it should be 4
    a = _mm256_hadd_epi32(a, a_hi);
    a = _mm256_hadd_epi32(a, a);
    a = _mm256_hadd_epi32(a, a);
    return _mm256_extract_epi32(a,0);
}
```


问:
Extracting text from link in python
I have a script in python 2.7 that scrapes the table in this page:
http://www.the-numbers.com/movie/budgets/all

I want to extract each of the columns, the problem is that my code doesn't recognize the columns that have links (2nd and 3rd columns).

```<code>budgeturl = "http://www.the-numbers.com/movie/budgets/all"
s = urllib.urlopen(budgeturl).read()
htmlpage = etree.HTML(s)
htmltable = htmlpage.xpath("//td[@class='data']/text()")
</code>```

With this code htmltable[0] is the rank, htmltable[1] is Production Budget and continues from there onwards.
From the ones I am missing, I need the text not the link.

答:
```<code>import urllib

budgeturl = "http://www.the-numbers.com/movie/budgets/all"
s = urllib.urlopen(budgeturl).read()

def find_between( s, first, last ):
    try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
    except ValueError:
        return ""

s = find_between(s, '<table>', '</table>')

print s[:500]
print '.............................................................'
print s[-250:]
</code>```

Find string between two substrings

returns:

```<code>>>>
<tr><th> </th><th>Release Date</th><th>Movie</th><th>Production Budget</th><th>Domestic Gross</th><th>Worldwide Gross</th></tr>
<tr><td class="data">1</td>
<td><a href="/box-office-chart/daily/2009/12/18">12/18/2009</a></td>
<td><b><a href="/movie/Avatar#tab=summary">Avatar</a></td>
<td class="data">$425,000,000</td>
<td class="data">$760,507,625</td>
<td class="data">$2,783,918,982</td>
<tr>
<tr><td class="data">2</td>
<td><a href="/box-office-chart/daily/2015/12/18">12/18/2015</a></td>
.............................................................
</td>
<td><a href="/box-office-chart/daily/2005/08/05">8/5/2005</a></td>
<td><b><a href="/movie/My-Date-With-Drew#tab=summary">My Date With Drew</a></td>
<td class="data">$1,100</td>
<td class="data">$181,041</td>
<td class="data">$181,041</td>
<tr>
</code>```

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

I need the text not the link.

via http://www.convertcsv.com/html-table-to-csv.htm

```<code>Release Date,Movie,Production Budget,Domestic Gross,Worldwide Gross
1,12/18/2009,Avatar,"$425,000,000","$760,507,625","$2,783,918,982"
8/5/2005,My Date With Drew,"$1,100","$181,041","$181,041"
</code>```

you can use beautifulsoup to do the same, see:

beautifulSoup html csv

Title: Extracting text from link in python

Body:
I have a script in python 2.7 that scrapes the table in this page:
http://www.the-numbers.com/movie/budgets/all

I want to extract each of the columns, the problem is that my code doesn't recognize the columns that have links (2nd and 3rd columns).

budgeturl = "http://www.the-numbers.com/movie/budgets/all"
s = urllib.urlopen(budgeturl).read()
htmlpage = etree.HTML(s)
htmltable = htmlpage.xpath("//td[@class='data']/text()")

With this code htmltable[0] is the rank, htmltable[1] is Production Budget and continues from there onwards.
From the ones I am missing, I need the text not the link.

Body:
import urllib

budgeturl = "http://www.the-numbers.com/movie/budgets/all"
s = urllib.urlopen(budgeturl).read()

def find_between( s, first, last ):
    try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
    except ValueError:
        return ""

s = find_between(s, '<table>', '</table>')

print s[:500]
print '.............................................................'
print s[-250:]

Find string between two substrings

returns:

>>>
<tr><th>&nbsp;</th><th>Release Date</th><th>Movie</th><th>Production Budget</th><th>Domestic Gross</th><th>Worldwide Gross</th></tr>
<tr><td class="data">1</td>
<td><a href="/box-office-chart/daily/2009/12/18">12/18/2009</a></td>
<td><b><a href="/movie/Avatar#tab=summary">Avatar</a></td>
<td class="data">$425,000,000</td>
<td class="data">$760,507,625</td>
<td class="data">$2,783,918,982</td>
<tr>
<tr><td class="data">2</td>
<td><a href="/box-office-chart/daily/2015/12/18">12/18/2015</a></td>
.............................................................
</td>
<td><a href="/box-office-chart/daily/2005/08/05">8/5/2005</a></td>
<td><b><a href="/movie/My-Date-With-Drew#tab=summary">My Date With Drew</a></td>
<td class="data">$1,100</td>
<td class="data">$181,041</td>
<td class="data">$181,041</td>
<tr>

.........................................

I need the text not the link.

via http://www.convertcsv.com/html-table-to-csv.htm

Release Date,Movie,Production Budget,Domestic Gross,Worldwide Gross
1,12/18/2009,Avatar,"$425,000,000","$760,507,625","$2,783,918,982"
8/5/2005,My Date With Drew,"$1,100","$181,041","$181,041"

you can use beautifulsoup to do the same, see:

beautifulSoup html csv


答:
For Swift 3

You can implement GMSMapViewDelegatesomething like this:

```<code>extension YourViewConytoller: GMSMapViewDelegate {
    func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
        print ("MarkerTapped Locations: \(marker.position.latitude), \(marker.position.longitude)")
        return true
    }
}
</code>```

Title: How to clickable for markers in google map

Body:
For Swift 3

You can implement GMSMapViewDelegatesomething like this:

extension YourViewConytoller: GMSMapViewDelegate {
    func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
        print ("MarkerTapped Locations: \(marker.position.latitude), \(marker.position.longitude)")
        return true
    }
}


问:
Delphi: TIdHTTP vs TNetHTTPClient
I'm writing a download manager in Delphi with some custom features like resumable downloads and downloading through proxies.

I'm studing different component solutions: Indy and NetHTTP, both seem very close.

TNetHTTPClient seem to be an interface of winhttp.dll.

TIdHTTP seem to be an interface of wininet.dll (but i'm not sure).

TIdHTTP seems like a very old component (maybe very stable/tested) and has tons of documentation online.

TNetHTTPClient seems to be a very recent component, and doesn't have good documentation online.

I'm a bit undecided... which one to choose?

The point is: what is the main difference between these two components?

My question is a bit disputable (primarily opinion-based), but I haven't found any practical comparison between these two components.

答:
Indy DOES NOT use WinInet/WinHTTP at all. It uses cross-platform BSD/POSIX based socket APIs directly (like WinSock on Windows), implementing Internet protocols (like HTTP) completely from scratch.

TIdHTTP is a manual HTTP implementation.

TNetHTTPClient, on the other hand, wraps system-provided HTTP APIs instead (like WinInet/WinHTTP on Windows).

Title: Delphi: TIdHTTP vs TNetHTTPClient


问:
Testing if an Array is empty JUNIT
I wanna write a Method displaying a deck from a Game.
I initialized an Array with 98 Elements

```<code>private int [] cards = new int[98];
</code>```

I also created a get and a set method

```<code>public int[] getCards() {
    return cards;
}
</code>```

and

```<code>public void setCards(final int... cards) {
    this.cards = cards;
}
</code>```

The Method I wrote is called drawCard. If I use this method it should remove the first element out of the Array and return it.

```<code>public int drawCard() throws IndexOutOfBoundsException {
    if (getCards().length == 0) {
        throw new IndexOutOfBoundsException("No Cards Left!");
    }
    setCards(ArrayUtils.removeElement(getCards(), 0));
    return getCards()[0];
}
</code>```

And then I wrote the JUnit Test.
The test should remove all the 98 elements and then the array should be empty == 0.
But the test always stops at 1.

```<code>@Test
public void testDrawCard() {
    Deck deck = new Deck();
    assertThat(deck.getCards().length).isEqualTo(98);

    for(int x = 98; x >= 0; x--){
        deck.drawCard();
    }
    assertThat(deck.getCards().length).isEqualTo(0);
}
</code>```

Error message:

```<code>java.lang.ArrayIndexOutOfBoundsException: 0
at edu.hm.hafner.java2.thegame.Deck.drawCard(Deck.java:35)
</code>```

35=Return Line

```<code>at edu.hm.hafner.java2.thegame.DeckTest.testDrawCard(DeckTest.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code>```

Does somebody know what's wrong?

答:
```<code>for(int x = 98; x >= 0; x--)
</code>```

This executes the loop while x >= 0.  That is, if we decrement x and it gets the value 0, we execute the loop again because 0 >= 0 is true.  Then, we decrement x and find that it's -1, so the loop stops.  This means that the loop will execute for x = 98, 97, 96, ..., 2, 1, 0.  There are 99 numbers in this list, so the loop executes 99 times.

Since you're not using x at all, there's no reason to have it start at the top and go downward.  If the only purpose is to make sure your loop is executed exactly 98 times, then don't get clever--just use the standard for loop idiom:

```<code>for (int i = 0; i < 98; i++)
</code>```

It doesn't make a difference to the program's execution.  But by sticking to the standard idioms except when necessary, you'll save some brain cells and end up with a lot fewer bugs to figure out.

Title: Testing if an Array is empty JUNIT

Body:
I wanna write a Method displaying a deck from a Game.
I initialized an Array with 98 Elements

private int [] cards = new int[98];

I also created a get and a set method

public int[] getCards() {
    return cards;
}

and

public void setCards(final int... cards) {
    this.cards = cards;
}

The Method I wrote is called drawCard. If I use this method it should remove the first element out of the Array and return it.

public int drawCard() throws IndexOutOfBoundsException {
    if (getCards().length == 0) {
        throw new IndexOutOfBoundsException("No Cards Left!");
    }
    setCards(ArrayUtils.removeElement(getCards(), 0));
    return getCards()[0];
}

And then I wrote the JUnit Test.
The test should remove all the 98 elements and then the array should be empty == 0.
But the test always stops at 1.

@Test
public void testDrawCard() {
    Deck deck = new Deck();
    assertThat(deck.getCards().length).isEqualTo(98);

    for(int x = 98; x >= 0; x--){
        deck.drawCard();
    }
    assertThat(deck.getCards().length).isEqualTo(0);
}

Error message:

java.lang.ArrayIndexOutOfBoundsException: 0
at edu.hm.hafner.java2.thegame.Deck.drawCard(Deck.java:35)

35=Return Line

at edu.hm.hafner.java2.thegame.DeckTest.testDrawCard(DeckTest.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Does somebody know what's wrong?

Body:
for(int x = 98; x >= 0; x--)

This executes the loop while x >= 0.  That is, if we decrement x and it gets the value 0, we execute the loop again because 0 >= 0 is true.  Then, we decrement x and find that it's -1, so the loop stops.  This means that the loop will execute for x = 98, 97, 96, ..., 2, 1, 0.  There are 99 numbers in this list, so the loop executes 99 times.

Since you're not using x at all, there's no reason to have it start at the top and go downward.  If the only purpose is to make sure your loop is executed exactly 98 times, then don't get clever--just use the standard for loop idiom:

for (int i = 0; i < 98; i++)

It doesn't make a difference to the program's execution.  But by sticking to the standard idioms except when necessary, you'll save some brain cells and end up with a lot fewer bugs to figure out.


答:
In the question there is no circle, so my answer doesn't include any circle either.

In order to have some space around the data in the plot, you can use ax.margins(y=ymargin), where ymargin is the percentage of space to add on each side of the data. I.e. if data goes from 0 to 1 and you add ymargin = 0.1 of margin, the ylimits will be (-0.1, 1.1). (This is independent on whether or not one limit would be zero or not.)

Now, by default this does not work for a bar plot, as it would in the general case be undesireable to have the bars start somewhere in the air, as opposed to the bottom axis. This behaviour is steered using a flag called use_sticky_edges. We can set this flag to False to get back the behaviour of margins being applied to both ends of the axis. For taking effect, we need to call ax.autoscale_view afterwards.

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

values = np.array([3.89, 3.76, 3.55, 3.28, 2.95, 2.72, 2.46, 2.28, 2.13, 2.03, 1.84,
                   1.62, 1.48, 1.28, 1.12, 0.93, 0.79, 0.66, 0.58, 0.52, 0.56, 0.72,
                   0.87, 1.09, 1.24, 1.37, 1.44, 1.35, 1.22, 1.13, 1.09, 1.02, 1.01,
                   1.02, 1.05, 1.02, 1.01, 0.89, 0.78, 0.75, 0.67, 0.59, 0.66, 0.74,
                   0.65, 0.60, 0.58, 0.50, 0.28, 0.36])

fig, ax = plt.subplots()
ax.bar(np.arange(values.shape[0]), values)

ax.margins(y=0.3)
ax.use_sticky_edges = False
ax.autoscale_view(scaley=True)
plt.show()
</code>```

Title: Matplotlib margins

Body:
Look at the chart below. In this chart, I want to draw to circle with the centre coordinates at (45, 0). But, as you see, bottom limit of chart is zero and half of my circle is not shown. So, I need to extend this chart to the bottom a little bit. "Margins" method of axes (ax.margins()) doesn't work, since bottom line of this chart is zero and zero multiplied by any number is equal to zero.

Note: Please, do not post replies like ax.set_ylim(...) or ax.set_yticks(...). I am looking for a general solution for this like problems.

Code
import matplotlib.pyplot as plt
import numpy as np

values = np.array([0.00388632352941, 0.00375827941176, 0.00355033823529,     0.00328273529412, 0.00294677941176, 0.00272142647059, 0.00246463235294,     0.00227766176471, 0.00213151470588, 0.00202594117647, 0.00183544117647,     0.00162102941177, 0.00148372058824, 0.00128380882353, 0.00112252941176,     0.000931544117647, 0.000786573529412, 0.000658220588235, 0.000584485294118,     0.000524044117647, 0.000562485294118, 0.000716441176471, 0.000872617647059,     0.00109039705882, 0.00124138235294, 0.00136894117647, 0.00143985294118,     0.00134760294118, 0.00121794117647, 0.00112772058824, 0.00109435294118,     0.00102432352941, 0.00101069117647, 0.00102417647059, 0.00104895588235,     0.00101776470588, 0.00101494117647, 0.000885558823529, 0.00078075,     0.000752647058824, 0.000667691176471, 0.000593220588236, 0.000658647058823,     0.000742117647059, 0.000651470588235, 0.000604647058824, 0.000584573529412,     0.00049530882353, 0.000281235294118, 0.000355029411765])
fig, ax = plt.subplots()
ax.bar(np.arange(values.shape[0]), values)
plt.show()

Body:
In the question there is no circle, so my answer doesn't include any circle either.

In order to have some space around the data in the plot, you can use ax.margins(y=ymargin), where ymargin is the percentage of space to add on each side of the data. I.e. if data goes from 0 to 1 and you add ymargin = 0.1 of margin, the ylimits will be (-0.1, 1.1). (This is independent on whether or not one limit would be zero or not.)

Now, by default this does not work for a bar plot, as it would in the general case be undesireable to have the bars start somewhere in the air, as opposed to the bottom axis. This behaviour is steered using a flag called use_sticky_edges. We can set this flag to False to get back the behaviour of margins being applied to both ends of the axis. For taking effect, we need to call ax.autoscale_view afterwards.

import matplotlib.pyplot as plt
import numpy as np

values = np.array([3.89, 3.76, 3.55, 3.28, 2.95, 2.72, 2.46, 2.28, 2.13, 2.03, 1.84,
                   1.62, 1.48, 1.28, 1.12, 0.93, 0.79, 0.66, 0.58, 0.52, 0.56, 0.72,
                   0.87, 1.09, 1.24, 1.37, 1.44, 1.35, 1.22, 1.13, 1.09, 1.02, 1.01,
                   1.02, 1.05, 1.02, 1.01, 0.89, 0.78, 0.75, 0.67, 0.59, 0.66, 0.74,
                   0.65, 0.60, 0.58, 0.50, 0.28, 0.36])

fig, ax = plt.subplots()
ax.bar(np.arange(values.shape[0]), values)

ax.margins(y=0.3)
ax.use_sticky_edges = False
ax.autoscale_view(scaley=True)
plt.show()


问:
In Odoo how to force overwriting of a record rule which is defined in a base module and data is set to noupdate='1'?
The following record rule is defined in product module

<data noupdate="1">
    <record id="product_comp_rule" model="ir.rule">
        <field name="name" >Product multi-company</field>
        <field name="model_id" ref="model_product_template"/>
        <field name="global" eval="True"/>
        <field name="domain_force"> ['|',('company_id','=',user.company_id.id),('company_id','=',False)]</field>
    </record>
</data>
```

<p>I want to edit it in my custom module to be</p>

<pre class="lang-xml prettyprint-override"><code><record id="product.product_comp_rule" model="ir.rule">
    <field name="name" >All Products (Parent Company)</field>
    <field name="model_id" ref="product.model_product_template"/>
    <field name="global" eval="True"/>
    <field name="domain_force">['|','|',('company_id','=',user.company_id.id),('company_id','=','False'),('company_id','child_of',[user.company_id.id])] </field>
</record>
</code>```

答:
You can use :

<function name="fix_er_role" model="ir.rule"/>
```
<p>After that add the method to ir.rule and fix your data</p>
<pre class="lang-py prettyprint-override"><code>class IRRule(models.Model):
    _inherit = 'ir.rule'

    def fix_er_role(self):
         rol_id = self.env.ref('product.product_comp_rule')
         rol_id = self.env['ir.rule'].search([('id','=',rol_id)])
         rol_id.write({'domain_force':['|','|',('company_id','=',user.company_id.id),('company_id','=','False'),('company_id','child_of',[user.company_id.id])]})
</code>```

Edit : an other good solution for this requirement.

    <function name="write" model="ir.model.data">

        <function name="search" model="ir.model.data">
            <value
              eval="[('module', '=', 'product'), ('name', '=', 'product_comp_rule')]"
              />
        </function>

        <value eval="{'noupdate': False}" />
    </function>

    <record id="product.product_comp_rule" model="ir.rule">
        <field name="name" >All Products (Parent Company)</field>
        <field name="model_id" ref="product.model_product_template"/>
        <field name="global" eval="True"/>
        <field name="domain_force">['|','|',('company_id','=',user.company_id.id),('company_id','=','False'),('company_id','child_of',[user.company_id.id])] </field>
    </record>

    <function name="write" model="ir.model.data">
        <function name="search" model="ir.model.data">
            <value
              eval="[('module', '=', 'product'), ('name', '=', 'product_comp_rule')]"
              />
        </function>
        <value eval="{'noupdate': True}" />
    </function>
```

Body:
The following record rule is defined in product module

<data noupdate="1">
    <record id="product_comp_rule" model="ir.rule">
        <field name="name" >Product multi-company</field>
        <field name="model_id" ref="model_product_template"/>
        <field name="global" eval="True"/>
        <field name="domain_force"> ['|',('company_id','=',user.company_id.id),('company_id','=',False)]</field>
    </record>
</data>

I want to edit it in my custom module to be

<record id="product.product_comp_rule" model="ir.rule">
    <field name="name" >All Products (Parent Company)</field>
    <field name="model_id" ref="product.model_product_template"/>
    <field name="global" eval="True"/>
    <field name="domain_force">['|','|',('company_id','=',user.company_id.id),('company_id','=','False'),('company_id','child_of',[user.company_id.id])] </field>
</record>

Body:
You can use :

<function name="fix_er_role" model="ir.rule"/>

After that add the method to ir.rule and fix your data

class IRRule(models.Model):
    _inherit = 'ir.rule'

    def fix_er_role(self):
         rol_id = self.env.ref('product.product_comp_rule')
         rol_id = self.env['ir.rule'].search([('id','=',rol_id)])
         rol_id.write({'domain_force':['|','|',('company_id','=',user.company_id.id),('company_id','=','False'),('company_id','child_of',[user.company_id.id])]})

Edit : an other good solution for this requirement.

    <function name="write" model="ir.model.data">
         <!-- get the record if from data base -->
        <function name="search" model="ir.model.data">
            <value
              eval="[('module', '=', 'product'), ('name', '=', 'product_comp_rule')]"
              />
        </function>
       <!-- remove noupdate -->
        <value eval="{'noupdate': False}" />
    </function>

    <record id="product.product_comp_rule" model="ir.rule">
        <field name="name" >All Products (Parent Company)</field>
        <field name="model_id" ref="product.model_product_template"/>
        <field name="global" eval="True"/>
        <field name="domain_force">['|','|',('company_id','=',user.company_id.id),('company_id','=','False'),('company_id','child_of',[user.company_id.id])] </field>
    </record>

    <!-- reset noupdate -->
    <function name="write" model="ir.model.data">
        <function name="search" model="ir.model.data">
            <value
              eval="[('module', '=', 'product'), ('name', '=', 'product_comp_rule')]"
              />
        </function>
        <value eval="{'noupdate': True}" />
    </function>


问:
What causes different behaviors in Chrome - IE and Firefox in this very simple Java app running on Tomcat?
I have a very simple Java web application running on Tomcat 8.5.4. Here are my dependencies in pom.xml

```<code><dependencies>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
</code>```

And web.xml is as follows..

```<code><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
</web-app>
</code>```

and all I have is 2 Servlets:

UTF16.java

```<code>@WebServlet(urlPatterns = "/utf16")
public class UTF16 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-16");
        resp.setContentType("text/html");

        final PrintWriter writer = resp.getWriter();
        writer.print("<!doctype html>\n" +
                     "<html lang=\"en\">\n" +
                     "<head>\n" +
                         "<meta charset=\"utf-16\"/>");
        writer.print("</head>\n");
        writer.print("<body>");
        writer.print('\u20ac'); // This is the unicode code point for the Euro sign.
        writer.print("<body>");
        writer.print("</html>");
        writer.flush();
    }
}
</code>```

and UTF32.java looks very similar..

```<code>@WebServlet(urlPatterns = "/utf32")
public class UTF32 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-32");
        resp.setContentType("text/html");

        final PrintWriter writer = resp.getWriter();
        writer.print("<!doctype html>\n" +
                     "<html lang=\"en\">\n" +
                     "<head>\n" +
                         "<meta charset=\"utf-32\"/>");
        writer.print("</head>\n");
        writer.print("<body>");
        writer.print('\u20ac'); // This is the unicode code point for the Euro sign.
        writer.print("<body>");
        writer.print("</html>");
        writer.flush();
    }
}
</code>```

This is what I get in Chrome for urls /utf16 and /utf32 respectivly..

Now try Internet Explorer (v11.0.96... something..)

For /utf16

For /utf32

What?

Firefox will return the same result with Chrome for /utf16 and same result for /utf32 with Internet Explorer.

What is going on?

In case related, this is what a simple HTTP Headers capture plugin will capture:

```<code>HTTP/1.1 200
Content-Type: text/html;charset=UTF-16
Transfer-Encoding: chunked
Date: Sat, 01 Apr 2017 12:57:48 GMT
</code>```

Why is Internet Explorer showing me some Chinese text for /utf16 and does not parse the HTML for /utf32 and shows it as just plain text?

A small edit..
I tried with Jetty to make sure the issue is not related to Tomcat, and all outputs are same on all browsers.

答:
Internet Explorer had some problems with encodings before. Microsoft provides some workarounds, try them:

To resolve this issue, use one of the following methods:

Disable the Auto-Select setting in Internet Explorer.

Provide the character set in the HTTP headers.

Move the META tag to within the first kilobyte of data that is parsed by MSHTML. Although we do not know how much data the parser reads at a time, this location will resolve the issue.

Increase the size of the server's initial HTTP response. The initial size should be at least 1 KB.

Make sure that the System Locale setting matches the character set of the META tag that is specified in the HTML page.

Also your <meta charset="utf-16"/> is the HTML5 way. I couldn't check anywhere if it's supported by IE11 or not, but using the old <meta http-equiv=Content-Type content="text/html; charset=utf-16"> declaration may be also worth a try.

Body:
I have a very simple Java web application running on Tomcat 8.5.4. Here are my dependencies in pom.xml

<dependencies>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

And web.xml is as follows..

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
</web-app>

and all I have is 2 Servlets:

UTF16.java

@WebServlet(urlPatterns = "/utf16")
public class UTF16 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-16");
        resp.setContentType("text/html");

        final PrintWriter writer = resp.getWriter();
        writer.print("<!doctype html>\n" +
                     "\n" +
                     "\n" +
                         "<meta charset=\"utf-16\"/>");
        writer.print("\n");
        writer.print("");
        writer.print('\u20ac'); // This is the unicode code point for the Euro sign.
        writer.print("");
        writer.print("");
        writer.flush();
    }
}

and UTF32.java looks very similar..

@WebServlet(urlPatterns = "/utf32")
public class UTF32 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-32");
        resp.setContentType("text/html");

        final PrintWriter writer = resp.getWriter();
        writer.print("<!doctype html>\n" +
                     "\n" +
                     "\n" +
                         "<meta charset=\"utf-32\"/>");
        writer.print("\n");
        writer.print("");
        writer.print('\u20ac'); // This is the unicode code point for the Euro sign.
        writer.print("");
        writer.print("");
        writer.flush();
    }
}

This is what I get in Chrome for urls /utf16 and /utf32 respectivly..

Now try Internet Explorer (v11.0.96... something..)

For /utf16

For /utf32

What?

Firefox will return the same result with Chrome for /utf16 and same result for /utf32 with Internet Explorer.

What is going on?

In case related, this is what a simple HTTP Headers capture plugin will capture:

HTTP/1.1 200
Content-Type: text/html;charset=UTF-16
Transfer-Encoding: chunked
Date: Sat, 01 Apr 2017 12:57:48 GMT

Why is Internet Explorer showing me some Chinese text for /utf16 and does not parse the HTML for /utf32 and shows it as just plain text?

A small edit..
I tried with Jetty to make sure the issue is not related to Tomcat, and all outputs are same on all browsers.


问:
Get a HTML5 video to play once on page load and then fade out
I am trying to get a HTML5 clip to play only once on first arrival/pageload to the home page and then not play again. Also I would like the video to fadeout and disappear after it's played. I know you can do this with JQuery once and fadeout, but I'm a beginner and I am struggling with the syntax. Can a more experienced coder help me adjust my code so this works please? Here's what I have so far!

```<code><!DOCTYPE html>
<html>
<head>
<script src="jquery-3.2.0.min.js"></script>
<script>
$(document).ready(function(){
$("#video").one("load", function(){
$('#video').get(0).play()
});

</script>

</head>
<body>

<h2>This is a website</h2>

<video id="video">
<source src="clip.mp4" type="video/mp4">

Your browser does not support HTML5 video.
</video>
</body>
</html>
</code>```

答:
I resolved this in a different way:

index.html is the video clip, after the video is ended I used this code below to make the video disappear and move onto the home page which is home.html

```<code><meta http-equiv="Refresh" content="9;url=home.html"
</code>```

Included in index.html are 2 javascript if statements, to redirect immediately to home.html if the screen width is less than 600 pixels, because mobile phones won't autoplay videos. 2 similar if statements were used to ensure the if statements worked in as many browsers as possible. Below are the if statements used:

```<code><script type="text/javascript">
<!--
if (screen.width <= 600) {
window.location = "home.html";
}
//-->
</script>
<script type="text/javascript">
<!--
if (window.innerWidth <= 600) {
document.location = "home.html";
}
//-->
</script>
</code>```

Originally I asked the question because I wanted the video to play only once per entire visit to the website and keep the video in the same html page as the home page, rather than a different page as I have now. Jquery one would not have achieved this, as that would have made the video play once per page load, not once per website visit. However other methods like session cookies or javascript session storage could have kept this video feature in the same page. But this solution resolved the issue well and simply so I used that method.

To further improve this, I added an event listener on to only move onto the next page when the video was ended, not at 9 seconds like this:

```<code><meta http-equiv="Refresh" content="9;url=home.html"
</code>```

but only when ended (incase the browser is slow to load and 9 seconds is not enough)

```<code><script>
video=document.getElementById('myvid').addEventListener('ended',function(){
window.location.href='home.html';
});
</script>
</code>```

The Javascript above assumes the video has an id="myvid"

Body:
I am trying to get a HTML5 clip to play only once on first arrival/pageload to the home page and then not play again. Also I would like the video to fadeout and disappear after it's played. I know you can do this with JQuery once and fadeout, but I'm a beginner and I am struggling with the syntax. Can a more experienced coder help me adjust my code so this works please? Here's what I have so far!

<!DOCTYPE html>

This is a website

<video id="video">
<source src="clip.mp4" type="video/mp4">

Your browser does not support HTML5 video.
</video>

Body:
I resolved this in a different way:

index.html is the video clip, after the video is ended I used this code below to make the video disappear and move onto the home page which is home.html

<meta http-equiv="Refresh" content="9;url=home.html"

Included in index.html are 2 javascript if statements, to redirect immediately to home.html if the screen width is less than 600 pixels, because mobile phones won't autoplay videos. 2 similar if statements were used to ensure the if statements worked in as many browsers as possible. Below are the if statements used:

<script type="text/javascript">
<!--
if (screen.width <= 600) {
window.location = "home.html";
}
//-->
</script>
<script type="text/javascript">
<!--
if (window.innerWidth <= 600) {
document.location = "home.html";
}
//-->
</script>

Originally I asked the question because I wanted the video to play only once per entire visit to the website and keep the video in the same html page as the home page, rather than a different page as I have now. Jquery one would not have achieved this, as that would have made the video play once per page load, not once per website visit. However other methods like session cookies or javascript session storage could have kept this video feature in the same page. But this solution resolved the issue well and simply so I used that method.

To further improve this, I added an event listener on to only move onto the next page when the video was ended, not at 9 seconds like this:

<meta http-equiv="Refresh" content="9;url=home.html"

but only when ended (incase the browser is slow to load and 9 seconds is not enough)

<script>
video=document.getElementById('myvid').addEventListener('ended',function(){
window.location.href='home.html';
});
</script>

The Javascript above assumes the video has an id="myvid"


问:
i m trying to redirect one JSP page to another along with the input text value
Page1.JSP

```<code>//input text box
Enter Form id:<input type="text" name="formID" id="formID" >
<a href='Page2.jsp?formID=<%=request.getParameter("formID")%>' value="View Form" name="displayForm">Show Form</a>
</code>```

This returns a null value. In page2. JSP

```<code>//get the input value
<%String formsubmitID=request.getParameter("formID");%>
</code>```

This returns null. I am not able to parse. I tried all the methods using window.location, adding a button adding a href link but i am not able to access the input text field and redirect both at the same time. Here is the code for first JSP Page from which I need to redirect to another JSP Page with the input text field entered at Firest JSP Page.

I tried using a button and redirect in Java script

```<code>//javascript for redirecting to another page
function redirect(elem){
  alert("in redirect Method:")
  elem.setAttribute("action","Page2.jsp");
  elem.submit();
  return false;
}
// Page1.JSP
<form ACTION="Page2.jsp" METHOD="POST" onload='onload()'>
  Enter Form id:<input type="text" name="formID" id="formID"/>
  <INPUT TYPE="SUBMIT" value="Submit" onclick="redirect(this);">
</form>
</code>```

This also doesn't work. Redirect doesn't happen at all when I am using window.location.href or window.location.

Please help me find the solution for the same.

答:
When you are using form than whenever you click on button you will be directed to Page2.jsp (i.e. url mentioned in form action) like

```<code><form ACTION="Page2.jsp">
Enter Form id:<input type="text" name="formID" id="formID"/>
<INPUT TYPE="SUBMIT" value="Submit">
</form>
</code>```

In Page2.jsp get value of text field like

```<code><%String formsubmitID=request.getParameter("formID");%>
</code>```

Body:
Page1.JSP

//input text box
Enter Form id:<input type="text" name="formID" id="formID" >
<a href='Page2.jsp?formID=<%=request.getParameter("formID")%>' value="View Form" name="displayForm">Show Form

This returns a null value. In page2. JSP

//get the input value
<%String formsubmitID=request.getParameter("formID");%>

This returns null. I am not able to parse. I tried all the methods using window.location, adding a button adding a href link but i am not able to access the input text field and redirect both at the same time. Here is the code for first JSP Page from which I need to redirect to another JSP Page with the input text field entered at Firest JSP Page.

I tried using a button and redirect in Java script

//javascript for redirecting to another page
function redirect(elem){
  alert("in redirect Method:")
  elem.setAttribute("action","Page2.jsp");
  elem.submit();
  return false;
}
// Page1.JSP
<form ACTION="Page2.jsp" METHOD="POST" onload='onload()'>
  Enter Form id:<input type="text" name="formID" id="formID"/>
  <INPUT TYPE="SUBMIT" value="Submit" onclick="redirect(this);">
</form>

This also doesn't work. Redirect doesn't happen at all when I am using window.location.href or window.location.

Please help me find the solution for the same.

Body:
When you are using form than whenever you click on button you will be directed to Page2.jsp (i.e. url mentioned in form action) like

<form ACTION="Page2.jsp">
Enter Form id:<input type="text" name="formID" id="formID"/>
<INPUT TYPE="SUBMIT" value="Submit">
</form>

In Page2.jsp get value of text field like

<%String formsubmitID=request.getParameter("formID");%>


问:
Matplotlib histogram title
I'm trying to call a variable in a function of matplotlib, but it gives me an error. Maybe it's not possible.

```<code>sigma = float(some number)
ax1.hist(population)
ax1.set_title('blah   N = 241', 'standard deviation =',sigma)
</code>```

It returns the error:

```<code>AttributeError: 'str' object has no attribute 'pop'
</code>```

or

```<code>AttributeError: 'int' object has no attribute 'pop'
</code>```

答:
ax.set_title() requires that the title is one character string. You must collect all string fragments into one string before passing them to the set_title function:

```<code>ax1.set_title('blah   N = 241' + 'standard deviation =' + str(sigma))
</code>```

Title: Matplotlib histogram title

Body:
I'm trying to call a variable in a function of matplotlib, but it gives me an error. Maybe it's not possible.

sigma = float(some number)
ax1.hist(population)
ax1.set_title('blah   N = 241', 'standard deviation =',sigma)

It returns the error:

AttributeError: 'str' object has no attribute 'pop'

or

AttributeError: 'int' object has no attribute 'pop'

Body:
ax.set_title() requires that the title is one character string. You must collect all string fragments into one string before passing them to the set_title function:

ax1.set_title('blah   N = 241' + 'standard deviation =' + str(sigma))


问:
Where to define C++ class member template function and functors that instantiate it?
I have a class Foo which is used in a small standalone project. It has a class definition in Foo.h with the implementation for the class' member functions in an implementation file Foo.cpp.

First question - one of the member functions of class Foo is a template method Foo::doSomething(), is it correct that the implementation of this method should appear with the declaration of the function in Foo.h ?

The template parameter which Foo::doSomething() will be instantiated with is one of two Functor types - class CalcA and CalcB.

Should I:

(A) put the defintion and implementation of the two Functor classes all together in Foo.cpp (where they are actually used by the implementation of other Foo member functions to call Foo::doSomething).

(B) put the definition and implementation of the two Functor classes in Foo.h.

(C) should I put split the definition and implementation of the two Functors across Foo.h and Foo.cpp as would be done with an ordinary class?

答:
My default would be to put the definition for the member function templates right in the .h file, like this:

```<code>class Foo
{
public:
  template<typename T> void DoSomething(T t);
};

// ... later...

template<typename T>
void Foo::DoSomething(T t)
{
  // ...
}
</code>```

If this is suboptimal for a particular case, then I'd take more heroic measures.  Starting with #include-ing a .inc file with the definition at the end of the .h file, or possibly even doing explicit instantiations in the .cpp files where I needed the member function templates to be used.

Body:
My default would be to put the definition for the member function templates right in the .h file, like this:

class Foo
{
public:
  template<typename T> void DoSomething(T t);
};

// ... later...

template<typename T>
void Foo::DoSomething(T t)
{
  // ...
}

If this is suboptimal for a particular case, then I'd take more heroic measures.  Starting with #include-ing a .inc file with the definition at the end of the .h file, or possibly even doing explicit instantiations in the .cpp files where I needed the member function templates to be used.


问:
Best way to check if value in dictionary of lists?
So I have a dictionary of lists like so:

```<code>dct = {'1': ['hello','goodbye'], '2': ['not here','definitely not here']}
</code>```

What's the fastest way to check if 'hello' is in one of my lists in my dictionary

答:
As Willem Van Onsem commented, the easiest way to achieve this is:

```<code>any('hello' in val for val in dct.values())
</code>```

any returns True if any of the values in the given iterable are truthy.

dct.values() returns a dict_values iterable that yields all the values in a dictionary.

'hello' in val for val in dct.values() is a generator expression that yields True for each value of dct that 'hello' is in.

If you want to know the keys the string is in, you can do:

```<code>keys = [key for key, value in dct.items() if 'hello' in value]
</code>```

In your case, keys will be ['1']. If you do this anyways, you can then just call use that list in a boolean context, e.g. if keys: ....

Body:
So I have a dictionary of lists like so:

dct = {'1': ['hello','goodbye'], '2': ['not here','definitely not here']}

What's the fastest way to check if 'hello' is in one of my lists in my dictionary

Body:
As Willem Van Onsem commented, the easiest way to achieve this is:

any('hello' in val for val in dct.values())

any returns True if any of the values in the given iterable are truthy.

dct.values() returns a dict_values iterable that yields all the values in a dictionary.

'hello' in val for val in dct.values() is a generator expression that yields True for each value of dct that 'hello' is in.

If you want to know the keys the string is in, you can do:

keys = [key for key, value in dct.items() if 'hello' in value]

In your case, keys will be ['1']. If you do this anyways, you can then just call use that list in a boolean context, e.g. if keys: ....


问:
JavaScript loop through to check duplicate value
I am having troubles trying to check if the date exists in the array.

```<code> for(var i = 0; i< crisislist.length; i++){
        hazecounter = 1;
        if(crisislist[i].category == 1){
            if(crisislist[i].date != crisislist[i+1].date) {
                hazelabel.push(crisislist[i].date);
            }else{
                hazecounter++;
            }
            hazedata.push(hazecounter);
        }
 }
</code>```

The sample data for the date is:

```<code>["01-02-2017", "22-03-2017", "22-03-2017", "07-08-2017"]
</code>```

And the expected output for hazelabel, hazedata should be:

hazelabel: ["01-02-2017", "22-03-2017", "07-08-2017"]
   hazedata: [1,2,1]

With the code above, when I check until the last element in the array and trying to make a comparison, it throw me an error message:

```<code>Uncaught TypeError: Cannot read property 'date' of undefined
</code>```

I think this is because when I reach the last element of array, and I try to find crisislist[I+1].date, it could not found and thus the error message.

Any idea how to fix this? Thanks in advance!

答:
You just need to check till second last :</p>

```<code>for(var i = 0; i< (crisislist.length-1); i++){
        hazecounter = 1;
        if(crisislist[i].category == 1){
            if(crisislist[i].date != crisislist[i+1].date) {
                hazelabel.push(crisislist[i].date);
                if (crisislist.length-2 == i)
                {
                    hazelabel.push(crisislist[i+1].date);
                }
            }else{
                hazecounter++;
            }
            hazedata.push(hazecounter);
        }
 }
</code>```

Body:
I am having troubles trying to check if the date exists in the array.

 for(var i = 0; i< crisislist.length; i++){
        hazecounter = 1;
        if(crisislist[i].category == 1){
            if(crisislist[i].date != crisislist[i+1].date) {
                hazelabel.push(crisislist[i].date);
            }else{
                hazecounter++;
            }
            hazedata.push(hazecounter);
        }
 }

The sample data for the date is:

["01-02-2017", "22-03-2017", "22-03-2017", "07-08-2017"]

And the expected output for hazelabel, hazedata should be:

hazelabel: ["01-02-2017", "22-03-2017", "07-08-2017"]
   hazedata: [1,2,1]

With the code above, when I check until the last element in the array and trying to make a comparison, it throw me an error message:

Uncaught TypeError: Cannot read property 'date' of undefined

I think this is because when I reach the last element of array, and I try to find crisislist[I+1].date, it could not found and thus the error message.

Any idea how to fix this? Thanks in advance!

Body:
You just need to check till second last :

for(var i = 0; i< (crisislist.length-1); i++){
        hazecounter = 1;
        if(crisislist[i].category == 1){
            if(crisislist[i].date != crisislist[i+1].date) {
                hazelabel.push(crisislist[i].date);
                if (crisislist.length-2 == i)
                {
                    hazelabel.push(crisislist[i+1].date);
                }
            }else{
                hazecounter++;
            }
            hazedata.push(hazecounter);
        }
 }


问:
Get all possible english words from a string
Generate all possible combination of english words from a given string in python.

Input: godaddy
Output: go, god, dad, add, daddy

Any good libraries?

答:
You can use nltk.corpus.words to create a set of all English words, then  find the intersection of all possible words generated from your string with the English words:

```<code>In [56]: all_words = {st[i:j + i] for j in range(2, len(st)) for i in range(len(st)- j + 1)}

In [57]: english_vocab = set(w.lower() for w in nltk.corpus.words.words())

In [58]: english_vocab.intersection(all_words)
Out[58]: {'ad', 'add', 'addy', 'da', 'dad', 'daddy', 'go', 'god', 'od', 'oda'}
</code>```

Note that the words like OD or oda are valid abbreviations.

Body:
You can use nltk.corpus.words to create a set of all English words, then  find the intersection of all possible words generated from your string with the English words:

In [56]: all_words = {st[i:j + i] for j in range(2, len(st)) for i in range(len(st)- j + 1)}

In [57]: english_vocab = set(w.lower() for w in nltk.corpus.words.words())

In [58]: english_vocab.intersection(all_words)
Out[58]: {'ad', 'add', 'addy', 'da', 'dad', 'daddy', 'go', 'god', 'od', 'oda'}

Note that the words like OD or oda are valid abbreviations.


答:
The documentation for set_title shows that it doesn't work the same way as print. You've provided three arguments, and the second is supposed to be a dict (which can be pop-ed). Since you've passed a string, that won't work.

Try this:

```<code>sigma = float(some number)
ax1.hist(population)
title = 'blah   N = 241, ' + 'standard deviation =' + str(sigma)
ax1.set_title(title)
</code>```

Title: Matplotlib histogram title

Body:
The documentation for set_title shows that it doesn't work the same way as print. You've provided three arguments, and the second is supposed to be a dict (which can be pop-ed). Since you've passed a string, that won't work.

Try this:

sigma = float(some number)
ax1.hist(population)
title = 'blah   N = 241, ' + 'standard deviation =' + str(sigma)
ax1.set_title(title)


问:
SQL Server: Help optimize my query
C# programmer here and I've been tasked to edit a lengthy SQL Server procedure in one of our legacy applications that needs to be as performance minded and efficient running as possible. I would appreciate some confirmation if my route is the best to take for the scenario at hand.

SCENARIO

It's an unorthodox one due to the design both code and DB wise by the original designers. For a search grid, I need to see if a "warranty doc" has been generated or not in the tbl.docs based on the option the user selects and the concatenation value of the string/word "Warranty" and the tbl.warranty.warrantyId value itself.

This value of 'Warranty' + tbl.warranty.warrantyId equals the tbl.docs.name column value and unfortunately appears my only way to join/link the two tables.

Warranty docs can be generated multiple times per warranty.

Parameter @IsGenerated is the user option the end-user will select to engage the filtering or not.

Here's some populated data for illustration:

tbl.warranty:

```<code>| warrantyId | name        | createdDate             |
|------------|-------------|-------------------------|
| 456        | Warranty 1  | 2002-04-01 12:14:53.330 |
| 1000       | Warranty 2  | 2002-04-01 12:14:53.327 |
| 1701       | Warranty 3  | 2002-04-01 12:14:53.333 |
| 2456       | Warranty 4  | 2002-04-01 12:14:53.327 |
| 3556       | Warranty 5  | 2002-04-01 12:14:53.330 |
</code>```

tbl.docs:

```<code>| docId      | name         | createdDate             |
|------------|--------------|-------------------------|
| 1          | Warranty1000 | 2006-11-25 13:33:31.093 |
| 2          | Warranty456  | 2015-02-11 13:33:31.100 |
| 3          | Warranty1000 | 2012-05-17 13:33:31.097 |
| 4          | Warranty1000 | 2017-01-11 13:33:31.097 |
| 5          | Warranty1701 | 2017-03-14 13:33:31.100 |
| 6          | Warranty456  | 2017-03-15 13:33:31.100 |
</code>```

So you can see:

warrantyId 1000 has been generated three times

warrantyId 456 has been generated twice

warranties with warrantyIds 3556 and 2456 have not been generated at all, so on...

DESIRED ACTION(s)/RESULT(s)

User can choose not to select any filter options, [I need to display all the warranty records and the time generated (tbl.docs.createdDate), but return with a null tbl.docs.createdDate (generateddate if you will) if it hasn't ever been requested to generate, or the MOST RECENT record based on max tbl.docs.createdDate (generatedDate) if it has]

```<code> | warrantyId | name         | generatedDate           |
 |------------|--------------|-------------------------|
 | 456        | Warranty 1   | 2017-03-15 13:33:31.100 |
 | 1000       | Warranty 2   | 2017-01-11 13:33:31.097 |
 | 1701       | Warranty 3   | 2017-03-14 13:33:31.100 |
 | 2456       | Warranty 4   | NULL                    |
 | 3556       | Warranty 5   | NULL                    |
</code>```

User can filter on warranties that docs HAVE been generated for, [I need to display all the warranty records that have a doc generated record based on the string/word "Warranty" and the warrantyId equaling the docs.name value.  Warranties that have multiple docs generated, I need ONLY the most recent time generated record]

```<code> | warrantyId | name         | generatedDate           |
 |------------|--------------|-------------------------|
 | 456        | Warranty 1   | 2017-03-15 13:33:31.100 |
 | 1000       | Warranty 2   | 2017-01-11 13:33:31.097 |
 | 1701       | Warranty 3   | 2017-03-14 13:33:31.100 |
</code>```

User can filter on warranties that docs HAVEN'T been generated for, [I need to display all the warranty records that haven't had a doc generated record based on the string/word "Warranty" and the warrantyId equaling docs.name]

```<code> | warrantyId | name         | generatedDate           |
 |------------|--------------|-------------------------|
 | 2456       | Warranty 4   | NULL                    |
 | 3556       | Warranty 5   | NULL                    |
</code>```

This is my stab at it. I figured creating a temp table based off the docs table and using that in my query is the best route for efficiency and not bogging this query down anymore than what already is.

```<code>IF OBJECT_ID('tempdb..#tmpDocs') IS NOT NULL
    DROP TABLE #tmpDocs
GO

CREATE TABLE #tmpDocs
(
    createdDate datetime not null,
    name varchar(30) not null
)

INSERT INTO #tmpDocs (createdDate, name)
    SELECT createdDate, name
    FROM docs

DECLARE @IsGenerated BIT
SET @IsGenerated = 0

SELECT
    w.warrantyId,
    w.name,
    (SELECT TOP 1 d.createdDate
     FROM #tmpDocs d
     WHERE d.name = CONCAT('Warranty', w.warrantyId)
     ORDER BY d.createdDate DESC) AS [generatedDate]
FROM
    warranty w
WHERE
    (@IsGenerated IS NULL OR @IsGenerated = 0
     OR EXISTS (SELECT *
                FROM #tmpDocs d
                WHERE d.name = CONCAT('Warranty', w.warrantyId)))
                  AND (@IsGenerated IS NULL OR @IsGenerated = 1 OR
                       NOT EXISTS (SELECT *
                                   FROM #tmpDocs d
                                   WHERE d.name = CONCAT('Warranty', w.warrantyId)
                      )
               )
      )
</code>```

EDITED -- ATTEMPT #2

```<code>select
    w.warrantyId,
    w.name,
    d.createdDate as [generatedDate]
from warranty w
left join #tmpDocs d
    on d.name = concat('Warranty', w.warrantyId)
    AND d.createdDate = (SELECT  top 1  d.createdDate
                      FROM     #tmpDocs d
                      WHERE d.name = CONCAT('Warranty', w.warrantyId)
                      ORDER BY d.createdDate desc)
WHERE
    (@IsGenerated IS NULL OR @IsGenerated = 0
     OR EXISTS (SELECT *
                FROM #tmpDocs d
                WHERE d.name = CONCAT('Warranty', w.warrantyId))
    )
    AND (@IsGenerated IS NULL OR @IsGenerated = 1
    OR NOT EXISTS (SELECT *
                    FROM #tmpDocs d
                    WHERE d.name = CONCAT('Warranty', w.warrantyId)
        )
    )
group by w.warrantyId, d.createdDate, w.name
</code>```

The execution times are the same though, I'm guessing because my small dataset I'm working with:

(5 row(s) affected)

SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

(5 row(s) affected)

SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

Thanks so much for reading this and etc.  If there's an alternative route (not using CTE because this is only one simple aspect of the proc i'll be editing, I don't have the time to refactor the whole thing at the time), I'd be very open to hearing it.  The execution of this procedure cannot afford to get bogged down.

答:
This is definitely not optimal. If you have any power, best solution would be to update the doc table and add the warranty id as a separate column, same datatype as the warranty id of the warranty table. If that's not an option another solution would be to break out both queries (one for docs, and one for warranties) and have the application generate the IN clause to contain the doc names.

As for the filtering that would be better handled in the application code.

The following query will get you what you need, though not too sure on the performance without actually being able to run the query against the db myself.

```<code>SELECT
    w.warrantyId,
    MAX(w.name) as name,
    MAX(d.createdDate) as generatedDate
FROM warranty w
LEFT JOIN docs d on d.Name = CONCAT('Warranty', w.warrantyId)
GROUP BY w.warrantyId
</code>```

Title: SQL Server: Help optimize my query

Body:
C# programmer here and I've been tasked to edit a lengthy SQL Server procedure in one of our legacy applications that needs to be as performance minded and efficient running as possible. I would appreciate some confirmation if my route is the best to take for the scenario at hand.

SCENARIO

It's an unorthodox one due to the design both code and DB wise by the original designers. For a search grid, I need to see if a "warranty doc" has been generated or not in the tbl.docs based on the option the user selects and the concatenation value of the string/word "Warranty" and the tbl.warranty.warrantyId value itself.

This value of 'Warranty' + tbl.warranty.warrantyId equals the tbl.docs.name column value and unfortunately appears my only way to join/link the two tables.

Warranty docs can be generated multiple times per warranty.

Parameter @IsGenerated is the user option the end-user will select to engage the filtering or not.

Here's some populated data for illustration:

tbl.warranty:

| warrantyId | name        | createdDate             |
|------------|-------------|-------------------------|
| 456        | Warranty 1  | 2002-04-01 12:14:53.330 |
| 1000       | Warranty 2  | 2002-04-01 12:14:53.327 |
| 1701       | Warranty 3  | 2002-04-01 12:14:53.333 |
| 2456       | Warranty 4  | 2002-04-01 12:14:53.327 |
| 3556       | Warranty 5  | 2002-04-01 12:14:53.330 |

tbl.docs:

| docId      | name         | createdDate             |
|------------|--------------|-------------------------|
| 1          | Warranty1000 | 2006-11-25 13:33:31.093 |
| 2          | Warranty456  | 2015-02-11 13:33:31.100 |
| 3          | Warranty1000 | 2012-05-17 13:33:31.097 |
| 4          | Warranty1000 | 2017-01-11 13:33:31.097 |
| 5          | Warranty1701 | 2017-03-14 13:33:31.100 |
| 6          | Warranty456  | 2017-03-15 13:33:31.100 |

So you can see:

warrantyId 1000 has been generated three times

warrantyId 456 has been generated twice

warranties with warrantyIds 3556 and 2456 have not been generated at all, so on...

DESIRED ACTION(s)/RESULT(s)

User can choose not to select any filter options, [I need to display all the warranty records and the time generated (tbl.docs.createdDate), but return with a null tbl.docs.createdDate (generateddate if you will) if it hasn't ever been requested to generate, or the MOST RECENT record based on max tbl.docs.createdDate (generatedDate) if it has]

 | warrantyId | name         | generatedDate           |
 |------------|--------------|-------------------------|
 | 456        | Warranty 1   | 2017-03-15 13:33:31.100 |
 | 1000       | Warranty 2   | 2017-01-11 13:33:31.097 |
 | 1701       | Warranty 3   | 2017-03-14 13:33:31.100 |
 | 2456       | Warranty 4   | NULL                    |
 | 3556       | Warranty 5   | NULL                    |

User can filter on warranties that docs HAVE been generated for, [I need to display all the warranty records that have a doc generated record based on the string/word "Warranty" and the warrantyId equaling the docs.name value.  Warranties that have multiple docs generated, I need ONLY the most recent time generated record]

 | warrantyId | name         | generatedDate           |
 |------------|--------------|-------------------------|
 | 456        | Warranty 1   | 2017-03-15 13:33:31.100 |
 | 1000       | Warranty 2   | 2017-01-11 13:33:31.097 |
 | 1701       | Warranty 3   | 2017-03-14 13:33:31.100 |

User can filter on warranties that docs HAVEN'T been generated for, [I need to display all the warranty records that haven't had a doc generated record based on the string/word "Warranty" and the warrantyId equaling docs.name]

 | warrantyId | name         | generatedDate           |
 |------------|--------------|-------------------------|
 | 2456       | Warranty 4   | NULL                    |
 | 3556       | Warranty 5   | NULL                    |

This is my stab at it. I figured creating a temp table based off the docs table and using that in my query is the best route for efficiency and not bogging this query down anymore than what already is.

IF OBJECT_ID('tempdb..#tmpDocs') IS NOT NULL
    DROP TABLE #tmpDocs
GO

CREATE TABLE #tmpDocs
(
    createdDate datetime not null,
    name varchar(30) not null
)

INSERT INTO #tmpDocs (createdDate, name)
    SELECT createdDate, name
    FROM docs

DECLARE @IsGenerated BIT
SET @IsGenerated = 0

SELECT
    w.warrantyId,
    w.name,
    (SELECT TOP 1 d.createdDate
     FROM #tmpDocs d
     WHERE d.name = CONCAT('Warranty', w.warrantyId)
     ORDER BY d.createdDate DESC) AS [generatedDate]
FROM
    warranty w
WHERE
    (@IsGenerated IS NULL OR @IsGenerated = 0
     OR EXISTS (SELECT *
                FROM #tmpDocs d
                WHERE d.name = CONCAT('Warranty', w.warrantyId)))
                  AND (@IsGenerated IS NULL OR @IsGenerated = 1 OR
                       NOT EXISTS (SELECT *
                                   FROM #tmpDocs d
                                   WHERE d.name = CONCAT('Warranty', w.warrantyId)
                      )
               )
      )

EDITED -- ATTEMPT #2

select
    w.warrantyId,
    w.name,
    d.createdDate as [generatedDate]
from warranty w
left join #tmpDocs d
    on d.name = concat('Warranty', w.warrantyId)
    AND d.createdDate = (SELECT  top 1  d.createdDate
                      FROM     #tmpDocs d
                      WHERE d.name = CONCAT('Warranty', w.warrantyId)
                      ORDER BY d.createdDate desc)
WHERE
    (@IsGenerated IS NULL OR @IsGenerated = 0
     OR EXISTS (SELECT *
                FROM #tmpDocs d
                WHERE d.name = CONCAT('Warranty', w.warrantyId))
    )
    AND (@IsGenerated IS NULL OR @IsGenerated = 1
    OR NOT EXISTS (SELECT *
                    FROM #tmpDocs d
                    WHERE d.name = CONCAT('Warranty', w.warrantyId)
        )
    )
group by w.warrantyId, d.createdDate, w.name

The execution times are the same though, I'm guessing because my small dataset I'm working with:

(5 row(s) affected)

SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

(5 row(s) affected)

SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

Thanks so much for reading this and etc.  If there's an alternative route (not using CTE because this is only one simple aspect of the proc i'll be editing, I don't have the time to refactor the whole thing at the time), I'd be very open to hearing it.  The execution of this procedure cannot afford to get bogged down.

Body:
This is definitely not optimal. If you have any power, best solution would be to update the doc table and add the warranty id as a separate column, same datatype as the warranty id of the warranty table. If that's not an option another solution would be to break out both queries (one for docs, and one for warranties) and have the application generate the IN clause to contain the doc names.

As for the filtering that would be better handled in the application code.

The following query will get you what you need, though not too sure on the performance without actually being able to run the query against the db myself.

SELECT
    w.warrantyId,
    MAX(w.name) as name,
    MAX(d.createdDate) as generatedDate
FROM warranty w
LEFT JOIN docs d on d.Name = CONCAT('Warranty', w.warrantyId)
GROUP BY w.warrantyId