问:
How do I remove cookies when the browser is closed? using angular2-cookies
When I close the browser, I want to remove cookies. How can I do this?
i use th bibliotek angular2-cookie.</p>

答:
The onbeforeunload event will allow you to run some code before the user leaves the page. Combining that with the code from this answer will allow you to clear all the cookies when the user tries to leave the page.

```<code>window.onbeforeunload = function (e) {
  deleteAllCookies();
}

function deleteAllCookies() {
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}
</code>```

In relation to angular 2, if this is a one-off thing, it's totally fine to put it in your index.html page as a bottom snippet, because it's not really related to your Angular 2 application. If you want to do it in Angular 2 fashion, you should be able to put this in your AppComponent.

```<code>@HostListener('window:onbeforeunload', ['$event'])
onBeforeUnload() {
    this.deleteAllCookies();
}

deleteAllCookies() {
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}
</code>```

Body:
The onbeforeunload event will allow you to run some code before the user leaves the page. Combining that with the code from this answer will allow you to clear all the cookies when the user tries to leave the page.

window.onbeforeunload = function (e) {
  deleteAllCookies();
}

function deleteAllCookies() {
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}

In relation to angular 2, if this is a one-off thing, it's totally fine to put it in your index.html page as a bottom snippet, because it's not really related to your Angular 2 application. If you want to do it in Angular 2 fashion, you should be able to put this in your AppComponent.

@HostListener('window:onbeforeunload', ['$event'])
onBeforeUnload() {
    this.deleteAllCookies();
}

deleteAllCookies() {
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}


来源: stackexchange

问:
Nightwatch - using execute to fill in table data cells
So I have a dynamically generated table that I am trying to use nightwatch to fill in some data with, the table is 12 x 7 and I only need to fill the middle row from top to bottom. Logically speaking I have been able to target most elements through an id or even a class selector where possible, but this table is a bit tricky.

The table cannot have an id's added to it, and is not in the semantic html as it's generated with knockout depending on certain values that are selected in the form above that I have already handled.

The page is essentially a popup modal, that blocks the rest of the ui.
My thought process has been
1. Wait for element visible (this works, and I successfully see the element I am waiting for)
2. I use browser.execute to get a list of the td nodes.

```<code>const elements : NodeListOf<Element> = document.querySelectorAll('td')
const arr = [].slice.call(elements) //hacky sorry!
arr.filter // do that here
</code>```

basically my issue is that using browser.execute has been hard to debug as I use the debugger in Visual Studio, I can't really step through this callback for some reason, and the querySelectorAl seems to return to me the td on the blocked ui that I am not trying to target, not on the ui I want.

Is there any advice on this being a god awful approach or perhaps a far simpler approach?

答: I basically ended up using execute to get a nodeList, hacked it into an array, filtered it out based on some things i wanted to use nad hacked it away. was annoying but its semi solved for now</p>

ContentLicense: CC BY-SA 3.0

Body:
So I have a dynamically generated table that I am trying to use nightwatch to fill in some data with, the table is 12 x 7 and I only need to fill the middle row from top to bottom. Logically speaking I have been able to target most elements through an id or even a class selector where possible, but this table is a bit tricky.

The table cannot have an id's added to it, and is not in the semantic html as it's generated with knockout depending on certain values that are selected in the form above that I have already handled.

The page is essentially a popup modal, that blocks the rest of the ui.
My thought process has been
1. Wait for element visible (this works, and I successfully see the element I am waiting for)
2. I use browser.execute to get a list of the td nodes.

const elements : NodeListOf<Element> = document.querySelectorAll('td')
const arr = [].slice.call(elements) //hacky sorry!
arr.filter // do that here

basically my issue is that using browser.execute has been hard to debug as I use the debugger in Visual Studio, I can't really step through this callback for some reason, and the querySelectorAl seems to return to me the td on the blocked ui that I am not trying to target, not on the ui I want.

Is there any advice on this being a god awful approach or perhaps a far simpler approach?


问:
Database Design review
I have an old database design that I think I can streamline and make more normalized.  I was hoping to get some thoughts on this.  Here are the “rules” for the database:

The organization is made up three hierarchies:

a. Bureau - is the highest level

b. Office - each bureau can have many offices

c. Division - each office can have many divisions

We have employees that work at all of the three tiers. For example:

a. We have Bureau level staff. They do not belong to an office or division.  The oversee all offices, but do not belong to them

b. We have Office level employees, that do not belong to a specific division, but oversees all divisions

c. Division level folks that belong to a division

We also have projects. A project can be at various levels:

a. Bureau wide projects

b. Projects that span multiple offices

c. Projects just in a division

Every project needs to be managed by at least one employee, having a specific role (project manager) tough the employees table would be made of individuals with other roles, and even multiple roles.

Currently, I have the following schema (it’s abridged for brevity):

With this schema, I have found the following issues:

All projects are tied to a division, in this model.  But, in reality, not all projects are directly attributable to a division.  Some  maybe at the office or bureau level.  Others may be across multiple offices or bureaus (but not across multiple bureaus AND offices).  So, I get around this by having extra options in each of the organization Tiers.  For example. In the Division Table, I have an option for Office Wide or Bureau Wide.  Or I might have an options like Office One/Office Two.

Another issue I see:  each of the roles tables have many duplicate values.  For example, if we look at divisionRole table.  Almost all divisions have the same role.  So, I have DivisionManager, divisonPM, divisionLead listed multiple times (once for each division).  Sometimes, a division may have a unique position, but this is rare.  This is true for the BureauRole and OfficeRole tables

So, I am looking for advice on how to better normalize this database, and address the above scenarios.  Anyone have suggestions?

答:
You could simplify this database design significantly by replacing your three distinct organizational levels with a single organization table that has a self-directed foreign key which indicates the parent.

Consider something like this:

```<code>CREATE TABLE ORGANIZATION
( org_id         int IDENTITY NOT NULL
, org_level      CHAR(1) NOT NULL
, [name]         VARCHAR(50) NOT NULL
, parent_org_id  INT
, constraint pk_org PRIMARY KEY (org_id)
, constraint fk_org_hierarchy FOREIGN KEY (parent_org_id)
  REFERENCES ORGANIZATION (org_id)
, constraint ck_org_level CHECK
  (   org_level = 'B' -- Bureau
   OR org_level = 'O' -- Office
   OR org_level = 'D')-- Division
, constraint ck_org_root CHECK
  (  (org_level = 'B' AND parent_org_id IS NULL)
  OR (org_level <> 'B' AND parent_org_id IS NOT NULL) )
);
</code>```

Now you have all of your organization levels in one table, which means all of your many to many intersection tables can be collapsed from three to one as well, and you have the ability to assign other foreign key relationships, such as the one from project to any level of the organization.

Note that you can add other constraints too, so that you can enforce your business rules such as:

4.Every project needs to be managed by at least one employee, having a specific role (project manager) tough the employees table would be
  made of individuals with other roles, and even multiple roles.

One thing to keep in mind is that managing hierarchical data in a relational database is a little tricky.  However, there are things that you can do to make this simpler.  For example, see my answer to this question for more about managing hierarchies in an RDBMS.

Title: Database Design review

Body:
You could simplify this database design significantly by replacing your three distinct organizational levels with a single organization table that has a self-directed foreign key which indicates the parent.

Consider something like this:

CREATE TABLE ORGANIZATION
( org_id         int IDENTITY NOT NULL
, org_level      CHAR(1) NOT NULL
, [name]         VARCHAR(50) NOT NULL
, parent_org_id  INT
, constraint pk_org PRIMARY KEY (org_id)
, constraint fk_org_hierarchy FOREIGN KEY (parent_org_id)
  REFERENCES ORGANIZATION (org_id)
, constraint ck_org_level CHECK
  (   org_level = 'B' -- Bureau
   OR org_level = 'O' -- Office
   OR org_level = 'D')-- Division
, constraint ck_org_root CHECK
  (  (org_level = 'B' AND parent_org_id IS NULL)
  OR (org_level <> 'B' AND parent_org_id IS NOT NULL) )
);

Now you have all of your organization levels in one table, which means all of your many to many intersection tables can be collapsed from three to one as well, and you have the ability to assign other foreign key relationships, such as the one from project to any level of the organization.

Note that you can add other constraints too, so that you can enforce your business rules such as:

4.Every project needs to be managed by at least one employee, having a specific role (project manager) tough the employees table would be
  made of individuals with other roles, and even multiple roles.

One thing to keep in mind is that managing hierarchical data in a relational database is a little tricky.  However, there are things that you can do to make this simpler.  For example, see my answer to this question for more about managing hierarchies in an RDBMS.


答:
You can use groupby by Series created by strftime:

```<code>print (df.groupby(df.index.strftime('%m-%d')).max())
       Temperature
03-20           51
08-15          228
12-31          -32
</code>```

For filtering use boolean indexing with mask created by numpy.in1d, because year return numpy array too:

```<code>mask = np.in1d(df.index.year, np.arange(2005, 2015))
print (df[mask].groupby(df.index.strftime('%m-%d')).max())
       Temperature
03-20           51
08-15          228
12-31          -32
</code>```

Title: Calculate maximum value by day of the year over certain period

Body:
I have the following data frame:

my_index = ['2005-03-20', '2008-03-20', '2014-03-20', '2007-08-15', '2012-08-15', '2007-12-31', '2011-12-31', '2013-12-31', '2014-12-31']
df = pd.DataFrame([42, 51, 36, 217, 228, -56, -50, -66, -32], index = my_index, columns = ['Temperature'])
df.index = pd.to_datetime(df.index)

Which looks like this:

            Temperature
2005-03-20           42
2008-03-20           51
2014-03-20           36
2007-08-15          217
2012-08-15          228
2007-12-31          -56
2011-12-31          -50
2013-12-31          -66
2014-12-31          -32

What I want is to calculate the maximum value by day of the year over the period 2005-2014. The desired output would be this one:

       Temperature
03-20           51
08-15          228
12-31          -32

Any idea? Thx.

Body:
You can use groupby by Series created by strftime:

print (df.groupby(df.index.strftime('%m-%d')).max())
       Temperature
03-20           51
08-15          228
12-31          -32

For filtering use boolean indexing with mask created by numpy.in1d, because year return numpy array too:

mask = np.in1d(df.index.year, np.arange(2005, 2015))
print (df[mask].groupby(df.index.strftime('%m-%d')).max())
       Temperature
03-20           51
08-15          228
12-31          -32


问:
price of developer license for Windows Phone 7?
Does Microsoft offer developer license for professionals and students? Is there a special student program?</p>

答:
the registration prices are here ($99) - http://create.msdn.com/en-US/home/membership

there is a great blog post about how to get from concept to marketplace here - http://blogs.msdn.com/b/mikeormond/archive/2010/11/15/windows-phone-7-apps-getting-from-concept-to-customer.aspx

ContentLicense: CC BY-SA 2.5


问:
How does splitting a matrix in blocks improve cache hits?
I am trying to understand the concepts of caches and blocking in matrix. I am trying to transpose a matrix.

I understand the concept of row-wise memory layout, so I get that when I am trying to access the data row-wise, I get fewer cache-misses as compared to column wise.

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

    for( int j = 0; j < n; j++ )

      destination[j+i*n] = source[i+j*n];
</code>```

So for the source matrix, I will have fewer cache misses, while for destination I will have more cache misses.

Here is code with blocking

```<code>for (int i = 0; i < n; i += blocksize) {
    for (int j = 0; j < n; j += blocksize) {
        // transpose the block beginning at [i,j]
        for (int k = i; k < i + blocksize; ++k) {
            for (int l = j; l < j + blocksize; ++l) {
                dst[k + l*n] = src[l + k*n];
            }
        }
    }
}
</code>```

The code above makes use of blocking technique. I can't quite understand how does blocking help with the performance?

答:
The most important aspect here is locality, in particular for your example spatial locality. Rougly speaking this means to access data that is close to each other.

Whenever one element of the matrix is accssed, and it is not yet in the cache, it always loads the entire cache line. This cache line can for example contain 64 byte or 16 integer elements. If you do not use the other elements while they are in cache, your code is inefficient.

The cache line will be evicted, if you load too much data in-between the accesses. Consider the first access from the inner loop which loads source[i]. The next element in memory source[i + 1] is on the same cache line and was already loaded. However, it will only be needed after the entire inner loop is completed. If the inner loop accesses too much data, source[i + 1] won't be in the cache any more. The distance between accessing source[i] and source[i+1] is too large.

Blocking removes this inefficiency. The innermost loop is much smaller than originally, the distance between accessing is reduced. All data handled by the innermost loop fits into the cache.

Body:
I am trying to understand the concepts of caches and blocking in matrix. I am trying to transpose a matrix.

I understand the concept of row-wise memory layout, so I get that when I am trying to access the data row-wise, I get fewer cache-misses as compared to column wise.

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

    for( int j = 0; j < n; j++ )

      destination[j+i*n] = source[i+j*n];

So for the source matrix, I will have fewer cache misses, while for destination I will have more cache misses.

Here is code with blocking

for (int i = 0; i < n; i += blocksize) {
    for (int j = 0; j < n; j += blocksize) {
        // transpose the block beginning at [i,j]
        for (int k = i; k < i + blocksize; ++k) {
            for (int l = j; l < j + blocksize; ++l) {
                dst[k + l*n] = src[l + k*n];
            }
        }
    }
}

The code above makes use of blocking technique. I can't quite understand how does blocking help with the performance?


问:
NPE when calling mock
I have just started with testing and I'm also using MVP pattern in my android apps.

Currently I have a presenter which uses the following android code to test if an email address is valid :

```<code> android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches()
</code>```

Since it's not possible to test it with a local JVM unit test I decided to hide it behind an interface :

```<code>public interface EmailValidator {

   boolean isValidEmail(CharSequence target);

}
</code>```

and here's the implementation :

```<code>public class EmailValidatorImpl implements EmailValidator {

@Override
public boolean isValidEmail(CharSequence target) {
    if (target == null) {
        return false;
    } else {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
    }
}

}
</code>```

So now my test code is :

public class SignUpPresenterTest {

```<code>@Mock
private SignUpMVP.View view;

@Mock
private EmailValidator validator;

private SignUpPresenter presenter;

private String email = "name@gmail.com";
private String password = "ABCDabcd";
private String username = "username";

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    presenter = new SignUpPresenter(view);
}

@Test
public void onButtonSignUpClicked() throws Exception {
    when(validator.isValidEmail(email))
            .thenReturn(true);

    presenter.onButtonSignUpClicked(email, password, username);

    verify(view).executeSignUpService();
}

}
</code>```

and now I'm getting a NPE when the code above calls : EmailValidatorImpl.isValidEmail()

```<code>java.lang.NullPointerException
at com.example.signup.helpers.EmailValidatorImpl.isValidEmail(EmailValidatorImpl.java:20)
at com.example.signup.SignUpPresenter.showErrors(SignUpPresenter.java:67)
at com.example.signup.SignUpPresenter.onButtonSignUpClicked(SignUpPresenter.java:25)
at com.example.signup.SignUpPresenterTest.onButtonSignUpClicked(SignUpPresenterTest.java:43)
</code>```

and my questions are : isn't this how I Should use Mockito ? Is there anything I can do to test my code and avoid NPE ?

答:
That happens because you are mocking the EmailValidator but you are not using that object inside SignUpPresenter.

You should pass the reference in the constructor:

presenter = new SignUpPresenter(view, validator);

or in the method signature:

presenter.onButtonSignUpClicked(email, password, username, validator);

Then you presenter should be something like this:

```<code>public class SignUpPresenter {

    private View view;
    private EmailValidator validator;

    public SignUpPresenter(View view, EmailValidator validator) {
        this.view = view;
        this.validator = validator;
    }

    private void onButtonSignUpClicked(String email, String password, String username) {
        //Your code...
        boolean isValid = validator.isValidEmail(email);
    }
}
</code>```

Title: NPE when calling mock

Body:
I have just started with testing and I'm also using MVP pattern in my android apps.

Currently I have a presenter which uses the following android code to test if an email address is valid :

 android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches()

Since it's not possible to test it with a local JVM unit test I decided to hide it behind an interface :

public interface EmailValidator {

   boolean isValidEmail(CharSequence target);

}

and here's the implementation :

public class EmailValidatorImpl implements EmailValidator {

@Override
public boolean isValidEmail(CharSequence target) {
    if (target == null) {
        return false;
    } else {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
    }
}

}

So now my test code is :

public class SignUpPresenterTest {

@Mock
private SignUpMVP.View view;

@Mock
private EmailValidator validator;

private SignUpPresenter presenter;

private String email = "name@gmail.com";
private String password = "ABCDabcd";
private String username = "username";

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    presenter = new SignUpPresenter(view);
}

@Test
public void onButtonSignUpClicked() throws Exception {
    when(validator.isValidEmail(email))
            .thenReturn(true);

    presenter.onButtonSignUpClicked(email, password, username);

    verify(view).executeSignUpService();
}

}

and now I'm getting a NPE when the code above calls : EmailValidatorImpl.isValidEmail()

java.lang.NullPointerException
at com.example.signup.helpers.EmailValidatorImpl.isValidEmail(EmailValidatorImpl.java:20)
at com.example.signup.SignUpPresenter.showErrors(SignUpPresenter.java:67)
at com.example.signup.SignUpPresenter.onButtonSignUpClicked(SignUpPresenter.java:25)
at com.example.signup.SignUpPresenterTest.onButtonSignUpClicked(SignUpPresenterTest.java:43)

and my questions are : isn't this how I Should use Mockito ? Is there anything I can do to test my code and avoid NPE ?

Body:
That happens because you are mocking the EmailValidator but you are not using that object inside SignUpPresenter.

You should pass the reference in the constructor:

presenter = new SignUpPresenter(view, validator);

or in the method signature:

presenter.onButtonSignUpClicked(email, password, username, validator);

Then you presenter should be something like this:

public class SignUpPresenter {

    private View view;
    private EmailValidator validator;

    public SignUpPresenter(View view, EmailValidator validator) {
        this.view = view;
        this.validator = validator;
    }

    private void onButtonSignUpClicked(String email, String password, String username) {
        //Your code...
        boolean isValid = validator.isValidEmail(email);
    }
}


问:
Setting Title for Tabs in Terminator (Console Application) in Ubuntu
Is there way to set terminator (Version: 0.95ppa1) title of tabs to a different string via bash command-line (CLI)?

I plan to use this feature with AutoKey and I can open multiple machines at same time and set title to Name of the machine its connected to.

答:
Right click on terminator and choose preferences from the drop-down menu. Choose profiles tab and enable "show title bar" option. It works!!

Tip: You can actually rename each terminator window!!


问:
What is the easiest/most effective way to learn Delphi?
I am totally new to programming and I have chosen Delphi as the programming language that I would like to learn.

I basically want to build tools that will fill and submit web forms using sockets and I want them to be multi threaded as well.

I would love for them to be feature rich and perform correctly.

I am in no real rush to do this as I do understand that it takes time to become efficient at anything (especially programming). However, I do want to take the shortest path that I can in learning.

If it were possible I would love to go to school to learn the language but it seems like there are no schools in the US that teach it.

I have found quite a good bit of information on the internet that has helped me gain a basic knowledge of how things work inside the IDE and how to build basic apps but I want to be able to build really good apps that these tutorial do not teach me how to do.

So.. My question is how do I go about becoming an expert Delphi programmer without having any "Real Teacher" to guide me? How did you guys learn?

Would learning another programming language with the help of a teacher and them coming back to delphi make sense?

答:
If you are looking to become an expert in Delphi, you will also need to become an expert in Windows...unless I misunderstand your intentions. Two great resources are:

Windows via C/C++ by Jeffrey Richter of Wintellect

You'll have to convert samples to Delphi, but hey, that's great practice too.

Windows Operating Systems Internals Curriculum by Mark Russinovich and Dave Solomon

As I mentioned in my other answer, check out Mark Russinovich's Windows Operating Systems Internals Curriculum which is offered for free. You will not only learn how Windows works, but it is a good "Operating Systems 101" type course.

ContentLicense: CC BY-SA 4.0


问:
Rails - How to handle record create with has_many association error
I am running into a problem when trying to handle a #create request on a model with a has_many association where one of the passed in IDs does not belong to an existing record.

Test request:

```<code>post authors_path, params: { book_ids: [-1] }
</code>```

Controller method:

```<code>def create
  @author= Author.create params
end
</code>```

Model:

```<code>class Author
  has_many :books
end
</code>```

This results in an ActiveRecord::RecordNotFound error being raised.

The problem is as follows:

I am already rescuing from an ActiveRecord::RecordNotFound error and responding with 404 Record Not Found in my ApplicationController because such an error typically arises when a user is attempting to GET, PATCH, PUT, or DELETE a record that does not exist, e.g., get author_path(-1). I would prefer to avoid moving the rescue clause onto the #show, #create, etc methods because I have a lot of controllers, resulting in a lot of duplicate code.

I want to keep my record and association creations atomic and this seems to be the best way to do it, but I also want to respond with a 400 Bad Request when the situation described above occurs. What would be the best way to handle such a situation?

UPDATE

After some more research, I wrote a quick custom validation that validates a record exists for all passed in book_ids

```<code>class Author < ApplicationRecord
  validate :books_exist

  def books_exist
    return if book_ids.blank?
    Book.find book_ids
  rescue ActiveRecord::RecordNotFound => e
    errors.add e.message
  end
end
</code>```

This doesn't seem to work though as even instantiating a new Author instance without saving it to the database throws an ActiveRecord::RecordNotFound error:

```<code>> Author.new(association_ids: [-1])
  Book Load (2.3ms) SELECT `books`.* FROM `books` WHERE `books`.`id` = -1
ActiveRecord::RecordNotFound: Couldn't find Book with 'id'=[-1]
  from ...
</code>```

The issue seems to be that ActiveRecord attempts to find a record for the passed in book_id before any validation occurs. Is there any way to rescue this error? It seems like there's not much of a workaround for this particular issue.

答:
The two solutions that were suggest to me outside of StackOverflow are as follows:

Rescue the error in each controller action

```<code>class AuthorsController
  def create
    @author = Author.create(params)
    render json: @author
  rescue ActiveRecord::RecordNotFound => e
    render json_error_message
  end
end
</code>```

Create a generic action in the ApplicationController

```<code>class ApplicationController
  def create(model)
    instance_variable_set("@#(model.class.name}", model.create(params)
  rescue ActiveRecord::RecordNotFound => e
    render json_error_message
  end
end

class AuthorsController
  def create
    super(Author)
  end
end
</code>```

Body:
I am running into a problem when trying to handle a #create request on a model with a has_many association where one of the passed in IDs does not belong to an existing record.

Test request:

post authors_path, params: { book_ids: [-1] }

Controller method:

def create
  @author= Author.create params
end

Model:

class Author
  has_many :books
end

This results in an ActiveRecord::RecordNotFound error being raised.

The problem is as follows:

I am already rescuing from an ActiveRecord::RecordNotFound error and responding with 404 Record Not Found in my ApplicationController because such an error typically arises when a user is attempting to GET, PATCH, PUT, or DELETE a record that does not exist, e.g., get author_path(-1). I would prefer to avoid moving the rescue clause onto the #show, #create, etc methods because I have a lot of controllers, resulting in a lot of duplicate code.

I want to keep my record and association creations atomic and this seems to be the best way to do it, but I also want to respond with a 400 Bad Request when the situation described above occurs. What would be the best way to handle such a situation?

UPDATE

After some more research, I wrote a quick custom validation that validates a record exists for all passed in book_ids

class Author < ApplicationRecord
  validate :books_exist

  def books_exist
    return if book_ids.blank?
    Book.find book_ids
  rescue ActiveRecord::RecordNotFound => e
    errors.add e.message
  end
end

This doesn't seem to work though as even instantiating a new Author instance without saving it to the database throws an ActiveRecord::RecordNotFound error:

> Author.new(association_ids: [-1])
  Book Load (2.3ms) SELECT `books`.* FROM `books` WHERE `books`.`id` = -1
ActiveRecord::RecordNotFound: Couldn't find Book with 'id'=[-1]
  from ...

The issue seems to be that ActiveRecord attempts to find a record for the passed in book_id before any validation occurs. Is there any way to rescue this error? It seems like there's not much of a workaround for this particular issue.

Body:
The two solutions that were suggest to me outside of StackOverflow are as follows:

Rescue the error in each controller action

class AuthorsController
  def create
    @author = Author.create(params)
    render json: @author
  rescue ActiveRecord::RecordNotFound => e
    render json_error_message
  end
end

Create a generic action in the ApplicationController

class ApplicationController
  def create(model)
    instance_variable_set("@#(model.class.name}", model.create(params)
  rescue ActiveRecord::RecordNotFound => e
    render json_error_message
  end
end

class AuthorsController
  def create
    super(Author)
  end
end


问:
Saving DbContext do not save data to database
There is automatically created database for authorize users. I update my database my local tables. There are some tables like Klient, Ulica, Address. Models who describe this tables:

```<code>public partial class Klient
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Klient()
    {
        this.Abonements = new HashSet<Abonement>();
    }

    public int ID_klient { get; set; }
    public string FIO_klient { get; set; }
    public string Telephon { get; set; }
    public Nullable<int> ID_adress { get; set; }
    public string ID_Login { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Abonement> Abonements { get; set; }
    public virtual Adress Adress { get; set; }
}
public partial class Ulica
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Ulica()
    {
        this.Adresses = new HashSet<Adress>();
    }

    public int ID_ulica { get; set; }
    public string Nazvanie_ulicu { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Adress> Adresses { get; set; }
}
public partial class Adress
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Adress()
    {
        this.Klients = new HashSet<Klient>();
        this.Sotrudniks = new HashSet<Sotrudnik>();
    }

    public int ID_adress { get; set; }
    public Nullable<int> Nomer_doma { get; set; }
    public Nullable<int> Nomer_kvartiru { get; set; }
    public Nullable<int> ID_ulica { get; set; }

    public virtual Ulica Ulica { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Klient> Klients { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Sotrudnik> Sotrudniks { get; set; }
}
</code>```

The DbContext of this model is :

```<code>public partial class Entities : DbContext
{
    public Entities()
        : base("name=Entities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<Adress> Adresses { get; set; }
    public virtual DbSet<Klient> Klients { get; set; }
    public virtual DbSet<Ulica> Ulicas { get; set; }
    // and others models of my database
}
</code>```

When I try change standart AccountController and add some data to model Klient on Register method, I add this code to Register method:

```<code>public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
              // some code
              var ulica = new Ulica() { Nazvanie_ulicu = model.Ulica };
                FitnesManager.Ulicas.Add(ulica);
                var adress = new Adress { Ulica = ulica, ID_ulica = ulica.ID_ulica, Nomer_doma = model.Nomer_doma, Nomer_kvartiru = model.Nomer_kvartiru};
                FitnesManager.Adresses.Add(adress);
                var klient = new Klient { FIO_klient = model.FIO, Telephon = model.Telephon, Adress = adress, ID_adress = adress.ID_adress, ID_Login = user.Id };
                var res = FitnesManager.Klients.Add(klient);
                await FitnesManager.SaveChangesAsync();
        }

        // Появление этого сообщения означает наличие ошибки; повторное отображение формы
        return View(model);
    }
</code>```

FitnesManager is DbContext value of AccountController

```<code>public Entities FitnesManager
    {
        get
        {
            return _fitnesManager ?? new Entities();
        }
        private set
        {
            _fitnesManager = value;
        }
    }
</code>```

But when I call Register method any data do not add to database. How do I fix it?

答:
This line is wrong:

```<code>return _fitnesManager ?? new Entities();
</code>```

You are returning a new instance every time.  I think you were going for this style:

```<code>return _fitnesManager ?? (_fitnesManager = new Entities());
</code>```

Either that, or just do this:

```<code>if (_fitnesManager == null)
   _fitnesManager = new Entities();
return _fitnesManager;
</code>```

Body:
There is automatically created database for authorize users. I update my database my local tables. There are some tables like Klient, Ulica, Address. Models who describe this tables:

public partial class Klient
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Klient()
    {
        this.Abonements = new HashSet<Abonement>();
    }

    public int ID_klient { get; set; }
    public string FIO_klient { get; set; }
    public string Telephon { get; set; }
    public Nullable<int> ID_adress { get; set; }
    public string ID_Login { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Abonement> Abonements { get; set; }
    public virtual Adress Adress { get; set; }
}
public partial class Ulica
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Ulica()
    {
        this.Adresses = new HashSet<Adress>();
    }

    public int ID_ulica { get; set; }
    public string Nazvanie_ulicu { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Adress> Adresses { get; set; }
}
public partial class Adress
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Adress()
    {
        this.Klients = new HashSet<Klient>();
        this.Sotrudniks = new HashSet<Sotrudnik>();
    }

    public int ID_adress { get; set; }
    public Nullable<int> Nomer_doma { get; set; }
    public Nullable<int> Nomer_kvartiru { get; set; }
    public Nullable<int> ID_ulica { get; set; }

    public virtual Ulica Ulica { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Klient> Klients { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Sotrudnik> Sotrudniks { get; set; }
}

The DbContext of this model is :

public partial class Entities : DbContext
{
    public Entities()
        : base("name=Entities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<Adress> Adresses { get; set; }
    public virtual DbSet<Klient> Klients { get; set; }
    public virtual DbSet<Ulica> Ulicas { get; set; }
    // and others models of my database
}

When I try change standart AccountController and add some data to model Klient on Register method, I add this code to Register method:

public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
              // some code
              var ulica = new Ulica() { Nazvanie_ulicu = model.Ulica };
                FitnesManager.Ulicas.Add(ulica);
                var adress = new Adress { Ulica = ulica, ID_ulica = ulica.ID_ulica, Nomer_doma = model.Nomer_doma, Nomer_kvartiru = model.Nomer_kvartiru};
                FitnesManager.Adresses.Add(adress);
                var klient = new Klient { FIO_klient = model.FIO, Telephon = model.Telephon, Adress = adress, ID_adress = adress.ID_adress, ID_Login = user.Id };
                var res = FitnesManager.Klients.Add(klient);
                await FitnesManager.SaveChangesAsync();
        }

        // Появление этого сообщения означает наличие ошибки; повторное отображение формы
        return View(model);
    }

FitnesManager is DbContext value of AccountController

public Entities FitnesManager
    {
        get
        {
            return _fitnesManager ?? new Entities();
        }
        private set
        {
            _fitnesManager = value;
        }
    }

But when I call Register method any data do not add to database. How do I fix it?

Body:
This line is wrong:

return _fitnesManager ?? new Entities();

You are returning a new instance every time.  I think you were going for this style:

return _fitnesManager ?? (_fitnesManager = new Entities());

Either that, or just do this:

if (_fitnesManager == null)
   _fitnesManager = new Entities();
return _fitnesManager;


问:
Build debian package without .orig file
I've created packages previously by using a Makefile, the command "dh_make --createorig", then adjusting files in the debian folder generated and finally using the debuild command to generate the .deb. That workflow is simple and works for me, but I was told to adjust it a little in a way that you could build the project from the sources without requiring the orig files and I'm unsure how to do it, but according to this (https://askubuntu.com/questions/17508/how-to-have-debian-packaging-generate-two-packages-given-an-upstream-source-arch) and this structure (http://bazaar.launchpad.net/~andrewsomething/imagination/debian/files) there must be a way. In my case I would have a folder with the sources and all of that and then a debian folder (generated with dh_make) but I'm unsure on how to avoid the debuild command to ask for the .orig files or if I should be using some other command for this.

Sorry for the superlong question, I think I provided all the relevant information, but I can clarify if anything is fuzzy.

答:
I think the question was asked differently, it was somewhat clear that the project was upstream and it's probably not a good reason to change its format to native.

Currently I package some upstream python project, this exact same question came to my mind. Why isn't there any dh_* hook to overwrite in order to generate this origin tarball on the fly so you do not get bothered by:

This package has a Debian revision number but there does not seem to be
an appropriate original tar file or .orig directory in the parent directory;

for a start, I added a makefile to the project:

# Makefile
VERSION:=$(shell dpkg-parsechangelog -S Version | sed -rne 's,([^-\+]+)+(\+dfsg)*.*,\1,p'i)
UPSTREAM_PACKAGE:=click_${VERSION}.orig.tar.gz
dpkg:
  tar cafv ../${UPSTREAM_PACKAGE} . --exclude debian --exclude .git
  debuild -uc -us
clean:
  rm -f ../${UPSTREAM_PACKAGE}
  debuild clean

so a simple make clean dpkg was all it needed to build the package.
Now I think the question remains if someone has some bright idea how to insert the tar operation within the debian/rules so I could just call debuild -uc -us and it magically creates the orig tarball I would be awsome :)

Title: Build debian package without .orig file


答:
If I understood correctly, this should be what you are looking for </p>

```<code>select count(*)
from users u
left join reviews r
on u.id =r.id
where r.modified > u.last_login and u.id = x
</code>```

Title: MySQL - Count how many "items" of one user changed since last login

Body:
I have the following tables:

Table reviews:
(Note: The modified = 00:00:00 is because it used to be a date, now it's a mysql datetime object) (Original Image):

+ -- + ------------- + ---------- + ------ + ------ +
| id | code_reviewer | modified   | course | review |
+ -- + ------------- + ---------- + ------ + ------ +
| 10 | 11            | null       | 1      | ....   |
| 10 | 12            | null       | 1      | ....   |
| 10 | 13            | null       | 1      | ....   |
| 11 | 12            | null       | 1      | ....   |
| 11 | 13            | null       | 1      | ....   |
| 11 | 14            | null       | 1      | ....   |
| 12 | 10            | 2017-03-31 | 1      | ....   |
| 12 | 11            | null       | 1      | ....   |
| 12 | 14            | null       | 1      | ....   |
| 13 | 10            | null       | 1      | ....   |
| 13 | 12            | null       | 1      | ....   |
| 13 | 14            | null       | 1      | ....   |
| 14 | 10            | 2017-03-31 | 1      | ....   |
| 14 | 11            | null       | 1      | ....   |
| 14 | 13            | null       | 1      | ....   |
+ -- + ------------- + ---------- + ------ + ------ +

Table users: (Original Image):

+ -- + ------------------- + ------- +
| id | last_login          | name    |
+ -- + ------------------- + ------- +
| 3  | 2017-03-31 18:06:11 | Jan     |
| 10 | 2017-03-31 18:22:12 | Mama    |
| 11 | 2017-03-31 22:00:55 | Roman   |
| 12 | 2017-03-31 18:06:01 | Bubi    |
| 13 | 0000-00-00 00:00:00 | Oscar   |
| 14 | 0000-00-00 00:00:00 | Vincent |
+ -- + ------------------- + ------- +

This basically is a review system, so that one user can write 3 reviews for another user. These reviews are stored as JSON strings in "reviews"."review". The column "reviews"."code_reviewer" says who writes a review and "reviews"."id" says who will get a review by the code_reviewer.

The users.last_login row and reviews.modified get updated as soon as an user logs in / a review gets updated.

What I want to select:

I basically want to get, how many reviews for a certain user changed since he last loged in. So, it'll select anything between the NOW() and user.last_login date, and only these rows, in which the reviews.id is equal to the user (users.id). This will be used for a kind of "badge feature"

**A good answer should contain two versions of the query:
    * One just as described above, so ALL THE REVIEWS of the user between the certain amuunt of time
    * Another which only returns the reviews the user got in the interval FOR ONE COURSE (the course is an int field). Example: I want all reviews for user Jan (id=1) from the course 1 which got updated between 2017-03-31:18:06:11 (users.last_login) and NOW().

Thanks in advance,
Jan!

Body:
If I understood correctly, this should be what you are looking for

select count(*)
from users u
left join reviews r
on u.id =r.id
where r.modified > u.last_login and u.id = x


问:
Jump div to bottom with out scrolling the page
I have an inner div that contains a list with the most recent list item being at the bottom. The div is part of a larger page. Essentially i want the div to default to the end of the list item and the user will then scroll upwards within the div to see the older content. I do not want the page to be scrolled to the bottom of the div which would occur if i used the following function

```<code>//Slide chat down to bottom
$("#div").scrollTop(function(){
    return $(this).height();
});
</code>```

The outer div would be the page at large. therefore the user would need to scroll down to the inner div and then see the last list item. If they want they can then use the inner scroll bar to look up older items

thanks

答:
You can do that in plain JavaScript:

```<code>var inner = document.querySelector('.inner');
inner.scrollTop = inner.scrollHeight;
</code>```

DEMO

Body:
I have an inner div that contains a list with the most recent list item being at the bottom. The div is part of a larger page. Essentially i want the div to default to the end of the list item and the user will then scroll upwards within the div to see the older content. I do not want the page to be scrolled to the bottom of the div which would occur if i used the following function

//Slide chat down to bottom
$("#div").scrollTop(function(){
    return $(this).height();
});

The outer div would be the page at large. therefore the user would need to scroll down to the inner div and then see the last list item. If they want they can then use the inner scroll bar to look up older items

thanks

Body:
You can do that in plain JavaScript:

var inner = document.querySelector('.inner');
inner.scrollTop = inner.scrollHeight;

DEMO


问:
How to query a table with multiple values in one column with join
Table 1:

```<code>A       B       C
Test    1       This
Test1   1;4     That
Test2   7       What
Test3   6;2     Which
Test4   1;2;7   Where
</code>```

Table 2:

```<code>X       Z
1       Sun
2       Mon
3       Tue
4       Wed
5       Thu
6       Fri
7       Sat
</code>```

Sql:

```<code>Select
    t1.A,
    t2.Z
from
    [dbo].[Table 1] t1
    inner join [dbo].[Table2] t2
    on t1.B = t2.X
</code>```

It works only for the rows that has only 1 entry in B column but fails at the 2 or more entries.

How can I modify the Sql so that it gives me the result like this:

```<code>A       Z
Test    Sun
Test1   Sun;Wed
Test2   Sat
Test3   Fri;Mon
Test4   Sun;Mon;Sat
</code>```

答:
Fun with Strings and XML, here is a little (scaled-down) technique to tokenize data.

Create Some Sample Data

```<code>Declare @Table1 table (A varchar(100),B varchar(100), C varchar(100))
Insert Into @Table1 values
('Test','1','This'),('Test1','1;4','That'),('Test2','7','What'),('Test3','6;2','Which'),('Test4','1;2;7','Where')

Declare @Table2 table (X int,Z varchar(100))
Insert Into @Table2 values
(1,'Sun'),(2,'Mon'),(3,'Tue'),(4,'Wed'),(5,'Thu'),(6,'Fri'),(7,'Sat')
</code>```

The SQL

```<code>Declare @XML xml,@Str varchar(max) = (Select a,z='['+replace(b,';','];[')+']' From  @Table1 For XML Raw)
Select @Str = Replace(@Str,'['+cast(X as varchar(25))+']',Z) From  @Table2
Select @XML = @Str

Select a = r.value('@a','varchar(100)')
      ,z = r.value('@z','varchar(100)')
From  @XML.nodes('/row') as A(r)
</code>```

Returns

```<code>a       z
Test    Sun
Test1   Sun;Wed
Test2   Sat
Test3   Fri;Mon
Test4   Sun;Mon;Sat
</code>```

Body:
Table 1:

A       B       C
Test    1       This
Test1   1;4     That
Test2   7       What
Test3   6;2     Which
Test4   1;2;7   Where

Table 2:

X       Z
1       Sun
2       Mon
3       Tue
4       Wed
5       Thu
6       Fri
7       Sat

Sql:

Select
    t1.A,
    t2.Z
from
    [dbo].[Table 1] t1
    inner join [dbo].[Table2] t2
    on t1.B = t2.X

It works only for the rows that has only 1 entry in B column but fails at the 2 or more entries.

How can I modify the Sql so that it gives me the result like this:

A       Z
Test    Sun
Test1   Sun;Wed
Test2   Sat
Test3   Fri;Mon
Test4   Sun;Mon;Sat

Body:
Fun with Strings and XML, here is a little (scaled-down) technique to tokenize data.

Create Some Sample Data

Declare @Table1 table (A varchar(100),B varchar(100), C varchar(100))
Insert Into @Table1 values
('Test','1','This'),('Test1','1;4','That'),('Test2','7','What'),('Test3','6;2','Which'),('Test4','1;2;7','Where')

Declare @Table2 table (X int,Z varchar(100))
Insert Into @Table2 values
(1,'Sun'),(2,'Mon'),(3,'Tue'),(4,'Wed'),(5,'Thu'),(6,'Fri'),(7,'Sat')

The SQL

Declare @XML xml,@Str varchar(max) = (Select a,z='['+replace(b,';','];[')+']' From  @Table1 For XML Raw)
Select @Str = Replace(@Str,'['+cast(X as varchar(25))+']',Z) From  @Table2
Select @XML = @Str

Select a = r.value('@a','varchar(100)')
      ,z = r.value('@z','varchar(100)')
From  @XML.nodes('/row') as A(r)

Returns

a       z
Test    Sun
Test1   Sun;Wed
Test2   Sat
Test3   Fri;Mon
Test4   Sun;Mon;Sat


问:
Round numbers to 50 thousands in Python
How can I round a number to the nearest up or down 50 thousand?

I want to round this 542756 to this 550000, or round this 521405 to this 500000. Considering that the number to be rounded is a variable x.

I tried this:

```<code>import math

def roundup(x):
    return int(math.ceil(x / 50000.0)) * 50000
</code>```

But it only round up and I need to round both up or down.

I also tried this:

```<code>round(float(x), -5)
</code>```

But this round to the nearest hundred thousand.

I suppose there is a simple solution but couldn't find anything.

答:
You can use:

```<code>def round_nearest(x,num=50000):
    return int(round(float(x)/num)*num)
</code>```

You can also avoid converting to floating point if you deal with large numbers. In that case, you can use:

```<code>def round_nearest<b>_large</b>(x,num=50000):
    return ((x+num//2)//num)*num</code>```

You can call it with two arguments to round to the nearest num, or without will round to the nearest 50000. You can omit the int(..) if you do not want the result to be an int(..) per se (for instance if you want to round on 0.5 as well). In that case we can define:

```<code>def round_nearest<b>_float</b>(x,num=50000):
    return round(float(x)/num)*num</code>```

This produces:

```<code>>>> round_nearest(542756)
550000
>>> round_nearest(521405)
500000
</code>```

Or if you want another number to round to:

```<code>>>> round_nearest(542756,1000)
543000
>>> round_nearest(542756,200000)
600000
</code>```

Title: Round numbers to 50 thousands in Python

Body:
How can I round a number to the nearest up or down 50 thousand?

I want to round this 542756 to this 550000, or round this 521405 to this 500000. Considering that the number to be rounded is a variable x.

I tried this:

import math

def roundup(x):
    return int(math.ceil(x / 50000.0)) * 50000

But it only round up and I need to round both up or down.

I also tried this:

round(float(x), -5)

But this round to the nearest hundred thousand.

I suppose there is a simple solution but couldn't find anything.

Body:
You can use:

def round_nearest(x,num=50000):
    return int(round(float(x)/num)*num)

You can also avoid converting to floating point if you deal with large numbers. In that case, you can use:

def round_nearest_large(x,num=50000):
    return ((x+num//2)//num)*num

You can call it with two arguments to round to the nearest num, or without will round to the nearest 50000. You can omit the int(..) if you do not want the result to be an int(..) per se (for instance if you want to round on 0.5 as well). In that case we can define:

def round_nearest_float(x,num=50000):
    return round(float(x)/num)*num

This produces:

>>> round_nearest(542756)
550000
>>> round_nearest(521405)
500000

Or if you want another number to round to:

>>> round_nearest(542756,1000)
543000
>>> round_nearest(542756,200000)
600000


问:
How to enter different types parameters into function to return one type data?
l want to enter different types parameters (such as:int,float,double,long) into function to return one type data(such as:string).

Here l just wanna make a function to turn different type data to be string data.

答:
I'm not sure if I understood your requirement correctly but may be you should do something like,

```<code>static String fun(Object object)
{
    if (object==null)
    {
        return null;
    }
    else
        return new String(object.toString());
}
</code>```

and make call like,

```<code>String val = fun(3.4);
</code>```

Body:
I'm not sure if I understood your requirement correctly but may be you should do something like,

static String fun(Object object)
{
    if (object==null)
    {
        return null;
    }
    else
        return new String(object.toString());
}

and make call like,

String val = fun(3.4);


问:
Select rows where string does not repeat
I'm not sure how to phrase this, but I have two tables that I use INNER JOIN on to count the number of records I have. This works fine but the problem is that I have some rows in table1 where some of the records have a string that can appear in another record. Something like this:

```<code>table1                   table2
------                   ------
id    string             id    table1_id    some_column
01    aaa                01    01           1
02    bbb                02    02           3
03    aaa                03    03           1
04    ccc                04    04           4
05    bbb                05    05           2
...                      ...
</code>```

My query looks like this:

```<code>SELECT COUNT(*) FROM table1
INNER JOIN table2 ON table1.id = table2.table1_id
</code>```

This query works fine, but I want to be able to get distinct values. So my query should bring me back only these records:

```<code>table1                   table2
------                   ------
id    string             id    table1_id    some_column
01    aaa                01    01           1
02    bbb                02    02           3
04    ccc                04    04           4
...                      ...
</code>```

As you can see, it doesn't show any additional records where they share the same string. What would I write after or before my INNER JOIN? Any help would be appreciated.

答:
You can group by the table 1 </p>

```<code>select count(*)
from (
    select min(id) as id, string
    from table1
    group by string
) t1
inner join table2 on t1.id = table2.table1_id
</code>```

Body:
I'm not sure how to phrase this, but I have two tables that I use INNER JOIN on to count the number of records I have. This works fine but the problem is that I have some rows in table1 where some of the records have a string that can appear in another record. Something like this:

table1                   table2
------                   ------
id    string             id    table1_id    some_column
01    aaa                01    01           1
02    bbb                02    02           3
03    aaa                03    03           1
04    ccc                04    04           4
05    bbb                05    05           2
...                      ...

My query looks like this:

SELECT COUNT(*) FROM table1
INNER JOIN table2 ON table1.id = table2.table1_id

This query works fine, but I want to be able to get distinct values. So my query should bring me back only these records:

table1                   table2
------                   ------
id    string             id    table1_id    some_column
01    aaa                01    01           1
02    bbb                02    02           3
04    ccc                04    04           4
...                      ...

As you can see, it doesn't show any additional records where they share the same string. What would I write after or before my INNER JOIN? Any help would be appreciated.

Body:
You can group by the table 1

select count(*)
from (
    select min(id) as id, string
    from table1
    group by string
) t1
inner join table2 on t1.id = table2.table1_id


问:
WPF: message box with checkbox added
In WPF I am looking for a "do not show again" checkbox on my messagebox popup.

Does anyone know where I can get such a control or maybe how to copy the style of the regular WPF messagebox so I can create my own?

Thanks

答: I think , you may have to create  by yourself  and it is really easy in the WPF</p>

Title: WPF: message box with checkbox added


问:
A JavaScript function is repeated many times
I have two function print and callPrint bellow. I click call function print the first time is right.
But when click call function print the second or third then function callPrint will be call 2 times or 3 times.
I have debug on attack file.

```<code>function print(url) {
    console.log('print');
    var _this = this, iframeId = 'iframeprint', $iframe = $('iframe#iframeprint');
    if ($iframe.attr('src') != url) {
        $.when(
            $iframe.attr('src', 'about:blank'),
            $iframe.load(function () {
                console.log($iframe.prop('contentWindow').document.readyState);
            })
        ).done(function () {
            $iframe.attr('src', url);
            $iframe.load(function () {
                console.log('new');
                _this.callPrint(iframeId);
            });
        });
    } else {
        console.log('old');
        _this.callPrint(iframeId);
    }
}

// initiates print once content has been loaded into iframe
function callPrint(iframeId) {
    console.log('callPrint');
    $('div.wait').hide();
    var PDF = document.getElementById(iframeId);
    PDF.focus();
    PDF.contentWindow.print();
    return false;
}
</code>```

A JavaScript function is repeated many times

答:
Thanks "Rory McCrossan". I add setTimeout function when callPrint so dialog print will open. But I can't vote for you at the moment.</p>

```<code>var $iframe = $('iframe#iframeprint').load(function () {
    // You'll need to make sure the function is in scope of the handler
    // There's not enough information in the OP for me to show you how
    setTimeout(function () {
        callPrint('iframeprint');
    }, 100);
});
function print(url) {
    if ($iframe.attr('src') != url) {
        $iframe.attr('src', url);
    } else {
        console.log('old');
        callPrint('iframeprint');
    }
}

// initiates print once content has been loaded into iframe
function callPrint(iframeId) {
    $('div.wait').hide();
    var PDF = document.getElementById(iframeId);
    PDF.focus();
    PDF.contentWindow.print();
}
</code>```

Body:
I have two function print and callPrint bellow. I click call function print the first time is right.
But when click call function print the second or third then function callPrint will be call 2 times or 3 times.
I have debug on attack file.

function print(url) {
    console.log('print');
    var _this = this, iframeId = 'iframeprint', $iframe = $('iframe#iframeprint');
    if ($iframe.attr('src') != url) {
        $.when(
            $iframe.attr('src', 'about:blank'),
            $iframe.load(function () {
                console.log($iframe.prop('contentWindow').document.readyState);
            })
        ).done(function () {
            $iframe.attr('src', url);
            $iframe.load(function () {
                console.log('new');
                _this.callPrint(iframeId);
            });
        });
    } else {
        console.log('old');
        _this.callPrint(iframeId);
    }
}

// initiates print once content has been loaded into iframe
function callPrint(iframeId) {
    console.log('callPrint');
    $('div.wait').hide();
    var PDF = document.getElementById(iframeId);
    PDF.focus();
    PDF.contentWindow.print();
    return false;
}

A JavaScript function is repeated many times

Body:
Thanks "Rory McCrossan". I add setTimeout function when callPrint so dialog print will open. But I can't vote for you at the moment.

var $iframe = $('iframe#iframeprint').load(function () {
    // You'll need to make sure the function is in scope of the handler
    // There's not enough information in the OP for me to show you how
    setTimeout(function () {
        callPrint('iframeprint');
    }, 100);
});
function print(url) {
    if ($iframe.attr('src') != url) {
        $iframe.attr('src', url);
    } else {
        console.log('old');
        callPrint('iframeprint');
    }
}

// initiates print once content has been loaded into iframe
function callPrint(iframeId) {
    $('div.wait').hide();
    var PDF = document.getElementById(iframeId);
    PDF.focus();
    PDF.contentWindow.print();
}


答:
```<code>def round_nearest(x, multiple):
    return math.floor(float(x) / multiple + 0.5) * multiple

>>> round_nearest(542756, 50000)
550000
>>> round_nearest(521405, 50000)
500000
</code>```

Title: Round numbers to 50 thousands in Python


问:
SSIS Package with Excel as source
I have an Excel sheet with some headers and logos in it. I want to create a SSIS package of that Excel but when I created the package I am not getting the required column names. How do I get the exact column names in SQl as in Excel sheet ?

This is the sheet i am working with

答:
I can't see your image because it is blocked by my firm's firewall, but I think you should take a look at these links.

https://www.simple-talk.com/sql/ssis/moving-data-from-excel-to-sql-server-10-steps-to-follow/

https://www.simple-talk.com/sql/ssis/importing-excel-data-into-sql-server-via-ssis-questions-you-were-too-shy-to-ask/

https://www.codeproject.com/Tips/846480/Import-Data-from-Excel-to-SQL-Using-SSIS-Dynamic-C

https://www.sqlshack.com/using-ssis-packages-import-ms-excel-data-database/

Title: SSIS Package with Excel as source


问:
Defining public ranges
I create in a sub custom ranges using the following code:

```<code>Dim custom_range(1 To 5) As Range

Set custom_range(1) = ActiveWorkbook.Sheets("Countries").Columns(5).Cells
Set custom_range(2) = ActiveWorkbook.Sheets("Operations").Columns(2).Cells
Set custom_range(3) = ActiveWorkbook.Sheets("Costs").Columns(2).Cells
Set custom_range(4) = ActiveWorkbook.Sheets("Revenue").Columns(2).Cells
Set custom_range(5) = ActiveWorkbook.Sheets("FS").Columns(2).Cells
</code>```

The issue I'm facing is that I use the same code in several subs, but I'd like to do it only once.

Creating public sub and then calling it unfortunately doesn't work.

Any ideas?

答:
I might get "rotten tomatoes" here for posting this, but you could use the simple Init sub below.

Just put it in a separate code module, and everywhere you need to use these custom_range array, just Call this sub.

Code (in Init Module)

```<code>Option Explicit

Public custom_range(1 To 5) As Range

Sub Init()

Set custom_range(1) = ActiveWorkbook.Sheets("Countries").Columns(5).Cells
Set custom_range(2) = ActiveWorkbook.Sheets("Operations").Columns(2).Cells
Set custom_range(3) = ActiveWorkbook.Sheets("Costs").Columns(2).Cells
Set custom_range(4) = ActiveWorkbook.Sheets("Revenue").Columns(2).Cells
Set custom_range(5) = ActiveWorkbook.Sheets("FS").Columns(2).Cells

End Sub
</code>```

Title: Defining public ranges

Body:
I create in a sub custom ranges using the following code:

Dim custom_range(1 To 5) As Range

Set custom_range(1) = ActiveWorkbook.Sheets("Countries").Columns(5).Cells
Set custom_range(2) = ActiveWorkbook.Sheets("Operations").Columns(2).Cells
Set custom_range(3) = ActiveWorkbook.Sheets("Costs").Columns(2).Cells
Set custom_range(4) = ActiveWorkbook.Sheets("Revenue").Columns(2).Cells
Set custom_range(5) = ActiveWorkbook.Sheets("FS").Columns(2).Cells

The issue I'm facing is that I use the same code in several subs, but I'd like to do it only once.

Creating public sub and then calling it unfortunately doesn't work.

Any ideas?

Body:
I might get "rotten tomatoes" here for posting this, but you could use the simple Init sub below.

Just put it in a separate code module, and everywhere you need to use these custom_range array, just Call this sub.

Code (in Init Module)

Option Explicit

Public custom_range(1 To 5) As Range

Sub Init()

Set custom_range(1) = ActiveWorkbook.Sheets("Countries").Columns(5).Cells
Set custom_range(2) = ActiveWorkbook.Sheets("Operations").Columns(2).Cells
Set custom_range(3) = ActiveWorkbook.Sheets("Costs").Columns(2).Cells
Set custom_range(4) = ActiveWorkbook.Sheets("Revenue").Columns(2).Cells
Set custom_range(5) = ActiveWorkbook.Sheets("FS").Columns(2).Cells

End Sub


问:
Ionic 2 / Angular - Manipulating JSON
I'm have a trouble to list a json file.

My code:

```<code>    this.http
      .post(link, data, options)
      .map(res => res.json().d)
      .subscribe(
          data => {
            this.profile = JSON.parse(data);
            console.log(this.profile);
          },
          err => {
            console.log("ERROR!: ", err);
          }
      );
</code>```

Console.log print this:

Object {user: Object, class: Array(1)}

```<code>{
   "user":{
      "name":"Name",
      "date":"19880210",
      "email":"test@test.com",
      "about":"About me",
      "picuteUrl":"http://www.url.com/Midia/User/picture.jpeg",
   },
   "class":[
      {
         "id":"82",
         "name":"Class 01"
      }
   ]
}
</code>```

I can also get these values in the TypeScript file

```<code>console.log(this.profile.user.name);
console.log(this.profile.class[0]);
console.log(this.profile.class[0].name);
</code>```

But in html code i dont get this values.

```<code><input type="text" value="{{profile.user.name}}">
</code>```

ERROR:

```<code>ion-dev.js?v=1.1.4:156 TypeError: Cannot read property 'usuario' of undefined
</code>```

答:
There is no where you are accessing, usuario in the provided code. You could use elvis/safe operator to check if the valaues are present

```<code><input type="text" value="{{profile?.user?.name}}">
</code>```

Title: Ionic 2 / Angular - Manipulating JSON

Body:
I'm have a trouble to list a json file.

My code:

    this.http
      .post(link, data, options)
      .map(res => res.json().d)
      .subscribe(
          data => {
            this.profile = JSON.parse(data);
            console.log(this.profile);
          },
          err => {
            console.log("ERROR!: ", err);
          }
      );

Console.log print this:

Object {user: Object, class: Array(1)}

{
   "user":{
      "name":"Name",
      "date":"19880210",
      "email":"test@test.com",
      "about":"About me",
      "picuteUrl":"http://www.url.com/Midia/User/picture.jpeg",
   },
   "class":[
      {
         "id":"82",
         "name":"Class 01"
      }
   ]
}

I can also get these values in the TypeScript file

console.log(this.profile.user.name);
console.log(this.profile.class[0]);
console.log(this.profile.class[0].name);

But in html code i dont get this values.

<input type="text" value="{{profile.user.name}}">

ERROR:

ion-dev.js?v=1.1.4:156 TypeError: Cannot read property 'usuario' of undefined

Body:
There is no where you are accessing, usuario in the provided code. You could use elvis/safe operator to check if the valaues are present

<input type="text" value="{{profile?.user?.name}}">


问:
Parsing Json and store data in sqlite database and view in a listView
Hi all I am developing an app that collects data from a fake site rest bees and stores them in a listView. So far I managed to download the JSON file and display it in a listView. These are my classes:

HomeScreen.java

```<code>import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class HomeScreen extends AppCompatActivity {
     private String classtag= HomeScreen.class.getSimpleName();  //return
        name of underlying class
     private ListView lv;
     private ProgressDialog progress;
     private String url="https://jsonplaceholder.typicode.com/posts";
     //passing url
     ArrayList<HashMap<String,String>> studentslist; //arraylist to save key
     value pair from json
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_home_screen);
         studentslist=new ArrayList<>();
         lv= (ListView) findViewById(R.id.list); //from home screen listview
         new getStudents().execute(); // it will execute your AsyncTask
     }
//--------------------------//-------------------------------//---------------------//
   public class getStudents extends AsyncTask<Void,Void,Void> {
        protected void onPreExecute(){
            super.onPreExecute(); //it will use pre defined preExecute
                                  method in async task
             progress=new ProgressDialog(HomeScreen.this);
             progress.setMessage("Fetching JSON.,."); // show what you want
                                                      in the progress dialog
             progress.setCancelable(false); //progress dialog is not
                                            cancellable here
            progress.show();
        }
        protected Void doInBackground(Void...arg0){
            HTTP_Handler hh = new HTTP_Handler(); // object of HTTP_Handler
            String jString = hh.makeHTTPCall(url); //calling makeHTTPCall
                                  method and string its response in a string
            Log.e(classtag, "Response from URL: " + jString);
            if (jString != null) {
            try {
                JSONArray students = new JSONArray(jString);
                 //our json data starts with the object
                 //fetch array from studentsinfo object
                for (int i = 0; i < students.length(); i++) {
                    JSONObject obj = students.getJSONObject(i); //get object
                                                                from i index
                    String userId=obj.getString("userId");   //save string
                                            from variable 'id' to string
                    String id=obj.getString("id");
                    String title=obj.getString("title");
                    String body=obj.getString("body");
                    HashMap<String, String> studentdata = new HashMap<>();
                      //create a hash map to set key and value pair

                    studentdata.put("userId", userId); //hash map will save
                                                    key and its value
                    studentdata.put("id", id);
                    studentdata.put("title", title);
                    studentdata.put("body", body);

                    studentslist.add(studentdata); //now save all of the key
                                                    value pairs to arraylist
                }
            } catch (final JSONException e) {
                Log.e(classtag, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show(); //show if you catch any exception
                                                                 with data
                    }
                });
            }
        } else {
            Log.e(classtag, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {Toast.makeText(getApplicationContext(),
                        "Couldn't get json from server. Check internet
                                                    connection!",
                        Toast.LENGTH_LONG).show();//show if you are unable
                        to connect with the internet or if jString is null
                }
            });
        }
        return null;
    }
    protected void onPostExecute(Void Result){
        super.onPostExecute(Result);
        if(progress.isShowing()){
            progress.dismiss();
        }
        ListAdapter adapter=new SimpleAdapter(
                HomeScreen.this,
                studentslist,
                R.layout.bucket_list,
                new String[]{"userId","id","title","body"},
                new int[]{R.id.list_Name,R.id.list_Email,R.id.list_Address
                                                       ,R.id.list_Gender});
        lv.setAdapter(adapter);

        }
    }
}
</code>```

Http_Handler.java

```<code>import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class HTTP_Handler {
      private static final String classtag=
      HTTP_Handler.class.getSimpleName();  //return name of underlying class

public String makeHTTPCall(String URLinput) { // method which will request
               to server when provided with url
    String response = null;
    try {
        URL url = new URL(URLinput);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //to open connection with url
        conn.setRequestMethod("GET");   //request type is of GET, which
                           means to get information from the server

        InputStream in = new BufferedInputStream(conn.getInputStream());
         //storing the input stream we are getting for the url
        response = InputStreamToString(in); //now storing string from the
                                            input stream
    } catch (MalformedURLException e) {
        Log.e(classtag, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(classtag, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(classtag, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(classtag, "Exception: " + e.getMessage());
    }
    return response; //returning whatever we fetching from the string to the
                     method.
  }
private String InputStreamToString(InputStream is) {   //fetching string
    form the input stream
    BufferedReader br = new BufferedReader(new InputStreamReader(is)); //it
    will read form stream
    StringBuilder sb = new StringBuilder();
    String line;
    try {
        while ((line = br.readLine()) != null) {
            sb.append(line).append('\n'); //whatever we read from the
            stream, we will append it to the stringbuilder
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
           } catch (IOException e) {
            e.printStackTrace();
           }
       }
    return sb.toString();
    }
}
</code>```

Could someone help me to integrate the saving in SQLite database and display ever in a listView.
Thanks in advance for the help.

答:
Try these links:

Json Parsing:

http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

Database:

http://www.vogella.com/tutorials/AndroidSQLite/article.html

These will give you a good idea on how to approach these things.

Body:
Hi all I am developing an app that collects data from a fake site rest bees and stores them in a listView. So far I managed to download the JSON file and display it in a listView. These are my classes:

HomeScreen.java

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class HomeScreen extends AppCompatActivity {
     private String classtag= HomeScreen.class.getSimpleName();  //return
        name of underlying class
     private ListView lv;
     private ProgressDialog progress;
     private String url="https://jsonplaceholder.typicode.com/posts";
     //passing url
     ArrayList<HashMap<String,String>> studentslist; //arraylist to save key
     value pair from json
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_home_screen);
         studentslist=new ArrayList<>();
         lv= (ListView) findViewById(R.id.list); //from home screen listview
         new getStudents().execute(); // it will execute your AsyncTask
     }
//--------------------------//-------------------------------//---------------------//
   public class getStudents extends AsyncTask<Void,Void,Void> {
        protected void onPreExecute(){
            super.onPreExecute(); //it will use pre defined preExecute
                                  method in async task
             progress=new ProgressDialog(HomeScreen.this);
             progress.setMessage("Fetching JSON.,."); // show what you want
                                                      in the progress dialog
             progress.setCancelable(false); //progress dialog is not
                                            cancellable here
            progress.show();
        }
        protected Void doInBackground(Void...arg0){
            HTTP_Handler hh = new HTTP_Handler(); // object of HTTP_Handler
            String jString = hh.makeHTTPCall(url); //calling makeHTTPCall
                                  method and string its response in a string
            Log.e(classtag, "Response from URL: " + jString);
            if (jString != null) {
            try {
                JSONArray students = new JSONArray(jString);
                 //our json data starts with the object
                 //fetch array from studentsinfo object
                for (int i = 0; i < students.length(); i++) {
                    JSONObject obj = students.getJSONObject(i); //get object
                                                                from i index
                    String userId=obj.getString("userId");   //save string
                                            from variable 'id' to string
                    String id=obj.getString("id");
                    String title=obj.getString("title");
                    String body=obj.getString("body");
                    HashMap<String, String> studentdata = new HashMap<>();
                      //create a hash map to set key and value pair

                    studentdata.put("userId", userId); //hash map will save
                                                    key and its value
                    studentdata.put("id", id);
                    studentdata.put("title", title);
                    studentdata.put("body", body);

                    studentslist.add(studentdata); //now save all of the key
                                                    value pairs to arraylist
                }
            } catch (final JSONException e) {
                Log.e(classtag, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show(); //show if you catch any exception
                                                                 with data
                    }
                });
            }
        } else {
            Log.e(classtag, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {Toast.makeText(getApplicationContext(),
                        "Couldn't get json from server. Check internet
                                                    connection!",
                        Toast.LENGTH_LONG).show();//show if you are unable
                        to connect with the internet or if jString is null
                }
            });
        }
        return null;
    }
    protected void onPostExecute(Void Result){
        super.onPostExecute(Result);
        if(progress.isShowing()){
            progress.dismiss();
        }
        ListAdapter adapter=new SimpleAdapter(
                HomeScreen.this,
                studentslist,
                R.layout.bucket_list,
                new String[]{"userId","id","title","body"},
                new int[]{R.id.list_Name,R.id.list_Email,R.id.list_Address
                                                       ,R.id.list_Gender});
        lv.setAdapter(adapter);

        }
    }
}

Http_Handler.java

import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class HTTP_Handler {
      private static final String classtag=
      HTTP_Handler.class.getSimpleName();  //return name of underlying class

public String makeHTTPCall(String URLinput) { // method which will request
               to server when provided with url
    String response = null;
    try {
        URL url = new URL(URLinput);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //to open connection with url
        conn.setRequestMethod("GET");   //request type is of GET, which
                           means to get information from the server

        InputStream in = new BufferedInputStream(conn.getInputStream());
         //storing the input stream we are getting for the url
        response = InputStreamToString(in); //now storing string from the
                                            input stream
    } catch (MalformedURLException e) {
        Log.e(classtag, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(classtag, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(classtag, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(classtag, "Exception: " + e.getMessage());
    }
    return response; //returning whatever we fetching from the string to the
                     method.
  }
private String InputStreamToString(InputStream is) {   //fetching string
    form the input stream
    BufferedReader br = new BufferedReader(new InputStreamReader(is)); //it
    will read form stream
    StringBuilder sb = new StringBuilder();
    String line;
    try {
        while ((line = br.readLine()) != null) {
            sb.append(line).append('\n'); //whatever we read from the
            stream, we will append it to the stringbuilder
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
           } catch (IOException e) {
            e.printStackTrace();
           }
       }
    return sb.toString();
    }
}

Could someone help me to integrate the saving in SQLite database and display ever in a listView.
Thanks in advance for the help.


问:
Can I prevent an ng-model update with an asyncValidator?
I have an application where certain options do not play nicely together.  In the case where a user has chosen a pair of options that may lead to poor performance, we show a dialog where the user has to agree to acknowledge that they're asking for a lot of data and we may not be able to satisfy the request.

Since the dialog service returns a promise that can be fulfilled or rejected depending on what the user wants to do, This seems like a pretty great place to add an async validator on the NgModelController.  I've written up a plunker to demonstrate the scenario and my attempt at a solution.

The guts of it are:

Html

```<code><body ng-controller="MainCtrl as ctrl">
  <br>
  Allow chili
  <input type="checkbox" ng-model="ctrl.allowChili">
  <br>
  <select
      ng-model="ctrl.val"
      ng-model-options="{allowInvalid: false}"
      validate-async="ctrl.validateAsync($modelVal)"
      ng-change="ctrl.tellMe()">
    <option value="very">very</option>
    <option value="chili">chili</option>
    <option value="jalepeno">jalepeno</option>
  </select>
  <br>
  <p>The food is {{ctrl.val}} spicy!</p>
</body>
</code>```

JS

```<code>var myApp = angular.module('plunker', []);

myApp.controller('MainCtrl', ['$q', '$scope', function($q, $scope) {
    this.val = 'very';
    this.allowChili = false;

    this.validateAsync = function(modelVal) {
      console.log(modelVal);
      if (modelVal != 'chili' || this.allowChili) {
        console.log('Accepting validation');
        return $q.when();
      } else {
        console.log('Rejecting validation');
        return $q.reject();
      }
    };

    this.tellMe = function() {
      // In my application, this actually issues an HTTP request to get new
      // data and update the view.
      alert('model value changed');
    };
}]);

myApp.directive('validateAsync', ['$q', function($q) {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: linkFn,
  };
  function linkFn(scope, element, attrs, ngModelCtrl) {
    ngModelCtrl.$asyncValidators.myValidator = function(modelVal, viewVal) {
      var args = {
        '$modelVal': modelVal,
        '$viewVal': viewVal,
      };
      return $q.when(scope.$eval(attrs['validateAsync'], args));
    };
  }
}]);
</code>```

Unfortunately, there are a few problems.  When a the async validator promise is rejected two bad things happen:

Change listeners (e.g. ng-change) still fire and my view still gets updated.

The new model value appears to be undefined whereas I'd like to prevent it from changing at all.

How can an NgModelController prevent a staged change from being committed based on the status of a promise?

答:
Here's a plunker of an ugly hack that I think I can adapt to my use-case.  The guts of the changes are in the validateAsync directive:

```<code>myApp.directive('validateAsync', ['$q', function($q) {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: linkFn,
  };
  function linkFn(scope, element, attrs, ngModelCtrl) {
    var ngModelCtrl$setViewValue = ngModelCtrl.$setViewValue;
    ngModelCtrl.$setViewValue = function(value, trigger) {
      var args = {
        '$val': value,
        '$trigger': trigger,
      };
      $q.when(scope.$eval(attrs['validateAsync'], args)).then(function() {
        ngModelCtrl$setViewValue.call(ngModelCtrl, value, trigger);
      });
    };
  }
}]);
</code>```

(with appropriate template changes to use $val rather than $modelVal).

Basically, I'm hijacking NgModelController.$setViewValue and not calling the base implementation if the promise is rejected.  In the demo plunker, you'll see that the select element still changes.  I believe that's OK with my designers (and if it isn't, I have the power to fix it in my use-case since I'm not actually using <select> elements -- I'm using a custom directive for picking the values that I have full control over when it updates).

Body:
I have an application where certain options do not play nicely together.  In the case where a user has chosen a pair of options that may lead to poor performance, we show a dialog where the user has to agree to acknowledge that they're asking for a lot of data and we may not be able to satisfy the request.

Since the dialog service returns a promise that can be fulfilled or rejected depending on what the user wants to do, This seems like a pretty great place to add an async validator on the NgModelController.  I've written up a plunker to demonstrate the scenario and my attempt at a solution.

The guts of it are:

Html

  Allow chili
  <input type="checkbox" ng-model="ctrl.allowChili">

  <select
      ng-model="ctrl.val"
      ng-model-options="{allowInvalid: false}"
      validate-async="ctrl.validateAsync($modelVal)"
      ng-change="ctrl.tellMe()">
    <option value="very">very</option>
    <option value="chili">chili</option>
    <option value="jalepeno">jalepeno</option>
  </select>

The food is {{ctrl.val}} spicy!

JS

var myApp = angular.module('plunker', []);

myApp.controller('MainCtrl', ['$q', '$scope', function($q, $scope) {
    this.val = 'very';
    this.allowChili = false;

    this.validateAsync = function(modelVal) {
      console.log(modelVal);
      if (modelVal != 'chili' || this.allowChili) {
        console.log('Accepting validation');
        return $q.when();
      } else {
        console.log('Rejecting validation');
        return $q.reject();
      }
    };

    this.tellMe = function() {
      // In my application, this actually issues an HTTP request to get new
      // data and update the view.
      alert('model value changed');
    };
}]);

myApp.directive('validateAsync', ['$q', function($q) {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: linkFn,
  };
  function linkFn(scope, element, attrs, ngModelCtrl) {
    ngModelCtrl.$asyncValidators.myValidator = function(modelVal, viewVal) {
      var args = {
        '$modelVal': modelVal,
        '$viewVal': viewVal,
      };
      return $q.when(scope.$eval(attrs['validateAsync'], args));
    };
  }
}]);

Unfortunately, there are a few problems.  When a the async validator promise is rejected two bad things happen:

Change listeners (e.g. ng-change) still fire and my view still gets updated.

The new model value appears to be undefined whereas I'd like to prevent it from changing at all.

How can an NgModelController prevent a staged change from being committed based on the status of a promise?

Body:
Here's a plunker of an ugly hack that I think I can adapt to my use-case.  The guts of the changes are in the validateAsync directive:

myApp.directive('validateAsync', ['$q', function($q) {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: linkFn,
  };
  function linkFn(scope, element, attrs, ngModelCtrl) {
    var ngModelCtrl$setViewValue = ngModelCtrl.$setViewValue;
    ngModelCtrl.$setViewValue = function(value, trigger) {
      var args = {
        '$val': value,
        '$trigger': trigger,
      };
      $q.when(scope.$eval(attrs['validateAsync'], args)).then(function() {
        ngModelCtrl$setViewValue.call(ngModelCtrl, value, trigger);
      });
    };
  }
}]);

(with appropriate template changes to use $val rather than $modelVal).

Basically, I'm hijacking NgModelController.$setViewValue and not calling the base implementation if the promise is rejected.  In the demo plunker, you'll see that the select element still changes.  I believe that's OK with my designers (and if it isn't, I have the power to fix it in my use-case since I'm not actually using <select> elements -- I'm using a custom directive for picking the values that I have full control over when it updates).


问:
Is there a difference between :: and . when calling class methods in Ruby?
Simple question, but one that I've been curious about...is there a functional difference between the following two commands?

```<code>String::class
String.class
</code>```

They both do what I expect -- that is to say they return Class -- but what is the difference between using the :: and the .?

I notice that on those classes that have constants defined, IRB's auto-completion will return the constants as available options when you press tab after :: but not after ., but I don't know what the reason for this is...

答:
The . operator basically says "send this message to the object". In your example it is calling that particular member. The :: operator "drills down" to the scope defined to the left of the operator, and then calls the member defined on the right side of operator.

When you use :: you have to be referencing members that are defined. When using . you are simply sending a message to the object. Because that message could be anything, auto-completion does not work for . while it does for ::.

OwnerDisplayName: Nathan Fritz

Body:
Simple question, but one that I've been curious about...is there a functional difference between the following two commands?

String::class
String.class

They both do what I expect -- that is to say they return Class -- but what is the difference between using the :: and the .?

I notice that on those classes that have constants defined, IRB's auto-completion will return the constants as available options when you press tab after :: but not after ., but I don't know what the reason for this is...

OwnerDisplayName: Joseph Daigle

LastEditorDisplayName: Joseph Daigle


问:
Restarting a Python Interpreter Quietly
I have a python interpreter embedded inside an application. The application takes a long time to start up and I have no ability to restart the interpreter without restarting the whole application. What I would like to do is to essentially save the state of the interpreter and return to that state easily.

I started by storing the names of all modules in sys.modules that the python interpreter started with and then deleting all new modules from sys.modules when requested. This appears to make the interpreter prepared to re-import the same modules even though it has already imported them before. However, this doesn't seem to work in all situations, such as using singleton classes and static methods, etc.

I'd rather not embed another interpreter inside this interpreter if it can be avoided, as the ease of being able to use the applications API will be lost (as well as including a slight speed hit I imagine).

So, does anyone know of a way I could store the interpreter's state and then return to this so that it can cope with all situations?

Thanks,

Dan

答:
One very hacky and bug prone approach might be a c module that simply copies the memory to a file so it can be loaded back the next time. But since I can't imagine that this would always work properly, would pickling be an alternative?

If you are able to make all of your modules pickleable than you should be able to pickle everything in globals() so it can be reloaded again.

OwnerDisplayName: Dan

Title: Restarting a Python Interpreter Quietly

LastEditorDisplayName: Benoit

OwnerDisplayName: Rick van Hattem