问:
How to print All rows in jtable
example data:
These are my 2 rows in jtable

```<code>[john, carter, post, add]
[smith, sale, col, late]

  for (int count = 0; count < dataModel.getRowCount(); count++){
  data.add(dataModel.getValueAt(count, 0).toString());
   }
  System.out.println(data);
</code>```

When I run this code i get output:

```<code>[john, smith]
</code>```

My question is how can i print the entire row rather than just the first column.
So the output should be:

```<code>[john, carter, post, add]
</code>```

答:
If you use DefaultTableModel you can get all table data by getDataVector():

Returns the Vector of Vectors that contains the table's data values.
  The vectors contained in the outer vector are each a single row

Retrieve a vector representing a single row by (Vector)getDataVector().elementAt(rowNumber)

Title: How to print All rows in jtable

Body:
example data:
These are my 2 rows in jtable

[john, carter, post, add]
[smith, sale, col, late]

  for (int count = 0; count < dataModel.getRowCount(); count++){
  data.add(dataModel.getValueAt(count, 0).toString());
   }
  System.out.println(data);

When I run this code i get output:

[john, smith]

My question is how can i print the entire row rather than just the first column.
So the output should be:

[john, carter, post, add]


来源: stackexchange

问:
How to sum values in column, linked to another column
I have a data set that looks like this:

```<code>                                       Company Year                       Name   Position Gender     Sales     rdb rdbpersal Directors Executives Employees
1          Johnson & Johnson 2016          Dominic J. Caruso  Executive      0  71891000 9095000     12,65         9          9    126400
2          Johnson & Johnson 2016              Joaquin Duato  Executive      0  71891000 9095000     12,65         9          9    126400
3          Johnson & Johnson 2016            Peter M. Fasolo  Executive      0  71891000 9095000     12,65         9          9    126400
4          Johnson & Johnson 2015                Alex Gorsky  Executive      0  71891000 9095000     12,65         9          9    126400
5          Johnson & Johnson 2015             Jorge Mesquita  Executive      0  71891000 9095000     12,65         9          9    126400
6          Johnson & Johnson 2015         Sandra E. Peterson  Executive      1  71891000 9095000     12,65         9          9    126400
7          Johnson & Johnson 2015                Gary Pruden  Executive      0  71891000 9095000     12,65         9          9    126400
8          Johnson & Johnson 2014            Paulus Stoffels  Executive      0  71891000 9095000     12,65         9          9    126400
9          Johnson & Johnson 2014         Michael H. Ullmann  Executive      0  71891000 9095000     12,65         9          9    126400
1
</code>```

I would like to plot the number of male/female executives over the years. Since I only have a dummy variable, I would like to count the amount of "0" or "1" for each year and company and draw them.

How can I do something like sum(data$Gender) "IF" (data$Year=same) "AND" (data$Company=same) ?

答:
```<code>library(dplyr)

df %>% group_by(company,year) %>% summarise(n.gender = sum(gender))
</code>```

<p>The data you provided only has one company. This will give you sum of "1" for each group. </p>

ContentLicense: CC BY-SA 3.0

Body:
I have a data set that looks like this:

                                       Company Year                       Name   Position Gender     Sales     rdb rdbpersal Directors Executives Employees
1          Johnson & Johnson 2016          Dominic J. Caruso  Executive      0  71891000 9095000     12,65         9          9    126400
2          Johnson & Johnson 2016              Joaquin Duato  Executive      0  71891000 9095000     12,65         9          9    126400
3          Johnson & Johnson 2016            Peter M. Fasolo  Executive      0  71891000 9095000     12,65         9          9    126400
4          Johnson & Johnson 2015                Alex Gorsky  Executive      0  71891000 9095000     12,65         9          9    126400
5          Johnson & Johnson 2015             Jorge Mesquita  Executive      0  71891000 9095000     12,65         9          9    126400
6          Johnson & Johnson 2015         Sandra E. Peterson  Executive      1  71891000 9095000     12,65         9          9    126400
7          Johnson & Johnson 2015                Gary Pruden  Executive      0  71891000 9095000     12,65         9          9    126400
8          Johnson & Johnson 2014            Paulus Stoffels  Executive      0  71891000 9095000     12,65         9          9    126400
9          Johnson & Johnson 2014         Michael H. Ullmann  Executive      0  71891000 9095000     12,65         9          9    126400
1

I would like to plot the number of male/female executives over the years. Since I only have a dummy variable, I would like to count the amount of "0" or "1" for each year and company and draw them.

How can I do something like sum(data$Gender) "IF" (data$Year=same) "AND" (data$Company=same) ?

Body:
library(dplyr)

df %>% group_by(company,year) %>% summarise(n.gender = sum(gender))

The data you provided only has one company. This will give you sum of "1" for each group.


问:
Django - how to add data using conditional statement in a separate python script
Purpose/Intension

I have created Django Model with the result being an sqlite3 database. I now want to use a separate python script to add to that database based on some conditional logic.

Problem

I am new to Django and Python so I am not sure how to interrogate the database and then add some values based on the return result from that interrogation using a separate python script.

This is my Models.py:

```<code>from django.db import models
from django.utils import timezone
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User

# Create your models here.
class Author(models.Model):
    '''
    Model representing the Author of the stocknote.
    '''
    user_id = models.ForeignKey('auth.User')
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Stock(models.Model):
    '''
    Model representing the stock info.
    '''
    author = models.ForeignKey(Author)
    ticker_code = models.CharField(max_length=10, null=True, blank=True)
    latest_stock_price = models.DecimalField(max_digits=20, decimal_places=4, null=True, blank=True)
    datetime_of_last_quote = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.ticker_code

class Note(models.Model):
    '''
    Model representing the Authors note.
    '''
    author = models.ForeignKey(Author)
    note = models.TextField()
    ticker_code = models.ForeignKey(Stock)
    date_note_created = models.DateTimeField(default=timezone.now)
    alert_price = models.DecimalField(max_digits=20, decimal_places=4, null=True, blank=True)

    def __str__(self):
        return self.note
</code>```

Now imagine I have added data into the database so it contains data in all the fields except for the field 'latest_stock_price' which is empty.

What i want to do in a separate python script - lets call it interrogate-db.py - is have programatic logic like so:

```<code>If 'GOOG' is in 'ticker_code' then
   add '1.234' to the latest_stock_price for GOOJ
</code>```

The best i could achieve in writing interrogate-db.py is:

```<code>import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject_project.settings')
import django
django.setup()
from myproject.models import Author, Stock, Note

def add_latest_price():
    for t in Stock.objects.values_list('ticker_code'):
        if 'GOOJ' in t:
            ...What goes here?...
</code>```

What should be the syntax to add 1.234 to latest_stock_price if GOOJ is in t?

答:
```<code>for stock in Stock.objects.all():
    if stock.ticker_code == 'GOOJ':
        stock.latest_stock_price = 1.234
        stock.save()
</code>```

Or

```<code>Stock.objects.filter(ticker_code='GOOJ').update(latest_stock_price=1.234)
</code>```

Body:
Purpose/Intension

I have created Django Model with the result being an sqlite3 database. I now want to use a separate python script to add to that database based on some conditional logic.

Problem

I am new to Django and Python so I am not sure how to interrogate the database and then add some values based on the return result from that interrogation using a separate python script.

This is my Models.py:

from django.db import models
from django.utils import timezone
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User

# Create your models here.
class Author(models.Model):
    '''
    Model representing the Author of the stocknote.
    '''
    user_id = models.ForeignKey('auth.User')
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Stock(models.Model):
    '''
    Model representing the stock info.
    '''
    author = models.ForeignKey(Author)
    ticker_code = models.CharField(max_length=10, null=True, blank=True)
    latest_stock_price = models.DecimalField(max_digits=20, decimal_places=4, null=True, blank=True)
    datetime_of_last_quote = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.ticker_code

class Note(models.Model):
    '''
    Model representing the Authors note.
    '''
    author = models.ForeignKey(Author)
    note = models.TextField()
    ticker_code = models.ForeignKey(Stock)
    date_note_created = models.DateTimeField(default=timezone.now)
    alert_price = models.DecimalField(max_digits=20, decimal_places=4, null=True, blank=True)

    def __str__(self):
        return self.note

Now imagine I have added data into the database so it contains data in all the fields except for the field 'latest_stock_price' which is empty.

What i want to do in a separate python script - lets call it interrogate-db.py - is have programatic logic like so:

If 'GOOG' is in 'ticker_code' then
   add '1.234' to the latest_stock_price for GOOJ

The best i could achieve in writing interrogate-db.py is:

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject_project.settings')
import django
django.setup()
from myproject.models import Author, Stock, Note

def add_latest_price():
    for t in Stock.objects.values_list('ticker_code'):
        if 'GOOJ' in t:
            ...What goes here?...

What should be the syntax to add 1.234 to latest_stock_price if GOOJ is in t?

Body:
for stock in Stock.objects.all():
    if stock.ticker_code == 'GOOJ':
        stock.latest_stock_price = 1.234
        stock.save()

Or

Stock.objects.filter(ticker_code='GOOJ').update(latest_stock_price=1.234)


问:
Core-Data: How to set up relationship from one object to specific one in many objects with same name?
I have a question in core data:

there are 2 Entities in the project, Books and Pages;
there are 3 Objects books user created in Entity Books;
there are several Objects pages user created in Entity Pages;
relationship inbetween is one page belongs to one book, one book has many pages.

and my question: there are 3 book with the same object name "book",and each has unique attribute .bookName : @"metal" ;@"plastic" ;@"glass". how to set page to the book with .bookName = @"glass" ?

```<code>    //In BookViewController
    Books *book = (Books *)[NSEntityDescription insertNewObjectForEntityForName:@"Books" inManagedObjectContext:managedObjectContext];
    //textView.text is user input text
    book.bookName = textView.text;

    //In PageViewController
    Pages *page = (Pages *)[NSEntityDescription insertNewObjectForEntityForName:@"Pages" inManagedObjectContext:managedObjectContext];
    page.itsbook = WHAT?
</code>```

Thank you for reading, I stuck here like: a day, really appreciate your help, love you!

答:
If you need to find a specific book then you need to use a NSFetchRequest to ask Core data for it.

Quite some code is needed, so you probably add a convinience method to your Bookclass that looks something like this:

```<code>+(Book*)bookWithName:(NSString*)name
{
    // 0. I assume you have something like this to get the context…
    NSManagedObjectContext* context = [NSManagedObjectContext threadLocalContext];

    // 1. Create an empty request
    NSFetchRequest* request = [[[NSFetchRequest alloc] init] autorelease];

    // 2. Set the entity description for the object to fetch
    NSEntityDescription* entity = [NSEntityDescription entityForName:@"Book"
                                              inManagedObjectContext:context];
    [request setEntity:entity];

    // 3. Set a predicate asking for objects with a mathing bookName property
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"%K LIKE[cd] %@",
                                                              @"bookName",
                                                              name];
    [request setPredicate:predicate];

    // 4. Execute the request on the managed object context.
    NSArray* objects = [context executeFetchRequest:request error:NULL];

    // 5. Result is an array, maybe handle empty array and many objects?
    return [objects lastObject];
 }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a question in core data:

there are 2 Entities in the project, Books and Pages;
there are 3 Objects books user created in Entity Books;
there are several Objects pages user created in Entity Pages;
relationship inbetween is one page belongs to one book, one book has many pages.

and my question: there are 3 book with the same object name "book",and each has unique attribute .bookName : @"metal" ;@"plastic" ;@"glass". how to set page to the book with .bookName = @"glass" ?

    //In BookViewController
    Books *book = (Books *)[NSEntityDescription insertNewObjectForEntityForName:@"Books" inManagedObjectContext:managedObjectContext];
    //textView.text is user input text
    book.bookName = textView.text;

    //In PageViewController
    Pages *page = (Pages *)[NSEntityDescription insertNewObjectForEntityForName:@"Pages" inManagedObjectContext:managedObjectContext];
    page.itsbook = WHAT?

Thank you for reading, I stuck here like: a day, really appreciate your help, love you!

Body:
If you need to find a specific book then you need to use a NSFetchRequest to ask Core data for it.

Quite some code is needed, so you probably add a convinience method to your Bookclass that looks something like this:

+(Book*)bookWithName:(NSString*)name
{
    // 0. I assume you have something like this to get the context…
    NSManagedObjectContext* context = [NSManagedObjectContext threadLocalContext];

    // 1. Create an empty request
    NSFetchRequest* request = [[[NSFetchRequest alloc] init] autorelease];

    // 2. Set the entity description for the object to fetch
    NSEntityDescription* entity = [NSEntityDescription entityForName:@"Book"
                                              inManagedObjectContext:context];
    [request setEntity:entity];

    // 3. Set a predicate asking for objects with a mathing bookName property
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"%K LIKE[cd] %@",
                                                              @"bookName",
                                                              name];
    [request setPredicate:predicate];

    // 4. Execute the request on the managed object context.
    NSArray* objects = [context executeFetchRequest:request error:NULL];

    // 5. Result is an array, maybe handle empty array and many objects?
    return [objects lastObject];
 }


问:
BDD behave Python need to create a World map to hold values
I'm not too familiar with Python but I have setup a BDD framework using Python behave, I now want to create a World map class that holds data and is retrievable throughout all scenarios.

For instance I will have a world class where I can use:

```<code>World w

w.key.add('key', api.response)
</code>```

In one scenario and in another I can then use:

```<code>World w

key = w.key.get('key').
</code>```

Edit:

Or if there is a built in way of using context or similar in behave where the attributes are saved and retrievable throughout all scenarios that would be good.

Like lettuce where you can use world http://lettuce.it/tutorial/simple.html

I've tried this between scenarios but it doesn't seem to be picking it up

```<code>class World(dict):
    def __setitem__(self, key, item):
        self.__dict__[key] = item
        print(item)

    def __getitem__(self, key):
        return self.__dict__[key]
</code>```

Setting the item in one step in scenario A: w.setitem('key', response)

Getting the item in another step in scenario B: w.getitem('key',)

This shows me an error though:

```<code>Traceback (most recent call last):
  File "C:\Program Files (x86)\Python\lib\site-packages\behave\model.py", line 1456, in run
    match.run(runner.context)
  File "C:\Program Files (x86)\Python\lib\site-packages\behave\model.py", line 1903, in run
    self.func(context, *args, **kwargs)
  File "steps\get_account.py", line 14, in step_impl
    print(w.__getitem__('appToken'))
  File "C:Project\steps\world.py", line 8, in __getitem__
    return self.__dict__[key]
KeyError: 'key'
</code>```

It appears that the World does not hold values here between steps that are run.

Edit:

I'm unsure how to use environment.py but can see it has a way of running code before the steps. How can I allow my call to a soap client within environment.py to be called and then pass this to a particular step?

Edit:

I have made the request in environment.py and hardcoded the values, how can I pass variables to environment.py and back?

答:
For this I actually used a config file [config.py] I then added the variables in there and retrieved them using getattr. See below:

```<code>WSDL_URL = 'wsdl'
USERNAME = 'name'
PASSWORD = 'PWD'
</code>```

Then retrieved them like:

```<code>import config

getattr(config, 'USERNAME ', 'username not found')
</code>```

Body:
I'm not too familiar with Python but I have setup a BDD framework using Python behave, I now want to create a World map class that holds data and is retrievable throughout all scenarios.

For instance I will have a world class where I can use:

World w

w.key.add('key', api.response)

In one scenario and in another I can then use:

World w

key = w.key.get('key').

Edit:

Or if there is a built in way of using context or similar in behave where the attributes are saved and retrievable throughout all scenarios that would be good.

Like lettuce where you can use world http://lettuce.it/tutorial/simple.html

I've tried this between scenarios but it doesn't seem to be picking it up

class World(dict):
    def __setitem__(self, key, item):
        self.__dict__[key] = item
        print(item)

    def __getitem__(self, key):
        return self.__dict__[key]

Setting the item in one step in scenario A: w.setitem('key', response)

Getting the item in another step in scenario B: w.getitem('key',)

This shows me an error though:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python\lib\site-packages\behave\model.py", line 1456, in run
    match.run(runner.context)
  File "C:\Program Files (x86)\Python\lib\site-packages\behave\model.py", line 1903, in run
    self.func(context, *args, **kwargs)
  File "steps\get_account.py", line 14, in step_impl
    print(w.__getitem__('appToken'))
  File "C:Project\steps\world.py", line 8, in __getitem__
    return self.__dict__[key]
KeyError: 'key'

It appears that the World does not hold values here between steps that are run.

Edit:

I'm unsure how to use environment.py but can see it has a way of running code before the steps. How can I allow my call to a soap client within environment.py to be called and then pass this to a particular step?

Edit:

I have made the request in environment.py and hardcoded the values, how can I pass variables to environment.py and back?

Body:
For this I actually used a config file [config.py] I then added the variables in there and retrieved them using getattr. See below:

WSDL_URL = 'wsdl'
USERNAME = 'name'
PASSWORD = 'PWD'

Then retrieved them like:

import config

getattr(config, 'USERNAME ', 'username not found')


问:
Openmp and reduction on std::vector?
I want to make this code parallel:

```<code>std::vector<float> res(n,0);
std::vector<float> vals(m);
std::vector<float> indexes(m);
// fill indexes with values in range [0,n)
// fill vals and indexes
for(size_t i=0; i<m; i++){
  res[indexes[i]] += //something using vas[i];
}
</code>```

In this article it's suggested to use:

```<code>#pragma omp parallel for reduction(+:myArray[:6])
</code>```

In this question the same approach is proposed in the comments section.

I have two questions:

I don't know m at compile time, and from these two examples it seems that's required. Is it so? Or if I can use it for this case, what do I have to replace ? with in the following command #pragma omp parallel for reduction(+:res[:?]) ? m or n?

Is it relevant that the indexes of the for are relative to indexes and vals and not to res, especially considering that reduction is done on the latter one?

However,  If so, how can I solve this problem?

答:
It is fairly straight forward to do a user declared reduction for C++ vectors of a specific type:

```<code>#include <algorithm>
#include <vector>

#pragma omp declare reduction(vec_float_plus : std::vector<float> : \
                              std::transform(omp_out.begin(), omp_out.end(), omp_in.begin(), omp_out.begin(), std::plus<float>())) \
                    initializer(omp_priv = decltype(omp_orig)(omp_orig.size()))

std::vector<float> res(n,0);
#pragma omp parallel for reduction(vec_float_plus : res)
for(size_t i=0; i<m; i++){
    res[...] += ...;
}
</code>```

1a) Not knowing m at compile time is not a requirement.

1b) You cannot use the array section reduction on std::vectors, because they are not arrays (and std::vector::data is not an identifier). If it were possible, you'd have to use n, as this is the number of elements in the array section.

2) As long as you are only reading indexes and vals, there is no issue.

Edit: The original initializer caluse was simpler: initializer(omp_priv = omp_orig). However, if the original copy is then not full of zeroes, the result will be wrong. Therefore, I suggest the more complicated initializer which always creates zero-element vectors.

Title: Openmp and reduction on std::vector?

Body:
I want to make this code parallel:

std::vector<float> res(n,0);
std::vector<float> vals(m);
std::vector<float> indexes(m);
// fill indexes with values in range [0,n)
// fill vals and indexes
for(size_t i=0; i<m; i++){
  res[indexes[i]] += //something using vas[i];
}

In this article it's suggested to use:

#pragma omp parallel for reduction(+:myArray[:6])

In this question the same approach is proposed in the comments section.

I have two questions:

I don't know m at compile time, and from these two examples it seems that's required. Is it so? Or if I can use it for this case, what do I have to replace ? with in the following command #pragma omp parallel for reduction(+:res[:?]) ? m or n?

Is it relevant that the indexes of the for are relative to indexes and vals and not to res, especially considering that reduction is done on the latter one?

However,  If so, how can I solve this problem?

Body:
It is fairly straight forward to do a user declared reduction for C++ vectors of a specific type:

#include <algorithm>
#include <vector>

#pragma omp declare reduction(vec_float_plus : std::vector<float> : \
                              std::transform(omp_out.begin(), omp_out.end(), omp_in.begin(), omp_out.begin(), std::plus<float>())) \
                    initializer(omp_priv = decltype(omp_orig)(omp_orig.size()))

std::vector<float> res(n,0);
#pragma omp parallel for reduction(vec_float_plus : res)
for(size_t i=0; i<m; i++){
    res[...] += ...;
}

1a) Not knowing m at compile time is not a requirement.

1b) You cannot use the array section reduction on std::vectors, because they are not arrays (and std::vector::data is not an identifier). If it were possible, you'd have to use n, as this is the number of elements in the array section.

2) As long as you are only reading indexes and vals, there is no issue.

Edit: The original initializer caluse was simpler: initializer(omp_priv = omp_orig). However, if the original copy is then not full of zeroes, the result will be wrong. Therefore, I suggest the more complicated initializer which always creates zero-element vectors.

ContentLicense: CC BY-SA 4.0


问:
Why Flask session is not working in heroku?
I just created one web app with the help of Flask and Heroku but when I started using session for log in stuff then in local (in my computer) its working fine but when I deployed it on heroku then its showing error: Internal Server Error

Can anyone help me with this ?

```<code>@app.route('/')
def home():
    ''' Home page'''
    if 'username' in session:
        session['logged_in'] = True
    else:
        session['logged_in'] = False
    return render_template('home.html')
</code>```

As soon as it come to 'if' line then server stops and shows error but if i run this locally then it works fine. I just pasted the small part of my code showing where it shows error.

Is it possible that for heroku we need to implement it differently or heroku doesn't support session.

答: Check if you have set app.config['SECRET_KEY']. If not, flask will report an error.

Body:
I just created one web app with the help of Flask and Heroku but when I started using session for log in stuff then in local (in my computer) its working fine but when I deployed it on heroku then its showing error: Internal Server Error

Can anyone help me with this ?

@app.route('/')
def home():
    ''' Home page'''
    if 'username' in session:
        session['logged_in'] = True
    else:
        session['logged_in'] = False
    return render_template('home.html')

As soon as it come to 'if' line then server stops and shows error but if i run this locally then it works fine. I just pasted the small part of my code showing where it shows error.

Is it possible that for heroku we need to implement it differently or heroku doesn't support session.


问:
What does this expression mean in nginx rewrite module?
I am encouted a regular in Nginx rewrite config:

```<code>location /main {
    root   /home/hldev/hldata/frontend/credit-system-frontend/dist;
    rewrite ^/(?!js|css).*$ /main/index.html break;
}
</code>```

the ^ match the start of the url,the $ match the end of the url,the * present one or more,but what the whole expression meaning?

答:
^/(?!js|css).*$ means: for each string starting (^) with a slash (/) that is not followed by "js" or "css" ((?!js|css)), consider all the characters (.*) until the end ($).

Basically, all the relative paths that do not start with "js" or "css".

Body:
I am encouted a regular in Nginx rewrite config:

location /main {
    root   /home/hldev/hldata/frontend/credit-system-frontend/dist;
    rewrite ^/(?!js|css).*$ /main/index.html break;
}

the ^ match the start of the url,the $ match the end of the url,the * present one or more,but what the whole expression meaning?


问:
How to save tensorflow specific variable to local disk as a ndarray?(not layer parameter,just a variable, or tensor)
How to save tensorflow specific variable to local disk as a ndarray?(not layer parameter,just a variable, or tensor)
Like :  </p>

```<code>ux=tf.Variable([10,1600,1,2])

tf.save('ux.npy',ux)
</code>```

<p>Is there anything like the code above? And after that I can load the ux.npy like: </p>

```<code>ux = numpy.load('ux.npy')
</code>```

答:
Numpy has save and load function itself so for saving the numpy array you can use its function. The syntax is:</p>

```<code>numpy.savetxt(Out_file_name, numpy_to_save)
</code>```

Body:
How to save tensorflow specific variable to local disk as a ndarray?(not layer parameter,just a variable, or tensor)
Like :

ux=tf.Variable([10,1600,1,2])

tf.save('ux.npy',ux)

Is there anything like the code above? And after that I can load the ux.npy like:

ux = numpy.load('ux.npy')

Body:
Numpy has save and load function itself so for saving the numpy array you can use its function. The syntax is:

numpy.savetxt(Out_file_name, numpy_to_save)


问:
Partition keys update

using cassandra 2.2.8

my challenge is as follows. In my database we've bunch of tables with millions of rows. Unfortunately, due to loose design partition keys on few tables have grown in Gigabytes in size - this is causing negative pressure on system and issues like jvm out-of-memory/node crashes are happening.

we need to redesign the partition keys on few tables. we've data in tables that we would need to retain/or migration to new table.

I'm looking for solution that enables me to export data from source table to  target table (i.e. with re-designed composite partitioned keys); I hope this would help spread partitions in more balance manner.

I tried to use COPY[tablename(column1,column2...)] command but that is probing number of nodes , causing pressure on system/heap i.e. affecting application.  I'm seeking guidance here  as how best i can address this challenge - thank you in advance for any help.

答:
Since you have very big tables and already failed at using COPY, you must export and import your data manually. To perform such task you need to use the TOKEN function.

With some small client code you can write queries to perform a full table data extraction with something like:

```<code>SELECT * FROM mytable WHERE token(pk) >= MIN_TOKEN AND TOKEN(pk) < MIN_TOKEN + QUERY_INTERVAL;
SELECT * FROM mytable WHERE token(pk) >= MIN_TOKEN + QUERY_INTERVAL AND TOKEN(pk) < MIN_TOKEN + 2*QUERY_INTERVAL;
....
SELECT * FROM mytable WHERE token(pk) >= MAX_TOKEN - QUERY_INTERVAL AND TOKEN(pk) < MIN_TOKEN;
</code>```

where MIN_TOKEN and MAX_TOKEN are both the constant minimum and the maximum token value of your cluster partitioner, and QUERY_INTERVAL is the range window you want to query. The bigger the QUERY_INTERVAL, the more data you will fetch in a single query (and more likely trigger a timeout).

Please note that Cassandra never allows a range operator (> >= <= <) in the WHERE clause on partition key column specifiers. The exception is with the use of the TOKEN function.

I also suggest these readings:

Understanding the Token Function in Cassandra

Displaying rows from an unordered partitioner with the TOKEN function

Title: Partition keys update

Body:
Since you have very big tables and already failed at using COPY, you must export and import your data manually. To perform such task you need to use the TOKEN function.

With some small client code you can write queries to perform a full table data extraction with something like:

SELECT * FROM mytable WHERE token(pk) >= MIN_TOKEN AND TOKEN(pk) < MIN_TOKEN + QUERY_INTERVAL;
SELECT * FROM mytable WHERE token(pk) >= MIN_TOKEN + QUERY_INTERVAL AND TOKEN(pk) < MIN_TOKEN + 2*QUERY_INTERVAL;
....
SELECT * FROM mytable WHERE token(pk) >= MAX_TOKEN - QUERY_INTERVAL AND TOKEN(pk) < MIN_TOKEN;

where MIN_TOKEN and MAX_TOKEN are both the constant minimum and the maximum token value of your cluster partitioner, and QUERY_INTERVAL is the range window you want to query. The bigger the QUERY_INTERVAL, the more data you will fetch in a single query (and more likely trigger a timeout).

Please note that Cassandra never allows a range operator (> >= <= <) in the WHERE clause on partition key column specifiers. The exception is with the use of the TOKEN function.

I also suggest these readings:

Understanding the Token Function in Cassandra

Displaying rows from an unordered partitioner with the TOKEN function


问:
SQL Identity Column out of step
We have a set of databases that have a table defined with an Identity column as the primary key. As a sub-set of these are replicated to other servers, a seed system was created so that they could never clash. That system was by using a starting seed with an increment of 50.

In this way the table on DB1 would generate 30001, 30051 etc, where Database2 would generate 30002, 30052 and so on.

I am looking at adding another database into this system (it is split for scaling/loading purposes) and have discovered that the identites have got out of sync on one or two of the databases - i.e. database 3 that should have numbers ending in 3, doesn't anymore. The seeding and increments is still correct according to the table design.

I am obviously going to have to work around this problem somehow (probably by setting a high initial value), but can anyone tell me what would cause them to get out of sync like this? From a query on the DB I can see the sequence went as follows: 32403,32453, 32456, 32474, 32524, 32574 and has continued in increments of 50 ever since it went wrong.

As far as I am aware no bulk-inserts or DTS or anything like that has put new data into these tables.

Second (bonus) question - how to reset the identity so that it goes back to what I want it to actually be!

EDIT:

I know the design is in principle a bit ropey - I didn't ask for criticism of it, I just wondered how it could have got out of sync. I inherited this system and changing the column to a GUID - whilst undoubtedly the best theoretical solution - is probably not going to happen. The system evolved from a single DB to multiple DBs when the load got too large (a few hundred GBs currently). Each ID in this table will be referenced in many other places  - sometimes a few hundred thousand times each (multiplied by about 40,000 for each item). Updating all those will not be happening ;-)

答:
To address your question directly,

Why did it get out of sync may be interesting to discuss, but the only result you could draw from the answer would be to prevent it in the future; which is a bad course of action. You will continue to have these and bigger problems unless you deal with the design which has a fatal flaw.

How to set the existing values right is also (IMHO) an invalid question, because you need to do something other than set the values right - it won't solve your problem.

This isn't to disparage you, it's to help you the best way I can think of. Changing the design is less work both short term and long term. Not to change the design is the pathway to FAIL.

OwnerDisplayName: Valerion

Title: SQL Identity Column out of step

LastEditorDisplayName: Valerion

OwnerDisplayName: le dorfier

LastEditorDisplayName: le dorfier


问:
How to update specific property in whole database in MongoDB?
I want to update a property in whole database.
Example I want to update property name if name=='Gaurav' then I want to replace this as name='gsb' in all documents in all collections, whether it is nested objects property. Is there any way to do this without knowing the structure of document, cause in each collection documents are of different structure. I want this query for Node JS.

What I tried is as follows. I am stuck in between.

```<code>var MongoClient = require('mongodb').MongoClient;
var config = require('../config.js');
var async = require('async');
_ = require ('lodash');

MongoClient.connect('mongodb://' + config.db_url + '/' + config.db_name, function(err, db) {
    if(err) throw err;
    db.listCollections().toArray(function(err, collInfos) {
    async.each(collInfos,function(collectionDetails,cb){
        db.collection(collectionDetails.name,function(err, collection){
            if(err){
                    console.log(err)
            }
            else
            {
            collection.find().toArray(function(error, result) {
                            if(error) {
                                console.log(error);
                            }
                            else {
                                    _depthFirstSearch = (collection, input) => {
                                       let type = typeof collection;
                                       if (type === 'string' || type === 'number' || type === 'boolean') {
                                         return _.includes(collection.toString().toLowerCase(), input.toString().toLowerCase());
                                       }
                                       return _.some(collection, (item) => this._depthFirstSearch(item, input));
                                     }
                                    var data= _.filter(result, (item) => {
                                         return _depthFirstSearch(item, "Gaurav");
                                       });

                                    console.log(data)

                            }
            });
        }
    })
    cb();
})
});
});
</code>```

答:
I found the solution after lots of brainstorm. I wrote below function to achieve this.</p>

```<code>var replaceAllInsatnceInDB=function(db_url/*localhost:27017*/,db_name,propName,stringToSearch,stringToReplace){
MongoClient.connect('mongodb://' + db_url + '/' + db_name, function(err, db) {
    if(err) throw err;
      db.listCollections().toArray(function(err, collInfos) {
         async.each(collInfos,function(collectionDetails,cb){
            db.collection(collectionDetails.name,function(err, collection){
            if(err){
                console.log(err)
            }
            else
            {
                collection.find().toArray(function(error, result) {
                    if(error) {
                        console.log(error);
                    }
                    else {
                        result.forEach(function(document){
                        var op=function(record){
                        if(record!== null && record!==undefined ){
                            var props=Object.keys(record);
                            var forObject=function(obj){
                                if(Array.isArray(obj)){
                                var forArray=function(arr){
                                    for(var j=0;j<arr.length;j++){
                                        if(typeof arr[j] ==="string"){
                                            if(arr[j]===stringToSearch  && props[i]==propName){
                                                arr[j]=stringToReplace
                                            }
                                        }
                                        if(typeof arr[j] ==="object"){
                                                                    forObject(arr[j]);
                                                                }

                                                            }
                                                            return(arr)
                                                        }
                                                        obj=forArray(obj)
                                                    }else{
                                                        op(obj);
                                                    }
                                                    return(obj);
                                                }
                                            for(var i=0;i<props.length;i++){
                                                if(typeof record[props[i]] ==="string"){
                                                        if(record[props[i]]===stringToSearch  && props[i]==propName){
                                                            record[props[i]]=stringToReplace
                                                            console.log()
                                                        }
                                                    }
                                                    if(typeof record[props[i]] ==="object"){
                                                        record[props[i]]=forObject(record[props[i]])
                                                    }
                                            }
                                        }
                                            return(record);
                                        }
                                        document=op(document);
                                        collection.update({_id : document._id},document,function(error,doc){
                                            if(error){
                                console.log(error)
                            }else{
                                console.log("template updated");
                            }
                                        })
                                    })

                            }

            });

        }
    })
    cb();
})
});
});
}
</code>```

Body:
I want to update a property in whole database.
Example I want to update property name if name=='Gaurav' then I want to replace this as name='gsb' in all documents in all collections, whether it is nested objects property. Is there any way to do this without knowing the structure of document, cause in each collection documents are of different structure. I want this query for Node JS.

What I tried is as follows. I am stuck in between.

var MongoClient = require('mongodb').MongoClient;
var config = require('../config.js');
var async = require('async');
_ = require ('lodash');

MongoClient.connect('mongodb://' + config.db_url + '/' + config.db_name, function(err, db) {
    if(err) throw err;
    db.listCollections().toArray(function(err, collInfos) {
    async.each(collInfos,function(collectionDetails,cb){
        db.collection(collectionDetails.name,function(err, collection){
            if(err){
                    console.log(err)
            }
            else
            {
            collection.find().toArray(function(error, result) {
                            if(error) {
                                console.log(error);
                            }
                            else {
                                    _depthFirstSearch = (collection, input) => {
                                       let type = typeof collection;
                                       if (type === 'string' || type === 'number' || type === 'boolean') {
                                         return _.includes(collection.toString().toLowerCase(), input.toString().toLowerCase());
                                       }
                                       return _.some(collection, (item) => this._depthFirstSearch(item, input));
                                     }
                                    var data= _.filter(result, (item) => {
                                         return _depthFirstSearch(item, "Gaurav");
                                       });

                                    console.log(data)

                            }
            });
        }
    })
    cb();
})
});
});

Body:
I found the solution after lots of brainstorm. I wrote below function to achieve this.

var replaceAllInsatnceInDB=function(db_url/*localhost:27017*/,db_name,propName,stringToSearch,stringToReplace){
MongoClient.connect('mongodb://' + db_url + '/' + db_name, function(err, db) {
    if(err) throw err;
      db.listCollections().toArray(function(err, collInfos) {
         async.each(collInfos,function(collectionDetails,cb){
            db.collection(collectionDetails.name,function(err, collection){
            if(err){
                console.log(err)
            }
            else
            {
                collection.find().toArray(function(error, result) {
                    if(error) {
                        console.log(error);
                    }
                    else {
                        result.forEach(function(document){
                        var op=function(record){
                        if(record!== null && record!==undefined ){
                            var props=Object.keys(record);
                            var forObject=function(obj){
                                if(Array.isArray(obj)){
                                var forArray=function(arr){
                                    for(var j=0;j<arr.length;j++){
                                        if(typeof arr[j] ==="string"){
                                            if(arr[j]===stringToSearch  && props[i]==propName){
                                                arr[j]=stringToReplace
                                            }
                                        }
                                        if(typeof arr[j] ==="object"){
                                                                    forObject(arr[j]);
                                                                }

                                                            }
                                                            return(arr)
                                                        }
                                                        obj=forArray(obj)
                                                    }else{
                                                        op(obj);
                                                    }
                                                    return(obj);
                                                }
                                            for(var i=0;i<props.length;i++){
                                                if(typeof record[props[i]] ==="string"){
                                                        if(record[props[i]]===stringToSearch  && props[i]==propName){
                                                            record[props[i]]=stringToReplace
                                                            console.log()
                                                        }
                                                    }
                                                    if(typeof record[props[i]] ==="object"){
                                                        record[props[i]]=forObject(record[props[i]])
                                                    }
                                            }
                                        }
                                            return(record);
                                        }
                                        document=op(document);
                                        collection.update({_id : document._id},document,function(error,doc){
                                            if(error){
                                console.log(error)
                            }else{
                                console.log("template updated");
                            }
                                        })
                                    })

                            }

            });

        }
    })
    cb();
})
});
});
}


问:
button sound stops after while
i have created an app with many sound buttons and problem is that after a while they stop working and i have to reset the app. Is there any way to manage it?

```<code>public class TwoFragment extends Fragment{

SoundPool mySound1;
int ayyId;
SoundPool mySound2;
int eyyId;
SoundPool mySound3;
int keId;
SoundPool mySound4;
int kraId;
SoundPool mySound5;
int pandaId;
SoundPool mySound6;
int timeId;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mySound1 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    ayyId = mySound1.load(getActivity().getApplicationContext(), R.raw.ayy, 1);
    mySound2 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    eyyId = mySound2.load(getActivity().getApplicationContext(), R.raw.eyy, 1);
    mySound3 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    keId = mySound3.load(getActivity().getApplicationContext(), R.raw.kee, 1);
    mySound4 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    kraId = mySound4.load(getActivity().getApplicationContext(), R.raw.kraaa, 1);
    mySound5 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    pandaId = mySound5.load(getActivity().getApplicationContext(), R.raw.pandaa, 1);
    mySound6 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    timeId = mySound6.load(getActivity().getApplicationContext(), R.raw.time, 1);
        }
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_two,container,false);
    View v = inflater.inflate(R.layout.fragment_two,container,false);
    Button des1 = (Button) view.findViewById(R.id.des1);
    Button des2 = (Button) view.findViewById(R.id.des2);
    Button des3 = (Button) view.findViewById(R.id.des3);
    Button des4 = (Button) view.findViewById(R.id.des4);
    Button des5 = (Button) view.findViewById(R.id.des5);
    Button des6 = (Button) view.findViewById(R.id.des6);
    des1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {mySound1.play(ayyId, 1, 1, 1, 0, 1);}
    });
    des2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {mySound2.play(eyyId, 1, 1, 1, 0, 1);}
    });
    des3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {mySound3.play(keId, 1, 1, 1, 0, 1);}
    });
    des4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {mySound4.play(kraId, 1, 1, 1, 0, 1);}
    });
    des5.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {mySound5.play(pandaId, 1, 1, 1, 0, 1);}
    });
    des6.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {mySound6.play(timeId, 1, 1, 1, 0, 1);}
    });

    MobileAds.initialize(getActivity(), "ca-app-pub-xxxxxxxxxxxxxxxxxxxx~xxxxxxxx");
    AdView mAdView = (AdView) view.findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

    return view;

}
}
</code>```

also I wanna ask how to stop button from playing when I click another one. thank you

答:
I'd recommend using .release(). According to docs:

Release the SoundPool resources. Release all memory and native resources used by the SoundPool object. The SoundPool can no longer be used and the reference should be set to null.

Also you can keep the playing streamid in arraylist, then clear and play when play button is clicked.

```<code>    List<Integer> streams = new ArrayList<Integer>();
SoundPool pool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);

public void onClick(View view) {
    int streamId = 0;
    stop_clear_stream();
    switch (view.getId()) {
        case R.id.button1:
            streamId = pool.play(soundid1, 1.0f, 1.0f, 1, 0, 1.0f);
            break;
        case R.id.button2:
            streamId = pool.play(soundid2, 1.0f, 1.0f, 1, 0, 1.0f);
            break;
        .
        .
        .
        .
        .

        streams.add(streamId);

    }
}

private void stop_clear_stream() {
    if (streams != null && streams.size() > 0)
        for (Integer stream : streams)
            pool.stop(stream);

    streams.clear();
}
</code>```

I have not tested the above code though.

Title: button sound stops after while

Body:
i have created an app with many sound buttons and problem is that after a while they stop working and i have to reset the app. Is there any way to manage it?

public class TwoFragment extends Fragment{

SoundPool mySound1;
int ayyId;
SoundPool mySound2;
int eyyId;
SoundPool mySound3;
int keId;
SoundPool mySound4;
int kraId;
SoundPool mySound5;
int pandaId;
SoundPool mySound6;
int timeId;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mySound1 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    ayyId = mySound1.load(getActivity().getApplicationContext(), R.raw.ayy, 1);
    mySound2 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    eyyId = mySound2.load(getActivity().getApplicationContext(), R.raw.eyy, 1);
    mySound3 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    keId = mySound3.load(getActivity().getApplicationContext(), R.raw.kee, 1);
    mySound4 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    kraId = mySound4.load(getActivity().getApplicationContext(), R.raw.kraaa, 1);
    mySound5 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    pandaId = mySound5.load(getActivity().getApplicationContext(), R.raw.pandaa, 1);
    mySound6 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    timeId = mySound6.load(getActivity().getApplicationContext(), R.raw.time, 1);
        }
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_two,container,false);
    View v = inflater.inflate(R.layout.fragment_two,container,false);
    Button des1 = (Button) view.findViewById(R.id.des1);
    Button des2 = (Button) view.findViewById(R.id.des2);
    Button des3 = (Button) view.findViewById(R.id.des3);
    Button des4 = (Button) view.findViewById(R.id.des4);
    Button des5 = (Button) view.findViewById(R.id.des5);
    Button des6 = (Button) view.findViewById(R.id.des6);
    des1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {mySound1.play(ayyId, 1, 1, 1, 0, 1);}
    });
    des2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {mySound2.play(eyyId, 1, 1, 1, 0, 1);}
    });
    des3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {mySound3.play(keId, 1, 1, 1, 0, 1);}
    });
    des4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {mySound4.play(kraId, 1, 1, 1, 0, 1);}
    });
    des5.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {mySound5.play(pandaId, 1, 1, 1, 0, 1);}
    });
    des6.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {mySound6.play(timeId, 1, 1, 1, 0, 1);}
    });

    MobileAds.initialize(getActivity(), "ca-app-pub-xxxxxxxxxxxxxxxxxxxx~xxxxxxxx");
    AdView mAdView = (AdView) view.findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

    return view;

}
}

also I wanna ask how to stop button from playing when I click another one. thank you

Body:
I'd recommend using .release(). According to docs:

Release the SoundPool resources. Release all memory and native resources used by the SoundPool object. The SoundPool can no longer be used and the reference should be set to null.

Also you can keep the playing streamid in arraylist, then clear and play when play button is clicked.

    List<Integer> streams = new ArrayList<Integer>();
SoundPool pool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);

public void onClick(View view) {
    int streamId = 0;
    stop_clear_stream();
    switch (view.getId()) {
        case R.id.button1:
            streamId = pool.play(soundid1, 1.0f, 1.0f, 1, 0, 1.0f);
            break;
        case R.id.button2:
            streamId = pool.play(soundid2, 1.0f, 1.0f, 1, 0, 1.0f);
            break;
        .
        .
        .
        .
        .

        streams.add(streamId);

    }
}

private void stop_clear_stream() {
    if (streams != null && streams.size() > 0)
        for (Integer stream : streams)
            pool.stop(stream);

    streams.clear();
}

I have not tested the above code though.


问:
Laravel Select2 Box not filtering
in my Laravel 5.4 app I want to use Select2 to filter for my "Providers" like that:

https://paste.laravel.io/RowKK

The Select2 Box show the correct content but when I start typing the name of a Provider it doesn't filter the correct items.

When using the same on the example pages, this is working.

Any ideas what I make wrong?

Regards

kay899

答:
It will still be your API backend that will do the filtering, all you have to do is to pass the query term via data property in your ajax. Example the params.term was passed to a q property and pulled from the API backend.

Example GitHub Repositories pulling:

function formatRepo (repo) {
  if (repo.loading) return repo.text;
  return repo.full_name
}

function formatRepoSelection (repo) {
  return repo.full_name || repo.text;
}

$(".js-data-example-ajax").select2({
  placeholder: 'Select an item',
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function (params) {
          return {
            q: params.term, // search term
            page: params.page
          };
        },
    processResults: function (data, params) {
            // notice we return the value of more so Select2 knows if more results can be loaded
          //console.log(data.items)
          params.page = params.page || 1;
          return {
            results: data.items,
            pagination: {
              more: (params.page * 30) < data.total_count
            }
          };
        },
    cache: true
  },
  escapeMarkup: function (markup) { return markup; },
  minimumInputLength: 1,
  templateResult: formatRepo,
  templateSelection: formatRepoSelection

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>

<select class="js-data-example-ajax" style="width:500px;">
  <option selected="selected"></option>
</select></code>```

Title: Laravel Select2 Box not filtering

Body:
It will still be your API backend that will do the filtering, all you have to do is to pass the query term via data property in your ajax. Example the params.term was passed to a q property and pulled from the API backend.

Example GitHub Repositories pulling:

function formatRepo (repo) {
  if (repo.loading) return repo.text;
  return repo.full_name
}

function formatRepoSelection (repo) {
  return repo.full_name || repo.text;
}

$(".js-data-example-ajax").select2({
  placeholder: 'Select an item',
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function (params) {
          return {
            q: params.term, // search term
            page: params.page
          };
        },
    processResults: function (data, params) {
            // notice we return the value of more so Select2 knows if more results can be loaded
          //console.log(data.items)
          params.page = params.page || 1;
          return {
            results: data.items,
            pagination: {
              more: (params.page * 30) < data.total_count
            }
          };
        },
    cache: true
  },
  escapeMarkup: function (markup) { return markup; },
  minimumInputLength: 1,
  templateResult: formatRepo,
  templateSelection: formatRepoSelection

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>

<select class="js-data-example-ajax" style="width:500px;">
  <option selected="selected"></option>
</select>


问:
Android developer change all app screens language on button click
I know how to use locale and strings.xml for global locale, in addition I created 3 buttons on rhe main activity with 3 different languages on them, how can I switch the whole strings in all screens in one click, how can I do that? </p>

答:
Step1:
Use a preference to store the locale language and country, if you want this language switching is persistent.

Step2:
Try a function like this

```<code>public void switchLocale(Locale locale) {
    Configuration config = getBaseContext().getResources().getConfiguration();
    if (locale != null && !config.locale.equals(locale)) {
          Locale.setDefault(locale);
          Configuration conf = new Configuration(config);
          conf.locale = locale;
          getBaseContext().getResources().updateConfiguration(conf,
          getBaseContext().getResources().getDisplayMetrics());
    }
  }
</code>```

Step3:
Restart your current activity.

Hope this helps.

Body:
Step1:
Use a preference to store the locale language and country, if you want this language switching is persistent.

Step2:
Try a function like this

public void switchLocale(Locale locale) {
    Configuration config = getBaseContext().getResources().getConfiguration();
    if (locale != null && !config.locale.equals(locale)) {
          Locale.setDefault(locale);
          Configuration conf = new Configuration(config);
          conf.locale = locale;
          getBaseContext().getResources().updateConfiguration(conf,
          getBaseContext().getResources().getDisplayMetrics());
    }
  }

Step3:
Restart your current activity.

Hope this helps.


问:
In Spring-Kafka which method does the same thing like onPartitionsRevoked?
I know that in Sping-Kafka we have below methods:

void registerSeekCallback(ConsumerSeekCallback callback);

void onPartitionsAssigned(Map assignments, ConsumerSeekCallback callback);

void onIdleContainer(Map assignments, ConsumerSeekCallback callback);

But which one it does the same thing like the native ConsumerRebalanceListener method onPartitionsRevoked?

"This method will be called before a rebalance operation starts and
  after the consumer stops fetching data. It is recommended that offsets
  should be committed in this callback to either Kafka or a custom
  offset store to prevent duplicate data."

If I want to implement the ConsumerRebalanceListener, how can I pass the KafkaConsumer reference? I only see the Consumer from Spring-Kafka.

=========update======

Hi,Gary when I add RebalanceListener this into the ContainerProperties. I can see that both methods get triggered. however, I got the exception, saying sth like "Commit cannot be completed since the group has already rebalanced and assigned the partitions to another member. This means that the time between subsequent calls to poll() was longer than the configured max.poll.interval.ms, which typically implies that the poll loop is spending too much time message processing" Do you have any idea?

=========== update 2 ============

```<code>    public ConcurrentMessageListenerContainer<Integer, String> createContainer(
      ContainerProperties containerProps, IKafkaConsumer iKafkaConsumer) {

    Map<String, Object> props = consumerProps();

    DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<Integer, String>(props);

    **RebalanceListner rebalanceListner = new RebalanceListner(cf.createConsumer());**

    CustomKafkaMessageListener ckml = new CustomKafkaMessageListener(iKafkaConsumer, rebalanceListner);

    CustomRecordFilter cff = new CustomRecordFilter();

    FilteringAcknowledgingMessageListenerAdapter faml = new FilteringAcknowledgingMessageListenerAdapter(ckml, cff, true);

    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(5);

    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    backOffPolicy.setBackOffPeriod(1500); // 1.5 seconds

    RetryTemplate rt = new RetryTemplate();
    rt.setBackOffPolicy(backOffPolicy);
    rt.setRetryPolicy(retryPolicy);
    rt.registerListener(ckml);
    RetryingAcknowledgingMessageListenerAdapter rml = new RetryingAcknowledgingMessageListenerAdapter(faml, rt);

    containerProps.setConsumerRebalanceListener(rebalanceListner);
    containerProps.setMessageListener(rml);
    containerProps.setAckMode(AbstractMessageListenerContainer.AckMode.MANUAL_IMMEDIATE);
    containerProps.setErrorHandler(ckml);
    containerProps.setAckOnError(false);
    ConcurrentMessageListenerContainer<Integer, String> container = new ConcurrentMessageListenerContainer<>(
        cf, containerProps);

    container.setConcurrency(1);
    return container;
  }
</code>```

答: You can add a RebalanceListener to the container's ContainerProperties that are passed into the constructor.

Body:
I know that in Sping-Kafka we have below methods:

void registerSeekCallback(ConsumerSeekCallback callback);

void onPartitionsAssigned(Map assignments, ConsumerSeekCallback callback);

void onIdleContainer(Map assignments, ConsumerSeekCallback callback);

But which one it does the same thing like the native ConsumerRebalanceListener method onPartitionsRevoked?

"This method will be called before a rebalance operation starts and
  after the consumer stops fetching data. It is recommended that offsets
  should be committed in this callback to either Kafka or a custom
  offset store to prevent duplicate data."

If I want to implement the ConsumerRebalanceListener, how can I pass the KafkaConsumer reference? I only see the Consumer from Spring-Kafka.

=========update======

Hi,Gary when I add RebalanceListener this into the ContainerProperties. I can see that both methods get triggered. however, I got the exception, saying sth like "Commit cannot be completed since the group has already rebalanced and assigned the partitions to another member. This means that the time between subsequent calls to poll() was longer than the configured max.poll.interval.ms, which typically implies that the poll loop is spending too much time message processing" Do you have any idea?

=========== update 2 ============

    public ConcurrentMessageListenerContainer<Integer, String> createContainer(
      ContainerProperties containerProps, IKafkaConsumer iKafkaConsumer) {

    Map<String, Object> props = consumerProps();

    DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<Integer, String>(props);

    **RebalanceListner rebalanceListner = new RebalanceListner(cf.createConsumer());**

    CustomKafkaMessageListener ckml = new CustomKafkaMessageListener(iKafkaConsumer, rebalanceListner);

    CustomRecordFilter cff = new CustomRecordFilter();

    FilteringAcknowledgingMessageListenerAdapter faml = new FilteringAcknowledgingMessageListenerAdapter(ckml, cff, true);

    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(5);

    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    backOffPolicy.setBackOffPeriod(1500); // 1.5 seconds

    RetryTemplate rt = new RetryTemplate();
    rt.setBackOffPolicy(backOffPolicy);
    rt.setRetryPolicy(retryPolicy);
    rt.registerListener(ckml);
    RetryingAcknowledgingMessageListenerAdapter rml = new RetryingAcknowledgingMessageListenerAdapter(faml, rt);

    containerProps.setConsumerRebalanceListener(rebalanceListner);
    containerProps.setMessageListener(rml);
    containerProps.setAckMode(AbstractMessageListenerContainer.AckMode.MANUAL_IMMEDIATE);
    containerProps.setErrorHandler(ckml);
    containerProps.setAckOnError(false);
    ConcurrentMessageListenerContainer<Integer, String> container = new ConcurrentMessageListenerContainer<>(
        cf, containerProps);

    container.setConcurrency(1);
    return container;
  }


问:
How can I protect a logging object from the garbage collector in a multiprocessing process?
I create a couple of worker processes using Python's Multiprocessing module 2.6.
In each worker I use the standard logging module (with log rotation and file per worker)
to keep an eye on the worker. I've noticed that after a couple of hours that no more
events are written to the log. The process doesn't appear to crash and still responds
to commands via my queue. Using lsof I can see that the log file is no longer open.
I suspect the log object may be killed by the garbage collector, if so is there a way
that I can mark it to protect it?</p>

答: You could run gc.collect() immediately after fork() to see if that causes the log to be closed. But it's not likely garbage collection would take effect only after a few hours.


问:
How to install Xcode source editor extension?
I created a source editor extension but don't understand how to use it. It works fine in debugging version of Xcode (with gray icon) but I cannot find a way to install this extension to "real" Xcode. Documentation is quite obscure for this topic. What I have tried - 1. Build and run host application. 2. Move resulting .appex file into PlugIns directory of Xcode. Nothing worked for me.

I use macOS Sierra and Xcode 8.

答:
Installation:

Archive extension project (Product > Archive).

(From Organizer window) 'Export...' > 'Export as a macOS App'.

Double click the app you just exported, (it will run the App). Quit it. That is the actual install.

A few notes:

If you open 'System Preferences' > Extension, it should show under 'Xcode Source Editor'.

Move extension to the trash, reopen 'System Preferences', extension is gone. Guessing this is the uninstall how to.

Move extension out of the trash and reopen 'System Preferences', it will reappears.

You must run the Extension App at least once. The registration is managed through macOS Launch Services.


问:
How do I push my git repository to dokku?
I'm new to Dokku, where I am using it in conjunction with a DigitalOcean droplet.

I'm following this tutorial.

My problem is that when I go to push my git repository from Github to dokku, I receive this message:

```<code>.git > git push -vvv dokku master
Pushing to dokku@dokku.me:my-rails-app
ssh: connect to host dokku.me port 22: Operation timed out
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

I checked to see if I was connected with Github and I seem to be:

```<code>my-rails-app > ssh -T git@github.com
Enter passphrase for key '/Users/xxxxx/.ssh/id_rsa':
Hi xxxxx! You've successfully authenticated, but GitHub does not provide shell access.
</code>```

I know the repository exists. Any idea why this push times out? What rights might I be missing?

Thanks!

答:
The push dokku master will push to hte remote doku, the one you have added with

```<code>git remote add dokku dokku@dokku.me:ruby-rails-sample
</code>```

So the fact that you are or are not connected to GitHub is not relevant.

You need to make sure ssh -T dokku.me is working.

That supposes of course you have replaced dokku.me by the name of your actual dokku server, as seen in this dokku user management documentation comment.

Body:
I'm new to Dokku, where I am using it in conjunction with a DigitalOcean droplet.

I'm following this tutorial.

My problem is that when I go to push my git repository from Github to dokku, I receive this message:

.git > git push -vvv dokku master
Pushing to dokku@dokku.me:my-rails-app
ssh: connect to host dokku.me port 22: Operation timed out
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I checked to see if I was connected with Github and I seem to be:

my-rails-app > ssh -T git@github.com
Enter passphrase for key '/Users/xxxxx/.ssh/id_rsa':
Hi xxxxx! You've successfully authenticated, but GitHub does not provide shell access.

I know the repository exists. Any idea why this push times out? What rights might I be missing?

Thanks!

Body:
The push dokku master will push to hte remote doku, the one you have added with

git remote add dokku dokku@dokku.me:ruby-rails-sample

So the fact that you are or are not connected to GitHub is not relevant.

You need to make sure ssh -T dokku.me is working.

That supposes of course you have replaced dokku.me by the name of your actual dokku server, as seen in this dokku user management documentation comment.


问:
Using strcpy with a char to a string?
I couldn't figure out how to have an input with spaces stored in a string so I store it in a char first and I want to copy it to the string.

```<code>string name[2]={"Sample name"};
char apname[50];

cout << "Input Name: ";
cin.getline(apname,sizeof(apname));
strcpy (apname,name[2]);
</code>```

If there's an easier way to do this please help me.

答:
This is the better way:

```<code>std::string line;
std::getline(std::cin, line);
std::cout << "You said: " << line << "\n";
</code>```

With error checking, prompting, and repetition, it'd be:

```<code>for (std::string line;
     (std::cout << "Input name: ") && std::getline(std::cin, line); )
{
    std::cout << "You said: " << line << "\n";
}
std::cout << "Goodbye\n";
</code>```

Title: Using strcpy with a char to a string?

Body:
I couldn't figure out how to have an input with spaces stored in a string so I store it in a char first and I want to copy it to the string.

string name[2]={"Sample name"};
char apname[50];

cout << "Input Name: ";
cin.getline(apname,sizeof(apname));
strcpy (apname,name[2]);

If there's an easier way to do this please help me.

Body:
This is the better way:

std::string line;
std::getline(std::cin, line);
std::cout << "You said: " << line << "\n";

With error checking, prompting, and repetition, it'd be:

for (std::string line;
     (std::cout << "Input name: ") && std::getline(std::cin, line); )
{
    std::cout << "You said: " << line << "\n";
}
std::cout << "Goodbye\n";


问:
Has .txt file been closed?
I have a slight problem. I have a project that I'm working on and that requires two programs to read/write into some .txt files.

Python writes into one .txt file, C++ reads from it. C++ does what it needs to do and then writes its own information into another .txt file that Python has to read.

What I want to know is how can I check with C++ if Python has closed the .txt file before opening the same file, as Python may still be writing stuff into it and vice versa?

If you need any extra information about this conundrum, feel free to contact me.

答:
Using the with open() method always closes the file after operations are performed. See section 7.2 in the Input and Output documentation.

```<code>with open(in_file, 'w') as f:
    content = 'Example text'
    f.write(content)
</code>```

Once the above is complete, the file is closed.

Title: Has .txt file been closed?

Body:
Using the with open() method always closes the file after operations are performed. See section 7.2 in the Input and Output documentation.

with open(in_file, 'w') as f:
    content = 'Example text'
    f.write(content)

Once the above is complete, the file is closed.


问:
Memcached Result =0
i have this code from my source

```<code>if ($where != "")
        $where = "WHERE $where";

$res = $mysqli->query("SELECT COUNT(id) FROM torrents $where LIMIT 1") or die(mysql_error());
$row = mysqli_fetch_array($res);
$count = $row[0];
</code>```

i try this is this corect? :

```<code> if ($where != "")

        $where = "WHERE $where";
    $ress = $mysqli->query('SELECT COUNT(id) FROM torrents $where LIMIT 1';) or die(mysql_error());
$nombre ='details'.$ress;
$res = mysqli_query($ress);
$count = array();
while($count = mysqli_fetch_array($res)) $rows[] = $count;
$memcache->set($nombre, $count, 1);
</code>```

Result "sorry pal not found"

答:
```<code>if ($where != "")
      $where = "WHERE $where";
  $res = mysql_query("SELECT COUNT(id) FROM torrents $where LIMIT 100") or die(mysql_error());
$key = md5($res);
$get_data = $memcache->get($key);

if($get_data) {
 echo 'Data Pulled From Cache';
} else {
   while ($row = mysql_fetch_array($res)) {
       $memcache->set($key, $res, TRUE, 3600);
       $count = $row[0];
 }
}
</code>```

While is resolved my prolem

Title: Memcached Result =0

Body:
i have this code from my source

if ($where != "")
        $where = "WHERE $where";

$res = $mysqli->query("SELECT COUNT(id) FROM torrents $where LIMIT 1") or die(mysql_error());
$row = mysqli_fetch_array($res);
$count = $row[0];

i try this is this corect? :

 if ($where != "")

        $where = "WHERE $where";
    $ress = $mysqli->query('SELECT COUNT(id) FROM torrents $where LIMIT 1';) or die(mysql_error());
$nombre ='details'.$ress;
$res = mysqli_query($ress);
$count = array();
while($count = mysqli_fetch_array($res)) $rows[] = $count;
$memcache->set($nombre, $count, 1);

Result "sorry pal not found"

Body:
if ($where != "")
      $where = "WHERE $where";
  $res = mysql_query("SELECT COUNT(id) FROM torrents $where LIMIT 100") or die(mysql_error());
$key = md5($res);
$get_data = $memcache->get($key);

if($get_data) {
 echo 'Data Pulled From Cache';
} else {
   while ($row = mysql_fetch_array($res)) {
       $memcache->set($key, $res, TRUE, 3600);
       $count = $row[0];
 }
}

While is resolved my prolem


问:
I want to create a program in Ocaml that will check if one matrix is contained in the other matrix
```<code>let my_matrix1 = [[1;2];[3;4]];;

let my_matrix2 = [[4;7;8];[3;2;1]];;
</code>```

I have defined two matrices so I can see if the code is working properly.

I have done it for the element:

```<code>let rec does_it_contain lis x =
if (lis = []) then false
else if ((List.hd lis) = x) then true
else does_it_contain (List.tl lis) x;;

let rec does_it matrix x =
if (matrix = []) then false
else if (does_it_contain (List.hd matrix) x = true) then true
else does_it (List.tl matrix) x;;

does_it my_matrix1 2;;
- bool = true
</code>```

And the problem is working, but I'm not sure what went wrong when I tried to do it with the matrices (if one contains the other):

```<code>let rec does_it_contain lis1 lis2 =
if (List.hd lis1 = []) then false
else if (List.hd lis1 = lis2) then true
else does_it_contain (List.tl lis1) lis2;;

let rec does_it matrix lis1 =
if (matrix = []) then false
else if (does_it_contain List. hd matrix List.hd lis1 = true) then true
else does_it (List.tl matrix) lis1;;

does_it my_matrix1 my_matrix2;;
</code>```

Please help

答:
I think you must clarify what you're meaning by "one matrix is contained in the other matrix".

Regarding at you're code i assume that the order of the elements in the matrix does not matter, and you just want to check if all the elements of one matrix appear in the other one.
Can you confirm that?

Moreover, you are not really saying what your problem is. compile-time error? not the good result?
From what i see, you have at least an error due to :

```<code>does_it_contain List. hd matrix List.hd lis1
</code>```

where you should put parenthesis around List. hd matrix and List.hd lis1 to avoid the applied to too many argument error.

Let's end with few coding-style remarks :

1) You can use List.mem instead of redefining it here :

```<code>let rec does_it_contain lis x =
if (lis = []) then false
else if ((List.hd lis) = x) then true
else does_it_contain (List.tl lis) x;;
</code>```

2) This ...

```<code>if (does_it_contain List. hd matrix List.hd lis1 = true) then true
else blabla
</code>```

... is very poor style. you can directly write

```<code>does_it_contain (List.hd matrix) (List.hd lis1) || blabla
</code>```

3) It's prefered to use pattern-matching instead of if (lis = []) then false else if ((List.hd lis) = x) .... It will check statically for you if you're missing some cases or if you are writing redundant ones.
Prefer :

```<code>match lis with
| [] -> false
| h::t -> ...
</code>```

Edit :
Working with matrix is an adapted task for array, so my approach would be to convert your list to an array an then use the classical imperative approach.
If you want to stick to the lists, than you need to make appear the index of the found sublines in your matrix :  if all the line of the matrix A, appear in the matrix B, AND at the same begining index, then A is a submatrix of B.

one of the problems of your code is (beside the fact that the following won't compile) is : if (does_it_contain List. hd matrix List.hd lis1 = true) then true

Here, you return true whenever the begining element of your matrix is the same than the one of your list. You should here check for all the elements and not only the head.

```<code>  if (does_it_contain (List.hd matrix) (List.hd lis1) = true) then
    does_it (List.tl matrix) lis1
  else false
</code>```

This makes you closer to the solution but wont fix your code. You should make the index appear in your computation.

Body:
let my_matrix1 = [[1;2];[3;4]];;

let my_matrix2 = [[4;7;8];[3;2;1]];;

I have defined two matrices so I can see if the code is working properly.

I have done it for the element:

let rec does_it_contain lis x =
if (lis = []) then false
else if ((List.hd lis) = x) then true
else does_it_contain (List.tl lis) x;;

let rec does_it matrix x =
if (matrix = []) then false
else if (does_it_contain (List.hd matrix) x = true) then true
else does_it (List.tl matrix) x;;

does_it my_matrix1 2;;
- bool = true

And the problem is working, but I'm not sure what went wrong when I tried to do it with the matrices (if one contains the other):

let rec does_it_contain lis1 lis2 =
if (List.hd lis1 = []) then false
else if (List.hd lis1 = lis2) then true
else does_it_contain (List.tl lis1) lis2;;

let rec does_it matrix lis1 =
if (matrix = []) then false
else if (does_it_contain List. hd matrix List.hd lis1 = true) then true
else does_it (List.tl matrix) lis1;;

does_it my_matrix1 my_matrix2;;

Please help

Body:
I think you must clarify what you're meaning by "one matrix is contained in the other matrix".

Regarding at you're code i assume that the order of the elements in the matrix does not matter, and you just want to check if all the elements of one matrix appear in the other one.
Can you confirm that?

Moreover, you are not really saying what your problem is. compile-time error? not the good result?
From what i see, you have at least an error due to :

does_it_contain List. hd matrix List.hd lis1

where you should put parenthesis around List. hd matrix and List.hd lis1 to avoid the applied to too many argument error.

Let's end with few coding-style remarks :

1) You can use List.mem instead of redefining it here :

let rec does_it_contain lis x =
if (lis = []) then false
else if ((List.hd lis) = x) then true
else does_it_contain (List.tl lis) x;;

2) This ...

if (does_it_contain List. hd matrix List.hd lis1 = true) then true
else blabla

... is very poor style. you can directly write

does_it_contain (List.hd matrix) (List.hd lis1) || blabla

3) It's prefered to use pattern-matching instead of if (lis = []) then false else if ((List.hd lis) = x) .... It will check statically for you if you're missing some cases or if you are writing redundant ones.
Prefer :

match lis with
| [] -> false
| h::t -> ...

Edit :
Working with matrix is an adapted task for array, so my approach would be to convert your list to an array an then use the classical imperative approach.
If you want to stick to the lists, than you need to make appear the index of the found sublines in your matrix :  if all the line of the matrix A, appear in the matrix B, AND at the same begining index, then A is a submatrix of B.

one of the problems of your code is (beside the fact that the following won't compile) is : if (does_it_contain List. hd matrix List.hd lis1 = true) then true

Here, you return true whenever the begining element of your matrix is the same than the one of your list. You should here check for all the elements and not only the head.

  if (does_it_contain (List.hd matrix) (List.hd lis1) = true) then
    does_it (List.tl matrix) lis1
  else false

This makes you closer to the solution but wont fix your code. You should make the index appear in your computation.


答:
In addition to operator << which skips whitespace C++ Standard Library provides std::getline function overload for strings. Use it instead:

```<code>std::string name;
std::getline(cin, name);
</code>```

Your function that calls

```<code>strcpy(apname, name[2]);
</code>```

is incorrect for several reasons:

You cannot copy characters directly into a string

name[2] on an array of two items is referencing an item past the end of the array.

Title: Using strcpy with a char to a string?

Body:
In addition to operator << which skips whitespace C++ Standard Library provides std::getline function overload for strings. Use it instead:

std::string name;
std::getline(cin, name);

Your function that calls

strcpy(apname, name[2]);

is incorrect for several reasons:

You cannot copy characters directly into a string

name[2] on an array of two items is referencing an item past the end of the array.


问:
emplace_back calls move constructor, and destructor
I try to emplace two instance of the class cBar to a vector with emplace_back function.

According to the reference calling an emplace_back only reserve the place in the vector, then create the new instance "in place".

Now, I tried to experiment with it:

```<code>#include <vector>
#include <iostream>
#include <memory>
#include <string>

class cBar
{
public:

    cBar(const int index);
    cBar(cBar&& other); //needed for emplace_back?
    ~cBar();

private:
    cBar(const cBar& other) = delete;
    cBar& operator=(const cBar& other) = delete;

public:
    int                         mIndex;

};

cBar::cBar(const int index) : mIndex(index)
{
    std::cout << "cBar being created ..." << std::endl;
}
cBar::cBar(cBar&& other) : mIndex(other.mIndex)
{
    std::cout << "cBar being moved ..." << std::endl;
}
cBar::~cBar()
{
    std::cout << "cBar being destroyed ..." << std::endl;
}

int main()
{
    std::vector<cBar> mBars;

    std::cout << "Begin to create 2 cBar instance, I am expecting 2 \"cBar being created ...\" messages here" << std::endl;
    mBars.emplace_back(0);//this supposed to call only cBar(const int index) constructor, and nothing more
    mBars.emplace_back(1);//this works as expected, only one constructor call

    //destroy all
    std::cout << "Destroy the 2 isntances (this works, I see the two expected \"cBar being destroyed ...\" messages here" << std::endl;
    mBars.clear();

    std::cin.get();
    return 0;
}
</code>```

Output:

```<code>Begin to create 2 cBar instance, I am expecting 2 "cBar being created ..." messages here
cBar being created ...
cBar being moved ...
cBar being destroyed ...
cBar being created ...
Destroy the 2 isntances (this works, I see the two expected "cBar being destroyed ..." messages here
cBar being destroyed ...
cBar being destroyed ...
</code>```

If you run the one above, you will see that the first emplace_back creates the instance "in place", but then immediately call the move constructor, and then destructor is called.

What is more strange, that in case of the second emplace, I see the expected behavior: Only one constructor call.

I have two questions:

Why do I need to define a move constructor in my class if I just want to emplace_back items, and never use push_back.

In case of the first instance creation, why the move constructor, then the destructor is called? If I access the data of the first instance all seems to correct, so I have no idea why the move constructor, and destructor is called.

I use Visual Studio 2015.

Output with vector sizes in each step:

```<code>Begin to create 2 cBar instance, I am expecting 2 "cBar being created ..." messages here
Vector size:0
cBar being created ...
Vector size:1
cBar being moved ...
cBar being destroyed ...
cBar being created ...
Vector size:2
Destroy the 2 isntances (this works, I see the two expected "cBar being destroyed ..." messages here
cBar being destroyed ...
cBar being destroyed ...
</code>```

答:
Odds are the capacity of your vector was one, and when you put the second element in, it had to resize the vector.  That can turn into a bunch of things being moved in memory, and the symptoms you see.

Kerreks advice is good.
I suggest printing the vectors capacity before and after each operation to see if the capacity change is the cause.

Body:
I try to emplace two instance of the class cBar to a vector with emplace_back function.

According to the reference calling an emplace_back only reserve the place in the vector, then create the new instance "in place".

Now, I tried to experiment with it:

#include <vector>
#include <iostream>
#include <memory>
#include <string>

class cBar
{
public:

    cBar(const int index);
    cBar(cBar&& other); //needed for emplace_back?
    ~cBar();

private:
    cBar(const cBar& other) = delete;
    cBar& operator=(const cBar& other) = delete;

public:
    int                         mIndex;

};

cBar::cBar(const int index) : mIndex(index)
{
    std::cout << "cBar being created ..." << std::endl;
}
cBar::cBar(cBar&& other) : mIndex(other.mIndex)
{
    std::cout << "cBar being moved ..." << std::endl;
}
cBar::~cBar()
{
    std::cout << "cBar being destroyed ..." << std::endl;
}

int main()
{
    std::vector<cBar> mBars;

    std::cout << "Begin to create 2 cBar instance, I am expecting 2 \"cBar being created ...\" messages here" << std::endl;
    mBars.emplace_back(0);//this supposed to call only cBar(const int index) constructor, and nothing more
    mBars.emplace_back(1);//this works as expected, only one constructor call

    //destroy all
    std::cout << "Destroy the 2 isntances (this works, I see the two expected \"cBar being destroyed ...\" messages here" << std::endl;
    mBars.clear();

    std::cin.get();
    return 0;
}

Output:

Begin to create 2 cBar instance, I am expecting 2 "cBar being created ..." messages here
cBar being created ...
cBar being moved ...
cBar being destroyed ...
cBar being created ...
Destroy the 2 isntances (this works, I see the two expected "cBar being destroyed ..." messages here
cBar being destroyed ...
cBar being destroyed ...

If you run the one above, you will see that the first emplace_back creates the instance "in place", but then immediately call the move constructor, and then destructor is called.

What is more strange, that in case of the second emplace, I see the expected behavior: Only one constructor call.

I have two questions:

Why do I need to define a move constructor in my class if I just want to emplace_back items, and never use push_back.

In case of the first instance creation, why the move constructor, then the destructor is called? If I access the data of the first instance all seems to correct, so I have no idea why the move constructor, and destructor is called.

I use Visual Studio 2015.

Output with vector sizes in each step:

Begin to create 2 cBar instance, I am expecting 2 "cBar being created ..." messages here
Vector size:0
cBar being created ...
Vector size:1
cBar being moved ...
cBar being destroyed ...
cBar being created ...
Vector size:2
Destroy the 2 isntances (this works, I see the two expected "cBar being destroyed ..." messages here
cBar being destroyed ...
cBar being destroyed ...


问:
"use of unresolved identifier 'myAlert & okAction'
I keep receiving an error on 15th and 16th lines from the bottom. It tells me:

"use of unresolved identifier 'myAlert & okAction'"

If anyone can help, it would be much appreciated.

Code:

```<code>import UIKit

class RegisterPageViewController: UIViewController {
    @IBOutlet weak var userNameTextField: UITextField!
    @IBOutlet weak var userPhoneTextField: UITextField!;
    @IBOutlet weak var userPasswordTextField: UITextField!;
    @IBOutlet weak var userConfirmPasswordTextField: UITextField!;
    @IBOutlet weak var userPlugTextField: UITextField!;

    @IBAction func RegisterButtonTapped(_ sender: Any) {
        let userName = userNameTextField.text;
        let userPhone = userPhoneTextField.text;
        let userPassword = userPasswordTextField.text;
        let userConfirmPassword = userConfirmPasswordTextField.text;
        let userPlug = userPlugTextField.text;

        // Check for empty fields
        if(userName!.isEmpty || userPhone!.isEmpty || userPassword!.isEmpty || userConfirmPassword!.isEmpty || userPlug!.isEmpty)
        {
            displayMyAlertMessage(userMessage: "All fields are required")

            return;
        }

        // check if passwords match
        if(userPassword != userConfirmPassword)
        {
         // Display an alert message
            displayMyAlertMessage(userMessage: "Passwords do not match")
            return;
        }

        // Store data
        UserDefaults.standard.set(userName, forKey: "userName")
        UserDefaults.standard.set(userName, forKey: "userPhone")
        UserDefaults.standard.set(userName, forKey: "userPassword")
        UserDefaults.standard.set(userName, forKey: "userPlug")
        UserDefaults.standard.synchronize();

        // Display alert message with confirmation
        _ = UIAlertController(title:"Alert", message:"Registration is successful. Thank you!", preferredStyle: UIAlertControllerStyle.alert);

        _ = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default){ action in
            self.dismiss(animated: true, completion:nil)
        }

        myAlert.addAction(okAction);
        self.present(myAlert, animated:true, completion:nil)
    }

    func displayMyAlertMessage(userMessage:String)
    {
        let myAlert = UIAlertController(title:"Alert", message:userMessage, preferredStyle: UIAlertControllerStyle.alert);

        let okAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default, handler:nil);

        myAlert.addAction(okAction);

        self.present(myAlert, animated:true, completion:nil);
    }
}
</code>```

答:
Replace

```<code>    _ = UIAlertController(title:"Alert", message:"Registration is successful. Thank you!", preferredStyle: UIAlertControllerStyle.alert);

    _ = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default){ action in
        self.dismiss(animated: true, completion:nil)
    }
</code>```

with

```<code>   let myAlert  = UIAlertController(title:"Alert", message:"Registration is successful. Thank you!", preferredStyle: UIAlertControllerStyle.alert);

   let okAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default){ action in
        self.dismiss(animated: true, completion:nil)
    }
</code>```

Body:
I keep receiving an error on 15th and 16th lines from the bottom. It tells me:

"use of unresolved identifier 'myAlert & okAction'"

If anyone can help, it would be much appreciated.

Code:

import UIKit

class RegisterPageViewController: UIViewController {
    @IBOutlet weak var userNameTextField: UITextField!
    @IBOutlet weak var userPhoneTextField: UITextField!;
    @IBOutlet weak var userPasswordTextField: UITextField!;
    @IBOutlet weak var userConfirmPasswordTextField: UITextField!;
    @IBOutlet weak var userPlugTextField: UITextField!;

    @IBAction func RegisterButtonTapped(_ sender: Any) {
        let userName = userNameTextField.text;
        let userPhone = userPhoneTextField.text;
        let userPassword = userPasswordTextField.text;
        let userConfirmPassword = userConfirmPasswordTextField.text;
        let userPlug = userPlugTextField.text;

        // Check for empty fields
        if(userName!.isEmpty || userPhone!.isEmpty || userPassword!.isEmpty || userConfirmPassword!.isEmpty || userPlug!.isEmpty)
        {
            displayMyAlertMessage(userMessage: "All fields are required")

            return;
        }

        // check if passwords match
        if(userPassword != userConfirmPassword)
        {
         // Display an alert message
            displayMyAlertMessage(userMessage: "Passwords do not match")
            return;
        }

        // Store data
        UserDefaults.standard.set(userName, forKey: "userName")
        UserDefaults.standard.set(userName, forKey: "userPhone")
        UserDefaults.standard.set(userName, forKey: "userPassword")
        UserDefaults.standard.set(userName, forKey: "userPlug")
        UserDefaults.standard.synchronize();

        // Display alert message with confirmation
        _ = UIAlertController(title:"Alert", message:"Registration is successful. Thank you!", preferredStyle: UIAlertControllerStyle.alert);

        _ = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default){ action in
            self.dismiss(animated: true, completion:nil)
        }

        myAlert.addAction(okAction);
        self.present(myAlert, animated:true, completion:nil)
    }

    func displayMyAlertMessage(userMessage:String)
    {
        let myAlert = UIAlertController(title:"Alert", message:userMessage, preferredStyle: UIAlertControllerStyle.alert);

        let okAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default, handler:nil);

        myAlert.addAction(okAction);

        self.present(myAlert, animated:true, completion:nil);
    }
}

Body:
Replace

    _ = UIAlertController(title:"Alert", message:"Registration is successful. Thank you!", preferredStyle: UIAlertControllerStyle.alert);

    _ = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default){ action in
        self.dismiss(animated: true, completion:nil)
    }

with

   let myAlert  = UIAlertController(title:"Alert", message:"Registration is successful. Thank you!", preferredStyle: UIAlertControllerStyle.alert);

   let okAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default){ action in
        self.dismiss(animated: true, completion:nil)
    }