问:
How to display all Java compiler warnings in a project using Netbeans?
Coming from Visual Studio and Eclipse, How to find out all the compiler warnings such as unused variables for whole project. It seems like a trivial thing but can't find it. I can find out all errors in "Action Items" window but not all warnings. </p>

答:
The question was how to display warnings in NetBeans which I don't believe is possible. However, to get all warning messages you can compile the program using the command line with the flag -Xlint.

Example:

```<code>javac -Xlint programName.java
</code>```

This will list all the warnings.

Body:
The question was how to display warnings in NetBeans which I don't believe is possible. However, to get all warning messages you can compile the program using the command line with the flag -Xlint.

Example:

javac -Xlint programName.java

This will list all the warnings.


来源: stackexchange

问:
Calculate using dplyr, percentage of NA'S in each column
I have a data frame with some columns  with missing values. Is there a way (using dplyr) to efficiently calculate the percentage of each column that is missing i.e. NA. Sought of like a colSum equivalent. So I dont have to calculate each column percentage missing individually ?</p>

答:
Loving the concision of purrr::map for this type of thing:

x %>% map(~ mean(is.na(.)))

ContentLicense: CC BY-SA 3.0


问:
The Console.logs of an Electron app runned by gulp are not shown
I'm starting to work with gulp. I have electron app that is invoked by a gulp process. The thing is that I wan't to be able to see the console.logs of the main.js process into the console where the gulp command was executed.

I'm able to see the console.logs of all the render processes in the dev tools.

My gulpfile is:

```<code>var gulp = require('gulp'),
  browserify = require('gulp-browserify'),
  concatCss = require('gulp-concat-css'),
  run = require('gulp-run');

var src = './process',
  app = './app';

gulp.task('js', function () {
  return gulp.src(src + '/js/render.js')
    .pipe(browserify({
      transform: 'reactify',
      extensions: 'browserify-css',
      debug: true
    }))
    .on('error', function (err) {
      console.error('Error!', err.message);
    })
    .pipe(gulp.dest(app + '/js'));
});

gulp.task('html', function () {
  gulp.src(src + '/**/*.html');
});

gulp.task('css', function () {
  gulp.src(src + '/css/*.css')
    .pipe(concatCss('app.css'))
    .pipe(gulp.dest(app + '/css'));
});

gulp.task('fonts', function () {
  gulp.src('node_modules/bootstrap/dist/fonts/**/*')
    .pipe(gulp.dest(app + '/fonts'));
});

gulp.task('watch', ['serve'], function () {
  gulp.watch(src + '/js/**/*', ['js']);
  gulp.watch(src + '/css/**/*.css', ['css']);
  gulp.watch([app + '/**/*.html'], ['html']);
});

gulp.task('serve', ['html', 'js', 'css'], function () {
  run('electron app/main.js').exec();
});

gulp.task('default', ['watch', 'fonts', 'serve']);
</code>```

Any idea of what to do?

答:
The verbosity option for gulp-run could be what you are looking for. It defaults to 2, which means that the output from electron just gets buffered and printed after you quit the app. Setting it to 3 should print your console.logs as soon as they come in.

```<code>gulp.task('serve', ['html', 'js', 'css'], function () {
    run('electron app/main.js', {verbosity: 3}).exec();
});
</code>```

Body:
I'm starting to work with gulp. I have electron app that is invoked by a gulp process. The thing is that I wan't to be able to see the console.logs of the main.js process into the console where the gulp command was executed.

I'm able to see the console.logs of all the render processes in the dev tools.

My gulpfile is:

var gulp = require('gulp'),
  browserify = require('gulp-browserify'),
  concatCss = require('gulp-concat-css'),
  run = require('gulp-run');

var src = './process',
  app = './app';

gulp.task('js', function () {
  return gulp.src(src + '/js/render.js')
    .pipe(browserify({
      transform: 'reactify',
      extensions: 'browserify-css',
      debug: true
    }))
    .on('error', function (err) {
      console.error('Error!', err.message);
    })
    .pipe(gulp.dest(app + '/js'));
});

gulp.task('html', function () {
  gulp.src(src + '/**/*.html');
});

gulp.task('css', function () {
  gulp.src(src + '/css/*.css')
    .pipe(concatCss('app.css'))
    .pipe(gulp.dest(app + '/css'));
});

gulp.task('fonts', function () {
  gulp.src('node_modules/bootstrap/dist/fonts/**/*')
    .pipe(gulp.dest(app + '/fonts'));
});

gulp.task('watch', ['serve'], function () {
  gulp.watch(src + '/js/**/*', ['js']);
  gulp.watch(src + '/css/**/*.css', ['css']);
  gulp.watch([app + '/**/*.html'], ['html']);
});

gulp.task('serve', ['html', 'js', 'css'], function () {
  run('electron app/main.js').exec();
});

gulp.task('default', ['watch', 'fonts', 'serve']);

Any idea of what to do?

Body:
The verbosity option for gulp-run could be what you are looking for. It defaults to 2, which means that the output from electron just gets buffered and printed after you quit the app. Setting it to 3 should print your console.logs as soon as they come in.

gulp.task('serve', ['html', 'js', 'css'], function () {
    run('electron app/main.js', {verbosity: 3}).exec();
});


问:
averaging by months with daily data
I have daily data with my matrix, divided into 6 columns -  "Years, months, days, ssts, anoms, missing ".

I want to calculate the average of each month of SST in each year. (For example - 1981 - september - avg values sts of all days in sept), and I want to do the same for all the years. i am trying to work, my code, but am unable to do so.

答:
In terms of data.table you can perform the following action

```<code>library(data.table)
dt[, average_sst := mean(SSTs), by = .(years,months)]
</code>```

adding an extra column average_sst.

Title: averaging by months with daily data

Body:
In terms of data.table you can perform the following action

library(data.table)
dt[, average_sst := mean(SSTs), by = .(years,months)]

adding an extra column average_sst.


问:
Is using COUNT(*) or SELECT * a good idea?
I've heard several times that you shouldn't perform COUNT(*) or SELECT * for performance reasons, but wasn't able to dig up some further information about it.

I can imagine that the database is then using all columns for the action, which can be an impressive performance loss, but I'm not sure about that. Does somebody have further information about the topic?

答:
1. On count(*) vs. count(something else)

SQL is declarative in that you specify what you want. This is different from specifying how to get what you want. That means the database engine is free to realize your query in whatever way it thinks is the most efficient. Many database optimizers rewrites your query to a less costly alternative (if such a plan is available).

Given the following table:

```<code>table(
   pk       not null
  ,color    not null
  ,nullable null
  ,unique(pk)
  ,index(color)
);
</code>```

...all of the following are functionally equivalent (due to the mechanics of count and nulls):

```<code>1) select count(*) from table;
2) select count(1) from table;
3) select count(pk) from table;
4) select count(color) from table;
</code>```

Regardless of which form you use, the optimizer is free to rewrite the query to another form if it is more efficient. (Again, not all optimizers are sophisticated enough to do this). The unique index(pk) would be smaller (bytes occupied) than the entire table. Therefore it would be more efficient to count the number of index entries rather than scanning through the entire table. In Oracle we have bitmap indexes, which also compress repeating strings. If we had used such an index on the color column, it would probably have been the smallest index to scan. Oracle also supports table compression which in some cases makes the physical table smaller than a composite index.

1. TL;DR;
Your specific dbms will have its own set of tools that enables different rewriting rules and in turn execution plans. That renders the question somewhat useless (unless we talk about a specific release of a specific dbms). I recommend COUNT(*) in all cases because it requires the least cognitive effort to grasp.

2. On select a,b,c vs. select *

There are very few valid uses of SELECT * in code you write and put into production. Imagine a table which contains Bluray movies (yes, the movies is stored as a blob in this table). So you slapped together your awesomesauce abstraction layer and put SELECT * FROM movies where id = ? in the getMovies(movie_id) method. I will refrain myself from explaining why SELECT name FROM movies will be transported across the network just a tad faster. Of course, in most realistic cases it won't have a noticable impact.

One last point on performance is that when all the referenced columns (selected, filtered) in your query exists as an index (called a covering index), the database need not touch the table at all. It can be fully resolved from scanning the index only. By selecting all columns you remove this option from the optimizer.

Another thing about SELECT * which is far more serious than anything, is that it creates an implicit dependency on a specific physical layout of the table. Let me explain. Consider the following tables:

```<code>table T1(name, id)
table T2(name, id)
</code>```

The following statement...

```<code>insert into t1 select * from t2;
</code>```

... will break or produce a different result if any of the following happens:

Any of the tables columns are rearranged for example T1(id, name)

T1 gets an additional not-null column

T2 gets another column

2. TL;DR; When possible, explicitly specify the columns you want (eventually, you'll have to do that anyway). Also, selecting fewer columns are faster than selecting more columns. A possitive side-effect on explicit selects is that it gives greater freedom to the optimizer.

Body:
1. On count(*) vs. count(something else)

SQL is declarative in that you specify what you want. This is different from specifying how to get what you want. That means the database engine is free to realize your query in whatever way it thinks is the most efficient. Many database optimizers rewrites your query to a less costly alternative (if such a plan is available).

Given the following table:

table(
   pk       not null
  ,color    not null
  ,nullable null
  ,unique(pk)
  ,index(color)
);

...all of the following are functionally equivalent (due to the mechanics of count and nulls):

1) select count(*) from table;
2) select count(1) from table;
3) select count(pk) from table;
4) select count(color) from table;

Regardless of which form you use, the optimizer is free to rewrite the query to another form if it is more efficient. (Again, not all optimizers are sophisticated enough to do this). The unique index(pk) would be smaller (bytes occupied) than the entire table. Therefore it would be more efficient to count the number of index entries rather than scanning through the entire table. In Oracle we have bitmap indexes, which also compress repeating strings. If we had used such an index on the color column, it would probably have been the smallest index to scan. Oracle also supports table compression which in some cases makes the physical table smaller than a composite index.

1. TL;DR;
Your specific dbms will have its own set of tools that enables different rewriting rules and in turn execution plans. That renders the question somewhat useless (unless we talk about a specific release of a specific dbms). I recommend COUNT(*) in all cases because it requires the least cognitive effort to grasp.

2. On select a,b,c vs. select *

There are very few valid uses of SELECT * in code you write and put into production. Imagine a table which contains Bluray movies (yes, the movies is stored as a blob in this table). So you slapped together your awesomesauce abstraction layer and put SELECT * FROM movies where id = ? in the getMovies(movie_id) method. I will refrain myself from explaining why SELECT name FROM movies will be transported across the network just a tad faster. Of course, in most realistic cases it won't have a noticable impact.

One last point on performance is that when all the referenced columns (selected, filtered) in your query exists as an index (called a covering index), the database need not touch the table at all. It can be fully resolved from scanning the index only. By selecting all columns you remove this option from the optimizer.

Another thing about SELECT * which is far more serious than anything, is that it creates an implicit dependency on a specific physical layout of the table. Let me explain. Consider the following tables:

table T1(name, id)
table T2(name, id)

The following statement...

insert into t1 select * from t2;

... will break or produce a different result if any of the following happens:

Any of the tables columns are rearranged for example T1(id, name)

T1 gets an additional not-null column

T2 gets another column

2. TL;DR; When possible, explicitly specify the columns you want (eventually, you'll have to do that anyway). Also, selecting fewer columns are faster than selecting more columns. A possitive side-effect on explicit selects is that it gives greater freedom to the optimizer.


问:
std::list::erase(iter) exception handling c++
I try to get an iterator from a function and then erase an element from a list.

Is there any way to catch that exception?

Is there any way to know if the iterator is valid?

When I run the program with invalid iterator it throws the following exception:

```<code> Exception thrown: read access violation.
 _Right.**_Myproxy** was 0xCCCCCCCC. occurred
</code>```

My func is:

```<code>list<AccountStruct>::const_iterator SearchAccount(list<AccountStruct>& Acc,string p)
{

    for (list<AccountStruct>::const_iterator j = Acc.begin(); j !=Acc.end(); ++j)
    {
        if ((*j).phone == p) return j;
    }

}

void RemoveAccount(list<AccountStruct>& Acc)
{
    string Phone;
    cout << "Enter Phone Number ->" << endl;
    cin >> Phone;
    //cout << "Searching..." << endl;
    list<AccountStruct>::const_iterator iter = SearchAccount(Acc,Phone);
    try
    {
        Acc.erase(iter);
    }
    catch()// <- What to put inside??
    {
        cout << "No Phone Number;" << endl;
    }

}
</code>```

答:
We can fix this with a couple changes.  First, SearchAccount doesn't return anything if the function does not find an object.  This is undefined behavior, as you must return something when you say you will.  We can fix this by returning end() if the item is not found like find does.  That gives you

```<code>list<AccountStruct>::const_iterator SearchAccount(list<AccountStruct>& Acc,string p)
{
    for (list<AccountStruct>::const_iterator j = Acc.begin(); j !=Acc.end(); ++j)
    {
        if ((*j).phone == p) return j;
    }
    return Acc.end(); // item not found
}
</code>```

Now that SearchAccount functions properly we can then check to see if end() is returned instead of using the exception mechanism.  That look like

```<code>void RemoveAccount(list<AccountStruct>& Acc)
{
    string Phone;
    cout << "Enter Phone Number ->" << endl;
    cin >> Phone;
    //cout << "Searching..." << endl;
    list<AccountStruct>::const_iterator iter = SearchAccount(Acc,Phone);
    if (iter != Acc.end())
    {
        Acc.erase(iter);
    }
    else
    {
        cout << "No Phone Number;" << endl;
    }
}
</code>```

And now you don't have the overhead of the exception mechanism and the "right thing" happens.

Body:
I try to get an iterator from a function and then erase an element from a list.

Is there any way to catch that exception?

Is there any way to know if the iterator is valid?

When I run the program with invalid iterator it throws the following exception:

 Exception thrown: read access violation.
 _Right.**_Myproxy** was 0xCCCCCCCC. occurred

My func is:

list<AccountStruct>::const_iterator SearchAccount(list<AccountStruct>& Acc,string p)
{

    for (list<AccountStruct>::const_iterator j = Acc.begin(); j !=Acc.end(); ++j)
    {
        if ((*j).phone == p) return j;
    }

}

void RemoveAccount(list<AccountStruct>& Acc)
{
    string Phone;
    cout << "Enter Phone Number ->" << endl;
    cin >> Phone;
    //cout << "Searching..." << endl;
    list<AccountStruct>::const_iterator iter = SearchAccount(Acc,Phone);
    try
    {
        Acc.erase(iter);
    }
    catch()// <- What to put inside??
    {
        cout << "No Phone Number;" << endl;
    }

}

Body:
We can fix this with a couple changes.  First, SearchAccount doesn't return anything if the function does not find an object.  This is undefined behavior, as you must return something when you say you will.  We can fix this by returning end() if the item is not found like find does.  That gives you

list<AccountStruct>::const_iterator SearchAccount(list<AccountStruct>& Acc,string p)
{
    for (list<AccountStruct>::const_iterator j = Acc.begin(); j !=Acc.end(); ++j)
    {
        if ((*j).phone == p) return j;
    }
    return Acc.end(); // item not found
}

Now that SearchAccount functions properly we can then check to see if end() is returned instead of using the exception mechanism.  That look like

void RemoveAccount(list<AccountStruct>& Acc)
{
    string Phone;
    cout << "Enter Phone Number ->" << endl;
    cin >> Phone;
    //cout << "Searching..." << endl;
    list<AccountStruct>::const_iterator iter = SearchAccount(Acc,Phone);
    if (iter != Acc.end())
    {
        Acc.erase(iter);
    }
    else
    {
        cout << "No Phone Number;" << endl;
    }
}

And now you don't have the overhead of the exception mechanism and the "right thing" happens.


问:
Does Resharper have more rules than SonarLint?
Jetbrains brags on their website that Resharper 2016.3 has over two thousand more rules than Visual Studio 2015. But how does Resharper 2016.3 compare to SonarLint? (a popular plugin for Visual Studio 2015)</p>

答: Yes, ReSharper has more rules. However, the covered cases might not show such big difference than the advertised numbers. For example SonarLint S2971 covers many cases. In ReSharper each of these are considered individual rules.</p>


问:
Guice bind a class and its adapter
I would like implement a Guice module which binds an adapter to a named argument, but to create this adapter, it needs to instantiate another class, which also need injected arguments.

Here is the example in Scala:

```<code>trait Service

class UserService @Inject()(@Named(value = "foo") foo: String) extends Service

trait Adapter

class AdapterImpl(service: Service) extends Adapter

class AdapterRef(val adapter: Adapter)

class Module extends AbstractModule {
  override def configure(): Unit = {
    val fooValue = "bar"

    bind(classOf[String])
      .annotatedWith(Names.named("foo"))
      .toInstance(fooValue)

    val userService = new UserService(fooValue)     //It should be instantiated by Guice somehow

    bind(classOf[AdapterRef])
      .annotatedWith(Names.named("userService"))
      .toInstance(new AdapterRef(new AdapterImpl(userService)))   //Thats kinda ok
  }
}
</code>```

Can someone point me to the right direction?

Thank you,

Gabor

答:
You can use a Provides method within your module, which lets you remove the binding. This is my best effort at Scala so if the syntax is incorrect let me know.

```<code>@Provides() @Singleton() def provideAdapterRef(service: Service): AdapterRef = {
    return new AdapterRef(new AdapterImpl(service))
}
</code>```

Note the use of Singleton to imitate your examples use of toInstance. If you don't need it to always provide the same instance I would recommend removing the scope and letting it create a new one every time.

An alternative solution is to use a Provider. This requires you to keep a modified version of the binding in your module and create an extra class, but it can be a cleaner solution if your Provider is more complex.

```<code>//Can inject UserService as well, or provide annotations to configure which
//implementation of Service you get if you have more than one.
class UserServiceProvider @Inject()(service: Service) extends Provider[AdapterRef] {
    override def get(): AdapterRef {
        return new AdapterRef(new AdapterImpl(service))
    }
}
</code>```

Then you can change your binding in the module to

```<code>bind(classOf[AdapterRef])
  .annotatedWith(Names.named("userService"))
  .toProvider(classOf[UserServiceProvider])
  .in(classOf[Singleton])
</code>```

Here note the use of in(Singleton) to replicate your toInstance behavior.

Title: Guice bind a class and its adapter

Body:
I would like implement a Guice module which binds an adapter to a named argument, but to create this adapter, it needs to instantiate another class, which also need injected arguments.

Here is the example in Scala:

trait Service

class UserService @Inject()(@Named(value = "foo") foo: String) extends Service

trait Adapter

class AdapterImpl(service: Service) extends Adapter

class AdapterRef(val adapter: Adapter)

class Module extends AbstractModule {
  override def configure(): Unit = {
    val fooValue = "bar"

    bind(classOf[String])
      .annotatedWith(Names.named("foo"))
      .toInstance(fooValue)

    val userService = new UserService(fooValue)     //It should be instantiated by Guice somehow

    bind(classOf[AdapterRef])
      .annotatedWith(Names.named("userService"))
      .toInstance(new AdapterRef(new AdapterImpl(userService)))   //Thats kinda ok
  }
}

Can someone point me to the right direction?

Thank you,

Gabor

Body:
You can use a Provides method within your module, which lets you remove the binding. This is my best effort at Scala so if the syntax is incorrect let me know.

@Provides() @Singleton() def provideAdapterRef(service: Service): AdapterRef = {
    return new AdapterRef(new AdapterImpl(service))
}

Note the use of Singleton to imitate your examples use of toInstance. If you don't need it to always provide the same instance I would recommend removing the scope and letting it create a new one every time.

An alternative solution is to use a Provider. This requires you to keep a modified version of the binding in your module and create an extra class, but it can be a cleaner solution if your Provider is more complex.

//Can inject UserService as well, or provide annotations to configure which
//implementation of Service you get if you have more than one.
class UserServiceProvider @Inject()(service: Service) extends Provider[AdapterRef] {
    override def get(): AdapterRef {
        return new AdapterRef(new AdapterImpl(service))
    }
}

Then you can change your binding in the module to

bind(classOf[AdapterRef])
  .annotatedWith(Names.named("userService"))
  .toProvider(classOf[UserServiceProvider])
  .in(classOf[Singleton])

Here note the use of in(Singleton) to replicate your toInstance behavior.


问:
find -type d and ls return different results on same directory
I'm trying to think of a reason find would return partial results on Ubuntu 16.04. I have a google drive mount (using plexdrive) located at
    /home/user/media

When using

```<code>find $HOME/media -type d
</code>```

16 results are returned. When using

```<code>ls -d $HOME/media/*/
</code>```

186 results are returned. The folders are all browsable via sftp and samba shares, all permissions on relevant directories are 775. The content in the media directory is formatted as

```<code>a/a.ext
b/b.ext
c/c.ext
</code>```

Has anyone seen this type of behavior before or have any clues on how to get find to return the full results?

答: This happens when find is looking at a directory with symbolic links. Use the -L flag to see the proper folder structure. find -L $HOME/media -type d

Body:
I'm trying to think of a reason find would return partial results on Ubuntu 16.04. I have a google drive mount (using plexdrive) located at
    /home/user/media

When using

find $HOME/media -type d

16 results are returned. When using

ls -d $HOME/media/*/

186 results are returned. The folders are all browsable via sftp and samba shares, all permissions on relevant directories are 775. The content in the media directory is formatted as

a/a.ext
b/b.ext
c/c.ext

Has anyone seen this type of behavior before or have any clues on how to get find to return the full results?


问:
plotting density map per km2 pr year
i have a csv file containing data of 6 years ( date, longitude, latitude,value ) i plotted the density map using histogramm2d and contourf per km ,i got a beautiful map, but i believe that i plotted the density per km per 6year, so i need to take into take consideration the criteria of knowing how many years do i have in the file and plot the density per km per year and not per 6 years.
 so here's the code i am using to achieve this :

```<code>with open('flash.csv') as f:
reader = csv.reader(f)
next(reader) # Ignore the header row.
lonMin, lonMax, dLon = -20.0, 5.0, 5
latMin, latMax, dLat = 18.0, 40.0, 5
for row in reader:
    lat = float(row[2])
    lon = float(row[3])
    # filter lat,lons to (approximate) map view:
    if lonMin <= lon <= lonMax and latMin <= lat <= latMax:
        lats.append( lat )
        lons.append( lon )

m = Basemap(llcrnrlon=min(lons), llcrnrlat=min(lats), urcrnrlon=max(lons), urcrnrlat=max(lats), projection='merc', resolution='f')

numcols = (max(lons)-min(lons)) * 100
numrows = (max(lats)-min(lats)) * 100

db = 1
lon_bins = np.linspace(min(lons)-db, max(lons)+db, numcols)
lat_bins = np.linspace(min(lats)-db, max(lats)+db, numrows)
h, xedges, yedges = (np.histogram2d(lats, lons,[lat_bins, lon_bins]))
xi, yi= m(*np.meshgrid(lon_bins, lat_bins))

#shape into continuous matrice
g = np.zeros(xi.shape)
g[:-1,:-1] = h
g[-1] = g[0]      # copy the top row to the bottom
g[:,-1] = g[:,0]  # copy the left column to the right
print g.shape,yi.shape,xi.shape

m.drawcoastlines()
m.drawstates()

g[g==0.0] = np.nan
cs = m.contourf(xi, yi, g)
cbar = plt.colorbar(cs, orientation='horizontal')
cbar.set_label('la densite des impacts foudre',size=18)

plt.gcf().set_size_inches(15,15)
plt.show()
</code>```

Any ideas ??

答:
I just found the solution of my question, i did this to obtain the number of the years i have in the csv file ,i divided the calculated density into NByears and it's working perfectly.</p>

```<code>DateMax = data.index.year.max()
DateMin = data.index.year.min()
NByears = (DateMax - DateMin)
</code>```

Title: plotting density map per km2 pr year

Body:
i have a csv file containing data of 6 years ( date, longitude, latitude,value ) i plotted the density map using histogramm2d and contourf per km ,i got a beautiful map, but i believe that i plotted the density per km per 6year, so i need to take into take consideration the criteria of knowing how many years do i have in the file and plot the density per km per year and not per 6 years.
 so here's the code i am using to achieve this :

with open('flash.csv') as f:
reader = csv.reader(f)
next(reader) # Ignore the header row.
lonMin, lonMax, dLon = -20.0, 5.0, 5
latMin, latMax, dLat = 18.0, 40.0, 5
for row in reader:
    lat = float(row[2])
    lon = float(row[3])
    # filter lat,lons to (approximate) map view:
    if lonMin <= lon <= lonMax and latMin <= lat <= latMax:
        lats.append( lat )
        lons.append( lon )

m = Basemap(llcrnrlon=min(lons), llcrnrlat=min(lats), urcrnrlon=max(lons), urcrnrlat=max(lats), projection='merc', resolution='f')

numcols = (max(lons)-min(lons)) * 100
numrows = (max(lats)-min(lats)) * 100

db = 1
lon_bins = np.linspace(min(lons)-db, max(lons)+db, numcols)
lat_bins = np.linspace(min(lats)-db, max(lats)+db, numrows)
h, xedges, yedges = (np.histogram2d(lats, lons,[lat_bins, lon_bins]))
xi, yi= m(*np.meshgrid(lon_bins, lat_bins))

#shape into continuous matrice
g = np.zeros(xi.shape)
g[:-1,:-1] = h
g[-1] = g[0]      # copy the top row to the bottom
g[:,-1] = g[:,0]  # copy the left column to the right
print g.shape,yi.shape,xi.shape

m.drawcoastlines()
m.drawstates()

g[g==0.0] = np.nan
cs = m.contourf(xi, yi, g)
cbar = plt.colorbar(cs, orientation='horizontal')
cbar.set_label('la densite des impacts foudre',size=18)

plt.gcf().set_size_inches(15,15)
plt.show()

Any ideas ??

Body:
I just found the solution of my question, i did this to obtain the number of the years i have in the csv file ,i divided the calculated density into NByears and it's working perfectly.

DateMax = data.index.year.max()
DateMin = data.index.year.min()
NByears = (DateMax - DateMin)


问:
What does Java do with my "equals" implementations here?
Today, I've stumbled over the following:

Consider two classes NewClass and NewClass1, which have the following "equals"-methods:

NewClass:

```<code>@Override
public boolean equals(Object obj) {
    return false;
}

public boolean equals(NewClass obj) {
    return value == obj.getValue();
}
</code>```

NewClass1:

```<code>@Override
public boolean equals(Object obj) {
    if(!(obj instanceof NewClass1)) {
        return false;
    }
    return equals((NewClass1) obj);
}

public boolean equals(NewClass1 obj) {
    return value == obj.getValue();
}
</code>```

What I find weird is that the equals in NewClass1 seems to be exponentially slower than the one in NewClass (for 10.000.000 calls 14ms against 3000ms). At first, I thought this was related to the "instanceof" check, but if I replace "return equals((NewClass1) obj);" with "return false;" in NewClass1, suddenly it runs more or less equally fast. I don't really understand what is happening here, because in my opinion, the return statement in equals(Object) should never actually be called. What am I getting wrong here?

The following is my "benchmarking code", in case I made some mistake there:

```<code>public static void main(String[] args) {
    // TODO code application logic here

    NewClass i1 = new NewClass(1);
    NewClass i2 = new NewClass(1);
    NewClass i3 = new NewClass(5);

    NewClass1 j1 = new NewClass1(1);
    NewClass1 j2 = new NewClass1(1);
    NewClass1 j3 = new NewClass1(5);

    Object o1 = new Object();
    Object o2 = new Object();

    assert(i1.equals(i1));
    assert(i1.equals(i2));
    assert(i1.equals(i3) == false);
    assert(i1.equals(o1) == false);

    assert(j1.equals(j1));
    assert(j1.equals(j2));
    assert(j1.equals(j3) == false);
    assert(j1.equals(o1) == false);

    long start = System.currentTimeMillis();

    for(int i=0; i<1000000000; i++) {
        i1.equals(i1);
        i1.equals(i2);
        i1.equals(o1);
        i1.equals(o2);
    }

    long end = System.currentTimeMillis();

    System.out.println("Execution time was "+(end-start)+" ms.");

    start = System.currentTimeMillis();

    for(int i=0; i<1000000000; i++) {
        j1.equals(j1);
        j1.equals(j2);
        j1.equals(o1);
        j1.equals(o2);
    }

    end = System.currentTimeMillis();

    System.out.println("Execution time was "+(end-start)+" ms.");
}
</code>```

答: In the first example you always return false. This is very fast. In the second example you have a much longer comparison algorithm</p>

ContentLicense: CC BY-SA 2.5

Body:
Today, I've stumbled over the following:

Consider two classes NewClass and NewClass1, which have the following "equals"-methods:

NewClass:

@Override
public boolean equals(Object obj) {
    return false;
}

public boolean equals(NewClass obj) {
    return value == obj.getValue();
}

NewClass1:

@Override
public boolean equals(Object obj) {
    if(!(obj instanceof NewClass1)) {
        return false;
    }
    return equals((NewClass1) obj);
}

public boolean equals(NewClass1 obj) {
    return value == obj.getValue();
}

What I find weird is that the equals in NewClass1 seems to be exponentially slower than the one in NewClass (for 10.000.000 calls 14ms against 3000ms). At first, I thought this was related to the "instanceof" check, but if I replace "return equals((NewClass1) obj);" with "return false;" in NewClass1, suddenly it runs more or less equally fast. I don't really understand what is happening here, because in my opinion, the return statement in equals(Object) should never actually be called. What am I getting wrong here?

The following is my "benchmarking code", in case I made some mistake there:

public static void main(String[] args) {
    // TODO code application logic here

    NewClass i1 = new NewClass(1);
    NewClass i2 = new NewClass(1);
    NewClass i3 = new NewClass(5);

    NewClass1 j1 = new NewClass1(1);
    NewClass1 j2 = new NewClass1(1);
    NewClass1 j3 = new NewClass1(5);

    Object o1 = new Object();
    Object o2 = new Object();

    assert(i1.equals(i1));
    assert(i1.equals(i2));
    assert(i1.equals(i3) == false);
    assert(i1.equals(o1) == false);

    assert(j1.equals(j1));
    assert(j1.equals(j2));
    assert(j1.equals(j3) == false);
    assert(j1.equals(o1) == false);

    long start = System.currentTimeMillis();

    for(int i=0; i<1000000000; i++) {
        i1.equals(i1);
        i1.equals(i2);
        i1.equals(o1);
        i1.equals(o2);
    }

    long end = System.currentTimeMillis();

    System.out.println("Execution time was "+(end-start)+" ms.");

    start = System.currentTimeMillis();

    for(int i=0; i<1000000000; i++) {
        j1.equals(j1);
        j1.equals(j2);
        j1.equals(o1);
        j1.equals(o2);
    }

    end = System.currentTimeMillis();

    System.out.println("Execution time was "+(end-start)+" ms.");
}

OwnerDisplayName: anon


问:
How could I pass std::function as function pointer?
I am trying to write a class template and internally it use a C function (implementation of BFGS optimization, provided by the R environment) with the following interface:

```<code>void vmmin(int n, double *x, double *Fmin,
           optimfn fn, optimgr gr, ... ,
           void *ex, ... );
</code>```

where fn and gr are function pointers of type

```<code>typedef double optimfn(int n, double *par, void *ex);
</code>```

and

```<code>typedef void optimgr(int n, double *par, double *gr, void *ex);
</code>```

respectively. My C++ class template looks like this:

```<code>template <typename T>
class optim {
 public:
  // ...
  void minimize(T& func, arma::vec &dpar, void *ex) {
    std::function<optimfn> fn =
      std::bind(&T::fr, func, std::placeholders::_1,
                std::placeholders::_2, std::placeholders::_3);
    std::function<optimgr> gr =
      std::bind(&T::grr, func, std::placeholders::_1,
                std::placeholders::_2, std::placeholders::_3,
                std::placeholders::_4);
    // ERROR: cannot convert std::function to function pointer
    vmmin(... , fn, gr, ...);
    // ...
  }
};
</code>```

so that it can be instantiated by any class with two specified member functions, e.g.:

```<code>class Rosen {
 public:
  // ...
  double fr(int n, double *par, void *ex);
  void grr(int n, double *par, double *gr, void *ex);
 private:
  // ...
};

// main.cc
Rosen func;
optim<Rosen> obj;
obj.minimize(func, dpar, ex);
</code>```

Is this possible? Or maybe there is a better way of doing this -- pass the two member functions separately as function pointer? (If the objective function and the corresponding gradient are simple, it is absolutely okay to write two functions. However, most of the time, the problem I got is far more complicated and I have to implement the problem as a class).

答:
An alternative solution could be to have the optim class do its magic with two (possibly pure) virtual functions, and then inherit to define a new class Rosen which implements them. This could look like

```<code>class optim {
    public:
        // ...

        virtual double fn(int n, double *par, void *ex) = 0;
        virtual void gr(int n, double *par, double *gr, void *ex) = 0;

        void minimize(arma::vec &dpar, void *ex) {
            vmmin(... , &fn, &gr, ...);
            // ...
        }
};

class Rosen : public optim {
    public:
        // ...
        double fn(int n, double *par, void *ex);
        void gr(int n, double *par, double *gr, void *ex);

    private:
        // ...
};

// main.cc
Rosen obj;
obj.minimize(dpar, ex);
</code>```

Body:
I am trying to write a class template and internally it use a C function (implementation of BFGS optimization, provided by the R environment) with the following interface:

void vmmin(int n, double *x, double *Fmin,
           optimfn fn, optimgr gr, ... ,
           void *ex, ... );

where fn and gr are function pointers of type

typedef double optimfn(int n, double *par, void *ex);

and

typedef void optimgr(int n, double *par, double *gr, void *ex);

respectively. My C++ class template looks like this:

template <typename T>
class optim {
 public:
  // ...
  void minimize(T& func, arma::vec &dpar, void *ex) {
    std::function<optimfn> fn =
      std::bind(&T::fr, func, std::placeholders::_1,
                std::placeholders::_2, std::placeholders::_3);
    std::function<optimgr> gr =
      std::bind(&T::grr, func, std::placeholders::_1,
                std::placeholders::_2, std::placeholders::_3,
                std::placeholders::_4);
    // ERROR: cannot convert std::function to function pointer
    vmmin(... , fn, gr, ...);
    // ...
  }
};

so that it can be instantiated by any class with two specified member functions, e.g.:

class Rosen {
 public:
  // ...
  double fr(int n, double *par, void *ex);
  void grr(int n, double *par, double *gr, void *ex);
 private:
  // ...
};

// main.cc
Rosen func;
optim<Rosen> obj;
obj.minimize(func, dpar, ex);

Is this possible? Or maybe there is a better way of doing this -- pass the two member functions separately as function pointer? (If the objective function and the corresponding gradient are simple, it is absolutely okay to write two functions. However, most of the time, the problem I got is far more complicated and I have to implement the problem as a class).

Body:
An alternative solution could be to have the optim class do its magic with two (possibly pure) virtual functions, and then inherit to define a new class Rosen which implements them. This could look like

class optim {
    public:
        // ...

        virtual double fn(int n, double *par, void *ex) = 0;
        virtual void gr(int n, double *par, double *gr, void *ex) = 0;

        void minimize(arma::vec &dpar, void *ex) {
            vmmin(... , &fn, &gr, ...);
            // ...
        }
};

class Rosen : public optim {
    public:
        // ...
        double fn(int n, double *par, void *ex);
        void gr(int n, double *par, double *gr, void *ex);

    private:
        // ...
};

// main.cc
Rosen obj;
obj.minimize(dpar, ex);


答:
You should use ::std::remove_if algorithm

```<code>Acc.erase
(
    ::std::remove_if
    (
        Acc.begin()
    ,   Acc.end()
    ,   [&Phone](AccountStruct const & acc)
        {
            return(acc.phone == Phone);
        }
    )
,   Acc.end()
);
</code>```

Title: std::list::erase(iter) exception handling c++

Body:
You should use ::std::remove_if algorithm

Acc.erase
(
    ::std::remove_if
    (
        Acc.begin()
    ,   Acc.end()
    ,   [&Phone](AccountStruct const & acc)
        {
            return(acc.phone == Phone);
        }
    )
,   Acc.end()
);


问:
Warning about "xsd:date"
I am using Jena to parse a "TTL" formatted file. I see the warning in the console

Lexical form '1896-13-04' not valid for datatype http://www.w3.org/2001/XMLSchema#date

I want to know why this warning happens.

答:
Per the XML schema specification for xsd:date:

The ·lexical space· of date consists of finite-length sequences of characters of the form: '-'? yyyy '-' mm '-' dd zzzzzz? where the date and optional timezone are represented exactly the same way as they are for dateTime

i.e. dates must follow the International Convention of having year then month then day.

From the example given your data appears to have dates in the American convention which has year then day then month. Since 13 is not a valid month you receive a warning.

Your input data is not valid according to the specifications and therefore may not be processed correctly when you try to ask queries based upon that data e.g. Find items with dates before or after a specific date of interest. Dates for which you are not receiving a warning maybe interpreted incorrectly a day and month being interchanged.

You need to correct the data as otherwise this will cause you issues later. If the data is from a public data source you should let them know that they have a data quality issue, if the data is being created by yourself you need to correct your data generation so the dates following the specification.

Title: Warning about "xsd:date"


问:
How do you submit a form to an app engine python application without refreshing the sending page?
As a newbie to app engine and python I can follow the examples given by Google and have created a python application with a template HTML page where I can enter data, submit it to the datastore and by reading back the data, just sent, recreate the sending page so I can continue adding data and store again.  However what I would like to do is submit the data, have it stored in the datastore without the sending page being refreshed. It seems like a waste of traffic to have all the data sent back again.</p>

答:
Have a look at Pyjamas pyjs.org

It's a Python Compiler for web browsers. Write your client side in Python and Pyjamas will compile it into JavaScript.


问:
Django- Disabling confirm password
I followed the example below copied from the now-defunct Documentation site.  The example is too good - here two password fields are used.

I don't want to use confirm password. I only want to use single password field. Is there any way to do that?

Update

RegistrationForm in forms.py uses inbuilt UserCreationForm. It contains two password fields.

Custom user model with email as primary login field

models.py :

```<code>from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import (
        AbstractBaseUser, BaseUserManager, PermissionsMixin)
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

class UserManager(BaseUserManager):
    def _create_user(self, email,password, is_staff, is_superuser, **extra_fields):
        now = timezone.now()
        if not email:
            raise ValueError('users must have an email address')
        email = self.normalize_email(email)
        user = self.model(email = email,
                            is_staff = is_staff,
                            is_superuser = is_superuser,
                            last_login = now,
                            date_joined = now,
                            **extra_fields)
        user.set_password(password)
        user.save(using = self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        user = self._create_user(email, password, False, False, **extra_fields)
        return user

    def create_superuser(self, email, password, **extra_fields):
        user = self._create_user(email, password, True, True, **extra_fields)
        return user

class User(AbstractBaseUser,PermissionsMixin):
    """My own custom user class"""

    email = models.EmailField(max_length=255, unique=True, db_index=True, verbose_name=_('email address'))
    date_joined = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_full_name(self):
    """Return the email."""
        return self.email

    def get_short_name(self):
    """Return the email."""
        return self.email
</code>```

forms.py :

```<code>from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import User

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(widget=forms.TextInput(
        attrs={'class': 'form-control','type':'text','name': 'email'}),
        label="Email")
    password1 = forms.CharField(widget=forms.PasswordInput(
        attrs={'class':'form-control','type':'password', 'name':'password1'}),
        label="Password")
    password2 = forms.CharField(widget=forms.PasswordInput(
        attrs={'class':'form-control','type':'password', 'name': 'password2'}),
        label="Password (again)")

    '''added attributes so as to customise for styling, like bootstrap'''
    class Meta:
        model = User
        fields = ['email','password1','password2']
        field_order = ['email','password1','password2']

    def clean(self):
    """
    Verifies that the values entered into the password fields match
    NOTE : errors here will appear in 'non_field_errors()'
    """
        cleaned_data = super(RegistrationForm, self).clean()
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError("Passwords don't match. Please try again!")
        return self.cleaned_data

    def save(self, commit=True):
        user = super(RegistrationForm,self).save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        if commit:
            user.save()
        return user

#The save(commit=False) tells Django to save the new record, but dont commit it to the database yet

class AuthenticationForm(forms.Form): # Note: forms.Form NOT forms.ModelForm
    email = forms.EmailField(widget=forms.TextInput(
        attrs={'class': 'form-control','type':'text','name': 'email','placeholder':'Email'}),
        label='Email')
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={'class':'form-control','type':'password', 'name': 'password','placeholder':'Password'}),
        label='Password')

    class Meta:
        fields = ['email', 'password']
</code>```

views.py :

```<code>from django.shortcuts import redirect, render, HttpResponse
from django.contrib.auth import login as django_login, logout as django_logout, authenticate as django_authenticate
#importing as such so that it doesn't create a confusion with our methods and django's default methods

from django.contrib.auth.decorators import login_required
from .forms import AuthenticationForm, RegistrationForm

def login(request):
    if request.method == 'POST':
        form = AuthenticationForm(data = request.POST)
        if form.is_valid():
            email = request.POST['email']
            password = request.POST['password']
            user = django_authenticate(email=email, password=password)
            if user is not None:
                if user.is_active:
                    django_login(request,user)
                    return redirect('/dashboard') #user is redirected to dashboard
    else:
        form = AuthenticationForm()

    return render(request,'login.html',{'form':form,})

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(data = request.POST)
        if form.is_valid():
            user = form.save()
            u = django_authenticate(user.email = user, user.password = password)
            django_login(request,u)
            return redirect('/dashboard')
    else:
        form = RegistrationForm()

    return render(request,'register.html',{'form':form,})

def logout(request):
    django_logout(request)
    return redirect('/')

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

settings.py :

```<code>AUTH_USER_MODEL = 'myapp.User'
</code>```

admin.py

```<code>from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import Group
from .models import User

class UserAdmin(BaseUserAdmin):
    list_display = ('email','is_staff')
    list_filter = ('is_staff',)
    fieldsets = ((None,
                  {'fields':('email','password')}), ('Permissions',{'fields':('is_staff',)}),)
    add_fieldsets = ((None, {'classes': ('wide',), 'fields': ('email', 'password1', 'password2')}),)
    search_fields =('email',)
    ordering = ('email',)
    filter_horizontal = ()

admin.site.register(User, UserAdmin)
admin.site.unregister(Group)
</code>```

Excerpted from Extending or Substituting User Model - Custom user model with email as primary login field. The original author was Rishabh Agrahari. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 and may be found in the Documentation archive. Reference topic ID: 1209 and example ID: 4050.

答:
If you remove the field password2 and the clean method it'll work

```<code>from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import User

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(widget=forms.TextInput(
        attrs={'class': 'form-control','type':'text','name': 'email'}),
        label="Email")
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={'class':'form-control','type':'password', 'name':'password'}),
        label="Password")

    '''added attributes so as to customise for styling, like bootstrap'''
    class Meta:
        model = User
        fields = ['email','password']
        field_order = ['email','password']

    def save(self, commit=True):
        user = super(RegistrationForm,self).save(commit=False)
        user.set_password(self.cleaned_data['password'])
        if commit:
            user.save()
        return user
</code>```

admin.py

```<code>from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import Group
from .models import User

class UserAdmin(BaseUserAdmin):
    list_display = ('email','is_staff')
    list_filter = ('is_staff',)
    fieldsets = ((None,
                  {'fields':('email','password')}), ('Permissions',{'fields':('is_staff',)}),)
    add_fieldsets = ((None, {'classes': ('wide',), 'fields': ('email', 'password')}),)
    search_fields =('email',)
    ordering = ('email',)
    filter_horizontal = ()
</code>```

Title: Django- Disabling confirm password

Body:
I followed the example below copied from the now-defunct Documentation site.  The example is too good - here two password fields are used.

I don't want to use confirm password. I only want to use single password field. Is there any way to do that?

Update

RegistrationForm in forms.py uses inbuilt UserCreationForm. It contains two password fields.

Custom user model with email as primary login field

models.py :

from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import (
        AbstractBaseUser, BaseUserManager, PermissionsMixin)
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

class UserManager(BaseUserManager):
    def _create_user(self, email,password, is_staff, is_superuser, **extra_fields):
        now = timezone.now()
        if not email:
            raise ValueError('users must have an email address')
        email = self.normalize_email(email)
        user = self.model(email = email,
                            is_staff = is_staff,
                            is_superuser = is_superuser,
                            last_login = now,
                            date_joined = now,
                            **extra_fields)
        user.set_password(password)
        user.save(using = self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        user = self._create_user(email, password, False, False, **extra_fields)
        return user

    def create_superuser(self, email, password, **extra_fields):
        user = self._create_user(email, password, True, True, **extra_fields)
        return user

class User(AbstractBaseUser,PermissionsMixin):
    """My own custom user class"""

    email = models.EmailField(max_length=255, unique=True, db_index=True, verbose_name=_('email address'))
    date_joined = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_full_name(self):
    """Return the email."""
        return self.email

    def get_short_name(self):
    """Return the email."""
        return self.email

forms.py :

from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import User

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(widget=forms.TextInput(
        attrs={'class': 'form-control','type':'text','name': 'email'}),
        label="Email")
    password1 = forms.CharField(widget=forms.PasswordInput(
        attrs={'class':'form-control','type':'password', 'name':'password1'}),
        label="Password")
    password2 = forms.CharField(widget=forms.PasswordInput(
        attrs={'class':'form-control','type':'password', 'name': 'password2'}),
        label="Password (again)")

    '''added attributes so as to customise for styling, like bootstrap'''
    class Meta:
        model = User
        fields = ['email','password1','password2']
        field_order = ['email','password1','password2']

    def clean(self):
    """
    Verifies that the values entered into the password fields match
    NOTE : errors here will appear in 'non_field_errors()'
    """
        cleaned_data = super(RegistrationForm, self).clean()
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError("Passwords don't match. Please try again!")
        return self.cleaned_data

    def save(self, commit=True):
        user = super(RegistrationForm,self).save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        if commit:
            user.save()
        return user

#The save(commit=False) tells Django to save the new record, but dont commit it to the database yet

class AuthenticationForm(forms.Form): # Note: forms.Form NOT forms.ModelForm
    email = forms.EmailField(widget=forms.TextInput(
        attrs={'class': 'form-control','type':'text','name': 'email','placeholder':'Email'}),
        label='Email')
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={'class':'form-control','type':'password', 'name': 'password','placeholder':'Password'}),
        label='Password')

    class Meta:
        fields = ['email', 'password']

views.py :

from django.shortcuts import redirect, render, HttpResponse
from django.contrib.auth import login as django_login, logout as django_logout, authenticate as django_authenticate
#importing as such so that it doesn't create a confusion with our methods and django's default methods

from django.contrib.auth.decorators import login_required
from .forms import AuthenticationForm, RegistrationForm

def login(request):
    if request.method == 'POST':
        form = AuthenticationForm(data = request.POST)
        if form.is_valid():
            email = request.POST['email']
            password = request.POST['password']
            user = django_authenticate(email=email, password=password)
            if user is not None:
                if user.is_active:
                    django_login(request,user)
                    return redirect('/dashboard') #user is redirected to dashboard
    else:
        form = AuthenticationForm()

    return render(request,'login.html',{'form':form,})

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(data = request.POST)
        if form.is_valid():
            user = form.save()
            u = django_authenticate(user.email = user, user.password = password)
            django_login(request,u)
            return redirect('/dashboard')
    else:
        form = RegistrationForm()

    return render(request,'register.html',{'form':form,})

def logout(request):
    django_logout(request)
    return redirect('/')

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

settings.py :

AUTH_USER_MODEL = 'myapp.User'

admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import Group
from .models import User

class UserAdmin(BaseUserAdmin):
    list_display = ('email','is_staff')
    list_filter = ('is_staff',)
    fieldsets = ((None,
                  {'fields':('email','password')}), ('Permissions',{'fields':('is_staff',)}),)
    add_fieldsets = ((None, {'classes': ('wide',), 'fields': ('email', 'password1', 'password2')}),)
    search_fields =('email',)
    ordering = ('email',)
    filter_horizontal = ()

admin.site.register(User, UserAdmin)
admin.site.unregister(Group)

Excerpted from Extending or Substituting User Model - Custom user model with email as primary login field. The original author was Rishabh Agrahari. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 and may be found in the Documentation archive. Reference topic ID: 1209 and example ID: 4050.

Body:
If you remove the field password2 and the clean method it'll work

from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import User

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(widget=forms.TextInput(
        attrs={'class': 'form-control','type':'text','name': 'email'}),
        label="Email")
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={'class':'form-control','type':'password', 'name':'password'}),
        label="Password")

    '''added attributes so as to customise for styling, like bootstrap'''
    class Meta:
        model = User
        fields = ['email','password']
        field_order = ['email','password']

    def save(self, commit=True):
        user = super(RegistrationForm,self).save(commit=False)
        user.set_password(self.cleaned_data['password'])
        if commit:
            user.save()
        return user

admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import Group
from .models import User

class UserAdmin(BaseUserAdmin):
    list_display = ('email','is_staff')
    list_filter = ('is_staff',)
    fieldsets = ((None,
                  {'fields':('email','password')}), ('Permissions',{'fields':('is_staff',)}),)
    add_fieldsets = ((None, {'classes': ('wide',), 'fields': ('email', 'password')}),)
    search_fields =('email',)
    ordering = ('email',)
    filter_horizontal = ()


问:
DDD - How to store aggregates in NoSql databases
A current project needs us to persist domain objects in a NoSQL database such as mongoDB.
In many examples (incl. Eric Evans, Vaughn Vernon) the domain objects are serialized and persisted to the mongoDB directly.

We would like to avoid mixing the domain layer with persistence related inforamtion by not having any annotations in our domain objects.
Also we are concerned about corrupting the persisted data by changing the domain object in the future.

We came to the conclusion that we need to have some kind of DTOs translating between the domain objects and the persisted data.

Did anyone of you come across a good solution for such a case?

答:
Like you, I want business objects to have no dependency on any kind of specific repository. I solved it like this: That have your business object define its state objects and repository functions as interfaces. Your repository implementation can create an actual state object and inject that into your business object using the constructor.

There are a lot of advantages to this approach (such as having business objects for specific purposes), but you easily achieve complete (two-way) independence of your repository this way. Martin Fowler also hinted at this approach elsewhere.

I actually use the same pattern in my Angular / TypeScript projects. My read-api calls return DTO objects that get state objects injected as well and their properties map directly onto state objects.

These DTOs that end up as untyped javascript objects when they come from the api to the client (Angular) project are then in turn injected as state objects into TypeScript objects, injected in the constructor again and mapped by getters and setters. It works very cleanly and is well maintainable. I have an example on my GitHub (niwra) account (Software-Management repositories), but can expand here if anyone is interested.

MongoDB allows for very clean and Unit-Testable repository implementations, that returns strongly typed aggregates. The only thing I haven't solved cleanly yet is telling MongoDb about state objects for child-collections. Currently that is pretty 'static' still, but I'm sure I'll find some nice solution.


问:
Updated: Setting bool default value to true
I need to find a way to set the default value of ischecked to true, I am passing it as a parameter and I don't always set it.

ischecked is defined in my config files, I have multiple configs and in some it is defined and some it isn't. I won't get into why I use different configs. When it isn't define it is defaulted to false but I need it to be true.

```<code>function showSaveCardControl(ischecked) {
    $(".saveCardControl").slideDown().find("input").prop("checked", ischecked);
}
</code>```

if it hasn't been defined I need the checkbox to be checked basically but since the default is false it is unchecked.

Update:

I am passing an xml element to a c# property. The xml would be where I set the value of ischecked but since I haven't set it somewhere either in the xml or once it has been turned into a c# property it is set to false. I am guessing it is set as the property tries to call that xml value.

I have tried setting the default using an attribute.

```<code>[XmlElement("EasyPaySaveCardControlChecked")]
[DefaultValue(true)]
public bool ischecked { get; set; }
</code>```

I have tried setting it using a constructor.

```<code>public className()
{
    ischecked = true;
}
</code>```

I have also tried making all the bools nullable and the value is still being set to false

none of these solutions work and I have no idea why. no matter what I do the property is set to false, if it was set to undefined it would be fine but bools have to defaulted to false

答:
Try something like this:</p>

```<code>function showSaveCardControl(ischecked) {
    if ('undefined' === typeof ischecked) ischecked = true;
    $(".saveCardControl").slideDown().find("input").prop("checked", ischecked);
}
</code>```

Body:
I need to find a way to set the default value of ischecked to true, I am passing it as a parameter and I don't always set it.

ischecked is defined in my config files, I have multiple configs and in some it is defined and some it isn't. I won't get into why I use different configs. When it isn't define it is defaulted to false but I need it to be true.

function showSaveCardControl(ischecked) {
    $(".saveCardControl").slideDown().find("input").prop("checked", ischecked);
}

if it hasn't been defined I need the checkbox to be checked basically but since the default is false it is unchecked.

Update:

I am passing an xml element to a c# property. The xml would be where I set the value of ischecked but since I haven't set it somewhere either in the xml or once it has been turned into a c# property it is set to false. I am guessing it is set as the property tries to call that xml value.

I have tried setting the default using an attribute.

[XmlElement("EasyPaySaveCardControlChecked")]
[DefaultValue(true)]
public bool ischecked { get; set; }

I have tried setting it using a constructor.

public className()
{
    ischecked = true;
}

I have also tried making all the bools nullable and the value is still being set to false

none of these solutions work and I have no idea why. no matter what I do the property is set to false, if it was set to undefined it would be fine but bools have to defaulted to false

Body:
Try something like this:

function showSaveCardControl(ischecked) {
    if ('undefined' === typeof ischecked) ischecked = true;
    $(".saveCardControl").slideDown().find("input").prop("checked", ischecked);
}


问:
How to manipulate the object a pointer represents C++
I am building a data structure and need to manipulate the object indicated by a pointer. The object indicated by the pointer is:

```<code>//in header file
struct treeNode{
    int value;
    treeNode* left;
    treeNode* right;
};
</code>```

My current implementation only changes what the pointer is pointing to.

```<code>target->value = oneLarger->value
</code>```

Target and oneLarger are defined:

```<code>void method(treeNode* target){
    treeNode* oneLarger = (tree node retrieved by another method)
    target->value = more->value
}
</code>```

Is this possible to do via pass by reference or do I have to pass by value?

答:
You can do: by Pointer, by Ref, by Copy

note that changes made in the byCopy function will get lost as soon as the function is done!

Those options look like:

```<code>//by Pointer
void method(treeNode* target) {

    treeNode* oneLarger = ...
    target->value = oneLarger->value;
}

//by Ref
// since that is a ref, you access the value using the dot(.)  and not the `->` operator
void method(treeNode& target) {

    treeNode* oneLarger = ...
    target.value = oneLarger->value;
}

//by Copy
// since that is a copy, you access the value using the dot(.)  and not the `->` operator
void method(treeNode target) {

    treeNode* oneLarger = ...
    target.value = oneLarger->value;
}
</code>```

Body:
I am building a data structure and need to manipulate the object indicated by a pointer. The object indicated by the pointer is:

//in header file
struct treeNode{
    int value;
    treeNode* left;
    treeNode* right;
};

My current implementation only changes what the pointer is pointing to.

target->value = oneLarger->value

Target and oneLarger are defined:

void method(treeNode* target){
    treeNode* oneLarger = (tree node retrieved by another method)
    target->value = more->value
}

Is this possible to do via pass by reference or do I have to pass by value?

Body:
You can do: by Pointer, by Ref, by Copy

note that changes made in the byCopy function will get lost as soon as the function is done!

Those options look like:

//by Pointer
void method(treeNode* target) {

    treeNode* oneLarger = ...
    target->value = oneLarger->value;
}

//by Ref
// since that is a ref, you access the value using the dot(.)  and not the `->` operator
void method(treeNode& target) {

    treeNode* oneLarger = ...
    target.value = oneLarger->value;
}

//by Copy
// since that is a copy, you access the value using the dot(.)  and not the `->` operator
void method(treeNode target) {

    treeNode* oneLarger = ...
    target.value = oneLarger->value;
}


答:
this should do the trick : </p>

```<code>function showSaveCardControl(ischecked) {
    if(typeof ischecked == 'undefined')
       ischecked = true;

    $(".saveCardControl").slideDown().find("input").prop("checked", ischecked);
}
</code>```

Title: Updated: Setting bool default value to true

Body:
this should do the trick :

function showSaveCardControl(ischecked) {
    if(typeof ischecked == 'undefined')
       ischecked = true;

    $(".saveCardControl").slideDown().find("input").prop("checked", ischecked);
}


问:
Trying to implement a link to open when a menubar item is clicked but getting an error
Using HostServices.

I am using the constructor

```<code>HostServices services = this.getHostServices();
</code>```

I want it to work with the following menu item so that when that menu item is clicked it should open a link to the web browser...
the piece of code i want the object services to work on is

```<code>MenuItem fbMenuItem = new MenuItem("Facebook Page");
    fbMenuItem.setId("fbMenuItem");
    fbMenuItem.setOnAction(event -> {
        services.showDocument("facebook.com");
    });
</code>```

I have imported the

```<code>import javafx.application.HostServices;
</code>```

which is supposed to work with HostServices but I keep getting an error that says

```<code>Caesar.java:359: error: cannot find symbol
    HostServices services = this.getHostServices();
                                ^
symbol: method getHostServices()
1 error
</code>```

But when I try same procedure with a normal button that is not in  a menuBar it works fine but when I use that trick above on the menuBar it still gives me that error

答:
One way to handle this is to create a singleton to hold these kinds of references and then instantiate that during the Application Start Up.

For example:

```<code>public class HostServiceWrapper {
     private static HostServiceWrapper _instance;
     private HostServices hostServices;

     private HostServiceWrapper (HostServices hostServices) {
        // Do not allow this to be created externally
        if (hostServices == null) {
            throw new RuntimeException("Host services can't be null to instantiate this method");
        }
        this.hostServices = hostServices;
     }

     public static void createInstance(HostServices hostServices) {
        if (_instance == null) {
            _instance = new HostServiceWrapper (hostServices);
        }
     }

     public static HostServiceWrapper getInstance() {
        if (_instance== null) {
            throw new RuntimeException("HostServiceWrapper has not been correctly instantiated.");
        }
        return _instance;
    }

     public void openURL(String url) {
        hostServices.showDocument(url);
    }

}
</code>```

Then in your application start method you would do something like this...

```<code>public void start(Stage primaryStage) throws Exception {
    .....
     HostServiceWrapper.createInstance(getHostServices());
}
</code>```

Then where you need to access it....

```<code>HostServiceWrapper.getInstance().openURL("http://www.google.com");
</code>```

Body:
Using HostServices.

I am using the constructor

HostServices services = this.getHostServices();

I want it to work with the following menu item so that when that menu item is clicked it should open a link to the web browser...
the piece of code i want the object services to work on is

MenuItem fbMenuItem = new MenuItem("Facebook Page");
    fbMenuItem.setId("fbMenuItem");
    fbMenuItem.setOnAction(event -> {
        services.showDocument("facebook.com");
    });

I have imported the

import javafx.application.HostServices;

which is supposed to work with HostServices but I keep getting an error that says

Caesar.java:359: error: cannot find symbol
    HostServices services = this.getHostServices();
                                ^
symbol: method getHostServices()
1 error

But when I try same procedure with a normal button that is not in  a menuBar it works fine but when I use that trick above on the menuBar it still gives me that error

Body:
One way to handle this is to create a singleton to hold these kinds of references and then instantiate that during the Application Start Up.

For example:

public class HostServiceWrapper {
     private static HostServiceWrapper _instance;
     private HostServices hostServices;

     private HostServiceWrapper (HostServices hostServices) {
        // Do not allow this to be created externally
        if (hostServices == null) {
            throw new RuntimeException("Host services can't be null to instantiate this method");
        }
        this.hostServices = hostServices;
     }

     public static void createInstance(HostServices hostServices) {
        if (_instance == null) {
            _instance = new HostServiceWrapper (hostServices);
        }
     }

     public static HostServiceWrapper getInstance() {
        if (_instance== null) {
            throw new RuntimeException("HostServiceWrapper has not been correctly instantiated.");
        }
        return _instance;
    }

     public void openURL(String url) {
        hostServices.showDocument(url);
    }

}

Then in your application start method you would do something like this...

public void start(Stage primaryStage) throws Exception {
    .....
     HostServiceWrapper.createInstance(getHostServices());
}

Then where you need to access it....

HostServiceWrapper.getInstance().openURL("http://www.google.com");


问:
Array adding new Series Highchart
This Code just Browser share name series..

series: [{
    name: 'Man',
    data: <?php echo json_encode($man_array,JSON_NUMERIC_CHECK) ?>

  }, {
    name: 'Women',
    data: <?php echo json_encode($woman_array,JSON_NUMERIC_CHECK) ?>

  }, {
    name: 'Kind',
    data: <?php echo json_encode($kind_array,JSON_NUMERIC_CHECK) ?>

  }, {
    name: 'User',
    data:<?php echo json_encode($user_array,JSON_NUMERIC_CHECK) ?>

  }]```
</div>
</div>
</p>

<p>Example</p>

<p>How can create series like series : women, series : man...help me please...</p>

```//Include Koneksi
$koneksi     = mysqli_connect("localhost", "root", "", "simcard");
// $bulan       = mysqli_query($koneksi, "SELECT bulan FROM penjualan WHERE tahun='2017' order by id asc");

//Membuat Query
$q=mysqli_query($koneksi, "SELECT * FROM penduduk");
$a=mysqli_query($koneksi, "SELECT * FROM card");

$man_array=array();
$woman_array=array();
$kind_array=array();
$user_array=array();
while($r=mysqli_fetch_array($q)){
    $man_array[]= $r["man"];
    $woman_array[]= $r["woman"];
}
while($f=mysqli_fetch_array($a)){
    $kind_array[]=$f["kind"];
    $user_array[]= $f["user"];
}
```

<p>this one highchart code any wrong this code..?no used the color no problem.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('#view').highcharts({
       chart: {
        type: 'column'
    },
    title: {
        text: 'Stacked column chart'
    },
    xAxis: {
        categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Total'
        },
        stackLabels: {
            enabled: true,
            style: {
                fontWeight: 'bold',
                color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
            }
        }
    },
    legend: {
        align: 'right',
        x: -30,
        verticalAlign: 'top',
        y: 25,
        floating: true,
        backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
        borderColor: '#CCC',
        borderWidth: 1,
        shadow: false
    },
    tooltip: {
        headerFormat: '<b>{point.x}</b><br/>',
        pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
    },
    plotOptions: {
        column: {
            //stacking: 'normal',
            dataLabels: {
                enabled: true,
                color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
            }
        }
    },</code>```

This Page View source html series.

series: [{
    name: 'Man',
    data: []

  }, {
    name: 'Women',
    data: []

  }, {
    name: 'Kind',
     data: []
  }, {
    name: 'User',
    data:[]
  }]

    });
});```

答:
your chart will come like this,Fiddle sample. So replace with code below. Also check Data from a database</p>

```<code><?php
    $man_array=array();
    $woman_array=array();
    $kind_array=array();
    $user_array=array();
    while($r=mysqli_fetch_array($q)){
        $man_array[]= $r["man"];
        $woman_array[]= $r["woman"];
    }
    while($f=mysqli_fetch_array($a)){
        $kind_array[]=$f["kind"];
        $user_array[]= $f["user"];
    }

    ?>
  series: [{
    name: 'Man',
    data: <?php echo json_encode($man_array,JSON_NUMERIC_CHECK) ?>,
    color: 'red'
  }, {
    name: 'Women',
    data: <?php echo json_encode($woman_array,JSON_NUMERIC_CHECK) ?>,

    color: 'black'
  }, {
    name: 'Kind',
    data: <?php echo json_encode($kind_array,JSON_NUMERIC_CHECK) ?>,
    color: 'green'
  }, {
    name: 'User',
    data:<?php echo json_encode($user_array,JSON_NUMERIC_CHECK) ?>,
    color: 'blue'
  }]
</code>```

Title: Array adding new Series Highchart

Body:
This Code just Browser share name series..

series: [{
    name: 'Man',
    data: <?php echo json_encode($man_array,JSON_NUMERIC_CHECK) ?>

  }, {
    name: 'Women',
    data: <?php echo json_encode($woman_array,JSON_NUMERIC_CHECK) ?>

  }, {
    name: 'Kind',
    data: <?php echo json_encode($kind_array,JSON_NUMERIC_CHECK) ?>

  }, {
    name: 'User',
    data:<?php echo json_encode($user_array,JSON_NUMERIC_CHECK) ?>

  }]

Example

How can create series like series : women, series : man...help me please...

//Include Koneksi
$koneksi     = mysqli_connect("localhost", "root", "", "simcard");
// $bulan       = mysqli_query($koneksi, "SELECT bulan FROM penjualan WHERE tahun='2017' order by id asc");

//Membuat Query
$q=mysqli_query($koneksi, "SELECT * FROM penduduk");
$a=mysqli_query($koneksi, "SELECT * FROM card");

$man_array=array();
$woman_array=array();
$kind_array=array();
$user_array=array();
while($r=mysqli_fetch_array($q)){
    $man_array[]= $r["man"];
    $woman_array[]= $r["woman"];
}
while($f=mysqli_fetch_array($a)){
    $kind_array[]=$f["kind"];
    $user_array[]= $f["user"];
}

this one highchart code any wrong this code..?no used the color no problem.

$('#view').highcharts({
       chart: {
        type: 'column'
    },
    title: {
        text: 'Stacked column chart'
    },
    xAxis: {
        categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Total'
        },
        stackLabels: {
            enabled: true,
            style: {
                fontWeight: 'bold',
                color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
            }
        }
    },
    legend: {
        align: 'right',
        x: -30,
        verticalAlign: 'top',
        y: 25,
        floating: true,
        backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
        borderColor: '#CCC',
        borderWidth: 1,
        shadow: false
    },
    tooltip: {
        headerFormat: '{point.x}
',
        pointFormat: '{series.name}: {point.y}
Total: {point.stackTotal}'
    },
    plotOptions: {
        column: {
            //stacking: 'normal',
            dataLabels: {
                enabled: true,
                color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
            }
        }
    },

This Page View source html series.

series: [{
    name: 'Man',
    data: []

  }, {
    name: 'Women',
    data: []

  }, {
    name: 'Kind',
     data: []
  }, {
    name: 'User',
    data:[]
  }]

    });
});

Body:
your chart will come like this,Fiddle sample. So replace with code below. Also check Data from a database

<?php
    $man_array=array();
    $woman_array=array();
    $kind_array=array();
    $user_array=array();
    while($r=mysqli_fetch_array($q)){
        $man_array[]= $r["man"];
        $woman_array[]= $r["woman"];
    }
    while($f=mysqli_fetch_array($a)){
        $kind_array[]=$f["kind"];
        $user_array[]= $f["user"];
    }

    ?>
  series: [{
    name: 'Man',
    data: <?php echo json_encode($man_array,JSON_NUMERIC_CHECK) ?>,
    color: 'red'
  }, {
    name: 'Women',
    data: <?php echo json_encode($woman_array,JSON_NUMERIC_CHECK) ?>,

    color: 'black'
  }, {
    name: 'Kind',
    data: <?php echo json_encode($kind_array,JSON_NUMERIC_CHECK) ?>,
    color: 'green'
  }, {
    name: 'User',
    data:<?php echo json_encode($user_array,JSON_NUMERIC_CHECK) ?>,
    color: 'blue'
  }]


问:
gitk show "future" branches?
If I use gitk to look at a commit object it lists under Branches (in the lower left pane) all the children of this branch to which I can navigate upwards (as long as they are not nameless commits but actually have branch names).

Why? IMHO this is not logical and not useful because it violates the chronology of events (how thinsg got committed into the repository).

Suppose I have a a tree which look like this:

o   branch 'Left' (commit 3)

| o branch 'Right' (commit 2)

|/

o commit 1

|

o branch 'base'

Now, if I select commit 1, then under 'Branches:' I will see:

  Branches: Left, Right

  Follows: base

What is the point of this? The commit 1 object is part of the base branch, it's not part of the Left branch, nor the Right branch, simply because at the time it was created Left and Right did not exist yet. So everything that gets merged or committed to Left and Right LATER will be part of Left or Right, NOT commit 1. So then how can the branches that commit 1 is part of include Left and Right?

Someone please explain what I am missing here, because coming from a ClearCase background  it does not make sense to me at all...

Thanks!

答:
Thanks to this information, you know that the changes introduced in the selected commit are included in all the branches figuring there.

I can think of situations where I would like to know in which branches the commit applies (or rather, if a given branch includes the selected commit). You could always follow the lines in gitk, but that can be cumbersome with long branches.

Sometimes I would like to do the opposite, select a commit and see if another previous commit applies there. There is no practical way to do that as far as I know, so selecting the other previous commit and checking the "Branches" field is a nice substitute.

Title: gitk show "future" branches?


问:
defining the type of a function- int and float on haskell
I have a problem with defining the type of a function. In the cases of 1, 10, 11 and 12, I insert an Int and return a float, but in the case in which I insert an Int and return an Int the types doesn't match.
I tried with
pointsForSeventy:: Int->Float and also with pointsForSeventy:: Real a-> Int->a (I thought this one would work because Integrals and Fractionals are inside the Real numbers)

```<code>pointsForSeventy 1 = 5.5
pointsForSeventy 10 = 0.5
pointsForSeventy 11 = 0.5
pointsForSeventy 12 = 0.5
pointsForSeventy a = a
</code>```

Thanks in advance

答:
You need an explicit conversion:

```<code>pointsForSeventy 1 = 5.5
pointsForSeventy 10 = 0.5
pointsForSeventy 11 = 0.5
pointsForSeventy 12 = 0.5
pointsForSeventy a = fromIntegral a
</code>```

Unlike several other programming languages, Haskell will never automatically perform automatic or implicit conversion between numeric types.

On the other hand, numeric literals belong to any numeric type. E.g. 1/2*0.5 :: Double will return 0.25 since all the three literals are Doubles. In some languages like C, instead, 1/2*0.5 evaluates to 0 since 1/2 is integer division (!), and evaluates to 0.

Body:
I have a problem with defining the type of a function. In the cases of 1, 10, 11 and 12, I insert an Int and return a float, but in the case in which I insert an Int and return an Int the types doesn't match.
I tried with
pointsForSeventy:: Int->Float and also with pointsForSeventy:: Real a-> Int->a (I thought this one would work because Integrals and Fractionals are inside the Real numbers)

pointsForSeventy 1 = 5.5
pointsForSeventy 10 = 0.5
pointsForSeventy 11 = 0.5
pointsForSeventy 12 = 0.5
pointsForSeventy a = a

Thanks in advance

Body:
You need an explicit conversion:

pointsForSeventy 1 = 5.5
pointsForSeventy 10 = 0.5
pointsForSeventy 11 = 0.5
pointsForSeventy 12 = 0.5
pointsForSeventy a = fromIntegral a

Unlike several other programming languages, Haskell will never automatically perform automatic or implicit conversion between numeric types.

On the other hand, numeric literals belong to any numeric type. E.g. 1/2*0.5 :: Double will return 0.25 since all the three literals are Doubles. In some languages like C, instead, 1/2*0.5 evaluates to 0 since 1/2 is integer division (!), and evaluates to 0.


问:
std::list::erase(iter) exception handling c++
I try to get an iterator from a function and then erase an element from a list.

Is there any way to catch that exception?

Is there any way to know if the iterator is valid?

When I run the program with invalid iterator it throws the following exception:

```<code> Exception thrown: read access violation.
 _Right.**_Myproxy** was 0xCCCCCCCC. occurred
</code>```

My func is:

```<code>list<AccountStruct>::const_iterator SearchAccount(list<AccountStruct>& Acc,string p)
{

    for (list<AccountStruct>::const_iterator j = Acc.begin(); j !=Acc.end(); ++j)
    {
        if ((*j).phone == p) return j;
    }

}

void RemoveAccount(list<AccountStruct>& Acc)
{
    string Phone;
    cout << "Enter Phone Number ->" << endl;
    cin >> Phone;
    //cout << "Searching..." << endl;
    list<AccountStruct>::const_iterator iter = SearchAccount(Acc,Phone);
    try
    {
        Acc.erase(iter);
    }
    catch()// <- What to put inside??
    {
        cout << "No Phone Number;" << endl;
    }

}
</code>```

答:
std::list::erase does not throw any exception.

The try block is not necessary. However an invalid iterator will cause undefined behavior.

You could return Acc.end() at after the for loop in SearchAccount and check the returned value against Acc.end instead of using try.

Body:
I try to get an iterator from a function and then erase an element from a list.

Is there any way to catch that exception?

Is there any way to know if the iterator is valid?

When I run the program with invalid iterator it throws the following exception:

 Exception thrown: read access violation.
 _Right.**_Myproxy** was 0xCCCCCCCC. occurred

My func is:

list<AccountStruct>::const_iterator SearchAccount(list<AccountStruct>& Acc,string p)
{

    for (list<AccountStruct>::const_iterator j = Acc.begin(); j !=Acc.end(); ++j)
    {
        if ((*j).phone == p) return j;
    }

}

void RemoveAccount(list<AccountStruct>& Acc)
{
    string Phone;
    cout << "Enter Phone Number ->" << endl;
    cin >> Phone;
    //cout << "Searching..." << endl;
    list<AccountStruct>::const_iterator iter = SearchAccount(Acc,Phone);
    try
    {
        Acc.erase(iter);
    }
    catch()// <- What to put inside??
    {
        cout << "No Phone Number;" << endl;
    }

}


问:
Text goes outside containing div
I have this codepen here, shouldn't the text goes to new line when it reaches the right border of div?

html:

```<code><div class="test">

    <p>dfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodj</p>
</div>
</code>```

css:

```<code>div.test{
    width:400px;
    height:800px;
    border-style: solid;
    border-color: red;
    margin:1px; padding:1px;

}
</code>```

答: You can do  width:auto;, but if you want specific width:400px; you can use word-wrap:break-word or word-wrap:break-all;

Title: Text goes outside containing div

Body:
I have this codepen here, shouldn't the text goes to new line when it reaches the right border of div?

html:

dfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodj

css:

div.test{
    width:400px;
    height:800px;
    border-style: solid;
    border-color: red;
    margin:1px; padding:1px;

}


问:
How to maintain sticky session(session persistence) with docker swarm?
I have one Java based web application which is deployed in jboss-10.1.0(wildfly). I am using docker swarm mode(docker version 1.12.1) to scale my application everything works perfectly but the only issue I am facing is session management.

Now let's take scenario.

I have two instance is running for my application(i.e. App1 and App2).I am using default load balancer provided by docker swarm mode with nginx to redirect my application from chintan.test.com:9080 to chintan.test.com:80 so that I don't need to write down port with my url and I am able to access directly with this URL chintan.test.com.

Now the default load balancer is using RR(Round-Robin algorithm) to serve my web request.So first time I visit the chintan.test.com it goes to App1 instance and display login page I login with credentials and everything works perfectly after few minutes it's switch to App2 and again the login page comes.

Is there any way or tools(should be Open-source) through which I handle sessions ? So at least I login to App1 and stick to App1 until I logout.

Thank you!

答:
Tried using Nginx and HA-Proxy but none of them seems to be work well in SWARM mode. Then I used Traefik in Docker Swarm and it did the trick for me.The only constraint is that Traefik should run on manager node as it needs to be aware of new worker nodes being added or removed. It doesn't require restart also even if you scale up service, add nodes etc.

I have tested the configuration with Docker compose version 3 which is the latest and deployed using Docker stack deploy.Step by step instructions are over here

To start off you need to create a docker-compose.yml (version 3) and add the load balancer Traefik Image. This is how it looks like

```<code>   loadbalancer:
image: traefik
command: --docker \
  --docker.swarmmode \
  --docker.watch \
  --web \
  --loglevel=DEBUG
ports:
  - 80:80
  - 9090:8080
volumes:
  - /var/run/docker.sock:/var/run/docker.sock
deploy:
  restart_policy:
    condition: any
  mode: replicated
  replicas: 1
  update_config:
    delay: 2s
  placement:
     constraints: [node.role == manager]
</code>```

and then the Image for which you need session stickiness

```<code>whoami:
image: tutum/hello-world
networks:
  - net
ports:
  - "80"
deploy:
  restart_policy:
    condition: any
  mode: replicated
  replicas: 5
  placement:
    constraints: [node.role == worker]
  update_config:
    delay: 2s
  labels:
    - "traefik.docker.network=test_net"
    - "traefik.port=80"
    - "traefik.frontend.rule=PathPrefix:/hello;"
    - "traefik.backend.loadbalancer.sticky=true"
</code>```

You can follow this link for a detailed explanation.

Body:
Tried using Nginx and HA-Proxy but none of them seems to be work well in SWARM mode. Then I used Traefik in Docker Swarm and it did the trick for me.The only constraint is that Traefik should run on manager node as it needs to be aware of new worker nodes being added or removed. It doesn't require restart also even if you scale up service, add nodes etc.

I have tested the configuration with Docker compose version 3 which is the latest and deployed using Docker stack deploy.Step by step instructions are over here

To start off you need to create a docker-compose.yml (version 3) and add the load balancer Traefik Image. This is how it looks like

   loadbalancer:
image: traefik
command: --docker \
  --docker.swarmmode \
  --docker.watch \
  --web \
  --loglevel=DEBUG
ports:
  - 80:80
  - 9090:8080
volumes:
  - /var/run/docker.sock:/var/run/docker.sock
deploy:
  restart_policy:
    condition: any
  mode: replicated
  replicas: 1
  update_config:
    delay: 2s
  placement:
     constraints: [node.role == manager]

and then the Image for which you need session stickiness

whoami:
image: tutum/hello-world
networks:
  - net
ports:
  - "80"
deploy:
  restart_policy:
    condition: any
  mode: replicated
  replicas: 5
  placement:
    constraints: [node.role == worker]
  update_config:
    delay: 2s
  labels:
    - "traefik.docker.network=test_net"
    - "traefik.port=80"
    - "traefik.frontend.rule=PathPrefix:/hello;"
    - "traefik.backend.loadbalancer.sticky=true"

You can follow this link for a detailed explanation.


问:
Is there any pre-built exe/binary for Adobe DNG SDK?
Someone might argue whether its related to photography or not, but since it is related to DNG format, asking here.

I am trying to build a Adobe DNG SDK so that I am able to convert many different camera raw formats to *.dng format.

I downloaded the Adobe DNG SDK source for here. When extracted it, found a workspace to build that source code. It had many dependencies which I tried to get and build the DNG SDK, but no success, I keep getting errors.

Is there any place where I can get a pre-built DNG SDK or some kind of Windows/Linux binary for it?

答:
Just went through the same nightmare on Windows 10, and came out the other side less than an hour ago. Here's what I found you have to do, to anyone who ever wants to use the DNG SDK.

Get MS Visual Studio 2013... not later versions!

Follow instructions of the README.txt in the DNG SDK folder

Open dng_sdk projects in VS

Set configuration to x64 (not sure if vital, not willing to test it)

Change project properties:
Platform Toolset to "Visual Studio 2013 (v120)"... will not work with v141!

Build

At this point you should be all set. I had a problem with the output directory not matching the location that VS thought it was, so I had to use the MS Build output statements to find the dng_validate.exe, copy it into the working directory, and run it from cmd. The .lib built just fine for me on these settings.

Hope you have a much nicer experience than my few hours of tearing my hair out over compile errors that seemed to be written into the code, but were just the result of an incorrect setup!

OwnerDisplayName: goldenmean


问:
SQL: Write a query that given a varchar, find if it exists in column A or column B
Suppose I have a table with two columns, A and B

```<code>CREATE table test(
    A VARCHAR(20)
    B VARCHAR(20)
);

INSERT into A
VALUES
('cat'), ('dog'),('cow'), ('horse')

INSERT into A
VALUES
('chicken'), ('steve'),('fish'), ('eel')
</code>```

I want to write a query where given a varchar, it would return the column name where it exists (returns an empty varchar if neither). A and B does not have any identical varchars. I'm relatively new with mySql.

find('cat') returns 'A'

find('eel') returns 'B'

find('goat') returns ''

答:
Try this</p>

```<code>SELECT
CASE WHEN A='input' THEN 'A'
     WHEN B='input' THEN 'B'
     ELSE '' END AS 'ColumnName'
FROM test WHERE A = 'yourString' OR B = 'yourString'
</code>```

Body:
Suppose I have a table with two columns, A and B

CREATE table test(
    A VARCHAR(20)
    B VARCHAR(20)
);

INSERT into A
VALUES
('cat'), ('dog'),('cow'), ('horse')

INSERT into A
VALUES
('chicken'), ('steve'),('fish'), ('eel')

I want to write a query where given a varchar, it would return the column name where it exists (returns an empty varchar if neither). A and B does not have any identical varchars. I'm relatively new with mySql.

find('cat') returns 'A'

find('eel') returns 'B'

find('goat') returns ''

Body:
Try this

SELECT
CASE WHEN A='input' THEN 'A'
     WHEN B='input' THEN 'B'
     ELSE '' END AS 'ColumnName'
FROM test WHERE A = 'yourString' OR B = 'yourString'


问:
Which layer do repository interfaces belong when using DI?
I recently joined a large team/project that uses the repository pattern and dependency injection throughout the solution. I noticed that the repository interfaces were located in a Data layer project, requiring the Business layer project to depend directly on it. It is my understanding that when using DI you would want to reverse this dependency to decouple the business logic from data access (Data references interfaces from the Business layer). When I suggested this to the team, there was a mixed reaction. They didn't see the benefit and argued against it ("everyone knows not to directly reference the concrete types", "we'll never need to swap out our data access technology", etc.).

Is it good practice to keep repository interfaces in the same project as the implementation (Data layer)? If the Business layer only references the repository interfaces from Data layer, are there any drawbacks to this setup?

答:
Well personally I've always had the dependencies "flowing" from the lowest level to the highest level. The UI needs to interact with business logic, therefore it depends on  the services interfaces. The services/business logic needs data access, therefore it depends on the repository interfaces to do so.

This is the general approach I've seen in most codebases.