问:
Is it possible to fetch a cursor into a record using rowtype?
I'm always getting

```<code>PLS-00597: expression 'V_EMP_REC' in the INTO list is of wrong type
</code>```

Here's the package, i'm using default HR schema

```<code>CREATE OR REPLACE PACKAGE EMP_PKG AS
  TYPE T_EMP_REC IS RECORD (
    V_EMP_TAB EMPLOYEES%ROWTYPE,
    V_DEPT_NAME DEPARTMENTS.DEPARTMENT_NAME%TYPE
  );

  FUNCTION GET_EMP (P_EMP_ID EMPLOYEES.EMPLOYEE_ID%TYPE) RETURN T_EMP_REC;
END EMP_PKG;
/
CREATE OR REPLACE PACKAGE BODY EMP_PKG AS
  FUNCTION GET_EMP (P_EMP_ID EMPLOYEES.EMPLOYEE_ID%TYPE)
  RETURN T_EMP_REC
  AS
    CURSOR V_EMP_CUR IS
      SELECT E.*, D.DEPARTMENT_NAME
      FROM EMPLOYEES E, DEPARTMENTS D
      WHERE E.EMPLOYEE_ID = P_EMP_ID
      AND E.DEPARTMENT_ID = D.DEPARTMENT_ID;

  V_EMP_REC T_EMP_REC;
  BEGIN
    OPEN V_EMP_CUR;
    FETCH V_EMP_CUR INTO V_EMP_REC;
    CLOSE V_EMP_CUR;

  RETURN V_EMP_REC;
  END GET_EMP;
END EMP_PKG;
</code>```

The number of columns matches and I'm always using the same types as the table. I don't know if this approach is possible instead of declaring every column in the record type.

答:
As an alternative, if you just want the record type to be a flat structure and match the cursor, you could place your cursor in the package spec and define a type as cursor%rowtype:

```<code>create or replace package emp_pkg
as
    cursor emp_cur
        ( cp_emp_id employees.employee_id%type )
    is
        select e.*, d.department_name
        from   employees e
               join departments d
                    on  e.department_id = d.department_id
        where  e.employee_id = cp_emp_id;

    subtype t_emp_rec is emp_cur%rowtype;

    function get_emp
        ( p_emp_id employees.employee_id%type )
        return t_emp_rec;

end emp_pkg;

create or replace package body emp_pkg
as
    function get_emp
        ( p_emp_id employees.employee_id%type )
        return t_emp_rec
    is
        v_emp_rec t_emp_rec;
    begin
        open emp_cur(p_emp_id);
        fetch emp_cur into v_emp_rec;
        close emp_cur;

        return v_emp_rec;
    end get_emp;
end emp_pkg;
</code>```

Body:
I'm always getting

PLS-00597: expression 'V_EMP_REC' in the INTO list is of wrong type

Here's the package, i'm using default HR schema

CREATE OR REPLACE PACKAGE EMP_PKG AS
  TYPE T_EMP_REC IS RECORD (
    V_EMP_TAB EMPLOYEES%ROWTYPE,
    V_DEPT_NAME DEPARTMENTS.DEPARTMENT_NAME%TYPE
  );

  FUNCTION GET_EMP (P_EMP_ID EMPLOYEES.EMPLOYEE_ID%TYPE) RETURN T_EMP_REC;
END EMP_PKG;
/
CREATE OR REPLACE PACKAGE BODY EMP_PKG AS
  FUNCTION GET_EMP (P_EMP_ID EMPLOYEES.EMPLOYEE_ID%TYPE)
  RETURN T_EMP_REC
  AS
    CURSOR V_EMP_CUR IS
      SELECT E.*, D.DEPARTMENT_NAME
      FROM EMPLOYEES E, DEPARTMENTS D
      WHERE E.EMPLOYEE_ID = P_EMP_ID
      AND E.DEPARTMENT_ID = D.DEPARTMENT_ID;

  V_EMP_REC T_EMP_REC;
  BEGIN
    OPEN V_EMP_CUR;
    FETCH V_EMP_CUR INTO V_EMP_REC;
    CLOSE V_EMP_CUR;

  RETURN V_EMP_REC;
  END GET_EMP;
END EMP_PKG;

The number of columns matches and I'm always using the same types as the table. I don't know if this approach is possible instead of declaring every column in the record type.

Body:
As an alternative, if you just want the record type to be a flat structure and match the cursor, you could place your cursor in the package spec and define a type as cursor%rowtype:

create or replace package emp_pkg
as
    cursor emp_cur
        ( cp_emp_id employees.employee_id%type )
    is
        select e.*, d.department_name
        from   employees e
               join departments d
                    on  e.department_id = d.department_id
        where  e.employee_id = cp_emp_id;

    subtype t_emp_rec is emp_cur%rowtype;

    function get_emp
        ( p_emp_id employees.employee_id%type )
        return t_emp_rec;

end emp_pkg;

create or replace package body emp_pkg
as
    function get_emp
        ( p_emp_id employees.employee_id%type )
        return t_emp_rec
    is
        v_emp_rec t_emp_rec;
    begin
        open emp_cur(p_emp_id);
        fetch emp_cur into v_emp_rec;
        close emp_cur;

        return v_emp_rec;
    end get_emp;
end emp_pkg;


来源: stackexchange

问:
php opcache variables not set correctly
I'm trying to set the variables to setup opcahe in my php.ini file.
phpinfo says:

```<code>Configuration File (php.ini)
Path    /etc/php/7.0/fpm
Loaded Configuration File   /etc/php/7.0/fpm/php.ini
Scan this dir for additional .ini files   /etc/php/7.0/fpm/conf.d
Additional .ini files parsed    /etc/php/7.0/fpm/conf.d/10-mysqlnd.ini,
</code>```

/etc/php/7.0/fpm/conf.d/10-opcache.ini,

```<code>/etc/php/7.0/fpm/conf.d/10-pdo.ini,
/etc/php/7.0/fpm/conf.d/15-xml.ini,
...
</code>```

And /etc/php/7.0/fpm/conf.d/10-opcache.ini, contains:

```<code>zend_extension=opcache.so
opcache.enable=1
opcache.enable_cli=1
opcache.fast_shutdown=1
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.memory_consumption=128
opcache.save_comments=1
opcache.revalidate_freq=1
opcache.file_cache=/tmp;
</code>```

When I look in phpinfo results for opcache, I see:

```<code>opcache.enable  On  On
opcache.enable_cli  Off Off
opcache.max_accelerated_files   2000    2000
opcache.interned_strings_buffer 4   4
opcache.memory_consumption  64  64
opcache.revalidate_freq 2   2
</code>```

Does anyone know why it does not take my variables???

答:
Solved but I don't really know how.
I just (re)installed php7-intl and php7-sqlite3 for other problems then the error messages concerning opcache disappeared </p>

ContentLicense: CC BY-SA 3.0

Title: php opcache variables not set correctly

Body:
I'm trying to set the variables to setup opcahe in my php.ini file.
phpinfo says:

Configuration File (php.ini)
Path    /etc/php/7.0/fpm
Loaded Configuration File   /etc/php/7.0/fpm/php.ini
Scan this dir for additional .ini files   /etc/php/7.0/fpm/conf.d
Additional .ini files parsed    /etc/php/7.0/fpm/conf.d/10-mysqlnd.ini,

/etc/php/7.0/fpm/conf.d/10-opcache.ini,

/etc/php/7.0/fpm/conf.d/10-pdo.ini,
/etc/php/7.0/fpm/conf.d/15-xml.ini,
...

And /etc/php/7.0/fpm/conf.d/10-opcache.ini, contains:

zend_extension=opcache.so
opcache.enable=1
opcache.enable_cli=1
opcache.fast_shutdown=1
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.memory_consumption=128
opcache.save_comments=1
opcache.revalidate_freq=1
opcache.file_cache=/tmp;

When I look in phpinfo results for opcache, I see:

opcache.enable  On  On
opcache.enable_cli  Off Off
opcache.max_accelerated_files   2000    2000
opcache.interned_strings_buffer 4   4
opcache.memory_consumption  64  64
opcache.revalidate_freq 2   2

Does anyone know why it does not take my variables???


问:
Why where clause doesn't affect of the query?
Here is my code:

```<code>$tracking_codes_obj = new TrackingCode;
$tracking_code = 140;

if ( !is_null($tracking_code) )
    $tracking_codes_obj->where('tracking_code', $tracking_code);

$tracking_codes = $tracking_codes_obj->orderBy('expired')->orderBy('id')->paginate(10);
</code>```

As you can see $tracking_code is not null, so that condition is true and that where clause should be applied. But still the result is the same as when I completely remove that condition.

Why and how can I fix it?

答:
The correct syntax is:</p>

```<code>$tracking_codes_obj = $tracking_codes_obj->where('tracking_code', $tracking_code);
</code>```

Body:
Here is my code:

$tracking_codes_obj = new TrackingCode;
$tracking_code = 140;

if ( !is_null($tracking_code) )
    $tracking_codes_obj->where('tracking_code', $tracking_code);

$tracking_codes = $tracking_codes_obj->orderBy('expired')->orderBy('id')->paginate(10);

As you can see $tracking_code is not null, so that condition is true and that where clause should be applied. But still the result is the same as when I completely remove that condition.

Why and how can I fix it?

Body:
The correct syntax is:

$tracking_codes_obj = $tracking_codes_obj->where('tracking_code', $tracking_code);


问:
Calling os.Lstat only if the file has changed since the last time I called os.Lstat
I'm trying to write a program, calcsize, that calculates the size of all sub directories. I want to create a cache of the result and only re-walk the directory if it has changed since the last time I've run the program.

Something like:

```<code>./calcsize
//outputs
/absolute/file/path1/ 1000 Bytes
/absolute/file/path2/ 2000 Bytes
</code>```

I'm already walking the dirs with my own walk implementation because the built in go filepath.Walk is already calling Lstat on every file.

Is there any way to know if a directory or set of files has changed without calling Lstat on every file? Maybe a system call I'm not aware of?

答:
Whether, and how, this is possible depends heavily on your operating system.  But you might take a look at github.com/howeyc/fsnotify which claims to offer this (I've never used it--I just now found it via Google).

In general, look at any Go program that provides a 'watch' feature.  GoConvey and GopherJS's serve mode come to mind as examples, but there are others (possibly even in the standard library).

Body:
I'm trying to write a program, calcsize, that calculates the size of all sub directories. I want to create a cache of the result and only re-walk the directory if it has changed since the last time I've run the program.

Something like:

./calcsize
//outputs
/absolute/file/path1/ 1000 Bytes
/absolute/file/path2/ 2000 Bytes

I'm already walking the dirs with my own walk implementation because the built in go filepath.Walk is already calling Lstat on every file.

Is there any way to know if a directory or set of files has changed without calling Lstat on every file? Maybe a system call I'm not aware of?


问:
Subtracts values one list from another in javascript
How to remove all values from var a = [1,2,2,2,3] which are present in var b=[2]If a values is present in b variable all of its occurrences must be remove

```<code> var a = [1,2,2,2,5];
 var b = [2];
 const result = a.filter(function(el){

  return /// which condition .?

 });
</code>```

How to remove the b var value. and we have many logics please answer it briefly

答:
use array.filter

var first = [1, 2, 2, 2, 5];
var second = [2];

var result = first.filter(function(n) {
  return second.indexOf(n) === -1;
});

console.log(result);```

Body:
How to remove all values from var a = [1,2,2,2,3] which are present in var b=[2]If a values is present in b variable all of its occurrences must be remove

 var a = [1,2,2,2,5];
 var b = [2];
 const result = a.filter(function(el){

  return /// which condition .?

 });

How to remove the b var value. and we have many logics please answer it briefly


答:
You could take a Set for the unwanted items.

var a = [1, 2, 2, 2, 5],
    b = [2],
    result = a.filter((s => v => !s.has(v))(new Set(b)));

console.log(result);```

Title: Subtracts values one list from another in javascript


问:
How to cancel the keyboard in UISearchbar?
I'm using UISearchBar in my application and it serves as both an edit field as well as a search.  So when I want to disappear the keyboard I have to use cancel button in UISearchBar but I can't have that cancel button on screen, so how could T make keyboard disappear when not used without using cancel button.  Please help me as i'm new to iPhone application development.

Thanks in advance!

答:
Use this:

```<code>
[UISearchBar resignFirstResponder];
</code>```

Just replace the word UISearchBar with the name of the object you have created.

ContentLicense: CC BY-SA 2.5

Body:
Use this:

[UISearchBar resignFirstResponder];

Just replace the word UISearchBar with the name of the object you have created.


答:
you need to replace if condition like this :

```<code>if ($tracking_code != null)
</code>```

Instead of

```<code>if ( !is_null($tracking_code) )
</code>```

and code will be like this

```<code>$tracking_codes_obj = new TrackingCode;
$tracking_code = 140;

if ($tracking_code != null)
{
    $tracking_codes_obj = $tracking_codes_obj->where('tracking_code', $tracking_code);
}

$tracking_codes = $tracking_codes_obj->orderBy('expired')->orderBy('id')->paginate(10);
</code>```

Title: Why where clause doesn't affect of the query?

Body:
you need to replace if condition like this :

if ($tracking_code != null)

Instead of

if ( !is_null($tracking_code) )

and code will be like this

$tracking_codes_obj = new TrackingCode;
$tracking_code = 140;

if ($tracking_code != null)
{
    $tracking_codes_obj = $tracking_codes_obj->where('tracking_code', $tracking_code);
}

$tracking_codes = $tracking_codes_obj->orderBy('expired')->orderBy('id')->paginate(10);


问:
Can REST clients be not RESTful?
REST is defined by its principle of uniform interface.  Resources are accessed and modified by manipulating their representations.  The uniform interface also implies Hypermedia as the engine of application state (HATEOAS) which is explained by Wikipedia:

Clients make state transitions only through actions that are dynamically identified within hypermedia by the server (e.g., by hyperlinks within hypertext). Except for simple fixed entry points to the application, a client does not assume that any particular action is available for any particular resources beyond those described in representations previously received from the server.

Essentially a REST client receives from the server links that it can use to create, modify, or delete resources similar to how a human chooses links on a Web page.

I often see examples in tutorials or documentation of how to access a REST API with jQuery that look like this:

```<code>jQuery.getJSON("/cities/mumbai/events/?month=2009-05", function(json) {
    alert(json[0]);
});
</code>```

In this case the client is not using HATEOAS or other connected aspects of REST.  Does this mean that we can say that this client is not RESTful?

答: @leo you shouldn't have use the adjectives "basically" and "strictly" in that comment. Heke is absolutely right. The sample code is definitely not RESTful. If the server changes the URL for example, then the client will break. Among other things, RESTful clients do not hard-code URLs other than the site homepage.</p>

Title: Can REST clients be not RESTful?

Body:
REST is defined by its principle of uniform interface.  Resources are accessed and modified by manipulating their representations.  The uniform interface also implies Hypermedia as the engine of application state (HATEOAS) which is explained by Wikipedia:

Clients make state transitions only through actions that are dynamically identified within hypermedia by the server (e.g., by hyperlinks within hypertext). Except for simple fixed entry points to the application, a client does not assume that any particular action is available for any particular resources beyond those described in representations previously received from the server.

Essentially a REST client receives from the server links that it can use to create, modify, or delete resources similar to how a human chooses links on a Web page.

I often see examples in tutorials or documentation of how to access a REST API with jQuery that look like this:

jQuery.getJSON("/cities/mumbai/events/?month=2009-05", function(json) {
    alert(json[0]);
});

In this case the client is not using HATEOAS or other connected aspects of REST.  Does this mean that we can say that this client is not RESTful?


问:
windows server 2012 r2 can not connect to sql Data Access Manager
Any help please, am trying to run SunSystems Data Access Manager on my windows server 2012 r2 but i get the following error:
Client found  content type of text/html; charset=utf-8; but expeted text/xml'. The reques failed with the error message:--   The file '/SunSystemsReportServer/SunSystemsStudio.asmx' has not been pre-compiled.</p>

答: i finally found a solution. The error was caused because the  SunSystems Reporting password was changed, i recovered the password and every went well. Thannks.</p>


问:
Point inside rectangle given sides and center
I'm given rectangle by it's height(h) and width(w), and it's center O(x0,y0). I need to calculate if given point A(x,y) is inside that rectangle. It is parallel to x and y axis. All values are real.

I came up with following test but for some reason website on which I'm testing the code is not working for all examples. Could someone point me in the right direction.

```<code>#include <iostream>
#include <cmath>
using namespace std;
int main(){
    long x,y,x0,y0,r,h,w;
    scanf("%ld",&x);
    scanf("%ld",&y);
    scanf("%ld",&x0);
    scanf("%ld",&y0);
    scanf("%ld",&h);
    scanf("%ld",&w);
    if((x0+w/2.0>=x)&&(x0-w/2.0<=x)&&(y0+h/2.0>=y)&&(y0-h/2.0<=y))
        printf("inside a rectangle");
    else
        printf("outside a rectangle");
}
</code>```

Thanks in advance.

答:
After OP's Edit:

The rectangle's side are parallel to x axis and y-axis. Then also it is possible to get the co-ordinates and apply the below mentioned algorithm.

```<code>Centre -- (x0,y0)
A -- (x0-w/2,y0-h/2)
B -- (x0-w/2.y0+h/2)
C -- (x0+w/2,y0+h/2)
D -- (x0+w/2,y0-h/2)
</code>```

So all you have to do is, Apply the algorithms provided below.

More simply we can do this,

```<code>if( 2*x <= 2*x0+w && 2*x >= 2*x0-w && 2*y <= 2*y0+h && 2*y >= 2*y0-h)
// it's inside
</code>```

Before OP's edit

Your logic is wrong. It may say a point inside rectangle to be outside of it.
(For any rectangle this is wrong - OP didn't mention the condition of being sides parallel to x-y axes)

There is a simple way and cleaner way to do this for rectangle. Find the Area of the rectangle.

Suppose it's A.

Now if the point P lies inside ABCD then

```<code>area of PAB+PBC+PCD+PDA = A
</code>```

For better thing do this with ,

```<code>AB.Bc+BC.CD+CD.DA+DA.AB = 2*AB*BC
</code>```

or even better make a square of both side

```<code>LHS^2 = 4*AB^2*BC^2
</code>```

Now you will just multiply and check it. One drawback of this solution is for large values of side length you have a chance of overflow.

Another method would be to consider the projections.

If point is inside of the rectangle then the projection of the corner of rectangle to point, on two of it's side must be less than the corresponding sides. You can check the projection length using dot products.

For example if P is the point and ABCD is rectangle check,

if AP's projection on AB has greater than zero length but less than the length of AB. Check the same with BC and BP and check if length is greater than zero and less than BC or not.

This two condition makes sure that your point lies inside the rectangle.

Body:
I'm given rectangle by it's height(h) and width(w), and it's center O(x0,y0). I need to calculate if given point A(x,y) is inside that rectangle. It is parallel to x and y axis. All values are real.

I came up with following test but for some reason website on which I'm testing the code is not working for all examples. Could someone point me in the right direction.

#include <iostream>
#include <cmath>
using namespace std;
int main(){
    long x,y,x0,y0,r,h,w;
    scanf("%ld",&x);
    scanf("%ld",&y);
    scanf("%ld",&x0);
    scanf("%ld",&y0);
    scanf("%ld",&h);
    scanf("%ld",&w);
    if((x0+w/2.0>=x)&&(x0-w/2.0<=x)&&(y0+h/2.0>=y)&&(y0-h/2.0<=y))
        printf("inside a rectangle");
    else
        printf("outside a rectangle");
}

Thanks in advance.

Body:
After OP's Edit:

The rectangle's side are parallel to x axis and y-axis. Then also it is possible to get the co-ordinates and apply the below mentioned algorithm.

Centre -- (x0,y0)
A -- (x0-w/2,y0-h/2)
B -- (x0-w/2.y0+h/2)
C -- (x0+w/2,y0+h/2)
D -- (x0+w/2,y0-h/2)

So all you have to do is, Apply the algorithms provided below.

More simply we can do this,

if( 2*x <= 2*x0+w && 2*x >= 2*x0-w && 2*y <= 2*y0+h && 2*y >= 2*y0-h)
// it's inside

Before OP's edit

Your logic is wrong. It may say a point inside rectangle to be outside of it.
(For any rectangle this is wrong - OP didn't mention the condition of being sides parallel to x-y axes)

There is a simple way and cleaner way to do this for rectangle. Find the Area of the rectangle.

Suppose it's A.

Now if the point P lies inside ABCD then

area of PAB+PBC+PCD+PDA = A

For better thing do this with ,

AB.Bc+BC.CD+CD.DA+DA.AB = 2*AB*BC

or even better make a square of both side

LHS^2 = 4*AB^2*BC^2

Now you will just multiply and check it. One drawback of this solution is for large values of side length you have a chance of overflow.

Another method would be to consider the projections.

If point is inside of the rectangle then the projection of the corner of rectangle to point, on two of it's side must be less than the corresponding sides. You can check the projection length using dot products.

For example if P is the point and ABCD is rectangle check,

if AP's projection on AB has greater than zero length but less than the length of AB. Check the same with BC and BP and check if length is greater than zero and less than BC or not.

This two condition makes sure that your point lies inside the rectangle.


问:
In Java, will empty collections of the same type, but different type parameters always be equal?
Consider the following snippet:

```<code>    List<String> list1 = new ArrayList<>();
    List<Integer> list2 = new ArrayList<>();
    assertThat(list1.equals(list2), is(true));
</code>```

The assertion succeeds.

Indeed, as far as I understand, there is no way in Java, for the equals method to differentiate between the two, due to run-time type-erasure (i.e. the fact the type arguments String and Integer are only accessible at compile-time, but not at run-time).
And since there are no elements, which could be compared, equals has to return true. And by this line of thought, this must be true, for all collections.

So the question is the following: is my thought process correct, or am I missing something?

EDIT

@qqilihq gave an excellent answer, which prompts the next question:
Is this possible to achieve without passing the type explicitly (I'm fine if the type is stored explicitly somehow, just the user does should not have to pass it.)

I attempted the following, but it did not work (I guess due to type erasure):

```<code>    public TypedList(List<T> delegate) {
        this.delegate = Objects.requireNonNull(delegate);
        this.type = (Class<T>) delegate.getClass();
    }
</code>```

But maybe you can do something similar to this? this.type = T. (This does not compile, but maybe something similar would be possible.)

答:
It really depends on how individual sublcass that implement the collection interface handles the equals() method. For ArrayList, the implementation is in AbstractList which as follow:

```<code>public boolean equals(Object o) {
    if (o == this)
        return true;
    if (!(o instanceof List))
        return false;

    ListIterator<E> e1 = listIterator();
    ListIterator<?> e2 = ((List<?>) o).listIterator();
    while (e1.hasNext() && e2.hasNext()) {
        E o1 = e1.next();
        Object o2 = e2.next();
        if (!(o1==null ? o2==null : o1.equals(o2)))
            return false;
    }
    return !(e1.hasNext() || e2.hasNext());
}
</code>```

So it just return true if the opposite object is also a List and the size is same and every element is equals. So if both List are empty the result must be true.

Body:
Consider the following snippet:

    List<String> list1 = new ArrayList<>();
    List<Integer> list2 = new ArrayList<>();
    assertThat(list1.equals(list2), is(true));

The assertion succeeds.

Indeed, as far as I understand, there is no way in Java, for the equals method to differentiate between the two, due to run-time type-erasure (i.e. the fact the type arguments String and Integer are only accessible at compile-time, but not at run-time).
And since there are no elements, which could be compared, equals has to return true. And by this line of thought, this must be true, for all collections.

So the question is the following: is my thought process correct, or am I missing something?

EDIT

@qqilihq gave an excellent answer, which prompts the next question:
Is this possible to achieve without passing the type explicitly (I'm fine if the type is stored explicitly somehow, just the user does should not have to pass it.)

I attempted the following, but it did not work (I guess due to type erasure):

    public TypedList(List<T> delegate) {
        this.delegate = Objects.requireNonNull(delegate);
        this.type = (Class<T>) delegate.getClass();
    }

But maybe you can do something similar to this? this.type = T. (This does not compile, but maybe something similar would be possible.)

Body:
It really depends on how individual sublcass that implement the collection interface handles the equals() method. For ArrayList, the implementation is in AbstractList which as follow:

public boolean equals(Object o) {
    if (o == this)
        return true;
    if (!(o instanceof List))
        return false;

    ListIterator<E> e1 = listIterator();
    ListIterator<?> e2 = ((List<?>) o).listIterator();
    while (e1.hasNext() && e2.hasNext()) {
        E o1 = e1.next();
        Object o2 = e2.next();
        if (!(o1==null ? o2==null : o1.equals(o2)))
            return false;
    }
    return !(e1.hasNext() || e2.hasNext());
}

So it just return true if the opposite object is also a List and the size is same and every element is equals. So if both List are empty the result must be true.


问:
How to make a flex element fully expand to fill the containing element?
Here is my code.

I want the element .container to fully expand and occupy the area of .toplevel.

.toplevel {
  height: 100%;
  min-height: 800px;
  border: solid 1px blue;
}

.container {
  display: flex;
  border: solid 1px red;
  height: 100%;
  flex: 0 1 auto;
  flex-direction: column;
  // min-height: 800px;
}

.up {
  display: flex;
  flex: 1 1 auto;
}

.down {
  display: flex;
  flex: 0 1 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="toplevel">
  <div class="container">
    <div class="up">
      This is up
    </div>
    <div class="up">
      This is down
    </div>
  </div>
</div></code>```

However it seems like the only way to make the .container larger height-wise is to define a min-height. It is too inflexible because I will have provide a different value for different device form factor.

How can I fix it?

答:
Simpy add display: flex to .toplevel and remove height: 100% from .container.

This work based on the fact that flex row item's height behavior can be controlled with the align-items property. As it by default has stretch, it will fill its parents height.

As a note, in general, when it comes to Flexbox, it is preferable to make use of its own properties instead of height/width. By doing so you also get a better cross browser support.

Stack snippet

.toplevel {
  height: 100%;
  min-height: 800px;
  border: solid 1px blue;
  display: flex;              /* added  */
}

.container {
  display: flex;
  border: solid 1px red;
  /*height: 100%;                removed  */
  flex: 1 1 auto;            /*  changed, flex row item need the grow value
                                          to be 1 to fill its parent's width  */
  flex-direction: column;
}

.up {
  display: flex;
  flex: 1 1 auto;
}

.down {
  display: flex;
  flex: 0 1 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="toplevel">
  <div class="container">
    <div class="up">
      This is up
    </div>
    <div class="down">
      This is down
    </div>
  </div>
</div></code>```

Body:
Here is my code.

I want the element .container to fully expand and occupy the area of .toplevel.

.toplevel {
  height: 100%;
  min-height: 800px;
  border: solid 1px blue;
}

.container {
  display: flex;
  border: solid 1px red;
  height: 100%;
  flex: 0 1 auto;
  flex-direction: column;
  // min-height: 800px;
}

.up {
  display: flex;
  flex: 1 1 auto;
}

.down {
  display: flex;
  flex: 0 1 auto;
}

      This is up

      This is down

However it seems like the only way to make the .container larger height-wise is to define a min-height. It is too inflexible because I will have provide a different value for different device form factor.

How can I fix it?

Body:
Simpy add display: flex to .toplevel and remove height: 100% from .container.

This work based on the fact that flex row item's height behavior can be controlled with the align-items property. As it by default has stretch, it will fill its parents height.

As a note, in general, when it comes to Flexbox, it is preferable to make use of its own properties instead of height/width. By doing so you also get a better cross browser support.

Stack snippet

.toplevel {
  height: 100%;
  min-height: 800px;
  border: solid 1px blue;
  display: flex;              /* added  */
}

.container {
  display: flex;
  border: solid 1px red;
  /*height: 100%;                removed  */
  flex: 1 1 auto;            /*  changed, flex row item need the grow value
                                          to be 1 to fill its parent's width  */
  flex-direction: column;
}

.up {
  display: flex;
  flex: 1 1 auto;
}

.down {
  display: flex;
  flex: 0 1 auto;
}

<div class="toplevel">
  <div class="container">
    <div class="up">
      This is up
    </div>
    <div class="down">
      This is down
    </div>
  </div>
</div>


问:
Are dynamic exception specifications invalid in c++17?
Are dynamic exception specifications invalid in c++17? Like this</p>

```<code>void f() throw(int);
</code>```

答:
They are officially invalid in C++17. However, Visual C++17 with C++/Language/C++ Language Standard set to ISO C++17 still allows them. Setting warning level to 3 or higher [properties/General/Warning Level/] gives the warning,

warning C4290: C++ exception specification ignored except to indicate a function is not __declspec(nothrow)

Note that throw() is still legal and is equivalent to the newly added noexcept.

Body:
Are dynamic exception specifications invalid in c++17? Like this

void f() throw(int);


答:
Try the following by using array's filter():

var a = [1,2,2,2,5];
var b = [2];
var c = a.filter(item => !b.includes(item))
console.log(c)```


问:
Multiple inserts in a loop codeigniter
Let's say in my DB i have 2 tables. One is named Father with Father_id as PK and Father_name as a row. Then i have the second table as Children with Child_id as PK, Father_id as FK, and Child_name as a row.

Children would have a relationship with Father as Many to One. Many Children to One Father.

So let's say the data looks like this in my controller.

```<code>Array([Father_id] => 1 [Children] => Array([0] => John [1] => Peter [2] => Michael))
</code>```

I pass the data above to my model to insert right but i have to restructure it in a way that i can just send it to my database to insert.

```<code>foreach($data as $row){
    for($temp = 0; $temp < count($data['Child_name']); $temp++){
        $query[$temp] = array('Father_id' => $data['Father_id'], 'child_name' => $row[$temp]);
    }
}
</code>```

So now it looks like this,

```<code>Array([0]=>Array([Father_id] => 1 [Child_name] => John)[1]=>Array([Father_id] => 1 [Child_name] => Peter)[2]=>Array([Father_id] => 1 [Child_name] => Michael))
</code>```

I understand how to insert this, i'll just have to do another foreach loop or i can just remove the $temp in $query[$temp] and instead put an insert query inside that loop.

My problem is that how can i know that each insert is successful, other than checking the database, i would like to have a return statement like if its only a single insert then if its successful it returns 1.

Also is there any better way to do multiple inserts?

UPDATE:

After some needed break i came back and made some changes.

This is now my model function:

```<code>        public function insert_children($data){
        foreach($data['child_name'] as $row){
            $query = array('father_id' => $data['father_id'], 'child_name' => $row);
            $result = $this->db->insert('children',$query);
        }
  //return something here
}
</code>```

It is essential to return something back to the controller right? for example, i want to return if the inserts were successful or not. So is there any already made function in codeigniter for this? or do i have to make myself.

for example, i can just make a $temp variable to contain an incremental value each time an insert is successful and compare it at the end of the loop to the count($data['children'])

So if there are 3 children the value of $temp should be 3 or 2 depending on declaration if i specify it with 1 like $temp = 1;

答:
You can use affected_rows() function on each loop item to check whether data is inserted or not and return error message only for the data that is not inserted :

```<code>foreach($data as $row) {
    for($temp = 0; $temp < count($data['Child_name']); $temp++){
        // note that I remove [$temp] below
        $query = array('Father_id' => $data['Father_id'], 'child_name' => $row[$temp]);
        $this->db->query($query);
        if($this->db->affected_rows() == 0) // data not inserted, return error message
        {
          $error[] = $row[$temp];
        }
    }
}

// shows error if one or more child name is not inserted
if (isset($error)) {
    foreach ($error as $child_name) {
        echo $child_name . ' is not inserted';
    }
}
</code>```

Title: Multiple inserts in a loop codeigniter

Body:
Let's say in my DB i have 2 tables. One is named Father with Father_id as PK and Father_name as a row. Then i have the second table as Children with Child_id as PK, Father_id as FK, and Child_name as a row.

Children would have a relationship with Father as Many to One. Many Children to One Father.

So let's say the data looks like this in my controller.

Array([Father_id] => 1 [Children] => Array([0] => John [1] => Peter [2] => Michael))

I pass the data above to my model to insert right but i have to restructure it in a way that i can just send it to my database to insert.

foreach($data as $row){
    for($temp = 0; $temp < count($data['Child_name']); $temp++){
        $query[$temp] = array('Father_id' => $data['Father_id'], 'child_name' => $row[$temp]);
    }
}

So now it looks like this,

Array([0]=>Array([Father_id] => 1 [Child_name] => John)[1]=>Array([Father_id] => 1 [Child_name] => Peter)[2]=>Array([Father_id] => 1 [Child_name] => Michael))

I understand how to insert this, i'll just have to do another foreach loop or i can just remove the $temp in $query[$temp] and instead put an insert query inside that loop.

My problem is that how can i know that each insert is successful, other than checking the database, i would like to have a return statement like if its only a single insert then if its successful it returns 1.

Also is there any better way to do multiple inserts?

UPDATE:

After some needed break i came back and made some changes.

This is now my model function:

        public function insert_children($data){
        foreach($data['child_name'] as $row){
            $query = array('father_id' => $data['father_id'], 'child_name' => $row);
            $result = $this->db->insert('children',$query);
        }
  //return something here
}

It is essential to return something back to the controller right? for example, i want to return if the inserts were successful or not. So is there any already made function in codeigniter for this? or do i have to make myself.

for example, i can just make a $temp variable to contain an incremental value each time an insert is successful and compare it at the end of the loop to the count($data['children'])

So if there are 3 children the value of $temp should be 3 or 2 depending on declaration if i specify it with 1 like $temp = 1;

Body:
You can use affected_rows() function on each loop item to check whether data is inserted or not and return error message only for the data that is not inserted :

foreach($data as $row) {
    for($temp = 0; $temp < count($data['Child_name']); $temp++){
        // note that I remove [$temp] below
        $query = array('Father_id' => $data['Father_id'], 'child_name' => $row[$temp]);
        $this->db->query($query);
        if($this->db->affected_rows() == 0) // data not inserted, return error message
        {
          $error[] = $row[$temp];
        }
    }
}

// shows error if one or more child name is not inserted
if (isset($error)) {
    foreach ($error as $child_name) {
        echo $child_name . ' is not inserted';
    }
}


问:
Mysql Database error connection
Might sound obvious but my database isn't connecting to my phpmyadmin.

is there something I did wrong? I'm using mamp as a backend server for php use.

```<code> <?php
    //
    require('database.php');
    $connection = mysqli_connect('localhost', 'root','','blurt');
    // If the values are posted, insert them into the database.
    if (isset($_POST['Register'])){
        $username = $_POST['username'];
    $email = $_POST['email'];
        $password = $_POST['password'];

        $query = "INSERT INTO `user` (username, email, password) VALUES ('$username', '$email', '$password')";
         //echo $query;
        $result=mysqli_query($connection,$query);
        if($result){
            $smsg = "User Created Successfully.";
        }else{
            $fmsg ="User Registration Failed";
        }
    }

    $connection = mysqli_connect('localhost', 'root', '', 'blurt');
    if (!$connection) {
        die("Database Connection Failed" . mysqli_error($connection));
    } $select_db = mysqli_select_db($connection, 'blurt');
    if (!$select_db) {
        die("Database Selection Failed" . mysqli_error($connection));
    }
    ?>
</code>```

答:
by seeing your question it is looks like you are registering the connection after the query..

please try to change the order..

$connection have to be created before using that..

some this like below:

```<code>// Step -1
$connection = mysqli_connect('localhost', 'root', '', 'blurt');
if (!$connection) {
die("Database Connection Failed" . mysqli_error($connection));
} $select_db = mysqli_select_db($connection, 'blurt');
if (!$select_db) {
die("Database Selection Failed" . mysqli_error($connection));
}

//Step-2
$query = "INSERT INTO `user` (username, email, password) VALUES ('$username', '$email', '$password')";
 //echo $query;
$result=mysqli_query($connection,$query);
if($result){
    $smsg = "User Created Successfully.";
}else{
    $fmsg ="User Registration Failed";
}
</code>```

Title: Mysql Database error connection

Body:
Might sound obvious but my database isn't connecting to my phpmyadmin.

is there something I did wrong? I'm using mamp as a backend server for php use.

 <?php
    //
    require('database.php');
    $connection = mysqli_connect('localhost', 'root','','blurt');
    // If the values are posted, insert them into the database.
    if (isset($_POST['Register'])){
        $username = $_POST['username'];
    $email = $_POST['email'];
        $password = $_POST['password'];

        $query = "INSERT INTO `user` (username, email, password) VALUES ('$username', '$email', '$password')";
         //echo $query;
        $result=mysqli_query($connection,$query);
        if($result){
            $smsg = "User Created Successfully.";
        }else{
            $fmsg ="User Registration Failed";
        }
    }

    $connection = mysqli_connect('localhost', 'root', '', 'blurt');
    if (!$connection) {
        die("Database Connection Failed" . mysqli_error($connection));
    } $select_db = mysqli_select_db($connection, 'blurt');
    if (!$select_db) {
        die("Database Selection Failed" . mysqli_error($connection));
    }
    ?>

Body:
by seeing your question it is looks like you are registering the connection after the query..

please try to change the order..

$connection have to be created before using that..

some this like below:

// Step -1
$connection = mysqli_connect('localhost', 'root', '', 'blurt');
if (!$connection) {
die("Database Connection Failed" . mysqli_error($connection));
} $select_db = mysqli_select_db($connection, 'blurt');
if (!$select_db) {
die("Database Selection Failed" . mysqli_error($connection));
}

//Step-2
$query = "INSERT INTO `user` (username, email, password) VALUES ('$username', '$email', '$password')";
 //echo $query;
$result=mysqli_query($connection,$query);
if($result){
    $smsg = "User Created Successfully.";
}else{
    $fmsg ="User Registration Failed";
}


问:
How to post values and get response in PHP
I want to do e-mail verification using email-checker. I want to post email and id, and I would like to withdraw it from the posted page, whichever answer is BAD or SUCCESS. Posted page is https://email-checker.net/check.

Here is my code:

```<code>$curl_connection = curl_init();
curl_setopt($curl_connection, CURLOPT_URL, 'https://www.bulkemailchecker.com/free-email-checker/');
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_FRESH_CONNECT,true);
curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_HEADER, false);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl_connection, CURLOPT_POST, true);
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
$data=curl_exec($curl_connection);
</code>```

Can anyone help me?

答:
first make a GET request to the url, in the headers you will receive a cookie session id, and in the html you will receive a CSRF token called _csrf, save both, and make a new request to https://email-checker.net/check with both the cookie session and the csrf token, and the email, in the parameter (aptly) named email, using a HTTP POST request, with the application/x-www-urlencoded encoding. now your answer will be in the text content of the element in the html you receive with the id results-wrapper.

example implementation using hhb_curl:

```<code><?php
declare(strict_types = 1);
const EMAIL = 'webmaster@hotmail.com';
require_once ('hhb_.inc.php');
$hc = new hhb_curl ( '', true );
$html = $hc->exec ( 'https://email-checker.net' )->getStdOut ();
$domd = @DOMDocument::loadHTML ( $html );
$xp = new DOMXPath ( $domd );
$csrf_token = $xp->query ( '//input[@name="_csrf"]' )->item ( 0 )->getAttribute ( "value" );
$html = $hc->setopt_array ( array (
        CURLOPT_URL => 'https://email-checker.net/check',
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => http_build_query ( array (
                '_csrf' => $csrf_token,
                'email' => EMAIL
        ) )
) )->exec ()->getStdOut ();
$domd = @DOMDocument::loadHTML ( $html );
$xp = new DOMXPath ( $domd );
$result = trim ( $xp->query ( '//*[@id="results-wrapper"]' )->item ( 0 )->textContent );
var_dump ( $result );
</code>```

currently outputs: string(30) "OK The email address is valid." - meaning that webmaster@hotmail.com is valid. (see line 3)

warning, after 5 attempts in less than an hour, you'll get the output Limit Exceeded Only 5 lookups per hour is allowed.  Try Premium Plan instead

warning, the results seem highly unreliable. if you actually need to validate an email address for something, send a verification url to the email instead.

Body:
I want to do e-mail verification using email-checker. I want to post email and id, and I would like to withdraw it from the posted page, whichever answer is BAD or SUCCESS. Posted page is https://email-checker.net/check.

Here is my code:

$curl_connection = curl_init();
curl_setopt($curl_connection, CURLOPT_URL, 'https://www.bulkemailchecker.com/free-email-checker/');
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_FRESH_CONNECT,true);
curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_HEADER, false);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl_connection, CURLOPT_POST, true);
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
$data=curl_exec($curl_connection);

Can anyone help me?

Body:
first make a GET request to the url, in the headers you will receive a cookie session id, and in the html you will receive a CSRF token called _csrf, save both, and make a new request to https://email-checker.net/check with both the cookie session and the csrf token, and the email, in the parameter (aptly) named email, using a HTTP POST request, with the application/x-www-urlencoded encoding. now your answer will be in the text content of the element in the html you receive with the id results-wrapper.

example implementation using hhb_curl:

<?php
declare(strict_types = 1);
const EMAIL = 'webmaster@hotmail.com';
require_once ('hhb_.inc.php');
$hc = new hhb_curl ( '', true );
$html = $hc->exec ( 'https://email-checker.net' )->getStdOut ();
$domd = @DOMDocument::loadHTML ( $html );
$xp = new DOMXPath ( $domd );
$csrf_token = $xp->query ( '//input[@name="_csrf"]' )->item ( 0 )->getAttribute ( "value" );
$html = $hc->setopt_array ( array (
        CURLOPT_URL => 'https://email-checker.net/check',
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => http_build_query ( array (
                '_csrf' => $csrf_token,
                'email' => EMAIL
        ) )
) )->exec ()->getStdOut ();
$domd = @DOMDocument::loadHTML ( $html );
$xp = new DOMXPath ( $domd );
$result = trim ( $xp->query ( '//*[@id="results-wrapper"]' )->item ( 0 )->textContent );
var_dump ( $result );

currently outputs: string(30) "OK The email address is valid." - meaning that webmaster@hotmail.com is valid. (see line 3)

warning, after 5 attempts in less than an hour, you'll get the output Limit Exceeded Only 5 lookups per hour is allowed.  Try Premium Plan instead

warning, the results seem highly unreliable. if you actually need to validate an email address for something, send a verification url to the email instead.


问:
Project Euler 18
Hey, been working at Project Euler, and this one is giving me some problems

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3

7 4

2 4 6

8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom of the triangle below:

...

NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)

here's the algorithm I've used to solve it

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Problem18
{
    class Program
    {
        static void Main(string[] args)
        {
            string triangle = @"75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23";
            string[] rows = triangle.Split('\n');
            int currindex = 1;
            int total = int.Parse(rows[0]);
            Console.WriteLine(rows[0]);
            for (int i = 1; i < rows.Length; i++)
            {
                string[] array1 = rows[i].Split(' ');
                if (array1.Length > 1)
                {
                    if (int.Parse(array1[currindex - 1]) > int.Parse(array1[currindex]))
                    {
                        Console.WriteLine(array1[currindex - 1]);
                        total += int.Parse(array1[currindex - 1]);
                    }
                    else
                    {
                        Console.WriteLine(array1[currindex]);
                        total += int.Parse(array1[currindex]);
                        currindex++;
                    }
                }
            }
            Console.WriteLine("Total: " + total);
            Console.ReadKey();
        }
    }
}
</code>```

now whenever i run it, it comes up with 1064, only 10 less then the solution -- 1074

i haven't found any problems with the algorithm and I did the problem by hand and also came up with 1064, anyone know if the solution is wrong, i'm interpreting the question wrong, or if there's just a flaw in the algorithm?

答: Here is a graphical description:

Title: Project Euler 18

Body:
Hey, been working at Project Euler, and this one is giving me some problems

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3

7 4

2 4 6

8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom of the triangle below:

...

NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)

here's the algorithm I've used to solve it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Problem18
{
    class Program
    {
        static void Main(string[] args)
        {
            string triangle = @"75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23";
            string[] rows = triangle.Split('\n');
            int currindex = 1;
            int total = int.Parse(rows[0]);
            Console.WriteLine(rows[0]);
            for (int i = 1; i < rows.Length; i++)
            {
                string[] array1 = rows[i].Split(' ');
                if (array1.Length > 1)
                {
                    if (int.Parse(array1[currindex - 1]) > int.Parse(array1[currindex]))
                    {
                        Console.WriteLine(array1[currindex - 1]);
                        total += int.Parse(array1[currindex - 1]);
                    }
                    else
                    {
                        Console.WriteLine(array1[currindex]);
                        total += int.Parse(array1[currindex]);
                        currindex++;
                    }
                }
            }
            Console.WriteLine("Total: " + total);
            Console.ReadKey();
        }
    }
}

now whenever i run it, it comes up with 1064, only 10 less then the solution -- 1074

i haven't found any problems with the algorithm and I did the problem by hand and also came up with 1064, anyone know if the solution is wrong, i'm interpreting the question wrong, or if there's just a flaw in the algorithm?

Body: Here is a graphical description:


问:
Retrieving selected items from DIV - Javascript
I am able to fetch data from database and append to my panel as in my code. But the problem is on page load for instance,

答:
This is simple Jquery code which can help you in your question.

$("#btn").click(function(){

var qty=$("#qty").val();
var rate=$("#rate").val();

var total=(qty*rate)

$("#tbody").append("
"+qty+"	"+rate+"	"+total+"
");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="qty" type="text" placeholder="quantity"/><br>
<input id="rate" type="text" placeholder="Rate"/><br>

<input id="btn" type="button" value="enter"/><br>

<table>
<tbody id="tbody">
<tr>
<td>quantity</td>
<td>rate</td>
<td>total</td>
</tr>
</tbody>
</table>
<script>

</script></code>```

Body:
This is simple Jquery code which can help you in your question.

$("#btn").click(function(){

var qty=$("#qty").val();
var rate=$("#rate").val();

var total=(qty*rate)

$("#tbody").append("<tr><td>"+qty+"</td><td>"+rate+"</td><td>"+total+"</td></tr>");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="qty" type="text" placeholder="quantity"/><br>
<input id="rate" type="text" placeholder="Rate"/><br>

<input id="btn" type="button" value="enter"/><br>

<table>
<tbody id="tbody">
<tr>
<td>quantity</td>
<td>rate</td>
<td>total</td>
</tr>
</tbody>
</table>
<script>

</script>


问:
Setting autolayout constraints causes 'Unable to simultaneously satisfy constraints' error
First time I set AutoLayout constraints of a view using code (I need a dynamic view to be created in different viewControllers and I prefer to create this UIView "on the fly").

My UIView should be attached to the superview top, as large as the superview and the bottom should be attached to the top of a particular view (navigationbar).

I tried the following:

```<code>let newView = UIView()
newView.backgroundColor = UIColor.red
view.addSubview(newView)

newView.translatesAutoresizingMaskIntoConstraints = false

let verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)

let widthConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: view,attribute: NSLayoutAttribute.width, multiplier: 1, constant: 0)

let bottomConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: navigationBar, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)

NSLayoutConstraint.activate([verticalConstraint, widthConstraint, bottomConstraint])
</code>```

I get the following runtime error but I can't understand what's the constraint that is not useful: I have a manually created view with identical constraints (there's one more too) and I get no errors:

```<code>[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x60800009d060 UINavigationBar:0x7f8061c0d2b0.top == UILayoutGuide:0x6080001ace80'UIViewSafeAreaLayoutGuide'.top   (active)>",
    "<NSLayoutConstraint:0x60400008fc80 UIView:0x7f8061f13b20.centerY == UIView:0x7f8061c17ce0.centerY   (active)>",
    "<NSLayoutConstraint:0x60400008faa0 UIView:0x7f8061f13b20.bottom == UINavigationBar:0x7f8061c0d2b0.top   (active)>",
    "<NSLayoutConstraint:0x60000009b120 'UIView-Encapsulated-Layout-Height' UIView:0x7f8061c17ce0.height == 667   (active)>",
    "<NSLayoutConstraint:0x60800009d0b0 'UIViewSafeAreaLayoutGuide-top' V:|-(20)-[UILayoutGuide:0x6080001ace80'UIViewSafeAreaLayoutGuide']   (active, names: '|':UIView:0x7f8061c17ce0 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x60400008fc80 UIView:0x7f8061f13b20.centerY == UIView:0x7f8061c17ce0.centerY   (active)>
</code>```

Any help is appreciated

答:
You don't need to use a constraint for the centerY property. Since you aim is to pin the view to the top, try using a topAnchor constraint and make it equal to superview.topAnchor. Hope this helps:</p>

```<code>let newView = UIView()
newView.backgroundColor = UIColor.red
view.addSubview(newView)

newView.translatesAutoresizingMaskIntoConstraints = false

let topConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.topAnchor, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.topAnchor, multiplier: 1, constant: 0)

let widthConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: view,attribute: NSLayoutAttribute.width, multiplier: 1, constant: 0)

let bottomConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: navigationBar, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)

NSLayoutConstraint.activate([verticalConstraint, widthConstraint, bottomConstraint])
</code>```

Body:
First time I set AutoLayout constraints of a view using code (I need a dynamic view to be created in different viewControllers and I prefer to create this UIView "on the fly").

My UIView should be attached to the superview top, as large as the superview and the bottom should be attached to the top of a particular view (navigationbar).

I tried the following:

let newView = UIView()
newView.backgroundColor = UIColor.red
view.addSubview(newView)

newView.translatesAutoresizingMaskIntoConstraints = false

let verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)

let widthConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: view,attribute: NSLayoutAttribute.width, multiplier: 1, constant: 0)

let bottomConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: navigationBar, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)

NSLayoutConstraint.activate([verticalConstraint, widthConstraint, bottomConstraint])

I get the following runtime error but I can't understand what's the constraint that is not useful: I have a manually created view with identical constraints (there's one more too) and I get no errors:

[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x60800009d060 UINavigationBar:0x7f8061c0d2b0.top == UILayoutGuide:0x6080001ace80'UIViewSafeAreaLayoutGuide'.top   (active)>",
    "<NSLayoutConstraint:0x60400008fc80 UIView:0x7f8061f13b20.centerY == UIView:0x7f8061c17ce0.centerY   (active)>",
    "<NSLayoutConstraint:0x60400008faa0 UIView:0x7f8061f13b20.bottom == UINavigationBar:0x7f8061c0d2b0.top   (active)>",
    "<NSLayoutConstraint:0x60000009b120 'UIView-Encapsulated-Layout-Height' UIView:0x7f8061c17ce0.height == 667   (active)>",
    "<NSLayoutConstraint:0x60800009d0b0 'UIViewSafeAreaLayoutGuide-top' V:|-(20)-[UILayoutGuide:0x6080001ace80'UIViewSafeAreaLayoutGuide']   (active, names: '|':UIView:0x7f8061c17ce0 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x60400008fc80 UIView:0x7f8061f13b20.centerY == UIView:0x7f8061c17ce0.centerY   (active)>

Any help is appreciated

Body:
You don't need to use a constraint for the centerY property. Since you aim is to pin the view to the top, try using a topAnchor constraint and make it equal to superview.topAnchor. Hope this helps:

let newView = UIView()
newView.backgroundColor = UIColor.red
view.addSubview(newView)

newView.translatesAutoresizingMaskIntoConstraints = false

let topConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.topAnchor, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.topAnchor, multiplier: 1, constant: 0)

let widthConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: view,attribute: NSLayoutAttribute.width, multiplier: 1, constant: 0)

let bottomConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: navigationBar, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)

NSLayoutConstraint.activate([verticalConstraint, widthConstraint, bottomConstraint])


问:
How to determine if a JSON response will bind to a model
We have a 3rd party service provider that based on a action a notification Webhook is sent to our webhook url using JSON. Due to the fact that i can only provide 1 webhook url all notifications need to funnel to the 1 url. I need to determine which model to deserialze to.

I understand how to deserialize JSON string into an object model.

Here is an example of what is first sent to our webhook

```<code>{
    "providerAccount": {
        "id": XXXXXX,
        "aggregationSource": "USER",
        "refreshInfo": {
            "statusCode": 801,
            "statusMessage": "ADD_IN_PROGRESS",
            "status": "IN_PROGRESS",
            "additionalStatus": "LOGIN_IN_PROGRESS"
        }
    }
}
</code>```

and then after another 10 or so seconds another JSON webhook comes in.

```<code>{
    "event": {
        "info": "REFRESH.INTERIM_PROGRESS",
        "loginName": "XXXXXX",
        "data": {
            "providerAccount": {
                "id": XXXXXX,
                "providerId": XXXXXX,
                "isManual": false,
                "createdDate": "2017-12-08",
                "aggregationSource": "USER",
                "refreshInfo": {
                    "status": "IN_PROGRESS",
                    "additionalStatus": "LOGIN_SUCCESS",
                    "statusCode": 0,
                    "statusMessage": "OK",
                    "nextRefreshScheduled": "0001-01-01T00:00:00",
                    "lastRefreshed": "0001-01-01T00:00:00",
                    "lastRefreshAttempt": "0001-01-01T00:00:00"
                },
                "loginForm": null
            }
        }
    }
}
</code>```

As you can see they would be 2 separate model objects which i need to deserialize.

I find that checking for null on the first model to the second model seems wrong and can be achieved in a different way.

There are another 3 different JSON strings that come through the same webhook. and to check for if model is null, if this model is null etc. then move to next seems wrong.

答:
If all of the Json objects have different object names, you could extract that name and get c# object type using it, and deserialize to it.

To get object name you can use Newtonsoft.Json package and parse it to JObject, or you could write regex to extract it, in case parsing is too costly for you. Example with JObject:

```<code> private string GetJsonObjectName(string json)
    {
        var jobj = JObject.Parse(json);
        return ((JProperty)jobj.First).Name;
    }
</code>```

After having the name you can either add simple switch and get type based on string, or add attribute with Json object name to classes and use reflection.

```<code> public class JsonType : Attribute
{
    private string _name;

    public JsonType(string name)
    {
        _name = name;
    }

    override
    public string ToString()
    {
        return _name;
    }
}

[JsonType("providerAccount")]
public class RootObjectProvider
{
    public ProviderAccount providerAccount { get; set; }
}
</code>```

Using reflection to get correct object:

```<code>var type = Assembly.GetExecutingAssembly().GetTypes()
            .Where(x => Attribute.IsDefined(x,typeof(JsonType)))
            .SingleOrDefault(x => x.GetCustomAttribute(typeof(JsonType)).ToString() == jsonObjectName);

var cobj = JsonConvert.DeserializeObject(json1, type);
</code>```

Reflection takes longer, but it is easier to extend later on when you add new classes

Body:
We have a 3rd party service provider that based on a action a notification Webhook is sent to our webhook url using JSON. Due to the fact that i can only provide 1 webhook url all notifications need to funnel to the 1 url. I need to determine which model to deserialze to.

I understand how to deserialize JSON string into an object model.

Here is an example of what is first sent to our webhook

{
    "providerAccount": {
        "id": XXXXXX,
        "aggregationSource": "USER",
        "refreshInfo": {
            "statusCode": 801,
            "statusMessage": "ADD_IN_PROGRESS",
            "status": "IN_PROGRESS",
            "additionalStatus": "LOGIN_IN_PROGRESS"
        }
    }
}

and then after another 10 or so seconds another JSON webhook comes in.

{
    "event": {
        "info": "REFRESH.INTERIM_PROGRESS",
        "loginName": "XXXXXX",
        "data": {
            "providerAccount": {
                "id": XXXXXX,
                "providerId": XXXXXX,
                "isManual": false,
                "createdDate": "2017-12-08",
                "aggregationSource": "USER",
                "refreshInfo": {
                    "status": "IN_PROGRESS",
                    "additionalStatus": "LOGIN_SUCCESS",
                    "statusCode": 0,
                    "statusMessage": "OK",
                    "nextRefreshScheduled": "0001-01-01T00:00:00",
                    "lastRefreshed": "0001-01-01T00:00:00",
                    "lastRefreshAttempt": "0001-01-01T00:00:00"
                },
                "loginForm": null
            }
        }
    }
}

As you can see they would be 2 separate model objects which i need to deserialize.

I find that checking for null on the first model to the second model seems wrong and can be achieved in a different way.

There are another 3 different JSON strings that come through the same webhook. and to check for if model is null, if this model is null etc. then move to next seems wrong.

Body:
If all of the Json objects have different object names, you could extract that name and get c# object type using it, and deserialize to it.

To get object name you can use Newtonsoft.Json package and parse it to JObject, or you could write regex to extract it, in case parsing is too costly for you. Example with JObject:

 private string GetJsonObjectName(string json)
    {
        var jobj = JObject.Parse(json);
        return ((JProperty)jobj.First).Name;
    }

After having the name you can either add simple switch and get type based on string, or add attribute with Json object name to classes and use reflection.

 public class JsonType : Attribute
{
    private string _name;

    public JsonType(string name)
    {
        _name = name;
    }

    override
    public string ToString()
    {
        return _name;
    }
}

[JsonType("providerAccount")]
public class RootObjectProvider
{
    public ProviderAccount providerAccount { get; set; }
}

Using reflection to get correct object:

var type = Assembly.GetExecutingAssembly().GetTypes()
            .Where(x => Attribute.IsDefined(x,typeof(JsonType)))
            .SingleOrDefault(x => x.GetCustomAttribute(typeof(JsonType)).ToString() == jsonObjectName);

var cobj = JsonConvert.DeserializeObject(json1, type);

Reflection takes longer, but it is easier to extend later on when you add new classes


问:
chi square on gender in two groups in R
I am trying to do a chi square test on gender in two groups

```<code>#My data is:
G1_F=10 #group 1, female
G1_M=14 #group2, male
G2_F=9
G2_M=15
</code>```

I know the answer is a p-value on 0.77, but how do i get to this?
If I make a matrix and calculate "chisq.test" (see below), I get the result: X-squared = 0, df = 1, p-value = 1

```<code>genderG = matrix(
c(PDF, PDM, CF, CM), nrow=2, ncol=2)
genderG

# Calculating p-sqaure and test statistics
chisq.test(genderG)
</code>```

答:
You should specify option correct = F, in order to ignore the continuity correction that the command does by default.

```<code>G1_F=10 #group 1, female
G1_M=14 #group2, male
G2_F=9
G2_M=15

genderG = data.frame(G1 = c(G1_M, G1_F),
                     G2 = c(G2_M, G2_F))

chisq.test(genderG, correct = F)

# Pearson's Chi-squared test
#
# data:  genderG
# X-squared = 0.087114, df = 1, p-value = 0.7679
</code>```

There's also another way to perform this test, using prop.test, but this time the inputs are observations in group 1 and total observations:

```<code>prop.test(genderG$G1, genderG$G1+genderG$G2, correct = F)

# 2-sample test for equality of proportions without continuity
# correction
#
# data:  genderG$G1 out of genderG$G1 + genderG$G2
# X-squared = 0.087114, df = 1, p-value = 0.7679
# alternative hypothesis: two.sided
# 95 percent confidence interval:
#   -0.3324899  0.2453756
# sample estimates:
#   prop 1    prop 2
# 0.4827586 0.5263158
</code>```

Title: chi square on gender in two groups in R

Body:
I am trying to do a chi square test on gender in two groups

#My data is:
G1_F=10 #group 1, female
G1_M=14 #group2, male
G2_F=9
G2_M=15

I know the answer is a p-value on 0.77, but how do i get to this?
If I make a matrix and calculate "chisq.test" (see below), I get the result: X-squared = 0, df = 1, p-value = 1

genderG = matrix(
c(PDF, PDM, CF, CM), nrow=2, ncol=2)
genderG

# Calculating p-sqaure and test statistics
chisq.test(genderG)

Body:
You should specify option correct = F, in order to ignore the continuity correction that the command does by default.

G1_F=10 #group 1, female
G1_M=14 #group2, male
G2_F=9
G2_M=15

genderG = data.frame(G1 = c(G1_M, G1_F),
                     G2 = c(G2_M, G2_F))

chisq.test(genderG, correct = F)

# Pearson's Chi-squared test
#
# data:  genderG
# X-squared = 0.087114, df = 1, p-value = 0.7679

There's also another way to perform this test, using prop.test, but this time the inputs are observations in group 1 and total observations:

prop.test(genderG$G1, genderG$G1+genderG$G2, correct = F)

# 2-sample test for equality of proportions without continuity
# correction
#
# data:  genderG$G1 out of genderG$G1 + genderG$G2
# X-squared = 0.087114, df = 1, p-value = 0.7679
# alternative hypothesis: two.sided
# 95 percent confidence interval:
#   -0.3324899  0.2453756
# sample estimates:
#   prop 1    prop 2
# 0.4827586 0.5263158


问:
Asp.net core 2.0 middleware - accessing config settings
In a asp.net core web api middleware, is it possible to access the configuration inside the middleware?  Can someone guide me how this is done?</p>

答:
In a middle-ware you can access settings. To achieve this, you need to get IOptions<AppSettings> in the middle-ware constructor. See following sample.

```<code>public static class HelloWorldMiddlewareExtensions
{
    public static IApplicationBuilder UseHelloWorld(
        this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<HelloWorldMiddleware>();
    }
}

public class HelloWorldMiddleware
{
    private readonly RequestDelegate _next;
    private readonly AppSettings _settings;

    public HelloWorldMiddleware(
        RequestDelegate next,
        IOptions<AppSettings> options)
    {
        _next = next;
        _settings = options.Value;
    }

    public async Task Invoke(HttpContext context)
    {
        await context.Response.WriteAsync($"PropA: {_settings.PropA}");
    }
}

public class AppSettings
{
    public string PropA { get; set; }
}
</code>```

For more information see here.

Body:
In a middle-ware you can access settings. To achieve this, you need to get IOptions<AppSettings> in the middle-ware constructor. See following sample.

public static class HelloWorldMiddlewareExtensions
{
    public static IApplicationBuilder UseHelloWorld(
        this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<HelloWorldMiddleware>();
    }
}

public class HelloWorldMiddleware
{
    private readonly RequestDelegate _next;
    private readonly AppSettings _settings;

    public HelloWorldMiddleware(
        RequestDelegate next,
        IOptions<AppSettings> options)
    {
        _next = next;
        _settings = options.Value;
    }

    public async Task Invoke(HttpContext context)
    {
        await context.Response.WriteAsync($"PropA: {_settings.PropA}");
    }
}

public class AppSettings
{
    public string PropA { get; set; }
}

For more information see here.


问:
Can traits have properties & methods with private & protected visibility? Can traits have constructor, destructor & class-constants?
I've never seen a single trait where properties and methods are private or protected.

Every time I worked with traits I observed that all the properties and methods declared into any trait are always public only.

Can traits have properties and methods with private and protected visibility too? If yes, how to access them inside a class/inside some other trait? If no, why?

Can traits have constructor and destructor defined/declared within them? If yes, how to access them inside a class? If no, why?

Can traits have constants, I mean like class constants with different visibility? If yes, how to inside a class/inside some other trait? If no, why?

Special Note : Please answer the question with working suitable examples demonstrating these concepts.

答:
Traits can have properties and methods with private and protected visibility too. You can access them like they belong to class itself. There is no difference.

Traits can have a constructor and destructor but they are not for the trait itself, they are for the class which uses the trait.

Traits cannot have constants. There is no private or protected constants in PHP before version 7.1.0.

```<code>trait Singleton{
    //private const CONST1 = 'const1'; //FatalError
    private static $instance = null;
    private $prop = 5;

    private function __construct()
    {
        echo "my private construct<br/>";
    }

    public static function getInstance()
    {
        if(self::$instance === null)
            self::$instance = new static();
        return self::$instance;
    }

    public function setProp($value)
    {
        $this->prop = $value;
    }

    public function getProp()
    {
        return $this->prop;
    }
}

class A
{
    use Singleton;

    private $classProp = 5;

    public function randProp()
    {
        $this->prop = rand(0,100);
    }

    public function writeProp()
    {
        echo $this->prop . "<br/>";
    }
}

//$a1 = new A(); //Fatal Error too private constructor
$a1 = A::getInstance();
$a1->writeProp();
echo $a1->getProp() . "<br/>";
$a1->setProp(10);
$a1->writeProp();
$a1->randProp();
$a1->writeProp();
$a2 = A::getInstance();
$a2->writeProp();
$a2->randProp();
$a2->writeProp();
$a1->writeProp();
</code>```

Body:
Traits can have properties and methods with private and protected visibility too. You can access them like they belong to class itself. There is no difference.

Traits can have a constructor and destructor but they are not for the trait itself, they are for the class which uses the trait.

Traits cannot have constants. There is no private or protected constants in PHP before version 7.1.0.

trait Singleton{
    //private const CONST1 = 'const1'; //FatalError
    private static $instance = null;
    private $prop = 5;

    private function __construct()
    {
        echo "my private construct<br/>";
    }

    public static function getInstance()
    {
        if(self::$instance === null)
            self::$instance = new static();
        return self::$instance;
    }

    public function setProp($value)
    {
        $this->prop = $value;
    }

    public function getProp()
    {
        return $this->prop;
    }
}

class A
{
    use Singleton;

    private $classProp = 5;

    public function randProp()
    {
        $this->prop = rand(0,100);
    }

    public function writeProp()
    {
        echo $this->prop . "<br/>";
    }
}

//$a1 = new A(); //Fatal Error too private constructor
$a1 = A::getInstance();
$a1->writeProp();
echo $a1->getProp() . "<br/>";
$a1->setProp(10);
$a1->writeProp();
$a1->randProp();
$a1->writeProp();
$a2 = A::getInstance();
$a2->writeProp();
$a2->randProp();
$a2->writeProp();
$a1->writeProp();


问:
dash separated params in routing angular 5
I want to separate my params in URL by dash like below:

```<code>localhost/add/5-ninja
</code>```

in here the id is 5 and the name is ninja. When i changed the config to this:
path: '/:id-:name'
It doesn't work properly.
How can I create dash separated params in URL

答:
I think it's not possible the way you like but here's my suggestion to achieve that result:

in your routes config you declare the path: for ex. /:dashed

in your component:

```<code>import { ActivatedRoute } from '@angular/router';

class MyComponent {
constructor(private _route: ActivatedRoute) {
    const [id, name] = _route.snapshot.params.dashed.split('-');
    // you've got two variables 'id' and 'name' thanks to the array destructing
  }
}
</code>```

Body:
I want to separate my params in URL by dash like below:

localhost/add/5-ninja

in here the id is 5 and the name is ninja. When i changed the config to this:
path: '/:id-:name'
It doesn't work properly.
How can I create dash separated params in URL

Body:
I think it's not possible the way you like but here's my suggestion to achieve that result:

in your routes config you declare the path: for ex. /:dashed

in your component:

import { ActivatedRoute } from '@angular/router';

class MyComponent {
constructor(private _route: ActivatedRoute) {
    const [id, name] = _route.snapshot.params.dashed.split('-');
    // you've got two variables 'id' and 'name' thanks to the array destructing
  }
}


问:
Algorithm to determine if a vertex is in any of the shortest paths
Given an undirected graph G = {E,V}, with positive edge costs. For all node combinations, is there a way do determine if a certain node v is not on any of the shortest paths that its not an endpoint?

My thought is that it could be done by performing a modified form of Dijkstra's Algorithm on each node except for v, where it would mark if a v was in the solution. But I'm not sure how to modify the algorithm to do this.

答:
Suppose v is the vertex and a and b are the starting and ending points relatively.

find shortest path length from a to b.

find shortest path length from a to v and v to b.

If sum of step 2 is equal to value of step 1, v is on a potential shortest path from a to b.

PS: The algorithm time complexity remains same as finding shortest path.

Update: Dijkstra starts from one node and propagate minimum distances from that to other nods. It do this until it reaches all nodes(while Q is not empty). If you are interested one specific node(end point) you can do this process in Dijkstra until you reach that point(i.e suppose t is target point, you do (minimum)distance propagation until u extracted from Q. On the other hand at this line u ← vertex in Q with min dist[u] such that u equals t you can return dist[u]). Look at this for more detailed explanation about Dijkstra and good graphical illustrations.


问:
Using indexPath vs. indexPath.row in tableView.deselectRowAtIndexPath
I noticed in that to disable the highlight feature of a table cell you would yse the following method:

```<code>override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
  ...
  tableView.deselectRowAtIndexPath(indexPath, animated: false)
}
</code>```

What I don't understand is what's going on in the first argument indexPath. In the instructional book I've been reading just about every other method has been using indexPath.row for selecting individual cells:

```<code>override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as CustomTableViewCell

        cell.nameLabel.text = restaurantNames[indexPath.row]
        cell.typeLabel.text = restaurantTypes[indexPath.row]
        cell.locationLabel.text = restaurantLocations[indexPath.row]
}
</code>```

Just out of curiosity I tried passing indexPath.row as an argument but got the error, 'NSNumber' is not a subtype of 'NSIndexPath'. In this particular case what is the main difference between using indexPath and indexPath.row.

答:
i see the perfect answer is from apple doc

https://developer.apple.com/documentation/uikit/uitableview/1614881-indexpath

if you print indexpath you may get [0,0] which is first item in the first section

Body:
I noticed in that to disable the highlight feature of a table cell you would yse the following method:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
  ...
  tableView.deselectRowAtIndexPath(indexPath, animated: false)
}

What I don't understand is what's going on in the first argument indexPath. In the instructional book I've been reading just about every other method has been using indexPath.row for selecting individual cells:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as CustomTableViewCell

        cell.nameLabel.text = restaurantNames[indexPath.row]
        cell.typeLabel.text = restaurantTypes[indexPath.row]
        cell.locationLabel.text = restaurantLocations[indexPath.row]
}

Just out of curiosity I tried passing indexPath.row as an argument but got the error, 'NSNumber' is not a subtype of 'NSIndexPath'. In this particular case what is the main difference between using indexPath and indexPath.row.


问:
Regex not removing A-Z and a-z
```<code>String s = "xxx(000) 001";
System.out.println(s.replaceAll("A-Za-z", ""));
</code>```

Why is this printing xxx(000) 001 instead of (000) 001 removing all occurrences from A-Z and a-z?

答:
In addition to the character class proposed by @YCF_L, I'd additionally use a quantifier:

```<code>s.replaceAll("[A-Za-z]+", "");
#                  ---^---
</code>```

Otherwise, the internal replace function needs to be called multiple times.

For this example, consider the string aa123bb with the regular expression [A-Za-z]. The regex engine scans the string from left to right, and finds a match with a (it is in the character class). This match is reported back and replaced with "" in our case. Then the next character is evaluated, which is another a: a match is reported and replaced. 1, 2 and 3 are not included in our character class, but b and b indeed are. So in total with this expression the internal engine reports four matches back.

Now consider a quantifier like [A-Za-z]+: the engine finds a in aa123bb but is greedy and is eager to find another character which in our case is another a. It now reports a match with aa which is then replaced by "". 1, 2 and 3 are not included in our character class so the engine leaves them as they are. Now, the engine finds b and (being greedy) yet another b (bb in total) and reports and replaces the second match.

While the result is the same (123 in our case) the regex engine only needs to give back two results (and to call the replacement) with a quantifier instead of four without.

Title: Regex not removing A-Z and a-z

Body:
String s = "xxx(000) 001";
System.out.println(s.replaceAll("A-Za-z", ""));

Why is this printing xxx(000) 001 instead of (000) 001 removing all occurrences from A-Z and a-z?

Body:
In addition to the character class proposed by @YCF_L, I'd additionally use a quantifier:

s.replaceAll("[A-Za-z]+", "");
#                  ---^---

Otherwise, the internal replace function needs to be called multiple times.

For this example, consider the string aa123bb with the regular expression [A-Za-z]. The regex engine scans the string from left to right, and finds a match with a (it is in the character class). This match is reported back and replaced with "" in our case. Then the next character is evaluated, which is another a: a match is reported and replaced. 1, 2 and 3 are not included in our character class, but b and b indeed are. So in total with this expression the internal engine reports four matches back.

Now consider a quantifier like [A-Za-z]+: the engine finds a in aa123bb but is greedy and is eager to find another character which in our case is another a. It now reports a match with aa which is then replaced by "". 1, 2 and 3 are not included in our character class so the engine leaves them as they are. Now, the engine finds b and (being greedy) yet another b (bb in total) and reports and replaces the second match.

While the result is the same (123 in our case) the regex engine only needs to give back two results (and to call the replacement) with a quantifier instead of four without.


答:
```<code>    $connection = mysqli_connect('localhost', 'root', '', 'dbname');
if (!$connection) {
    die("Database Connection Failed" . mysqli_error($connection));
}

$select_db = mysqli_select_db($connection, 'dbname');
if (!$select_db) {
    die("Database Selection Failed" . mysqli_error($connection));
}
 $query = "INSERT INTO `user` ('$username', '$email', '$password') VALUES ('username', 'email', 'password')";
     //echo $query;
    $result=mysqli_query($connection,$query);
    if($result){
        $smsg = "User Created Successfully.";
    }else{
        $fmsg ="User Registration Failed";
    }
</code>```

Title: Mysql Database error connection

Body:
Might sound obvious but my database isn't connecting to my phpmyadmin.

is there something I did wrong? I'm using mamp as a backend server for php use.

 <?php
    //
    require('database.php');
    $connection = mysqli_connect('localhost', 'root','','blurt');
    // If the values are posted, insert them into the database.
    if (isset($_POST['Register'])){
        $username = $_POST['username'];
    $email = $_POST['email'];
        $password = $_POST['password'];

        $query = "INSERT INTO `user` (username, email, password) VALUES ('$username', '$email', '$password')";
         //echo $query;
        $result=mysqli_query($connection,$query);
        if($result){
            $smsg = "User Created Successfully.";
        }else{
            $fmsg ="User Registration Failed";
        }
    }

    $connection = mysqli_connect('localhost', 'root', '', 'blurt');
    if (!$connection) {
        die("Database Connection Failed" . mysqli_error($connection));
    } $select_db = mysqli_select_db($connection, 'blurt');
    if (!$select_db) {
        die("Database Selection Failed" . mysqli_error($connection));
    }
    ?>


问:
Grab json response from api
Please check the controller bellow. I have to process the Json response inside this controller. My goal is to grab "success" value true or false. How can i access that value from following json response? I already tried to use JsSerialializer but no luck. Please check pictures for better understanding. Thanks in advance.

View Model:

```<code>public class GoogleRecaptcha
{
    public bool success { get; set; }
    public DateTime challenge_ts { get; set; }
    public string hostname { get; set; }
}
</code>```

```<code>public ActionResult DownloadProcess()
{
    using (BlexzWebDbEntities db = new BlexzWebDbEntities())
    {
        //Validate Google recaptcha below
        var Response = Request["g-recaptcha-response"];
        string SecretKey = "6Lghu-MJoniMPXVf";

        //var client = new WebClient();

        var client = new RestClient("https://www.google.com/recaptcha/api/siteverify");
        var request = new RestRequest(Method.POST);
        request.Method = Method.POST;
        request.Parameters.Clear();
        request.AddParameter("secret", SecretKey);
        request.AddParameter("response", Response);
        var ResultFromGoogle = client.Execute(request).Content;

        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        var r = jsSerializer.DeserializeObject(ResultFromGoogle);

        return View();
    }

}
</code>```

答:
There are multiple ways to do what you want:

1. Using JavaScriptSerializer with strongly typed model:

```<code>public class ResultFromGoogle
{
    public bool Success { get; set; }

    public DateTime Challenge_ts { get; set; }

    public string Hostname { get; set; }
}

ResultFromGoogle results = jsSerializer.Deserialize<ResultFromGoogle>(ResultFromGoogle);
var successValue = results.Success;
</code>```

2. Using JavaScriptSerializer without strongly typed model:

```<code>var props = (Dictionary<string, object>)jsSerializer.DeserializeObject(ResultFromGoogle);
var successValue = props["success"];
</code>```

3. Using JSON.Net with strongly typed model:

```<code>var results = JsonConvert.DeserializeObject<ResultFromGoogle>();
var successValue = results.Success;
</code>```

4. Using JSON.Net without strongly typed model:

```<code>var successValue = JObject.Parse(ResultFromGoogle).GetValue("success");
</code>```

Overall, I suggest using strongly-typed model, because it provides conversion to required type (e.g. bool for success property and DateTime for challenge_ts). It's also more convenient if you need to access other fields of the response.

Json.Net in its turn is much more flexible than JavaScriptSerializer. You need to install Json.Net NuGet to use options #3 and #4.

Title: Grab json response from api

Body:
Please check the controller bellow. I have to process the Json response inside this controller. My goal is to grab "success" value true or false. How can i access that value from following json response? I already tried to use JsSerialializer but no luck. Please check pictures for better understanding. Thanks in advance.

View Model:

public class GoogleRecaptcha
{
    public bool success { get; set; }
    public DateTime challenge_ts { get; set; }
    public string hostname { get; set; }
}

public ActionResult DownloadProcess()
{
    using (BlexzWebDbEntities db = new BlexzWebDbEntities())
    {
        //Validate Google recaptcha below
        var Response = Request["g-recaptcha-response"];
        string SecretKey = "6Lghu-MJoniMPXVf";

        //var client = new WebClient();

        var client = new RestClient("https://www.google.com/recaptcha/api/siteverify");
        var request = new RestRequest(Method.POST);
        request.Method = Method.POST;
        request.Parameters.Clear();
        request.AddParameter("secret", SecretKey);
        request.AddParameter("response", Response);
        var ResultFromGoogle = client.Execute(request).Content;

        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        var r = jsSerializer.DeserializeObject(ResultFromGoogle);

        return View();
    }

}

Body:
There are multiple ways to do what you want:

1. Using JavaScriptSerializer with strongly typed model:

public class ResultFromGoogle
{
    public bool Success { get; set; }

    public DateTime Challenge_ts { get; set; }

    public string Hostname { get; set; }
}

ResultFromGoogle results = jsSerializer.Deserialize<ResultFromGoogle>(ResultFromGoogle);
var successValue = results.Success;

2. Using JavaScriptSerializer without strongly typed model:

var props = (Dictionary<string, object>)jsSerializer.DeserializeObject(ResultFromGoogle);
var successValue = props["success"];

3. Using JSON.Net with strongly typed model:

var results = JsonConvert.DeserializeObject<ResultFromGoogle>();
var successValue = results.Success;

4. Using JSON.Net without strongly typed model:

var successValue = JObject.Parse(ResultFromGoogle).GetValue("success");

Overall, I suggest using strongly-typed model, because it provides conversion to required type (e.g. bool for success property and DateTime for challenge_ts). It's also more convenient if you need to access other fields of the response.

Json.Net in its turn is much more flexible than JavaScriptSerializer. You need to install Json.Net NuGet to use options #3 and #4.


问:
diff to web display?
I want to create a diff between two pieces of text (code but i may also want forum post) and highlight the difference in a webpage. What lib might i use to do that? I dont mind if highlighting is done in javascript. I am using asp.net with C#</p>

答:
You can use the DiffPlex library.

It is the same diff'ing library that is used by CodePlex.com to show source code diffs.  You can see an example of its output here.

Title: diff to web display?


问:
Android ClassNotFoundException: Didn't find class on path
Here's the exception message that I get when I launch the app.

FATAL EXCEPTION: main Process: net.johnhany.opencv3jniPID: 10721
  java.lang.RuntimeException: Unable to instantiate activity
  ComponentInfo{net.johnhany.opencv3jni/net.johnhany.opencv3jni.MainActivity}:
  java.lang.ClassNotFoundException: Didn't find class
  "net.johnhany.opencv3jni.MainActivity" on path: DexPathList[[zip file
  "/data/app/net.johnhany.opencv3jni-1/base.apk"],nativeLibraryDirectories=[/data/app/net.johnhany.opencv3jni-1lib/arm,
  /vendor/lib, /system/lib]] at
  android.app.ActivityThread.performLaunchActivityActivityThread.java:2322)
  at
  android.app.ActivityThread.handleLaunchActivityActivityThread.java:2474)
  at android.app.ActivityThread.ess$800(ActivityThread.java:144) at
  android.app.ActivityThread$H.handleMessageActivityThread.java:1359) at
  android.os.Handler.sage(Handler.java:102) at
  android.os.Looper.loopLooper.java:155) at
  android.app.ActivityThread.mainActivityThread.java:5696) at
  java.lang.reflect.Method.invokeNative Method) at
  java.lang.reflect.Method.invokeMethod.java:372) at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.runZygoteInit.java:1028)
  at com.android.internal.os.Init.main(ZygoteInit.java:823) Caused by:
  java.lang.ClassNotFoundException: Didn't find class
  "net.johnhany.opencv3jni.MainActivity" on path: DexPathList[[zip file
  "/data/app/net.johnhany.opencv3jni-1/base.apk"],nativeLibraryDirectories=[/data/app/net.johnhany.opencv3jni-1/lib/arm/vendor/lib,
  /system/lib]] at
  dalvik.system.BaseDexClassLoader.findClassBaseDexClassLoader.java:56)
  at java.lang.ClassLoader.loadClassClassLoader.java:511) at
  java.lang.ClassLoader.loadClassClassLoader.java:469) at
  android.app.Instrumentation.newActivityInstrumentation.java:1083) at
  android.app.ActivityThread.performLaunchActivityActivityThread.java:2312)
  at
  android.app.ActivityThread.handleLaunchActivityActivityThread.java:2474)
  at android.app.ActivityThread.ess$800(ActivityThread.java:144)  at
  android.app.ActivityThread$H.handleMessageActivityThread.java:1359)
  at android.os.Handler.sage(Handler.java:102)  at
  android.os.Looper.loopLooper.java:155)  at
  android.app.ActivityThread.mainActivityThread.java:5696)  at
  java.lang.reflect.Method.invokeNative Method)  at
  java.lang.reflect.Method.invokeMethod.java:372)  at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.runZygoteInit.java:1028)
  at com.android.internal.os.Init.main(ZygoteInit.java:823)  Suppressed:
  java.lang.ClassNotFoundException: net.johnhany.opencv3jni.ty at
  java.lang.Class.classForNameNative Method) at
  java.lang.BootClassLoader.Class(ClassLoader.java:781) at
  java.lang.BootClassLoader.Class(ClassLoader.java:841) at
  java.lang.ClassLoader.loadClassClassLoader.java:504) ... 13 more
  Caused by: java.lang.NoClassDefFoundError: Class not found using the
  boot class loader; no stack available 05-18 16:01:27.927 645-1928/?
  E/ActivityManager: App crashedProcess: net.johnhany.opencv3jni

答:
I had this problem once and clearly remember:

My Mistake

I created two projects with same name in different folders.

My Solution

On discovering this i deleted the older project and then :

 1.Clean Project

 2.Rebuild

 3.Run